@assistant-ui/react 0.11.36 → 0.11.38

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.
Files changed (53) hide show
  1. package/dist/legacy-runtime/runtime-cores/remote-thread-list/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
  2. package/dist/legacy-runtime/runtime-cores/remote-thread-list/RemoteThreadListThreadListRuntimeCore.js +34 -1
  3. package/dist/legacy-runtime/runtime-cores/remote-thread-list/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
  4. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/cloud.d.ts.map +1 -1
  5. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/cloud.js +9 -0
  6. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/cloud.js.map +1 -1
  7. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/in-memory.d.ts +2 -1
  8. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/in-memory.d.ts.map +1 -1
  9. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/in-memory.js +3 -0
  10. package/dist/legacy-runtime/runtime-cores/remote-thread-list/adapter/in-memory.js.map +1 -1
  11. package/dist/legacy-runtime/runtime-cores/remote-thread-list/types.d.ts +1 -0
  12. package/dist/legacy-runtime/runtime-cores/remote-thread-list/types.d.ts.map +1 -1
  13. package/dist/primitives/assistantModal/scope.d.ts +2 -3
  14. package/dist/primitives/assistantModal/scope.d.ts.map +1 -1
  15. package/dist/primitives/assistantModal/scope.js.map +1 -1
  16. package/dist/primitives/index.d.ts +1 -0
  17. package/dist/primitives/index.d.ts.map +1 -1
  18. package/dist/primitives/index.js +2 -0
  19. package/dist/primitives/index.js.map +1 -1
  20. package/dist/primitives/message/MessageParts.d.ts +31 -1
  21. package/dist/primitives/message/MessageParts.d.ts.map +1 -1
  22. package/dist/primitives/message/MessageParts.js +66 -23
  23. package/dist/primitives/message/MessageParts.js.map +1 -1
  24. package/dist/primitives/reasoning/index.d.ts +2 -0
  25. package/dist/primitives/reasoning/index.d.ts.map +1 -0
  26. package/dist/primitives/reasoning/index.js +6 -0
  27. package/dist/primitives/reasoning/index.js.map +1 -0
  28. package/dist/primitives/reasoning/useScrollLock.d.ts +29 -0
  29. package/dist/primitives/reasoning/useScrollLock.d.ts.map +1 -0
  30. package/dist/primitives/reasoning/useScrollLock.js +50 -0
  31. package/dist/primitives/reasoning/useScrollLock.js.map +1 -0
  32. package/dist/primitives/thread/useThreadViewportAutoScroll.d.ts.map +1 -1
  33. package/dist/primitives/thread/useThreadViewportAutoScroll.js +11 -12
  34. package/dist/primitives/thread/useThreadViewportAutoScroll.js.map +1 -1
  35. package/dist/tests/setup.js +287 -125
  36. package/dist/tests/setup.js.map +1 -1
  37. package/dist/types/MessagePartComponentTypes.d.ts +6 -1
  38. package/dist/types/MessagePartComponentTypes.d.ts.map +1 -1
  39. package/dist/types/index.d.ts +1 -1
  40. package/dist/types/index.d.ts.map +1 -1
  41. package/package.json +8 -8
  42. package/src/legacy-runtime/runtime-cores/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx +49 -2
  43. package/src/legacy-runtime/runtime-cores/remote-thread-list/adapter/cloud.tsx +10 -0
  44. package/src/legacy-runtime/runtime-cores/remote-thread-list/adapter/in-memory.tsx +5 -0
  45. package/src/legacy-runtime/runtime-cores/remote-thread-list/types.tsx +1 -0
  46. package/src/primitives/assistantModal/scope.tsx +3 -1
  47. package/src/primitives/index.ts +1 -0
  48. package/src/primitives/message/MessageParts.tsx +111 -30
  49. package/src/primitives/reasoning/index.ts +1 -0
  50. package/src/primitives/reasoning/useScrollLock.tsx +86 -0
  51. package/src/primitives/thread/useThreadViewportAutoScroll.tsx +14 -13
  52. package/src/types/MessagePartComponentTypes.tsx +7 -1
  53. package/src/types/index.ts +2 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/primitives/message/MessageParts.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type ComponentType,\n type FC,\n memo,\n PropsWithChildren,\n useMemo,\n} from \"react\";\nimport {\n useAssistantState,\n useAssistantApi,\n PartByIndexProvider,\n TextMessagePartProvider,\n} from \"../../context\";\nimport { MessagePartPrimitiveText } from \"../messagePart/MessagePartText\";\nimport { MessagePartPrimitiveImage } from \"../messagePart/MessagePartImage\";\nimport type {\n Unstable_AudioMessagePartComponent,\n EmptyMessagePartComponent,\n TextMessagePartComponent,\n ImageMessagePartComponent,\n SourceMessagePartComponent,\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n FileMessagePartComponent,\n ReasoningMessagePartComponent,\n} from \"../../types/MessagePartComponentTypes\";\nimport { MessagePartPrimitiveInProgress } from \"../messagePart/MessagePartInProgress\";\nimport { MessagePartStatus } from \"../../types/AssistantTypes\";\nimport { useShallow } from \"zustand/shallow\";\n\ntype MessagePartRange =\n | { type: \"single\"; index: number }\n | { type: \"toolGroup\"; startIndex: number; endIndex: number };\n\n/**\n * Groups consecutive tool-call message parts into ranges.\n * Always groups tool calls, even if there's only one.\n */\nconst groupMessageParts = (\n messageTypes: readonly string[],\n): MessagePartRange[] => {\n const ranges: MessagePartRange[] = [];\n let currentToolGroupStart = -1;\n\n for (let i = 0; i < messageTypes.length; i++) {\n const type = messageTypes[i];\n\n if (type === \"tool-call\") {\n // Start a new tool group if we haven't started one\n if (currentToolGroupStart === -1) {\n currentToolGroupStart = i;\n }\n } else {\n // End current tool group if it exists\n if (currentToolGroupStart !== -1) {\n ranges.push({\n type: \"toolGroup\",\n startIndex: currentToolGroupStart,\n endIndex: i - 1,\n });\n currentToolGroupStart = -1;\n }\n\n // Add non-tool-call part individually\n ranges.push({ type: \"single\", index: i });\n }\n }\n\n // Handle any remaining tool group at the end\n if (currentToolGroupStart !== -1) {\n ranges.push({\n type: \"toolGroup\",\n startIndex: currentToolGroupStart,\n endIndex: messageTypes.length - 1,\n });\n }\n\n return ranges;\n};\n\nconst useMessagePartsGroups = (): MessagePartRange[] => {\n const messageTypes = useAssistantState(\n useShallow((s) => s.message.parts.map((c: any) => c.type)),\n );\n\n return useMemo(() => {\n if (messageTypes.length === 0) {\n return [];\n }\n return groupMessageParts(messageTypes);\n }, [messageTypes]);\n};\n\nexport namespace MessagePrimitiveParts {\n export type Props = {\n /**\n * Component configuration for rendering different types of message content.\n *\n * You can provide custom components for each content type (text, image, file, etc.)\n * and configure tool rendering behavior. If not provided, default components will be used.\n */\n components?:\n | {\n /** Component for rendering empty messages */\n Empty?: EmptyMessagePartComponent | undefined;\n /** Component for rendering text content */\n Text?: TextMessagePartComponent | undefined;\n /** Component for rendering reasoning content (typically hidden) */\n Reasoning?: ReasoningMessagePartComponent | undefined;\n /** Component for rendering source content */\n Source?: SourceMessagePartComponent | undefined;\n /** Component for rendering image content */\n Image?: ImageMessagePartComponent | undefined;\n /** Component for rendering file content */\n File?: FileMessagePartComponent | undefined;\n /** Component for rendering audio content (experimental) */\n Unstable_Audio?: Unstable_AudioMessagePartComponent | undefined;\n /** Configuration for tool call rendering */\n tools?:\n | {\n /** Map of tool names to their specific components */\n by_name?:\n | Record<string, ToolCallMessagePartComponent | undefined>\n | undefined;\n /** Fallback component for unregistered tools */\n Fallback?: ComponentType<ToolCallMessagePartProps> | undefined;\n }\n | {\n /** Override component that handles all tool calls */\n Override: ComponentType<ToolCallMessagePartProps>;\n }\n | undefined;\n\n /**\n * Component for rendering grouped consecutive tool calls.\n *\n * When provided, this component will automatically wrap consecutive tool-call\n * message parts, allowing you to create collapsible sections, custom styling,\n * or other grouped presentations for multiple tool calls.\n *\n * The component receives:\n * - `startIndex`: The index of the first tool call in the group\n * - `endIndex`: The index of the last tool call in the group\n * - `children`: The rendered tool call components\n *\n * @example\n * ```tsx\n * // Collapsible tool group\n * ToolGroup: ({ startIndex, endIndex, children }) => (\n * <details className=\"tool-group\">\n * <summary>\n * {endIndex - startIndex + 1} tool calls\n * </summary>\n * <div className=\"tool-group-content\">\n * {children}\n * </div>\n * </details>\n * )\n * ```\n *\n * @example\n * ```tsx\n * // Custom styled tool group with header\n * ToolGroup: ({ startIndex, endIndex, children }) => (\n * <div className=\"border rounded-lg p-4 my-2\">\n * <div className=\"text-sm text-gray-600 mb-2\">\n * Tool execution #{startIndex + 1}-{endIndex + 1}\n * </div>\n * <div className=\"space-y-2\">\n * {children}\n * </div>\n * </div>\n * )\n * ```\n *\n * @param startIndex - Index of the first tool call in the group\n * @param endIndex - Index of the last tool call in the group\n * @param children - Rendered tool call components to display within the group\n *\n * @deprecated This feature is still experimental and subject to change.\n */\n ToolGroup?: ComponentType<\n PropsWithChildren<{ startIndex: number; endIndex: number }>\n >;\n }\n | undefined;\n };\n}\n\nconst ToolUIDisplay = ({\n Fallback,\n ...props\n}: {\n Fallback: ToolCallMessagePartComponent | undefined;\n} & ToolCallMessagePartProps) => {\n const Render = useAssistantState(({ toolUIs }) => {\n const Render =\n toolUIs.tools[props.toolName] ?? toolUIs.fallback ?? Fallback;\n if (Array.isArray(Render)) return Render[0] ?? Fallback;\n return Render;\n });\n if (!Render) return null;\n return <Render {...props} />;\n};\n\nconst defaultComponents = {\n Text: () => (\n <p style={{ whiteSpace: \"pre-line\" }}>\n <MessagePartPrimitiveText />\n <MessagePartPrimitiveInProgress>\n <span style={{ fontFamily: \"revert\" }}>{\" \\u25CF\"}</span>\n </MessagePartPrimitiveInProgress>\n </p>\n ),\n Reasoning: () => null,\n Source: () => null,\n Image: () => <MessagePartPrimitiveImage />,\n File: () => null,\n Unstable_Audio: () => null,\n ToolGroup: ({ children }) => children,\n} satisfies MessagePrimitiveParts.Props[\"components\"];\n\ntype MessagePartComponentProps = {\n components: MessagePrimitiveParts.Props[\"components\"];\n};\n\nconst MessagePartComponent: FC<MessagePartComponentProps> = ({\n components: {\n Text = defaultComponents.Text,\n Reasoning = defaultComponents.Reasoning,\n Image = defaultComponents.Image,\n Source = defaultComponents.Source,\n File = defaultComponents.File,\n Unstable_Audio: Audio = defaultComponents.Unstable_Audio,\n tools = {},\n } = {},\n}) => {\n const api = useAssistantApi();\n const part = useAssistantState(({ part }) => part);\n\n const type = part.type;\n if (type === \"tool-call\") {\n const addResult = api.part().addToolResult;\n const resume = api.part().resumeToolCall;\n if (\"Override\" in tools)\n return <tools.Override {...part} addResult={addResult} resume={resume} />;\n const Tool = tools.by_name?.[part.toolName] ?? tools.Fallback;\n return (\n <ToolUIDisplay\n {...part}\n Fallback={Tool}\n addResult={addResult}\n resume={resume}\n />\n );\n }\n\n if (part.status?.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n\n switch (type) {\n case \"text\":\n return <Text {...part} />;\n\n case \"reasoning\":\n return <Reasoning {...part} />;\n\n case \"source\":\n return <Source {...part} />;\n\n case \"image\":\n // eslint-disable-next-line jsx-a11y/alt-text\n return <Image {...part} />;\n\n case \"file\":\n return <File {...part} />;\n\n case \"audio\":\n return <Audio {...part} />;\n\n default:\n const unhandledType: never = type;\n throw new Error(`Unknown message part type: ${unhandledType}`);\n }\n};\n\nexport namespace MessagePrimitivePartByIndex {\n export type Props = {\n index: number;\n components: MessagePrimitiveParts.Props[\"components\"];\n };\n}\n\n/**\n * Renders a single message part at the specified index.\n *\n * This component provides direct access to render a specific message part\n * within the current message context, using the provided component configuration.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.PartByIndex\n * index={0}\n * components={{\n * Text: MyTextComponent,\n * Image: MyImageComponent\n * }}\n * />\n * ```\n */\nexport const MessagePrimitivePartByIndex: FC<MessagePrimitivePartByIndex.Props> =\n memo(\n ({ index, components }) => {\n return (\n <PartByIndexProvider index={index}>\n <MessagePartComponent components={components} />\n </PartByIndexProvider>\n );\n },\n (prev, next) =>\n prev.index === next.index &&\n prev.components?.Text === next.components?.Text &&\n prev.components?.Reasoning === next.components?.Reasoning &&\n prev.components?.Source === next.components?.Source &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.File === next.components?.File &&\n prev.components?.Unstable_Audio === next.components?.Unstable_Audio &&\n prev.components?.tools === next.components?.tools &&\n prev.components?.ToolGroup === next.components?.ToolGroup,\n );\n\nMessagePrimitivePartByIndex.displayName = \"MessagePrimitive.PartByIndex\";\n\nconst EmptyPartFallback: FC<{\n status: MessagePartStatus;\n component: TextMessagePartComponent;\n}> = ({ status, component: Component }) => {\n return (\n <TextMessagePartProvider text=\"\" isRunning={status.type === \"running\"}>\n <Component type=\"text\" text=\"\" status={status} />\n </TextMessagePartProvider>\n );\n};\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({\n type: \"complete\",\n});\n\nconst EmptyPartsImpl: FC<MessagePartComponentProps> = ({ components }) => {\n const status = useAssistantState(\n (s) => (s.message.status ?? COMPLETE_STATUS) as MessagePartStatus,\n );\n\n if (components?.Empty) return <components.Empty status={status} />;\n\n return (\n <EmptyPartFallback\n status={status}\n component={components?.Text ?? defaultComponents.Text}\n />\n );\n};\n\nconst EmptyParts = memo(\n EmptyPartsImpl,\n (prev, next) =>\n prev.components?.Empty === next.components?.Empty &&\n prev.components?.Text === next.components?.Text,\n);\n\n/**\n * Renders the parts of a message with support for multiple content types.\n *\n * This component automatically handles different types of message content including\n * text, images, files, tool calls, and more. It provides a flexible component\n * system for customizing how each content type is rendered.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.Parts\n * components={{\n * Text: ({ text }) => <p className=\"message-text\">{text}</p>,\n * Image: ({ image }) => <img src={image} alt=\"Message image\" />,\n * tools: {\n * by_name: {\n * calculator: CalculatorTool,\n * weather: WeatherTool,\n * },\n * Fallback: DefaultToolComponent\n * }\n * }}\n * />\n * ```\n */\nexport const MessagePrimitiveParts: FC<MessagePrimitiveParts.Props> = ({\n components,\n}) => {\n const contentLength = useAssistantState(\n ({ message }) => message.parts.length,\n );\n const messageRanges = useMessagePartsGroups();\n\n const partsElements = useMemo(() => {\n if (contentLength === 0) {\n return <EmptyParts components={components} />;\n }\n\n return messageRanges.map((range) => {\n if (range.type === \"single\") {\n return (\n <MessagePrimitivePartByIndex\n key={range.index}\n index={range.index}\n components={components}\n />\n );\n } else {\n const ToolGroupComponent =\n components!.ToolGroup ?? defaultComponents.ToolGroup;\n return (\n <ToolGroupComponent\n key={range.startIndex}\n startIndex={range.startIndex}\n endIndex={range.endIndex}\n >\n {Array.from(\n { length: range.endIndex - range.startIndex + 1 },\n (_, i) => (\n <MessagePrimitivePartByIndex\n key={i}\n index={range.startIndex + i}\n components={components}\n />\n ),\n )}\n </ToolGroupComponent>\n );\n }\n });\n }, [messageRanges, components, contentLength]);\n\n return <>{partsElements}</>;\n};\n\nMessagePrimitiveParts.displayName = \"MessagePrimitive.Parts\";\n"],"mappings":";;;AAEA;AAAA,EAGE;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gCAAgC;AACzC,SAAS,iCAAiC;AAY1C,SAAS,sCAAsC;AAE/C,SAAS,kBAAkB;AA8KlB,SA+OA,UA/OA,KAKL,YALK;AApKT,IAAM,oBAAoB,CACxB,iBACuB;AACvB,QAAM,SAA6B,CAAC;AACpC,MAAI,wBAAwB;AAE5B,WAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,UAAM,OAAO,aAAa,CAAC;AAE3B,QAAI,SAAS,aAAa;AAExB,UAAI,0BAA0B,IAAI;AAChC,gCAAwB;AAAA,MAC1B;AAAA,IACF,OAAO;AAEL,UAAI,0BAA0B,IAAI;AAChC,eAAO,KAAK;AAAA,UACV,MAAM;AAAA,UACN,YAAY;AAAA,UACZ,UAAU,IAAI;AAAA,QAChB,CAAC;AACD,gCAAwB;AAAA,MAC1B;AAGA,aAAO,KAAK,EAAE,MAAM,UAAU,OAAO,EAAE,CAAC;AAAA,IAC1C;AAAA,EACF;AAGA,MAAI,0BAA0B,IAAI;AAChC,WAAO,KAAK;AAAA,MACV,MAAM;AAAA,MACN,YAAY;AAAA,MACZ,UAAU,aAAa,SAAS;AAAA,IAClC,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAEA,IAAM,wBAAwB,MAA0B;AACt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A,IAC7C;AAEA,WAAO,cAAc,IAAI,CAAC,UAAU;AAClC,UAAI,MAAM,SAAS,UAAU;AAC3B,eACE;AAAA,UAAC;AAAA;AAAA,YAEC,OAAO,MAAM;AAAA,YACb;AAAA;AAAA,UAFK,MAAM;AAAA,QAGb;AAAA,MAEJ,OAAO;AACL,cAAM,qBACJ,WAAY,aAAa,kBAAkB;AAC7C,eACE;AAAA,UAAC;AAAA;AAAA,YAEC,YAAY,MAAM;AAAA,YAClB,UAAU,MAAM;AAAA,YAEf,gBAAM;AAAA,cACL,EAAE,QAAQ,MAAM,WAAW,MAAM,aAAa,EAAE;AAAA,cAChD,CAAC,GAAG,MACF;AAAA,gBAAC;AAAA;AAAA,kBAEC,OAAO,MAAM,aAAa;AAAA,kBAC1B;AAAA;AAAA,gBAFK;AAAA,cAGP;AAAA,YAEJ;AAAA;AAAA,UAbK,MAAM;AAAA,QAcb;AAAA,MAEJ;AAAA,IACF,CAAC;AAAA,EACH,GAAG,CAAC,eAAe,YAAY,aAAa,CAAC;AAE7C,SAAO,gCAAG,yBAAc;AAC1B;AAEA,sBAAsB,cAAc;","names":["Render","part"]}
1
+ {"version":3,"sources":["../../../src/primitives/message/MessageParts.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n type ComponentType,\n type FC,\n memo,\n PropsWithChildren,\n useMemo,\n} from \"react\";\nimport {\n useAssistantState,\n useAssistantApi,\n PartByIndexProvider,\n TextMessagePartProvider,\n} from \"../../context\";\nimport { MessagePartPrimitiveText } from \"../messagePart/MessagePartText\";\nimport { MessagePartPrimitiveImage } from \"../messagePart/MessagePartImage\";\nimport type {\n Unstable_AudioMessagePartComponent,\n EmptyMessagePartComponent,\n TextMessagePartComponent,\n ImageMessagePartComponent,\n SourceMessagePartComponent,\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n FileMessagePartComponent,\n ReasoningMessagePartComponent,\n ReasoningGroupComponent,\n} from \"../../types/MessagePartComponentTypes\";\nimport { MessagePartPrimitiveInProgress } from \"../messagePart/MessagePartInProgress\";\nimport { MessagePartStatus } from \"../../types/AssistantTypes\";\nimport { useShallow } from \"zustand/shallow\";\n\ntype MessagePartRange =\n | { type: \"single\"; index: number }\n | { type: \"toolGroup\"; startIndex: number; endIndex: number }\n | { type: \"reasoningGroup\"; startIndex: number; endIndex: number };\n\n/**\n * Creates a group state manager for a specific part type.\n * Returns functions to start, end, and finalize groups.\n */\nconst createGroupState = <T extends \"toolGroup\" | \"reasoningGroup\">(\n groupType: T,\n) => {\n let start = -1;\n\n return {\n startGroup: (index: number) => {\n if (start === -1) {\n start = index;\n }\n },\n endGroup: (endIndex: number, ranges: MessagePartRange[]) => {\n if (start !== -1) {\n ranges.push({\n type: groupType,\n startIndex: start,\n endIndex,\n } as MessagePartRange);\n start = -1;\n }\n },\n finalize: (endIndex: number, ranges: MessagePartRange[]) => {\n if (start !== -1) {\n ranges.push({\n type: groupType,\n startIndex: start,\n endIndex,\n } as MessagePartRange);\n }\n },\n };\n};\n\n/**\n * Groups consecutive tool-call and reasoning message parts into ranges.\n * Always groups tool calls and reasoning parts, even if there's only one.\n */\nconst groupMessageParts = (\n messageTypes: readonly string[],\n): MessagePartRange[] => {\n const ranges: MessagePartRange[] = [];\n const toolGroup = createGroupState(\"toolGroup\");\n const reasoningGroup = createGroupState(\"reasoningGroup\");\n\n for (let i = 0; i < messageTypes.length; i++) {\n const type = messageTypes[i];\n\n if (type === \"tool-call\") {\n reasoningGroup.endGroup(i - 1, ranges);\n toolGroup.startGroup(i);\n } else if (type === \"reasoning\") {\n toolGroup.endGroup(i - 1, ranges);\n reasoningGroup.startGroup(i);\n } else {\n toolGroup.endGroup(i - 1, ranges);\n reasoningGroup.endGroup(i - 1, ranges);\n ranges.push({ type: \"single\", index: i });\n }\n }\n\n toolGroup.finalize(messageTypes.length - 1, ranges);\n reasoningGroup.finalize(messageTypes.length - 1, ranges);\n\n return ranges;\n};\n\nconst useMessagePartsGroups = (): MessagePartRange[] => {\n const messageTypes = useAssistantState(\n useShallow((s) => s.message.parts.map((c: any) => c.type)),\n );\n\n return useMemo(() => {\n if (messageTypes.length === 0) {\n return [];\n }\n return groupMessageParts(messageTypes);\n }, [messageTypes]);\n};\n\nexport namespace MessagePrimitiveParts {\n export type Props = {\n /**\n * Component configuration for rendering different types of message content.\n *\n * You can provide custom components for each content type (text, image, file, etc.)\n * and configure tool rendering behavior. If not provided, default components will be used.\n */\n components?:\n | {\n /** Component for rendering empty messages */\n Empty?: EmptyMessagePartComponent | undefined;\n /** Component for rendering text content */\n Text?: TextMessagePartComponent | undefined;\n /** Component for rendering reasoning content (typically hidden) */\n Reasoning?: ReasoningMessagePartComponent | undefined;\n /** Component for rendering source content */\n Source?: SourceMessagePartComponent | undefined;\n /** Component for rendering image content */\n Image?: ImageMessagePartComponent | undefined;\n /** Component for rendering file content */\n File?: FileMessagePartComponent | undefined;\n /** Component for rendering audio content (experimental) */\n Unstable_Audio?: Unstable_AudioMessagePartComponent | undefined;\n /** Configuration for tool call rendering */\n tools?:\n | {\n /** Map of tool names to their specific components */\n by_name?:\n | Record<string, ToolCallMessagePartComponent | undefined>\n | undefined;\n /** Fallback component for unregistered tools */\n Fallback?: ComponentType<ToolCallMessagePartProps> | undefined;\n }\n | {\n /** Override component that handles all tool calls */\n Override: ComponentType<ToolCallMessagePartProps>;\n }\n | undefined;\n\n /**\n * Component for rendering grouped consecutive tool calls.\n *\n * When provided, this component will automatically wrap consecutive tool-call\n * message parts, allowing you to create collapsible sections, custom styling,\n * or other grouped presentations for multiple tool calls.\n *\n * The component receives:\n * - `startIndex`: The index of the first tool call in the group\n * - `endIndex`: The index of the last tool call in the group\n * - `children`: The rendered tool call components\n *\n * @example\n * ```tsx\n * // Collapsible tool group\n * ToolGroup: ({ startIndex, endIndex, children }) => (\n * <details className=\"tool-group\">\n * <summary>\n * {endIndex - startIndex + 1} tool calls\n * </summary>\n * <div className=\"tool-group-content\">\n * {children}\n * </div>\n * </details>\n * )\n * ```\n *\n * @example\n * ```tsx\n * // Custom styled tool group with header\n * ToolGroup: ({ startIndex, endIndex, children }) => (\n * <div className=\"border rounded-lg p-4 my-2\">\n * <div className=\"text-sm text-gray-600 mb-2\">\n * Tool execution #{startIndex + 1}-{endIndex + 1}\n * </div>\n * <div className=\"space-y-2\">\n * {children}\n * </div>\n * </div>\n * )\n * ```\n *\n * @param startIndex - Index of the first tool call in the group\n * @param endIndex - Index of the last tool call in the group\n * @param children - Rendered tool call components to display within the group\n *\n * @deprecated This feature is still experimental and subject to change.\n */\n ToolGroup?: ComponentType<\n PropsWithChildren<{ startIndex: number; endIndex: number }>\n >;\n\n /**\n * Component for rendering grouped reasoning parts.\n *\n * When provided, this component will automatically wrap reasoning message parts\n * (one or more consecutive) in a group container. Each reasoning part inside\n * renders its own text independently - no text merging occurs.\n *\n * The component receives:\n * - `startIndex`: The index of the first reasoning part in the group\n * - `endIndex`: The index of the last reasoning part in the group\n * - `children`: The rendered Reasoning components (one per part)\n *\n * @example\n * ```tsx\n * // Collapsible reasoning group\n * ReasoningGroup: ({ children }) => (\n * <details className=\"reasoning-group\">\n * <summary>Reasoning</summary>\n * <div className=\"reasoning-content\">\n * {children}\n * </div>\n * </details>\n * )\n * ```\n *\n * @param startIndex - Index of the first reasoning part in the group\n * @param endIndex - Index of the last reasoning part in the group\n * @param children - Rendered reasoning part components\n */\n ReasoningGroup?: ReasoningGroupComponent;\n }\n | undefined;\n };\n}\n\nconst ToolUIDisplay = ({\n Fallback,\n ...props\n}: {\n Fallback: ToolCallMessagePartComponent | undefined;\n} & ToolCallMessagePartProps) => {\n const Render = useAssistantState(({ toolUIs }) => {\n const Render =\n toolUIs.tools[props.toolName] ?? toolUIs.fallback ?? Fallback;\n if (Array.isArray(Render)) return Render[0] ?? Fallback;\n return Render;\n });\n if (!Render) return null;\n return <Render {...props} />;\n};\n\nconst defaultComponents = {\n Text: () => (\n <p style={{ whiteSpace: \"pre-line\" }}>\n <MessagePartPrimitiveText />\n <MessagePartPrimitiveInProgress>\n <span style={{ fontFamily: \"revert\" }}>{\" \\u25CF\"}</span>\n </MessagePartPrimitiveInProgress>\n </p>\n ),\n Reasoning: () => null,\n Source: () => null,\n Image: () => <MessagePartPrimitiveImage />,\n File: () => null,\n Unstable_Audio: () => null,\n ToolGroup: ({ children }) => children,\n ReasoningGroup: ({ children }) => children,\n} satisfies MessagePrimitiveParts.Props[\"components\"];\n\ntype MessagePartComponentProps = {\n components: MessagePrimitiveParts.Props[\"components\"];\n};\n\nconst MessagePartComponent: FC<MessagePartComponentProps> = ({\n components: {\n Text = defaultComponents.Text,\n Reasoning = defaultComponents.Reasoning,\n Image = defaultComponents.Image,\n Source = defaultComponents.Source,\n File = defaultComponents.File,\n Unstable_Audio: Audio = defaultComponents.Unstable_Audio,\n tools = {},\n } = {},\n}) => {\n const api = useAssistantApi();\n const part = useAssistantState(({ part }) => part);\n\n const type = part.type;\n if (type === \"tool-call\") {\n const addResult = api.part().addToolResult;\n const resume = api.part().resumeToolCall;\n if (\"Override\" in tools)\n return <tools.Override {...part} addResult={addResult} resume={resume} />;\n const Tool = tools.by_name?.[part.toolName] ?? tools.Fallback;\n return (\n <ToolUIDisplay\n {...part}\n Fallback={Tool}\n addResult={addResult}\n resume={resume}\n />\n );\n }\n\n if (part.status?.type === \"requires-action\")\n throw new Error(\"Encountered unexpected requires-action status\");\n\n switch (type) {\n case \"text\":\n return <Text {...part} />;\n\n case \"reasoning\":\n return <Reasoning {...part} />;\n\n case \"source\":\n return <Source {...part} />;\n\n case \"image\":\n // eslint-disable-next-line jsx-a11y/alt-text\n return <Image {...part} />;\n\n case \"file\":\n return <File {...part} />;\n\n case \"audio\":\n return <Audio {...part} />;\n\n default:\n const unhandledType: never = type;\n throw new Error(`Unknown message part type: ${unhandledType}`);\n }\n};\n\nexport namespace MessagePrimitivePartByIndex {\n export type Props = {\n index: number;\n components: MessagePrimitiveParts.Props[\"components\"];\n };\n}\n\n/**\n * Renders a single message part at the specified index.\n *\n * This component provides direct access to render a specific message part\n * within the current message context, using the provided component configuration.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.PartByIndex\n * index={0}\n * components={{\n * Text: MyTextComponent,\n * Image: MyImageComponent\n * }}\n * />\n * ```\n */\nexport const MessagePrimitivePartByIndex: FC<MessagePrimitivePartByIndex.Props> =\n memo(\n ({ index, components }) => {\n return (\n <PartByIndexProvider index={index}>\n <MessagePartComponent components={components} />\n </PartByIndexProvider>\n );\n },\n (prev, next) =>\n prev.index === next.index &&\n prev.components?.Text === next.components?.Text &&\n prev.components?.Reasoning === next.components?.Reasoning &&\n prev.components?.Source === next.components?.Source &&\n prev.components?.Image === next.components?.Image &&\n prev.components?.File === next.components?.File &&\n prev.components?.Unstable_Audio === next.components?.Unstable_Audio &&\n prev.components?.tools === next.components?.tools &&\n prev.components?.ToolGroup === next.components?.ToolGroup &&\n prev.components?.ReasoningGroup === next.components?.ReasoningGroup,\n );\n\nMessagePrimitivePartByIndex.displayName = \"MessagePrimitive.PartByIndex\";\n\nconst EmptyPartFallback: FC<{\n status: MessagePartStatus;\n component: TextMessagePartComponent;\n}> = ({ status, component: Component }) => {\n return (\n <TextMessagePartProvider text=\"\" isRunning={status.type === \"running\"}>\n <Component type=\"text\" text=\"\" status={status} />\n </TextMessagePartProvider>\n );\n};\n\nconst COMPLETE_STATUS: MessagePartStatus = Object.freeze({\n type: \"complete\",\n});\n\nconst EmptyPartsImpl: FC<MessagePartComponentProps> = ({ components }) => {\n const status = useAssistantState(\n (s) => (s.message.status ?? COMPLETE_STATUS) as MessagePartStatus,\n );\n\n if (components?.Empty) return <components.Empty status={status} />;\n\n return (\n <EmptyPartFallback\n status={status}\n component={components?.Text ?? defaultComponents.Text}\n />\n );\n};\n\nconst EmptyParts = memo(\n EmptyPartsImpl,\n (prev, next) =>\n prev.components?.Empty === next.components?.Empty &&\n prev.components?.Text === next.components?.Text,\n);\n\n/**\n * Renders the parts of a message with support for multiple content types.\n *\n * This component automatically handles different types of message content including\n * text, images, files, tool calls, and more. It provides a flexible component\n * system for customizing how each content type is rendered.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.Parts\n * components={{\n * Text: ({ text }) => <p className=\"message-text\">{text}</p>,\n * Image: ({ image }) => <img src={image} alt=\"Message image\" />,\n * tools: {\n * by_name: {\n * calculator: CalculatorTool,\n * weather: WeatherTool,\n * },\n * Fallback: DefaultToolComponent\n * }\n * }}\n * />\n * ```\n */\nexport const MessagePrimitiveParts: FC<MessagePrimitiveParts.Props> = ({\n components,\n}) => {\n const contentLength = useAssistantState(\n ({ message }) => message.parts.length,\n );\n const messageRanges = useMessagePartsGroups();\n\n const partsElements = useMemo(() => {\n if (contentLength === 0) {\n return <EmptyParts components={components} />;\n }\n\n return messageRanges.map((range) => {\n if (range.type === \"single\") {\n return (\n <MessagePrimitivePartByIndex\n key={range.index}\n index={range.index}\n components={components}\n />\n );\n } else if (range.type === \"toolGroup\") {\n const ToolGroupComponent =\n components!.ToolGroup ?? defaultComponents.ToolGroup;\n return (\n <ToolGroupComponent\n key={`tool-${range.startIndex}`}\n startIndex={range.startIndex}\n endIndex={range.endIndex}\n >\n {Array.from(\n { length: range.endIndex - range.startIndex + 1 },\n (_, i) => (\n <MessagePrimitivePartByIndex\n key={i}\n index={range.startIndex + i}\n components={components}\n />\n ),\n )}\n </ToolGroupComponent>\n );\n } else {\n // reasoningGroup\n const ReasoningGroupComponent =\n components!.ReasoningGroup ?? defaultComponents.ReasoningGroup;\n return (\n <ReasoningGroupComponent\n key={`reasoning-${range.startIndex}`}\n startIndex={range.startIndex}\n endIndex={range.endIndex}\n >\n {Array.from(\n { length: range.endIndex - range.startIndex + 1 },\n (_, i) => (\n <MessagePrimitivePartByIndex\n key={i}\n index={range.startIndex + i}\n components={components}\n />\n ),\n )}\n </ReasoningGroupComponent>\n );\n }\n });\n }, [messageRanges, components, contentLength]);\n\n return <>{partsElements}</>;\n};\n\nMessagePrimitiveParts.displayName = \"MessagePrimitive.Parts\";\n"],"mappings":";;;AAEA;AAAA,EAGE;AAAA,EAEA;A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;AAAA,QAcpC;AAAA,MAEJ;AAAA,IACF,CAAC;AAAA,EACH,GAAG,CAAC,eAAe,YAAY,aAAa,CAAC;AAE7C,SAAO,gCAAG,yBAAc;AAC1B;AAEA,sBAAsB,cAAc;","names":["Render","part"]}
@@ -0,0 +1,2 @@
1
+ export { useScrollLock } from "./useScrollLock";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/primitives/reasoning/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,6 @@
1
+ // src/primitives/reasoning/index.ts
2
+ import { useScrollLock } from "./useScrollLock.js";
3
+ export {
4
+ useScrollLock
5
+ };
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/primitives/reasoning/index.ts"],"sourcesContent":["export { useScrollLock } from \"./useScrollLock\";\n"],"mappings":";AAAA,SAAS,qBAAqB;","names":[]}
@@ -0,0 +1,29 @@
1
+ import { type RefObject } from "react";
2
+ /**
3
+ * Locks scroll position during collapsible/height animations and hides scrollbar.
4
+ *
5
+ * This utility prevents page jumps when content height changes during animations,
6
+ * providing a smooth user experience. It finds the nearest scrollable ancestor and
7
+ * temporarily locks its scroll position while the animation completes.
8
+ *
9
+ * - Prevents forced reflows: no layout reads, mutations scoped to scrollable parent only
10
+ * - Reactive: only intercepts scroll events when browser actually adjusts
11
+ * - Cleans up automatically after animation duration
12
+ *
13
+ * @param animatedElementRef - Ref to the animated element
14
+ * @param animationDuration - Lock duration in milliseconds
15
+ * @returns Function to activate the scroll lock
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * const collapsibleRef = useRef<HTMLDivElement>(null);
20
+ * const lockScroll = useScrollLock(collapsibleRef, 200);
21
+ *
22
+ * const handleCollapse = () => {
23
+ * lockScroll(); // Lock scroll before collapsing
24
+ * setIsOpen(false);
25
+ * };
26
+ * ```
27
+ */
28
+ export declare const useScrollLock: <T extends HTMLElement = HTMLElement>(animatedElementRef: RefObject<T | null>, animationDuration: number) => () => void;
29
+ //# sourceMappingURL=useScrollLock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useScrollLock.d.ts","sourceRoot":"","sources":["../../../src/primitives/reasoning/useScrollLock.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,SAAS,EAAkC,MAAM,OAAO,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,WAAW,GAAG,WAAW,EAC/D,oBAAoB,SAAS,CAAC,CAAC,GAAG,IAAI,CAAC,EACvC,mBAAmB,MAAM,eAqD1B,CAAC"}
@@ -0,0 +1,50 @@
1
+ "use client";
2
+
3
+ // src/primitives/reasoning/useScrollLock.tsx
4
+ import { useCallback, useEffect, useRef } from "react";
5
+ var useScrollLock = (animatedElementRef, animationDuration) => {
6
+ const scrollContainerRef = useRef(null);
7
+ const cleanupRef = useRef(null);
8
+ useEffect(() => {
9
+ return () => {
10
+ cleanupRef.current?.();
11
+ };
12
+ }, []);
13
+ const lockScroll = useCallback(() => {
14
+ cleanupRef.current?.();
15
+ (function findScrollableAncestor() {
16
+ if (scrollContainerRef.current || !animatedElementRef.current) return;
17
+ let el = animatedElementRef.current;
18
+ while (el) {
19
+ const { overflowY } = getComputedStyle(el);
20
+ if (overflowY === "scroll" || overflowY === "auto") {
21
+ scrollContainerRef.current = el;
22
+ break;
23
+ }
24
+ el = el.parentElement;
25
+ }
26
+ })();
27
+ const scrollContainer = scrollContainerRef.current;
28
+ if (!scrollContainer) return;
29
+ const scrollPosition = scrollContainer.scrollTop;
30
+ const scrollbarWidth = scrollContainer.style.scrollbarWidth;
31
+ scrollContainer.style.scrollbarWidth = "none";
32
+ const resetPosition = () => scrollContainer.scrollTop = scrollPosition;
33
+ scrollContainer.addEventListener("scroll", resetPosition);
34
+ const timeoutId = setTimeout(() => {
35
+ scrollContainer.removeEventListener("scroll", resetPosition);
36
+ scrollContainer.style.scrollbarWidth = scrollbarWidth;
37
+ cleanupRef.current = null;
38
+ }, animationDuration);
39
+ cleanupRef.current = () => {
40
+ clearTimeout(timeoutId);
41
+ scrollContainer.removeEventListener("scroll", resetPosition);
42
+ scrollContainer.style.scrollbarWidth = scrollbarWidth;
43
+ };
44
+ }, [animationDuration, animatedElementRef]);
45
+ return lockScroll;
46
+ };
47
+ export {
48
+ useScrollLock
49
+ };
50
+ //# sourceMappingURL=useScrollLock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/primitives/reasoning/useScrollLock.tsx"],"sourcesContent":["\"use client\";\n\nimport { type RefObject, useCallback, useEffect, useRef } from \"react\";\n\n/**\n * Locks scroll position during collapsible/height animations and hides scrollbar.\n *\n * This utility prevents page jumps when content height changes during animations,\n * providing a smooth user experience. It finds the nearest scrollable ancestor and\n * temporarily locks its scroll position while the animation completes.\n *\n * - Prevents forced reflows: no layout reads, mutations scoped to scrollable parent only\n * - Reactive: only intercepts scroll events when browser actually adjusts\n * - Cleans up automatically after animation duration\n *\n * @param animatedElementRef - Ref to the animated element\n * @param animationDuration - Lock duration in milliseconds\n * @returns Function to activate the scroll lock\n *\n * @example\n * ```tsx\n * const collapsibleRef = useRef<HTMLDivElement>(null);\n * const lockScroll = useScrollLock(collapsibleRef, 200);\n *\n * const handleCollapse = () => {\n * lockScroll(); // Lock scroll before collapsing\n * setIsOpen(false);\n * };\n * ```\n */\nexport const useScrollLock = <T extends HTMLElement = HTMLElement>(\n animatedElementRef: RefObject<T | null>,\n animationDuration: number,\n) => {\n const scrollContainerRef = useRef<HTMLElement | null>(null);\n const cleanupRef = useRef<(() => void) | null>(null);\n\n useEffect(() => {\n return () => {\n cleanupRef.current?.();\n };\n }, []);\n\n const lockScroll = useCallback(() => {\n cleanupRef.current?.();\n\n (function findScrollableAncestor() {\n if (scrollContainerRef.current || !animatedElementRef.current) return;\n\n let el: HTMLElement | null = animatedElementRef.current;\n while (el) {\n const { overflowY } = getComputedStyle(el);\n if (overflowY === \"scroll\" || overflowY === \"auto\") {\n scrollContainerRef.current = el;\n break;\n }\n el = el.parentElement;\n }\n })();\n\n const scrollContainer = scrollContainerRef.current;\n if (!scrollContainer) return;\n\n const scrollPosition = scrollContainer.scrollTop;\n const scrollbarWidth = scrollContainer.style.scrollbarWidth;\n\n scrollContainer.style.scrollbarWidth = \"none\";\n\n const resetPosition = () => (scrollContainer.scrollTop = scrollPosition);\n scrollContainer.addEventListener(\"scroll\", resetPosition);\n\n const timeoutId = setTimeout(() => {\n scrollContainer.removeEventListener(\"scroll\", resetPosition);\n scrollContainer.style.scrollbarWidth = scrollbarWidth;\n cleanupRef.current = null;\n }, animationDuration);\n\n cleanupRef.current = () => {\n clearTimeout(timeoutId);\n scrollContainer.removeEventListener(\"scroll\", resetPosition);\n scrollContainer.style.scrollbarWidth = scrollbarWidth;\n };\n }, [animationDuration, animatedElementRef]);\n\n return lockScroll;\n};\n"],"mappings":";;;AAEA,SAAyB,aAAa,WAAW,cAAc;AA4BxD,IAAM,gBAAgB,CAC3B,oBACA,sBACG;AACH,QAAM,qBAAqB,OAA2B,IAAI;AAC1D,QAAM,aAAa,OAA4B,IAAI;AAEnD,YAAU,MAAM;AACd,WAAO,MAAM;AACX,iBAAW,UAAU;AAAA,IACvB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,QAAM,aAAa,YAAY,MAAM;AACnC,eAAW,UAAU;AAErB,KAAC,SAAS,yBAAyB;AACjC,UAAI,mBAAmB,WAAW,CAAC,mBAAmB,QAAS;AAE/D,UAAI,KAAyB,mBAAmB;AAChD,aAAO,IAAI;AACT,cAAM,EAAE,UAAU,IAAI,iBAAiB,EAAE;AACzC,YAAI,cAAc,YAAY,cAAc,QAAQ;AAClD,6BAAmB,UAAU;AAC7B;AAAA,QACF;AACA,aAAK,GAAG;AAAA,MACV;AAAA,IACF,GAAG;AAEH,UAAM,kBAAkB,mBAAmB;AAC3C,QAAI,CAAC,gBAAiB;AAEtB,UAAM,iBAAiB,gBAAgB;AACvC,UAAM,iBAAiB,gBAAgB,MAAM;AAE7C,oBAAgB,MAAM,iBAAiB;AAEvC,UAAM,gBAAgB,MAAO,gBAAgB,YAAY;AACzD,oBAAgB,iBAAiB,UAAU,aAAa;AAExD,UAAM,YAAY,WAAW,MAAM;AACjC,sBAAgB,oBAAoB,UAAU,aAAa;AAC3D,sBAAgB,MAAM,iBAAiB;AACvC,iBAAW,UAAU;AAAA,IACvB,GAAG,iBAAiB;AAEpB,eAAW,UAAU,MAAM;AACzB,mBAAa,SAAS;AACtB,sBAAgB,oBAAoB,UAAU,aAAa;AAC3D,sBAAgB,MAAM,iBAAiB;AAAA,IACzC;AAAA,EACF,GAAG,CAAC,mBAAmB,kBAAkB,CAAC;AAE1C,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"useThreadViewportAutoScroll.d.ts","sourceRoot":"","sources":["../../../src/primitives/thread/useThreadViewportAutoScroll.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAuB,MAAM,OAAO,CAAC;AAQzD,yBAAiB,2BAA2B,CAAC;IAC3C,KAAY,OAAO,GAAG;QACpB,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;KAClC,CAAC;CACH;AAED,eAAO,MAAM,2BAA2B,GAAI,QAAQ,SAAS,WAAW,EAAE,iBAEvE,2BAA2B,CAAC,OAAO,KAAG,WAAW,CAAC,QAAQ,CA0E5D,CAAC"}
1
+ {"version":3,"file":"useThreadViewportAutoScroll.d.ts","sourceRoot":"","sources":["../../../src/primitives/thread/useThreadViewportAutoScroll.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,WAAW,EAAuB,MAAM,OAAO,CAAC;AAQzD,yBAAiB,2BAA2B,CAAC;IAC3C,KAAY,OAAO,GAAG;QACpB,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;KAClC,CAAC;CACH;AAED,eAAO,MAAM,2BAA2B,GAAI,QAAQ,SAAS,WAAW,EAAE,iBAEvE,2BAA2B,CAAC,OAAO,KAAG,WAAW,CAAC,QAAQ,CA2E5D,CAAC"}
@@ -16,20 +16,17 @@ var useThreadViewportAutoScroll = ({
16
16
  const threadViewportStore = useThreadViewportStore();
17
17
  const lastScrollTop = useRef(0);
18
18
  const isScrollingToBottomRef = useRef(false);
19
- const scrollToBottom = useCallback(
20
- (behavior) => {
21
- const div = divRef.current;
22
- if (!div || !autoScroll) return;
23
- isScrollingToBottomRef.current = true;
24
- div.scrollTo({ top: div.scrollHeight, behavior });
25
- },
26
- [autoScroll]
27
- );
19
+ const scrollToBottom = useCallback((behavior) => {
20
+ const div = divRef.current;
21
+ if (!div) return;
22
+ isScrollingToBottomRef.current = true;
23
+ div.scrollTo({ top: div.scrollHeight, behavior });
24
+ }, []);
28
25
  const handleScroll = () => {
29
26
  const div = divRef.current;
30
27
  if (!div) return;
31
28
  const isAtBottom = threadViewportStore.getState().isAtBottom;
32
- const newIsAtBottom = div.scrollHeight - div.scrollTop <= div.clientHeight + 1;
29
+ const newIsAtBottom = Math.abs(div.scrollHeight - div.scrollTop - div.clientHeight) < 1 || div.scrollHeight <= div.clientHeight;
33
30
  if (!newIsAtBottom && lastScrollTop.current < div.scrollTop) {
34
31
  } else {
35
32
  if (newIsAtBottom) {
@@ -44,7 +41,7 @@ var useThreadViewportAutoScroll = ({
44
41
  lastScrollTop.current = div.scrollTop;
45
42
  };
46
43
  const resizeRef = useOnResizeContent(() => {
47
- if (isScrollingToBottomRef.current || threadViewportStore.getState().isAtBottom) {
44
+ if (autoScroll && (isScrollingToBottomRef.current || threadViewportStore.getState().isAtBottom)) {
48
45
  scrollToBottom("instant");
49
46
  }
50
47
  handleScroll();
@@ -58,7 +55,9 @@ var useThreadViewportAutoScroll = ({
58
55
  useOnScrollToBottom(() => {
59
56
  scrollToBottom("auto");
60
57
  });
61
- useAssistantEvent("thread.run-start", () => scrollToBottom("auto"));
58
+ useAssistantEvent("thread.run-start", () => {
59
+ if (autoScroll) scrollToBottom("auto");
60
+ });
62
61
  const autoScrollRef = useComposedRefs(resizeRef, scrollRef, divRef);
63
62
  return autoScrollRef;
64
63
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/primitives/thread/useThreadViewportAutoScroll.tsx"],"sourcesContent":["\"use client\";\n\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { RefCallback, useCallback, useRef } from \"react\";\nimport { useAssistantEvent } from \"../../context\";\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\nexport namespace useThreadViewportAutoScroll {\n export type Options = {\n autoScroll?: boolean | undefined;\n };\n}\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll = true,\n}: useThreadViewportAutoScroll.Options): RefCallback<TElement> => {\n const divRef = useRef<TElement>(null);\n\n const threadViewportStore = useThreadViewportStore();\n\n const lastScrollTop = useRef<number>(0);\n\n // bug: when ScrollToBottom's button changes its disabled state, the scroll stops\n // fix: delay the state change until the scroll is done\n const isScrollingToBottomRef = useRef(false);\n\n const scrollToBottom = useCallback(\n (behavior: ScrollBehavior) => {\n const div = divRef.current;\n if (!div || !autoScroll) return;\n\n isScrollingToBottomRef.current = true;\n div.scrollTo({ top: div.scrollHeight, behavior });\n },\n [autoScroll],\n );\n\n const handleScroll = () => {\n const div = divRef.current;\n if (!div) return;\n\n const isAtBottom = threadViewportStore.getState().isAtBottom;\n const newIsAtBottom =\n div.scrollHeight - div.scrollTop <= div.clientHeight + 1; // TODO figure out why +1 is needed\n\n if (!newIsAtBottom && lastScrollTop.current < div.scrollTop) {\n // ignore scroll down\n } else {\n if (newIsAtBottom) {\n isScrollingToBottomRef.current = false;\n }\n\n if (newIsAtBottom !== isAtBottom) {\n writableStore(threadViewportStore).setState({\n isAtBottom: newIsAtBottom,\n });\n }\n }\n\n lastScrollTop.current = div.scrollTop;\n };\n\n const resizeRef = useOnResizeContent(() => {\n if (\n isScrollingToBottomRef.current ||\n threadViewportStore.getState().isAtBottom\n ) {\n scrollToBottom(\"instant\");\n }\n\n handleScroll();\n });\n\n const scrollRef = useManagedRef<HTMLElement>((el) => {\n el.addEventListener(\"scroll\", handleScroll);\n return () => {\n el.removeEventListener(\"scroll\", handleScroll);\n };\n });\n\n useOnScrollToBottom(() => {\n scrollToBottom(\"auto\");\n });\n\n // autoscroll on run start\n useAssistantEvent(\"thread.run-start\", () => scrollToBottom(\"auto\"));\n\n const autoScrollRef = useComposedRefs<TElement>(resizeRef, scrollRef, divRef);\n return autoScrollRef as RefCallback<TElement>;\n};\n"],"mappings":";;;AAEA,SAAS,uBAAuB;AAChC,SAAsB,aAAa,cAAc;AACjD,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,8BAA8B;AAQhC,IAAM,8BAA8B,CAA+B;AAAA,EACxE,aAAa;AACf,MAAkE;AAChE,QAAM,SAAS,OAAiB,IAAI;AAEpC,QAAM,sBAAsB,uBAAuB;AAEnD,QAAM,gBAAgB,OAAe,CAAC;AAItC,QAAM,yBAAyB,OAAO,KAAK;AAE3C,QAAM,iBAAiB;AAAA,IACrB,CAAC,aAA6B;AAC5B,YAAM,MAAM,OAAO;AACnB,UAAI,CAAC,OAAO,CAAC,WAAY;AAEzB,6BAAuB,UAAU;AACjC,UAAI,SAAS,EAAE,KAAK,IAAI,cAAc,SAAS,CAAC;AAAA,IAClD;AAAA,IACA,CAAC,UAAU;AAAA,EACb;AAEA,QAAM,eAAe,MAAM;AACzB,UAAM,MAAM,OAAO;AACnB,QAAI,CAAC,IAAK;AAEV,UAAM,aAAa,oBAAoB,SAAS,EAAE;AAClD,UAAM,gBACJ,IAAI,eAAe,IAAI,aAAa,IAAI,eAAe;AAEzD,QAAI,CAAC,iBAAiB,cAAc,UAAU,IAAI,WAAW;AAAA,IAE7D,OAAO;AACL,UAAI,eAAe;AACjB,+BAAuB,UAAU;AAAA,MACnC;AAEA,UAAI,kBAAkB,YAAY;AAChC,sBAAc,mBAAmB,EAAE,SAAS;AAAA,UAC1C,YAAY;AAAA,QACd,CAAC;AAAA,MACH;AAAA,IACF;AAEA,kBAAc,UAAU,IAAI;AAAA,EAC9B;AAEA,QAAM,YAAY,mBAAmB,MAAM;AACzC,QACE,uBAAuB,WACvB,oBAAoB,SAAS,EAAE,YAC/B;AACA,qBAAe,SAAS;AAAA,IAC1B;AAEA,iBAAa;AAAA,EACf,CAAC;AAED,QAAM,YAAY,cAA2B,CAAC,OAAO;AACnD,OAAG,iBAAiB,UAAU,YAAY;AAC1C,WAAO,MAAM;AACX,SAAG,oBAAoB,UAAU,YAAY;AAAA,IAC/C;AAAA,EACF,CAAC;AAED,sBAAoB,MAAM;AACxB,mBAAe,MAAM;AAAA,EACvB,CAAC;AAGD,oBAAkB,oBAAoB,MAAM,eAAe,MAAM,CAAC;AAElE,QAAM,gBAAgB,gBAA0B,WAAW,WAAW,MAAM;AAC5E,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../../src/primitives/thread/useThreadViewportAutoScroll.tsx"],"sourcesContent":["\"use client\";\n\nimport { useComposedRefs } from \"@radix-ui/react-compose-refs\";\nimport { RefCallback, useCallback, useRef } from \"react\";\nimport { useAssistantEvent } from \"../../context\";\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\nexport namespace useThreadViewportAutoScroll {\n export type Options = {\n autoScroll?: boolean | undefined;\n };\n}\n\nexport const useThreadViewportAutoScroll = <TElement extends HTMLElement>({\n autoScroll = true,\n}: useThreadViewportAutoScroll.Options): RefCallback<TElement> => {\n const divRef = useRef<TElement>(null);\n\n const threadViewportStore = useThreadViewportStore();\n\n const lastScrollTop = useRef<number>(0);\n\n // bug: when ScrollToBottom's button changes its disabled state, the scroll stops\n // fix: delay the state change until the scroll is done\n const isScrollingToBottomRef = useRef(false);\n\n const scrollToBottom = useCallback((behavior: ScrollBehavior) => {\n const div = divRef.current;\n if (!div) return;\n\n isScrollingToBottomRef.current = true;\n div.scrollTo({ top: div.scrollHeight, behavior });\n }, []);\n\n const handleScroll = () => {\n const div = divRef.current;\n if (!div) return;\n\n const isAtBottom = threadViewportStore.getState().isAtBottom;\n const newIsAtBottom =\n Math.abs(div.scrollHeight - div.scrollTop - div.clientHeight) < 1 ||\n div.scrollHeight <= div.clientHeight;\n\n if (!newIsAtBottom && lastScrollTop.current < div.scrollTop) {\n // ignore scroll down\n } else {\n if (newIsAtBottom) {\n isScrollingToBottomRef.current = false;\n }\n\n if (newIsAtBottom !== isAtBottom) {\n writableStore(threadViewportStore).setState({\n isAtBottom: newIsAtBottom,\n });\n }\n }\n\n lastScrollTop.current = div.scrollTop;\n };\n\n const resizeRef = useOnResizeContent(() => {\n if (\n autoScroll &&\n (isScrollingToBottomRef.current ||\n threadViewportStore.getState().isAtBottom)\n ) {\n scrollToBottom(\"instant\");\n }\n\n handleScroll();\n });\n\n const scrollRef = useManagedRef<HTMLElement>((el) => {\n el.addEventListener(\"scroll\", handleScroll);\n return () => {\n el.removeEventListener(\"scroll\", handleScroll);\n };\n });\n\n useOnScrollToBottom(() => {\n scrollToBottom(\"auto\");\n });\n\n // autoscroll on run start\n useAssistantEvent(\"thread.run-start\", () => {\n if (autoScroll) scrollToBottom(\"auto\");\n });\n\n const autoScrollRef = useComposedRefs<TElement>(resizeRef, scrollRef, divRef);\n return autoScr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