@assistant-ui/react 0.15.25 → 0.15.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/hooks/useToolCallElapsed.d.ts.map +1 -1
- package/dist/hooks/useToolCallElapsed.js +3 -2
- package/dist/hooks/useToolCallElapsed.js.map +1 -1
- package/dist/index.d.ts +31 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/mcp-apps/McpAppRenderer.d.ts.map +1 -1
- package/dist/mcp-apps/McpAppRenderer.js +3 -2
- package/dist/mcp-apps/McpAppRenderer.js.map +1 -1
- package/dist/mcp-apps/app-frame.d.ts.map +1 -1
- package/dist/mcp-apps/app-frame.js +58 -48
- package/dist/mcp-apps/app-frame.js.map +1 -1
- package/dist/mcp-apps/bridge.d.ts.map +1 -1
- package/dist/mcp-apps/bridge.js +28 -3
- package/dist/mcp-apps/bridge.js.map +1 -1
- package/dist/mcp-apps/csp.d.ts +4 -0
- package/dist/mcp-apps/csp.d.ts.map +1 -0
- package/dist/mcp-apps/csp.js +93 -0
- package/dist/mcp-apps/csp.js.map +1 -0
- package/dist/mcp-apps/index.d.ts +1 -1
- package/dist/mcp-apps/index.d.ts.map +1 -1
- package/dist/mcp-apps/types.d.ts +19 -1
- package/dist/mcp-apps/types.d.ts.map +1 -1
- package/dist/mcp-apps/types.js.map +1 -1
- package/dist/primitives/assistantModal/AssistantModalRoot.d.ts +1 -0
- package/dist/primitives/assistantModal/AssistantModalRoot.d.ts.map +1 -1
- package/dist/primitives/assistantModal/AssistantModalRoot.js.map +1 -1
- package/dist/primitives/attachment.d.ts +3 -1
- package/dist/primitives/attachment.d.ts.map +1 -1
- package/dist/primitives/attachment.js.map +1 -1
- package/dist/primitives/composer/ComposerAttachmentDropzone.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerAttachmentDropzone.js +14 -12
- package/dist/primitives/composer/ComposerAttachmentDropzone.js.map +1 -1
- package/dist/primitives/composer/ComposerCancel.d.ts +5 -1
- package/dist/primitives/composer/ComposerCancel.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerCancel.js +14 -1
- package/dist/primitives/composer/ComposerCancel.js.map +1 -1
- package/dist/primitives/composer/ComposerInput.d.ts +14 -0
- package/dist/primitives/composer/ComposerInput.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerInput.js +4 -3
- package/dist/primitives/composer/ComposerInput.js.map +1 -1
- package/dist/primitives/composer/ComposerRoot.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerRoot.js +24 -19
- package/dist/primitives/composer/ComposerRoot.js.map +1 -1
- package/dist/primitives/composer/composerInputSelector.d.ts +3 -0
- package/dist/primitives/composer/composerInputSelector.d.ts.map +1 -0
- package/dist/primitives/composer/composerInputSelector.js +7 -0
- package/dist/primitives/composer/composerInputSelector.js.map +1 -0
- package/dist/primitives/composer/useComposerCancelWithFocus.d.ts +2 -0
- package/dist/primitives/composer/useComposerCancelWithFocus.d.ts.map +1 -0
- package/dist/primitives/composer/useComposerCancelWithFocus.js +42 -0
- package/dist/primitives/composer/useComposerCancelWithFocus.js.map +1 -0
- package/dist/primitives/composer.d.ts +35 -14
- package/dist/primitives/composer.d.ts.map +1 -1
- package/dist/primitives/composer.js.map +1 -1
- package/dist/primitives/message/MessagePartsGrouped.d.ts +8 -1
- package/dist/primitives/message/MessagePartsGrouped.d.ts.map +1 -1
- package/dist/primitives/message/MessagePartsGrouped.js +58 -278
- package/dist/primitives/message/MessagePartsGrouped.js.map +1 -1
- package/dist/primitives/selectionToolbar/SelectionToolbarRoot.d.ts.map +1 -1
- package/dist/primitives/selectionToolbar/SelectionToolbarRoot.js +5 -2
- package/dist/primitives/selectionToolbar/SelectionToolbarRoot.js.map +1 -1
- package/dist/primitives/thread/ThreadViewport.d.ts.map +1 -1
- package/dist/primitives/thread/ThreadViewport.js +4 -3
- package/dist/primitives/thread/ThreadViewport.js.map +1 -1
- package/dist/primitives/thread/topAnchor/useTopAnchorReserve.js +2 -2
- package/dist/primitives/thread/topAnchor/useTopAnchorReserve.js.map +1 -1
- package/dist/primitives/thread/useThreadViewportAutoScroll.d.ts.map +1 -1
- package/dist/primitives/thread/useThreadViewportAutoScroll.js +90 -21
- package/dist/primitives/thread/useThreadViewportAutoScroll.js.map +1 -1
- package/dist/sandbox-host/SandboxHost.d.ts.map +1 -1
- package/dist/sandbox-host/SandboxHost.js +3 -2
- package/dist/sandbox-host/SandboxHost.js.map +1 -1
- package/dist/unstable/useComposerInput.d.ts +9 -4
- package/dist/unstable/useComposerInput.d.ts.map +1 -1
- package/dist/unstable/useComposerInput.js +6 -4
- package/dist/unstable/useComposerInput.js.map +1 -1
- package/dist/unstable/useComposerInputHistory.d.ts +3 -2
- package/dist/unstable/useComposerInputHistory.d.ts.map +1 -1
- package/dist/unstable/useComposerInputHistory.js +2 -2
- package/dist/unstable/useComposerInputHistory.js.map +1 -1
- package/dist/unstable/useLiveCompletionAdapter.d.ts +3 -2
- package/dist/unstable/useLiveCompletionAdapter.d.ts.map +1 -1
- package/dist/unstable/useLiveCompletionAdapter.js +8 -7
- package/dist/unstable/useLiveCompletionAdapter.js.map +1 -1
- package/dist/unstable/useMentionAdapter.d.ts +12 -3
- package/dist/unstable/useMentionAdapter.d.ts.map +1 -1
- package/dist/unstable/useMentionAdapter.js +2 -2
- package/dist/unstable/useMentionAdapter.js.map +1 -1
- package/dist/unstable/useMessageStallDetection.d.ts +4 -2
- package/dist/unstable/useMessageStallDetection.d.ts.map +1 -1
- package/dist/unstable/useMessageStallDetection.js +2 -2
- package/dist/unstable/useMessageStallDetection.js.map +1 -1
- package/dist/unstable/useSlashCommandAdapter.d.ts +5 -2
- package/dist/unstable/useSlashCommandAdapter.d.ts.map +1 -1
- package/dist/unstable/useSlashCommandAdapter.js +5 -4
- package/dist/unstable/useSlashCommandAdapter.js.map +1 -1
- package/dist/unstable/webmcp/useWebMcpProvider.d.ts +4 -0
- package/dist/unstable/webmcp/useWebMcpProvider.d.ts.map +1 -1
- package/dist/unstable/webmcp/useWebMcpProvider.js +2 -0
- package/dist/unstable/webmcp/useWebMcpProvider.js.map +1 -1
- package/dist/utils/getSelectionMessageId.d.ts.map +1 -1
- package/dist/utils/getSelectionMessageId.js +31 -8
- package/dist/utils/getSelectionMessageId.js.map +1 -1
- package/dist/utils/hooks/useOnResizeContent.d.ts.map +1 -1
- package/dist/utils/hooks/useOnResizeContent.js +2 -22
- package/dist/utils/hooks/useOnResizeContent.js.map +1 -1
- package/dist/utils/useIsomorphicLayoutEffect.d.ts +3 -0
- package/dist/utils/useIsomorphicLayoutEffect.d.ts.map +1 -0
- package/dist/utils/useIsomorphicLayoutEffect.js +6 -0
- package/dist/utils/useIsomorphicLayoutEffect.js.map +1 -0
- package/package.json +10 -10
- package/src/hooks/useToolCallElapsed.test.tsx +4 -2
- package/src/hooks/useToolCallElapsed.ts +3 -2
- package/src/index.ts +20 -2
- package/src/mcp-apps/McpAppRenderer.test.tsx +7 -2
- package/src/mcp-apps/McpAppRenderer.tsx +3 -9
- package/src/mcp-apps/app-frame.test.tsx +102 -6
- package/src/mcp-apps/app-frame.tsx +7 -10
- package/src/mcp-apps/bridge.test.ts +154 -0
- package/src/mcp-apps/bridge.ts +51 -9
- package/src/mcp-apps/csp.test.ts +112 -0
- package/src/mcp-apps/csp.ts +124 -0
- package/src/mcp-apps/index.ts +1 -0
- package/src/mcp-apps/types.ts +16 -1
- package/src/model-context/frame/AssistantFrame.test.ts +45 -0
- package/src/model-context/frame/SPEC_AssistantFrame.md +1 -0
- package/src/primitives/assistantModal/AssistantModalRoot.tsx +1 -0
- package/src/primitives/attachment.ts +4 -1
- package/src/primitives/composer/ComposerAttachmentDropzone.test.tsx +32 -1
- package/src/primitives/composer/ComposerAttachmentDropzone.tsx +14 -12
- package/src/primitives/composer/ComposerCancel.focus.test.tsx +307 -0
- package/src/primitives/composer/ComposerCancel.ts +8 -1
- package/src/primitives/composer/ComposerDisabledThread.test.tsx +121 -0
- package/src/primitives/composer/ComposerInput.tsx +19 -1
- package/src/primitives/composer/ComposerRoot.tsx +6 -5
- package/src/primitives/composer/composerInputSelector.ts +4 -0
- package/src/primitives/composer/useComposerCancelWithFocus.ts +57 -0
- package/src/primitives/composer.ts +56 -21
- package/src/primitives/message/MessagePartsGrouped.test.tsx +106 -2
- package/src/primitives/message/MessagePartsGrouped.tsx +36 -134
- package/src/primitives/selectionToolbar/SelectionToolbarRoot.test.tsx +20 -12
- package/src/primitives/selectionToolbar/SelectionToolbarRoot.tsx +6 -2
- package/src/primitives/thread/ThreadViewport.tsx +3 -3
- package/src/primitives/thread/topAnchor/useTopAnchorReserve.ts +2 -2
- package/src/primitives/thread/useThreadViewportAutoScroll.test.tsx +666 -63
- package/src/primitives/thread/useThreadViewportAutoScroll.ts +201 -73
- package/src/sandbox-host/SandboxHost.tsx +3 -8
- package/src/unstable/useComposerInput.ts +9 -4
- package/src/unstable/useComposerInputHistory.ts +3 -2
- package/src/unstable/useLiveCompletionAdapter.ts +9 -14
- package/src/unstable/useMentionAdapter.ts +12 -3
- package/src/unstable/useMessageStallDetection.ts +4 -2
- package/src/unstable/useSlashCommandAdapter.ts +8 -4
- package/src/unstable/webmcp/useWebMcpProvider.ts +4 -0
- package/src/utils/getSelectionMessageId.test.ts +231 -0
- package/src/utils/getSelectionMessageId.ts +45 -7
- package/src/utils/hooks/useOnResizeContent.ts +2 -29
- package/src/utils/useIsomorphicLayoutEffect.test.tsx +21 -0
- package/src/utils/useIsomorphicLayoutEffect.ts +9 -0
|
@@ -1,15 +1,25 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useThreadViewportStore } from "../../context/react/ThreadViewportContext.js";
|
|
3
3
|
import { writableStore } from "../../context/ReadonlyStore.js";
|
|
4
|
+
import { useIsomorphicLayoutEffect } from "../../utils/useIsomorphicLayoutEffect.js";
|
|
4
5
|
import { useOnScrollToBottom } from "../../utils/hooks/useOnScrollToBottom.js";
|
|
5
6
|
import { useManagedRef } from "../../utils/hooks/useManagedRef.js";
|
|
6
7
|
import { useOnResizeContent } from "../../utils/hooks/useOnResizeContent.js";
|
|
7
|
-
import { useCallback,
|
|
8
|
+
import { useCallback, useRef } from "@assistant-ui/tap/react-shim";
|
|
8
9
|
import { useAui, useAuiEvent, useAuiState } from "@assistant-ui/store";
|
|
9
10
|
import { useComposedRefs } from "radix-ui/internal";
|
|
10
11
|
import { isUserScrollUp, isViewportAtBottom, viewportOverflows } from "@assistant-ui/store/client";
|
|
11
12
|
//#region src/primitives/thread/useThreadViewportAutoScroll.ts
|
|
12
|
-
const
|
|
13
|
+
const SCROLL_KEYS = /* @__PURE__ */ new Set([
|
|
14
|
+
" ",
|
|
15
|
+
"ArrowUp",
|
|
16
|
+
"ArrowDown",
|
|
17
|
+
"PageUp",
|
|
18
|
+
"PageDown",
|
|
19
|
+
"Home",
|
|
20
|
+
"End"
|
|
21
|
+
]);
|
|
22
|
+
const INTENT_CANCEL_KEYS = /* @__PURE__ */ new Set(["Enter", ...SCROLL_KEYS]);
|
|
13
23
|
const TEXT_ENTRY_SELECTOR = [
|
|
14
24
|
"textarea",
|
|
15
25
|
"select",
|
|
@@ -17,6 +27,13 @@ const TEXT_ENTRY_SELECTOR = [
|
|
|
17
27
|
"input:not([type='checkbox']):not([type='radio']):not([type='button']):not([type='submit']):not([type='reset']):not([type='image']):not([type='range']):not([type='file']):not([type='color'])"
|
|
18
28
|
].join(", ");
|
|
19
29
|
const MESSAGE_SELECTOR = "[data-message-id]";
|
|
30
|
+
const DISCLOSURE_SELECTOR = "[aria-expanded], summary";
|
|
31
|
+
const isOpeningDisclosure = (target) => {
|
|
32
|
+
const control = target.closest(DISCLOSURE_SELECTOR);
|
|
33
|
+
if (!control) return false;
|
|
34
|
+
if (control.tagName === "SUMMARY") return control.parentElement?.hasAttribute("open") === false;
|
|
35
|
+
return control.getAttribute("aria-expanded") === "false" && (control.getAttribute("aria-haspopup") ?? "false") === "false" && control.getAttribute("role") !== "combobox";
|
|
36
|
+
};
|
|
20
37
|
const offsetInViewport = (element, viewport) => element.getBoundingClientRect().top - viewport.getBoundingClientRect().top;
|
|
21
38
|
const measureFirstMessage = (viewport) => {
|
|
22
39
|
const element = viewport.querySelector(MESSAGE_SELECTOR);
|
|
@@ -88,8 +105,10 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
88
105
|
const heldScrollTopRef = useRef(0);
|
|
89
106
|
const scrollingToBottomBehaviorRef = useRef(null);
|
|
90
107
|
const followBottomRef = useRef(autoScroll);
|
|
108
|
+
const followPausedRef = useRef(false);
|
|
109
|
+
const scrolledSincePauseRef = useRef(false);
|
|
91
110
|
const previousAutoScrollRef = useRef(autoScroll);
|
|
92
|
-
|
|
111
|
+
useIsomorphicLayoutEffect(() => {
|
|
93
112
|
const previousAutoScroll = previousAutoScrollRef.current;
|
|
94
113
|
previousAutoScrollRef.current = autoScroll;
|
|
95
114
|
if (previousAutoScroll || !autoScroll) return;
|
|
@@ -100,12 +119,15 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
100
119
|
const div_0 = divRef.current;
|
|
101
120
|
if (!div_0) return;
|
|
102
121
|
followBottomRef.current = true;
|
|
122
|
+
followPausedRef.current = false;
|
|
103
123
|
scrollingToBottomBehaviorRef.current = behavior;
|
|
104
124
|
prependAnchorRef.current = null;
|
|
105
125
|
div_0.scrollTo({
|
|
106
126
|
top: div_0.scrollHeight,
|
|
107
127
|
behavior
|
|
108
128
|
});
|
|
129
|
+
lastScrollTop.current = div_0.scrollTop;
|
|
130
|
+
lastScrollHeight.current = div_0.scrollHeight;
|
|
109
131
|
}, []);
|
|
110
132
|
const cancelScheduledFrame = useCallback(() => {
|
|
111
133
|
if (scheduledFrameRef.current === null) return;
|
|
@@ -120,24 +142,27 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
120
142
|
scrollToBottom(behavior_0);
|
|
121
143
|
});
|
|
122
144
|
}, [cancelScheduledFrame, scrollToBottom]);
|
|
123
|
-
|
|
145
|
+
useIsomorphicLayoutEffect(() => () => cancelScheduledFrame(), [cancelScheduledFrame]);
|
|
124
146
|
const hasActiveTopAnchor = useCallback(() => {
|
|
125
147
|
const state = threadViewportStore.getState();
|
|
126
148
|
return state.turnAnchor === "top" && state.element.viewport === divRef.current && state.element.anchor !== null;
|
|
127
149
|
}, [threadViewportStore]);
|
|
128
|
-
const
|
|
150
|
+
const onScroll = () => {
|
|
129
151
|
const div_1 = divRef.current;
|
|
130
152
|
if (!div_1) return;
|
|
131
153
|
if (prependAnchorRef.current && Math.abs(div_1.scrollTop - heldScrollTopRef.current) >= 1) prependAnchorRef.current = null;
|
|
132
154
|
const isAtBottom = threadViewportStore.getState().isAtBottom;
|
|
133
155
|
const newIsAtBottom = isViewportAtBottom(div_1);
|
|
134
|
-
if (!newIsAtBottom && lastScrollTop.current < div_1.scrollTop) {} else {
|
|
156
|
+
if (scrollingToBottomBehaviorRef.current !== null && !newIsAtBottom && lastScrollTop.current < div_1.scrollTop) {} else {
|
|
135
157
|
const userScrolledUp = isUserScrollUp({
|
|
136
158
|
scrollTop: lastScrollTop.current,
|
|
137
159
|
scrollHeight: lastScrollHeight.current
|
|
138
160
|
}, div_1);
|
|
139
161
|
if (newIsAtBottom) {
|
|
140
|
-
if (viewportOverflows(div_1))
|
|
162
|
+
if (viewportOverflows(div_1)) {
|
|
163
|
+
scrollingToBottomBehaviorRef.current = null;
|
|
164
|
+
if (scrolledSincePauseRef.current) followPausedRef.current = false;
|
|
165
|
+
}
|
|
141
166
|
if (autoScroll) followBottomRef.current = true;
|
|
142
167
|
} else if (userScrolledUp) {
|
|
143
168
|
cancelScheduledFrame();
|
|
@@ -150,30 +175,58 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
150
175
|
lastScrollHeight.current = div_1.scrollHeight;
|
|
151
176
|
firstMessageRef.current = measureFirstMessage(div_1);
|
|
152
177
|
};
|
|
153
|
-
const
|
|
178
|
+
const onScrollRef = useRef(onScroll);
|
|
179
|
+
useIsomorphicLayoutEffect(() => {
|
|
180
|
+
onScrollRef.current = onScroll;
|
|
181
|
+
});
|
|
182
|
+
const handleScroll = useCallback(() => onScrollRef.current(), []);
|
|
183
|
+
const onResize = () => {
|
|
154
184
|
const div_2 = divRef.current;
|
|
155
185
|
if (!div_2) return;
|
|
156
186
|
const { scrollHeight, clientHeight } = div_2;
|
|
157
187
|
if (scrollHeight === lastObservedScrollHeight.current && clientHeight === lastObservedClientHeight.current) return;
|
|
158
188
|
lastObservedScrollHeight.current = scrollHeight;
|
|
159
189
|
lastObservedClientHeight.current = clientHeight;
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
190
|
+
if (scheduledFrameRef.current === null) {
|
|
191
|
+
const scrollBehavior = scrollingToBottomBehaviorRef.current;
|
|
192
|
+
if (scrollBehavior && hasActiveTopAnchor()) scrollingToBottomBehaviorRef.current = null;
|
|
193
|
+
else if (scrollBehavior) scrollToBottom(scrollBehavior);
|
|
194
|
+
else if (autoScroll && !(isRunning && hasActiveTopAnchor()) && followBottomRef.current && !followPausedRef.current) scrollToBottom("instant");
|
|
195
|
+
else if (prependAnchorRef.current && !keepMessageAt(div_2, prependAnchorRef.current, heldScrollTopRef)) prependAnchorRef.current = null;
|
|
196
|
+
}
|
|
165
197
|
handleScroll();
|
|
198
|
+
};
|
|
199
|
+
const onResizeRef = useRef(onResize);
|
|
200
|
+
useIsomorphicLayoutEffect(() => {
|
|
201
|
+
onResizeRef.current = onResize;
|
|
166
202
|
});
|
|
167
|
-
const
|
|
203
|
+
const resizeRef = useOnResizeContent(() => onResizeRef.current());
|
|
204
|
+
const scrollRef = useManagedRef(useCallback((el) => {
|
|
168
205
|
const cancelPendingScrollToBottom = () => {
|
|
206
|
+
if (scrollingToBottomBehaviorRef.current === null && scheduledFrameRef.current === null) return;
|
|
169
207
|
cancelScheduledFrame();
|
|
170
208
|
scrollingToBottomBehaviorRef.current = null;
|
|
209
|
+
handleScroll();
|
|
171
210
|
};
|
|
172
211
|
const cancelOnKeyDown = (event) => {
|
|
173
|
-
if (!
|
|
212
|
+
if (!INTENT_CANCEL_KEYS.has(event.key)) return;
|
|
174
213
|
if (event.target?.closest?.(TEXT_ENTRY_SELECTOR)) return;
|
|
175
214
|
cancelPendingScrollToBottom();
|
|
176
215
|
};
|
|
216
|
+
const pauseFollowOnExpand = (event_0) => {
|
|
217
|
+
const target_0 = event_0.target;
|
|
218
|
+
if (!target_0?.closest?.(MESSAGE_SELECTOR) || target_0.closest(TEXT_ENTRY_SELECTOR) || !isOpeningDisclosure(target_0)) return;
|
|
219
|
+
followPausedRef.current = true;
|
|
220
|
+
scrolledSincePauseRef.current = false;
|
|
221
|
+
cancelPendingScrollToBottom();
|
|
222
|
+
};
|
|
223
|
+
const noteScrollGesture = (event_1) => {
|
|
224
|
+
if (event_1 instanceof KeyboardEvent) {
|
|
225
|
+
if (!SCROLL_KEYS.has(event_1.key)) return;
|
|
226
|
+
if (event_1.target?.closest?.(TEXT_ENTRY_SELECTOR)) return;
|
|
227
|
+
} else if (event_1.type === "pointerdown" && event_1.target !== el) return;
|
|
228
|
+
scrolledSincePauseRef.current = true;
|
|
229
|
+
};
|
|
177
230
|
const releasePrependAnchor = () => {
|
|
178
231
|
prependAnchorRef.current = null;
|
|
179
232
|
};
|
|
@@ -183,22 +236,36 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
183
236
|
"touchstart",
|
|
184
237
|
"keydown"
|
|
185
238
|
];
|
|
239
|
+
const resumeGestures = [
|
|
240
|
+
"pointerdown",
|
|
241
|
+
"wheel",
|
|
242
|
+
"touchmove",
|
|
243
|
+
"keydown"
|
|
244
|
+
];
|
|
186
245
|
el.addEventListener("scroll", handleScroll);
|
|
187
246
|
el.addEventListener("pointerdown", cancelPendingScrollToBottom);
|
|
247
|
+
el.addEventListener("wheel", cancelPendingScrollToBottom, { passive: true });
|
|
248
|
+
el.addEventListener("touchstart", cancelPendingScrollToBottom, { passive: true });
|
|
188
249
|
el.addEventListener("keydown", cancelOnKeyDown);
|
|
189
|
-
|
|
250
|
+
el.addEventListener("click", pauseFollowOnExpand, { capture: true });
|
|
251
|
+
for (const gesture of resumeGestures) el.addEventListener(gesture, noteScrollGesture, { passive: true });
|
|
252
|
+
for (const gesture_0 of gestures) el.addEventListener(gesture_0, releasePrependAnchor, { passive: true });
|
|
190
253
|
return () => {
|
|
191
254
|
el.removeEventListener("scroll", handleScroll);
|
|
192
255
|
el.removeEventListener("pointerdown", cancelPendingScrollToBottom);
|
|
256
|
+
el.removeEventListener("wheel", cancelPendingScrollToBottom);
|
|
257
|
+
el.removeEventListener("touchstart", cancelPendingScrollToBottom);
|
|
193
258
|
el.removeEventListener("keydown", cancelOnKeyDown);
|
|
194
|
-
|
|
259
|
+
el.removeEventListener("click", pauseFollowOnExpand, { capture: true });
|
|
260
|
+
for (const gesture_1 of resumeGestures) el.removeEventListener(gesture_1, noteScrollGesture);
|
|
261
|
+
for (const gesture_2 of gestures) el.removeEventListener(gesture_2, releasePrependAnchor);
|
|
195
262
|
};
|
|
196
|
-
});
|
|
263
|
+
}, [cancelScheduledFrame, handleScroll]));
|
|
197
264
|
const previousRef = useRef({
|
|
198
265
|
threadId,
|
|
199
266
|
firstMessageId
|
|
200
267
|
});
|
|
201
|
-
|
|
268
|
+
useIsomorphicLayoutEffect(() => {
|
|
202
269
|
const previous = previousRef.current;
|
|
203
270
|
previousRef.current = {
|
|
204
271
|
threadId,
|
|
@@ -210,7 +277,7 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
210
277
|
}
|
|
211
278
|
const div_3 = divRef.current;
|
|
212
279
|
const previousFirstMessageId = previous.firstMessageId;
|
|
213
|
-
if (!div_3 || previousFirstMessageId === void 0 || previousFirstMessageId === firstMessageId || autoScroll && followBottomRef.current || scrollingToBottomBehaviorRef.current !== null) return;
|
|
280
|
+
if (!div_3 || previousFirstMessageId === void 0 || previousFirstMessageId === firstMessageId || autoScroll && followBottomRef.current && !followPausedRef.current || scrollingToBottomBehaviorRef.current !== null) return;
|
|
214
281
|
if (!aui.thread.getState().messages.some((message, index) => index > 0 && message.id === previousFirstMessageId)) return;
|
|
215
282
|
const anchor = firstMessageRef.current;
|
|
216
283
|
if (anchor?.id === previousFirstMessageId && keepMessageAt(div_3, anchor, heldScrollTopRef)) prependAnchorRef.current = measureReaderMessage(div_3) ?? anchor;
|
|
@@ -229,7 +296,7 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
229
296
|
firstMessageId,
|
|
230
297
|
threadId
|
|
231
298
|
]);
|
|
232
|
-
|
|
299
|
+
useIsomorphicLayoutEffect(() => {
|
|
233
300
|
if (!scrollToBottomOnInitialize) return;
|
|
234
301
|
if (!hasMessages) {
|
|
235
302
|
initializeScrollRequestedRef.current = false;
|
|
@@ -249,11 +316,13 @@ const useThreadViewportAutoScroll = ({ autoScroll, scrollToBottomOnRunStart = tr
|
|
|
249
316
|
});
|
|
250
317
|
useAuiEvent("thread.runStart", () => {
|
|
251
318
|
prependAnchorRef.current = null;
|
|
319
|
+
followPausedRef.current = false;
|
|
252
320
|
if (!scrollToBottomOnRunStart) return;
|
|
253
321
|
if (threadViewportStore.getState().turnAnchor === "top") return;
|
|
254
322
|
scheduleScrollToBottom("auto");
|
|
255
323
|
});
|
|
256
324
|
useAuiEvent("threads.selectionChanged", () => {
|
|
325
|
+
followPausedRef.current = false;
|
|
257
326
|
if (!scrollToBottomOnThreadSwitch) return;
|
|
258
327
|
scheduleScrollToBottom("instant");
|
|
259
328
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useThreadViewportAutoScroll.js","names":["useComposedRefs","useCallback","useLayoutEffect","useRef","RefCallback","useAui","useAuiEvent","useAuiState","isUserScrollUp","isViewportAtBottom","viewportOverflows","useOnResizeContent","useOnScrollToBottom","useManagedRef","writableStore","useThreadViewportStore","ACTIVATION_KEYS","Set","TEXT_ENTRY_SELECTOR","join","MESSAGE_SELECTOR","MessageOffset","id","offset","offsetInViewport","element","Element","viewport","getBoundingClientRect","top","measureFirstMessage","HTMLElement","querySelector","dataset","measureReaderMessage","bottom","spanning","querySelectorAll","rect","findMessage","keepMessageAt","anchor","heldScrollTop","current","delta","scrollTop","Math","abs","scrollTo","behavior","useThreadViewportAutoScroll","Options","autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","TElement","aui","divRef","hasMessages","s","thread","messages","length","firstMessageId","threadId","threadListItem","isRunning","initializeScrollRequestedRef","scheduledFrameRef","threadViewportStore","undefined","getState","turnAnchor","lastScrollTop","lastScrollHeight","lastObservedScrollHeight","lastObservedClientHeight","firstMessageRef","prependAnchorRef","heldScrollTopRef","scrollingToBottomBehaviorRef","ScrollBehavior","followBottomRef","previousAutoScrollRef","previousAutoScroll","div","scrollToBottom","scrollHeight","cancelScheduledFrame","cancelAnimationFrame","scheduleScrollToBottom","requestAnimationFrame","hasActiveTopAnchor","state","handleScroll","isAtBottom","newIsAtBottom","isInFlightDownwardScroll","userScrolledUp","shouldUpdate","setState","resizeRef","clientHeight","scrollBehavior","scrollRef","el","cancelPendingScrollToBottom","cancelOnKeyDown","event","KeyboardEvent","has","key","target","closest","releasePrependAnchor","gestures","const","addEventListener","gesture","passive","removeEventListener","previousRef","previous","previousFirstMessageId","prepended","some","message","index","autoScrollRef"],"sources":["../../../src/primitives/thread/useThreadViewportAutoScroll.ts"],"sourcesContent":["\"use client\";\n\nimport { useComposedRefs } from \"radix-ui/internal\";\nimport { useCallback, useLayoutEffect, useRef, type RefCallback } from \"react\";\nimport { useAui, useAuiEvent, useAuiState } from \"@assistant-ui/store\";\nimport {\n isUserScrollUp,\n isViewportAtBottom,\n viewportOverflows,\n} from \"@assistant-ui/store/client\";\nimport { useOnResizeContent } from \"../../utils/hooks/useOnResizeContent\";\nimport { useOnScrollToBottom } from \"../../utils/hooks/useOnScrollToBottom\";\nimport { useManagedRef } from \"../../utils/hooks/useManagedRef\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\nimport { useThreadViewportStore } from \"../../context/react/ThreadViewportContext\";\n\n// Enter and Space activate a focused control, which is how a collapsible tool\n// call expands without a pointer event ever firing. No other key changes thread\n// content: the keys that scroll the viewport reach handleScroll, which already\n// clears the intent when the user scrolls up.\nconst ACTIVATION_KEYS = new Set([\"Enter\", \" \"]);\n\n// A control that consumes the activation key itself instead of acting on thread\n// content. `contenteditable=\"false\"` marks a non-editable island inside an\n// editable tree, so it is excluded the way ComposerRoot already excludes it;\n// the input types left out are the ones a key activates rather than fills.\nconst TEXT_ENTRY_SELECTOR = [\n \"textarea\",\n \"select\",\n \"[contenteditable]:not([contenteditable='false'])\",\n \"input:not([type='checkbox']):not([type='radio']):not([type='button'])\" +\n \":not([type='submit']):not([type='reset']):not([type='image'])\" +\n \":not([type='range']):not([type='file']):not([type='color'])\",\n].join(\", \");\n\nconst MESSAGE_SELECTOR = \"[data-message-id]\";\n\ntype MessageOffset = { readonly id: string; readonly offset: number };\n\nconst offsetInViewport = (element: Element, viewport: Element) =>\n element.getBoundingClientRect().top - viewport.getBoundingClientRect().top;\n\nconst measureFirstMessage = (viewport: HTMLElement): MessageOffset | null => {\n const element = viewport.querySelector<HTMLElement>(MESSAGE_SELECTOR);\n const id = element?.dataset[\"messageId\"];\n return element && id\n ? { id, offset: offsetInViewport(element, viewport) }\n : null;\n};\n\n/** The first message that starts in view, else the one spanning its top edge. */\nconst measureReaderMessage = (viewport: HTMLElement): MessageOffset | null => {\n const { top, bottom } = viewport.getBoundingClientRect();\n let spanning: MessageOffset | null = null;\n for (const element of viewport.querySelectorAll<HTMLElement>(\n MESSAGE_SELECTOR,\n )) {\n const rect = element.getBoundingClientRect();\n if (rect.bottom <= top) continue;\n if (rect.top >= bottom) break;\n const id = element.dataset[\"messageId\"];\n if (!id) continue;\n if (rect.top >= top) return { id, offset: rect.top - top };\n spanning ??= { id, offset: rect.top - top };\n }\n return spanning;\n};\n\nconst findMessage = (viewport: HTMLElement, id: string) => {\n for (const element of viewport.querySelectorAll<HTMLElement>(\n MESSAGE_SELECTOR,\n )) {\n if (element.dataset[\"messageId\"] === id) return element;\n }\n return null;\n};\n\n/**\n * Scrolls so the message sits at `anchor.offset` again, recording the\n * position it scrolls to in `heldScrollTop` before the scroll event can\n * report it; false when the message is gone.\n */\nconst keepMessageAt = (\n viewport: HTMLElement,\n anchor: MessageOffset,\n heldScrollTop: { current: number },\n) => {\n const element = findMessage(viewport, anchor.id);\n if (!element) return false;\n const delta = offsetInViewport(element, viewport) - anchor.offset;\n heldScrollTop.current = viewport.scrollTop + delta;\n if (Math.abs(delta) >= 1) {\n viewport.scrollTo({ top: heldScrollTop.current, behavior: \"instant\" });\n }\n heldScrollTop.current = viewport.scrollTop;\n return true;\n};\n\nexport namespace useThreadViewportAutoScroll {\n export type Options = {\n /**\n * Whether to automatically scroll to the bottom when new messages are added.\n * When enabled, the viewport will automatically scroll to show the latest content.\n *\n * Default false if `turnAnchor` is \"top\", otherwise defaults to true.\n */\n autoScroll?: boolean | undefined;\n\n /**\n * Whether to scroll to bottom when a new run starts.\n *\n * Defaults to true.\n */\n scrollToBottomOnRunStart?: boolean | undefined;\n\n /**\n * Whether to scroll to bottom when messages first appear in the thread.\n *\n * Defaults to true.\n */\n scrollToBottomOnInitialize?: boolean | undefined;\n\n /**\n * Whether to scroll to bottom when switching to a different thread.\n *\n * Defaults to true.\n */\n scrollToBottomOnThreadSwitch?: boolean | undefined;\n };\n}\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll,\n scrollToBottomOnRunStart = true,\n scrollToBottomOnInitialize = true,\n scrollToBottomOnThreadSwitch = true,\n}: useThreadViewportAutoScroll.Options): RefCallback<TElement> => {\n const aui = useAui();\n const divRef = useRef<TElement>(null);\n const hasMessages = useAuiState((s) => s.thread.messages.length > 0);\n const firstMessageId = useAuiState((s) => s.thread.messages[0]?.id);\n const threadId = useAuiState((s) => s.threadListItem.id);\n const isRunning = useAuiState((s) => s.thread.isRunning);\n const initializeScrollRequestedRef = useRef(false);\n const scheduledFrameRef = useRef<number | null>(null);\n\n const threadViewportStore = useThreadViewportStore();\n if (autoScroll === undefined) {\n autoScroll = threadViewportStore.getState().turnAnchor !== \"top\";\n }\n\n const lastScrollTop = useRef<number>(0);\n const lastScrollHeight = useRef<number>(0);\n const lastObservedScrollHeight = useRef<number>(0);\n const lastObservedClientHeight = useRef<number>(0);\n const firstMessageRef = useRef<MessageOffset | null>(null);\n // The row the reader sees when earlier messages land, held until a gesture\n // or a scroll this hook did not make, so content above it that settles\n // afterwards (lazy layout, late media) does not move it on engines without\n // native scroll anchoring.\n const prependAnchorRef = useRef<MessageOffset | null>(null);\n const heldScrollTopRef = useRef(0);\n\n // Pending bottom-scroll intent. Planted by initialize/run-start/switch/button\n // triggers, cleared when handleScroll confirms we reached bottom, or when the\n // user actively scrolls up while content size is stable.\n const scrollingToBottomBehaviorRef = useRef<ScrollBehavior | null>(null);\n const followBottomRef = useRef(autoScroll);\n const previousAutoScrollRef = useRef(autoScroll);\n\n useLayoutEffect(() => {\n const previousAutoScroll = previousAutoScrollRef.current;\n previousAutoScrollRef.current = autoScroll;\n if (previousAutoScroll || !autoScroll) return;\n\n const div = divRef.current;\n followBottomRef.current = div !== null && isViewportAtBottom(div);\n }, [autoScroll]);\n\n const scrollToBottom = useCallback((behavior: ScrollBehavior) => {\n const div = divRef.current;\n if (!div) return;\n\n followBottomRef.current = true;\n scrollingToBottomBehaviorRef.current = behavior;\n prependAnchorRef.current = null;\n div.scrollTo({ top: div.scrollHeight, behavior });\n }, []);\n\n const cancelScheduledFrame = useCallback(() => {\n if (scheduledFrameRef.current === null) return;\n cancelAnimationFrame(scheduledFrameRef.current);\n scheduledFrameRef.current = null;\n }, []);\n\n const scheduleScrollToBottom = useCallback(\n (behavior: ScrollBehavior) => {\n scrollingToBottomBehaviorRef.current = behavior;\n cancelScheduledFrame();\n scheduledFrameRef.current = requestAnimationFrame(() => {\n scheduledFrameRef.current = null;\n scrollToBottom(behavior);\n });\n },\n [cancelScheduledFrame, scrollToBottom],\n );\n\n useLayoutEffect(() => () => cancelScheduledFrame(), [cancelScheduledFrame]);\n\n const hasActiveTopAnchor = useCallback(() => {\n const state = threadViewportStore.getState();\n return (\n state.turnAnchor === \"top\" &&\n state.element.viewport === divRef.current &&\n state.element.anchor !== null\n );\n }, [threadViewportStore]);\n\n const handleScroll = () => {\n const div = divRef.current;\n if (!div) return;\n\n if (\n prependAnchorRef.current &&\n Math.abs(div.scrollTop - heldScrollTopRef.current) >= 1\n ) {\n prependAnchorRef.current = null;\n }\n\n const isAtBottom = threadViewportStore.getState().isAtBottom;\n const newIsAtBottom = isViewportAtBottom(div);\n\n const isInFlightDownwardScroll =\n !newIsAtBottom && lastScrollTop.current < div.scrollTop;\n if (isInFlightDownwardScroll) {\n // no-op: a smooth scroll-to-bottom fires many midpoint scroll events\n // before landing, don't flicker isAtBottom or clear intent mid-animation\n } else {\n const userScrolledUp = isUserScrollUp(\n {\n scrollTop: lastScrollTop.current,\n scrollHeight: lastScrollHeight.current,\n },\n div,\n );\n\n if (newIsAtBottom) {\n // newIsAtBottom is ambiguous when the viewport doesn't overflow —\n // keep intent alive until content can actually scroll\n if (viewportOverflows(div)) {\n scrollingToBottomBehaviorRef.current = null;\n }\n if (autoScroll) followBottomRef.current = true;\n } else if (userScrolledUp) {\n cancelScheduledFrame();\n scrollingToBottomBehaviorRef.current = null;\n followBottomRef.current = false;\n }\n\n const shouldUpdate =\n newIsAtBottom || scrollingToBottomBehaviorRef.current === null;\n\n if (shouldUpdate && newIsAtBottom !== isAtBottom) {\n writableStore(threadViewportStore).setState({\n isAtBottom: newIsAtBottom,\n });\n }\n }\n\n lastScrollTop.current = div.scrollTop;\n lastScrollHeight.current = div.scrollHeight;\n firstMessageRef.current = measureFirstMessage(div);\n };\n\n const resizeRef = useOnResizeContent(() => {\n const div = divRef.current;\n if (!div) return;\n\n const { scrollHeight, clientHeight } = div;\n if (\n scrollHeight === lastObservedScrollHeight.current &&\n clientHeight === lastObservedClientHeight.current\n ) {\n return;\n }\n lastObservedScrollHeight.current = scrollHeight;\n lastObservedClientHeight.current = clientHeight;\n\n const scrollBehavior = scrollingToBottomBehaviorRef.current;\n if (scrollBehavior && hasActiveTopAnchor()) {\n // Let the top-anchor reserve own scrolling while a run starts to avoid a bottom-scroll race.\n scrollingToBottomBehaviorRef.current = null;\n } else if (scrollBehavior) {\n scrollToBottom(scrollBehavior);\n } else if (\n autoScroll &&\n !(isRunning && hasActiveTopAnchor()) &&\n followBottomRef.current\n ) {\n scrollToBottom(\"instant\");\n } else if (\n prependAnchorRef.current &&\n !keepMessageAt(div, prependAnchorRef.current, heldScrollTopRef)\n ) {\n prependAnchorRef.current = null;\n }\n\n handleScroll();\n });\n\n const scrollRef = useManagedRef<HTMLElement>((el) => {\n // A user gesture invalidates pending bottom-scroll intent; otherwise an\n // intent kept alive by a non-overflowing thread (see handleScroll) hijacks\n // the next content growth, e.g. expanding a collapsible tool call. Keyboard\n // activation reaches that same content without ever emitting a pointer\n // event, so it has to cancel the intent too.\n const cancelPendingScrollToBottom = () => {\n // A scheduled frame re-plants the intent when it runs, so clearing the\n // ref alone leaves the gesture undone.\n cancelScheduledFrame();\n scrollingToBottomBehaviorRef.current = null;\n };\n // The composer renders inside the viewport, so its keystrokes bubble here;\n // only an activation key aimed at something other than a text field is a\n // gesture on thread content.\n const cancelOnKeyDown = (event: KeyboardEvent) => {\n if (!ACTIVATION_KEYS.has(event.key)) return;\n const target = event.target as Element | null;\n if (target?.closest?.(TEXT_ENTRY_SELECTOR)) return;\n cancelPendingScrollToBottom();\n };\n const releasePrependAnchor = () => {\n prependAnchorRef.current = null;\n };\n const gestures = [\"pointerdown\", \"wheel\", \"touchstart\", \"keydown\"] as const;\n el.addEventListener(\"scroll\", handleScroll);\n el.addEventListener(\"pointerdown\", cancelPendingScrollToBottom);\n el.addEventListener(\"keydown\", cancelOnKeyDown);\n for (const gesture of gestures) {\n el.addEventListener(gesture, releasePrependAnchor, { passive: true });\n }\n return () => {\n el.removeEventListener(\"scroll\", handleScroll);\n el.removeEventListener(\"pointerdown\", cancelPendingScrollToBottom);\n el.removeEventListener(\"keydown\", cancelOnKeyDown);\n for (const gesture of gestures) {\n el.removeEventListener(gesture, releasePrependAnchor);\n }\n };\n });\n\n // Earlier messages prepended above the reader put the old first message back\n // where the reader saw it, so growth below it in the same commit (a\n // streaming reply) is not mistaken for the page; where the browser already\n // anchored the scroll, this is a no-op.\n const previousRef = useRef({ threadId, firstMessageId });\n useLayoutEffect(() => {\n const previous = previousRef.current;\n previousRef.current = { threadId, firstMessageId };\n if (previous.threadId !== threadId) {\n prependAnchorRef.current = null;\n return;\n }\n const div = divRef.current;\n const previousFirstMessageId = previous.firstMessageId;\n if (\n !div ||\n previousFirstMessageId === undefined ||\n previousFirstMessageId === firstMessageId ||\n (autoScroll && followBottomRef.current) ||\n scrollingToBottomBehaviorRef.current !== null\n )\n return;\n const prepended = aui.thread\n .getState()\n .messages.some(\n (message, index) => index > 0 && message.id === previousFirstMessageId,\n );\n if (!prepended) return;\n\n const anchor = firstMessageRef.current;\n if (\n anchor?.id === previousFirstMessageId &&\n keepMessageAt(div, anchor, heldScrollTopRef)\n ) {\n prependAnchorRef.current = measureReaderMessage(div) ?? anchor;\n } else {\n // Message roots that render no `data-message-id` leave only the total\n // growth to go on, which counts any growth below the reader too.\n const top =\n div.scrollHeight - (lastScrollHeight.current - lastScrollTop.current);\n if (Math.abs(div.scrollTop - top) >= 1) {\n div.scrollTo({ top, behavior: \"instant\" });\n }\n }\n lastScrollTop.current = div.scrollTop;\n lastScrollHeight.current = div.scrollHeight;\n }, [aui, autoScroll, firstMessageId, threadId]);\n\n useLayoutEffect(() => {\n if (!scrollToBottomOnInitialize) return;\n if (!hasMessages) {\n initializeScrollRequestedRef.current = false;\n return;\n }\n if (initializeScrollRequestedRef.current) return;\n\n initializeScrollRequestedRef.current = true;\n // defer to an in-flight run (e.g. first message on a new thread) that\n // already planted intent — otherwise we'd downgrade its \"auto\" to \"instant\"\n if (scrollingToBottomBehaviorRef.current !== null) return;\n scheduleScrollToBottom(\"instant\");\n }, [hasMessages, scheduleScrollToBottom, scrollToBottomOnInitialize]);\n\n useOnScrollToBottom(({ behavior }) => {\n scrollToBottom(behavior);\n });\n\n useAuiEvent(\"thread.runStart\", () => {\n prependAnchorRef.current = null;\n if (!scrollToBottomOnRunStart) return;\n if (threadViewportStore.getState().turnAnchor === \"top\") return;\n scheduleScrollToBottom(\"auto\");\n });\n\n useAuiEvent(\"threads.selectionChanged\", () => {\n if (!scrollToBottomOnThreadSwitch) return;\n scheduleScrollToBottom(\"instant\");\n });\n\n const autoScrollRef = useComposedRefs<TElement>(resizeRef, scrollRef, divRef);\n return autoScrollRef as RefCallback<TElement>;\n};\n"],"mappings":";;;;;;;;;;;AAoBA,MAAMgB,kCAAkB,IAAIC,IAAI,CAAC,SAAS,GAAG,CAAC;AAM9C,MAAMC,sBAAsB;CAC1B;CACA;CACA;CACA;AAE+D,CAChE,CAACC,KAAK,IAAI;AAEX,MAAMC,mBAAmB;AAIzB,MAAMI,oBAAoBC,SAAkBE,aAC1CF,QAAQG,sBAAsB,CAAC,CAACC,MAAMF,SAASC,sBAAsB,CAAC,CAACC;AAEzE,MAAMC,uBAAuBH,aAAgD;CAC3E,MAAMF,UAAUE,SAASK,cAA2BZ,gBAAgB;CACpE,MAAME,KAAKG,SAASQ,QAAQ;CAC5B,OAAOR,WAAWH,KACd;EAAEA;EAAIC,QAAQC,iBAAiBC,SAASE,QAAQ;CAAE,IAClD;AACN;;AAGA,MAAMO,wBAAwBP,aAAgD;CAC5E,MAAM,EAAEE,KAAKM,WAAWR,SAASC,sBAAsB;CACvD,IAAIQ,WAAiC;CACrC,KAAK,MAAMX,WAAWE,SAASU,iBAC7BjB,gBACF,GAAG;EACD,MAAMkB,OAAOb,QAAQG,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EAE7C;EACAyB,cAAc/B,UAAU2C,MAAIzC;EAC5B8B,iBAAiBhC,UAAU2C,MAAIE;CACjC,GAAG;EAAC/B;EAAKL;EAAYY;EAAgBC;CAAQ,CAAC;CAE9C/D,sBAAsB;EACpB,IAAI,CAACoD,4BAA4B;EACjC,IAAI,CAACK,aAAa;GAChBS,6BAA6BzB,UAAU;GACvC;EACF;EACA,IAAIyB,6BAA6BzB,SAAS;EAE1CyB,6BAA6BzB,UAAU;EAGvC,IAAIsC,6BAA6BtC,YAAY,MAAM;EACnDgD,uBAAuB,SAAS;CAClC,GAAG;EAAChC;EAAagC;EAAwBrC;CAA0B,CAAC;CAEpE1C,qBAAqB,EAAEqC,UAAAA,iBAAe;EACpCsC,eAAetC,UAAQ;CACzB,CAAC;CAED3C,YAAY,yBAAyB;EACnCyE,iBAAiBpC,UAAU;EAC3B,IAAI,CAACU,0BAA0B;EAC/B,IAAIiB,oBAAoBE,SAAS,CAAC,CAACC,eAAe,OAAO;EACzDkB,uBAAuB,MAAM;CAC/B,CAAC;CAEDrF,YAAY,kCAAkC;EAC5C,IAAI,CAACiD,8BAA8B;EACnCoC,uBAAuB,SAAS;CAClC,CAAC;CAGD,OADsB3F,gBAA0BsG,WAAWG,WAAW/C,MAC/DuE;AACT"}
|
|
1
|
+
{"version":3,"file":"useThreadViewportAutoScroll.js","names":["useComposedRefs","useCallback","useRef","RefCallback","useAui","useAuiEvent","useAuiState","isUserScrollUp","isViewportAtBottom","viewportOverflows","useOnResizeContent","useOnScrollToBottom","useManagedRef","writableStore","useThreadViewportStore","useIsomorphicLayoutEffect","SCROLL_KEYS","Set","INTENT_CANCEL_KEYS","TEXT_ENTRY_SELECTOR","join","MESSAGE_SELECTOR","DISCLOSURE_SELECTOR","isOpeningDisclosure","target","Element","control","closest","tagName","parentElement","hasAttribute","getAttribute","MessageOffset","id","offset","offsetInViewport","element","viewport","getBoundingClientRect","top","measureFirstMessage","HTMLElement","querySelector","dataset","measureReaderMessage","bottom","spanning","querySelectorAll","rect","findMessage","keepMessageAt","anchor","heldScrollTop","current","delta","scrollTop","Math","abs","scrollTo","behavior","useThreadViewportAutoScroll","Options","autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","TElement","aui","divRef","hasMessages","s","thread","messages","length","firstMessageId","threadId","threadListItem","isRunning","initializeScrollRequestedRef","scheduledFrameRef","threadViewportStore","undefined","getState","turnAnchor","lastScrollTop","lastScrollHeight","lastObservedScrollHeight","lastObservedClientHeight","firstMessageRef","prependAnchorRef","heldScrollTopRef","scrollingToBottomBehaviorRef","ScrollBehavior","followBottomRef","followPausedRef","scrolledSincePauseRef","previousAutoScrollRef","previousAutoScroll","div","scrollToBottom","scrollHeight","cancelScheduledFrame","cancelAnimationFrame","scheduleScrollToBottom","requestAnimationFrame","hasActiveTopAnchor","state","onScroll","isAtBottom","newIsAtBottom","isInFlightDownwardScroll","userScrolledUp","shouldUpdate","setState","onScrollRef","handleScroll","onResize","clientHeight","scrollBehavior","onResizeRef","resizeRef","scrollRef","el","cancelPendingScrollToBottom","cancelOnKeyDown","event","KeyboardEvent","has","key","pauseFollowOnExpand","MouseEvent","noteScrollGesture","Event","type","releasePrependAnchor","gestures","const","resumeGestures","addEventListener","passive","capture","gesture","removeEventListener","previousRef","previous","previousFirstMessageId","prepended","some","message","index","autoScrollRef"],"sources":["../../../src/primitives/thread/useThreadViewportAutoScroll.ts"],"sourcesContent":["\"use client\";\n\nimport { useComposedRefs } from \"radix-ui/internal\";\nimport { useCallback, useRef, type RefCallback } from \"react\";\nimport { useAui, useAuiEvent, useAuiState } from \"@assistant-ui/store\";\nimport {\n isUserScrollUp,\n isViewportAtBottom,\n viewportOverflows,\n} from \"@assistant-ui/store/client\";\nimport { useOnResizeContent } from \"../../utils/hooks/useOnResizeContent\";\nimport { useOnScrollToBottom } from \"../../utils/hooks/useOnScrollToBottom\";\nimport { useManagedRef } from \"../../utils/hooks/useManagedRef\";\nimport { writableStore } from \"../../context/ReadonlyStore\";\nimport { useThreadViewportStore } from \"../../context/react/ThreadViewportContext\";\nimport { useIsomorphicLayoutEffect } from \"../../utils/useIsomorphicLayoutEffect\";\n\nconst SCROLL_KEYS = new Set([\n \" \",\n \"ArrowUp\",\n \"ArrowDown\",\n \"PageUp\",\n \"PageDown\",\n \"Home\",\n \"End\",\n]);\n\n// Enter and Space activate focused controls, while navigation keys can\n// interrupt scrolling without producing a scroll event.\nconst INTENT_CANCEL_KEYS = new Set([\"Enter\", ...SCROLL_KEYS]);\n\n// A control that consumes the activation key itself instead of acting on thread\n// content. `contenteditable=\"false\"` marks a non-editable island inside an\n// editable tree, so it is excluded the way ComposerRoot already excludes it;\n// the input types left out are the ones a key activates rather than fills.\nconst TEXT_ENTRY_SELECTOR = [\n \"textarea\",\n \"select\",\n \"[contenteditable]:not([contenteditable='false'])\",\n \"input:not([type='checkbox']):not([type='radio']):not([type='button'])\" +\n \":not([type='submit']):not([type='reset']):not([type='image'])\" +\n \":not([type='range']):not([type='file']):not([type='color'])\",\n].join(\", \");\n\nconst MESSAGE_SELECTOR = \"[data-message-id]\";\n\nconst DISCLOSURE_SELECTOR = \"[aria-expanded], summary\";\n\n// A popup trigger (menu, dialog, listbox) also carries aria-expanded, but what\n// it opens is portaled away from the thread, so only disclosures count.\nconst isOpeningDisclosure = (target: Element): boolean => {\n const control = target.closest(DISCLOSURE_SELECTOR);\n if (!control) return false;\n if (control.tagName === \"SUMMARY\")\n return control.parentElement?.hasAttribute(\"open\") === false;\n return (\n control.getAttribute(\"aria-expanded\") === \"false\" &&\n (control.getAttribute(\"aria-haspopup\") ?? \"false\") === \"false\" &&\n control.getAttribute(\"role\") !== \"combobox\"\n );\n};\n\ntype MessageOffset = { readonly id: string; readonly offset: number };\n\nconst offsetInViewport = (element: Element, viewport: Element) =>\n element.getBoundingClientRect().top - viewport.getBoundingClientRect().top;\n\nconst measureFirstMessage = (viewport: HTMLElement): MessageOffset | null => {\n const element = viewport.querySelector<HTMLElement>(MESSAGE_SELECTOR);\n const id = element?.dataset[\"messageId\"];\n return element && id\n ? { id, offset: offsetInViewport(element, viewport) }\n : null;\n};\n\n/** The first message that starts in view, else the one spanning its top edge. */\nconst measureReaderMessage = (viewport: HTMLElement): MessageOffset | null => {\n const { top, bottom } = viewport.getBoundingClientRect();\n let spanning: MessageOffset | null = null;\n for (const element of viewport.querySelectorAll<HTMLElement>(\n MESSAGE_SELECTOR,\n )) {\n const rect = element.getBoundingClientRect();\n if (rect.bottom <= top) continue;\n if (rect.top >= bottom) break;\n const id = element.dataset[\"messageId\"];\n if (!id) continue;\n if (rect.top >= top) return { id, offset: rect.top - top };\n spanning ??= { id, offset: rect.top - top };\n }\n return spanning;\n};\n\nconst findMessage = (viewport: HTMLElement, id: string) => {\n for (const element of viewport.querySelectorAll<HTMLElement>(\n MESSAGE_SELECTOR,\n )) {\n if (element.dataset[\"messageId\"] === id) return element;\n }\n return null;\n};\n\n/**\n * Scrolls so the message sits at `anchor.offset` again, recording the\n * position it scrolls to in `heldScrollTop` before the scroll event can\n * report it; false when the message is gone.\n */\nconst keepMessageAt = (\n viewport: HTMLElement,\n anchor: MessageOffset,\n heldScrollTop: { current: number },\n) => {\n const element = findMessage(viewport, anchor.id);\n if (!element) return false;\n const delta = offsetInViewport(element, viewport) - anchor.offset;\n heldScrollTop.current = viewport.scrollTop + delta;\n if (Math.abs(delta) >= 1) {\n viewport.scrollTo({ top: heldScrollTop.current, behavior: \"instant\" });\n }\n heldScrollTop.current = viewport.scrollTop;\n return true;\n};\n\nexport namespace useThreadViewportAutoScroll {\n export type Options = {\n /**\n * Whether to automatically scroll to the bottom when new messages are added.\n * When enabled, the viewport will automatically scroll to show the latest content.\n *\n * Default false if `turnAnchor` is \"top\", otherwise defaults to true.\n */\n autoScroll?: boolean | undefined;\n\n /**\n * Whether to scroll to bottom when a new run starts.\n *\n * Defaults to true.\n */\n scrollToBottomOnRunStart?: boolean | undefined;\n\n /**\n * Whether to scroll to bottom when messages first appear in the thread.\n *\n * Defaults to true.\n */\n scrollToBottomOnInitialize?: boolean | undefined;\n\n /**\n * Whether to scroll to bottom when switching to a different thread.\n *\n * Defaults to true.\n */\n scrollToBottomOnThreadSwitch?: boolean | undefined;\n };\n}\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll,\n scrollToBottomOnRunStart = true,\n scrollToBottomOnInitialize = true,\n scrollToBottomOnThreadSwitch = true,\n}: useThreadViewportAutoScroll.Options): RefCallback<TElement> => {\n const aui = useAui();\n const divRef = useRef<TElement>(null);\n const hasMessages = useAuiState((s) => s.thread.messages.length > 0);\n const firstMessageId = useAuiState((s) => s.thread.messages[0]?.id);\n const threadId = useAuiState((s) => s.threadListItem.id);\n const isRunning = useAuiState((s) => s.thread.isRunning);\n const initializeScrollRequestedRef = useRef(false);\n const scheduledFrameRef = useRef<number | null>(null);\n\n const threadViewportStore = useThreadViewportStore();\n if (autoScroll === undefined) {\n autoScroll = threadViewportStore.getState().turnAnchor !== \"top\";\n }\n\n const lastScrollTop = useRef<number>(0);\n const lastScrollHeight = useRef<number>(0);\n const lastObservedScrollHeight = useRef<number>(0);\n const lastObservedClientHeight = useRef<number>(0);\n const firstMessageRef = useRef<MessageOffset | null>(null);\n // The row the reader sees when earlier messages land, held until a gesture\n // or a scroll this hook did not make, so content above it that settles\n // afterwards (lazy layout, late media) does not move it on engines without\n // native scroll anchoring.\n const prependAnchorRef = useRef<MessageOffset | null>(null);\n const heldScrollTopRef = useRef(0);\n\n // Pending bottom-scroll intent. Planted by initialize/run-start/switch/button\n // triggers, cleared when handleScroll confirms we reached bottom, or when the\n // user actively scrolls up while content size is stable.\n const scrollingToBottomBehaviorRef = useRef<ScrollBehavior | null>(null);\n const followBottomRef = useRef(autoScroll);\n // Set by expanding a disclosure; suspends follow without clearing its intent\n // until a scroll gesture reaches an overflowing bottom (content that fits\n // reads as at the bottom), a run starts, the thread changes, or the reader\n // asks for the bottom again.\n const followPausedRef = useRef(false);\n const scrolledSincePauseRef = useRef(false);\n const previousAutoScrollRef = useRef(autoScroll);\n\n useIsomorphicLayoutEffect(() => {\n const previousAutoScroll = previousAutoScrollRef.current;\n previousAutoScrollRef.current = autoScroll;\n if (previousAutoScroll || !autoScroll) return;\n\n const div = divRef.current;\n followBottomRef.current = div !== null && isViewportAtBottom(div);\n }, [autoScroll]);\n\n const scrollToBottom = useCallback((behavior: ScrollBehavior) => {\n const div = divRef.current;\n if (!div) return;\n\n followBottomRef.current = true;\n followPausedRef.current = false;\n scrollingToBottomBehaviorRef.current = behavior;\n prependAnchorRef.current = null;\n div.scrollTo({ top: div.scrollHeight, behavior });\n lastScrollTop.current = div.scrollTop;\n lastScrollHeight.current = div.scrollHeight;\n }, []);\n\n const cancelScheduledFrame = useCallback(() => {\n if (scheduledFrameRef.current === null) return;\n cancelAnimationFrame(scheduledFrameRef.current);\n scheduledFrameRef.current = null;\n }, []);\n\n const scheduleScrollToBottom = useCallback(\n (behavior: ScrollBehavior) => {\n scrollingToBottomBehaviorRef.current = behavior;\n cancelScheduledFrame();\n scheduledFrameRef.current = requestAnimationFrame(() => {\n scheduledFrameRef.current = null;\n scrollToBottom(behavior);\n });\n },\n [cancelScheduledFrame, scrollToBottom],\n );\n\n useIsomorphicLayoutEffect(\n () => () => cancelScheduledFrame(),\n [cancelScheduledFrame],\n );\n\n const hasActiveTopAnchor = useCallback(() => {\n const state = threadViewportStore.getState();\n return (\n state.turnAnchor === \"top\" &&\n state.element.viewport === divRef.current &&\n state.element.anchor !== null\n );\n }, [threadViewportStore]);\n\n const onScroll = () => {\n const div = divRef.current;\n if (!div) return;\n\n if (\n prependAnchorRef.current &&\n Math.abs(div.scrollTop - heldScrollTopRef.current) >= 1\n ) {\n prependAnchorRef.current = null;\n }\n\n const isAtBottom = threadViewportStore.getState().isAtBottom;\n const newIsAtBottom = isViewportAtBottom(div);\n\n const isInFlightDownwardScroll =\n scrollingToBottomBehaviorRef.current !== null &&\n !newIsAtBottom &&\n lastScrollTop.current < div.scrollTop;\n if (isInFlightDownwardScroll) {\n // no-op: a smooth scroll-to-bottom fires many midpoint scroll events\n // before landing, don't flicker isAtBottom or clear intent mid-animation\n } else {\n const userScrolledUp = isUserScrollUp(\n {\n scrollTop: lastScrollTop.current,\n scrollHeight: lastScrollHeight.current,\n },\n div,\n );\n\n if (newIsAtBottom) {\n // newIsAtBottom is ambiguous when the viewport doesn't overflow —\n // keep intent alive until content can actually scroll\n if (viewportOverflows(div)) {\n scrollingToBottomBehaviorRef.current = null;\n if (scrolledSincePauseRef.current) followPausedRef.current = false;\n }\n if (autoScroll) followBottomRef.current = true;\n } else if (userScrolledUp) {\n cancelScheduledFrame();\n scrollingToBottomBehaviorRef.current = null;\n followBottomRef.current = false;\n }\n\n const shouldUpdate =\n newIsAtBottom || scrollingToBottomBehaviorRef.current === null;\n\n if (shouldUpdate && newIsAtBottom !== isAtBottom) {\n writableStore(threadViewportStore).setState({\n isAtBottom: newIsAtBottom,\n });\n }\n }\n\n lastScrollTop.current = div.scrollTop;\n lastScrollHeight.current = div.scrollHeight;\n firstMessageRef.current = measureFirstMessage(div);\n };\n const onScrollRef = useRef(onScroll);\n useIsomorphicLayoutEffect(() => {\n onScrollRef.current = onScroll;\n });\n const handleScroll = useCallback(() => onScrollRef.current(), []);\n\n const onResize = () => {\n const div = divRef.current;\n if (!div) return;\n\n const { scrollHeight, clientHeight } = div;\n if (\n scrollHeight === lastObservedScrollHeight.current &&\n clientHeight === lastObservedClientHeight.current\n ) {\n return;\n }\n lastObservedScrollHeight.current = scrollHeight;\n lastObservedClientHeight.current = clientHeight;\n\n // A scheduled frame owns the pending behavior; resize callbacks must not apply it early.\n if (scheduledFrameRef.current === null) {\n const scrollBehavior = scrollingToBottomBehaviorRef.current;\n if (scrollBehavior && hasActiveTopAnchor()) {\n // Let the top-anchor reserve own scrolling while a run starts to avoid a bottom-scroll race.\n scrollingToBottomBehaviorRef.current = null;\n } else if (scrollBehavior) {\n scrollToBottom(scrollBehavior);\n } else if (\n autoScroll &&\n !(isRunning && hasActiveTopAnchor()) &&\n followBottomRef.current &&\n !followPausedRef.current\n ) {\n scrollToBottom(\"instant\");\n } else if (\n prependAnchorRef.current &&\n !keepMessageAt(div, prependAnchorRef.current, heldScrollTopRef)\n ) {\n prependAnchorRef.current = null;\n }\n }\n\n handleScroll();\n };\n const onResizeRef = useRef(onResize);\n useIsomorphicLayoutEffect(() => {\n onResizeRef.current = onResize;\n });\n const resizeRef = useOnResizeContent(() => onResizeRef.current());\n\n const scrollRef = useManagedRef<HTMLElement>(\n useCallback(\n (el) => {\n // A user gesture invalidates pending bottom-scroll intent; otherwise an\n // intent kept alive by a non-overflowing thread (see handleScroll) hijacks\n // the next content growth, e.g. expanding a collapsible tool call. Keyboard\n // activation reaches that same content without ever emitting a pointer\n // event, so it has to cancel the intent too.\n const cancelPendingScrollToBottom = () => {\n // With nothing pending, the last scroll event already published isAtBottom.\n if (\n scrollingToBottomBehaviorRef.current === null &&\n scheduledFrameRef.current === null\n )\n return;\n // A scheduled frame re-plants the intent when it runs, so clearing the\n // ref alone leaves the gesture undone.\n cancelScheduledFrame();\n scrollingToBottomBehaviorRef.current = null;\n handleScroll();\n };\n // The composer renders inside the viewport, so its keystrokes bubble here;\n // cancellation keys only represent a gesture on thread content when they\n // originate outside text entry.\n const cancelOnKeyDown = (event: KeyboardEvent) => {\n if (!INTENT_CANCEL_KEYS.has(event.key)) return;\n const target = event.target as Element | null;\n if (target?.closest?.(TEXT_ENTRY_SELECTOR)) return;\n cancelPendingScrollToBottom();\n };\n // Expanding a disclosure inside a message, such as a reasoning block or a\n // tool call card, means the reader is inspecting it, so bottom follow\n // pauses until the reader scrolls or asks for the bottom again. Every\n // other interaction, including copying or selecting text, keeps\n // following. Activation is read from click, which keyboard activation also\n // dispatches, in the capture phase so the state is read before any handler\n // on the disclosure flips it or stops the event.\n const pauseFollowOnExpand = (event: MouseEvent) => {\n const target = event.target as Element | null;\n if (\n !target?.closest?.(MESSAGE_SELECTOR) ||\n target.closest(TEXT_ENTRY_SELECTOR) ||\n !isOpeningDisclosure(target)\n )\n return;\n followPausedRef.current = true;\n scrolledSincePauseRef.current = false;\n cancelPendingScrollToBottom();\n };\n const noteScrollGesture = (event: Event) => {\n if (event instanceof KeyboardEvent) {\n if (!SCROLL_KEYS.has(event.key)) return;\n if (\n (event.target as Element | null)?.closest?.(TEXT_ENTRY_SELECTOR)\n )\n return;\n } else if (event.type === \"pointerdown\" && event.target !== el) {\n return;\n }\n scrolledSincePauseRef.current = true;\n };\n const releasePrependAnchor = () => {\n prependAnchorRef.current = null;\n };\n const gestures = [\n \"pointerdown\",\n \"wheel\",\n \"touchstart\",\n \"keydown\",\n ] as const;\n const resumeGestures = [\n \"pointerdown\",\n \"wheel\",\n \"touchmove\",\n \"keydown\",\n ] as const;\n el.addEventListener(\"scroll\", handleScroll);\n el.addEventListener(\"pointerdown\", cancelPendingScrollToBottom);\n el.addEventListener(\"wheel\", cancelPendingScrollToBottom, {\n passive: true,\n });\n el.addEventListener(\"touchstart\", cancelPendingScrollToBottom, {\n passive: true,\n });\n el.addEventListener(\"keydown\", cancelOnKeyDown);\n el.addEventListener(\"click\", pauseFollowOnExpand, { capture: true });\n for (const gesture of resumeGestures) {\n el.addEventListener(gesture, noteScrollGesture, { passive: true });\n }\n for (const gesture of gestures) {\n el.addEventListener(gesture, releasePrependAnchor, { passive: true });\n }\n return () => {\n el.removeEventListener(\"scroll\", handleScroll);\n el.removeEventListener(\"pointerdown\", cancelPendingScrollToBottom);\n el.removeEventListener(\"wheel\", cancelPendingScrollToBottom);\n el.removeEventListener(\"touchstart\", cancelPendingScrollToBottom);\n el.removeEventListener(\"keydown\", cancelOnKeyDown);\n el.removeEventListener(\"click\", pauseFollowOnExpand, {\n capture: true,\n });\n for (const gesture of resumeGestures) {\n el.removeEventListener(gesture, noteScrollGesture);\n }\n for (const gesture of gestures) {\n el.removeEventListener(gesture, releasePrependAnchor);\n }\n };\n },\n [cancelScheduledFrame, handleScroll],\n ),\n );\n\n // Earlier messages prepended above the reader put the old first message back\n // where the reader saw it, so growth below it in the same commit (a\n // streaming reply) is not mistaken for the page; where the browser already\n // anchored the scroll, this is a no-op.\n const previousRef = useRef({ threadId, firstMessageId });\n useIsomorphicLayoutEffect(() => {\n const previous = previousRef.current;\n previousRef.current = { threadId, firstMessageId };\n if (previous.threadId !== threadId) {\n prependAnchorRef.current = null;\n return;\n }\n const div = divRef.current;\n const previousFirstMessageId = previous.firstMessageId;\n if (\n !div ||\n previousFirstMessageId === undefined ||\n previousFirstMessageId === firstMessageId ||\n (autoScroll && followBottomRef.current && !followPausedRef.current) ||\n scrollingToBottomBehaviorRef.current !== null\n )\n return;\n const prepended = aui.thread\n .getState()\n .messages.some(\n (message, index) => index > 0 && message.id === previousFirstMessageId,\n );\n if (!prepended) return;\n\n const anchor = firstMessageRef.current;\n if (\n anchor?.id === previousFirstMessageId &&\n keepMessageAt(div, anchor, heldScrollTopRef)\n ) {\n prependAnchorRef.current = measureReaderMessage(div) ?? anchor;\n } else {\n // Message roots that render no `data-message-id` leave only the total\n // growth to go on, which counts any growth below the reader too.\n const top =\n div.scrollHeight - (lastScrollHeight.current - lastScrollTop.current);\n if (Math.abs(div.scrollTop - top) >= 1) {\n div.scrollTo({ top, behavior: \"instant\" });\n }\n }\n lastScrollTop.current = div.scrollTop;\n lastScrollHeight.current = div.scrollHeight;\n }, [aui, autoScroll, firstMessageId, threadId]);\n\n useIsomorphicLayoutEffect(() => {\n if (!scrollToBottomOnInitialize) return;\n if (!hasMessages) {\n initializeScrollRequestedRef.current = false;\n return;\n }\n if (initializeScrollRequestedRef.current) return;\n\n initializeScrollRequestedRef.current = true;\n // defer to an in-flight run (e.g. first message on a new thread) that\n // already planted intent — otherwise we'd downgrade its \"auto\" to \"instant\"\n if (scrollingToBottomBehaviorRef.current !== null) return;\n scheduleScrollToBottom(\"instant\");\n }, [hasMessages, scheduleScrollToBottom, scrollToBottomOnInitialize]);\n\n useOnScrollToBottom(({ behavior }) => {\n scrollToBottom(behavior);\n });\n\n useAuiEvent(\"thread.runStart\", () => {\n prependAnchorRef.current = null;\n followPausedRef.current = false;\n if (!scrollToBottomOnRunStart) return;\n if (threadViewportStore.getState().turnAnchor === \"top\") return;\n scheduleScrollToBottom(\"auto\");\n });\n\n useAuiEvent(\"threads.selectionChanged\", () => {\n followPausedRef.current = false;\n if (!scrollToBottomOnThreadSwitch) return;\n scheduleScrollToBottom(\"instant\");\n });\n\n const autoScrollRef = useComposedRefs<TElement>(resizeRef, scrollRef, divRef);\n return autoScrollRef as RefCallback<TElement>;\n};\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAMgB,8BAAc,IAAIC,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;AAAK,CACN;AAID,MAAMC,qCAAqB,IAAID,IAAI,CAAC,SAAS,GAAGD,WAAW,CAAC;AAM5D,MAAMG,sBAAsB;CAC1B;CACA;CACA;CACA;AAE+D,CAChE,CAACC,KAAK,IAAI;AAEX,MAAMC,mBAAmB;AAEzB,MAAMC,sBAAsB;AAI5B,MAAMC,uBAAuBC,WAA6B;CACxD,MAAME,UAAUF,OAAOG,QAAQL,mBAAmB;CAClD,IAAI,CAACI,SAAS,OAAO;CACrB,IAAIA,QAAQE,YAAY,WACtB,OAAOF,QAAQG,eAAeC,aAAa,MAAM,MAAM;CACzD,OACEJ,QAAQK,aAAa,eAAe,MAAM,YACzCL,QAAQK,aAAa,eAAe,KAAK,aAAa,WACvDL,QAAQK,aAAa,MAAM,MAAM;AAErC;AAIA,MAAMI,oBAAoBC,SAAkBC,aAC1CD,QAAQE,sBAAsB,CAAC,CAACC,MAAMF,SAASC,sBAAsB,CAAC,CAACC;AAEzE,MAAMC,uBAAuBH,aAAgD;CAC3E,MAAMD,UAAUC,SAASK,cAA2BrB,gBAAgB;CACpE,MAAMY,KAAKG,SAASO,QAAQ;CAC5B,OAAOP,WAAWH,KACd;EAAEA;EAAIC,QAAQC,iBAAiBC,SAASC,QAAQ;CAAE,IAClD;AACN;;AAGA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;CAEDtD,YAAY,yBAAyB;EACnCoF,iBAAiBpC,UAAU;EAC3ByC,gBAAgBzC,UAAU;EAC1B,IAAI,CAACU,0BAA0B;EAC/B,IAAIiB,oBAAoBE,SAAS,CAAC,CAACC,eAAe,OAAO;EACzDoB,uBAAuB,MAAM;CAC/B,CAAC;CAEDlG,YAAY,kCAAkC;EAC5CyF,gBAAgBzC,UAAU;EAC1B,IAAI,CAACY,8BAA8B;EACnCsC,uBAAuB,SAAS;CAClC,CAAC;CAGD,OADsBvG,gBAA0BwH,WAAWC,WAAWrD,MAC/DkF;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SandboxHost.d.ts","sourceRoot":"","sources":["../../src/sandbox-host/SandboxHost.tsx"],"names":[],"mappings":"AAEA,OAAO,
|
|
1
|
+
{"version":3,"file":"SandboxHost.d.ts","sourceRoot":"","sources":["../../src/sandbox-host/SandboxHost.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,aAAa,EAA+B,MAAM,OAAO,CAAC;AAExE,OAAO,EAEL,KAAK,aAAa,EAElB,KAAK,aAAa,EACnB,MAAM,oBAAoB,CAAC;AAO5B,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,CAAC,EAAE,aAAa,EAAE,CAAC;IAC1B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,mBAAmB,CAAC,EAAE,OAAO,CAAC;CAC/B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG,IAAI,CACjC,aAAa,EACb,QAAQ,GAAG,QAAQ,GAAG,aAAa,CACpC,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,SAAS,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CACrC,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,SAAS,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,CAAC;IACzC,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9C,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,cAAc,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,iBAAiB,GAAG,SAAS,CAAC;IACxC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,YAAY,EAAE,CACZ,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,cAAc,KACjB,aAAa,CAAC;IACnB,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IAC/C,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,SAAS,CAAC;CACjE,CAAC;AAEF,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,YAAY,EACnB,KAAK,EAAE;IAAE,MAAM,EAAE,iBAAiB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GACnD,OAAO,CAIT;AASD,wBAAgB,WAAW,CAAC,EAC1B,OAAO,EACP,UAAU,EACV,OAAO,EACP,SAA8B,EAC9B,YAAY,EACZ,OAAO,EACP,cAAc,GACf,EAAE,gBAAgB,+BAkKlB"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { useIsomorphicLayoutEffect } from "../utils/useIsomorphicLayoutEffect.js";
|
|
2
3
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
3
|
-
import { useEffect,
|
|
4
|
+
import { useEffect, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
4
5
|
import { invokeUserCallback } from "@assistant-ui/core/internal";
|
|
5
6
|
import { jsx } from "react/jsx-runtime";
|
|
6
7
|
import { SafeContentFrame, isShimLoadError } from "safe-content-frame";
|
|
@@ -59,7 +60,7 @@ function SandboxHost(t0) {
|
|
|
59
60
|
t3 = $[9];
|
|
60
61
|
t4 = $[10];
|
|
61
62
|
}
|
|
62
|
-
|
|
63
|
+
useIsomorphicLayoutEffect(t3, t4);
|
|
63
64
|
let t5;
|
|
64
65
|
if ($[11] === Symbol.for("react.memo_cache_sentinel")) {
|
|
65
66
|
t5 = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SandboxHost.js","names":["c","_c","CSSProperties","useEffect","useLayoutEffect","useRef","useState","isShimLoadError","RenderedFrame","SafeContentFrame","SandboxOption","invokeUserCallback","DEFAULT_PRODUCT","DEFAULT_MAX_HEIGHT","LOAD_TIMEOUT_MS","SandboxHostConfig","sandbox","useShadowDom","enableBrowserCaching","salt","product","className","style","unsafeDocumentWrite","SandboxHostFrame","Pick","SandboxHostApi","setHeight","height","SandboxBridge","onMessage","event","MessageEvent","dispose","SandboxContent","html","SandboxHostProps","content","contentKey","maxHeight","createBridge","frame","host","onError","error","Error","containerProps","Record","isSandboxFrameMessage","iframe","HTMLIFrameElement","origin","source","contentWindow","LiveSnapshot","SandboxHost","t0","$","t1","undefined","containerRef","contentHeight","setContentHeight","t2","liveRef","t3","t4","current","t5","Symbol","for","container","cancelled","bridge","renderController","AbortController","liveContent","sb","reportError","err","String","bind","scf","renderOpts","signal","renderHtml","then","rendered","hostApi","Number","isFinite","sendMessage","window","addEventListener","fullyLoadedPromiseWithTimeout","catch","err_0","code","err_1","cleanupFailed","cleanupError","runCleanup","cleanup","t6","console","listener","removeEventListener","bridgeToDispose","abort","frameToDispose","resolvedHeight","Math","min","t7","mergedStyle","t8","t9","_c"],"sources":["../../src/sandbox-host/SandboxHost.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type CSSProperties,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport {\n isShimLoadError,\n type RenderedFrame,\n SafeContentFrame,\n type SandboxOption,\n} from \"safe-content-frame\";\nimport { invokeUserCallback } from \"@assistant-ui/core/internal\";\n\nconst DEFAULT_PRODUCT = \"assistant-ui-sandbox\";\nconst DEFAULT_MAX_HEIGHT = 800;\nconst LOAD_TIMEOUT_MS = 10_000;\n\nexport type SandboxHostConfig = {\n sandbox?: SandboxOption[];\n useShadowDom?: boolean;\n enableBrowserCaching?: boolean;\n salt?: string;\n product?: string;\n className?: string;\n style?: CSSProperties;\n unsafeDocumentWrite?: boolean;\n};\n\nexport type SandboxHostFrame = Pick<\n RenderedFrame,\n \"iframe\" | \"origin\" | \"sendMessage\"\n>;\n\nexport type SandboxHostApi = {\n setHeight: (height: number) => void;\n};\n\nexport type SandboxBridge = {\n onMessage: (event: MessageEvent) => void;\n dispose: () => void;\n};\n\nexport type SandboxContent = { html: string };\n\nexport type SandboxHostProps = {\n content: SandboxContent;\n contentKey: string;\n sandbox?: SandboxHostConfig | undefined;\n maxHeight?: number | undefined;\n createBridge: (\n frame: SandboxHostFrame,\n host: SandboxHostApi,\n ) => SandboxBridge;\n onError?: ((error: Error) => void) | undefined;\n containerProps?: Record<string, string | undefined> | undefined;\n};\n\nexport function isSandboxFrameMessage(\n event: MessageEvent,\n frame: { iframe: HTMLIFrameElement; origin: string },\n): boolean {\n return (\n event.source === frame.iframe.contentWindow && event.origin === frame.origin\n );\n}\n\ntype LiveSnapshot = {\n content: SandboxContent;\n sandbox: SandboxHostConfig | undefined;\n createBridge: SandboxHostProps[\"createBridge\"];\n onError: SandboxHostProps[\"onError\"];\n};\n\nexport function SandboxHost({\n content,\n contentKey,\n sandbox,\n maxHeight = DEFAULT_MAX_HEIGHT,\n createBridge,\n onError,\n containerProps,\n}: SandboxHostProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const [contentHeight, setContentHeight] = useState<number | undefined>(\n undefined,\n );\n\n const liveRef = useRef<LiveSnapshot>({\n content,\n sandbox,\n createBridge,\n onError,\n });\n useLayoutEffect(() => {\n liveRef.current = { content, sandbox, createBridge, onError };\n }, [content, sandbox, createBridge, onError]);\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container) return;\n\n let cancelled = false;\n let frame: RenderedFrame | null = null;\n let bridge: SandboxBridge | null = null;\n let onMessage: ((event: MessageEvent) => void) | null = null;\n const renderController = new AbortController();\n\n const { content: liveContent, sandbox: sb } = liveRef.current;\n\n const reportError = (err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n invokeUserCallback(\n \"assistant-ui\",\n \"SandboxHost onError\",\n liveRef.current.onError?.bind(liveRef.current),\n error,\n );\n };\n\n const scf = new SafeContentFrame(sb?.product ?? DEFAULT_PRODUCT, {\n ...(sb?.sandbox !== undefined && { sandbox: sb.sandbox }),\n ...(sb?.useShadowDom !== undefined && { useShadowDom: sb.useShadowDom }),\n ...(sb?.enableBrowserCaching !== undefined && {\n enableBrowserCaching: sb.enableBrowserCaching,\n }),\n ...(sb?.salt !== undefined && { salt: sb.salt }),\n });\n\n const renderOpts = {\n signal: renderController.signal,\n ...(sb?.unsafeDocumentWrite !== undefined && {\n unsafeDocumentWrite: sb.unsafeDocumentWrite,\n }),\n };\n\n scf\n .renderHtml(liveContent.html, container, renderOpts)\n .then((rendered) => {\n if (cancelled) {\n rendered.dispose();\n return;\n }\n frame = rendered;\n\n const hostApi: SandboxHostApi = {\n setHeight: (height) => {\n if (\n typeof height === \"number\" &&\n Number.isFinite(height) &&\n height > 0\n ) {\n setContentHeight(height);\n }\n },\n };\n\n bridge = liveRef.current.createBridge(\n {\n iframe: rendered.iframe,\n origin: rendered.origin,\n sendMessage: rendered.sendMessage,\n },\n hostApi,\n );\n\n // Single owner of the window listener; the cross-origin guard runs\n // here so the bridge only sees frame-validated messages.\n onMessage = (event) => {\n if (!isSandboxFrameMessage(event, rendered)) return;\n bridge?.onMessage(event);\n };\n window.addEventListener(\"message\", onMessage);\n\n // renderHtml resolves at iframe load, which a shim that was never\n // served also reaches, so a completed render is only known once the\n // frame says so. render-timeout is excluded because the shim is\n // running and the guest may still paint, and reporting it would leave\n // a host that renders an error state showing one over a frame that\n // recovers.\n rendered.fullyLoadedPromiseWithTimeout(LOAD_TIMEOUT_MS).catch((err) => {\n if (cancelled) return;\n if (isShimLoadError(err) && err.code === \"render-timeout\") return;\n reportError(err);\n });\n })\n .catch((err) => {\n if (cancelled) return;\n frame?.dispose();\n frame = null;\n reportError(err);\n });\n\n return () => {\n cancelled = true;\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n if (onMessage) {\n const listener = onMessage;\n onMessage = null;\n runCleanup(() => window.removeEventListener(\"message\", listener));\n }\n const bridgeToDispose = bridge;\n bridge = null;\n if (bridgeToDispose) runCleanup(() => bridgeToDispose.dispose());\n runCleanup(() => renderController.abort());\n const frameToDispose = frame;\n frame = null;\n if (frameToDispose) runCleanup(() => frameToDispose.dispose());\n runCleanup(() => setContentHeight(undefined));\n\n if (cleanupFailed) throw cleanupError;\n };\n // oxlint-disable-next-line react/exhaustive-deps -- re-init only on contentKey change; live values flow through liveRef\n }, [contentKey]);\n\n const resolvedHeight =\n contentHeight != null ? Math.min(contentHeight, maxHeight) : undefined;\n const mergedStyle =\n resolvedHeight != null\n ? { ...sandbox?.style, height: resolvedHeight }\n : sandbox?.style;\n\n return (\n <div\n {...containerProps}\n ref={containerRef}\n className={sandbox?.className}\n style={mergedStyle}\n />\n );\n}\n"],"mappings":";;;;;;;AAiBA,MAAMY,kBAAkB;AACxB,MAAMC,qBAAqB;AAC3B,MAAMC,kBAAkB;AA0CxB,SAAgBkC,sBACdjB,OACAU,OACS;CACT,OACEV,MAAMqB,WAAWX,MAAMQ,OAAOI,iBAA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IAE5C,IAAIwC,eAAe,MAAMC;GAAa;EACvC;EAEF3C,EAAA,MAAAW;CAAA,OAAAA,KAAAX,EAAA;CAAA,IAAA8C;CAAA,IAAA9C,EAAA,QAAAnB,YAAA;EAAEiE,KAAA,CAACjE,UAAU;EAACmB,EAAA,MAAAnB;EAAAmB,EAAA,MAAA8C;CAAA,OAAAA,KAAA9C,EAAA;CAjIftD,UAAUiE,IAiIPmC,EAAY;CAEf,MAAAO,iBACEjD,iBAAiB,OAAOkD,KAAIC,IAAKnD,eAAetB,SAAqB,IAArEoB,KAAAA;CAAuE,IAAAsD;CAAA,IAAAxD,EAAA,QAAAqD,kBAAArD,EAAA,QAAAzC,SAAAM,OAAA;EAEvE2F,KAAAH,kBAAkB,OAAlB;GAAA,GACS9F,SAAOM;GAAOM,QAAUkF;EAChB,IAAb9F,SAAOM;EAAOmC,EAAA,MAAAqD;EAAArD,EAAA,MAAAzC,SAAAM;EAAAmC,EAAA,MAAAwD;CAAA,OAAAA,KAAAxD,EAAA;CAHpB,MAAAyD,cACED;CAQa,MAAAE,KAAAnG,SAAOK;CAAW,IAAA+F;CAAA,IAAA3D,EAAA,QAAAX,kBAAAW,EAAA,QAAAyD,eAAAzD,EAAA,QAAA0D,IAAA;EAH/BC,KAAA,oBAAA,OAAA;GAKE,GAJItE;GACCc,KAAAA;GACM,WAAAuD;GACJD,OAAAA;EAAW,CAAA;EAClBzD,EAAA,MAAAX;EAAAW,EAAA,MAAAyD;EAAAzD,EAAA,MAAA0D;EAAA1D,EAAA,MAAA2D;CAAA,OAAAA,KAAA3D,EAAA;CAAA,OALF2D;AAKE"}
|
|
1
|
+
{"version":3,"file":"SandboxHost.js","names":["c","_c","CSSProperties","useEffect","useRef","useState","useIsomorphicLayoutEffect","isShimLoadError","RenderedFrame","SafeContentFrame","SandboxOption","invokeUserCallback","DEFAULT_PRODUCT","DEFAULT_MAX_HEIGHT","LOAD_TIMEOUT_MS","SandboxHostConfig","sandbox","useShadowDom","enableBrowserCaching","salt","product","className","style","unsafeDocumentWrite","SandboxHostFrame","Pick","SandboxHostApi","setHeight","height","SandboxBridge","onMessage","event","MessageEvent","dispose","SandboxContent","html","SandboxHostProps","content","contentKey","maxHeight","createBridge","frame","host","onError","error","Error","containerProps","Record","isSandboxFrameMessage","iframe","HTMLIFrameElement","origin","source","contentWindow","LiveSnapshot","SandboxHost","t0","$","t1","undefined","containerRef","contentHeight","setContentHeight","t2","liveRef","t3","t4","current","t5","Symbol","for","container","cancelled","bridge","renderController","AbortController","liveContent","sb","reportError","err","String","bind","scf","renderOpts","signal","renderHtml","then","rendered","hostApi","Number","isFinite","sendMessage","window","addEventListener","fullyLoadedPromiseWithTimeout","catch","err_0","code","err_1","cleanupFailed","cleanupError","runCleanup","cleanup","t6","console","listener","removeEventListener","bridgeToDispose","abort","frameToDispose","resolvedHeight","Math","min","t7","mergedStyle","t8","t9","_c"],"sources":["../../src/sandbox-host/SandboxHost.tsx"],"sourcesContent":["\"use client\";\n\nimport { type CSSProperties, useEffect, useRef, useState } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../utils/useIsomorphicLayoutEffect\";\nimport {\n isShimLoadError,\n type RenderedFrame,\n SafeContentFrame,\n type SandboxOption,\n} from \"safe-content-frame\";\nimport { invokeUserCallback } from \"@assistant-ui/core/internal\";\n\nconst DEFAULT_PRODUCT = \"assistant-ui-sandbox\";\nconst DEFAULT_MAX_HEIGHT = 800;\nconst LOAD_TIMEOUT_MS = 10_000;\n\nexport type SandboxHostConfig = {\n sandbox?: SandboxOption[];\n useShadowDom?: boolean;\n enableBrowserCaching?: boolean;\n salt?: string;\n product?: string;\n className?: string;\n style?: CSSProperties;\n unsafeDocumentWrite?: boolean;\n};\n\nexport type SandboxHostFrame = Pick<\n RenderedFrame,\n \"iframe\" | \"origin\" | \"sendMessage\"\n>;\n\nexport type SandboxHostApi = {\n setHeight: (height: number) => void;\n};\n\nexport type SandboxBridge = {\n onMessage: (event: MessageEvent) => void;\n dispose: () => void;\n};\n\nexport type SandboxContent = { html: string };\n\nexport type SandboxHostProps = {\n content: SandboxContent;\n contentKey: string;\n sandbox?: SandboxHostConfig | undefined;\n maxHeight?: number | undefined;\n createBridge: (\n frame: SandboxHostFrame,\n host: SandboxHostApi,\n ) => SandboxBridge;\n onError?: ((error: Error) => void) | undefined;\n containerProps?: Record<string, string | undefined> | undefined;\n};\n\nexport function isSandboxFrameMessage(\n event: MessageEvent,\n frame: { iframe: HTMLIFrameElement; origin: string },\n): boolean {\n return (\n event.source === frame.iframe.contentWindow && event.origin === frame.origin\n );\n}\n\ntype LiveSnapshot = {\n content: SandboxContent;\n sandbox: SandboxHostConfig | undefined;\n createBridge: SandboxHostProps[\"createBridge\"];\n onError: SandboxHostProps[\"onError\"];\n};\n\nexport function SandboxHost({\n content,\n contentKey,\n sandbox,\n maxHeight = DEFAULT_MAX_HEIGHT,\n createBridge,\n onError,\n containerProps,\n}: SandboxHostProps) {\n const containerRef = useRef<HTMLDivElement>(null);\n const [contentHeight, setContentHeight] = useState<number | undefined>(\n undefined,\n );\n\n const liveRef = useRef<LiveSnapshot>({\n content,\n sandbox,\n createBridge,\n onError,\n });\n useIsomorphicLayoutEffect(() => {\n liveRef.current = { content, sandbox, createBridge, onError };\n }, [content, sandbox, createBridge, onError]);\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container) return;\n\n let cancelled = false;\n let frame: RenderedFrame | null = null;\n let bridge: SandboxBridge | null = null;\n let onMessage: ((event: MessageEvent) => void) | null = null;\n const renderController = new AbortController();\n\n const { content: liveContent, sandbox: sb } = liveRef.current;\n\n const reportError = (err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n invokeUserCallback(\n \"assistant-ui\",\n \"SandboxHost onError\",\n liveRef.current.onError?.bind(liveRef.current),\n error,\n );\n };\n\n const scf = new SafeContentFrame(sb?.product ?? DEFAULT_PRODUCT, {\n ...(sb?.sandbox !== undefined && { sandbox: sb.sandbox }),\n ...(sb?.useShadowDom !== undefined && { useShadowDom: sb.useShadowDom }),\n ...(sb?.enableBrowserCaching !== undefined && {\n enableBrowserCaching: sb.enableBrowserCaching,\n }),\n ...(sb?.salt !== undefined && { salt: sb.salt }),\n });\n\n const renderOpts = {\n signal: renderController.signal,\n ...(sb?.unsafeDocumentWrite !== undefined && {\n unsafeDocumentWrite: sb.unsafeDocumentWrite,\n }),\n };\n\n scf\n .renderHtml(liveContent.html, container, renderOpts)\n .then((rendered) => {\n if (cancelled) {\n rendered.dispose();\n return;\n }\n frame = rendered;\n\n const hostApi: SandboxHostApi = {\n setHeight: (height) => {\n if (\n typeof height === \"number\" &&\n Number.isFinite(height) &&\n height > 0\n ) {\n setContentHeight(height);\n }\n },\n };\n\n bridge = liveRef.current.createBridge(\n {\n iframe: rendered.iframe,\n origin: rendered.origin,\n sendMessage: rendered.sendMessage,\n },\n hostApi,\n );\n\n // Single owner of the window listener; the cross-origin guard runs\n // here so the bridge only sees frame-validated messages.\n onMessage = (event) => {\n if (!isSandboxFrameMessage(event, rendered)) return;\n bridge?.onMessage(event);\n };\n window.addEventListener(\"message\", onMessage);\n\n // renderHtml resolves at iframe load, which a shim that was never\n // served also reaches, so a completed render is only known once the\n // frame says so. render-timeout is excluded because the shim is\n // running and the guest may still paint, and reporting it would leave\n // a host that renders an error state showing one over a frame that\n // recovers.\n rendered.fullyLoadedPromiseWithTimeout(LOAD_TIMEOUT_MS).catch((err) => {\n if (cancelled) return;\n if (isShimLoadError(err) && err.code === \"render-timeout\") return;\n reportError(err);\n });\n })\n .catch((err) => {\n if (cancelled) return;\n frame?.dispose();\n frame = null;\n reportError(err);\n });\n\n return () => {\n cancelled = true;\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n if (onMessage) {\n const listener = onMessage;\n onMessage = null;\n runCleanup(() => window.removeEventListener(\"message\", listener));\n }\n const bridgeToDispose = bridge;\n bridge = null;\n if (bridgeToDispose) runCleanup(() => bridgeToDispose.dispose());\n runCleanup(() => renderController.abort());\n const frameToDispose = frame;\n frame = null;\n if (frameToDispose) runCleanup(() => frameToDispose.dispose());\n runCleanup(() => setContentHeight(undefined));\n\n if (cleanupFailed) throw cleanupError;\n };\n // oxlint-disable-next-line react/exhaustive-deps -- re-init only on contentKey change; live values flow through liveRef\n }, [contentKey]);\n\n const resolvedHeight =\n contentHeight != null ? Math.min(contentHeight, maxHeight) : undefined;\n const mergedStyle =\n resolvedHeight != null\n ? { ...sandbox?.style, height: resolvedHeight }\n : sandbox?.style;\n\n return (\n <div\n {...containerProps}\n ref={containerRef}\n className={sandbox?.className}\n style={mergedStyle}\n />\n );\n}\n"],"mappings":";;;;;;;;AAYA,MAAMY,kBAAkB;AACxB,MAAMC,qBAAqB;AAC3B,MAAMC,kBAAkB;AA0CxB,SAAgBkC,sBACdjB,OACAU,OACS;CACT,OACEV,MAAMqB,WAAWX,MAAMQ,OAAOI,iBAAiBtB,MAAMoB,WAAWV,MAAMU;AAE1E;AASA,SAAOI,YAAAC,IAAA;CAAA,MAAAC,IAAAxD,EAAA,EAAA;CAAqB,MAAA,EAAAoC,SAAAC,YAAAtB,SAAAuB,WAAAmB,IAAAlB,cAAAG,SAAAG,mBAAAU;CAI1B,MAAAjB,YAAAmB,OAAAC,KAAAA,IAAA9C,qBAAA6C;CAKA,MAAAE,eAAqBxD,OAAuB,IAAI;CAChD,MAAA,CAAAyD,eAAAC,oBAA0CzD,SACxCsD,KAAAA,CACF;CAAE,IAAAI;CAAA,IAAAN,EAAA,OAAApB,WAAAoB,EAAA,OAAAjB,gBAAAiB,EAAA,OAAAd,WAAAc,EAAA,OAAAzC,SAAA;EAEmC+C,KAAA;GAAA1B;GAAArB;GAAAwB;GAAAG;EAKrC;EAACc,EAAA,KAAApB;EAAAoB,EAAA,KAAAjB;EAAAiB,EAAA,KAAAd;EAAAc,EAAA,KAAAzC;EAAAyC,E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,MAAAwD;CAAA,OAAAA,KAAAxD,EAAA;CAHpB,MAAAyD,cACED;CAQa,MAAAE,KAAAnG,SAAOK;CAAW,IAAA+F;CAAA,IAAA3D,EAAA,QAAAX,kBAAAW,EAAA,QAAAyD,eAAAzD,EAAA,QAAA0D,IAAA;EAH/BC,KAAA,oBAAA,OAAA;GAKE,GAJItE;GACCc,KAAAA;GACM,WAAAuD;GACJD,OAAAA;EAAW,CAAA;EAClBzD,EAAA,MAAAX;EAAAW,EAAA,MAAAyD;EAAAzD,EAAA,MAAA0D;EAAA1D,EAAA,MAAA2D;CAAA,OAAAA,KAAA3D,EAAA;CAAA,OALF2D;AAKE"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ComposerSendOptions } from "@assistant-ui/core/store";
|
|
2
2
|
import { type TriggerPopoverAriaProps } from "../primitives/composer/useComposerInputState.js";
|
|
3
|
+
/** @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release. */
|
|
3
4
|
export type Unstable_UseComposerInputOptions = {
|
|
4
5
|
/**
|
|
5
6
|
* Disables the input in addition to the composer's own disabled sources
|
|
@@ -8,6 +9,7 @@ export type Unstable_UseComposerInputOptions = {
|
|
|
8
9
|
*/
|
|
9
10
|
disabled?: boolean | undefined;
|
|
10
11
|
};
|
|
12
|
+
/** @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release. */
|
|
11
13
|
export type Unstable_ComposerInput = {
|
|
12
14
|
/** Current composer text, or `""` when the composer is not editing. */
|
|
13
15
|
value: string;
|
|
@@ -35,8 +37,6 @@ export type Unstable_ComposerInput = {
|
|
|
35
37
|
canSend: boolean;
|
|
36
38
|
};
|
|
37
39
|
/**
|
|
38
|
-
* @deprecated Under active development and might change without notice.
|
|
39
|
-
*
|
|
40
40
|
* Headless bridge to the composer's text value and send action, for building a
|
|
41
41
|
* custom composer input without `ComposerPrimitive.Input`. It is a thin bridge,
|
|
42
42
|
* not a second input: it does not own keyboard behavior, autosize, IME or
|
|
@@ -44,6 +44,8 @@ export type Unstable_ComposerInput = {
|
|
|
44
44
|
* state. Spread `unstable_useTriggerPopoverAriaProps()` onto your element for
|
|
45
45
|
* trigger-popover combobox semantics.
|
|
46
46
|
*
|
|
47
|
+
* @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release.
|
|
48
|
+
*
|
|
47
49
|
* @example
|
|
48
50
|
* ```tsx
|
|
49
51
|
* const { value, setText, send, isDisabled, canSend } = unstable_useComposerInput();
|
|
@@ -52,6 +54,8 @@ export type Unstable_ComposerInput = {
|
|
|
52
54
|
* disabled={isDisabled}
|
|
53
55
|
* onChange={(e) => setText(e.target.value)}
|
|
54
56
|
* onKeyDown={(e) => {
|
|
57
|
+
* if (e.nativeEvent.isComposing || e.keyCode === 229) return;
|
|
58
|
+
*
|
|
55
59
|
* if (e.key === "Enter" && !e.shiftKey && canSend) {
|
|
56
60
|
* e.preventDefault();
|
|
57
61
|
* send();
|
|
@@ -61,16 +65,17 @@ export type Unstable_ComposerInput = {
|
|
|
61
65
|
* ```
|
|
62
66
|
*/
|
|
63
67
|
export declare function unstable_useComposerInput(options?: Unstable_UseComposerInputOptions): Unstable_ComposerInput;
|
|
68
|
+
/** @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release. */
|
|
64
69
|
export type Unstable_TriggerPopoverAriaProps = TriggerPopoverAriaProps;
|
|
65
70
|
/**
|
|
66
|
-
* @deprecated Under active development and might change without notice.
|
|
67
|
-
*
|
|
68
71
|
* ARIA combobox attributes for the focused element (typically the composer
|
|
69
72
|
* input) describing the open trigger popover, per the WAI-ARIA editable
|
|
70
73
|
* combobox pattern. Returns an empty object outside a `TriggerPopoverRoot` or
|
|
71
74
|
* when no popover is open. Spread these last so they take precedence over any
|
|
72
75
|
* matching ARIA props you set yourself, mirroring `ComposerPrimitive.Input`.
|
|
73
76
|
*
|
|
77
|
+
* @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release.
|
|
78
|
+
*
|
|
74
79
|
* @example
|
|
75
80
|
* ```tsx
|
|
76
81
|
* const aria = unstable_useTriggerPopoverAriaProps();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useComposerInput.d.ts","sourceRoot":"","sources":["../../src/unstable/useComposerInput.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EACL,KAAK,uBAAuB,EAI7B,wDAAqD;AAEtD,MAAM,MAAM,gCAAgC,GAAG;IAC7C;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CAChC,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,uEAAuE;IACvE,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,IAAI,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC1C;;;OAGG;IACH,UAAU,EAAE,OAAO,CAAC;IACpB;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF
|
|
1
|
+
{"version":3,"file":"useComposerInput.d.ts","sourceRoot":"","sources":["../../src/unstable/useComposerInput.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AACpE,OAAO,EACL,KAAK,uBAAuB,EAI7B,wDAAqD;AAEtD,+GAA+G;AAC/G,MAAM,MAAM,gCAAgC,GAAG;IAC7C;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CAChC,CAAC;AAEF,+GAA+G;AAC/G,MAAM,MAAM,sBAAsB,GAAG;IACnC,uEAAuE;IACvE,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,IAAI,CAAC,OAAO,CAAC,EAAE,mBAAmB,GAAG,IAAI,CAAC;IAC1C;;;OAGG;IACH,UAAU,EAAE,OAAO,CAAC;IACpB;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,CAAC,EAAE,gCAAgC,GACzC,sBAAsB,CA0BxB;AAED,+GAA+G;AAC/G,MAAM,MAAM,gCAAgC,GAAG,uBAAuB,CAAC;AAEvE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mCAAmC,IAAI,gCAAgC,CAEtF"}
|
|
@@ -6,8 +6,6 @@ import { useAui } from "@assistant-ui/store";
|
|
|
6
6
|
import { flushTapSync } from "@assistant-ui/tap";
|
|
7
7
|
//#region src/unstable/useComposerInput.ts
|
|
8
8
|
/**
|
|
9
|
-
* @deprecated Under active development and might change without notice.
|
|
10
|
-
*
|
|
11
9
|
* Headless bridge to the composer's text value and send action, for building a
|
|
12
10
|
* custom composer input without `ComposerPrimitive.Input`. It is a thin bridge,
|
|
13
11
|
* not a second input: it does not own keyboard behavior, autosize, IME or
|
|
@@ -15,6 +13,8 @@ import { flushTapSync } from "@assistant-ui/tap";
|
|
|
15
13
|
* state. Spread `unstable_useTriggerPopoverAriaProps()` onto your element for
|
|
16
14
|
* trigger-popover combobox semantics.
|
|
17
15
|
*
|
|
16
|
+
* @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release.
|
|
17
|
+
*
|
|
18
18
|
* @example
|
|
19
19
|
* ```tsx
|
|
20
20
|
* const { value, setText, send, isDisabled, canSend } = unstable_useComposerInput();
|
|
@@ -23,6 +23,8 @@ import { flushTapSync } from "@assistant-ui/tap";
|
|
|
23
23
|
* disabled={isDisabled}
|
|
24
24
|
* onChange={(e) => setText(e.target.value)}
|
|
25
25
|
* onKeyDown={(e) => {
|
|
26
|
+
* if (e.nativeEvent.isComposing || e.keyCode === 229) return;
|
|
27
|
+
*
|
|
26
28
|
* if (e.key === "Enter" && !e.shiftKey && canSend) {
|
|
27
29
|
* e.preventDefault();
|
|
28
30
|
* send();
|
|
@@ -55,14 +57,14 @@ function unstable_useComposerInput(options) {
|
|
|
55
57
|
};
|
|
56
58
|
}
|
|
57
59
|
/**
|
|
58
|
-
* @deprecated Under active development and might change without notice.
|
|
59
|
-
*
|
|
60
60
|
* ARIA combobox attributes for the focused element (typically the composer
|
|
61
61
|
* input) describing the open trigger popover, per the WAI-ARIA editable
|
|
62
62
|
* combobox pattern. Returns an empty object outside a `TriggerPopoverRoot` or
|
|
63
63
|
* when no popover is open. Spread these last so they take precedence over any
|
|
64
64
|
* matching ARIA props you set yourself, mirroring `ComposerPrimitive.Input`.
|
|
65
65
|
*
|
|
66
|
+
* @deprecated Experimental since 2026-06-23. Not scheduled for removal; the API may change in any release.
|
|
67
|
+
*
|
|
66
68
|
* @example
|
|
67
69
|
* ```tsx
|
|
68
70
|
* const aria = unstable_useTriggerPopoverAriaProps();
|