@gravity-ui/aikit 2.35.1-beta.825d8992519addb8fa910ae23de201d0ad0ec8a6.0 → 2.36.0

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 (28) hide show
  1. package/build/cjs/components/organisms/MessageList/MessageList.d.ts +3 -0
  2. package/build/cjs/components/organisms/MessageList/MessageList.js +2 -1
  3. package/build/cjs/components/organisms/MessageList/MessageList.js.map +1 -1
  4. package/build/cjs/components/organisms/MessageList/MessageList.virtualized.d.ts +1 -1
  5. package/build/cjs/components/organisms/MessageList/MessageList.virtualized.js +2 -1
  6. package/build/cjs/components/organisms/MessageList/MessageList.virtualized.js.map +1 -1
  7. package/build/cjs/hooks/useSmartScroll.d.ts +10 -2
  8. package/build/cjs/hooks/useSmartScroll.js +47 -6
  9. package/build/cjs/hooks/useSmartScroll.js.map +1 -1
  10. package/build/cjs/hooks/useVirtualStickToBottom.d.ts +3 -1
  11. package/build/cjs/hooks/useVirtualStickToBottom.js +80 -12
  12. package/build/cjs/hooks/useVirtualStickToBottom.js.map +1 -1
  13. package/build/cjs/package.json +1 -1
  14. package/build/docs/components/organisms/MessageList.md +13 -0
  15. package/build/esm/components/organisms/MessageList/MessageList.d.ts +3 -0
  16. package/build/esm/components/organisms/MessageList/MessageList.js +3 -2
  17. package/build/esm/components/organisms/MessageList/MessageList.js.map +1 -1
  18. package/build/esm/components/organisms/MessageList/MessageList.virtualized.d.ts +1 -1
  19. package/build/esm/components/organisms/MessageList/MessageList.virtualized.js +2 -1
  20. package/build/esm/components/organisms/MessageList/MessageList.virtualized.js.map +1 -1
  21. package/build/esm/hooks/useSmartScroll.d.ts +10 -2
  22. package/build/esm/hooks/useSmartScroll.js +48 -7
  23. package/build/esm/hooks/useSmartScroll.js.map +1 -1
  24. package/build/esm/hooks/useVirtualStickToBottom.d.ts +3 -1
  25. package/build/esm/hooks/useVirtualStickToBottom.js +80 -12
  26. package/build/esm/hooks/useVirtualStickToBottom.js.map +1 -1
  27. package/build/esm/package.json +1 -1
  28. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import type { HTMLAttributes, ReactNode } from 'react';
2
2
  import type { OptionsType } from '@diplodoc/transform/lib/typings';
3
3
  import type { PopupPlacement } from '@gravity-ui/uikit';
4
+ import { type MessageListScrollPositionRef } from "../../../hooks/index.js";
4
5
  import type { MarkdownRendererMdxOptions, MermaidOptions } from "../../../markdown/types.js";
5
6
  import { ChatStatus } from "../../../types/index.js";
6
7
  import type { DefaultMessageAction, MessageExtraInfoComponent, TAssistantMessage, TChatMessage, TMessageContent, TMessageMetadata, TUserMessage } from "../../../types/messages.js";
@@ -48,6 +49,8 @@ export type MdxProps<TContent extends TMessageContent = never> = {
48
49
  };
49
50
  export type MessageListProps<TContent extends TMessageContent = never> = {
50
51
  messages: TChatMessage<TContent, TMessageMetadata>[];
52
+ /** Host-owned reading position. Use a separate ref and list key for each conversation. */
53
+ scrollPositionRef?: MessageListScrollPositionRef;
51
54
  /** Render message-local content before assistant actions and timestamp. */
52
55
  renderAssistantFooter?: (message: TAssistantMessage<TContent, TMessageMetadata>) => ReactNode;
53
56
  /** Delegate scrolling to a surrounding layout such as ChatContentV2. */
@@ -25,7 +25,7 @@ function MessageList(props) {
25
25
  }
26
26
  return (0, jsx_runtime_1.jsx)(PlainMessageList, Object.assign({}, props));
27
27
  }
28
- function PlainMessageList({ messages, scrollMode = 'internal', messageRendererRegistry, thinkingMessageView, transformOptions, shouldParseIncompleteMarkdown, mermaidOptions, openMarkdownLinksInNewTab, mdxProps, showActionsOnHover, showTimestamp, showAvatar, userActions, assistantActions, renderAssistantFooter, userExtraInfo: UserExtraInfo, assistantExtraInfo: AssistantExtraInfo, loaderStatuses = ['submitted', 'streaming_loading'], className, qa, status, errorMessage, loaderMessage, withLoaderShimmer, onRetry, hasPreviousMessages = false, onLoadPreviousMessages, ratingBlockProps, actionPopupProps, footerContent, }) {
28
+ function PlainMessageList({ messages, scrollPositionRef, scrollMode = 'internal', messageRendererRegistry, thinkingMessageView, transformOptions, shouldParseIncompleteMarkdown, mermaidOptions, openMarkdownLinksInNewTab, mdxProps, showActionsOnHover, showTimestamp, showAvatar, userActions, assistantActions, renderAssistantFooter, userExtraInfo: UserExtraInfo, assistantExtraInfo: AssistantExtraInfo, loaderStatuses = ['submitted', 'streaming_loading'], className, qa, status, errorMessage, loaderMessage, withLoaderShimmer, onRetry, hasPreviousMessages = false, onLoadPreviousMessages, ratingBlockProps, actionPopupProps, footerContent, }) {
29
29
  const isStreaming = status === 'streaming' || status === 'streaming_loading';
30
30
  const isSubmitted = status === 'submitted';
31
31
  const showLoader = status && loaderStatuses.includes(status);
@@ -35,6 +35,7 @@ function PlainMessageList({ messages, scrollMode = 'internal', messageRendererRe
35
35
  isStreaming: isStreaming || isSubmitted,
36
36
  messagesCount: messages.length,
37
37
  status,
38
+ scrollPositionRef,
38
39
  });
39
40
  // Preserve scroll position when older messages are loaded
40
41
  (0, hooks_1.useScrollPreservation)(containerRef, messages.length);
@@ -1 +1 @@
1
- {"version":3,"file":"MessageList.js","sourceRoot":"../../../../../src","sources":["components/organisms/MessageList/MessageList.tsx"],"names":[],"mappings":";;;AA6HA,kCASC;;AAjID,mDAAqE;AAYrE,6CAAwC;AAGxC,sFAAwE;AACxE,wDAA0C;AAG1C,kDAA0C;AAC1C,0EAAiE;AACjE,8DAAsD;AACtD,4CAAiE;AAEjE,6BAA4B;AAE5B,MAAM,CAAC,GAAG,IAAA,UAAK,EAAC,cAAc,CAAC,CAAC;AAEhC,IAAY,aAGX;AAHD,WAAY,aAAa;IACrB,sCAAqB,CAAA;IACrB,mDAAkC,CAAA;AACtC,CAAC,EAHW,aAAa,6BAAb,aAAa,QAGxB;AAyFD,SAAgB,WAAW,CACvB,KAAiC;IAEjC,wFAAwF;IACxF,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QACpB,OAAO,uBAAC,gDAAsB,oBAAe,KAAK,EAAI,CAAC;IAC3D,CAAC;IAED,O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AAR,QAAQ,uBAAR,QAAQ,CAAE,aAAa,EACtC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,WAAW,EACxB,gBAAgB,EAAE,gBAAgB,EAClC,qBAAqB,EAAE,qBAAqB,EAC5C,aAAa,EAAE,aAAa,EAC5B,kBAAkB,EAAE,kBAAkB,EACtC,aAAa,EAAE,iBAAiB,IAvB3B,OAAO,CAAC,EAAE,IAAI,WAAW,KAAK,EAAE,CAwBvC,CACL,CAAC,GACA,EACN,uBAAC,qCAAiB,IACd,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,YAAY,EAC1B,aAAa,EAAE,aAAa,EAC5B,iBAAiB,EAAE,iBAAiB,EACpC,OAAO,EAAE,OAAO,EAChB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,EAAE,gBAAgB,EAClC,EAAE,EAAE,EAAE,EACN,eAAe,EAAE,eAAe,EAChC,UAAU,EAAE,UAAU,EACtB,iBAAiB,EAAE,qBAAqB,GAC1C,EACD,aAAa,KAAK,SAAS,IAAI,aAAa,KAAK,IAAI,IAAI,CACtD,gCAAK,SAAS,EAAE,CAAC,CAAC,gBAAgB,CAAC,YAAG,aAAa,GAAO,CAC7D,IACC,CACT,CAAC;AACN,CAAC","sourcesContent":["import type {HTMLAttributes, ReactNode} from 'react';\n\nimport type {OptionsType} from '@diplodoc/transform/lib/typings';\nimport type {PopupPlacement} from '@gravity-ui/uikit';\n\nimport {useScrollPreservation, useSmartScroll} from '../../../hooks';\nimport type {MarkdownRendererMdxOptions, MermaidOptions} from '../../../markdown/types';\nimport {ChatStatus} from '../../../types';\nimport type {\n DefaultMessageAction,\n MessageExtraInfoComponent,\n TAssistantMessage,\n TChatMessage,\n TMessageContent,\n TMessageMetadata,\n TUserMessage,\n} from '../../../types/messages';\nimport {block} from '../../../utils/cn';\nimport {type MessageRendererRegistry} from '../../../utils/messageTypeRegistry';\nimport {AlertProps} from '../../atoms/Alert';\nimport {IntersectionContainer} from '../../atoms/IntersectionContainer';\nimport {Loader} from '../../atoms/Loader';\nimport {type RatingBlockProps} from '../../molecules/RatingBlock/RatingBlock';\n\nimport {MessageItem} from './MessageItem';\nimport {VirtualizedMessageList} from './MessageList.virtualized';\nimport {MessageListFooter} from './MessageListFooter';\nimport {isActionPopupOpenForMessage, usePopup} from './usePopup';\n\nimport './MessageList.scss';\n\nconst b = block('message-list');\n\nexport enum MessageListQa {\n Root = 'message-list',\n Messages = 'message-list-messages',\n}\n\n/** Configuration for action popup behavior */\nexport interface MessageListActionPopupConfig {\n /** Override title for all popups (overrides action-specific title) */\n title?: string;\n /** Override subtitle for all popups (overrides action-specific subtitle) */\n subtitle?: string;\n /** Override placement for all popups (overrides action-specific placement) */\n placement?: PopupPlacement;\n /** Additional CSS class for popup */\n className?: string;\n /** QA/test identifier for popup */\n qa?: string;\n}\n\n/**\n * Grouped MDX/markdown rendering props exposed as a single object on `MessageList` and\n * `ChatContainer`. They are destructured back into individual props before being handed to\n * the low-level `MessageItem` renderer.\n */\nexport type MdxProps<TContent extends TMessageContent = never> = {\n /** Options for rendering MDX (`@diplodoc/mdx-extension`) in the default message renderers */\n mdxOptions?: MarkdownRendererMdxOptions;\n /**\n * Resolves the extra props forwarded to the root container `div` of each rendered\n * markdown block. Called with the concrete message so handlers (e.g. `onClick`) can\n * identify the message they belong to.\n */\n getMarkdownExtraProps?: (\n message: TChatMessage<TContent, TMessageMetadata>,\n ) => HTMLAttributes<HTMLDivElement> | undefined;\n /**\n * Resolves the per-message value exposed to MDX components (via `useMdxContext`).\n * Called with the concrete message so embedded MDX components can read data\n * unique to the message they belong to.\n */\n getMdxContext?: (\n message: TChatMessage<TContent, TMessageMetadata>,\n ) => Record<string, unknown> | undefined;\n};\n\nexport type MessageListProps<TContent extends TMessageContent = never> = {\n messages: TChatMessage<TContent, TMessageMetadata>[];\n /** Render message-local content before assistant actions and timestamp. */\n renderAssistantFooter?: (message: TAssistantMessage<TContent, TMessageMetadata>) => ReactNode;\n /** Delegate scrolling to a surrounding layout such as ChatContentV2. */\n scrollMode?: 'internal' | 'external';\n status?: ChatStatus;\n errorMessage?: AlertProps;\n loaderMessage?: string;\n withLoaderShimmer?: boolean;\n onRetry?: () => void;\n messageRendererRegistry?: MessageRendererRegistry;\n thinkingMessageView?: 'default' | 'grouped';\n transformOptions?: OptionsType;\n shouldParseIncompleteMarkdown?: boolean;\n mermaidOptions?: MermaidOptions;\n openMarkdownLinksInNewTab?: boolean;\n /** Grouped MDX/markdown rendering props (`mdxOptions`, `getMarkdownExtraProps`, `getMdxContext`). */\n mdxProps?: MdxProps<TContent>;\n showActionsOnHover?: boolean;\n showTimestamp?: boolean;\n showAvatar?: boolean;\n userActions?: DefaultMessageAction<TUserMessage<TMessageMetadata>>[];\n assistantActions?: DefaultMessageAction<TAssistantMessage<TContent, TMessageMetadata>>[];\n /** Component rendered alongside action buttons for each user message. Receives message as prop. */\n userExtraInfo?: MessageExtraInfoComponent<TUserMessage<TMessageMetadata>>;\n /** Component rendered alongside action buttons for each assistant message. Receives message as prop. */\n assistantExtraInfo?: MessageExtraInfoComponent<TAssistantMessage<TContent, TMessageMetadata>>;\n /** Array of chat statuses that should display the loader */\n loaderStatuses?: ChatStatus[];\n className?: string;\n qa?: string;\n hasPreviousMessages?: boolean;\n onLoadPreviousMessages?: () => void;\n /** Rating block configuration (for CSAT or other feedback use cases) - renders after messages list */\n ratingBlockProps?: RatingBlockProps;\n /** Action popup configuration - applies to all action popups */\n actionPopupProps?: MessageListActionPopupConfig;\n /**\n * Enable windowed rendering via react-window for very large histories.\n * Off by default to preserve the existing rendering/scroll behavior.\n */\n virtualized?: boolean;\n /** Last scrollable row rendered after all messages. */\n footerContent?: React.ReactNode;\n};\n\nexport function MessageList<TContent extends TMessageContent = never>(\n props: MessageListProps<TContent>,\n) {\n // Opt-in virtualized path - keeps the proven non-virtualized rendering untouched below.\n if (props.virtualized) {\n return <VirtualizedMessageList<TContent> {...props} />;\n }\n\n return <PlainMessageList<TContent> {...props} />;\n}\n\nfunction PlainMessageList<TContent extends TMessageContent = never>({\n messages,\n scrollMode = 'internal',\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxProps,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n renderAssistantFooter,\n userExtraInfo: UserExtraInfo,\n assistantExtraInfo: AssistantExtraInfo,\n loaderStatuses = ['submitted', 'streaming_loading'],\n className,\n qa,\n status,\n errorMessage,\n loaderMessage,\n withLoaderShimmer,\n onRetry,\n hasPreviousMessages = false,\n onLoadPreviousMessages,\n ratingBlockProps,\n actionPopupProps,\n footerContent,\n}: MessageListProps<TContent>) {\n const isStreaming = status === 'streaming' || status === 'streaming_loading';\n const isSubmitted = status === 'submitted';\n const showLoader = status && loaderStatuses.includes(status);\n\n // Use popup hook for managing popup state\n const {popupState, handleActionPopup, handlePopupOpenChange, showActionPopup} = usePopup<\n TContent,\n TMessageMetadata\n >();\n\n const {containerRef} = useSmartScroll<HTMLDivElement>({\n isStreaming: isStreaming || isSubmitted,\n messagesCount: messages.length,\n status,\n });\n\n // Preserve scroll position when older messages are loaded\n useScrollPreservation(containerRef, messages.length);\n\n const isNotCompleted = isSubmitted || isStreaming;\n\n return (\n <div\n ref={scrollMode === 'internal' ? containerRef : undefined}\n style={scrollMode === 'external' ? {overflow: 'visible', flex: 'none'} : undefined}\n className={b(null, className)}\n data-qa={qa ?? MessageListQa.Root}\n >\n {hasPreviousMessages && (\n <IntersectionContainer\n onIntersect={onLoadPreviousMessages}\n className={b('load-trigger')}\n >\n <Loader view=\"loading\" />\n </IntersectionContainer>\n )}\n <div className={b('messages')} data-qa={qa ? `${qa}-messages` : MessageListQa.Messages}>\n {messages.map((message, index) => (\n <MessageItem<TContent>\n key={message.id || `message-${index}`}\n message={message}\n suppressActions={index === messages.length - 1 && isNotCompleted}\n showActionsOnHover={\n showActionsOnHover &&\n !isActionPopupOpenForMessage(popupState, message.id)\n }\n messageRendererRegistry={messageRendererRegistry}\n thinkingMessageView={thinkingMessageView}\n transformOptions={transformOptions}\n shouldParseIncompleteMarkdown={shouldParseIncompleteMarkdown}\n mermaidOptions={mermaidOptions}\n openMarkdownLinksInNewTab={openMarkdownLinksInNewTab}\n mdxOptions={mdxProps?.mdxOptions}\n getMarkdownExtraProps={mdxProps?.getMarkdownExtraProps}\n getMdxContext={mdxProps?.getMdxContext}\n showTimestamp={showTimestamp}\n showAvatar={showAvatar}\n userActions={userActions}\n assistantActions={assistantActions}\n renderAssistantFooter={renderAssistantFooter}\n userExtraInfo={UserExtraInfo}\n assistantExtraInfo={AssistantExtraInfo}\n onActionPopup={handleActionPopup}\n />\n ))}\n </div>\n <MessageListFooter\n showLoader={showLoader}\n status={status}\n errorMessage={errorMessage}\n loaderMessage={loaderMessage}\n withLoaderShimmer={withLoaderShimmer}\n onRetry={onRetry}\n ratingBlockProps={ratingBlockProps}\n actionPopupProps={actionPopupProps}\n qa={qa}\n showActionPopup={showActionPopup}\n popupState={popupState}\n onPopupOpenChange={handlePopupOpenChange}\n />\n {footerContent !== undefined && footerContent !== null && (\n <div className={b('footer-content')}>{footerContent}</div>\n )}\n </div>\n );\n}\n"]}
1
+ {"version":3,"file":"MessageList.js","sourceRoot":"../../../../../src","sources":["components/organisms/MessageList/MessageList.tsx"],"names":[],"mappings":";;;AAmIA,kCASC;;AAvID,mDAIwB;AAYxB,6CAAwC;AAGxC,sFAAwE;AACxE,wDAA0C;AAG1C,kDAA0C;AAC1C,0EAAiE;AACjE,8DAAsD;AACtD,4CAAiE;AAEjE,6BAA4B;AAE5B,MAAM,CAAC,GAAG,IAAA,UAAK,EAAC,cAAc,CAAC,CAAC;AAEhC,IAAY,aAGX;AAHD,WAAY,aAAa;IACrB,sCAAqB,CAAA;IACrB,mDAAkC,CAAA;AACtC,CAAC,EAHW,aAAa,6BAAb,aAAa,QAGxB;AA2F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9B,yBAAyB,EAAE,yBAAyB,EACpD,UAAU,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,UAAU,EAChC,qBAAqB,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,qBAAqB,EACtD,aAAa,EAAE,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,aAAa,EACtC,aAAa,EAAE,aAAa,EAC5B,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,WAAW,EACxB,gBAAgB,EAAE,gBAAgB,EAClC,qBAAqB,EAAE,qBAAqB,EAC5C,aAAa,EAAE,aAAa,EAC5B,kBAAkB,EAAE,kBAAkB,EACtC,aAAa,EAAE,iBAAiB,IAvB3B,OAAO,CAAC,EAAE,IAAI,WAAW,KAAK,EAAE,CAwBvC,CACL,CAAC,GACA,EACN,uBAAC,qCAAiB,IACd,UAAU,EAAE,UAAU,EACtB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,YAAY,EAC1B,aAAa,EAAE,aAAa,EAC5B,iBAAiB,EAAE,iBAAiB,EACpC,OAAO,EAAE,OAAO,EAChB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,EAAE,gBAAgB,EAClC,EAAE,EAAE,EAAE,EACN,eAAe,EAAE,eAAe,EAChC,UAAU,EAAE,UAAU,EACtB,iBAAiB,EAAE,qBAAqB,GAC1C,EACD,aAAa,KAAK,SAAS,IAAI,aAAa,KAAK,IAAI,IAAI,CACtD,gCAAK,SAAS,EAAE,CAAC,CAAC,gBAAgB,CAAC,YAAG,aAAa,GAAO,CAC7D,IACC,CACT,CAAC;AACN,CAAC","sourcesContent":["import type {HTMLAttributes, ReactNode} from 'react';\n\nimport type {OptionsType} from '@diplodoc/transform/lib/typings';\nimport type {PopupPlacement} from '@gravity-ui/uikit';\n\nimport {\n type MessageListScrollPositionRef,\n useScrollPreservation,\n useSmartScroll,\n} from '../../../hooks';\nimport type {MarkdownRendererMdxOptions, MermaidOptions} from '../../../markdown/types';\nimport {ChatStatus} from '../../../types';\nimport type {\n DefaultMessageAction,\n MessageExtraInfoComponent,\n TAssistantMessage,\n TChatMessage,\n TMessageContent,\n TMessageMetadata,\n TUserMessage,\n} from '../../../types/messages';\nimport {block} from '../../../utils/cn';\nimport {type MessageRendererRegistry} from '../../../utils/messageTypeRegistry';\nimport {AlertProps} from '../../atoms/Alert';\nimport {IntersectionContainer} from '../../atoms/IntersectionContainer';\nimport {Loader} from '../../atoms/Loader';\nimport {type RatingBlockProps} from '../../molecules/RatingBlock/RatingBlock';\n\nimport {MessageItem} from './MessageItem';\nimport {VirtualizedMessageList} from './MessageList.virtualized';\nimport {MessageListFooter} from './MessageListFooter';\nimport {isActionPopupOpenForMessage, usePopup} from './usePopup';\n\nimport './MessageList.scss';\n\nconst b = block('message-list');\n\nexport enum MessageListQa {\n Root = 'message-list',\n Messages = 'message-list-messages',\n}\n\n/** Configuration for action popup behavior */\nexport interface MessageListActionPopupConfig {\n /** Override title for all popups (overrides action-specific title) */\n title?: string;\n /** Override subtitle for all popups (overrides action-specific subtitle) */\n subtitle?: string;\n /** Override placement for all popups (overrides action-specific placement) */\n placement?: PopupPlacement;\n /** Additional CSS class for popup */\n className?: string;\n /** QA/test identifier for popup */\n qa?: string;\n}\n\n/**\n * Grouped MDX/markdown rendering props exposed as a single object on `MessageList` and\n * `ChatContainer`. They are destructured back into individual props before being handed to\n * the low-level `MessageItem` renderer.\n */\nexport type MdxProps<TContent extends TMessageContent = never> = {\n /** Options for rendering MDX (`@diplodoc/mdx-extension`) in the default message renderers */\n mdxOptions?: MarkdownRendererMdxOptions;\n /**\n * Resolves the extra props forwarded to the root container `div` of each rendered\n * markdown block. Called with the concrete message so handlers (e.g. `onClick`) can\n * identify the message they belong to.\n */\n getMarkdownExtraProps?: (\n message: TChatMessage<TContent, TMessageMetadata>,\n ) => HTMLAttributes<HTMLDivElement> | undefined;\n /**\n * Resolves the per-message value exposed to MDX components (via `useMdxContext`).\n * Called with the concrete message so embedded MDX components can read data\n * unique to the message they belong to.\n */\n getMdxContext?: (\n message: TChatMessage<TContent, TMessageMetadata>,\n ) => Record<string, unknown> | undefined;\n};\n\nexport type MessageListProps<TContent extends TMessageContent = never> = {\n messages: TChatMessage<TContent, TMessageMetadata>[];\n /** Host-owned reading position. Use a separate ref and list key for each conversation. */\n scrollPositionRef?: MessageListScrollPositionRef;\n /** Render message-local content before assistant actions and timestamp. */\n renderAssistantFooter?: (message: TAssistantMessage<TContent, TMessageMetadata>) => ReactNode;\n /** Delegate scrolling to a surrounding layout such as ChatContentV2. */\n scrollMode?: 'internal' | 'external';\n status?: ChatStatus;\n errorMessage?: AlertProps;\n loaderMessage?: string;\n withLoaderShimmer?: boolean;\n onRetry?: () => void;\n messageRendererRegistry?: MessageRendererRegistry;\n thinkingMessageView?: 'default' | 'grouped';\n transformOptions?: OptionsType;\n shouldParseIncompleteMarkdown?: boolean;\n mermaidOptions?: MermaidOptions;\n openMarkdownLinksInNewTab?: boolean;\n /** Grouped MDX/markdown rendering props (`mdxOptions`, `getMarkdownExtraProps`, `getMdxContext`). */\n mdxProps?: MdxProps<TContent>;\n showActionsOnHover?: boolean;\n showTimestamp?: boolean;\n showAvatar?: boolean;\n userActions?: DefaultMessageAction<TUserMessage<TMessageMetadata>>[];\n assistantActions?: DefaultMessageAction<TAssistantMessage<TContent, TMessageMetadata>>[];\n /** Component rendered alongside action buttons for each user message. Receives message as prop. */\n userExtraInfo?: MessageExtraInfoComponent<TUserMessage<TMessageMetadata>>;\n /** Component rendered alongside action buttons for each assistant message. Receives message as prop. */\n assistantExtraInfo?: MessageExtraInfoComponent<TAssistantMessage<TContent, TMessageMetadata>>;\n /** Array of chat statuses that should display the loader */\n loaderStatuses?: ChatStatus[];\n className?: string;\n qa?: string;\n hasPreviousMessages?: boolean;\n onLoadPreviousMessages?: () => void;\n /** Rating block configuration (for CSAT or other feedback use cases) - renders after messages list */\n ratingBlockProps?: RatingBlockProps;\n /** Action popup configuration - applies to all action popups */\n actionPopupProps?: MessageListActionPopupConfig;\n /**\n * Enable windowed rendering via react-window for very large histories.\n * Off by default to preserve the existing rendering/scroll behavior.\n */\n virtualized?: boolean;\n /** Last scrollable row rendered after all messages. */\n footerContent?: React.ReactNode;\n};\n\nexport function MessageList<TContent extends TMessageContent = never>(\n props: MessageListProps<TContent>,\n) {\n // Opt-in virtualized path - keeps the proven non-virtualized rendering untouched below.\n if (props.virtualized) {\n return <VirtualizedMessageList<TContent> {...props} />;\n }\n\n return <PlainMessageList<TContent> {...props} />;\n}\n\nfunction PlainMessageList<TContent extends TMessageContent = never>({\n messages,\n scrollPositionRef,\n scrollMode = 'internal',\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxProps,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n renderAssistantFooter,\n userExtraInfo: UserExtraInfo,\n assistantExtraInfo: AssistantExtraInfo,\n loaderStatuses = ['submitted', 'streaming_loading'],\n className,\n qa,\n status,\n errorMessage,\n loaderMessage,\n withLoaderShimmer,\n onRetry,\n hasPreviousMessages = false,\n onLoadPreviousMessages,\n ratingBlockProps,\n actionPopupProps,\n footerContent,\n}: MessageListProps<TContent>) {\n const isStreaming = status === 'streaming' || status === 'streaming_loading';\n const isSubmitted = status === 'submitted';\n const showLoader = status && loaderStatuses.includes(status);\n\n // Use popup hook for managing popup state\n const {popupState, handleActionPopup, handlePopupOpenChange, showActionPopup} = usePopup<\n TContent,\n TMessageMetadata\n >();\n\n const {containerRef} = useSmartScroll<HTMLDivElement>({\n isStreaming: isStreaming || isSubmitted,\n messagesCount: messages.length,\n status,\n scrollPositionRef,\n });\n\n // Preserve scroll position when older messages are loaded\n useScrollPreservation(containerRef, messages.length);\n\n const isNotCompleted = isSubmitted || isStreaming;\n\n return (\n <div\n ref={scrollMode === 'internal' ? containerRef : undefined}\n style={scrollMode === 'external' ? {overflow: 'visible', flex: 'none'} : undefined}\n className={b(null, className)}\n data-qa={qa ?? MessageListQa.Root}\n >\n {hasPreviousMessages && (\n <IntersectionContainer\n onIntersect={onLoadPreviousMessages}\n className={b('load-trigger')}\n >\n <Loader view=\"loading\" />\n </IntersectionContainer>\n )}\n <div className={b('messages')} data-qa={qa ? `${qa}-messages` : MessageListQa.Messages}>\n {messages.map((message, index) => (\n <MessageItem<TContent>\n key={message.id || `message-${index}`}\n message={message}\n suppressActions={index === messages.length - 1 && isNotCompleted}\n showActionsOnHover={\n showActionsOnHover &&\n !isActionPopupOpenForMessage(popupState, message.id)\n }\n messageRendererRegistry={messageRendererRegistry}\n thinkingMessageView={thinkingMessageView}\n transformOptions={transformOptions}\n shouldParseIncompleteMarkdown={shouldParseIncompleteMarkdown}\n mermaidOptions={mermaidOptions}\n openMarkdownLinksInNewTab={openMarkdownLinksInNewTab}\n mdxOptions={mdxProps?.mdxOptions}\n getMarkdownExtraProps={mdxProps?.getMarkdownExtraProps}\n getMdxContext={mdxProps?.getMdxContext}\n showTimestamp={showTimestamp}\n showAvatar={showAvatar}\n userActions={userActions}\n assistantActions={assistantActions}\n renderAssistantFooter={renderAssistantFooter}\n userExtraInfo={UserExtraInfo}\n assistantExtraInfo={AssistantExtraInfo}\n onActionPopup={handleActionPopup}\n />\n ))}\n </div>\n <MessageListFooter\n showLoader={showLoader}\n status={status}\n errorMessage={errorMessage}\n loaderMessage={loaderMessage}\n withLoaderShimmer={withLoaderShimmer}\n onRetry={onRetry}\n ratingBlockProps={ratingBlockProps}\n actionPopupProps={actionPopupProps}\n qa={qa}\n showActionPopup={showActionPopup}\n popupState={popupState}\n onPopupOpenChange={handlePopupOpenChange}\n />\n {footerContent !== undefined && footerContent !== null && (\n <div className={b('footer-content')}>{footerContent}</div>\n )}\n </div>\n );\n}\n"]}
@@ -1,3 +1,3 @@
1
1
  import type { TMessageContent } from "../../../types/messages.js";
2
2
  import { type MessageListProps } from "./MessageList.js";
3
- export declare function VirtualizedMessageList<TContent extends TMessageContent = never>({ messages, messageRendererRegistry, thinkingMessageView, transformOptions, shouldParseIncompleteMarkdown, mermaidOptions, openMarkdownLinksInNewTab, mdxProps, showActionsOnHover, showTimestamp, showAvatar, userActions, assistantActions, renderAssistantFooter, userExtraInfo: UserExtraInfo, assistantExtraInfo: AssistantExtraInfo, loaderStatuses, className, qa, status, errorMessage, loaderMessage, withLoaderShimmer, onRetry, hasPreviousMessages, onLoadPreviousMessages, ratingBlockProps, actionPopupProps, footerContent, }: MessageListProps<TContent>): import("react/jsx-runtime").JSX.Element;
3
+ export declare function VirtualizedMessageList<TContent extends TMessageContent = never>({ messages, scrollPositionRef, messageRendererRegistry, thinkingMessageView, transformOptions, shouldParseIncompleteMarkdown, mermaidOptions, openMarkdownLinksInNewTab, mdxProps, showActionsOnHover, showTimestamp, showAvatar, userActions, assistantActions, renderAssistantFooter, userExtraInfo: UserExtraInfo, assistantExtraInfo: AssistantExtraInfo, loaderStatuses, className, qa, status, errorMessage, loaderMessage, withLoaderShimmer, onRetry, hasPreviousMessages, onLoadPreviousMessages, ratingBlockProps, actionPopupProps, footerContent, }: MessageListProps<TContent>): import("react/jsx-runtime").JSX.Element;
@@ -34,7 +34,7 @@ function MessageRow({ index, style, ariaAttributes, messages, isNotCompleted, he
34
34
  return ((0, jsx_runtime_1.jsx)("div", Object.assign({ style: style }, ariaAttributes, { children: (0, jsx_runtime_1.jsx)("div", { className: b('row'), "data-message-id": message.id, children: (0, jsx_runtime_1.jsx)(MessageItem_1.MessageItem, Object.assign({ message: message, suppressActions: isLast && isNotCompleted }, config, { showActionsOnHover: Boolean(config.showActionsOnHover) &&
35
35
  !(0, usePopup_1.isActionPopupOpenForMessage)(popupState, message.id) })) }) })));
36
36
  }
37
- function VirtualizedMessageList({ messages, messageRendererRegistry, thinkingMessageView, transformOptions, shouldParseIncompleteMarkdown, mermaidOptions, openMarkdownLinksInNewTab, mdxProps, showActionsOnHover, showTimestamp, showAvatar, userActions, assistantActions, renderAssistantFooter, userExtraInfo: UserExtraInfo, assistantExtraInfo: AssistantExtraInfo, loaderStatuses = ['submitted', 'streaming_loading'], className, qa, status, errorMessage, loaderMessage, withLoaderShimmer, onRetry, hasPreviousMessages = false, onLoadPreviousMessages, ratingBlockProps, actionPopupProps, footerContent, }) {
37
+ function VirtualizedMessageList({ messages, scrollPositionRef, messageRendererRegistry, thinkingMessageView, transformOptions, shouldParseIncompleteMarkdown, mermaidOptions, openMarkdownLinksInNewTab, mdxProps, showActionsOnHover, showTimestamp, showAvatar, userActions, assistantActions, renderAssistantFooter, userExtraInfo: UserExtraInfo, assistantExtraInfo: AssistantExtraInfo, loaderStatuses = ['submitted', 'streaming_loading'], className, qa, status, errorMessage, loaderMessage, withLoaderShimmer, onRetry, hasPreviousMessages = false, onLoadPreviousMessages, ratingBlockProps, actionPopupProps, footerContent, }) {
38
38
  var _a;
39
39
  const isStreaming = status === 'streaming' || status === 'streaming_loading';
40
40
  const isSubmitted = status === 'submitted';
@@ -105,6 +105,7 @@ function VirtualizedMessageList({ messages, messageRendererRegistry, thinkingMes
105
105
  const rowHeight = (0, react_window_1.useDynamicRowHeight)({ defaultRowHeight: DEFAULT_ROW_HEIGHT });
106
106
  const { listRef, isPrepending } = (0, hooks_1.useVirtualStickToBottom)({
107
107
  rowCount,
108
+ scrollPositionRef,
108
109
  isStreaming: isNotCompleted,
109
110
  status,
110
111
  messagesCount: messages.length,
@@ -1 +1 @@
1
- {"version":3,"file":"MessageList.virtualized.js","sourceRoot":"../../../../../src","sources":["components/organisms/MessageList/MessageList.virtualized.tsx"],"names":[],"mappings":";;AAgGA,wDAyLC;;AAzRD,iCAA2C;AAE3C,+CAA+E;AAE/E,mDAAuD;AAEvD,6CAAwC;AACxC,sFAAwE;AACxE,wDAA0C;AAE1C,kDAAkE;AAClE,kDAAmE;AACnE,8DAAsD;AACtD,4CAAkF;AAElF,MAAM,CAAC,GAAG,IAAA,UAAK,EAAC,cAAc,CAAC,CAAC;AAEhC,8EAA8E;AAC9E,MAAM,kBAAkB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UAAU,EAAE,UAAU,EACtB,iBAAiB,EAAE,qBAAqB,GAC1C,IACA,CACT,CAAC;AACN,CAAC","sourcesContent":["import {useCallback, useMemo} from 'react';\n\nimport {List, type RowComponentProps, useDynamicRowHeight} from 'react-window';\n\nimport {useVirtualStickToBottom} from '../../../hooks';\nimport type {TChatMessage, TMessageContent, TMessageMetadata} from '../../../types/messages';\nimport {block} from '../../../utils/cn';\nimport {IntersectionContainer} from '../../atoms/IntersectionContainer';\nimport {Loader} from '../../atoms/Loader';\n\nimport {MessageItem, type MessageItemConfig} from './MessageItem';\nimport {type MessageListProps, MessageListQa} from './MessageList';\nimport {MessageListFooter} from './MessageListFooter';\nimport {type PopupState, isActionPopupOpenForMessage, usePopup} from './usePopup';\n\nconst b = block('message-list');\n\n/** Estimated row height used before a row has been measured (and for SSR). */\nconst DEFAULT_ROW_HEIGHT = 80;\n/** Extra rows rendered outside the viewport to reduce flicker while scrolling. */\nconst OVERSCAN_COUNT = 5;\n\ntype MessageRowProps = {\n messages: TChatMessage<TMessageContent, TMessageMetadata>[];\n /** Whether the current response is still streaming/submitted (hide actions on last row). */\n isNotCompleted: boolean;\n /** Number of non-message rows before the messages (the load-more trigger). */\n headerOffset: number;\n hasPreviousMessages: boolean;\n onLoadPreviousMessages?: () => void;\n popupState: PopupState;\n config: MessageItemConfig<TMessageContent>;\n footerContent?: React.ReactNode;\n};\n\nfunction MessageRow({\n index,\n style,\n ariaAttributes,\n messages,\n isNotCompleted,\n headerOffset,\n hasPreviousMessages,\n onLoadPreviousMessages,\n popupState,\n config,\n footerContent,\n}: RowComponentProps<MessageRowProps>) {\n // Header row: the \"load previous messages\" intersection trigger.\n if (hasPreviousMessages && index === 0) {\n return (\n <div style={style} {...ariaAttributes}>\n <IntersectionContainer\n onIntersect={onLoadPreviousMessages}\n className={b('load-trigger')}\n >\n <Loader view=\"loading\" />\n </IntersectionContainer>\n </div>\n );\n }\n\n const messageIndex = index - headerOffset;\n const message = messages[messageIndex];\n if (!message) {\n if (messageIndex === messages.length && footerContent !== undefined) {\n return (\n <div style={style} {...ariaAttributes}>\n <div className={b('footer-content')}>{footerContent}</div>\n </div>\n );\n }\n return <div style={style} {...ariaAttributes} />;\n }\n\n const isLast = messageIndex === messages.length - 1;\n\n return (\n <div style={style} {...ariaAttributes}>\n {/* data-message-id lets useVirtualStickToBottom anchor scroll position to a specific\n rendered row (robust to off-screen height estimation) when older messages load. */}\n <div className={b('row')} data-message-id={message.id}>\n <MessageItem\n message={message}\n suppressActions={isLast && isNotCompleted}\n {...config}\n showActionsOnHover={\n Boolean(config.showActionsOnHover) &&\n !isActionPopupOpenForMessage(popupState, message.id)\n }\n />\n </div>\n </div>\n );\n}\n\nexport function VirtualizedMessageList<TContent extends TMessageContent = never>({\n messages,\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxProps,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n renderAssistantFooter,\n userExtraInfo: UserExtraInfo,\n assistantExtraInfo: AssistantExtraInfo,\n loaderStatuses = ['submitted', 'streaming_loading'],\n className,\n qa,\n status,\n errorMessage,\n loaderMessage,\n withLoaderShimmer,\n onRetry,\n hasPreviousMessages = false,\n onLoadPreviousMessages,\n ratingBlockProps,\n actionPopupProps,\n footerContent,\n}: MessageListProps<TContent>) {\n const isStreaming = status === 'streaming' || status === 'streaming_loading';\n const isSubmitted = status === 'submitted';\n const isNotCompleted = isSubmitted || isStreaming;\n const showLoader = status && loaderStatuses.includes(status);\n\n const {popupState, handleActionPopup, handlePopupOpenChange, showActionPopup} = usePopup<\n TContent,\n TMessageMetadata\n >();\n\n const headerOffset = hasPreviousMessages ? 1 : 0;\n const hasFooterContent = footerContent !== undefined && footerContent !== null;\n const footerOffset = hasFooterContent ? 1 : 0;\n const rowCount = messages.length + headerOffset + footerOffset;\n\n const config = useMemo<MessageItemConfig<TContent>>(\n () => ({\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxOptions: mdxProps?.mdxOptions,\n getMarkdownExtraProps: mdxProps?.getMarkdownExtraProps,\n getMdxContext: mdxProps?.getMdxContext,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n renderAssistantFooter,\n userExtraInfo: UserExtraInfo,\n assistantExtraInfo: AssistantExtraInfo,\n onActionPopup: handleActionPopup,\n }),\n [\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxProps,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n UserExtraInfo,\n AssistantExtraInfo,\n renderAssistantFooter,\n handleActionPopup,\n ],\n );\n\n const rowProps = useMemo<MessageRowProps>(\n () => ({\n messages: messages as TChatMessage<TMessageContent, TMessageMetadata>[],\n isNotCompleted,\n headerOffset,\n hasPreviousMessages,\n onLoadPreviousMessages,\n popupState,\n config: config as unknown as MessageItemConfig<TMessageContent>,\n footerContent: hasFooterContent ? footerContent : undefined,\n }),\n [\n messages,\n isNotCompleted,\n headerOffset,\n hasPreviousMessages,\n onLoadPreviousMessages,\n popupState,\n config,\n hasFooterContent,\n footerContent,\n ],\n );\n\n const rowHeight = useDynamicRowHeight({defaultRowHeight: DEFAULT_ROW_HEIGHT});\n\n const {listRef, isPrepending} = useVirtualStickToBottom({\n rowCount,\n isStreaming: isNotCompleted,\n status,\n messagesCount: messages.length,\n firstMessageId: messages[0]?.id,\n headerOffset,\n // The last message reference changes on every streamed token, so it pins the view to the\n // growing last row even while react-window keeps the same set of rows mounted.\n streamingSignal: isNotCompleted ? messages[messages.length - 1] : undefined,\n trailingContentSignal: footerOffset,\n });\n\n // Close a popup whose anchor row scrolls out of view (react-window unmounts off-screen rows,\n // detaching the popup's anchor element).\n const onRowsRendered = useCallback(\n (visibleRows: {startIndex: number; stopIndex: number}) => {\n if (!popupState.open || popupState.messageId === null) {\n return;\n }\n const messageIndex = messages.findIndex(\n (message) => message.id === popupState.messageId,\n );\n // Anchor message no longer in the list - its row is gone, so close the popup.\n if (messageIndex === -1) {\n handlePopupOpenChange(false);\n return;\n }\n const anchorIndex = messageIndex + headerOffset;\n if (anchorIndex < visibleRows.startIndex || anchorIndex > visibleRows.stopIndex) {\n handlePopupOpenChange(false);\n }\n },\n [popupState.open, popupState.messageId, messages, headerOffset, handlePopupOpenChange],\n );\n\n return (\n <div className={b({virtualized: true}, className)} data-qa={qa ?? MessageListQa.Root}>\n {isPrepending && (\n <div className={b('shimmer')} aria-hidden=\"true\">\n {Array.from({length: 6}, (_, i) => (\n <div key={i} className={b('shimmer-row', {assistant: i % 2 === 1})} />\n ))}\n </div>\n )}\n <List<MessageRowProps>\n className={b('list')}\n listRef={listRef}\n rowComponent={MessageRow}\n rowCount={rowCount}\n rowHeight={rowHeight}\n rowProps={rowProps}\n overscanCount={OVERSCAN_COUNT}\n onRowsRendered={onRowsRendered}\n data-qa={qa ? `${qa}-messages` : MessageListQa.Messages}\n />\n <MessageListFooter\n showLoader={showLoader}\n status={status}\n errorMessage={errorMessage}\n loaderMessage={loaderMessage}\n withLoaderShimmer={withLoaderShimmer}\n onRetry={onRetry}\n ratingBlockProps={ratingBlockProps}\n actionPopupProps={actionPopupProps}\n qa={qa}\n showActionPopup={showActionPopup}\n popupState={popupState}\n onPopupOpenChange={handlePopupOpenChange}\n />\n </div>\n );\n}\n"]}
1
+ {"version":3,"file":"MessageList.virtualized.js","sourceRoot":"../../../../../src","sources":["components/organisms/MessageList/MessageList.virtualized.tsx"],"names":[],"mappings":";;AAgGA,wDA2LC;;AA3RD,iCAA2C;AAE3C,+CAA+E;AAE/E,mDAAuD;AAEvD,6CAAwC;AACxC,sFAAwE;AACxE,wDAA0C;AAE1C,kDAAkE;AAClE,kDAAmE;AACnE,8DAAsD;AACtD,4CAAkF;AAElF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AE,OAAO,EAChB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,EAAE,gBAAgB,EAClC,EAAE,EAAE,EAAE,EACN,eAAe,EAAE,eAAe,EAChC,UAAU,EAAE,UAAU,EACtB,iBAAiB,EAAE,qBAAqB,GAC1C,IACA,CACT,CAAC;AACN,CAAC","sourcesContent":["import {useCallback, useMemo} from 'react';\n\nimport {List, type RowComponentProps, useDynamicRowHeight} from 'react-window';\n\nimport {useVirtualStickToBottom} from '../../../hooks';\nimport type {TChatMessage, TMessageContent, TMessageMetadata} from '../../../types/messages';\nimport {block} from '../../../utils/cn';\nimport {IntersectionContainer} from '../../atoms/IntersectionContainer';\nimport {Loader} from '../../atoms/Loader';\n\nimport {MessageItem, type MessageItemConfig} from './MessageItem';\nimport {type MessageListProps, MessageListQa} from './MessageList';\nimport {MessageListFooter} from './MessageListFooter';\nimport {type PopupState, isActionPopupOpenForMessage, usePopup} from './usePopup';\n\nconst b = block('message-list');\n\n/** Estimated row height used before a row has been measured (and for SSR). */\nconst DEFAULT_ROW_HEIGHT = 80;\n/** Extra rows rendered outside the viewport to reduce flicker while scrolling. */\nconst OVERSCAN_COUNT = 5;\n\ntype MessageRowProps = {\n messages: TChatMessage<TMessageContent, TMessageMetadata>[];\n /** Whether the current response is still streaming/submitted (hide actions on last row). */\n isNotCompleted: boolean;\n /** Number of non-message rows before the messages (the load-more trigger). */\n headerOffset: number;\n hasPreviousMessages: boolean;\n onLoadPreviousMessages?: () => void;\n popupState: PopupState;\n config: MessageItemConfig<TMessageContent>;\n footerContent?: React.ReactNode;\n};\n\nfunction MessageRow({\n index,\n style,\n ariaAttributes,\n messages,\n isNotCompleted,\n headerOffset,\n hasPreviousMessages,\n onLoadPreviousMessages,\n popupState,\n config,\n footerContent,\n}: RowComponentProps<MessageRowProps>) {\n // Header row: the \"load previous messages\" intersection trigger.\n if (hasPreviousMessages && index === 0) {\n return (\n <div style={style} {...ariaAttributes}>\n <IntersectionContainer\n onIntersect={onLoadPreviousMessages}\n className={b('load-trigger')}\n >\n <Loader view=\"loading\" />\n </IntersectionContainer>\n </div>\n );\n }\n\n const messageIndex = index - headerOffset;\n const message = messages[messageIndex];\n if (!message) {\n if (messageIndex === messages.length && footerContent !== undefined) {\n return (\n <div style={style} {...ariaAttributes}>\n <div className={b('footer-content')}>{footerContent}</div>\n </div>\n );\n }\n return <div style={style} {...ariaAttributes} />;\n }\n\n const isLast = messageIndex === messages.length - 1;\n\n return (\n <div style={style} {...ariaAttributes}>\n {/* data-message-id lets useVirtualStickToBottom anchor scroll position to a specific\n rendered row (robust to off-screen height estimation) when older messages load. */}\n <div className={b('row')} data-message-id={message.id}>\n <MessageItem\n message={message}\n suppressActions={isLast && isNotCompleted}\n {...config}\n showActionsOnHover={\n Boolean(config.showActionsOnHover) &&\n !isActionPopupOpenForMessage(popupState, message.id)\n }\n />\n </div>\n </div>\n );\n}\n\nexport function VirtualizedMessageList<TContent extends TMessageContent = never>({\n messages,\n scrollPositionRef,\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxProps,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n renderAssistantFooter,\n userExtraInfo: UserExtraInfo,\n assistantExtraInfo: AssistantExtraInfo,\n loaderStatuses = ['submitted', 'streaming_loading'],\n className,\n qa,\n status,\n errorMessage,\n loaderMessage,\n withLoaderShimmer,\n onRetry,\n hasPreviousMessages = false,\n onLoadPreviousMessages,\n ratingBlockProps,\n actionPopupProps,\n footerContent,\n}: MessageListProps<TContent>) {\n const isStreaming = status === 'streaming' || status === 'streaming_loading';\n const isSubmitted = status === 'submitted';\n const isNotCompleted = isSubmitted || isStreaming;\n const showLoader = status && loaderStatuses.includes(status);\n\n const {popupState, handleActionPopup, handlePopupOpenChange, showActionPopup} = usePopup<\n TContent,\n TMessageMetadata\n >();\n\n const headerOffset = hasPreviousMessages ? 1 : 0;\n const hasFooterContent = footerContent !== undefined && footerContent !== null;\n const footerOffset = hasFooterContent ? 1 : 0;\n const rowCount = messages.length + headerOffset + footerOffset;\n\n const config = useMemo<MessageItemConfig<TContent>>(\n () => ({\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxOptions: mdxProps?.mdxOptions,\n getMarkdownExtraProps: mdxProps?.getMarkdownExtraProps,\n getMdxContext: mdxProps?.getMdxContext,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n renderAssistantFooter,\n userExtraInfo: UserExtraInfo,\n assistantExtraInfo: AssistantExtraInfo,\n onActionPopup: handleActionPopup,\n }),\n [\n messageRendererRegistry,\n thinkingMessageView,\n transformOptions,\n shouldParseIncompleteMarkdown,\n mermaidOptions,\n openMarkdownLinksInNewTab,\n mdxProps,\n showActionsOnHover,\n showTimestamp,\n showAvatar,\n userActions,\n assistantActions,\n UserExtraInfo,\n AssistantExtraInfo,\n renderAssistantFooter,\n handleActionPopup,\n ],\n );\n\n const rowProps = useMemo<MessageRowProps>(\n () => ({\n messages: messages as TChatMessage<TMessageContent, TMessageMetadata>[],\n isNotCompleted,\n headerOffset,\n hasPreviousMessages,\n onLoadPreviousMessages,\n popupState,\n config: config as unknown as MessageItemConfig<TMessageContent>,\n footerContent: hasFooterContent ? footerContent : undefined,\n }),\n [\n messages,\n isNotCompleted,\n headerOffset,\n hasPreviousMessages,\n onLoadPreviousMessages,\n popupState,\n config,\n hasFooterContent,\n footerContent,\n ],\n );\n\n const rowHeight = useDynamicRowHeight({defaultRowHeight: DEFAULT_ROW_HEIGHT});\n\n const {listRef, isPrepending} = useVirtualStickToBottom({\n rowCount,\n scrollPositionRef,\n isStreaming: isNotCompleted,\n status,\n messagesCount: messages.length,\n firstMessageId: messages[0]?.id,\n headerOffset,\n // The last message reference changes on every streamed token, so it pins the view to the\n // growing last row even while react-window keeps the same set of rows mounted.\n streamingSignal: isNotCompleted ? messages[messages.length - 1] : undefined,\n trailingContentSignal: footerOffset,\n });\n\n // Close a popup whose anchor row scrolls out of view (react-window unmounts off-screen rows,\n // detaching the popup's anchor element).\n const onRowsRendered = useCallback(\n (visibleRows: {startIndex: number; stopIndex: number}) => {\n if (!popupState.open || popupState.messageId === null) {\n return;\n }\n const messageIndex = messages.findIndex(\n (message) => message.id === popupState.messageId,\n );\n // Anchor message no longer in the list - its row is gone, so close the popup.\n if (messageIndex === -1) {\n handlePopupOpenChange(false);\n return;\n }\n const anchorIndex = messageIndex + headerOffset;\n if (anchorIndex < visibleRows.startIndex || anchorIndex > visibleRows.stopIndex) {\n handlePopupOpenChange(false);\n }\n },\n [popupState.open, popupState.messageId, messages, headerOffset, handlePopupOpenChange],\n );\n\n return (\n <div className={b({virtualized: true}, className)} data-qa={qa ?? MessageListQa.Root}>\n {isPrepending && (\n <div className={b('shimmer')} aria-hidden=\"true\">\n {Array.from({length: 6}, (_, i) => (\n <div key={i} className={b('shimmer-row', {assistant: i % 2 === 1})} />\n ))}\n </div>\n )}\n <List<MessageRowProps>\n className={b('list')}\n listRef={listRef}\n rowComponent={MessageRow}\n rowCount={rowCount}\n rowHeight={rowHeight}\n rowProps={rowProps}\n overscanCount={OVERSCAN_COUNT}\n onRowsRendered={onRowsRendered}\n data-qa={qa ? `${qa}-messages` : MessageListQa.Messages}\n />\n <MessageListFooter\n showLoader={showLoader}\n status={status}\n errorMessage={errorMessage}\n loaderMessage={loaderMessage}\n withLoaderShimmer={withLoaderShimmer}\n onRetry={onRetry}\n ratingBlockProps={ratingBlockProps}\n actionPopupProps={actionPopupProps}\n qa={qa}\n showActionPopup={showActionPopup}\n popupState={popupState}\n onPopupOpenChange={handlePopupOpenChange}\n />\n </div>\n );\n}\n"]}
@@ -1,11 +1,19 @@
1
- import { type RefObject } from 'react';
1
+ import { type MutableRefObject, type RefObject } from 'react';
2
2
  import type { ChatStatus } from "../types/index.js";
3
3
  export interface UseSmartScrollReturn<T extends HTMLElement> {
4
4
  containerRef: RefObject<T>;
5
5
  scrollToBottom: (behavior?: ScrollBehavior) => void;
6
6
  }
7
- export declare function useSmartScroll<T extends HTMLElement>({ isStreaming, messagesCount, status, }: {
7
+ /** Reading position retained by the host across message-list mounts. */
8
+ export interface MessageListScrollPosition {
9
+ scrollTop: number;
10
+ /** Follow new content on restore when the reader was at the bottom. */
11
+ isAtBottom: boolean;
12
+ }
13
+ export type MessageListScrollPositionRef = MutableRefObject<MessageListScrollPosition | undefined>;
14
+ export declare function useSmartScroll<T extends HTMLElement>({ isStreaming, messagesCount, status, scrollPositionRef, }: {
8
15
  isStreaming?: boolean;
9
16
  messagesCount: number;
10
17
  status?: ChatStatus;
18
+ scrollPositionRef?: MessageListScrollPositionRef;
11
19
  }): UseSmartScrollReturn<T>;
@@ -4,10 +4,21 @@ exports.useSmartScroll = useSmartScroll;
4
4
  const react_1 = require("react");
5
5
  const observeScrollContent_1 = require("../utils/observeScrollContent.js");
6
6
  const SCROLL_THRESHOLD = 10;
7
- function useSmartScroll({ isStreaming = false, messagesCount, status, }) {
7
+ function useSmartScroll({ isStreaming = false, messagesCount, status, scrollPositionRef, }) {
8
+ const positionRef = scrollPositionRef;
8
9
  const containerRef = (0, react_1.useRef)(null);
9
10
  const userScrolledUpRef = (0, react_1.useRef)(false);
11
+ const pendingRestoreTopRef = (0, react_1.useRef)();
10
12
  const scrollToBottom = (0, react_1.useCallback)((behavior = 'instant') => {
13
+ const pendingTop = pendingRestoreTopRef.current;
14
+ const currentContainer = containerRef.current;
15
+ if (pendingTop !== undefined && currentContainer) {
16
+ currentContainer.scrollTop = pendingTop;
17
+ if (currentContainer.scrollTop >= pendingTop) {
18
+ pendingRestoreTopRef.current = undefined;
19
+ }
20
+ return;
21
+ }
11
22
  if (!userScrolledUpRef.current) {
12
23
  const container = containerRef.current;
13
24
  if (container) {
@@ -18,10 +29,28 @@ function useSmartScroll({ isStreaming = false, messagesCount, status, }) {
18
29
  }
19
30
  }
20
31
  }, []);
21
- // Initial scroll to bottom
22
- (0, react_1.useEffect)(() => {
23
- scrollToBottom();
24
- }, []);
32
+ // Restore before paint, including whether streaming should keep following the bottom.
33
+ (0, react_1.useLayoutEffect)(() => {
34
+ const container = containerRef.current;
35
+ if (!container) {
36
+ return undefined;
37
+ }
38
+ const position = positionRef === null || positionRef === void 0 ? void 0 : positionRef.current;
39
+ userScrolledUpRef.current = position ? !position.isAtBottom : false;
40
+ pendingRestoreTopRef.current =
41
+ position && !position.isAtBottom ? position.scrollTop : undefined;
42
+ container.scrollTop =
43
+ position && !position.isAtBottom ? position.scrollTop : container.scrollHeight;
44
+ return () => {
45
+ var _a;
46
+ if (positionRef) {
47
+ positionRef.current = {
48
+ scrollTop: (_a = pendingRestoreTopRef.current) !== null && _a !== void 0 ? _a : container.scrollTop,
49
+ isAtBottom: !userScrolledUpRef.current,
50
+ };
51
+ }
52
+ };
53
+ }, [positionRef]);
25
54
  // Handle user scroll events
26
55
  (0, react_1.useEffect)(() => {
27
56
  const container = containerRef.current;
@@ -33,15 +62,27 @@ function useSmartScroll({ isStreaming = false, messagesCount, status, }) {
33
62
  return;
34
63
  }
35
64
  const { scrollTop, scrollHeight, clientHeight } = container;
65
+ const pendingTop = pendingRestoreTopRef.current;
66
+ if (pendingTop !== undefined) {
67
+ const availableTop = Math.max(0, scrollHeight - clientHeight);
68
+ if (scrollTop === Math.min(pendingTop, availableTop)) {
69
+ return;
70
+ }
71
+ // A user scroll cancels a pending restore while delayed content is rendering.
72
+ pendingRestoreTopRef.current = undefined;
73
+ }
36
74
  const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
37
75
  const scrolledUp = distanceFromBottom > SCROLL_THRESHOLD;
38
76
  userScrolledUpRef.current = scrolledUp;
77
+ if (positionRef) {
78
+ positionRef.current = { scrollTop, isAtBottom: !scrolledUp };
79
+ }
39
80
  };
40
81
  container.addEventListener('scroll', handleScroll, { passive: true });
41
82
  return () => {
42
83
  container.removeEventListener('scroll', handleScroll);
43
84
  };
44
- }, []);
85
+ }, [positionRef]);
45
86
  // Keep pinned after delayed content renders as well as viewport changes,
46
87
  // even when the response has already finished streaming.
47
88
  (0, react_1.useEffect)(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"useSmartScroll.js","sourceRoot":"../../../src","sources":["hooks/useSmartScroll.tsx"],"names":[],"mappings":";;AAYA,wCAuGC;AAnHD,iCAAqE;AAGrE,2EAAmE;AAOnE,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,SAAgB,cAAc,CAAwB,EAClD,WAAW,GAAG,KAAK,EACnB,aAAa,EACb,MAAM,GAKT;IACG,MAAM,YAAY,GAAG,IAAA,cAAM,EAAI,IAAI,CAAC,CAAC;IACrC,MAAM,iBAAiB,GAAG,IAAA,cAAM,EAAC,KAAK,CAAC,CAAC;IAExC,MAAM,cAAc,GAAG,IAAA,mBAAW,EAAC,CAAC,WAA2B,SAAS,EAAE,EAAE;QACxE,IAAI,CAAC,iBAAiB,CAAC,OAAO,EAAE,CAAC;YAC7B,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC;YACvC,IAAI,SAAS,EAAE,CAAC;gBACZ,SAAS,CAAC,QAAQ,CAAC;oBACf,GAAG,EAAE,SAAS,CAAC,YAAY;oBAC3B,QAAQ;iBACX,CAAC,CAAC;YACP,CAAC;QACL,CAAC;IACL,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,2BAA2B;IAC3B,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,cAAc,EAAE,CAAC;IACrB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,4BAA4B;IAC5B,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,CAAC;QACvC,IAAI,CAAC,SAAS,EAAE,CAAC;YACb,OAAO,SAAS,CAAC;QACrB,CAAC;QAED,MAAM,YAAY,GAAG,GAAG,EAAE;YACtB,IAAI,CAAC,SAAS,EAAE,CAAC;gBACb,OAAO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AAE,IAAI;YACf,OAAO,EAAE,IAAI;YACb,UAAU,EAAE,IAAI;YAChB,aAAa,EAAE,IAAI;SACtB,CAAC,CAAC;QAEH,OAAO,GAAG,EAAE;YACR,QAAQ,CAAC,UAAU,EAAE,CAAC;QAC1B,CAAC,CAAC;IACN,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IAElB,wBAAwB;IACxB,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,cAAc,CAAC,QAAQ,CAAC,CAAC;IAC7B,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAEb,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,IAAI,aAAa,EAAE,CAAC;YAChB,cAAc,CAAC,QAAQ,CAAC,CAAC;QAC7B,CAAC;IACL,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC;IAEpB,OAAO;QACH,YAAY;QACZ,cAAc;KACjB,CAAC;AACN,CAAC","sourcesContent":["import {type RefObject, useCallback, useEffect, useRef} from 'react';\n\nimport type {ChatStatus} from '../types';\nimport {observeScrollContent} from '../utils/observeScrollContent';\n\nexport interface UseSmartScrollReturn<T extends HTMLElement> {\n containerRef: RefObject<T>;\n scrollToBottom: (behavior?: ScrollBehavior) => void;\n}\n\nconst SCROLL_THRESHOLD = 10;\n\nexport function useSmartScroll<T extends HTMLElement>({\n isStreaming = false,\n messagesCount,\n status,\n}: {\n isStreaming?: boolean;\n messagesCount: number;\n status?: ChatStatus;\n}): UseSmartScrollReturn<T> {\n const containerRef = useRef<T>(null);\n const userScrolledUpRef = useRef(false);\n\n const scrollToBottom = useCallback((behavior: ScrollBehavior = 'instant') => {\n if (!userScrolledUpRef.current) {\n const container = containerRef.current;\n if (container) {\n container.scrollTo({\n top: container.scrollHeight,\n behavior,\n });\n }\n }\n }, []);\n\n // Initial scroll to bottom\n useEffect(() => {\n scrollToBottom();\n }, []);\n\n // Handle user scroll events\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n\n const handleScroll = () => {\n if (!container) {\n return;\n }\n\n const {scrollTop, scrollHeight, clientHeight} = container;\n const distanceFromBottom = scrollHeight - scrollTop - clientHeight;\n\n const scrolledUp = distanceFromBottom > SCROLL_THRESHOLD;\n userScrolledUpRef.current = scrolledUp;\n };\n\n container.addEventListener('scroll', handleScroll, {passive: true});\n return () => {\n container.removeEventListener('scroll', handleScroll);\n };\n }, []);\n\n // Keep pinned after delayed content renders as well as viewport changes,\n // even when the response has already finished streaming.\n useEffect(() => {\n const container = containerRef.current;\n if (!container || typeof ResizeObserver === 'undefined') {\n return undefined;\n }\n\n return observeScrollContent(container, () => scrollToBottom('instant'));\n }, [scrollToBottom]);\n\n // Handle DOM mutations during streaming\n useEffect(() => {\n const container = containerRef.current;\n if (!container || !isStreaming) {\n return undefined;\n }\n\n const observer = new MutationObserver(() => {\n scrollToBottom('instant');\n });\n\n observer.observe(container, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n\n return () => {\n observer.disconnect();\n };\n }, [isStreaming]);\n\n // Handle status changes\n useEffect(() => {\n scrollToBottom('smooth');\n }, [status]);\n\n useEffect(() => {\n if (messagesCount) {\n scrollToBottom('smooth');\n }\n }, [messagesCount]);\n\n return {\n containerRef,\n scrollToBottom,\n };\n}\n"]}
1
+ {"version":3,"file":"useSmartScroll.js","sourceRoot":"../../../src","sources":["hooks/useSmartScroll.tsx"],"names":[],"mappings":";;AA4BA,wCAiJC;AA7KD,iCAOe;AAGf,2EAAmE;AAgBnE,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,SAAgB,cAAc,CAAwB,EAClD,WAAW,GAAG,KAAK,EACnB,aAAa,EACb,MAAM,EACN,iBAAiB,GAMpB;IACG,MAAM,WAAW,GAAG,iBAAiB,CAAC;IACtC,MAAM,YAAY,GAAG,IAAA,cAAM,EAAI,IAAI,CAAC,CAAC;IACrC,MAAM,iBAAiB,GAAG,IAAA,cAAM,EAAC,KAAK,CAAC,CAAC;IACxC,MAA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AE,IAAI;YACb,UAAU,EAAE,IAAI;YAChB,aAAa,EAAE,IAAI;SACtB,CAAC,CAAC;QAEH,OAAO,GAAG,EAAE;YACR,QAAQ,CAAC,UAAU,EAAE,CAAC;QAC1B,CAAC,CAAC;IACN,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAC;IAElB,wBAAwB;IACxB,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,cAAc,CAAC,QAAQ,CAAC,CAAC;IAC7B,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAEb,IAAA,iBAAS,EAAC,GAAG,EAAE;QACX,IAAI,aAAa,EAAE,CAAC;YAChB,cAAc,CAAC,QAAQ,CAAC,CAAC;QAC7B,CAAC;IACL,CAAC,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC;IAEpB,OAAO;QACH,YAAY;QACZ,cAAc;KACjB,CAAC;AACN,CAAC","sourcesContent":["import {\n type MutableRefObject,\n type RefObject,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n} from 'react';\n\nimport type {ChatStatus} from '../types';\nimport {observeScrollContent} from '../utils/observeScrollContent';\n\nexport interface UseSmartScrollReturn<T extends HTMLElement> {\n containerRef: RefObject<T>;\n scrollToBottom: (behavior?: ScrollBehavior) => void;\n}\n\n/** Reading position retained by the host across message-list mounts. */\nexport interface MessageListScrollPosition {\n scrollTop: number;\n /** Follow new content on restore when the reader was at the bottom. */\n isAtBottom: boolean;\n}\n\nexport type MessageListScrollPositionRef = MutableRefObject<MessageListScrollPosition | undefined>;\n\nconst SCROLL_THRESHOLD = 10;\n\nexport function useSmartScroll<T extends HTMLElement>({\n isStreaming = false,\n messagesCount,\n status,\n scrollPositionRef,\n}: {\n isStreaming?: boolean;\n messagesCount: number;\n status?: ChatStatus;\n scrollPositionRef?: MessageListScrollPositionRef;\n}): UseSmartScrollReturn<T> {\n const positionRef = scrollPositionRef;\n const containerRef = useRef<T>(null);\n const userScrolledUpRef = useRef(false);\n const pendingRestoreTopRef = useRef<number>();\n\n const scrollToBottom = useCallback((behavior: ScrollBehavior = 'instant') => {\n const pendingTop = pendingRestoreTopRef.current;\n const currentContainer = containerRef.current;\n if (pendingTop !== undefined && currentContainer) {\n currentContainer.scrollTop = pendingTop;\n if (currentContainer.scrollTop >= pendingTop) {\n pendingRestoreTopRef.current = undefined;\n }\n return;\n }\n if (!userScrolledUpRef.current) {\n const container = containerRef.current;\n if (container) {\n container.scrollTo({\n top: container.scrollHeight,\n behavior,\n });\n }\n }\n }, []);\n\n // Restore before paint, including whether streaming should keep following the bottom.\n useLayoutEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n const position = positionRef?.current;\n userScrolledUpRef.current = position ? !position.isAtBottom : false;\n pendingRestoreTopRef.current =\n position && !position.isAtBottom ? position.scrollTop : undefined;\n container.scrollTop =\n position && !position.isAtBottom ? position.scrollTop : container.scrollHeight;\n return () => {\n if (positionRef) {\n positionRef.current = {\n scrollTop: pendingRestoreTopRef.current ?? container.scrollTop,\n isAtBottom: !userScrolledUpRef.current,\n };\n }\n };\n }, [positionRef]);\n\n // Handle user scroll events\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return undefined;\n }\n\n const handleScroll = () => {\n if (!container) {\n return;\n }\n\n const {scrollTop, scrollHeight, clientHeight} = container;\n const pendingTop = pendingRestoreTopRef.current;\n if (pendingTop !== undefined) {\n const availableTop = Math.max(0, scrollHeight - clientHeight);\n if (scrollTop === Math.min(pendingTop, availableTop)) {\n return;\n }\n // A user scroll cancels a pending restore while delayed content is rendering.\n pendingRestoreTopRef.current = undefined;\n }\n const distanceFromBottom = scrollHeight - scrollTop - clientHeight;\n\n const scrolledUp = distanceFromBottom > SCROLL_THRESHOLD;\n userScrolledUpRef.current = scrolledUp;\n if (positionRef) {\n positionRef.current = {scrollTop, isAtBottom: !scrolledUp};\n }\n };\n\n container.addEventListener('scroll', handleScroll, {passive: true});\n return () => {\n container.removeEventListener('scroll', handleScroll);\n };\n }, [positionRef]);\n\n // Keep pinned after delayed content renders as well as viewport changes,\n // even when the response has already finished streaming.\n useEffect(() => {\n const container = containerRef.current;\n if (!container || typeof ResizeObserver === 'undefined') {\n return undefined;\n }\n\n return observeScrollContent(container, () => scrollToBottom('instant'));\n }, [scrollToBottom]);\n\n // Handle DOM mutations during streaming\n useEffect(() => {\n const container = containerRef.current;\n if (!container || !isStreaming) {\n return undefined;\n }\n\n const observer = new MutationObserver(() => {\n scrollToBottom('instant');\n });\n\n observer.observe(container, {\n childList: true,\n subtree: true,\n attributes: true,\n characterData: true,\n });\n\n return () => {\n observer.disconnect();\n };\n }, [isStreaming]);\n\n // Handle status changes\n useEffect(() => {\n scrollToBottom('smooth');\n }, [status]);\n\n useEffect(() => {\n if (messagesCount) {\n scrollToBottom('smooth');\n }\n }, [messagesCount]);\n\n return {\n containerRef,\n scrollToBottom,\n };\n}\n"]}
@@ -1,7 +1,9 @@
1
1
  import type { ChatStatus } from "../types/index.js";
2
+ import type { MessageListScrollPositionRef } from "./useSmartScroll.js";
2
3
  export interface UseVirtualStickToBottomParams {
3
4
  /** Total number of rows rendered by the list, including non-message header rows. */
4
5
  rowCount: number;
6
+ scrollPositionRef?: MessageListScrollPositionRef;
5
7
  /** Whether a response is currently streaming (keep pinned to the growing last row). */
6
8
  isStreaming?: boolean;
7
9
  status?: ChatStatus;
@@ -35,7 +37,7 @@ export interface UseVirtualStickToBottomParams {
35
37
  * - keeps the last row pinned to the bottom while streaming, unless the user scrolled up;
36
38
  * - preserves the on-screen position of the top visible message when older messages are prepended.
37
39
  */
38
- export declare function useVirtualStickToBottom({ rowCount, isStreaming, status, messagesCount, firstMessageId, headerOffset, streamingSignal, trailingContentSignal, }: UseVirtualStickToBottomParams): {
40
+ export declare function useVirtualStickToBottom({ rowCount, scrollPositionRef, isStreaming, status, messagesCount, firstMessageId, headerOffset, streamingSignal, trailingContentSignal, }: UseVirtualStickToBottomParams): {
39
41
  listRef: import("react").Dispatch<import("react").SetStateAction<import("react-window", { with: { "resolution-mode": "import" } }).ListImperativeAPI | null | undefined>>;
40
42
  isPrepending: boolean;
41
43
  };
@@ -28,12 +28,15 @@ const PREPEND_SHIMMER_MS = 320;
28
28
  * - keeps the last row pinned to the bottom while streaming, unless the user scrolled up;
29
29
  * - preserves the on-screen position of the top visible message when older messages are prepended.
30
30
  */
31
- function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messagesCount, firstMessageId, headerOffset = 0, streamingSignal, trailingContentSignal, }) {
31
+ function useVirtualStickToBottom({ rowCount, scrollPositionRef, isStreaming = false, status, messagesCount, firstMessageId, headerOffset = 0, streamingSignal, trailingContentSignal, }) {
32
+ var _a;
33
+ const positionRef = scrollPositionRef;
32
34
  const [listApi, listRef] = (0, react_window_1.useListCallbackRef)();
33
35
  // Drives a shimmer overlay while older messages are being prepended and the scroll is restored.
34
36
  const [isPrepending, setIsPrepending] = (0, react_1.useState)(false);
35
- const userScrolledUpRef = (0, react_1.useRef)(false);
37
+ const userScrolledUpRef = (0, react_1.useRef)(((_a = positionRef === null || positionRef === void 0 ? void 0 : positionRef.current) === null || _a === void 0 ? void 0 : _a.isAtBottom) === false);
36
38
  const prependingRef = (0, react_1.useRef)(false);
39
+ const pendingRestoreRef = (0, react_1.useRef)();
37
40
  const shimmerTimerRef = (0, react_1.useRef)();
38
41
  const prevFirstIdRef = (0, react_1.useRef)(firstMessageId);
39
42
  const prevMessagesCountRef = (0, react_1.useRef)(messagesCount);
@@ -67,10 +70,42 @@ function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messag
67
70
  rafRef.current = 0;
68
71
  }
69
72
  }, []);
73
+ // Keep the target until it is reachable. Exhausting the measurement-frame budget only
74
+ // pauses the animation; new messages or a content resize resume the pending restore.
75
+ const restorePosition = (0, react_1.useCallback)(() => {
76
+ cancelPendingScroll();
77
+ let frame = 0;
78
+ const step = () => {
79
+ var _a;
80
+ const pending = pendingRestoreRef.current;
81
+ const element = (_a = listApiRef.current) === null || _a === void 0 ? void 0 : _a.element;
82
+ if (!pending || !element) {
83
+ return;
84
+ }
85
+ element.scrollTop = pending.scrollTop;
86
+ pending.appliedTop = element.scrollTop;
87
+ lastScrollTopRef.current = element.scrollTop;
88
+ frame += 1;
89
+ if (frame < REANCHOR_FRAMES) {
90
+ rafRef.current = requestAnimationFrame(step);
91
+ }
92
+ else {
93
+ rafRef.current = 0;
94
+ if (Math.abs(element.scrollTop - pending.scrollTop) < 1) {
95
+ pendingRestoreRef.current = undefined;
96
+ }
97
+ }
98
+ };
99
+ step();
100
+ }, [cancelPendingScroll]);
70
101
  // Pin to the true bottom, re-applying across frames: react-window's `scrollToRow` targets a
71
102
  // position computed from (partly estimated) row heights, so a single call lands short; once the
72
103
  // bottom rows render and are measured, the next frame re-targets the now-lower bottom.
73
104
  const pinToBottom = (0, react_1.useCallback)(() => {
105
+ if (pendingRestoreRef.current) {
106
+ restorePosition();
107
+ return;
108
+ }
74
109
  if (userScrolledUpRef.current || prependingRef.current || rowCountRef.current <= 0) {
75
110
  return;
76
111
  }
@@ -88,7 +123,7 @@ function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messag
88
123
  }
89
124
  };
90
125
  step();
91
- }, [cancelPendingScroll]);
126
+ }, [cancelPendingScroll, restorePosition]);
92
127
  // Record the first message row's top offset (relative to the scroll container) so a prepend can
93
128
  // restore it. Only meaningful while the first message is rendered, i.e. when scrolled near the
94
129
  // top - which is exactly when a load-previous can be triggered.
@@ -121,8 +156,22 @@ function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messag
121
156
  if (prependingRef.current) {
122
157
  return;
123
158
  }
159
+ const pending = pendingRestoreRef.current;
160
+ if (pending &&
161
+ pending.appliedTop !== undefined &&
162
+ Math.abs(scrollTop - pending.appliedTop) < 1) {
163
+ // A restore write (including one clamped by unloaded content) is not user intent.
164
+ return;
165
+ }
124
166
  const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
125
- if (scrollTop < prevTop - 1) {
167
+ if (pending) {
168
+ pendingRestoreRef.current = undefined;
169
+ cancelPendingScroll();
170
+ // A reader can interrupt restoration in either direction.
171
+ userScrolledUpRef.current = distanceFromBottom > SCROLL_THRESHOLD;
172
+ }
173
+ else if (scrollTop < prevTop - 1) {
174
+ cancelPendingScroll();
126
175
  // User scrolled up: pause auto-stick unless they are still effectively at the bottom.
127
176
  userScrolledUpRef.current = distanceFromBottom > SCROLL_THRESHOLD;
128
177
  }
@@ -130,6 +179,9 @@ function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messag
130
179
  // At (or back to) the bottom: resume auto-stick.
131
180
  userScrolledUpRef.current = false;
132
181
  }
182
+ if (positionRef) {
183
+ positionRef.current = { scrollTop, isAtBottom: !userScrolledUpRef.current };
184
+ }
133
185
  // Measure the first message's offset only after scrolling settles: react-window renders
134
186
  // the rows for the new position asynchronously, and a programmatic pin jumps through
135
187
  // intermediate positions, so a synchronous (or single-frame) read can capture a stale
@@ -146,14 +198,29 @@ function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messag
146
198
  element.removeEventListener('scroll', handleScroll);
147
199
  clearTimeout(captureTimerRef.current);
148
200
  };
149
- }, [listApi, captureFirstOffset]);
150
- // Initial scroll to bottom once the list element is mounted.
151
- (0, react_1.useEffect)(() => {
152
- if (listApi) {
153
- pinToBottom();
201
+ }, [listApi, captureFirstOffset, positionRef, cancelPendingScroll]);
202
+ // Restore the host position before paint. Re-apply while virtual row heights settle.
203
+ (0, react_1.useLayoutEffect)(() => {
204
+ const element = listApi === null || listApi === void 0 ? void 0 : listApi.element;
205
+ if (!element) {
206
+ return undefined;
154
207
  }
155
- return cancelPendingScroll;
156
- }, [listApi, pinToBottom, cancelPendingScroll]);
208
+ const position = positionRef === null || positionRef === void 0 ? void 0 : positionRef.current;
209
+ userScrolledUpRef.current = position ? !position.isAtBottom : false;
210
+ pendingRestoreRef.current =
211
+ position && !position.isAtBottom ? { scrollTop: position.scrollTop } : undefined;
212
+ pinToBottom();
213
+ return () => {
214
+ var _a, _b;
215
+ cancelPendingScroll();
216
+ if (positionRef) {
217
+ positionRef.current = {
218
+ scrollTop: (_b = (_a = pendingRestoreRef.current) === null || _a === void 0 ? void 0 : _a.scrollTop) !== null && _b !== void 0 ? _b : element.scrollTop,
219
+ isAtBottom: !userScrolledUpRef.current,
220
+ };
221
+ }
222
+ };
223
+ }, [listApi, pinToBottom, cancelPendingScroll, positionRef]);
157
224
  // Re-pin after delayed row measurements (including diagrams) and viewport changes.
158
225
  // pinToBottom preserves user scroll intent and the existing prepend guard.
159
226
  (0, react_1.useEffect)(() => {
@@ -186,7 +253,8 @@ function useVirtualStickToBottom({ rowCount, isStreaming = false, status, messag
186
253
  if (!element) {
187
254
  return undefined;
188
255
  }
189
- const isPrepend = userScrolledUpRef.current &&
256
+ const isPrepend = !pendingRestoreRef.current &&
257
+ userScrolledUpRef.current &&
190
258
  messagesCount > prevCount &&
191
259
  prevCount > 0 &&
192
260
  firstMessageId !== undefined &&