@dbx-tools/ui-mastra 0.9.184 → 0.9.185

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/index.react.ts CHANGED
@@ -60,4 +60,3 @@ export type { ToolInputPresentation, WebSearchProgressGroup } from "./src/react/
60
60
  export { isActiveChatStatus, isRespondingChatStatus } from "./src/react/types.ts";
61
61
  export type { ChatStatus, ToolEvent, ToolProgress, ChatModelOption, ChatInputMessage, QueuedSteer, FeedbackValue, FeedbackSubmission, MessageFeedback, ThreadSummary, ThreadPlacement, ChatViewProps, ApprovalDecision, PendingApproval } from "./src/react/types.ts";
62
62
  export { useChatThreadQuery } from "./src/react/use-chat-thread-query.ts";
63
- export { CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT, useComposerViewportLock } from "./src/react/use-composer-viewport-lock.ts";
package/index.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  // Hand edits are overwritten on the next watch; this file is read-only.
4
4
 
5
5
  export const PACKAGE_IDENTIFIER = "@dbx-tools/ui-mastra";
6
- export const PACKAGE_VERSION = "0.9.184";
6
+ export const PACKAGE_VERSION = "0.9.185";
package/package.json CHANGED
@@ -32,12 +32,12 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@databricks/appkit-ui": "0.81.0",
35
- "@dbx-tools/shared-auth": "^0.9.184",
36
- "@dbx-tools/shared-core": "^0.9.184",
37
- "@dbx-tools/shared-genie": "^0.9.184",
38
- "@dbx-tools/shared-mastra": "^0.9.184",
39
- "@dbx-tools/shared-model": "^0.9.184",
40
- "@dbx-tools/ui": "^0.9.184",
35
+ "@dbx-tools/shared-auth": "^0.9.185",
36
+ "@dbx-tools/shared-core": "^0.9.185",
37
+ "@dbx-tools/shared-genie": "^0.9.185",
38
+ "@dbx-tools/shared-mastra": "^0.9.185",
39
+ "@dbx-tools/shared-model": "^0.9.185",
40
+ "@dbx-tools/ui": "^0.9.185",
41
41
  "@mastra/client-js": "1.50.0",
42
42
  "@mastra/core": "1.71.0",
43
43
  "@tanstack/react-table": "^8.21.3",
@@ -46,7 +46,6 @@
46
46
  "echarts-for-react": "^3.0.2",
47
47
  "lucide-react": "^0.554.0",
48
48
  "marked": "^18.0.5",
49
- "scrollbooster": "4.0.0",
50
49
  "sql-formatter": "^15.6.9",
51
50
  "streamdown": "^2.5.0",
52
51
  "zod": "4.3.6"
@@ -56,7 +55,7 @@
56
55
  "publishConfig": {
57
56
  "access": "public"
58
57
  },
59
- "version": "0.9.184",
58
+ "version": "0.9.185",
60
59
  "types": "index.ts",
61
60
  "dbxToolsConfig": {
62
61
  "tags": [
@@ -11,7 +11,6 @@ import React, { useEffect, useRef, useState } from "react";
11
11
  import { ThreadSidebar, type ThreadSidebarProps } from "./thread-sidebar.tsx";
12
12
  import { ThreadTabs } from "./thread-tabs.tsx";
13
13
  import type { ChatViewProps } from "./types.ts";
14
- import { useComposerViewportLock } from "./use-composer-viewport-lock.ts";
15
14
  import { closeThreadTab, nextActiveThreadTab, syncThreadTabs } from "../support/thread-tabs.ts";
16
15
 
17
16
  const SIDE_PANEL_MIN_WIDTH_PX = 768;
@@ -112,7 +111,6 @@ export const ChatThreadLayout = ({
112
111
  onToggleSidebar,
113
112
  }: ChatThreadLayoutProps) => {
114
113
  const rootRef = useRef<HTMLDivElement>(null);
115
- useComposerViewportLock(rootRef);
116
114
  const isNarrow = useIsNarrow(rootRef);
117
115
  const showThreads = Boolean(threads && onSelectThread) && threadPlacement !== "disabled";
118
116
  const placement = threadPlacement === "auto" ? (isNarrow ? "top" : "left") : threadPlacement;
@@ -14,11 +14,11 @@ import { errorMessage } from "@dbx-tools/shared-core";
14
14
  import { isToolUIPart } from "ai";
15
15
  import { ArrowDownIcon, MessageSquareIcon, RefreshCwIcon, TriangleAlertIcon } from "lucide-react";
16
16
  import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
17
+ import { flushSync } from "react-dom";
17
18
  import { AssistantBubble, UserBubble } from "./bubbles.tsx";
18
19
  import { messageFeedbackDestination, mlflowTraceUrl } from "./chat-feedback.ts";
19
20
  import { SuggestionPills } from "./suggestion-pills.tsx";
20
21
  import { isActiveChatStatus, type ChatViewProps, type ToolEvent } from "./types.ts";
21
- import { CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT } from "./use-composer-viewport-lock.ts";
22
22
  import { messageText } from "../support/export.ts";
23
23
 
24
24
  const BOTTOM_THRESHOLD_PX = 24;
@@ -233,7 +233,9 @@ export const useChatTranscriptController = ({
233
233
 
234
234
  const scrollToBottomNow = useCallback(() => {
235
235
  pinnedRef.current = true;
236
- setIsAtBottom(true);
236
+ // Native Mobile Safari touch listeners run outside React's delegated event path. Commit the
237
+ // hidden state before mutating scrollTop so the control disappears before the transcript jumps.
238
+ flushSync(() => setIsAtBottom(true));
237
239
  pinToBottomNow();
238
240
  }, [pinToBottomNow]);
239
241
 
@@ -317,10 +319,9 @@ export const ChatTranscript = ({
317
319
  if (scrollToBottomOverflowRef.current === null) {
318
320
  scrollToBottomOverflowRef.current = transcript.style.overflowY;
319
321
  }
320
- transcript.dispatchEvent(new Event(CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT));
321
322
 
322
- // Hiding overflow cancels WebKit's native momentum immediately. The second assignment on the
323
- // next frame keeps the transcript pinned after its normal scroll range has been restored.
323
+ // WebKit has no public API for stopping an overflow scroller's momentum. Briefly removing
324
+ // overflow terminates that momentum; restoring it one frame later keeps normal scrolling native.
324
325
  transcript.style.overflowY = "hidden";
325
326
  controller.scrollToBottomNow();
326
327
  if (scrollToBottomFrameRef.current !== null) {
@@ -338,9 +339,8 @@ export const ChatTranscript = ({
338
339
  const button = scrollToBottomButtonRef.current;
339
340
  if (!button) return;
340
341
 
341
- // React delegates touch events through a passive document listener in Mobile Safari. Native
342
- // non-passive listeners are required here so the button can scroll without transferring focus
343
- // away from the composer and closing the keyboard.
342
+ // React's delegated touch listener may be passive in Mobile Safari. These button-local,
343
+ // non-passive listeners prevent focus transfer without changing transcript gesture handling.
344
344
  const handlePointerDown = (event: PointerEvent) => {
345
345
  event.preventDefault();
346
346
  };
@@ -369,7 +369,7 @@ export const ChatTranscript = ({
369
369
  button.removeEventListener("touchstart", handleTouchStart);
370
370
  button.removeEventListener("touchend", handleTouchEnd);
371
371
  };
372
- }, [activateScrollToBottomFromTouch]);
372
+ }, [activateScrollToBottomFromTouch, controller.scrollRef]);
373
373
 
374
374
  return (
375
375
  <div className="relative flex min-w-0 max-w-full flex-1 flex-col overflow-hidden">
@@ -505,13 +505,7 @@ export const ChatTranscript = ({
505
505
  )}
506
506
  </div>
507
507
  </div>
508
- <div
509
- data-slot="aui_thread-scroll-indicator"
510
- className="pointer-events-none absolute right-0.5 top-0 z-20 w-0.5 rounded-full bg-foreground/50"
511
- hidden
512
- aria-hidden="true"
513
- />
514
- <div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 mx-auto flex w-full max-w-4xl justify-end px-4 md:px-6">
508
+ <div className="pointer-events-none absolute inset-x-0 bottom-4 z-20 mx-auto flex w-full max-w-4xl justify-center px-4 md:px-6">
515
509
  <Button
516
510
  ref={scrollToBottomButtonRef}
517
511
  type="button"
@@ -586,6 +586,20 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
586
586
  // `driveStream` (which invokes this) - the ref breaks that cycle without a
587
587
  // stale-closure hazard (assigned each render, same pattern as `loadMoreRef`).
588
588
  const drainQueueRef = useRef<(threadId: string) => void>(() => {});
589
+ const streamSettlementsRef = useRef(new Map<string, Promise<void>>());
590
+ const adoptedThreadIdsRef = useRef(new Map<string, string>());
591
+
592
+ const resolveThreadId = useCallback((threadId: string): string => {
593
+ let resolved = threadId;
594
+ const visited = new Set<string>();
595
+ while (!visited.has(resolved)) {
596
+ visited.add(resolved);
597
+ const next = adoptedThreadIdsRef.current.get(resolved);
598
+ if (!next) break;
599
+ resolved = next;
600
+ }
601
+ return resolved;
602
+ }, []);
589
603
 
590
604
  const activeThreadIdRef = useRef(activeThreadId);
591
605
  activeThreadIdRef.current = activeThreadId;
@@ -594,6 +608,12 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
594
608
  // switch to it when it is still the active thread.
595
609
  const adoptThreadId = useCallback(
596
610
  (localId: string, assignedId: string) => {
611
+ adoptedThreadIdsRef.current.set(localId, assignedId);
612
+ const settlement = streamSettlementsRef.current.get(localId);
613
+ if (settlement) {
614
+ streamSettlementsRef.current.delete(localId);
615
+ streamSettlementsRef.current.set(assignedId, settlement);
616
+ }
597
617
  moveSession(localId, assignedId);
598
618
  localThreadIdsRef.current.delete(localId);
599
619
  localThreadIdsRef.current.add(assignedId);
@@ -844,7 +864,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
844
864
  const streamThreadId = threadId === DEFAULT_THREAD_SESSION_KEY ? undefined : threadId;
845
865
  const model = modelRef.current || undefined;
846
866
  const turnReasoningEffort = reasoningEffortRef.current;
847
- return driveStream(threadId, assistantId, (signal) => {
867
+ const settlement = driveStream(threadId, assistantId, (signal) => {
848
868
  return mastraClient.streamAgent({
849
869
  agentId,
850
870
  messages: turnMessages,
@@ -856,6 +876,14 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
856
876
  signal,
857
877
  });
858
878
  });
879
+ streamSettlementsRef.current.set(threadId, settlement);
880
+ const clearSettlement = () => {
881
+ for (const [settlementThreadId, current] of streamSettlementsRef.current) {
882
+ if (current === settlement) streamSettlementsRef.current.delete(settlementThreadId);
883
+ }
884
+ };
885
+ void settlement.then(clearSettlement, clearSettlement);
886
+ return settlement;
859
887
  },
860
888
  [activeRunsKey, driveStream, mastraClient, agentId, updateSession],
861
889
  );
@@ -995,9 +1023,14 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
995
1023
  async (threadId: string): Promise<void> => {
996
1024
  const current = getSession(threadId);
997
1025
  if (!isSessionRunning(current)) return;
1026
+ const localSettlement = streamSettlementsRef.current.get(threadId);
998
1027
  const streamThreadId = threadId === DEFAULT_THREAD_SESSION_KEY ? undefined : threadId;
999
1028
  const runId = current.runId;
1000
1029
  const settlementSignal = AbortSignal.timeout(STEER_INTERRUPT_SETTLEMENT_TIMEOUT_MS);
1030
+ const settlementTimeout = new Promise<void>((resolve) => {
1031
+ if (settlementSignal.aborted) resolve();
1032
+ else settlementSignal.addEventListener("abort", () => resolve(), { once: true });
1033
+ });
1001
1034
  const settlement =
1002
1035
  mastraClient.backgroundTurns && runId
1003
1036
  ? mastraClient
@@ -1048,6 +1081,7 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1048
1081
  });
1049
1082
  await serverAbort;
1050
1083
  await settlement;
1084
+ if (localSettlement) await Promise.race([localSettlement, settlementTimeout]);
1051
1085
  },
1052
1086
  [activeRunsKey, agentId, getSession, mastraClient, updateSession],
1053
1087
  );
@@ -1115,10 +1149,10 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1115
1149
  [appendUserMessage, runStream, activeKey, getSession, updateSession],
1116
1150
  );
1117
1151
 
1118
- // Fire a queued steer immediately, out of order: remove it from the queue
1119
- // and append it first so acceptance is visible while the prior durable run
1120
- // settles. `runStream`/`driveStream` then supersede the in-flight run (abort
1121
- // + runToken bump + settle running pills) and send the chosen steer.
1152
+ // Fire a queued steer immediately, out of order. Wait for the interrupted
1153
+ // stream to publish and adopt any server-assigned thread id before appending
1154
+ // the replacement turn; otherwise a new direct Genie conversation can start
1155
+ // under the stale local thread id.
1122
1156
  const sendSteerNow = useCallback(
1123
1157
  (steerId: string) => {
1124
1158
  const threadId = activeKey;
@@ -1130,14 +1164,23 @@ export const useMastraChat = <TValues extends Record<string, unknown> = Record<s
1130
1164
  queuedSteers: removeSteerFromQueue(session.queuedSteers, steerId),
1131
1165
  }));
1132
1166
  logger.info("steer:send-now", { threadId });
1133
- const { message } = appendUserMessage(threadId, steer.text ?? "", steer.files);
1134
- const replacementMessages = interruptedTurnMessages(current.messages, message);
1135
1167
  void (async () => {
1136
1168
  await interruptActiveRun(threadId);
1137
- void runStream(threadId, replacementMessages, steer.requestContext);
1169
+ const replacementThreadId = resolveThreadId(threadId);
1170
+ const { message } = appendUserMessage(replacementThreadId, steer.text ?? "", steer.files);
1171
+ const replacementMessages = interruptedTurnMessages(current.messages, message);
1172
+ void runStream(replacementThreadId, replacementMessages, steer.requestContext);
1138
1173
  })();
1139
1174
  },
1140
- [activeKey, appendUserMessage, getSession, interruptActiveRun, runStream, updateSession],
1175
+ [
1176
+ activeKey,
1177
+ appendUserMessage,
1178
+ getSession,
1179
+ interruptActiveRun,
1180
+ resolveThreadId,
1181
+ runStream,
1182
+ updateSession,
1183
+ ],
1141
1184
  );
1142
1185
 
1143
1186
  // Drop a queued steer without sending it.
package/src/styles.css CHANGED
@@ -20,15 +20,3 @@
20
20
  @import "@dbx-tools/ui/styles.css";
21
21
 
22
22
  @source "./react";
23
-
24
- [data-slot="aui_thread-viewport"][data-keyboard-touch-scroller] {
25
- /* The adjacent custom thumb uses the transcript's keyboard-resized geometry. */
26
- scrollbar-gutter: auto;
27
- scrollbar-width: none;
28
- }
29
-
30
- [data-slot="aui_thread-viewport"][data-keyboard-touch-scroller]::-webkit-scrollbar {
31
- display: none;
32
- width: 0;
33
- height: 0;
34
- }
@@ -38,8 +38,8 @@ export class GenieChatClient extends MastraPluginClient {
38
38
  override readonly threadRename = false;
39
39
  override readonly attachments = false;
40
40
  override readonly followUpSuggestions: "none" | "genie";
41
- /** Thread ids known to be Genie conversations (listed, loaded, or announced). */
42
- readonly #conversations = new Set<string>();
41
+ /** Local and resolved thread ids mapped to their Genie conversation id. */
42
+ readonly #conversationIds = new Map<string, string>();
43
43
  /** Transcript message id to Genie message id, for regenerate cleanup. */
44
44
  readonly #genieMessageIds = new Map<string, string>();
45
45
 
@@ -57,6 +57,17 @@ export class GenieChatClient extends MastraPluginClient {
57
57
  return `${this.basePath}${genieRoutePath(this.alias, ...parts)}`;
58
58
  }
59
59
 
60
+ #rememberConversation(threadId: string | undefined, conversationId: string): void {
61
+ this.#conversationIds.set(conversationId, conversationId);
62
+ if (threadId) this.#conversationIds.set(threadId, conversationId);
63
+ }
64
+
65
+ #forgetConversation(conversationId: string): void {
66
+ for (const [threadId, resolvedId] of this.#conversationIds) {
67
+ if (resolvedId === conversationId) this.#conversationIds.delete(threadId);
68
+ }
69
+ }
70
+
60
71
  async #delete(url: string, signal?: AbortSignal): Promise<void> {
61
72
  const res = await fetch(url, {
62
73
  method: "DELETE",
@@ -79,8 +90,7 @@ export class GenieChatClient extends MastraPluginClient {
79
90
  .map((part) => (part.type === "text" ? part.text : ""))
80
91
  .join("")
81
92
  .trim();
82
- const conversationId =
83
- params.threadId && this.#conversations.has(params.threadId) ? params.threadId : undefined;
93
+ const conversationId = params.threadId ? this.#conversationIds.get(params.threadId) : undefined;
84
94
  const response = await this.uiStream({
85
95
  path: this.#url(MASTRA_ROUTES.chat),
86
96
  chatId: params.threadId ?? params.runId,
@@ -101,7 +111,7 @@ export class GenieChatClient extends MastraPluginClient {
101
111
  const data = GenieConversationPartDataSchema.safeParse(chunk.data);
102
112
  if (data.success) {
103
113
  resolved = data.data.conversationId;
104
- this.#conversations.add(resolved);
114
+ this.#rememberConversation(params.threadId, resolved);
105
115
  if (userMessage && data.data.messageId) {
106
116
  this.#genieMessageIds.set(userMessage.id, data.data.messageId);
107
117
  }
@@ -148,7 +158,7 @@ export class GenieChatClient extends MastraPluginClient {
148
158
  GenieThreadsResponseSchema,
149
159
  options.signal,
150
160
  );
151
- for (const thread of payload.threads) this.#conversations.add(thread.id);
161
+ for (const thread of payload.threads) this.#rememberConversation(thread.id, thread.id);
152
162
  const threads = payload.threads.map((thread) => ({
153
163
  id: thread.id,
154
164
  ...(thread.title ? { title: thread.title } : {}),
@@ -184,7 +194,7 @@ export class GenieChatClient extends MastraPluginClient {
184
194
  options.signal,
185
195
  );
186
196
  messages = await validateUIMessages({ messages: payload.messages });
187
- this.#conversations.add(options.threadId);
197
+ this.#rememberConversation(options.threadId, options.threadId);
188
198
  // History ids already address their Genie message; the delete route
189
199
  // resolves a question id to the message that owns it.
190
200
  for (const message of messages) this.#genieMessageIds.set(message.id, message.id);
@@ -204,9 +214,10 @@ export class GenieChatClient extends MastraPluginClient {
204
214
  threadId: string,
205
215
  options: { signal?: AbortSignal } = {},
206
216
  ): Promise<void> {
207
- if (!this.#conversations.has(threadId)) return;
208
- await this.#delete(this.#url(MASTRA_ROUTES.threads, threadId), options.signal);
209
- this.#conversations.delete(threadId);
217
+ const conversationId = this.#conversationIds.get(threadId);
218
+ if (!conversationId) return;
219
+ await this.#delete(this.#url(MASTRA_ROUTES.threads, conversationId), options.signal);
220
+ this.#forgetConversation(conversationId);
210
221
  }
211
222
 
212
223
  /** Clearing a Genie thread deletes its conversation; the next turn starts a new one. */
@@ -225,7 +236,8 @@ export class GenieChatClient extends MastraPluginClient {
225
236
  messageIds: string[],
226
237
  options: { signal?: AbortSignal } = {},
227
238
  ): Promise<void> {
228
- if (!this.#conversations.has(threadId)) return;
239
+ const conversationId = this.#conversationIds.get(threadId);
240
+ if (!conversationId) return;
229
241
  const genieIds = new Set(
230
242
  messageIds.flatMap((id) => {
231
243
  const genieId = this.#genieMessageIds.get(id);
@@ -234,7 +246,7 @@ export class GenieChatClient extends MastraPluginClient {
234
246
  );
235
247
  for (const genieId of genieIds) {
236
248
  await this.#delete(
237
- this.#url(MASTRA_ROUTES.threads, threadId, MASTRA_ROUTES.messages, genieId),
249
+ this.#url(MASTRA_ROUTES.threads, conversationId, MASTRA_ROUTES.messages, genieId),
238
250
  options.signal,
239
251
  );
240
252
  }
@@ -1,299 +0,0 @@
1
- import { useLayoutEffect, type RefObject } from "react";
2
- import { ScrollBooster } from "scrollbooster";
3
-
4
- const COMPOSER_DOCK_SELECTOR = '[data-slot="aui_composer-dock"]';
5
- const COMPOSER_INPUT_SELECTOR = ".aui-composer-input";
6
- const TRANSCRIPT_SELECTOR = '[data-slot="aui_thread-viewport"]';
7
- const TRANSCRIPT_CONTENT_SELECTOR = '[data-slot="aui_thread-content"]';
8
- const TRANSCRIPT_INDICATOR_SELECTOR = '[data-slot="aui_thread-scroll-indicator"]';
9
-
10
- const SCROLL_BOUNDARY_EPSILON_PX = 1;
11
- const KEYBOARD_GEOMETRY_THRESHOLD_PX = 80;
12
- const FOCUS_GUARD_FALLBACK_MS = 600;
13
- const FOCUS_GUARD_SETTLE_MS = 120;
14
- const MIN_SCROLL_INDICATOR_HEIGHT_PX = 28;
15
-
16
- /** Internal event used by the scroll-to-bottom control to cancel iOS drag momentum first. */
17
- export const CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT = "dbx-tools:cancel-transcript-kinetic-scroll";
18
-
19
- const isIOSWebKit = () => {
20
- const userAgent = window.navigator.userAgent;
21
- return (
22
- /iPad|iPhone|iPod/.test(userAgent) ||
23
- (userAgent.includes("Macintosh") && window.navigator.maxTouchPoints > 1)
24
- );
25
- };
26
-
27
- const isKeyboardVisible = (viewport: VisualViewport | null): boolean =>
28
- Boolean(viewport && window.innerHeight - viewport.height > KEYBOARD_GEOMETRY_THRESHOLD_PX);
29
-
30
- const composerInputFromEvent = (event: Event): HTMLTextAreaElement | null => {
31
- const target = event.target instanceof Element ? event.target : null;
32
- return target?.closest<HTMLTextAreaElement>(COMPOSER_INPUT_SELECTOR) ?? null;
33
- };
34
-
35
- const createTranscriptScroller = (viewport: HTMLElement, content: HTMLElement) =>
36
- new ScrollBooster({
37
- viewport,
38
- content,
39
- direction: "vertical",
40
- pointerMode: "mouse",
41
- scrollMode: "native",
42
- bounce: false,
43
- textSelection: true,
44
- wheel: false,
45
- keyboard: false,
46
- });
47
-
48
- const syncScrollIndicator = (
49
- transcript: HTMLElement,
50
- indicator: HTMLElement | null,
51
- visible: boolean,
52
- ) => {
53
- if (!indicator) return;
54
-
55
- const maxScrollTop = transcript.scrollHeight - transcript.clientHeight;
56
- indicator.hidden = !visible || maxScrollTop <= 0;
57
- if (indicator.hidden) return;
58
-
59
- // Safari paints native overlay scrollbars against stale pre-keyboard geometry. This thumb is
60
- // positioned inside the resized transcript so it always matches the visible scroll region.
61
- const proportionalHeight =
62
- (transcript.clientHeight / transcript.scrollHeight) * transcript.clientHeight;
63
- const height = Math.min(
64
- transcript.clientHeight,
65
- Math.max(MIN_SCROLL_INDICATOR_HEIGHT_PX, Math.round(proportionalHeight)),
66
- );
67
- const scrollTop = Math.min(maxScrollTop, Math.max(0, transcript.scrollTop));
68
- const top = Math.round((scrollTop / maxScrollTop) * (transcript.clientHeight - height));
69
- indicator.style.height = `${height}px`;
70
- indicator.style.transform = `translateY(${top}px)`;
71
- };
72
-
73
- /**
74
- * Contains Mobile Safari keyboard and touch behavior inside the chat frame.
75
- *
76
- * When the host shell follows `visualViewport`, this hook owns the remaining iOS-specific work:
77
- * suppressing Safari's input-reveal pan, routing keyboard-open transcript drags through
78
- * ScrollBooster, stopping existing momentum before composer actions, and drawing the keyboard-safe
79
- * scrollbar thumb.
80
- */
81
- export const useComposerViewportLock = (frameRef: RefObject<HTMLElement | null>) => {
82
- useLayoutEffect(() => {
83
- const frame = frameRef.current;
84
- const dock = frame?.querySelector<HTMLElement>(COMPOSER_DOCK_SELECTOR);
85
- const transcript = frame?.querySelector<HTMLElement>(TRANSCRIPT_SELECTOR);
86
- const transcriptContent = frame?.querySelector<HTMLElement>(TRANSCRIPT_CONTENT_SELECTOR);
87
- const scrollIndicator =
88
- frame?.querySelector<HTMLElement>(TRANSCRIPT_INDICATOR_SELECTOR) ?? null;
89
- if (!frame || !dock || !transcript || !transcriptContent) return;
90
-
91
- const iosWebKit = isIOSWebKit();
92
- let transcriptScroller = iosWebKit
93
- ? createTranscriptScroller(transcript, transcriptContent)
94
- : null;
95
- let transcriptScrollerRestartFrame: number | null = null;
96
- let transcriptTouchRoutingEnabled = false;
97
- let momentumRestoreFrame: number | null = null;
98
- let momentumScrollTop = 0;
99
- let momentumOverflowY: string | null = null;
100
- let lastTouchY: number | null = null;
101
- let focusRevealTimer: number | null = null;
102
- let guardedInput: HTMLTextAreaElement | null = null;
103
- let guardedOpacity = "";
104
- let guardViewportHeight = 0;
105
- let guardViewportTop = 0;
106
-
107
- const syncIndicator = () =>
108
- syncScrollIndicator(transcript, scrollIndicator, transcriptTouchRoutingEnabled);
109
-
110
- const syncKeyboardState = () => {
111
- const keyboardVisible = iosWebKit && isKeyboardVisible(window.visualViewport);
112
- transcript.toggleAttribute("data-keyboard-touch-scroller", keyboardVisible);
113
-
114
- if (keyboardVisible !== transcriptTouchRoutingEnabled) {
115
- transcriptTouchRoutingEnabled = keyboardVisible;
116
- transcriptScroller?.updateOptions({ pointerMode: keyboardVisible ? "touch" : "mouse" });
117
- }
118
- syncIndicator();
119
- };
120
-
121
- const revealGuardedInput = () => {
122
- if (!guardedInput) return;
123
- guardedInput.style.opacity = guardedOpacity;
124
- delete guardedInput.dataset.iosFocusGuard;
125
- guardedInput = null;
126
- focusRevealTimer = null;
127
- guardViewportHeight = 0;
128
- guardViewportTop = 0;
129
- };
130
-
131
- const scheduleGuardReveal = (delay: number) => {
132
- if (focusRevealTimer !== null) window.clearTimeout(focusRevealTimer);
133
- focusRevealTimer = window.setTimeout(revealGuardedInput, delay);
134
- };
135
-
136
- const guardInput = (input: HTMLTextAreaElement) => {
137
- if (guardedInput === input) return;
138
- if (focusRevealTimer !== null) window.clearTimeout(focusRevealTimer);
139
- revealGuardedInput();
140
- guardedInput = input;
141
- guardedOpacity = input.style.opacity;
142
- guardViewportHeight = window.visualViewport?.height ?? window.innerHeight;
143
- guardViewportTop = window.visualViewport?.offsetTop ?? 0;
144
- input.dataset.iosFocusGuard = "true";
145
- input.style.opacity = "0";
146
- };
147
-
148
- const stopNativeTranscriptMomentum = () => {
149
- if (!iosWebKit) return;
150
-
151
- transcriptScroller?.setPosition({ y: transcript.scrollTop });
152
- momentumScrollTop = transcript.scrollTop;
153
- if (momentumOverflowY === null) momentumOverflowY = transcript.style.overflowY;
154
- if (momentumRestoreFrame !== null) window.cancelAnimationFrame(momentumRestoreFrame);
155
-
156
- // WebKit carries an existing inertial transcript gesture through keyboard focus. Removing
157
- // overflow for one frame ends that gesture while preserving the reader's exact position.
158
- transcript.style.overflowY = "hidden";
159
- transcript.scrollTop = momentumScrollTop;
160
- momentumRestoreFrame = window.requestAnimationFrame(() => {
161
- transcript.style.overflowY = momentumOverflowY ?? "";
162
- transcript.scrollTop = momentumScrollTop;
163
- momentumOverflowY = null;
164
- momentumRestoreFrame = null;
165
- });
166
- };
167
-
168
- const restartTranscriptScroller = () => {
169
- if (!iosWebKit) return;
170
- transcriptScroller?.destroy();
171
- transcriptScroller = null;
172
- if (transcriptScrollerRestartFrame !== null) {
173
- window.cancelAnimationFrame(transcriptScrollerRestartFrame);
174
- }
175
-
176
- // Reattach after the current touch sequence and its next paint have completed. Recreating the
177
- // instance during the same dispatch allows ScrollBooster's old kinetic loop to keep running.
178
- transcriptScrollerRestartFrame = window.requestAnimationFrame(() => {
179
- transcriptScrollerRestartFrame = window.requestAnimationFrame(() => {
180
- transcriptScroller = createTranscriptScroller(transcript, transcriptContent);
181
- transcriptScroller.updateOptions({
182
- pointerMode: transcriptTouchRoutingEnabled ? "touch" : "mouse",
183
- });
184
- transcriptScrollerRestartFrame = null;
185
- });
186
- });
187
- };
188
-
189
- const handleInputFocus = (event: FocusEvent) => {
190
- if (!iosWebKit) return;
191
- const input = event.target instanceof HTMLTextAreaElement ? event.target : null;
192
- if (!input?.matches(COMPOSER_INPUT_SELECTOR)) return;
193
- guardInput(input);
194
- scheduleGuardReveal(FOCUS_GUARD_FALLBACK_MS);
195
- };
196
-
197
- const handleInputBlur = (event: FocusEvent) => {
198
- if (event.target === guardedInput) revealGuardedInput();
199
- };
200
-
201
- const handleVisualViewportChange = () => {
202
- syncKeyboardState();
203
- const viewport = window.visualViewport;
204
- if (!guardedInput || !viewport) return;
205
- const heightChanged = guardViewportHeight - viewport.height > KEYBOARD_GEOMETRY_THRESHOLD_PX;
206
- const topChanged =
207
- Math.abs(viewport.offsetTop - guardViewportTop) > KEYBOARD_GEOMETRY_THRESHOLD_PX;
208
- if (!heightChanged && !topChanged) return;
209
-
210
- // Restore only after WebKit has started the keyboard transition and the host shell has
211
- // resized. Restoring earlier makes the visible textarea eligible for another reveal pan.
212
- scheduleGuardReveal(FOCUS_GUARD_SETTLE_MS);
213
- };
214
-
215
- const handleTouchStart = (event: TouchEvent) => {
216
- const input = composerInputFromEvent(event);
217
- if (input && iosWebKit) {
218
- // This must run before the native focus default action. Focus events can arrive after Safari
219
- // has already selected and centered its reveal target.
220
- guardInput(input);
221
- scheduleGuardReveal(FOCUS_GUARD_FALLBACK_MS);
222
- }
223
- lastTouchY = event.touches[0]?.clientY ?? null;
224
- stopNativeTranscriptMomentum();
225
- };
226
-
227
- const handleTouchMove = (event: TouchEvent) => {
228
- const touchY = event.touches[0]?.clientY;
229
- if (touchY === undefined) return;
230
-
231
- const input = composerInputFromEvent(event);
232
- const deltaY = lastTouchY === null ? 0 : touchY - lastTouchY;
233
- lastTouchY = touchY;
234
-
235
- if (input && input.scrollHeight > input.clientHeight + SCROLL_BOUNDARY_EPSILON_PX) {
236
- const canScrollTowardStart = deltaY > 0 && input.scrollTop > SCROLL_BOUNDARY_EPSILON_PX;
237
- const canScrollTowardEnd =
238
- deltaY < 0 &&
239
- input.scrollTop + input.clientHeight < input.scrollHeight - SCROLL_BOUNDARY_EPSILON_PX;
240
- if (canScrollTowardStart || canScrollTowardEnd) return;
241
- }
242
-
243
- // Composer drags must not select the document or visual viewport as the gesture scroller.
244
- if (event.cancelable) event.preventDefault();
245
- };
246
-
247
- const handleTouchEnd = () => {
248
- lastTouchY = null;
249
- };
250
-
251
- const resizeObserver =
252
- iosWebKit && scrollIndicator && typeof ResizeObserver !== "undefined"
253
- ? new ResizeObserver(syncIndicator)
254
- : null;
255
- resizeObserver?.observe(transcript);
256
- resizeObserver?.observe(transcriptContent);
257
-
258
- dock.addEventListener("touchstart", handleTouchStart, { passive: true });
259
- dock.addEventListener("touchmove", handleTouchMove, { passive: false });
260
- dock.addEventListener("touchend", handleTouchEnd, { passive: true });
261
- dock.addEventListener("touchcancel", handleTouchEnd, { passive: true });
262
- dock.addEventListener("focus", handleInputFocus, true);
263
- dock.addEventListener("blur", handleInputBlur, true);
264
- transcript.addEventListener("scroll", syncIndicator, { passive: true });
265
- transcript.addEventListener(CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT, restartTranscriptScroller);
266
- window.visualViewport?.addEventListener("resize", handleVisualViewportChange);
267
- window.visualViewport?.addEventListener("scroll", handleVisualViewportChange);
268
- window.visualViewport?.addEventListener("scrollend", handleVisualViewportChange);
269
- syncKeyboardState();
270
-
271
- return () => {
272
- if (momentumRestoreFrame !== null) window.cancelAnimationFrame(momentumRestoreFrame);
273
- if (focusRevealTimer !== null) window.clearTimeout(focusRevealTimer);
274
- if (transcriptScrollerRestartFrame !== null) {
275
- window.cancelAnimationFrame(transcriptScrollerRestartFrame);
276
- }
277
- revealGuardedInput();
278
- transcriptScroller?.destroy();
279
- resizeObserver?.disconnect();
280
- transcript.removeAttribute("data-keyboard-touch-scroller");
281
- if (scrollIndicator) scrollIndicator.hidden = true;
282
- if (momentumOverflowY !== null) transcript.style.overflowY = momentumOverflowY;
283
- dock.removeEventListener("touchstart", handleTouchStart);
284
- dock.removeEventListener("touchmove", handleTouchMove);
285
- dock.removeEventListener("touchend", handleTouchEnd);
286
- dock.removeEventListener("touchcancel", handleTouchEnd);
287
- dock.removeEventListener("focus", handleInputFocus, true);
288
- dock.removeEventListener("blur", handleInputBlur, true);
289
- transcript.removeEventListener("scroll", syncIndicator);
290
- transcript.removeEventListener(
291
- CANCEL_TRANSCRIPT_KINETIC_SCROLL_EVENT,
292
- restartTranscriptScroller,
293
- );
294
- window.visualViewport?.removeEventListener("resize", handleVisualViewportChange);
295
- window.visualViewport?.removeEventListener("scroll", handleVisualViewportChange);
296
- window.visualViewport?.removeEventListener("scrollend", handleVisualViewportChange);
297
- };
298
- }, [frameRef]);
299
- };