-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathideal.html
More file actions
348 lines (298 loc) · 11.9 KB
/
ideal.html
File metadata and controls
348 lines (298 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
<!doctype html>
<html lang="en-US">
<head>
<link href="/assets/index.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.chat-history__body {
display: flex;
flex-direction: column;
gap: 12px;
padding: 6px;
}
/* Can we eliminate .chat-history:focus? It doesn't follow BEM. */
.chat-history:focus .chat-message__is-active {
outline: dashed 2px black;
outline-offset: 2px;
}
.chat-message {
background-color: White;
border: solid 1px #ddd;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
padding: 8px;
}
.chat-message__header {
color: #999;
font-size: smaller;
font-weight: lighter;
margin-block-start: 0;
margin-block-end: 0.2em;
}
.chat-message__content > .focus-trap > p:first-of-type {
margin-block-start: 0;
}
.chat-message__content > .focus-trap > p:last-of-type {
margin-block-end: 0;
}
.chat-message__content,
.focus-trap {
/* These elements are meaningless in CSS world, adding "display: contents" to save some CPUs. */
display: contents;
}
.send-box {
margin: 6px;
}
</style>
</head>
<body>
<main></main>
<script type="importmap">
{
"imports": {
"classnames": "https://esm.sh/classnames",
"jest-mock": "https://esm.sh/jest-mock",
"react": "https://esm.sh/react",
"react-dom": "https://esm.sh/react-dom"
}
}
</script>
<script crossorigin="anonymous" src="https://esm.sh/tsx" type="module"></script>
<script type="text/babel">
import cx from 'classnames';
import { useRefFrom } from 'https://esm.sh/use-ref-from';
import { useStateWithRef } from 'https://esm.sh/use-state-with-ref';
import { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
const FOCUSABLE_SELECTOR_QUERY = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])'
].join(',');
function usePrevious(value) {
const previousRef = useRef();
useEffect(() => {
previousRef.current = value;
});
return previousRef.current;
}
// TODO: Use our own implementation of <FocusTrap>, we have better UX:
// - Save last focus
// - When an element become non-focusable
// However, this implementation is better at:
// - Handle "inert" attribute
// - Handle invisible element (element without `offsetParent`)
function FocusTrap({ children, onLeave }) {
const onLeaveRef = useRefFrom(onLeave);
const rootRef = useRef();
const handleKeyDown = useCallback(
event => {
const container = rootRef.current;
if (!container) {
return;
}
if (event.key === 'Tab') {
const focusables = Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR_QUERY)).filter(
element => !element.closest('[inert]') && element.offsetParent
);
if (focusables.length === 0) {
return;
}
const firstElement = focusables[0];
const lastElement = focusables.at(-1);
if (event.shiftKey && document.activeElement === firstElement) {
event.preventDefault();
event.stopPropagation();
lastElement.focus();
} else if (!event.shiftKey && document.activeElement === lastElement) {
event.preventDefault();
event.stopPropagation();
firstElement.focus();
}
} else if (event.key === 'Escape') {
event.stopPropagation();
onLeaveRef.current?.();
}
},
[onLeaveRef]
);
return (
<div className="focus-trap" onKeyDown={handleKeyDown} ref={rootRef}>
{children}
</div>
);
}
function ChatMessage({ abstract, activeMode, children, index, onLeave, onRequestFocus }) {
const bodyRef = useRef();
const contentId = useMemo(() => crypto.randomUUID(), []);
const headerId = useMemo(() => crypto.randomUUID(), []);
const indexRef = useRefFrom(index);
const onLeaveRef = useRefFrom(onLeave);
const onRequestFocusRef = useRefFrom(onRequestFocus);
const isFocused = activeMode === 'focus';
const wasFocused = usePrevious(isFocused);
const becomingFocused = !wasFocused && isFocused;
const isFocusedRef = useRefFrom(isFocused);
const handleKeyDown = useCallback(
event => {
if (isFocusedRef.current) {
event.stopPropagation();
}
if (event.key === 'Escape') {
event.stopPropagation();
onLeaveRef.current?.();
}
},
[onLeaveRef]
);
useEffect(() => {
if (becomingFocused) {
bodyRef.current?.focus();
}
}, [becomingFocused]);
const handleHeaderClick = useCallback(
event => onRequestFocusRef.current?.(indexRef.current),
[indexRef, onRequestFocusRef]
);
return (
<article // Required: children of role="feed" must be role="article".
aria-labelledby={headerId} // Required: we just want screen reader to narrate header. Without this, it will narrate the whole content.
className={cx('chat-message', { 'chat-message__is-active': activeMode === 'active' })}
id={`chat-message__index-${index}`}
>
<h4
className="chat-message__header"
id={headerId}
// Narrator UX: in scan mode, when user press ENTER, we will get onClick and we can use it to focus into the message.
// However, this item should be hidden as we want to prevent mouse clicks.
onClick={handleHeaderClick}
>
{abstract}
</h4>
<div
aria-labelledby={contentId} // Narrator quirks: without aria-labelledby, after pressing ENTER and focus on this element, Narrator will say nothing.
className="chat-message__body"
inert={!isFocused} // Required: if the element is not focused, its contents should not be tabbable.
onKeyDown={handleKeyDown}
ref={bodyRef}
role={isFocused ? 'document' : undefined} // Required: as instructed by C+AI accessibility team: after pressing ENTER, add role="document" and focus on the element, screen reader should change to scan/browse mode.
tabindex={isFocused ? -1 : undefined} // Required: as instructed by C+AI accessibility team: after pressing ENTER, add role="document" and focus on the element, screen reader should change to scan/browse mode.
>
<div className="chat-message__content" id={contentId}>
<FocusTrap onLeave={onLeave}>{children}</FocusTrap>
</div>
</div>
</article>
);
}
function ChatHistory({ onLeave }) {
const [activeMessageIndex, setActiveMessageIndex] = useState(0);
const [isFocused, setIsFocused, isFocusedRef] = useStateWithRef(false);
const onLeaveRef = useRefFrom(onLeave);
const rootRef = useRef();
const handleKeyDown = useCallback(
event => {
if (event.key === 'ArrowUp') {
event.stopPropagation();
setActiveMessageIndex(index => Math.max(0, index - 1));
} else if (event.key === 'ArrowDown') {
event.stopPropagation();
setActiveMessageIndex(index => Math.min(1, index + 1));
} else if (event.key === 'Enter') {
event.stopPropagation();
setIsFocused(true);
} else if (event.key === 'Escape') {
// We like this, when pressing ESCAPE key on chat history, send the focus to send box.
setIsFocused(false);
onLeaveRef.current?.();
}
},
[isFocusedRef, onLeaveRef, setActiveMessageIndex, setIsFocused]
);
const handleMessageLeave = useCallback(() => {
rootRef.current?.focus();
setIsFocused(false);
}, [rootRef, setIsFocused]);
const handleMessageRequestFocus = useCallback(
index => {
setActiveMessageIndex(index);
setIsFocused(true);
},
[setActiveMessageIndex, setIsFocused]
);
return (
<div
aria-activedescendant={`chat-message__index-${activeMessageIndex}`} // Matter of taste: we are using active descendant to control focus, instead of roving tab index.
className="chat-history"
onKeyDown={handleKeyDown}
ref={rootRef}
role="group" // Required: aria-activedescendant is only available for role="group".
tabindex="0" // Required: container of the active descendant must be focusable.
>
<section
className="chat-history__body"
role="feed" // Required: we are using role="feed/article" to represent the chat thread.
>
<ChatMessage
abstract="Bot said: Hello, World!" // Matter of taste on how to abstract the text: this is for screen reader user pressing H key to quickly jump between messages.
activeMode={activeMessageIndex === 0 ? (isFocused ? 'focus' : 'active') : undefined}
index={0}
onLeave={activeMessageIndex === 0 ? handleMessageLeave : undefined}
onRequestFocus={handleMessageRequestFocus}
>
<p>Hello, World!</p>
<p>
Click <a href="https://bing.com/">this link</a> for more details.
</p>
</ChatMessage>
<ChatMessage
abstract="You said: Aloha!"
activeMode={activeMessageIndex === 1 ? (isFocused ? 'focus' : 'active') : undefined}
index={1}
onLeave={activeMessageIndex === 1 ? handleMessageLeave : undefined}
onRequestFocus={handleMessageRequestFocus}
>
<p>Aloha!</p>
</ChatMessage>
</section>
</div>
);
}
const SendBox = forwardRef(function SendBox(_, ref) {
const handleSubmit = useCallback(event => {
event.preventDefault();
}, []);
return (
<form className="send-box" onSubmit={handleSubmit}>
<textarea className="send-box__text-box" placeholder="Type a message" ref={ref} />
</form>
);
});
function ChatApp() {
const sendBoxRef = useRef();
const handleChatHistoryLeave = useCallback(() => {
sendBoxRef.current?.focus();
}, [sendBoxRef]);
return (
<div
className="chat-app"
role="application" // Required: role="document" will only work when its container has role="application".
>
<ChatHistory onLeave={handleChatHistoryLeave} />
<SendBox ref={sendBoxRef} />
</div>
);
}
const mainElement = document.querySelector('main');
mainElement && createRoot(mainElement).render(<ChatApp />);
setTimeout(() => {
document.querySelector('textarea')?.focus();
}, 100);
</script>
</body>
</html>