-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathThread.tsx
More file actions
317 lines (282 loc) · 10 KB
/
Copy pathThread.tsx
File metadata and controls
317 lines (282 loc) · 10 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
/*
* Copyright 2026 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {announce} from 'react-aria/private/live-announcer/LiveAnnouncer';
import {ButtonContext} from 'react-aria-components/Button';
import {
createContext,
forwardRef,
ReactNode,
useCallback,
useContext,
useEffect,
useRef,
useState
} from 'react';
import type {CSSProperties} from 'react';
import {DEFAULT_SLOT, Provider} from 'react-aria-components/slots';
import {DOMRef, forwardRefType} from '@react-types/shared';
import {
GridList,
GridListItem,
GridListItemProps,
GridListProps
} from 'react-aria-components/GridList';
import {nodeContains} from 'react-aria/private/utils/shadowdom/DOMFunctions';
import {TextFieldContext} from 'react-aria-components/TextField';
import {useDOMRef} from './useDOMRef';
import {useLayoutEffect} from 'react-aria/private/utils/useLayoutEffect';
interface InternalThreadContextValue {
announceItem: (text: string) => void;
setGridListFocused: (isFocused: boolean) => void;
setIsNearBottom: (isNear: boolean) => void;
setScrollElement: (element: HTMLElement | null) => void;
}
const InternalThreadContext = createContext<InternalThreadContextValue>({
announceItem: text => announce(text, 'polite'),
setGridListFocused: () => {},
setIsNearBottom: () => {},
setScrollElement: () => {}
});
interface ThreadScrollButtonContextValue {
isNearBottom: boolean;
scrollToBottom: () => void;
}
const ThreadScrollButtonContext = createContext<ThreadScrollButtonContextValue>({
isNearBottom: true,
scrollToBottom: () => {}
});
// TODO: make this more RAC like (aka default class name and other RAC prop)
export interface ThreadProps {
className?: string;
style?: CSSProperties;
children?: ReactNode;
}
// TODO: tabbing is a bit broken as well since we hit the child elements of the gridlist rows in opposite order... This seems to be due to the
// tabIndex = 0 of the ToggleButtons in the ToggleButtonGroup
export const Thread = /*#__PURE__*/ (forwardRef as forwardRefType)(function Thread(
props: ThreadProps,
ref: DOMRef<HTMLDivElement>
) {
let {children, className, style} = props;
let domRef = useDOMRef(ref);
let isGridListFocusedRef = useRef(false);
let isFieldFocusedRef = useRef(false);
let hasNewMessagesRef = useRef(false);
let timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
let scrollRef = useRef<HTMLElement | null>(null);
let scrollToBottom = useCallback(() => {
scrollRef.current?.scrollTo({top: 0, behavior: 'smooth'});
}, []);
let [isNearBottom, setIsNearBottom] = useState(true);
// only announce new items if user is in the prompt field, otherwise if they
// are in the thread only announce there are new responses. If not in thread, don't announce
let announceItem = useCallback((text: string) => {
if (isGridListFocusedRef.current) {
// TODO: ideally announce number of new messages, but only count system messages? maybe threaditem needs
// to have a "type" prop
if (!hasNewMessagesRef.current) {
hasNewMessagesRef.current = true;
announce('New message', 'polite');
// TODO: arbirary amount of time to wait before announcing new message, maybe we don't clear until
// we detect they scroll down? Or maybe when we do the message count we do it after a certain number of messages?
// or maybe this is fine
timeout.current = setTimeout(() => {
hasNewMessagesRef.current = false;
timeout.current = null;
}, 5000);
}
return;
}
if (isFieldFocusedRef.current) {
announce(text, 'polite');
}
}, []);
let setGridListFocused = useCallback((isFocused: boolean) => {
isGridListFocusedRef.current = isFocused;
}, []);
let setScrollElement = useCallback((el: HTMLElement | null) => {
scrollRef.current = el;
}, []);
useEffect(() => {
return () => {
if (timeout.current !== null) {
clearTimeout(timeout.current);
}
};
}, []);
return (
<Provider
values={[
[
InternalThreadContext,
{announceItem, setGridListFocused, setIsNearBottom, setScrollElement}
],
[ThreadScrollButtonContext, {isNearBottom, scrollToBottom}],
[
TextFieldContext,
{
slots: {
[DEFAULT_SLOT]: {},
prompt: {
onFocusChange: (focused: boolean) => {
isFieldFocusedRef.current = focused;
}
}
}
}
]
]}>
<div ref={domRef} className={className} style={style}>
{children}
</div>
</Provider>
);
});
// TODO: update the items/className/children/etc type to reflect a thread specific classname once we finalize API
export interface ThreadListProps<T extends object> extends Pick<
GridListProps<T>,
'items' | 'children' | 'focusOnEntry' | 'aria-label' | 'aria-labelledby' | 'className'
> {}
export function ThreadList<T extends object>(props: ThreadListProps<T>) {
let {
items,
children,
className,
focusOnEntry,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledby
} = props;
let {setGridListFocused, setIsNearBottom, setScrollElement} = useContext(InternalThreadContext);
let isNearBottomRef = useRef(true);
let gridListRef = useRef<HTMLDivElement | null>(null);
let callbackRef = useCallback(
(el: HTMLDivElement | null) => {
gridListRef.current = el;
setScrollElement(el);
},
[setScrollElement]
);
// TODO: gridlist doesn't have onFocus/onBlur
useEffect(() => {
let el = gridListRef.current;
if (!el) {
return;
}
let onFocusIn = () => setGridListFocused(true);
let onFocusOut = (e: FocusEvent) => {
if (!nodeContains(el, e.relatedTarget as Node)) {
setGridListFocused(false);
}
};
el.addEventListener('focusin', onFocusIn);
el.addEventListener('focusout', onFocusOut);
return () => {
el.removeEventListener('focusin', onFocusIn);
el.removeEventListener('focusout', onFocusOut);
};
}, [setGridListFocused]);
let handleScroll = useCallback(() => {
let el = gridListRef.current;
if (!el) {
return;
}
// because column reversed scrollTop=0 is the bottom and the scrollTop goes negative as you move up
let nearBottom = el.scrollTop > -100;
isNearBottomRef.current = nearBottom;
setIsNearBottom(nearBottom);
}, [setIsNearBottom]);
useEffect(() => {
// scrolls to bottom on first render cuz we initialize isNearBottomRef to true,
// otherwise handles scrolling new prompts/etc into view unless you are scrolled up above
// 100px
if (isNearBottomRef.current) {
requestAnimationFrame(() => {
if (gridListRef.current) {
gridListRef.current.scrollTop = 0;
}
});
}
}, [items]);
return (
<GridList
ref={callbackRef}
disallowTypeAhead
onScroll={handleScroll}
keyboardNavigationBehavior="tab"
focusOnEntry={focusOnEntry}
items={items}
aria-label={ariaLabel}
aria-labelledby={ariaLabelledby}
// TODO: for now we enforce this, but to be configurable?
style={{display: 'flex', flexDirection: 'column-reverse'}}
className={className}>
{children}
</GridList>
);
}
export interface ThreadScrollButtonProps {
children?: ReactNode;
}
// TODO: wrapper so we can do the "if isNearBottom then hide" logic, could do this via inline styles perhaps
// and ditch the wrapper?
export function ThreadScrollButton({children}: ThreadScrollButtonProps) {
let {isNearBottom, scrollToBottom} = useContext(ThreadScrollButtonContext);
if (isNearBottom) {
return null;
}
return (
<ButtonContext.Provider
value={{slots: {[DEFAULT_SLOT]: {}, scroll: {onPress: scrollToBottom}}}}>
{children}
</ButtonContext.Provider>
);
}
// TODO: update the className type to reflect a thread specific classname once we finalize API
export interface ThreadItemProps extends Pick<
GridListItemProps,
'className' | 'children' | 'textValue'
> {
/** Whether or not the item's content is currently being streamed in. */
isStreaming?: boolean;
/** Announce textValue on mount even when isStreaming is provided. */
shouldAnnounceOnMount?: boolean;
}
export function ThreadItem(props: ThreadItemProps) {
let {className, children, textValue = ' ', isStreaming, shouldAnnounceOnMount} = props;
let {announceItem} = useContext(InternalThreadContext);
// TODO: using aria-live on the gridlist item was pretty chatty and the streaming causes the text announcement
// to constantly reset. If we used a live region and updated its contents when streaming finished that worked decently
// but still feels quite verbose. Stick with this and get feedback
useLayoutEffect(() => {
if ((isStreaming === undefined || shouldAnnounceOnMount) && textValue && textValue !== ' ') {
announceItem(textValue);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
let isStreamingNow = isStreaming ?? false;
let prevStreamingRef = useRef(isStreamingNow);
useLayoutEffect(() => {
if (isStreaming === undefined) {
return;
}
let wasStreaming = prevStreamingRef.current;
prevStreamingRef.current = isStreamingNow;
if (wasStreaming && !isStreamingNow && textValue && textValue !== ' ') {
announceItem(textValue);
}
}, [isStreaming, isStreamingNow, textValue, announceItem]);
return (
<GridListItem textValue={textValue} className={className}>
{children}
</GridListItem>
);
}