@swisper.ai/web-chat-ui 0.2.15 → 0.3.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","names":["EXPORT_TRANSFORMERS","IMPORT_TRANSFORMERS","$setSelectionToEnd","ControlledValuePlugin","EXPORT_TRANSFORMERS","IMPORT_TRANSFORMERS","DisabledPlugin","FocusPlugin","MarkdownPlainPastePlugin","MAX_EMITTED_VALUES","ValuePlugin","EXPORT_TRANSFORMERS","DisabledPlugin","ControlledValuePlugin","ValuePlugin","MarkdownPlainPastePlugin","FocusPlugin","_Fragment","MessageScrollerPrimitive","UiEmptyState","UiEmptyStateIcon","UiEmptyStateTitle","UiEmptyStateDescription","UiEmptyStateActionRow","TRANSFORMERS","elementNode","_Fragment","EmptyState$1","EmptyStateActionRow$1","EmptyStateDescription$1","EmptyStateIcon$1","EmptyStateTitle$1","React","TRANSFORMERS$1","ScrollAreaPrimitive","mime","rehypeSanitize","InlineStyleParser","remarkGfm","remarkParse","ChatCardContext","createContext","useChatCardContext","context","useContext","ChatCardProvider","ChatCardHeader","rest","inner","cn","level","isCollapsible","hoverAreaClassName","className","CollapsibleTrigger","ChatCardIcon","ChatCardHeaderContent","ChatCardTitle","Typography","ChatCardSubTitle","ChatCardActions","ChatCardActionButton","handleClick","shouldPreventCollapse","onClick","content","IconButton","tooltip","Tooltip","ChatCardCollapsibleButton","CollapsibleChevron","ChatCardMedia","ChatCardBody","Component","asChild","Slot","CollapsibleContent","ChatCardContent","hasPadding","hasHeaderPadding","ChatCardPreview","ChatCardFooter","ChatCardFooterNotes","ChatCardFooterPrice","ChatCardFooterActions","ChatCardForm","forwardRef","ChatCardAttributes","ChatCardAttribute","ChatCardAttributeLabel","Chip","ChatCardAttributeValue","ChatCard","openProp","isControlled","uncontrolledOpen","setUncontrolledOpen","useState","defaultOpen","open","handleOpenChange","useCallback","next","onOpenChange","contextValue","useMemo","event","Collapsible","isSelected","variant","fullWidth","isRounded","useEditChatCard","isEditing","setIsEditing","defaultEditing","checkIsEditable","isEditable","startEdit","discard","toggleEdit","EditableChatCardContext","useEditableChatCardContext","EditableChatCardContextProvider","ChatCardContainer","inline","DEFAULT_CONTENT_WIDTH","SLOT_VARIABLES","toCssLength","value","ChatContainerContext","useChatContainerContext","ChatContainer","Comp","useElementMeasure","slotHeights","setSlotHeights","setSlotHeight","current","slot","slotHeight","containerStyle","width","height","contentWidth","style","useChatContainerSlot","useLayoutEffect","ref","ChatContainerPrompt","ChatContainerWelcome","AutoFocusPlugin","editor","useLexicalComposerContext","useEffect","autoFocus","activeElement","rootElement","defaultSelection","isDisabled","EXPORT_TRANSFORMERS$1","TRANSFORMERS","IMPORT_TRANSFORMERS$1","useChatInputEditor","$getEditorPlainText","$getRoot","$setSelectionToEnd$1","lastDescendant","$isTextNode","selection","$createRangeSelection","endOffset","$setSelection","$getSelection","$isRangeSelection","focusNode","focusOffset","ControlledValuePlugin$1","previousValueRef","useRef","emittedValuesRef","echoIndex","currentValue","$convertToMarkdownString","$addUpdateTag","SKIP_DOM_SELECTION_TAG","$convertFromMarkdownString","DisabledPlugin$1","isReadOnly","FocusPlugin$1","onFocusChange","handleFocus","handleBlur","getHasValue","hasValue","syncHasValue","lastHasValueRef","onHasValueChange","HasValuePlugin","MarkdownPlainPastePlugin$1","PASTE_COMMAND","clipboardData","plainText","root","paragraph","$createParagraphNode","line","$createTextNode","COMMAND_PRIORITY_CRITICAL","MAX_EMITTED_VALUES$1","ValuePlugin$1","handleChange","onChange","error","OnChangePlugin","ChatInputContext","useChatInputContext","DEFAULT_CONFIG","HeadingNode","QuoteNode","ListNode","ListItemNode","CodeNode","LinkNode","ChatInput","hasError","setHasError","setHasValue","isFocused","setIsFocused","LexicalComposer","ChatInputPlaceholder","ChatInputTextarea","isReadOnlyState","RichTextPlugin","ContentEditable","placeholder","placeholderClassName","LexicalErrorBoundary","HistoryPlugin","children","ChatListContext","useChatListContext","ChatList","hasMoreProp","ariaLabel","scrollElementRef","loadMoreContentRef","loadMoreVersion","setLoadMoreVersion","skeletonContainer","setSkeletonContainer","setScrollElementVersion","setScrollElement","node","version","bumpLoadMore","hasMore","totalCount","loadedCount","isEmpty","isLoading","isLoadingMore","onLoadMore","getItemKey","TITLE_WIDTHS","PREVIEW_WIDTHS","ChatListSkeleton","createPortal","rows","rowClassName","Skeleton","index","ChatListEmptyState","ChatListError","messageClassName","ChatListLoadMore","LOAD_MORE_KEY","ChatListItems","memo","loadMoreContent","showSkeleton","count","getItemKeyStable","virtualizer","useVirtualizer","estimateSize","virtualItems","lastItem","ScrollArea","MenuList","listClassName","isLoaderRow","virtualItem","ChatListItem","ChatPromptBoxContext","useChatPromptBoxContext","ChatPromptBoxContextProvider","focusInputRef","registerFocusInput","focus","unregisterFocusInput","focusInput","reportInputHeight","resetCompact","ChatPromptBoxFocusPlugin","COMPACT_INPUT_HEIGHT_THRESHOLD","INTERACTIVE_SELECTOR","shouldSkipFocus","target","ChatPromptBox","isCompact","setIsCompact","ChatPromptBoxContainer","props","handleMouseDown","onMouseDown","innerClassName","ChatPromptBoxFocusRadials","Fragment","ChatPromptBoxToolbar","ChatPromptBoxContent","ChatPromptBoxInput","measureRef","setRef","element","textareaClassName","ChatPromptBoxActionsLeft","ChatPromptBoxActionsRight","ChatMessage","isQuestion","ChatMessageContent","ChatMessageActions","getNewChatId","nanoid","ChatContext","useChatContext","ChatProvider","chatIdProp","newChatId","setNewChatId","promptPlaceholder","setPromptPlaceholderState","loadedChatIdsRef","chatId","isNewChat","goToNewChat","nextChatId","setPromptPlaceholder","clearPromptPlaceholder","LAST_ITEM_SCROLL_MAX_COUNT","USER_SCROLL_INTENT_IDLE_MS","ChatConversationContext","useChatConversationContext","ChatConversationProvider","_chatId","isAtBottom","setIsAtBottom","debugInfo","setDebugInfo","viewportNodeRef","bottomTriggerNodeRef","lastItemNodeRef","resizeObserverRef","viewportResizeObserverRef","bottomTriggerObserverRef","messageCountRef","isAtBottomRef","isSmoothScrollRef","hasUserEscapedRef","isProgrammaticScrollRef","userScrollIntentRef","userScrollIntentTimeoutRef","lastScrollTopRef","scrollStrategyRef","lastViewportScrollHeightRef","scrollRef","attachLastItemResizeObserverRef","detachLastItemResizeObserverRef","syncDebugInfoRef","debug","detachLastItemResizeObserver","detachBottomTriggerObserver","detachViewportResizeObserver","syncAtBottomFromViewportRef","clearProgrammaticScroll","clearUserScrollIntent","markUserScrollIntent","applyLastItemScrollStrategy","setHasUserEscaped","hasUserEscaped","scroll","behavior","stickScrollToEnd","scrollHeight","syncAtBottomFromViewport","atBottom","attachViewportResizeObserver","observer","attachLastItemResizeObserver","applyEndScrollStrategy","handleBottomTriggerVisibility","isVisible","handleScroll","lastScrollTop","currentScrollTop","isScrollingUp","handleWheel","handleTouchStart","handlePointerDown","attachBottomTriggerObserver","entry","viewportRef","bottomTriggerRef","lastItemRef","previousNode","setMessageCount","reset","scrollBottom","scrollToLatest","ChatMessagesContext","ChatMessagesListRowContext","useChatMessagesContext","ChatMessages","messageCount","gap","ChatMessagesList","lastIndex","scrollAreaClassName","viewportClassName","ChatMessagesListRow","bottomTriggerClassName","ChatMessagesScrollBar","isLast","ChatMessageListGroup","orientation","ChatMessagesScrollButton","buttonClassName","ChevronDownIcon","ChatMessageAttachmentCard","isPreview","isInteractive","ChatMessageAttachmentCardContent","ChatMessageAttachmentCardTitle","ChatMessageAttachmentCardPreview","previewSrc","imageClassName","ChatMessageAttachmentCardActions","onDelete","CloseIcon","CHAT_ATTACHMENT_ICON_MAP","XlsIcon","PdfIcon","PptIcon","DocIcon","CodeIcon","DraftIcon","ChatMessageAttachmentCardIcon","Icon","iconClassName","icon","MIME_TO_ICON","getAttachmentIcon","mimeType","file","isCustomComponentTag","tag","useMarkdownViewer","swiTags","customComponents","key","defaultRemarkPlugins","defaultRehypePlugins","defaultSchema","MarkdownViewer","Streamdown","hasCaret","isStreaming","swiTagHandler","markdown","incompleteMatch","tagName","text","separator","openingTagRegex","openingTags","match","lastTag","closingTag","ChatMessageResponse","message","ChatMessageToolbar","reverse","ChatMessageToolbarActions","ChatMessageToolbarActionButton","ChatMessageToolbarTimestamp","getSnoozeUntilDate","minutes","MINUTES_PER_HOUR","MINUTES_PER_DAY","MILLISECONDS_PER_MINUTE","formatDurationPart","unit","formatSnoozeDate","totalMinutes","date","now","days","hours","parts","prefix","ChatNotificationCardContext","useChatNotificationCardContext","ChatNotificationCard","internalExpanded","setInternalExpanded","defaultExpanded","isExpanded","expanded","setExpanded","nextExpanded","onExpandedChange","toggleExpanded","overlayClassName","ChatNotificationCardHead","ChatNotificationCardHeader","ChatNotificationCardHeaderIcon","ChatNotificationCardHeaderTitle","ChatNotificationCardHeaderTitleLabel","CHIP_PRIORITY_MAP","ChatNotificationCardHeaderStatus","color","priority","ChatNotificationCardActions","ChatNotificationCardTimestamp","ChatNotificationCardButtons","ChatNotificationCardReadActionButton","isRead","jsx","SignalUnreadIcon","SignalReadIcon","ChatNotificationCardSnoozeButton","isHovered","setIsHovered","isSnoozed","snoozeUntilDate","handleMouseEnter","onMouseEnter","handleMouseLeave","onMouseLeave","handleCancel","onCancel","Button","SnoozeIcon","labelClassName","formatDate","cancelLabelClassName","cancelLabel","ChatNotificationCardDeleteButton","DeleteIcon","ChatNotificationCardCloseButton","ChatNotificationCardContent","ChatNotificationCardExpandButton","ChatNotificationCardContentTitle","ChatNotificationCardContentDescription","ChatNotificationCardContentActions","ChevronUpIcon","ChatNotificationCardIcon","ChatNotificationCardDescription","ChatNotificationCardTimeStamp","ChatNotificationPopup","Popover","ChatNotificationPopupTrigger","PopoverTrigger","ChatNotificationPopupContent","PopoverContent","ChatReplies","ChatReply","isMultiline","ChatReplyLabel","ChatReplyValue","ChatSuggestionContext","useChatSuggestionContext","ChatSuggestions","List","Children","isValidElement","child","cloneElement","ChatSuggestion","onHover","ListItem","listItemVariants","ListItemTrigger","triggerClassName","ChatSuggestionLabelIcon","ChatSuggestionLabel","ListItemTitle","ChatSuggestionActions","ChatSuggestionAction","ListItemAction","withForwardedRef","Primitive","displayName","ViewportPrimitive","MessageScroller","ContentPrimitive","ItemPrimitive","assignRef","DEFAULT_SCROLL_MARGIN","GROUP_MIN_HEIGHT_VAR","NOOP_COMMANDS","ChatThreadCommandsContext","useChatThread","ChatThreadCommandsBridge","useMessageScroller","commands","scrollToEnd","scrollToMessage","scrollToStart","ChatThreadSessionContext","useChatThreadSession","session","component","createSessionState","conversationId","groupIds","ChatThreadProvider","scrollMode","sessionState","setSessionState","scrollMargin","knownGroupIds","FollowNewGroups","lastGroupId","ChatThread","isAnchored","viewportElementRef","contentElementRef","setViewport","setContent","contentRef","useGroupMinHeight","contentClassName","ChatThreadErrorState","renderError","scrollButton","ChatThreadScrollButton","scrollButtonClassName","scrollButtonTooltip","viewport","isEnabled","update","minHeight","paddingTop","paddingBottom","ChatThreadGroup","isNew","groupId","ChatThreadQuestion","messageId","ChatThreadAnswer","hasContentBelow","useMessageScrollerScrollable","_children","inert","ChatArtifact","Card","ChatArtifactIcon","CardIcon","ChatArtifactContent","ChatArtifactTitle","CardTitle","ChatArtifactCaption","CardDescription","ChatArtifactActions","CardAction","CanvasShell","PanelProvider","Panel","CanvasShellHeader","PanelHeader","CanvasShellTitle","PanelTitle","CanvasShellCloseTrigger","PanelActionCloseButton","CanvasShellFullScreenTrigger","PanelActionButton","isFullScreen","labels","OpenInFullIcon","CanvasShellOptionsButton","isOpen","setIsOpen","MenuProvider","MenuTrigger","MoreHorizontalIcon","Menu","menuClassName","canvasShellContentPadding","panelBodyPadding","CanvasShellContent","PanelContent","hasScroll","PanelBody","bodyClassName","CanvasShellFooter","PanelFooter","NewChatTrigger","ChatThinkingProcess","ChatThinkingProcessTrigger","ChatThinkingProcessTriggerIcon","ChatThinkingProcessTriggerLabel","ChatThinkingProcessTriggerArrow","ChatThinkingProcessContent","childrenArray","hasLastMessagePreview","lastItemContent","AnimatePresence","ChatThinkingProcessContentPreview","lastItemIndex","previewClassName","itemsClassName","markerClassName","connectorClassName","motion","contentId","ChatThinkingProcessContentItem","EmptyState","EmptyStateIcon","EmptyStateTitle","EmptyStateDescription","EmptyStateActionRow","defaultEditorTheme","ImageNode","DecoratorNode","src","altText","span","img","domNode","alt","$createImageNode","json","$isImageNode","extractFontStyles","fontSizeRegex","fontFamilyRegex","colorRegex","fontSizeMatch","fontFamilyMatch","colorMatch","FONT_STYLE_EXPORT","fontStyles","styleStr","FONT_STYLE_IMPORT","newNode","textNode","UNDERLINE_TRANSFORMER","getAlignment","alignmentMatch","ALIGNMENT_TRANSFORMER","alignment","parentNode","$isParagraphNode","exportChildren","IMAGE_EXPORT_TRANSFORMER","IMAGE_IMPORT_TRANSFORMER","imageNode","EXPORT_TRANSFORMERS","IMPORT_TRANSFORMERS","convertHeadingElement","nodeName","$createHeadingNode","align","setNodeIndentFromDOM","isDomChecklist","isHTMLElement","convertListElement","start","$createListNode","convertListItemElement","input","checked","$createListItemNode","ariaCheckedAttr","IMPORT_PRIORITY","convertSpanElementWithStyles","fontSize","fontFamily","domStyle","lexicalNode","fontWeight","textDecoration","HTML_IMPORT_CONFIG","wrapExportWithStyle","result","OriginalClass","HTML_EXPORT_CONFIG","DivBlockNode","ElementNode","div","prevStyle","prevNode","nextStyle","convertDivElement","$createDivBlockNode","serializedNode","updated","MAX_EMITTED_VALUES","ValuePlugin","source","$generateHtmlFromNodes","useRichTextAreaEditor","useRichTextAreaSelectedText","selectedText","DisabledPlugin","ControlledPlugin","editorRef","useImperativeHandle","controlledRef","EditorRefPlugin","scrollRichTextAreaToBottom","$setSelectionToEnd","getHTMLNodesFromValue","dom","html","$generateNodesFromDOM","p","$replaceEditorHTMLContent","$replaceEditorSelectionHTMLContent","nodes","ControlledValuePlugin","shouldScrollOnInitialValueRef","isDesktop","useIsResolution","BlurPlugin","onBlur","FocusPlugin","INSERT_IMAGE_COMMAND","createCommand","INSERT_IMAGE_EVENT_NAME","ImageAddedEvent","payload","ImageDropPlugin","COMMAND_PRIORITY_EDITOR","handleInsertImage","customEvent","PASTE_HTML_COMMAND","INSERT_HTML_COMMAND","PASTE_HTML_EVENT","INSERT_HTML_EVENT","PasteHtmlEvent","InsertHtmlEvent","HtmlPastePlugin","handlePasteHtml","handleInsertHtml","MarkdownPlainPastePlugin","ATTACH_FILE_COMMAND","FileAttachmentPlugin","inputRef","files","isMultiple","acceptedFiles","Wrapper","INITIAL_CONFIG","TableNode","TableCellNode","TableRowNode","RichTextAreaImpl","containerClassName","name","onKeyDown","forwardedRef","TablePlugin","RichTextArea","DEFAULT_FONT_FAMILY","FONT_FAMILY_OPTIONS","DEFAULT_FONT_FAMILY_VALUE","FONT_SIZE_OPTIONS","DEFAULT_ALIGNMENT","DEFAULT_TEXT_COLOR","ToolbarSelect","SelectField","toAlignment","format","ALIGNMENT_OPTIONS_MAP","FormatAlignLeftIcon","FormatAlignCenterIcon","FormatAlignRightIcon","AlignmentSelect","setValue","options","$updateValue","parent","$isElementNode","mergeRegister","SELECTION_CHANGE_COMMAND","COMMAND_PRIORITY_LOW","FORMAT_ELEMENT_COMMAND","ToolbarButton","AttachmentButton","AttachmentsIcon","getStyleObjectFromRawCSS","styleObject","token","css","NO_STYLE","parse","v","unparse","styles","k","isEqualValue","a","b","isEqual","styleState","createState","$setStyleObject","$setState","valueOrUpdater","mergeStyleObjects","prevStyles","nextStyles","$patchSelectedTextStyle","prevSelection","$getPreviousSelection","styleCallback","styleObjectOrCallback","getSelectedNode","anchor","anchorNode","$isAtNodeEnd","updateFontSizeInSelection","skipRefocus","$patchStyleText","newFontSize","sanitizeUrl","url","RichTextFieldContext","useRichTextFieldContext","normalizeColorToHex","trimmed","hexMatch","r","g","rgbMatch","clamp","n","toHex","RichTextFieldContextProvider","setFontFamily","setFontSize","isBold","setIsBold","isItalic","setIsItalic","isUnderline","setIsUnderline","textColor","setTextColor","isLink","setIsLink","$updateToolbar","$getSelectionStyleValueForProperty","rawColor","$isLinkNode","onFontFamily","SKIP_SELECTION_FOCUS_TAG","onFontSize","onBold","FORMAT_TEXT_COMMAND","onItalic","onUnderline","onTextColor","onLink","TOGGLE_LINK_COMMAND","BoldButton","FormatBoldIcon","CleanFormatButton","$getNearestBlockElementAncestorOrThrow","FormatCleanIcon","ImageButton","ImageIcon","ItalicButton","FormatItalicIcon","LinkButton","isActive","LinkOnIcon","LinkOffIcon","SizeSelect","TextColorButton","isDefaultColor","handleColorChange","wrapperClassName","FormatColorIcon","TypographySelect","UnderlineButton","FormatUnderlineIcon","DefaultFormattingToolbarChildren","Divider","hasAttachments","FormattingToolbarPlugin","RichTextField","isToolbarTop","toolbarPlacement","enableAttachments","toolbarClassName","toolbarChildren","isMultipleAttachments","topMenuActionsVariants","cva","TopMenu","TopMenuActions","size","CHAT_ACTION_PROTOCOL","createChatActionURL","action","params","createChatActionLink","label","isChatActionURL","uri","extractChatActionMetadataFromUrl","link","extractLabelFromNode","extractChatActionFromLink","ast","unified","visit","metadata","useChatActions","actions","defaultTokenParser","data","isAbortError","toError","fallbackMessage","useChatStreamMessage","parseToken","tokenParser","timeoutId","didHandleAbort","clearStreamTimeout","handleAbort","onAbort","resetStreamTimeout","timeout","abortController","decoder","parser","createParser","onChunkReceived","e","stream","chunk","done","onFinish","onError","useOnChatChanged","isNewChatRef","prevChatIdRef","chatChangedFn","onChatChanged","useCurrentChatId","useIsCurrentChatNew","useChatLoadedIds","useChatPromptPlaceholder"],"sources":["../src/components/chat-card/context.tsx","../src/components/chat-card/components/chat-card-header.tsx","../src/components/chat-card/components/chat-card-body.tsx","../src/components/chat-card/components/chat-card-footer.tsx","../src/components/chat-card/components/chat-card-form.tsx","../src/components/chat-card/chat-card.tsx","../src/components/chat-card/hooks.ts","../src/components/chat-card/contexts.tsx","../src/components/chat-card-container/chat-card-container.tsx","../src/components/chat-container/chat-container.tsx","../src/components/chat-input/plugins/auto-focus-plugin.tsx","../src/components/chat-input/transformers.ts","../src/components/chat-input/plugins/hooks.ts","../src/components/chat-input/plugins/utils.ts","../src/components/chat-input/plugins/controlled-value-plugin.tsx","../src/components/chat-input/plugins/disabled-plugin.tsx","../src/components/chat-input/plugins/focus-plugin.tsx","../src/components/chat-input/plugins/has-value-plugin.tsx","../src/components/chat-input/plugins/markdown-plain-paste-plugin.tsx","../src/components/chat-input/plugins/value-plugin.tsx","../src/components/chat-input/chat-input.tsx","../src/components/chat-list/chat-list.tsx","../src/components/chat-list/chat-list-items.tsx","../src/components/chat-list/chat-list-item.tsx","../src/components/chat-prompt-box/chat-prompt-box-context.tsx","../src/components/chat-prompt-box/chat-prompt-box-focus-plugin.tsx","../src/components/chat-prompt-box/chat-prompt-box.tsx","../src/components/chat-message/chat-message.tsx","../src/contexts/chat-context/utils.ts","../src/contexts/chat-context/chat-context.tsx","../src/contexts/chat-conversation-context/chat-conversation-context.tsx","../src/components/chat-messages/chat-messages.tsx","../src/components/chat-message-attachment-card/chat-message-attachment-card.tsx","../src/components/chat-message-attachment-card/chat-message-attachment-card-icon.tsx","../src/components/chat-message-attachment-card/utils.ts","../src/components/markdown-viewer/utils.ts","../src/components/markdown-viewer/hooks.ts","../src/components/markdown-viewer/markdown-viewer.tsx","../src/components/chat-message-response/chat-message-response.tsx","../src/components/chat-message-toolbar/chat-message-toolbar.tsx","../src/components/chat-notification-card/utils.ts","../src/components/chat-notification-card/chat-notification-card.tsx","../src/components/chat-notification-popup/chat-notification-popup.tsx","../src/components/chat-reply/chat-reply.tsx","../src/components/chat-suggestion/chat-suggestion.tsx","../src/components/chat-thread/chat-thread.tsx","../src/components/chat-artifact/chat-artifact.tsx","../src/components/canvas-shell/canvas-shell.tsx","../src/components/new-chat-trigger/new-chat-trigger.tsx","../src/components/chat-thinking-process/chat-thinking-process.tsx","../src/components/deprecated-empty-state.ts","../src/components/rich-text-area/constants/index.ts","../src/components/rich-text-area/nodes/image-node.tsx","../src/components/rich-text-area/transformers.ts","../src/components/rich-text-area/html-config.ts","../src/components/rich-text-area/nodes/div-block-node.tsx","../src/components/rich-text-area/plugins/value-plugin.tsx","../src/components/rich-text-area/hooks.ts","../src/components/rich-text-area/plugins/disabled-plugin.tsx","../src/components/rich-text-area/plugins/controlled-plugin.tsx","../src/components/rich-text-area/utils/index.ts","../src/components/rich-text-area/plugins/controlled-value-plugin.tsx","../src/components/rich-text-area/plugins/blur-plugin.tsx","../src/components/rich-text-area/plugins/focus-plugin.tsx","../src/components/rich-text-area/plugins/image-drop-plugin.tsx","../src/components/rich-text-area/plugins/html-paste-plugin.tsx","../src/components/rich-text-area/plugins/markdown-plain-paste-plugin.tsx","../src/components/rich-text-area/plugins/file-attachment-plugin.tsx","../src/components/rich-text-area/styled.tsx","../src/components/rich-text-area/rich-text-area.tsx","../src/components/rich-text-field/constants.ts","../src/components/rich-text-field/components/toolbar-select.tsx","../src/components/rich-text-field/components/alignment-select.tsx","../src/components/rich-text-field/components/toolbar-button.tsx","../src/components/rich-text-field/components/attachment-button.tsx","../src/components/rich-text-field/utils.ts","../src/components/rich-text-field/context.tsx","../src/components/rich-text-field/components/bold-button.tsx","../src/components/rich-text-field/components/clean-format-button.tsx","../src/components/rich-text-field/components/image-button.tsx","../src/components/rich-text-field/components/italic-button.tsx","../src/components/rich-text-field/components/link-button.tsx","../src/components/rich-text-field/components/size-select.tsx","../src/components/rich-text-field/components/text-color-button.tsx","../src/components/rich-text-field/components/typography-select.tsx","../src/components/rich-text-field/components/underline-button.tsx","../src/components/rich-text-field/components/formatting-toolbar-plugin.tsx","../src/components/rich-text-field/rich-text-field.tsx","../src/components/topmenu/topmenu.tsx","../src/domain/actions/constants.ts","../src/domain/actions/utils/index.ts","../src/domain/actions/hooks/index.ts","../src/hooks/use-chat-stream-message.ts","../src/hooks/use-on-chat-changed.ts","../src/hooks/use-current-chat-id.ts","../src/hooks/use-is-current-chat-new.ts","../src/hooks/use-loaded-chat-ids.ts","../src/hooks/use-chat-prompt-placeholder.ts"],"sourcesContent":["import { createContext, useContext, type ReactNode } from 'react';\n\nimport type { ChatCardLevel } from './types';\n\nexport interface ChatCardContextValue {\n isCollapsible: boolean;\n level: ChatCardLevel;\n open: boolean;\n}\n\nconst ChatCardContext = createContext<ChatCardContextValue | null>(null);\n\nexport function useChatCardContext() {\n const context = useContext(ChatCardContext);\n\n if (!context) {\n throw new Error(\n '[web-chat-ui] useChatCardContext() called outside ChatCard. ' +\n 'Wrap this component in <ChatCard>, or the provider and the caller resolved two copies of the package.',\n );\n }\n\n return context;\n}\n\nexport function ChatCardProvider({\n value,\n children,\n}: {\n value: ChatCardContextValue;\n children: ReactNode;\n}) {\n return <ChatCardContext.Provider value={value}>{children}</ChatCardContext.Provider>;\n}\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport {\n CollapsibleChevron,\n CollapsibleTrigger,\n IconButton,\n Tooltip,\n Typography,\n type IconButtonProps,\n type TypographyProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatCardContext } from '../context';\n\n/** @deprecated Use `CardHeaderProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardHeaderProps extends Omit<ComponentProps<'header'>, 'aria-label'> {\n children: ReactNode;\n /**\n * Classes for the inner row that wraps the children (`data-slot=\"chat-card-header-hover-area\"`):\n * the element that highlights on hover and, in a collapsible card, toggles it.\n */\n hoverAreaClassName?: string;\n}\n\n/** @deprecated Use `CardHeader` from `@swisper.ai/cards-ui`. */\nexport function ChatCardHeader({\n className,\n children,\n hoverAreaClassName,\n ...rest\n}: ChatCardHeaderProps) {\n const { isCollapsible, level } = useChatCardContext();\n\n const inner = (\n <div\n data-slot=\"chat-card-header-hover-area\"\n className={cn(\n 'w-full',\n 'flex flex-row items-start',\n 'gap-card-header-gap',\n level === 1 && 'px-card-header-hover-area rounded-card-header',\n level === 1 && isCollapsible && 'hover:bg-layout-accent-low-background-hover-base',\n level === 1 && 'group-hover/chat-card:bg-layout-accent-low-background-hover-base',\n !isCollapsible && 'cursor-default',\n hoverAreaClassName,\n )}\n >\n {children}\n </div>\n );\n\n return (\n <header\n data-slot=\"chat-card-header\"\n data-level={level}\n data-collapsible={isCollapsible}\n className={cn(\n 'flex items-start',\n level === 1 ? 'p-card-header-lvl-1' : 'px-card-header-lvl-2',\n className,\n )}\n {...rest}\n >\n {isCollapsible ? (\n <CollapsibleTrigger className=\"w-full\" asChild>\n {inner}\n </CollapsibleTrigger>\n ) : (\n inner\n )}\n </header>\n );\n}\n\n/** @deprecated Use `CardIconProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardIconProps extends ComponentProps<'div'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardIcon` from `@swisper.ai/cards-ui`. */\nexport function ChatCardIcon({ className, children, ...rest }: ChatCardIconProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n data-slot=\"chat-card-icon\"\n data-testid=\"chat-card-icon\"\n data-level={level}\n className={cn(\n 'shrink-0',\n 'inline-flex items-center justify-center self-center',\n 'size-[32px]',\n 'bg-avatar-background',\n 'rounded-full overflow-hidden',\n level === 1 ? 'my-[14px]' : 'my-4',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardHeaderContentProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardHeaderContentProps extends ComponentProps<'div'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardHeaderContent` from `@swisper.ai/cards-ui`. */\nexport function ChatCardHeaderContent({\n className,\n children,\n ...rest\n}: ChatCardHeaderContentProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n data-slot=\"chat-card-header-content\"\n data-testid=\"chat-card-header-content\"\n data-level={level}\n className={cn(\n 'flex-1',\n 'flex flex-col gap-0 items-start justify-center',\n level === 1 ? 'min-h-[60px] py-1.5' : 'min-h-[40px] py-4',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardTitleProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardTitleProps extends Omit<TypographyProps, 'variant'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardTitle` from `@swisper.ai/cards-ui`. */\nexport function ChatCardTitle({ className, children, ...rest }: ChatCardTitleProps) {\n return (\n <Typography\n data-testid=\"chat-card-title\"\n variant=\"body-medium\"\n className={cn(className)}\n {...rest}\n >\n {children}\n </Typography>\n );\n}\n\n/** @deprecated Use `CardSubTitleProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardSubTitleProps extends Omit<TypographyProps, 'variant'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardSubTitle` from `@swisper.ai/cards-ui`. */\nexport function ChatCardSubTitle({ className, children, ...rest }: ChatCardSubTitleProps) {\n return (\n <Typography\n data-testid=\"chat-card-sub-title\"\n variant=\"body-small-high\"\n className={cn('text-text-secondary', className)}\n {...rest}\n >\n {children}\n </Typography>\n );\n}\n\n/** @deprecated Use `CardActionsProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardActionsProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardActions` from `@swisper.ai/cards-ui`. */\nexport function ChatCardActions({ className, children, ...rest }: ChatCardActionsProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n role=\"group\"\n data-slot=\"chat-card-actions\"\n data-testid=\"chat-card-actions\"\n data-level={level}\n className={cn(\n 'ml-auto shrink-0',\n 'flex items-center self-center gap-card-header-gap-icon-buttons',\n 'min-h-[32px]',\n '[&>button]:text-secondary-main!',\n level === 1 ? 'my-[14px]' : 'my-4',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardActionButtonProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardActionButtonProps extends Omit<IconButtonProps, 'variant' | 'size'> {\n children: ReactNode;\n shouldPreventCollapse?: boolean;\n tooltip?: ReactNode;\n}\n\n/** @deprecated Use `CardActionButton` from `@swisper.ai/cards-ui`. */\nexport function ChatCardActionButton({\n className,\n children,\n shouldPreventCollapse = true,\n tooltip,\n onClick,\n ...rest\n}: ChatCardActionButtonProps) {\n function handleClick(e: React.MouseEvent<HTMLButtonElement>) {\n if (shouldPreventCollapse) {\n e.stopPropagation();\n }\n\n onClick?.(e);\n }\n\n const content = (\n <IconButton\n data-slot=\"chat-card-action-button\"\n variant=\"tertiary\"\n size=\"sm\"\n className={cn(className)}\n onClick={handleClick}\n {...rest}\n >\n {children}\n </IconButton>\n );\n\n if (!tooltip) {\n return content;\n }\n\n return <Tooltip tooltip={tooltip}>{content}</Tooltip>;\n}\n\n/** @deprecated Use `CardCollapsibleButtonProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardCollapsibleButtonProps extends Omit<\n ChatCardActionButtonProps,\n 'children' | 'shouldPreventCollapse'\n> {}\n\n/** @deprecated Use `CardCollapsibleButton` from `@swisper.ai/cards-ui`. */\nexport function ChatCardCollapsibleButton({ className, ...rest }: ChatCardCollapsibleButtonProps) {\n const { isCollapsible } = useChatCardContext();\n if (!isCollapsible) {\n return;\n }\n\n return (\n <ChatCardActionButton\n data-slot=\"chat-card-collapsible-button\"\n shouldPreventCollapse={false}\n isSemantic={false}\n className={className}\n {...rest}\n >\n <CollapsibleChevron className=\"size-16\" />\n </ChatCardActionButton>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport type { ComponentProps, ReactNode } from 'react';\n\nimport { CollapsibleContent } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatCardContext } from '../context';\n\n/** @deprecated Use `CardMediaProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardMediaProps extends Omit<ComponentProps<'figure'>, 'aria-label'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardMedia` from `@swisper.ai/cards-ui`. */\nexport function ChatCardMedia({ className, children, ...rest }: ChatCardMediaProps) {\n return (\n <figure\n data-slot=\"chat-card-media\"\n data-testid=\"chat-card-media\"\n className={cn('min-h-0 shrink-0 h-[222px]', className)}\n {...rest}\n >\n {children}\n </figure>\n );\n}\n\n/** @deprecated Use `CardBodyProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardBodyProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** @deprecated Use `CardBody` from `@swisper.ai/cards-ui`. */\nexport function ChatCardBody({ className, children, asChild = false, ...rest }: ChatCardBodyProps) {\n const Component = asChild ? Slot : 'div';\n\n return (\n <CollapsibleContent\n data-slot=\"chat-card-body\"\n data-testid=\"chat-card-body\"\n className={cn(\n 'flex flex-1 flex-col',\n 'min-h-0',\n 'md:group-data-[collapsible=true]/cards-ui-card:max-h-[calc(var(--chat-window-height)*0.9)]',\n 'overflow-hidden',\n className,\n )}\n asChild\n {...rest}\n >\n <Component>{children}</Component>\n </CollapsibleContent>\n );\n}\n\n/** @deprecated Use `CardContentProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardContentProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n asChild?: boolean;\n hasPadding?: boolean;\n hasHeaderPadding?: boolean;\n}\n\n/** @deprecated Use `CardContent` from `@swisper.ai/cards-ui`. */\nexport function ChatCardContent({\n className,\n children,\n asChild = false,\n hasPadding = true,\n hasHeaderPadding = true,\n ...rest\n}: ChatCardContentProps) {\n const { level } = useChatCardContext();\n const Component = asChild ? Slot : 'div';\n\n return (\n <Component\n data-slot=\"chat-card-content\"\n data-testid=\"chat-card-content\"\n data-padding={hasPadding}\n data-has-header-padding={hasHeaderPadding}\n data-level={level}\n className={cn(\n 'overflow-auto',\n 'gap-card-slots-gap',\n 'data-[level=1]:p-card-slots-lvl-1',\n 'data-[level=2]:p-card-slots-lvl-2',\n 'data-[has-header-padding=false]:pt-0',\n 'data-[padding=false]:p-0',\n className,\n )}\n {...rest}\n >\n {children}\n </Component>\n );\n}\n\n/** @deprecated Use `CardPreviewProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardPreviewProps extends ComponentProps<'div'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardPreview` from `@swisper.ai/cards-ui`. */\nexport function ChatCardPreview({ className, children, ...rest }: ChatCardPreviewProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n data-slot=\"chat-card-preview\"\n data-testid=\"chat-card-preview\"\n data-level={level}\n className={cn(\n 'group-data-[state=open]/collapsible:hidden',\n 'overflow-auto',\n 'pt-0',\n 'data-[level=1]:p-card-slots-lvl-1',\n 'data-[level=2]:p-card-slots-lvl-2',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatCardContext } from '../context';\n\n/** @deprecated Use `CardFooterProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterProps extends ComponentProps<'footer'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardFooter` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooter({ className, children, ...rest }: ChatCardFooterProps) {\n const { level } = useChatCardContext();\n\n return (\n <footer\n data-slot=\"chat-card-footer\"\n data-level={level}\n className={cn(\n 'mt-auto',\n 'flex flex-row items-center justify-end',\n 'gap-card-footer-gap',\n 'w-full',\n 'data-[level=1]:p-card-footer-lvl-1',\n 'data-[level=2]:p-card-footer-lvl-2',\n className,\n )}\n {...rest}\n >\n {children}\n </footer>\n );\n}\n\n/** @deprecated Put your own block in `CardFooterLeft` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterNotesProps {\n children: ReactNode;\n className?: string;\n}\n\n/** @deprecated Put your own block in `CardFooterLeft` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooterNotes({ className, children }: ChatCardFooterNotesProps) {\n return (\n <div\n data-slot=\"chat-card-footer-notes\"\n data-testid=\"chat-card-footer-notes\"\n className={cn(\n 'mr-auto shrink-0',\n 'flex flex-col items-start justify-center',\n 'gap-card-footer-gap-left-notes',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Put your own block in `CardFooterRight` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterPriceProps {\n children: ReactNode;\n className?: string;\n}\n\n/** @deprecated Put your own block in `CardFooterRight` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooterPrice({ className, children }: ChatCardFooterPriceProps) {\n return (\n <div\n data-slot=\"chat-card-footer-price\"\n data-testid=\"chat-card-footer-price\"\n className={cn(\n 'flex flex-col items-end justify-center',\n 'gap-card-footer-gap-prices',\n 'shrink-0',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardFooterActionsProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterActionsProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardFooterActions` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooterActions({\n className,\n children,\n ...rest\n}: ChatCardFooterActionsProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-card-footer-actions\"\n data-testid=\"chat-card-footer-actions\"\n className={cn('flex items-center gap-card-footer-gap shrink-0', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport { forwardRef } from 'react';\nimport type { ComponentProps, ReactNode } from 'react';\n\nimport { Chip, Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\n/** @deprecated Use `CardFieldsProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFormProps extends ComponentProps<'form'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** @deprecated The props of `ChatCardForm` under the component's own name; use `ChatCardFormProps`. */\nexport interface ChatCardForm extends ChatCardFormProps {}\n\n/** @deprecated Use `CardFields` from `@swisper.ai/cards-ui`. */\nexport const ChatCardForm = forwardRef<HTMLFormElement, ChatCardFormProps>(function ChatCardForm(\n { className, children, asChild, ...rest },\n ref,\n) {\n const Component = asChild ? Slot : 'form';\n\n return (\n <Component\n ref={ref}\n data-slot=\"chat-card-form\"\n data-testid=\"chat-card-form\"\n className={cn(\n 'bg-steel-900 border border-steel-700',\n 'rounded-[12px]',\n 'm-8 mb-16 p-[12px]',\n 'overflow-hidden',\n className,\n )}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardForm.displayName = 'ChatCardForm';\n\n/** @deprecated Use `CardAttributesProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributesProps {\n children: ReactNode;\n className?: string;\n}\n\n/** @deprecated Use `CardAttributes` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttributes({ className, children }: ChatCardAttributesProps) {\n return (\n <ul\n data-slot=\"chat-card-attributes\"\n data-testid=\"chat-card-attributes\"\n className={cn('flex flex-col justify-start items-start gap-8', 'mb-24', className)}\n >\n {children}\n </ul>\n );\n}\n\n/** @deprecated Use `CardAttributeProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributeProps {\n className?: string;\n children: ReactNode;\n}\n\n/** @deprecated Use `CardAttribute` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttribute({ className, children, ...rest }: ChatCardAttributeProps) {\n return (\n <li\n data-slot=\"chat-card-attribute\"\n data-testid=\"chat-card-attribute-item\"\n className={cn('grid grid-cols-[66px_1fr] gap-8', 'w-full', 'min-h-24', className)}\n {...rest}\n >\n {children}\n </li>\n );\n}\n\n/** @deprecated Use `CardAttributeLabelProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributeLabelProps {\n children: ReactNode;\n className?: string;\n hasPadding?: boolean;\n}\n\n/** @deprecated Use `CardAttributeLabel` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttributeLabel({\n className,\n children,\n hasPadding = false,\n ...rest\n}: ChatCardAttributeLabelProps) {\n return (\n <Chip\n variant=\"outlined\"\n size=\"md\"\n color=\"info\"\n data-slot=\"chat-card-attribute-label\"\n data-has-padding={hasPadding}\n className={cn('w-full', 'data-[has-padding=true]:my-[5px]', className)}\n data-testid=\"chat-card-attribute-label\"\n {...rest}\n >\n {children}\n </Chip>\n );\n}\n\n/** @deprecated Use `CardAttributeValueProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributeValueProps extends Omit<ComponentProps<'dt'>, 'aria-Value'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** @deprecated Use `CardAttributeValue` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttributeValue({\n className,\n children,\n asChild = false,\n ...rest\n}: ChatCardAttributeValueProps) {\n const Component = asChild ? Slot : Typography;\n\n return (\n <Component\n data-testid=\"chat-card-attribute-value\"\n variant=\"body-sm\"\n className={cn('flex-1 text-text-secondary', className)}\n {...rest}\n >\n {children}\n </Component>\n );\n}\n","import { forwardRef, useCallback, useMemo, useState } from 'react';\n\nimport { Collapsible } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { ChatCardProvider } from './context';\nimport type { ChatCardProps } from './types';\n\nexport { useChatCardContext } from './context';\n\n/** @deprecated Use `Card` from `@swisper.ai/cards-ui`. */\nexport const ChatCard = forwardRef<HTMLElement, ChatCardProps>(function ChatCard(\n {\n className,\n variant = 'default',\n level = 1,\n children,\n fullWidth = false,\n defaultOpen = true,\n open: openProp,\n isRounded = true,\n isCollapsible = true,\n isSelected = false,\n onOpenChange,\n onClick,\n ...rest\n },\n ref,\n) {\n const isControlled = openProp !== undefined;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n const open = isControlled ? openProp : uncontrolledOpen;\n\n const handleOpenChange = useCallback(\n (next: boolean) => {\n if (!isControlled) {\n setUncontrolledOpen(next);\n }\n onOpenChange?.(next);\n },\n [isControlled, onOpenChange],\n );\n\n const contextValue = useMemo(\n () => ({\n isCollapsible,\n level,\n open,\n }),\n [isCollapsible, level, open],\n );\n\n function handleClick(event: React.MouseEvent<HTMLElement>) {\n onClick?.(event);\n if (event.defaultPrevented) {\n return;\n }\n\n // Closed surface is the expand hit target. Never toggle here: an expanded\n // body/footer click must not collapse the card.\n if (isCollapsible && !open) {\n handleOpenChange(true);\n }\n }\n\n return (\n <ChatCardProvider value={contextValue}>\n <Collapsible isDisabled={!isCollapsible} open={open} onOpenChange={handleOpenChange} asChild>\n <section\n ref={ref}\n role=\"region\"\n data-slot=\"chat-card\"\n aria-current={isSelected}\n data-testid=\"chat-card\"\n data-variant={variant}\n data-level={level}\n data-full-width={fullWidth}\n data-rounded={isRounded}\n data-selected={isSelected}\n data-collapsible={isCollapsible}\n onClick={handleClick}\n className={cn(\n 'group/chat-card',\n // keep card smaller width in a closed state\n 'w-full data-[state=closed]:max-w-(--message-list-content-width) data-[state=closed]:mx-auto',\n 'flex flex-col',\n 'relative overflow-hidden',\n 'border border-solid border-card-border-base',\n 'data-[level=1]:bg-card-background-base',\n 'data-[level=2]:bg-card-background-lvl-2',\n 'data-[full-width=true]:w-full',\n 'data-[level=1]:data-[rounded=true]:rounded-card-lvl-1',\n 'data-[level=2]:data-[rounded=true]:rounded-card-lvl-2',\n 'data-[selected=true]:border-primary-main',\n 'hover:data-[variant=action]:bg-secondary-states-hover',\n 'data-[collapsible=true]:data-[state=closed]:cursor-pointer',\n className,\n )}\n {...rest}\n >\n {children}\n </section>\n </Collapsible>\n </ChatCardProvider>\n );\n});\n\nChatCard.displayName = 'ChatCard';\n","import { useState } from 'react';\n\ninterface UseEditChatCardProps {\n isEditable: boolean;\n defaultEditing?: boolean;\n}\n\n/** @deprecated `@swisper.ai/cards-ui` holds no edit state: keep `isEditing` in the app and pass it to `Card`'s `isSelected`. */\nexport function useEditChatCard({ isEditable, defaultEditing = false }: UseEditChatCardProps) {\n const [isEditing, setIsEditing] = useState(defaultEditing);\n\n function checkIsEditable() {\n if (!isEditable) {\n console.warn('Chat card is not editable');\n return false;\n }\n\n return true;\n }\n\n function startEdit() {\n if (!checkIsEditable()) {\n return;\n }\n\n setIsEditing(true);\n }\n\n function discard() {\n if (!checkIsEditable()) {\n return;\n }\n\n setIsEditing(false);\n }\n\n function toggleEdit() {\n if (!checkIsEditable()) {\n return;\n }\n\n setIsEditing((e) => !e);\n }\n\n return {\n isEditable,\n isEditing,\n startEdit,\n discard,\n toggleEdit,\n };\n}\n","import { type ReactNode, createContext, useContext } from 'react';\n\nimport { useEditChatCard } from './hooks';\n\ntype EditableChatCardContextValue = ReturnType<typeof useEditChatCard>;\n\nconst EditableChatCardContext = createContext<EditableChatCardContextValue>(null!);\n\n/** @deprecated `@swisper.ai/cards-ui` holds no edit state: keep `isEditing` in the app and pass it to `Card`'s `isSelected`. */\nexport function useEditableChatCardContext() {\n const context = useContext(EditableChatCardContext);\n\n if (!context) {\n throw new Error(\n '\"useEditableChatCardContext\" must be used within a EditableChatCardContextProvider',\n );\n }\n\n return context;\n}\n\ninterface EditableChatCardContextProviderProps {\n children: ReactNode;\n defaultEditing?: boolean;\n isEditable?: boolean;\n}\n\n/** @deprecated `@swisper.ai/cards-ui` holds no edit state: keep `isEditing` in the app and pass it to `Card`'s `isSelected`. */\nexport function EditableChatCardContextProvider({\n children,\n defaultEditing = false,\n isEditable = false,\n}: EditableChatCardContextProviderProps) {\n const contextValue = useEditChatCard({\n isEditable,\n defaultEditing,\n });\n\n return (\n <EditableChatCardContext.Provider value={contextValue}>\n {children}\n </EditableChatCardContext.Provider>\n );\n}\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\n/** @deprecated Use `FlexibleContainerVariant` from `@swisper.ai/cards-ui`. */\nexport type ChatCardContainerVariant = 'fixed' | 'fluid' | 'full';\n\n/** @deprecated Use `FlexibleContainerProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardContainerProps extends ComponentProps<'div'> {\n children: ReactNode;\n /**\n * How the card is sized against the chat window published by `ChatContainer`:\n *\n * - `fixed` — clamped to the reading column (`--message-list-content-width`) from\n * `md` up, so body cards line up with the message text.\n * - `fluid` — shrinks to its content from `md` up, still capped at the window.\n * - `full` — always the full chat window width.\n *\n * Below `md` (820px in this design system, not Tailwind's default 768px) all three\n * are full width. There is no room to distinguish them on a phone, and a card\n * narrower than the viewport there reads as a layout bug.\n */\n variant?: ChatCardContainerVariant;\n /**\n * Set when the card is rendered inside a message body rather than as its own block,\n * so it aligns with the surrounding text.\n *\n * This swaps the inset from margin to padding rather than adding a second one: the\n * width cap opens up to the full `--chat-window-width` and `px-message` supplies the\n * gutter, so the total inset stays at one `--spacing-message` either way. Applying\n * `px-message` on top of the block cap instead would inset an inlined card by two\n * gutters and it would visibly not line up with the text around it.\n */\n inline?: boolean;\n}\n\n/**\n * Sizes a card inside a `ChatContainer`, against the `--chat-window-width` and\n * `--message-list-content-width` variables that container publishes.\n *\n * `full` is the base behaviour and adds no classes of its own — every variant starts\n * at the window width less one `--spacing-message` gutter, and `fixed` and `fluid`\n * narrow it from `md` up.\n *\n * Both variables are read with a `100%` fallback, so a card rendered outside a\n * `ChatContainer` (a portal, a test, a Storybook story) degrades to its parent's width\n * instead of collapsing to zero.\n *\n * @deprecated Use `FlexibleContainer` from `@swisper.ai/cards-ui`.\n */\nexport function ChatCardContainer({\n children,\n variant = 'fixed',\n inline = false,\n className,\n ...rest\n}: ChatCardContainerProps) {\n return (\n <div\n data-slot=\"chat-card-container\"\n data-testid=\"chat-card-container\"\n data-variant={variant}\n data-inline={inline}\n className={cn(\n 'mx-auto w-full',\n 'max-w-[calc(var(--chat-window-width,100%)-var(--spacing-message))]',\n 'md:data-[variant=fixed]:max-w-[calc(var(--message-list-content-width,var(--spacing-chat-area))-var(--spacing-message))]',\n 'md:data-[variant=fluid]:min-w-[calc(var(--message-list-content-width,var(--spacing-chat-area))-var(--spacing-message))]',\n 'md:data-[variant=fluid]:w-fit',\n 'md:data-[variant=full]:max-w-full',\n 'data-[inline=true]:max-w-[var(--chat-window-width,100%)]',\n 'data-[inline=true]:px-message',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport {\n createContext,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useState,\n type ComponentProps,\n type CSSProperties,\n type ReactNode,\n} from 'react';\n\nimport { cn, useElementMeasure } from '@swisper.ai/web-core';\n\n/**\n * Width of the reading column when the consumer does not override it.\n *\n * Read from `--spacing-chat-area` (736px) rather than hardcoded, so a theme that\n * retunes the chat area token moves the reading column with it.\n */\nconst DEFAULT_CONTENT_WIDTH = 'var(--spacing-chat-area)';\n\n/**\n * The slots a child can measure itself into, and the custom property each publishes.\n *\n * These two heights cannot be measured by `ChatContainer` itself — they belong to\n * specific children whose size the rest of the layout has to react to (the composer\n * grows as the user types; the welcome box only exists on an empty chat). The slot\n * reports upward so the variable lands on the container, where *siblings* can read it\n * too; publishing it on the slot's own element would scope it to that subtree and the\n * message list could not size against it.\n */\nconst SLOT_VARIABLES = {\n prompt: '--type-window-height',\n welcome: '--welcome-screen-box-height',\n} as const;\n\ntype ChatContainerSlot = keyof typeof SLOT_VARIABLES;\n\ntype MeasuredLength = number | 'unset';\n\n/** `unset` mirrors the pre-measurement state; for a height it computes as `auto`. */\nfunction toCssLength(value: MeasuredLength): string {\n return value === 'unset' ? 'unset' : `${value}px`;\n}\n\ninterface ChatContainerContextValue {\n setSlotHeight: (slot: ChatContainerSlot, height: MeasuredLength) => void;\n}\n\nconst ChatContainerContext = createContext<ChatContainerContextValue | null>(null);\n\nfunction useChatContainerContext() {\n const context = useContext(ChatContainerContext);\n\n if (!context) {\n throw new Error(\n '[web-chat-ui] ChatContainer slot rendered outside a ChatContainer. ' +\n 'ChatContainerPrompt and ChatContainerWelcome report their measured height up ' +\n 'to the container, so one must be mounted above them. If it is mounted, check ' +\n 'the slot is not rendered through a portal that escapes the provider.',\n );\n }\n\n return context;\n}\n\nexport interface ChatContainerProps extends ComponentProps<'section'> {\n children: ReactNode;\n /**\n * Max width of the reading column, published as `--message-list-content-width` and\n * consumed by `ChatCardContainer`'s `fixed` variant. Any CSS length.\n *\n * The published value is clamped with `min()` against the measured window width, so\n * a container narrower than the reading column never sizes a child wider than\n * itself — the case that makes a card overflow horizontally in a split-pane layout.\n */\n contentWidth?: string;\n asChild?: boolean;\n}\n\n/**\n * Root of a chat surface. Measures its own box and republishes it as CSS custom\n * properties, so descendants size themselves against the chat window without a width\n * being prop-drilled through every layer:\n *\n * - `--chat-window-width` / `--chat-window-height` — the measured border box, or\n * `100%` until the first measurement lands.\n * - `--message-list-content-width` — the reading column (see `contentWidth`).\n * - `--type-window-height` / `--welcome-screen-box-height` — reported up by\n * `ChatContainerPrompt` and `ChatContainerWelcome`; `unset` while unmounted.\n *\n * Deliberately applies **no horizontal padding of its own**. `useElementMeasure`\n * reports the border box, so padding here would be counted inside\n * `--chat-window-width`, and every child sizing against that variable would overflow\n * by exactly that padding. Insetting is the child's job instead, through the\n * `--spacing-message` gutter that `ChatCardContainer` subtracts.\n *\n * Every read site carries a `100%` fallback, so children still lay out sensibly when\n * rendered outside a `ChatContainer` (portals, tests, Storybook).\n */\nexport function ChatContainer({\n asChild = false,\n children,\n className,\n contentWidth = DEFAULT_CONTENT_WIDTH,\n style,\n ...rest\n}: ChatContainerProps) {\n const Comp = asChild ? Slot : 'section';\n const { ref, width, height } = useElementMeasure<HTMLElement>();\n const [slotHeights, setSlotHeights] = useState<Record<ChatContainerSlot, MeasuredLength>>({\n prompt: 'unset',\n welcome: 'unset',\n });\n\n const setSlotHeight = useCallback((slot: ChatContainerSlot, slotHeight: MeasuredLength) => {\n // Returning the same object on an unchanged height keeps a slot's resize effect\n // from re-rendering the whole chat on every observer callback.\n setSlotHeights((current) =>\n current[slot] === slotHeight ? current : { ...current, [slot]: slotHeight },\n );\n }, []);\n\n const contextValue = useMemo<ChatContainerContextValue>(\n () => ({ setSlotHeight }),\n [setSlotHeight],\n );\n\n const containerStyle = useMemo(\n () =>\n ({\n '--chat-window-width': width === 'unset' ? '100%' : `${width}px`,\n '--chat-window-height': height === 'unset' ? '100%' : `${height}px`,\n '--message-list-content-width': `min(${contentWidth}, var(--chat-window-width))`,\n [SLOT_VARIABLES.prompt]: toCssLength(slotHeights.prompt),\n [SLOT_VARIABLES.welcome]: toCssLength(slotHeights.welcome),\n ...style,\n }) as CSSProperties,\n [width, height, contentWidth, slotHeights, style],\n );\n\n return (\n <ChatContainerContext.Provider value={contextValue}>\n <Comp\n ref={ref}\n data-slot=\"chat-container\"\n data-testid=\"chat-container\"\n className={cn('relative flex h-full min-h-0 w-full flex-col', className)}\n style={containerStyle}\n {...rest}\n >\n {children}\n </Comp>\n </ChatContainerContext.Provider>\n );\n}\n\n/** Measures the slot element and reports its height to the nearest `ChatContainer`. */\nfunction useChatContainerSlot(slot: ChatContainerSlot) {\n const { setSlotHeight } = useChatContainerContext();\n // `HTMLElement`, not `HTMLDivElement`: with `asChild` the measured node is whatever\n // element the consumer rendered, and the callback ref has to accept all of them.\n const { ref, height } = useElementMeasure<HTMLElement>();\n\n useLayoutEffect(() => {\n setSlotHeight(slot, height);\n\n // Reset on unmount so a layout that hides the welcome box after the first message\n // does not leave a stale height behind for the message list to reserve space for.\n return () => setSlotHeight(slot, 'unset');\n }, [slot, height, setSlotHeight]);\n\n return ref;\n}\n\nexport interface ChatContainerSlotProps extends ComponentProps<'div'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/**\n * Wraps the composer. Publishes its measured height as `--type-window-height` on the\n * container, so the message list can reserve room for a composer that grows as the\n * user types.\n */\nexport function ChatContainerPrompt({\n asChild = false,\n children,\n className,\n ...rest\n}: ChatContainerSlotProps) {\n const ref = useChatContainerSlot('prompt');\n const Comp = asChild ? Slot : 'div';\n\n return (\n <Comp\n ref={ref}\n data-slot=\"chat-container-prompt\"\n data-testid=\"chat-container-prompt\"\n className={cn('shrink-0', className)}\n {...rest}\n >\n {children}\n </Comp>\n );\n}\n\n/**\n * Wraps the empty-chat welcome box. Publishes its measured height as\n * `--welcome-screen-box-height` on the container.\n */\nexport function ChatContainerWelcome({\n asChild = false,\n children,\n className,\n ...rest\n}: ChatContainerSlotProps) {\n const ref = useChatContainerSlot('welcome');\n const Comp = asChild ? Slot : 'div';\n\n return (\n <Comp\n ref={ref}\n data-slot=\"chat-container-welcome\"\n data-testid=\"chat-container-welcome\"\n className={cn('shrink-0', className)}\n {...rest}\n >\n {children}\n </Comp>\n );\n}\n","import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';\nimport { useEffect } from 'react';\n\ninterface AutoFocusPluginProps {\n autoFocus?: boolean;\n isDisabled?: boolean;\n defaultSelection?: 'rootStart' | 'rootEnd';\n}\n\nexport function AutoFocusPlugin({\n defaultSelection = 'rootEnd',\n autoFocus,\n isDisabled,\n}: AutoFocusPluginProps) {\n const [editor] = useLexicalComposerContext();\n\n useEffect(() => {\n if (!autoFocus || isDisabled) {\n return;\n }\n\n editor.focus(\n () => {\n // If we try and move selection to the same point with setBaseAndExtent, it won't\n // trigger a re-focus on the element. So in the case this occurs, we'll need to correct it.\n // Normally this is fine, Selection API !== Focus API, but fore the intents of the naming\n // of this plugin, which should preserve focus too.\n const activeElement = document.activeElement;\n const rootElement = editor.getRootElement() as HTMLDivElement;\n if (\n rootElement !== null &&\n (activeElement === null || !rootElement.contains(activeElement))\n ) {\n // Note: preventScroll won't work in Webkit.\n rootElement.focus({ preventScroll: true });\n }\n },\n { defaultSelection },\n );\n }, [defaultSelection, editor, autoFocus, isDisabled]);\n\n return null;\n}\n","import { TRANSFORMERS } from '@lexical/markdown';\n\nexport const EXPORT_TRANSFORMERS = TRANSFORMERS;\nexport const IMPORT_TRANSFORMERS = TRANSFORMERS;\n","import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';\n\nexport function useChatInputEditor() {\n const [editor] = useLexicalComposerContext();\n\n return editor;\n}\n","import {\n $createParagraphNode,\n $createRangeSelection,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n $isTextNode,\n $selectAll,\n $setSelection,\n} from 'lexical';\n\nexport function $getEditorPlainText(): string {\n return $getRoot().getTextContent();\n}\n\nexport function $setEditorPlainText(value: string): void {\n const root = $getRoot();\n root.clear();\n const paragraph = $createParagraphNode();\n if (value) {\n paragraph.append($createTextNode(value));\n }\n root.append(paragraph);\n}\n\nexport function $setSelectionToEnd(): void {\n const root = $getRoot();\n const lastDescendant = root.getLastDescendant();\n\n if (lastDescendant && $isTextNode(lastDescendant)) {\n const selection = $createRangeSelection();\n const endOffset = lastDescendant.getTextContentSize();\n selection.anchor.set(lastDescendant.getKey(), endOffset, 'text');\n selection.focus.set(lastDescendant.getKey(), endOffset, 'text');\n $setSelection(selection);\n } else {\n $selectAll();\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const focusNode = selection.focus.getNode();\n const focusOffset = $isTextNode(focusNode) ? focusNode.getTextContentSize() : 0;\n selection.anchor.set(selection.focus.key, selection.focus.offset, selection.focus.type);\n selection.focus.set(selection.focus.key, focusOffset, selection.focus.type);\n $setSelection(selection);\n }\n }\n}\n","import { $convertFromMarkdownString, $convertToMarkdownString } from '@lexical/markdown';\nimport { $addUpdateTag, SKIP_DOM_SELECTION_TAG } from 'lexical';\nimport { type MutableRefObject, useEffect, useRef } from 'react';\n\nimport { EXPORT_TRANSFORMERS, IMPORT_TRANSFORMERS } from '../transformers';\n\nimport { useChatInputEditor } from './hooks';\nimport { $setSelectionToEnd } from './utils';\n\ninterface ControlledValuePluginProps {\n value?: string;\n /** The values `ValuePlugin` gave to `onChange` that the parent has not rendered back yet. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ControlledValuePlugin({ value, emittedValuesRef }: ControlledValuePluginProps) {\n const editor = useChatInputEditor();\n const previousValueRef = useRef<string | undefined>();\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n\n if (value === previousValueRef.current) {\n return;\n }\n\n previousValueRef.current = value;\n\n // The parent renders back each value `onChange` gave it, and that render can land after later\n // keystrokes. Such a value is an echo of an older edit, not a change to apply: applying it\n // would drop what was typed since.\n if (emittedValuesRef && value !== undefined) {\n const echoIndex = emittedValuesRef.current.lastIndexOf(value);\n emittedValuesRef.current.splice(0, echoIndex === -1 ? Infinity : echoIndex + 1);\n if (echoIndex !== -1) {\n return;\n }\n }\n\n let currentValue = '';\n editor.getEditorState().read(() => {\n currentValue = $convertToMarkdownString(EXPORT_TRANSFORMERS);\n });\n\n if (value !== undefined && value !== currentValue) {\n editor.update(\n () => {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n $convertFromMarkdownString(value ?? '', IMPORT_TRANSFORMERS);\n $setSelectionToEnd();\n },\n { discrete: true },\n );\n }\n }, [editor, value, emittedValuesRef]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useChatInputEditor } from './hooks';\n\ninterface DisabledPluginProps {\n isDisabled?: boolean;\n isReadOnly?: boolean;\n}\n\nexport function DisabledPlugin({ isDisabled, isReadOnly }: DisabledPluginProps) {\n const editor = useChatInputEditor();\n\n useEffect(() => {\n editor.setEditable(!isDisabled && !isReadOnly);\n }, [editor, isDisabled, isReadOnly]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useChatInputEditor } from './hooks';\n\ninterface FocusPluginProps {\n onFocusChange?: (isFocused: boolean) => void;\n}\n\nexport function FocusPlugin({ onFocusChange }: FocusPluginProps) {\n const editor = useChatInputEditor();\n\n useEffect(() => {\n if (!onFocusChange) {\n return;\n }\n\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n\n function handleFocus() {\n if (rootElement && onFocusChange) {\n onFocusChange(true);\n }\n }\n\n function handleBlur(event: FocusEvent) {\n if (rootElement && onFocusChange && !rootElement.contains(event.relatedTarget as Node)) {\n onFocusChange(false);\n }\n }\n\n rootElement.addEventListener('focus', handleFocus, true);\n rootElement.addEventListener('blur', handleBlur, true);\n\n return () => {\n rootElement.removeEventListener('focus', handleFocus, true);\n rootElement.removeEventListener('blur', handleBlur, true);\n };\n }, [editor, onFocusChange]);\n\n return null;\n}\n","import type { LexicalEditor } from 'lexical';\nimport { useEffect, useRef } from 'react';\n\nimport { useChatInputEditor } from './hooks';\nimport { $getEditorPlainText } from './utils';\n\ninterface HasValuePluginProps {\n onHasValueChange?: (hasValue: boolean) => void;\n}\n\nfunction getHasValue(editor: LexicalEditor): boolean {\n let hasValue = false;\n editor.getEditorState().read(() => {\n hasValue = $getEditorPlainText().length > 0;\n });\n return hasValue;\n}\n\nfunction syncHasValue(\n editor: LexicalEditor,\n onHasValueChange: ((hasValue: boolean) => void) | undefined,\n lastHasValueRef: { current: boolean | undefined },\n): void {\n const hasValue = getHasValue(editor);\n\n if (lastHasValueRef.current === hasValue) {\n return;\n }\n\n lastHasValueRef.current = hasValue;\n onHasValueChange?.(hasValue);\n}\n\nexport function HasValuePlugin({ onHasValueChange }: HasValuePluginProps) {\n const editor = useChatInputEditor();\n const lastHasValueRef = useRef<boolean | undefined>();\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n\n syncHasValue(editor, onHasValueChange, lastHasValueRef);\n\n return editor.registerUpdateListener(() => {\n syncHasValue(editor, onHasValueChange, lastHasValueRef);\n });\n }, [editor, onHasValueChange]);\n\n return null;\n}\n","import {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n COMMAND_PRIORITY_CRITICAL,\n PASTE_COMMAND,\n} from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useChatInputEditor } from './hooks';\n\nexport function MarkdownPlainPastePlugin() {\n const editor = useChatInputEditor();\n\n useEffect(() => {\n return editor.registerCommand<ClipboardEvent>(\n PASTE_COMMAND,\n (event) => {\n const { clipboardData } = event;\n\n if (!clipboardData) {\n return false;\n }\n\n const plainText = clipboardData.getData('text/plain');\n\n if (!plainText) {\n return false;\n }\n\n event.preventDefault();\n\n editor.update(() => {\n const selection = $getSelection();\n\n if ($isRangeSelection(selection)) {\n selection.insertText(plainText);\n return;\n }\n\n const root = $getRoot();\n root.clear();\n\n const lines = plainText.split(/\\r?\\n/);\n lines.forEach((line) => {\n const paragraph = $createParagraphNode();\n if (line.length > 0) {\n paragraph.append($createTextNode(line));\n }\n root.append(paragraph);\n });\n });\n\n return true;\n },\n COMMAND_PRIORITY_CRITICAL,\n );\n }, [editor]);\n\n return null;\n}\n","import { $convertToMarkdownString } from '@lexical/markdown';\nimport { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';\nimport type { EditorState, LexicalEditor } from 'lexical';\nimport { type MutableRefObject, useCallback } from 'react';\n\nimport { EXPORT_TRANSFORMERS } from '../transformers';\n\n/** How many emitted values to remember; a parent that never echoes them back must not grow the list. */\nconst MAX_EMITTED_VALUES = 50;\n\ninterface ValuePluginProps {\n onChange?: (value: string) => void;\n /** Receives every value given to `onChange`, so `ControlledValuePlugin` can tell an echo of one. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ValuePlugin({ onChange, emittedValuesRef }: ValuePluginProps) {\n const handleChange = useCallback(\n (editorState: EditorState, _editor: LexicalEditor, tags: Set<string>) => {\n if (tags.has('focus')) {\n return;\n }\n\n if (!onChange) {\n return;\n }\n\n try {\n editorState.read(() => {\n const value = $convertToMarkdownString(EXPORT_TRANSFORMERS);\n\n if (emittedValuesRef) {\n emittedValuesRef.current.push(value);\n emittedValuesRef.current.splice(\n 0,\n emittedValuesRef.current.length - MAX_EMITTED_VALUES,\n );\n }\n\n onChange(value);\n });\n } catch (error) {\n console.error('ValuePlugin error:', error);\n }\n },\n [onChange, emittedValuesRef],\n );\n\n return <OnChangePlugin onChange={handleChange} />;\n}\n","import { CodeNode } from '@lexical/code';\nimport { LinkNode } from '@lexical/link';\nimport { ListItemNode, ListNode } from '@lexical/list';\nimport { type InitialConfigType, LexicalComposer } from '@lexical/react/LexicalComposer';\nimport { ContentEditable } from '@lexical/react/LexicalContentEditable';\nimport { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';\nimport { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';\nimport { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';\nimport { HeadingNode, QuoteNode } from '@lexical/rich-text';\nimport { createContext, forwardRef, useContext, useMemo, useRef, useState } from 'react';\nimport type { CSSProperties, ComponentPropsWithoutRef, KeyboardEvent, ReactNode } from 'react';\n\nimport { Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport {\n AutoFocusPlugin,\n ControlledValuePlugin,\n DisabledPlugin,\n FocusPlugin,\n HasValuePlugin,\n MarkdownPlainPastePlugin,\n ValuePlugin,\n} from './plugins';\n\nexport type ChatInputConfig = InitialConfigType;\n\ninterface ChatInputContextValue {\n isFocused: boolean;\n hasError: boolean;\n hasValue: boolean;\n\n setIsFocused: (isFocused: boolean) => void;\n setHasError: (hasError: boolean) => void;\n setHasValue: (hasValue: boolean) => void;\n}\n\nconst ChatInputContext = createContext<ChatInputContextValue>(null!);\n\n/**\n * The editor state `ChatInput` tracks (`isFocused`, `hasValue`, `hasError`) and its setters.\n * Throws when called outside a `ChatInput`.\n */\nexport function useChatInputContext() {\n const context = useContext(ChatInputContext);\n\n if (!context) {\n throw new Error('\"useChatInputContext\" must be used within a ChatInputContextProvider');\n }\n\n return context;\n}\n\nexport const DEFAULT_CONFIG: ChatInputConfig = {\n namespace: 'chat-input',\n editable: true,\n nodes: [HeadingNode, QuoteNode, ListNode, ListItemNode, CodeNode, LinkNode],\n theme: {\n paragraph: 'm-0 min-h-[26px]',\n text: {\n bold: 'font-bold',\n italic: 'italic',\n underline: 'underline',\n },\n },\n onError: (error) => {\n console.error('ChatInput Lexical error:', error);\n },\n};\n\nexport interface ChatInputProps extends ComponentPropsWithoutRef<'div'> {\n /** Lexical composer config, read once on mount. Override only to add nodes or retheme. */\n initialConfig?: ChatInputConfig;\n}\n\n/**\n * Root of the composer: holds the Lexical editor and puts its state on the wrapper as\n * `data-focused`, `data-empty` and `data-error`. Ships unstyled.\n */\nexport const ChatInput = forwardRef<HTMLDivElement, ChatInputProps>(function ChatInput(\n { className, children, initialConfig = DEFAULT_CONFIG, ...rest },\n ref,\n) {\n const [hasError, setHasError] = useState(false);\n const [hasValue, setHasValue] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n const contextValue = useMemo(\n () => ({\n hasError,\n hasValue,\n isFocused,\n setHasError,\n setHasValue,\n setIsFocused,\n }),\n [hasError, hasValue, isFocused],\n );\n\n return (\n <ChatInputContext.Provider value={contextValue}>\n <LexicalComposer initialConfig={initialConfig}>\n <div\n ref={ref}\n data-slot=\"chat-input\"\n data-testid=\"chat-input\"\n data-focused={isFocused}\n data-empty={!hasValue}\n data-error={hasError}\n aria-invalid={hasError}\n className={cn('group/chat-input', 'relative', className)}\n {...rest}\n >\n {children}\n </div>\n </LexicalComposer>\n </ChatInputContext.Provider>\n );\n});\n\nChatInput.displayName = 'ChatInput';\n\nexport interface ChatInputPlaceholderProps extends ComponentPropsWithoutRef<'span'> {}\n\nexport const ChatInputPlaceholder = forwardRef<HTMLSpanElement, ChatInputPlaceholderProps>(\n function ChatInputPlaceholder({ className, children, ...rest }, ref) {\n return (\n <Typography\n ref={ref}\n variant=\"body\"\n className={cn(\n 'pointer-events-none absolute inset-0 z-0',\n 'min-h-[26px]',\n 'text-text-tertiary',\n className,\n )}\n asChild\n {...rest}\n >\n {/* Typography stamps its own data-slot unless it renders as its child. */}\n <p data-slot=\"chat-input-placeholder\">{children}</p>\n </Typography>\n );\n },\n);\n\nChatInputPlaceholder.displayName = 'ChatInputPlaceholder';\n\nexport interface ChatInputTextareaProps {\n /** Classes for the editable element (`data-slot=\"chat-input-editable\"`), not its wrapper. */\n className?: string;\n /** Inline styles for the wrapper around the editable element. */\n style?: CSSProperties | undefined;\n /** Classes for the placeholder (`data-slot=\"chat-input-placeholder\"`). */\n placeholderClassName?: string;\n /** Shown while the editor is empty; also the editable's `aria-placeholder`. */\n placeholder?: string;\n /** Custom Lexical plugins; rendered inside the composer, after the built-in ones. */\n children?: ReactNode;\n /**\n * Content as Markdown. When it differs from the editor's, it replaces the content; a late\n * render of a value `onChange` already emitted is ignored.\n */\n value?: string;\n /** Focuses the editor on mount, caret at the end. Skipped when disabled or read-only. */\n autoFocus?: boolean;\n /** Blocks editing and selection and dims the wrapper (`data-disabled`). */\n isDisabled?: boolean;\n /** Blocks editing but keeps the text selectable (`data-readonly`). */\n isReadOnly?: boolean;\n /** Called with the content as Markdown on every edit. */\n onChange?: (value: string) => void;\n /** Key handler on the editable element; implement send-on-Enter here. */\n onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;\n}\n\n/**\n * The editable area of a `ChatInput`. Its value is a Markdown string; paste inserts plain\n * text. Must be rendered inside a `ChatInput`.\n */\nexport const ChatInputTextarea = forwardRef<HTMLDivElement, ChatInputTextareaProps>(\n function ChatInputTextarea(\n {\n className,\n style,\n placeholderClassName,\n placeholder = 'Input your message...',\n children,\n value,\n autoFocus = true,\n isDisabled = false,\n isReadOnly = false,\n onChange,\n onKeyDown,\n ...rest\n },\n ref,\n ) {\n const { setHasValue, setIsFocused } = useChatInputContext();\n const isReadOnlyState = isReadOnly && !isDisabled;\n const emittedValuesRef = useRef<string[]>([]);\n\n return (\n <div\n data-slot=\"chat-input-textarea\"\n data-testid=\"chat-input-textarea\"\n data-disabled={isDisabled}\n data-readonly={isReadOnlyState}\n aria-disabled={isDisabled}\n aria-readonly={isReadOnlyState}\n className={cn(\n 'group/chat-input-textarea',\n 'relative',\n 'data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-80 data-[disabled=true]:select-none',\n 'data-[readonly=true]:text-text-secondary',\n )}\n style={style}\n {...rest}\n >\n <RichTextPlugin\n contentEditable={\n <ContentEditable\n ref={ref}\n data-slot=\"chat-input-editable\"\n className={cn('min-h-[26px]!', 'overflow-y-auto text-wrap outline-none', className)}\n aria-label=\"Chat input\"\n aria-placeholder={placeholder}\n placeholder={\n <ChatInputPlaceholder className={placeholderClassName}>\n {placeholder}\n </ChatInputPlaceholder>\n }\n onKeyDown={onKeyDown}\n />\n }\n ErrorBoundary={LexicalErrorBoundary}\n />\n\n <HistoryPlugin />\n <DisabledPlugin isDisabled={isDisabled} isReadOnly={isReadOnly} />\n <ControlledValuePlugin value={value} emittedValuesRef={emittedValuesRef} />\n <ValuePlugin onChange={onChange} emittedValuesRef={emittedValuesRef} />\n <MarkdownPlainPastePlugin />\n <HasValuePlugin onHasValueChange={setHasValue} />\n <FocusPlugin onFocusChange={setIsFocused} />\n <AutoFocusPlugin autoFocus={autoFocus} isDisabled={isDisabled || isReadOnly} />\n\n {children}\n </div>\n );\n },\n);\n\nChatInputTextarea.displayName = 'ChatInputTextarea';\n","import {\n createContext,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type MutableRefObject,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { Skeleton } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatListContextValue {\n loadedCount: number;\n totalCount?: number;\n hasMore: boolean;\n isLoading: boolean;\n isLoadingMore: boolean;\n isEmpty: boolean;\n hasError: boolean;\n onLoadMore?: () => void;\n getItemKey: (index: number) => string | number;\n scrollElementRef: RefObject<HTMLDivElement | null>;\n setScrollElement: (node: HTMLDivElement | null) => void;\n loadMoreContentRef: MutableRefObject<ReactNode>;\n loadMoreVersion: number;\n bumpLoadMore: () => void;\n skeletonContainer: HTMLElement | null;\n setSkeletonContainer: (node: HTMLElement | null) => void;\n}\n\nconst ChatListContext = createContext<ChatListContextValue | null>(null);\n\n/** The list state `ChatList` shares with its parts. Throws when called outside a `ChatList`. */\nexport function useChatListContext() {\n const context = useContext(ChatListContext);\n\n if (!context) {\n throw new Error('\"useChatListContext\" must be used within a ChatList');\n }\n\n return context;\n}\n\nexport interface ChatListProps {\n /** The list parts: `ChatListItems`, `ChatListSkeleton`, `ChatListLoadMore`, `ChatListEmptyState` and `ChatListError`. */\n children: ReactNode;\n className?: string;\n /** Number of rows already loaded; `ChatListItems` renders this many. */\n loadedCount: number;\n /** Total rows on the server, when known; used to work out `hasMore`. */\n totalCount?: number;\n /** Whether another page can be loaded. Defaults to `loadedCount < totalCount`, and to false without `totalCount`. */\n hasMore?: boolean;\n /** The first page is loading: with no rows loaded, `ChatListSkeleton` shows in place of the rows. */\n isLoading?: boolean;\n /** The next page is loading: stops `onLoadMore` from firing again until it is false. */\n isLoadingMore?: boolean;\n /** Loading failed: with no rows loaded, `ChatListError` shows. */\n hasError?: boolean;\n /** Called when the last rendered row reaches the end of the loaded rows while `hasMore` is true. */\n onLoadMore?: () => void;\n /** Returns a stable key for the row at an index, e.g. the chat id. */\n getItemKey: (index: number) => string | number;\n /** Accessible name of the navigation landmark. Defaults to \"Chat list\". */\n 'aria-label'?: string;\n}\n\n/**\n * Root of the conversation list: a `role=\"navigation\"` landmark that holds the fetch state and\n * shares it with its parts. Give it a bounded height; `ChatListItems` scrolls inside it.\n */\nexport function ChatList({\n children,\n className,\n loadedCount,\n totalCount,\n hasMore: hasMoreProp,\n isLoading = false,\n isLoadingMore = false,\n hasError = false,\n onLoadMore,\n getItemKey,\n 'aria-label': ariaLabel = 'Chat list',\n}: ChatListProps) {\n const scrollElementRef = useRef<HTMLDivElement | null>(null);\n const loadMoreContentRef = useRef<ReactNode>(null);\n const [loadMoreVersion, setLoadMoreVersion] = useState(0);\n const [skeletonContainer, setSkeletonContainer] = useState<HTMLElement | null>(null);\n const [, setScrollElementVersion] = useState(0);\n\n const setScrollElement = useCallback((node: HTMLDivElement | null) => {\n scrollElementRef.current = node;\n setScrollElementVersion((version) => version + 1);\n }, []);\n\n const bumpLoadMore = useCallback(() => {\n setLoadMoreVersion((version) => version + 1);\n }, []);\n\n const hasMore = hasMoreProp ?? (totalCount != null ? loadedCount < totalCount : false);\n const isEmpty = loadedCount === 0 && !isLoading && !hasError;\n\n const contextValue = useMemo<ChatListContextValue>(\n () => ({\n loadedCount,\n totalCount,\n hasMore,\n isLoading,\n isLoadingMore,\n isEmpty,\n hasError,\n onLoadMore,\n getItemKey,\n scrollElementRef,\n setScrollElement,\n loadMoreContentRef,\n loadMoreVersion,\n bumpLoadMore,\n skeletonContainer,\n setSkeletonContainer,\n }),\n [\n loadedCount,\n totalCount,\n hasMore,\n isLoading,\n isLoadingMore,\n isEmpty,\n hasError,\n onLoadMore,\n getItemKey,\n setScrollElement,\n loadMoreVersion,\n bumpLoadMore,\n skeletonContainer,\n ],\n );\n\n return (\n <ChatListContext.Provider value={contextValue}>\n <div\n data-slot=\"chat-list\"\n data-testid=\"chat-list\"\n data-loading={isLoading}\n data-loading-more={isLoadingMore}\n data-empty={isEmpty}\n data-error={hasError}\n role=\"navigation\"\n aria-label={ariaLabel}\n className={cn('group/chat-list relative flex min-h-0 flex-1 flex-col', className)}\n >\n {children}\n </div>\n </ChatListContext.Provider>\n );\n}\n\nexport interface ChatListSkeletonProps {\n /** Your own placeholder rows. Leave it out to get `rows` default rows built from `Skeleton`. */\n children?: ReactNode;\n /** Number of default rows, used only when `children` is not passed. Rows past the list's height are clipped. */\n rows?: number;\n className?: string;\n /** Classes for each default row; merged after its defaults. Not used when `children` is passed. */\n rowClassName?: string;\n}\n\n// Title and preview widths alternate per row, so the placeholder reads as a list of chats.\nconst TITLE_WIDTHS = ['w-2/3', 'w-1/2'] as const;\nconst PREVIEW_WIDTHS = ['w-full', 'w-4/5'] as const;\n\n/**\n * Placeholder for the first page of chats. Renders only while `isLoading` is true and no chats are\n * loaded, in the space `ChatListItems` will fill. It is a `role=\"status\"` region named\n * \"Loading chats\"; its rows are `Skeleton`s from `@swisper.ai/ui`, which are `aria-hidden`.\n */\nexport function ChatListSkeleton({\n children,\n rows = 16,\n className,\n rowClassName,\n}: ChatListSkeletonProps) {\n const { isLoading, loadedCount, skeletonContainer } = useChatListContext();\n\n if (!(isLoading && loadedCount === 0) || !skeletonContainer) {\n return null;\n }\n\n return createPortal(\n <div\n data-slot=\"chat-list-skeleton\"\n data-testid=\"chat-list-skeleton\"\n role=\"status\"\n aria-busy=\"true\"\n aria-label=\"Loading chats\"\n className={cn('flex min-h-0 flex-1 flex-col gap-4 overflow-hidden', className)}\n >\n {children ??\n Array.from({ length: rows }, (_, index) => (\n <div\n key={index}\n data-slot=\"chat-list-skeleton-row\"\n className={cn('flex shrink-0 flex-col gap-4 px-12 py-8', rowClassName)}\n >\n <div className=\"flex h-20 items-center\">\n <Skeleton className={cn('h-12', TITLE_WIDTHS[index % 2])} />\n </div>\n <div className=\"flex h-16 items-center\">\n <Skeleton className={cn('h-10', PREVIEW_WIDTHS[index % 2])} />\n </div>\n </div>\n ))}\n </div>,\n skeletonContainer,\n );\n}\n\nexport interface ChatListEmptyStateProps {\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * What the list says when it has no chats. Renders only when nothing is loaded, nothing is loading\n * and there is no error, as a `role=\"status\"` region named \"No chats\".\n */\nexport function ChatListEmptyState({ children, className }: ChatListEmptyStateProps) {\n const { isEmpty } = useChatListContext();\n\n if (!isEmpty) {\n return null;\n }\n\n return (\n <div\n data-slot=\"chat-list-empty-state\"\n data-testid=\"chat-list-empty-state\"\n role=\"status\"\n aria-live=\"polite\"\n aria-label=\"No chats\"\n className={cn('flex flex-1 items-center justify-center', className)}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatListErrorProps {\n /** Your own error content. Leave it out to get the `error` message, or \"An error occurred\". */\n children?: ReactNode;\n /** The failure to show when `children` is not passed: an `Error`'s message, or the string itself. */\n error?: Error | string;\n className?: string;\n /** Classes for the default message; merged after its defaults. Not used when `children` is passed. */\n messageClassName?: string;\n}\n\n/**\n * What the list says when the first page fails. Renders only while `hasError` is true and no chats\n * are loaded, as a `role=\"alert\"` region named \"Error loading chats\".\n */\nexport function ChatListError({\n children,\n error,\n className,\n messageClassName,\n}: ChatListErrorProps) {\n const { hasError, loadedCount } = useChatListContext();\n\n if (!(hasError && loadedCount === 0)) {\n return null;\n }\n\n return (\n <div\n data-slot=\"chat-list-error\"\n data-testid=\"chat-list-error\"\n role=\"alert\"\n aria-live=\"assertive\"\n aria-label=\"Error loading chats\"\n className={cn('flex flex-1 items-center justify-center', className)}\n >\n {children || (\n <div\n data-slot=\"chat-list-error-message\"\n className={cn('text-text-error-main', messageClassName)}\n >\n {error instanceof Error ? error.message : error || 'An error occurred'}\n </div>\n )}\n </div>\n );\n}\n\nexport interface ChatListLoadMoreProps {\n /** Content of the load-more row, e.g. \"Loading more…\" or a few skeleton rows. */\n children?: ReactNode;\n}\n\n/**\n * Registers its children as the content of the row `ChatListItems` appends while `hasMore` is true.\n * It renders nothing where it is placed.\n */\nexport function ChatListLoadMore({ children }: ChatListLoadMoreProps) {\n const { loadMoreContentRef, bumpLoadMore } = useChatListContext();\n\n loadMoreContentRef.current = children ?? null;\n\n useLayoutEffect(() => {\n bumpLoadMore();\n\n return () => {\n loadMoreContentRef.current = null;\n bumpLoadMore();\n };\n }, [bumpLoadMore, loadMoreContentRef]);\n\n return null;\n}\n","import { useVirtualizer } from '@tanstack/react-virtual';\nimport { memo, useCallback, useEffect, type ReactNode } from 'react';\n\nimport { MenuList, ScrollArea } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatListContext } from './chat-list';\n\nconst LOAD_MORE_KEY = 'chat-list-load-more';\n\nexport interface ChatListItemsProps {\n /** Render function called with each loaded row's index; return a `ChatListItem`. */\n children: (index: number) => ReactNode;\n className?: string;\n /** Classes for the `ul` that holds the rows; merged after its defaults. */\n listClassName?: string;\n /** Classes for every `li`, the load-more row included; merged after its defaults. */\n rowClassName?: string;\n /** First guess of a row's height in pixels; rows are measured after they render. */\n estimateSize?: number;\n /** Rows rendered beyond the visible ones, above and below. */\n overscan?: number;\n /** Space between rows, in pixels. */\n gap?: number;\n}\n\n/**\n * The scrolling, virtualised rows of a `ChatList`. While `hasMore` is true it appends one row with\n * the `ChatListLoadMore` content and calls `onLoadMore` when that row comes into range.\n */\nexport const ChatListItems = memo(function ChatListItems({\n children,\n className,\n listClassName,\n rowClassName,\n estimateSize = 54,\n overscan = 6,\n gap = 4,\n}: ChatListItemsProps) {\n const {\n loadedCount,\n hasMore,\n isLoading,\n isLoadingMore,\n onLoadMore,\n getItemKey,\n scrollElementRef,\n setScrollElement,\n loadMoreContentRef,\n loadMoreVersion,\n setSkeletonContainer,\n } = useChatListContext();\n\n // Re-read registered sentinel content when ChatListLoadMore mounts/unmounts.\n const loadMoreContent = loadMoreVersion >= 0 ? loadMoreContentRef.current : null;\n\n const showSkeleton = isLoading && loadedCount === 0;\n const count = hasMore ? loadedCount + 1 : loadedCount;\n\n const getItemKeyStable = useCallback(\n (index: number) => {\n if (index >= loadedCount) {\n return LOAD_MORE_KEY;\n }\n\n return getItemKey(index);\n },\n [getItemKey, loadedCount],\n );\n\n const virtualizer = useVirtualizer({\n count: showSkeleton ? 0 : count,\n getScrollElement: () => scrollElementRef.current,\n estimateSize: () => estimateSize,\n overscan,\n gap,\n getItemKey: getItemKeyStable,\n });\n\n const virtualItems = virtualizer.getVirtualItems();\n\n useEffect(() => {\n if (showSkeleton) {\n return;\n }\n\n const [lastItem] = [...virtualItems].reverse();\n\n if (!lastItem) {\n return;\n }\n\n if (lastItem.index >= loadedCount - 1 && hasMore && !isLoadingMore) {\n onLoadMore?.();\n }\n }, [virtualItems, loadedCount, hasMore, isLoadingMore, onLoadMore, showSkeleton]);\n\n // The skeleton sits outside the ScrollArea: Radix wraps the viewport's content in a\n // `display: table` box, where the skeleton could neither fill the list height nor clip to it.\n if (showSkeleton) {\n return (\n <div\n ref={setSkeletonContainer}\n data-slot=\"chat-list-items\"\n data-testid=\"chat-list-items\"\n className={cn('flex min-h-0 flex-1 flex-col overflow-hidden', className)}\n />\n );\n }\n\n return (\n <ScrollArea\n ref={setScrollElement}\n data-slot=\"chat-list-items\"\n data-testid=\"chat-list-items\"\n className={cn('min-h-0 flex-1', 'overflow-auto', className)}\n >\n <MenuList\n data-slot=\"chat-list-items-list\"\n role=\"list\"\n aria-label=\"Chats\"\n className={cn(\n 'table relative w-full transform-gpu table-fixed',\n 'space-y-[4px]',\n listClassName,\n )}\n style={{\n height: `${virtualizer.getTotalSize()}px`,\n }}\n >\n {virtualItems.map((virtualItem) => {\n const isLoaderRow = virtualItem.index >= loadedCount;\n\n return (\n <li\n key={virtualItem.key}\n data-slot=\"chat-list-items-row\"\n data-index={virtualItem.index}\n data-load-more={isLoaderRow}\n ref={virtualizer.measureElement}\n role={isLoaderRow ? 'status' : 'listitem'}\n aria-live={isLoaderRow ? 'polite' : undefined}\n aria-busy={isLoaderRow ? isLoadingMore : undefined}\n className={rowClassName}\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n transform: `translateY(${virtualItem.start}px)`,\n }}\n >\n {isLoaderRow ? loadMoreContent : children(virtualItem.index)}\n </li>\n );\n })}\n </MenuList>\n </ScrollArea>\n );\n});\n","import { Slot } from '@radix-ui/react-slot';\nimport { forwardRef, type ComponentPropsWithoutRef, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatListItemProps extends ComponentPropsWithoutRef<'div'> {\n children?: ReactNode;\n /** Merges the item's props onto its only child, e.g. a link or a button, without adding a `div`. */\n asChild?: boolean;\n /** Marks the open conversation: sets `data-selected` and `aria-selected`. */\n isSelected?: boolean;\n}\n\n/**\n * One row's content, returned from the `ChatListItems` render function. It has no role, tab stop or\n * look of its own: render it `asChild` over a link or button and style that from `data-selected`.\n */\nexport const ChatListItem = forwardRef<HTMLDivElement, ChatListItemProps>(function ChatListItem(\n { children, className, asChild = false, isSelected = false, ...rest },\n ref,\n) {\n const Component = asChild ? Slot : 'div';\n\n return (\n <Component\n ref={ref}\n data-slot=\"chat-list-item\"\n data-testid=\"chat-list-item\"\n data-selected={isSelected}\n aria-selected={isSelected || undefined}\n className={cn('cursor-pointer outline-none', className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatListItem.displayName = 'ChatListItem';\n","import { createContext, useCallback, useContext, useMemo, useRef, type ReactNode } from 'react';\n\ninterface ChatPromptBoxContextValue {\n reportInputHeight: (height: number) => void;\n resetCompact: () => void;\n registerFocusInput: (focus: () => void) => void;\n unregisterFocusInput: () => void;\n focusInput: () => void;\n}\n\nconst ChatPromptBoxContext = createContext<ChatPromptBoxContextValue | null>(null);\n\nexport function useChatPromptBoxContext() {\n const context = useContext(ChatPromptBoxContext);\n\n if (!context) {\n throw new Error('\"useChatPromptBoxContext\" must be used within a ChatPromptBox');\n }\n\n return context;\n}\n\ninterface ChatPromptBoxContextProviderProps {\n children: ReactNode;\n reportInputHeight: (height: number) => void;\n resetCompact: () => void;\n}\n\nexport function ChatPromptBoxContextProvider({\n children,\n reportInputHeight,\n resetCompact,\n}: ChatPromptBoxContextProviderProps) {\n const focusInputRef = useRef<(() => void) | null>(null);\n\n const registerFocusInput = useCallback((focus: () => void) => {\n focusInputRef.current = focus;\n }, []);\n\n const unregisterFocusInput = useCallback(() => {\n focusInputRef.current = null;\n }, []);\n\n const focusInput = useCallback(() => {\n focusInputRef.current?.();\n }, []);\n\n const contextValue = useMemo(\n () => ({\n reportInputHeight,\n resetCompact,\n registerFocusInput,\n unregisterFocusInput,\n focusInput,\n }),\n [reportInputHeight, resetCompact, registerFocusInput, unregisterFocusInput, focusInput],\n );\n\n return (\n <ChatPromptBoxContext.Provider value={contextValue}>{children}</ChatPromptBoxContext.Provider>\n );\n}\n","import { useEffect } from 'react';\n\nimport { useChatInputEditor } from '../chat-input/plugins/hooks';\n\nimport { useChatPromptBoxContext } from './chat-prompt-box-context';\n\nexport function ChatPromptBoxFocusPlugin() {\n const editor = useChatInputEditor();\n const { registerFocusInput, unregisterFocusInput } = useChatPromptBoxContext();\n\n useEffect(() => {\n registerFocusInput(() => {\n editor.focus();\n });\n\n return () => {\n unregisterFocusInput();\n };\n }, [editor, registerFocusInput, unregisterFocusInput]);\n\n return null;\n}\n","import type { ComponentPropsWithoutRef, MouseEvent, ReactNode } from 'react';\nimport { forwardRef, useCallback, useLayoutEffect, useState } from 'react';\n\nimport { cn, useElementMeasure } from '@swisper.ai/web-core';\n\nimport { ChatInput, ChatInputTextarea, useChatInputContext } from '../chat-input';\nimport type { ChatInputProps, ChatInputTextareaProps } from '../chat-input';\n\nimport { ChatPromptBoxContextProvider, useChatPromptBoxContext } from './chat-prompt-box-context';\nimport { ChatPromptBoxFocusPlugin } from './chat-prompt-box-focus-plugin';\n\nexport interface ChatPromptBoxProps extends ChatInputProps {\n /** Classes merged last onto the inner surface, the element that carries the box's background and padding. */\n innerClassName?: string;\n}\n\nconst COMPACT_INPUT_HEIGHT_THRESHOLD = 40;\n\nconst INTERACTIVE_SELECTOR = 'button, a, input, select, textarea, [role=\"button\"]';\n\nfunction shouldSkipFocus(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) {\n return false;\n }\n\n return Boolean(target.closest(INTERACTIVE_SELECTOR));\n}\n\n/**\n * The styled chat composer: a `ChatInput` with the box's border, background and focus glow. Sets\n * `data-compact` on the root, which the parts read to move the actions under the text.\n */\nexport const ChatPromptBox = forwardRef<HTMLDivElement, ChatPromptBoxProps>(\n function ChatPromptBox(props, ref) {\n const [isCompact, setIsCompact] = useState(true);\n\n const reportInputHeight = useCallback((height: number) => {\n if (height > COMPACT_INPUT_HEIGHT_THRESHOLD) {\n setIsCompact(false);\n }\n }, []);\n\n const resetCompact = useCallback(() => {\n setIsCompact(true);\n }, []);\n\n return (\n <ChatPromptBoxContextProvider\n reportInputHeight={reportInputHeight}\n resetCompact={resetCompact}\n >\n <ChatPromptBoxContainer ref={ref} data-compact={isCompact} {...props} />\n </ChatPromptBoxContextProvider>\n );\n },\n);\n\nChatPromptBox.displayName = 'ChatPromptBox';\n\nconst ChatPromptBoxContainer = forwardRef<HTMLDivElement, ChatPromptBoxProps>(\n function ChatPromptBoxContainer(\n { className, innerClassName, children, onMouseDown, ...rest },\n ref,\n ) {\n const { focusInput } = useChatPromptBoxContext();\n\n const handleMouseDown = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n if (!shouldSkipFocus(event.target)) {\n focusInput();\n }\n\n onMouseDown?.(event);\n },\n [focusInput, onMouseDown],\n );\n\n return (\n <ChatInput\n ref={ref}\n data-slot=\"chat-prompt-box\"\n className={cn(\n 'group/chat-prompt-box',\n 'relative overflow-hidden',\n 'cursor-text',\n 'p-px',\n 'rounded-[16px]',\n // border color\n 'bg-transparent',\n 'hover:bg-promptbox-background-border-base',\n 'data-[focused=true]:bg-promptbox-background-border-base',\n className,\n )}\n onMouseDown={handleMouseDown}\n {...rest}\n >\n <div\n data-slot=\"chat-prompt-box-inner\"\n className={cn(\n 'rounded-[15px]',\n 'p-[4px]',\n // regular bg\n 'bg-[#171A20]',\n // hover bg\n 'group-hover/chat-prompt-box:bg-[#252931]',\n // focused bg\n 'group-data-[focused=true]/chat-prompt-box:bg-[linear-gradient(var(--color-promptbox-background-hover),var(--color-promptbox-background-hover)),var(--color-promptbox-background-base)]',\n // focused & hover bg\n 'group-data-[focused=true]/chat-prompt-box:group-hover/chat-prompt-box:bg-[linear-gradient(var(--color-promptbox-background-hover),var(--color-promptbox-background-hover)),var(--color-promptbox-background-base)]',\n innerClassName,\n )}\n >\n {children}\n </div>\n\n <ChatPromptBoxFocusRadials />\n </ChatInput>\n );\n },\n);\n\nChatPromptBoxContainer.displayName = 'ChatPromptBoxContainer';\n\nfunction ChatPromptBoxFocusRadials() {\n return (\n <>\n <div\n data-slot=\"chat-prompt-box-glow-top\"\n className={cn(\n 'absolute left-1/2 top-[-40px]',\n 'translate-x-[-50%]',\n 'pointer-events-none',\n 'w-[380px] h-[72px]',\n 'opacity-0 group-data-[focused=true]/chat-prompt-box:opacity-50',\n )}\n style={{\n borderRadius: '380px',\n background:\n 'gradient(50% 50% at 50% 50%, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.00) 100%)',\n }}\n />\n\n <div\n data-slot=\"chat-prompt-box-glow-bottom\"\n className={cn(\n 'absolute left-1/2 -bottom-22',\n 'translate-x-[-50%]',\n 'pointer-events-none',\n 'w-[1082px] h-[172px]',\n 'opacity-0 group-data-[focused=true]/chat-prompt-box:opacity-5',\n )}\n style={{\n borderRadius: '1082px',\n background:\n 'radial-gradient(50% 50% at 50% 50%, rgba(255, 255, 255, 0.80) 0%, #2979FF 28%, rgba(63, 70, 88, 0.00) 100%)',\n }}\n />\n </>\n );\n}\n\nexport interface ChatPromptBoxToolbarProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/** A row above the content for what the message carries, such as the attached files. */\nexport function ChatPromptBoxToolbar({ className, children, ...rest }: ChatPromptBoxToolbarProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-toolbar\"\n data-testid=\"chat-prompt-box-toolbar\"\n className={cn(className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatPromptBoxContentProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/** The row holding the input and both action groups. Reserves room under the text once the box expands. */\nexport function ChatPromptBoxContent({ className, children, ...rest }: ChatPromptBoxContentProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-content\"\n data-testid=\"chat-prompt-box-content\"\n className={cn(\n 'relative',\n 'px-[8px] py-[8px]',\n 'flex flex-row gap-[8px]',\n 'group-data-[compact=false]/chat-prompt-box:pb-[calc(8px+4px+40px)]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatPromptBoxInputProps extends ChatInputTextareaProps {\n /** Classes merged last onto the editable element, after its 72px max height. `className` goes to the wrapper around it. */\n textareaClassName?: string;\n}\n\n/**\n * The box's text input: a `ChatInputTextarea` that reports its height to the box and registers\n * click-to-focus. `children` are rendered inside the editor, for extra Lexical plugins.\n */\nexport const ChatPromptBoxInput = forwardRef<HTMLDivElement, ChatPromptBoxInputProps>(\n function ChatPromptBoxInput(\n { className, textareaClassName, placeholderClassName, children, ...rest },\n ref,\n ) {\n const { reportInputHeight, resetCompact } = useChatPromptBoxContext();\n const { hasValue } = useChatInputContext();\n const { ref: measureRef, height } = useElementMeasure<HTMLDivElement>();\n\n useLayoutEffect(() => {\n if (typeof height === 'number') {\n reportInputHeight(height);\n }\n }, [height, reportInputHeight]);\n\n useLayoutEffect(() => {\n return () => {\n resetCompact();\n };\n }, [resetCompact]);\n\n useLayoutEffect(() => {\n if (!hasValue) {\n resetCompact();\n }\n }, [hasValue, resetCompact]);\n\n const setRef = useCallback(\n (element: HTMLDivElement | null) => {\n measureRef(element);\n\n if (typeof ref === 'function') {\n ref(element);\n } else if (ref) {\n ref.current = element;\n }\n },\n [measureRef, ref],\n );\n\n return (\n <div\n data-slot=\"chat-prompt-box-input\"\n data-testid=\"chat-prompt-box-input\"\n className={cn(\n 'min-h-[40px]',\n 'inline-flex justify-center items-center',\n 'group-data-[compact=false]/chat-prompt-box:items-start',\n 'group-data-[compact=false]/chat-prompt-box:min-h-[48px]',\n 'order-2 grow min-w-0 flex-1',\n '[&>div]:flex-1 [&>div]:min-w-0',\n className,\n )}\n >\n <ChatInputTextarea\n ref={setRef}\n className={cn('max-h-[72px]!', textareaClassName)}\n placeholderClassName={cn('leading-[24px]!', placeholderClassName)}\n {...rest}\n >\n <ChatPromptBoxFocusPlugin />\n {children}\n </ChatInputTextarea>\n </div>\n );\n },\n);\n\nChatPromptBoxInput.displayName = 'ChatPromptBoxInput';\n\nexport interface ChatPromptBoxActionsLeftProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/**\n * The `role=\"group\"` of secondary actions before the text, e.g. attach. Moves to the bottom-left\n * when the box expands. Name it with `aria-label`.\n */\nexport function ChatPromptBoxActionsLeft({\n className,\n children,\n ...rest\n}: ChatPromptBoxActionsLeftProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-actions-left\"\n data-testid=\"chat-prompt-box-actions-left\"\n role=\"group\"\n className={cn(\n 'order-1 shrink-0',\n 'group-data-[compact=false]/chat-prompt-box:absolute',\n 'group-data-[compact=false]/chat-prompt-box:bottom-[8px]',\n 'group-data-[compact=false]/chat-prompt-box:left-[8px]',\n 'flex items-center gap-[8px]',\n '[grid-area:left]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatPromptBoxActionsRightProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/**\n * The `role=\"group\"` of actions after the text, ending in send. Moves to the bottom-right when the\n * box expands. Name it with `aria-label`.\n */\nexport function ChatPromptBoxActionsRight({\n className,\n children,\n ...rest\n}: ChatPromptBoxActionsRightProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-actions-right\"\n data-testid=\"chat-prompt-box-actions-right\"\n role=\"group\"\n className={cn(\n 'order-3 shrink-0',\n 'group-data-[compact=false]/chat-prompt-box:order-3',\n 'group-data-[compact=false]/chat-prompt-box:absolute',\n 'group-data-[compact=false]/chat-prompt-box:bottom-[8px]',\n 'group-data-[compact=false]/chat-prompt-box:right-[8px]',\n 'flex items-center justify-end gap-[8px]',\n '[grid-area:right]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import React from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatMessageProps {\n /** The message parts, usually a `ChatMessageContent` followed by an optional `ChatMessageActions`. */\n children: React.ReactNode;\n /** Classes merged last onto the root, e.g. `gap-12` to change the gap between the parts. */\n className?: string;\n /** Marks the message as the user's question: end-aligns it and turns its content into a filled bubble. */\n isQuestion?: boolean;\n}\n\n/** One message in a conversation: the user's question as an end-aligned bubble, or the assistant's answer. */\nexport function ChatMessage({ children, className, isQuestion }: ChatMessageProps) {\n return (\n <div\n data-slot=\"chat-message\"\n data-question={isQuestion}\n className={cn(\n 'group/message',\n 'flex flex-col',\n 'data-[question=true]:items-end',\n 'gap-8',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageContentProps {\n /** The message body: plain text, a `MarkdownViewer` or a `ChatCardContainer`. */\n children: React.ReactNode;\n /** Classes merged last onto the content element. */\n className?: string;\n}\n\n/** The body of a `ChatMessage`. Inside a question it renders as a padded, filled bubble. */\nexport function ChatMessageContent({ children, className }: ChatMessageContentProps) {\n return (\n <div\n data-slot=\"chat-message-content\"\n data-bubble={true}\n className={cn(\n 'w-fit',\n 'min-w-message-mobile-min md:min-w-auto',\n 'group-data-[question=true]/message:data-[bubble=true]:p-16',\n 'group-data-[question=true]/message:data-[bubble=true]:rounded-[20px]',\n 'group-data-[question=true]/message:data-[bubble=true]:bg-[#22283499]',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageActionsProps {\n /** The controls under the message, usually a `ChatMessageToolbar`. */\n children: React.ReactNode;\n /** Classes merged last onto the actions row. */\n className?: string;\n}\n\n/** A row under the message body. From `md` up it is hidden until its `ChatMessage` is hovered. */\nexport function ChatMessageActions({ children, className }: ChatMessageActionsProps) {\n return (\n <div\n data-slot=\"chat-message-actions\"\n className={cn(\n 'transition-opacity duration-300',\n 'md:opacity-0 group-hover/message:opacity-100',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n","import { nanoid } from 'nanoid';\n\nimport { type ChatId } from '@/types';\n\nexport function getNewChatId(): ChatId {\n return `__${nanoid()}__`;\n}\n","import {\n type ReactNode,\n type RefObject,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport type { ChatId } from '@/types';\n\nimport { getNewChatId } from './utils';\n\nexport interface ChatContextValue {\n chatId: ChatId;\n newChatId: ChatId;\n loadedChatIdsRef: RefObject<Set<ChatId>>;\n isNewChat: boolean;\n goToNewChat: () => ChatId;\n promptPlaceholder: string | undefined;\n setPromptPlaceholder: (placeholder: string) => void;\n clearPromptPlaceholder: () => void;\n}\n\nconst ChatContext = createContext<ChatContextValue>(null!);\n\nexport function useChatContext() {\n const context = useContext(ChatContext);\n\n if (!context) {\n throw new Error('\"useChatContext\" must be used within a ChatProvider');\n }\n\n return context;\n}\n\ninterface ChatProviderProps {\n children: ReactNode;\n chatId: ChatId | undefined;\n}\n\nexport function ChatProvider({ children, chatId: chatIdProp }: ChatProviderProps) {\n const [newChatId, setNewChatId] = useState<ChatId>(getNewChatId());\n const [promptPlaceholder, setPromptPlaceholderState] = useState<string | undefined>(undefined);\n const loadedChatIdsRef = useRef<Set<ChatId>>(new Set());\n const chatId: ChatId = chatIdProp || newChatId;\n const isNewChat: boolean = chatId === newChatId;\n\n const goToNewChat = useCallback(() => {\n const nextChatId = getNewChatId();\n setNewChatId(nextChatId);\n return nextChatId;\n }, [setNewChatId]);\n\n const setPromptPlaceholder = useCallback((placeholder: string) => {\n setPromptPlaceholderState(placeholder);\n }, []);\n\n const clearPromptPlaceholder = useCallback(() => {\n setPromptPlaceholderState(undefined);\n }, []);\n\n useEffect(\n function resetStateOnChatChange() {\n clearPromptPlaceholder();\n },\n [chatId, newChatId, clearPromptPlaceholder],\n );\n\n const contextValue = useMemo(\n () => ({\n newChatId,\n chatId,\n loadedChatIdsRef,\n isNewChat,\n goToNewChat,\n promptPlaceholder,\n setPromptPlaceholder,\n clearPromptPlaceholder,\n }),\n [\n chatId,\n loadedChatIdsRef,\n newChatId,\n isNewChat,\n goToNewChat,\n promptPlaceholder,\n setPromptPlaceholder,\n clearPromptPlaceholder,\n ],\n );\n\n return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n type ReactNode,\n useState,\n} from 'react';\n\nimport type { ChatId } from '@/types';\n\nconst LAST_ITEM_SCROLL_MAX_COUNT = 3;\nconst USER_SCROLL_INTENT_IDLE_MS = 250;\n\nexport interface ChatConversationContextValue {\n viewportRef: (node: HTMLDivElement | null) => void;\n bottomTriggerRef: (node: HTMLLIElement | null) => void;\n lastItemRef: (node: HTMLElement | null) => void;\n isAtBottom: boolean;\n setMessageCount: (count: number) => void;\n scrollBottom: () => void;\n scrollToLatest: () => void;\n}\n\nconst ChatConversationContext = createContext<ChatConversationContextValue | null>(null);\n\nexport function useChatConversationContext() {\n const context = useContext(ChatConversationContext);\n\n if (!context) {\n throw new Error('\"useChatConversationContext\" must be used within a ChatConversationProvider');\n }\n\n return context;\n}\n\ninterface ChatConversationProviderProps {\n children: ReactNode;\n chatId: ChatId;\n debug?: boolean;\n}\n\nexport function ChatConversationProvider({\n children,\n chatId: _chatId,\n debug = false,\n}: ChatConversationProviderProps) {\n const [isAtBottom, setIsAtBottom] = useState(true);\n const [debugInfo, setDebugInfo] = useState({\n isAtBottom: true,\n isSmoothScroll: false,\n hasUserEscaped: false,\n isProgrammaticScroll: false,\n userScrollIntent: false,\n scrollStrategy: 'lastItem' as 'end' | 'lastItem',\n });\n\n const viewportNodeRef = useRef<HTMLDivElement | null>(null);\n const bottomTriggerNodeRef = useRef<HTMLLIElement | null>(null);\n const lastItemNodeRef = useRef<HTMLElement | null>(null);\n const resizeObserverRef = useRef<ResizeObserver | null>(null);\n const viewportResizeObserverRef = useRef<ResizeObserver | null>(null);\n const bottomTriggerObserverRef = useRef<IntersectionObserver | null>(null);\n\n const messageCountRef = useRef(0);\n const isAtBottomRef = useRef(true);\n const isSmoothScrollRef = useRef<boolean>(false);\n const hasUserEscapedRef = useRef<boolean>(false);\n const isProgrammaticScrollRef = useRef<boolean>(false);\n const userScrollIntentRef = useRef<boolean>(false);\n const userScrollIntentTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const lastScrollTopRef = useRef<number | null>(null);\n const scrollStrategyRef = useRef<'end' | 'lastItem'>('lastItem');\n const lastViewportScrollHeightRef = useRef(0);\n const scrollRef = useRef<() => void>(() => {});\n const attachLastItemResizeObserverRef = useRef<(node: HTMLElement) => void>(() => {});\n const detachLastItemResizeObserverRef = useRef<() => void>(() => {});\n const syncDebugInfoRef = useRef<() => void>(() => {});\n\n const syncDebugInfo = useCallback(() => {\n if (!debug) {\n return;\n }\n\n setDebugInfo({\n isAtBottom: isAtBottomRef.current,\n isSmoothScroll: isSmoothScrollRef.current,\n hasUserEscaped: hasUserEscapedRef.current,\n isProgrammaticScroll: isProgrammaticScrollRef.current,\n userScrollIntent: userScrollIntentRef.current,\n scrollStrategy: scrollStrategyRef.current,\n });\n }, [debug]);\n\n syncDebugInfoRef.current = syncDebugInfo;\n\n const detachLastItemResizeObserver = useCallback(() => {\n resizeObserverRef.current?.disconnect();\n resizeObserverRef.current = null;\n }, []);\n\n detachLastItemResizeObserverRef.current = detachLastItemResizeObserver;\n\n const detachBottomTriggerObserver = useCallback(() => {\n bottomTriggerObserverRef.current?.disconnect();\n bottomTriggerObserverRef.current = null;\n }, []);\n\n const detachViewportResizeObserver = useCallback(() => {\n viewportResizeObserverRef.current?.disconnect();\n viewportResizeObserverRef.current = null;\n }, []);\n\n const syncAtBottomFromViewportRef = useRef<() => void>(() => {});\n\n const clearProgrammaticScroll = useCallback(() => {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n isProgrammaticScrollRef.current = false;\n syncAtBottomFromViewportRef.current();\n syncDebugInfoRef.current();\n });\n });\n }, []);\n\n const clearUserScrollIntent = useCallback(() => {\n if (userScrollIntentTimeoutRef.current) {\n clearTimeout(userScrollIntentTimeoutRef.current);\n userScrollIntentTimeoutRef.current = null;\n }\n\n if (!userScrollIntentRef.current) {\n return;\n }\n\n userScrollIntentRef.current = false;\n syncDebugInfoRef.current();\n }, []);\n\n const markUserScrollIntent = useCallback(() => {\n userScrollIntentRef.current = true;\n if (userScrollIntentTimeoutRef.current) {\n clearTimeout(userScrollIntentTimeoutRef.current);\n }\n\n userScrollIntentTimeoutRef.current = setTimeout(() => {\n userScrollIntentTimeoutRef.current = null;\n userScrollIntentRef.current = false;\n syncDebugInfoRef.current();\n }, USER_SCROLL_INTENT_IDLE_MS);\n\n syncDebugInfoRef.current();\n }, []);\n\n const applyLastItemScrollStrategy = useCallback(() => {\n scrollStrategyRef.current = 'lastItem';\n detachLastItemResizeObserverRef.current();\n syncDebugInfoRef.current();\n }, []);\n\n const setHasUserEscaped = useCallback((hasUserEscaped: boolean) => {\n if (hasUserEscapedRef.current === hasUserEscaped) {\n return;\n }\n\n hasUserEscapedRef.current = hasUserEscaped;\n\n if (hasUserEscaped) {\n syncAtBottomFromViewportRef.current();\n }\n\n syncDebugInfoRef.current();\n }, []);\n\n const scroll = useCallback(() => {\n if (hasUserEscapedRef.current) {\n return;\n }\n\n isProgrammaticScrollRef.current = true;\n syncDebugInfoRef.current();\n\n const behavior = isSmoothScrollRef.current ? 'smooth' : 'instant';\n isSmoothScrollRef.current = true;\n\n requestAnimationFrame(() => {\n if (hasUserEscapedRef.current) {\n clearProgrammaticScroll();\n return;\n }\n\n if (scrollStrategyRef.current === 'lastItem') {\n lastItemNodeRef.current?.scrollIntoView({ behavior, block: 'start', inline: 'start' });\n } else {\n viewportNodeRef.current?.scrollTo({\n top: viewportNodeRef.current.scrollHeight,\n behavior,\n });\n }\n\n clearProgrammaticScroll();\n syncDebugInfoRef.current();\n });\n }, [clearProgrammaticScroll]);\n\n scrollRef.current = scroll;\n\n const stickScrollToEnd = useCallback(() => {\n const node = viewportNodeRef.current;\n\n if (!node) {\n return;\n }\n\n const scrollHeight = node.scrollHeight;\n const distanceFromBottom = scrollHeight - node.clientHeight - node.scrollTop;\n\n if (distanceFromBottom <= 1 && scrollHeight === lastViewportScrollHeightRef.current) {\n return;\n }\n\n lastViewportScrollHeightRef.current = scrollHeight;\n isProgrammaticScrollRef.current = true;\n syncDebugInfoRef.current();\n\n requestAnimationFrame(() => {\n node.scrollTo({\n top: scrollHeight,\n behavior: 'instant',\n });\n\n lastViewportScrollHeightRef.current = node.scrollHeight;\n clearProgrammaticScroll();\n syncDebugInfoRef.current();\n });\n }, [clearProgrammaticScroll]);\n\n const syncAtBottomFromViewport = useCallback(() => {\n const node = viewportNodeRef.current;\n\n if (!node) {\n return;\n }\n\n const atBottom = node.scrollHeight - node.clientHeight - node.scrollTop <= 1;\n\n if (!atBottom && !hasUserEscapedRef.current) {\n return;\n }\n\n isAtBottomRef.current = atBottom;\n setIsAtBottom(atBottom);\n\n if (scrollStrategyRef.current === 'end' && atBottom) {\n stickScrollToEnd();\n }\n\n syncDebugInfoRef.current();\n }, [stickScrollToEnd]);\n\n syncAtBottomFromViewportRef.current = syncAtBottomFromViewport;\n\n const attachViewportResizeObserver = useCallback(() => {\n detachViewportResizeObserver();\n\n const node = viewportNodeRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new ResizeObserver(() => {\n syncAtBottomFromViewportRef.current();\n });\n\n observer.observe(node);\n viewportResizeObserverRef.current = observer;\n }, [detachViewportResizeObserver]);\n\n const attachLastItemResizeObserver = useCallback(\n (node: HTMLElement) => {\n detachLastItemResizeObserver();\n\n if (scrollStrategyRef.current !== 'end') {\n return;\n }\n\n const observer = new ResizeObserver(() => {\n // check the scroll strategy allways in callback to avoid race condition\n if (scrollStrategyRef.current === 'end') {\n stickScrollToEnd();\n }\n });\n\n observer.observe(node);\n resizeObserverRef.current = observer;\n },\n [detachLastItemResizeObserver, stickScrollToEnd],\n );\n\n attachLastItemResizeObserverRef.current = attachLastItemResizeObserver;\n\n const applyEndScrollStrategy = useCallback(() => {\n if (!userScrollIntentRef.current || scrollStrategyRef.current === 'end') {\n return;\n }\n\n scrollStrategyRef.current = 'end';\n clearUserScrollIntent();\n\n const lastItem = lastItemNodeRef.current;\n\n if (lastItem) {\n attachLastItemResizeObserverRef.current(lastItem);\n }\n\n syncDebugInfoRef.current();\n }, [clearUserScrollIntent]);\n\n const handleBottomTriggerVisibility = useCallback(\n (isVisible: boolean) => {\n if (!isVisible && !hasUserEscapedRef.current) {\n syncDebugInfoRef.current();\n return;\n }\n\n isAtBottomRef.current = isVisible;\n setIsAtBottom(isVisible);\n\n if (isProgrammaticScrollRef.current) {\n syncDebugInfoRef.current();\n return;\n }\n\n if (isVisible) {\n setHasUserEscaped(false);\n applyEndScrollStrategy();\n }\n\n syncDebugInfoRef.current();\n },\n [applyEndScrollStrategy, setHasUserEscaped],\n );\n\n const handleScroll = useCallback(\n (event: Event) => {\n if (event.target !== viewportNodeRef.current) {\n return;\n }\n\n const node = event.target as HTMLDivElement;\n const lastScrollTop = lastScrollTopRef.current ?? node.scrollTop;\n const currentScrollTop = node.scrollTop;\n\n lastScrollTopRef.current = currentScrollTop;\n\n if (isProgrammaticScrollRef.current || !userScrollIntentRef.current) {\n return;\n }\n\n const isScrollingUp = currentScrollTop < lastScrollTop;\n const atBottom = node.scrollHeight - node.clientHeight - currentScrollTop <= 1;\n\n if (atBottom) {\n if (scrollStrategyRef.current !== 'end') {\n handleBottomTriggerVisibility(true);\n }\n\n return;\n }\n\n if (isScrollingUp) {\n setHasUserEscaped(true);\n applyLastItemScrollStrategy();\n }\n },\n [applyLastItemScrollStrategy, handleBottomTriggerVisibility, setHasUserEscaped],\n );\n\n const handleWheel = useCallback(\n (event: WheelEvent) => {\n const node = viewportNodeRef.current;\n\n if (event.deltaY < 0 && node && node.scrollHeight > node.clientHeight) {\n setHasUserEscaped(true);\n applyLastItemScrollStrategy();\n }\n\n markUserScrollIntent();\n },\n [applyLastItemScrollStrategy, markUserScrollIntent, setHasUserEscaped],\n );\n\n const handleTouchStart = useCallback(() => {\n markUserScrollIntent();\n }, [markUserScrollIntent]);\n\n const handlePointerDown = useCallback(() => {\n markUserScrollIntent();\n }, [markUserScrollIntent]);\n\n const attachBottomTriggerObserver = useCallback(() => {\n detachBottomTriggerObserver();\n\n const root = viewportNodeRef.current;\n const target = bottomTriggerNodeRef.current;\n\n if (!root || !target) {\n return;\n }\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (!entry) {\n return;\n }\n\n handleBottomTriggerVisibility(entry.isIntersecting);\n },\n { root, threshold: 0 },\n );\n\n observer.observe(target);\n bottomTriggerObserverRef.current = observer;\n }, [detachBottomTriggerObserver, handleBottomTriggerVisibility]);\n\n const viewportRef = useCallback(\n (node: HTMLDivElement | null) => {\n if (viewportNodeRef.current) {\n viewportNodeRef.current.removeEventListener('scroll', handleScroll);\n viewportNodeRef.current.removeEventListener('wheel', handleWheel);\n viewportNodeRef.current.removeEventListener('touchstart', handleTouchStart);\n viewportNodeRef.current.removeEventListener('pointerdown', handlePointerDown);\n detachViewportResizeObserver();\n }\n\n viewportNodeRef.current = node;\n\n if (node) {\n lastScrollTopRef.current = node.scrollTop;\n lastViewportScrollHeightRef.current = node.scrollHeight;\n node.addEventListener('scroll', handleScroll, { passive: true });\n node.addEventListener('wheel', handleWheel, { passive: true });\n node.addEventListener('touchstart', handleTouchStart, { passive: true });\n node.addEventListener('pointerdown', handlePointerDown);\n attachBottomTriggerObserver();\n attachViewportResizeObserver();\n syncAtBottomFromViewport();\n } else {\n clearUserScrollIntent();\n detachBottomTriggerObserver();\n detachViewportResizeObserver();\n }\n },\n [\n attachBottomTriggerObserver,\n attachViewportResizeObserver,\n clearUserScrollIntent,\n detachBottomTriggerObserver,\n detachViewportResizeObserver,\n handlePointerDown,\n handleScroll,\n handleTouchStart,\n handleWheel,\n syncAtBottomFromViewport,\n ],\n );\n\n const bottomTriggerRef = useCallback(\n (node: HTMLLIElement | null) => {\n bottomTriggerNodeRef.current = node;\n\n if (node) {\n attachBottomTriggerObserver();\n } else {\n detachBottomTriggerObserver();\n }\n },\n [attachBottomTriggerObserver, detachBottomTriggerObserver],\n );\n\n const lastItemRef = useCallback(\n (node: HTMLElement | null) => {\n const previousNode = lastItemNodeRef.current;\n\n if (node === null) {\n detachLastItemResizeObserver();\n lastItemNodeRef.current = null;\n syncDebugInfoRef.current();\n return;\n }\n\n if (node === previousNode) {\n if (scrollStrategyRef.current === 'end') {\n attachLastItemResizeObserver(node);\n }\n\n return;\n }\n\n detachLastItemResizeObserver();\n lastItemNodeRef.current = node;\n\n // Intentional: on every new last-item node, reset to lastItem so the viewport\n // shows the head (start) of the new message. Do not change this.\n setHasUserEscaped(false);\n isAtBottomRef.current = true;\n setIsAtBottom(true);\n scrollStrategyRef.current = 'lastItem';\n\n if (node) {\n attachLastItemResizeObserver(node);\n }\n\n syncDebugInfoRef.current();\n },\n [attachLastItemResizeObserver, detachLastItemResizeObserver, setHasUserEscaped],\n );\n\n const setMessageCount = useCallback(\n (count: number) => {\n messageCountRef.current = count;\n\n if (count < LAST_ITEM_SCROLL_MAX_COUNT) {\n scrollStrategyRef.current = 'lastItem';\n detachLastItemResizeObserver();\n } else if (scrollStrategyRef.current === 'end') {\n const lastItem = lastItemNodeRef.current;\n\n if (lastItem) {\n attachLastItemResizeObserver(lastItem);\n }\n }\n\n syncDebugInfoRef.current();\n },\n [attachLastItemResizeObserver, detachLastItemResizeObserver],\n );\n\n const reset = useCallback(() => {\n setHasUserEscaped(false);\n\n if (messageCountRef.current < LAST_ITEM_SCROLL_MAX_COUNT) {\n scrollStrategyRef.current = 'lastItem';\n detachLastItemResizeObserver();\n }\n\n syncDebugInfoRef.current();\n }, [detachLastItemResizeObserver, setHasUserEscaped]);\n\n const scrollBottom = useCallback(() => {\n reset();\n markUserScrollIntent();\n applyEndScrollStrategy();\n isProgrammaticScrollRef.current = true;\n syncDebugInfoRef.current();\n\n const behavior = isSmoothScrollRef.current ? 'smooth' : 'instant';\n isSmoothScrollRef.current = true;\n\n requestAnimationFrame(() => {\n viewportNodeRef.current?.scrollTo({\n top: viewportNodeRef.current.scrollHeight,\n behavior,\n });\n\n clearProgrammaticScroll();\n syncDebugInfoRef.current();\n });\n }, [applyEndScrollStrategy, clearProgrammaticScroll, markUserScrollIntent, reset]);\n\n const scrollToLatest = useCallback(() => {\n scroll();\n }, [scroll]);\n\n const contextValue = useMemo<ChatConversationContextValue>(\n () => ({\n viewportRef,\n bottomTriggerRef,\n lastItemRef,\n isAtBottom,\n setMessageCount,\n scrollBottom,\n scrollToLatest,\n }),\n [\n viewportRef,\n bottomTriggerRef,\n lastItemRef,\n isAtBottom,\n setMessageCount,\n scrollBottom,\n scrollToLatest,\n ],\n );\n\n return (\n <ChatConversationContext.Provider value={contextValue}>\n {debug && (\n <code className=\"absolute top-0 left-0 z-50 w-full bg-red-500/90 p-8 text-white pointer-events-none\">\n {JSON.stringify(debugInfo, null, 2)}\n </code>\n )}\n {children}\n </ChatConversationContext.Provider>\n );\n}\n","import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';\nimport {\n createContext,\n memo,\n useContext,\n useLayoutEffect,\n useMemo,\n type CSSProperties,\n type ReactNode,\n type ComponentProps,\n} from 'react';\n\nimport { useChatConversationContext } from '@/contexts';\nimport { ChevronDownIcon } from '@swisper.ai/icons';\nimport { IconButton, Tooltip } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\ninterface ChatMessagesContextValue {\n messageCount: number;\n}\n\nconst ChatMessagesContext = createContext<ChatMessagesContextValue | null>(null);\n\nconst ChatMessagesListRowContext = createContext(false);\n\nfunction useChatMessagesContext() {\n const context = useContext(ChatMessagesContext);\n\n if (!context) {\n throw new Error('\"ChatMessagesList\" must be used within a ChatMessages');\n }\n\n return context;\n}\n\nexport interface ChatMessagesProps {\n /** A `ChatMessagesList` and an optional `ChatMessagesScrollButton`. */\n children: ReactNode;\n /** Classes merged last onto the root (`data-slot=\"chat-messages\"`). */\n className?: string;\n /** Number of rows `ChatMessagesList` renders; changing it scrolls the last row into view. */\n messageCount?: number;\n /** Space in px between rows and between the messages inside a `ChatMessageListGroup`. */\n gap?: number;\n}\n\n/**\n * Root of a conversation that scrolls itself. It holds the row count and the gap, and has to be\n * rendered inside a `ChatConversationProvider`, which owns the scroll state.\n */\nexport function ChatMessages({\n children,\n className,\n messageCount = 0,\n gap = 16,\n}: ChatMessagesProps) {\n const { setMessageCount } = useChatConversationContext();\n const contextValue = useMemo<ChatMessagesContextValue>(() => ({ messageCount }), [messageCount]);\n\n useLayoutEffect(() => {\n setMessageCount(messageCount);\n }, [messageCount, setMessageCount]);\n\n return (\n <ChatMessagesContext.Provider value={contextValue}>\n <div\n data-slot=\"chat-messages\"\n data-testid=\"chat-messages\"\n className={cn('relative flex min-h-0 flex-1 flex-col', className)}\n style={{ '--chat-messages-gap': `${gap}px` } as CSSProperties}\n >\n {children}\n </div>\n </ChatMessagesContext.Provider>\n );\n}\n\nexport interface ChatMessagesListProps {\n /** Render function for one row; it gets the row's index and returns a `ChatMessageListGroup`. */\n children: (index: number) => ReactNode;\n /** Classes merged last onto the `role=\"log\"` list (`data-slot=\"chat-messages-list\"`). */\n className?: string;\n /** Classes merged last onto the scroll container (`data-slot=\"chat-messages-scroll-area\"`). */\n scrollAreaClassName?: string;\n /** Classes merged last onto the scrolling viewport (`data-slot=\"chat-messages-viewport\"`). */\n viewportClassName?: string;\n /** Classes merged last onto the hidden end sentinel the list uses to detect the bottom. */\n bottomTriggerClassName?: string;\n}\n\n/**\n * The scrolling list: renders `messageCount` rows from its render function inside a `role=\"log\"`\n * list, and scrolls the last row to the top of the view when the count changes.\n */\nexport function ChatMessagesList({\n children,\n className,\n scrollAreaClassName,\n viewportClassName,\n bottomTriggerClassName,\n}: ChatMessagesListProps) {\n const { viewportRef, bottomTriggerRef, scrollToLatest } = useChatConversationContext();\n const { messageCount } = useChatMessagesContext();\n\n const rows = useMemo(() => {\n return Array.from({ length: messageCount }, (_, index) => index);\n }, [messageCount]);\n\n const lastIndex = messageCount - 1;\n\n useLayoutEffect(() => {\n scrollToLatest();\n }, [messageCount, scrollToLatest]);\n\n return (\n <ScrollAreaPrimitive.Root\n data-slot=\"chat-messages-scroll-area\"\n className={cn(\n 'min-h-0 flex-1',\n 'relative group/scroll-area',\n 'overflow-y-hidden',\n 'transform-gpu',\n scrollAreaClassName,\n )}\n >\n <ScrollAreaPrimitive.Viewport\n ref={viewportRef}\n data-slot=\"chat-messages-viewport\"\n className={cn('@container-[size]', 'will-change-scroll h-full w-full', viewportClassName)}\n style={{ scrollbarGutter: 'stable both-edges' }}\n >\n <ul\n data-slot=\"chat-messages-list\"\n data-testid=\"chat-messages-list\"\n role=\"log\"\n aria-label=\"Message list\"\n aria-atomic=\"false\"\n className={cn('m-0 flex flex-col gap-(--chat-messages-gap) p-0', className)}\n >\n {rows.map((index) => (\n <ChatMessagesListRow key={index} index={index} isLast={index === lastIndex}>\n {children}\n </ChatMessagesListRow>\n ))}\n\n <li\n ref={bottomTriggerRef}\n data-slot=\"chat-messages-bottom-trigger\"\n className={cn('h-px -mt-(--chat-messages-gap)', bottomTriggerClassName)}\n aria-hidden=\"true\"\n />\n </ul>\n </ScrollAreaPrimitive.Viewport>\n\n <ChatMessagesScrollBar orientation=\"vertical\" />\n </ScrollAreaPrimitive.Root>\n );\n}\n\ninterface ChatMessagesListRowProps {\n children: (index: number) => ReactNode;\n index: number;\n isLast: boolean;\n}\n\nconst ChatMessagesListRow = memo(function ChatMessagesListRow({\n children,\n index,\n isLast,\n}: ChatMessagesListRowProps) {\n return (\n <li data-slot=\"chat-messages-row\">\n <ChatMessagesListRowContext.Provider value={isLast}>\n {children(index)}\n </ChatMessagesListRowContext.Provider>\n </li>\n );\n});\n\nexport interface ChatMessageListGroupProps extends ComponentProps<'div'> {}\n\n/**\n * One row's content: a question with its answer. The last group is at least as tall as the\n * viewport, so a new question can settle at the top while its answer grows below it.\n */\nexport function ChatMessageListGroup({ children, className, ...rest }: ChatMessageListGroupProps) {\n const isLast = useContext(ChatMessagesListRowContext);\n const { lastItemRef } = useChatConversationContext();\n\n return (\n <div\n ref={isLast ? lastItemRef : undefined}\n data-slot=\"chat-message-list-group\"\n data-is-last={isLast}\n className={cn(\n 'flex flex-col gap-(--chat-messages-gap)',\n 'data-[is-last=true]:min-h-[calc(100cqh-var(--chat-messages-gap))]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessagesScrollButtonProps {\n /** Classes merged last onto the positioned wrapper (`data-slot=\"chat-messages-scroll-button\"`). */\n className?: string;\n /** Classes merged last onto the icon button inside the wrapper. */\n buttonClassName?: string;\n /** The button's tooltip and its `aria-label`. */\n tooltip?: string;\n /** Replaces the chevron icon. */\n children?: ReactNode;\n}\n\ninterface ChatMessagesScrollBarProps extends ComponentProps<\n typeof ScrollAreaPrimitive.ScrollAreaScrollbar\n> {\n className?: string;\n orientation?: 'vertical' | 'horizontal';\n}\n\nfunction ChatMessagesScrollBar({\n className,\n orientation = 'vertical',\n ...rest\n}: ChatMessagesScrollBarProps) {\n return (\n <ScrollAreaPrimitive.ScrollAreaScrollbar\n data-slot=\"scroll-area-scrollbar\"\n orientation={orientation}\n className={cn(\n 'opacity-0 group-hover/scroll-area:opacity-100',\n 'rounded-[8px]',\n 'bg-scrollbar-track hover:bg-scrollbar-track-hover',\n 'transition-opacity duration-200 ease-in-out',\n 'flextouch-none select-none transition-colors',\n orientation === 'vertical' &&\n 'h-full w-scrollbar border-l border-l-transparent px-4 py-[12px]',\n orientation === 'horizontal' &&\n 'h-scrollbar w-full border-t border-t-transparent px-[12px] py-4',\n className,\n )}\n {...rest}\n >\n <ScrollAreaPrimitive.ScrollAreaThumb\n data-slot=\"scroll-area-thumb\"\n className={cn(\n 'relative flex-1 rounded-full',\n 'bg-scrollbar-thumb hover:bg-scrollbar-thumb-hover',\n orientation === 'vertical' && 'w-scrollbar-thumb!',\n orientation === 'horizontal' && 'h-scrollbar-thumb!',\n )}\n />\n </ScrollAreaPrimitive.ScrollAreaScrollbar>\n );\n}\n\n/**\n * Scroll-to-latest button over the list. It is hidden while the view is at the bottom and scrolls\n * there when clicked.\n */\nexport const ChatMessagesScrollButton = memo(function ChatMessagesScrollButton({\n className,\n buttonClassName,\n tooltip,\n children,\n}: ChatMessagesScrollButtonProps) {\n const { isAtBottom, scrollBottom } = useChatConversationContext();\n\n return (\n <div\n data-slot=\"chat-messages-scroll-button\"\n data-testid=\"chat-message-history-scroll-button\"\n data-hidden={isAtBottom}\n aria-hidden={isAtBottom ? true : undefined}\n className={cn(\n 'absolute',\n 'px-[12px]',\n 'bottom-0',\n 'right-0 -translate-x-[12px]',\n 'md:right-auto md:left-1/2 md:-translate-x-1/2',\n '-translate-y-[12px]',\n 'flex items-center justify-center',\n 'transition-opacity duration-200 ease-in-out',\n 'data-[hidden=true]:pointer-events-none',\n 'data-[hidden=true]:opacity-0 data-[hidden=false]:opacity-100',\n className,\n )}\n >\n <Tooltip tooltip={tooltip} side={'top'}>\n <IconButton\n className={cn('bg-paper-elevation-2', buttonClassName)}\n color=\"primary\"\n size=\"md\"\n onClick={() => scrollBottom()}\n tabIndex={-1}\n aria-label={tooltip}\n >\n {children || <ChevronDownIcon />}\n </IconButton>\n </Tooltip>\n </div>\n );\n});\n","import type { ReactNode } from 'react';\n\nimport { CloseIcon } from '@swisper.ai/icons';\nimport { IconButton, Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatMessageAttachmentCardProps {\n /** Classes merged last onto the card root, e.g. `w-fit max-w-60` to cap the chip's width. */\n className?: string;\n /** The card parts: an icon or a preview, the content with the file name, and the actions. */\n children?: ReactNode;\n /** Shrinks the card to a 56px square for an image shown through `ChatMessageAttachmentCardPreview`. */\n isPreview?: boolean;\n /** Shows a pointer cursor, a hover background and the remove action on hover. Set `false` for a sent message's attachments. */\n isInteractive?: boolean;\n}\n\n/** A compact chip for a file attached to a chat prompt or message. */\nexport function ChatMessageAttachmentCard({\n className,\n children,\n isPreview,\n isInteractive = true,\n}: ChatMessageAttachmentCardProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-message-attachment-card\"\n data-testid=\"chat-message-attachment-card\"\n data-preview={isPreview}\n data-interactive={isInteractive}\n className={cn(\n 'group/chat-message-attachment-card',\n 'relative',\n 'flex flex-row gap-8',\n 'p-8 rounded-promptbox-attachment',\n 'bg-promptbox-attachment-background',\n 'data-[interactive=true]:cursor-pointer',\n 'data-[interactive=true]:hover:bg-[linear-gradient(var(--color-promptbox-attachment-background-hover),var(--color-promptbox-attachment-background-hover)),linear-gradient(var(--color-promptbox-attachment-background),var(--color-promptbox-attachment-background))]',\n 'data-[preview=true]:m-px',\n 'data-[preview=true]:size-[56px]',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageAttachmentCardContentProps {\n /** Classes merged last onto the content element. */\n className?: string;\n /** The file name, usually a `ChatMessageAttachmentCardTitle`. */\n children?: ReactNode;\n}\n\n/** The text area of the card: takes the width left beside the icon and clips what overflows. */\nexport function ChatMessageAttachmentCardContent({\n className,\n children,\n}: ChatMessageAttachmentCardContentProps) {\n return (\n <div\n data-slot=\"chat-message-attachment-card-content\"\n data-testid=\"chat-message-attachment-card-content\"\n className={cn('flex-1', 'flex items-center', 'overflow-hidden', className)}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageAttachmentCardTitleProps {\n /** Classes merged last onto the title element. */\n className?: string;\n /** The file name as uploaded, including its extension. */\n children?: ReactNode;\n}\n\n/** The file name, truncated to one line. */\nexport function ChatMessageAttachmentCardTitle({\n className,\n children,\n}: ChatMessageAttachmentCardTitleProps) {\n return (\n <Typography\n variant=\"body-sm\"\n data-slot=\"chat-message-attachment-card-title\"\n data-testid=\"chat-message-attachment-card-title\"\n className={cn('truncate', className)}\n >\n {children}\n </Typography>\n );\n}\n\nexport interface ChatMessageAttachmentCardPreviewProps {\n /** Classes merged last onto the `figure` that covers the card. */\n className?: string;\n /** Classes merged last onto the image inside the figure, e.g. `object-contain`. */\n imageClassName?: string;\n /** URL of the image, e.g. a data URL read from the attached file. */\n previewSrc: string;\n}\n\n/** An image thumbnail that covers the whole card. Use it on a card with `isPreview`. */\nexport function ChatMessageAttachmentCardPreview({\n className,\n imageClassName,\n previewSrc,\n}: ChatMessageAttachmentCardPreviewProps) {\n return (\n <figure\n data-slot=\"chat-message-attachment-card-preview\"\n data-testid=\"chat-message-attachment-card-preview\"\n className={cn(\n 'absolute top-0 left-0',\n 'inset-0 w-full h-full',\n 'overflow-hidden rounded-promptbox-attachment',\n 'pointer-events-none',\n className,\n )}\n >\n <img\n data-slot=\"chat-message-attachment-card-preview-image\"\n src={previewSrc}\n alt=\"Preview\"\n className={cn('w-full h-full object-cover', imageClassName)}\n />\n </figure>\n );\n}\n\nexport interface ChatMessageAttachmentCardActionsProps {\n /** Classes merged last onto the wrapper pinned to the card's top-right corner. */\n className?: string;\n /** Classes merged last onto the remove button inside the wrapper. */\n buttonClassName?: string;\n /** Called when the remove button is clicked. The consumer removes the attachment. */\n onDelete?: () => void;\n}\n\n/** The remove button of an interactive card, shown while the card is hovered. */\nexport function ChatMessageAttachmentCardActions({\n className,\n buttonClassName,\n onDelete,\n}: ChatMessageAttachmentCardActionsProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-message-attachment-card-actions\"\n data-testid=\"chat-message-attachment-card-actions\"\n className={cn(\n 'absolute top-0 right-0',\n 'translate-x-1/2 -translate-y-1/2',\n 'hidden',\n 'group-data-[interactive=true]/chat-message-attachment-card:group-hover/chat-message-attachment-card:flex',\n 'rounded-overlay-tools-wrapper',\n 'bg-overlay-tools-background-base',\n className,\n )}\n >\n <IconButton\n variant=\"tertiary\"\n isSemantic={false}\n onClick={onDelete}\n size=\"xs\"\n className={cn('size-[24px]', 'text-icon-button-tertiary-icon', buttonClassName)}\n >\n <CloseIcon />\n </IconButton>\n </div>\n );\n}\n","import { type FunctionComponent } from 'react';\n\nimport {\n PdfIcon,\n PptIcon,\n CodeIcon,\n DocIcon,\n XlsIcon,\n DraftIcon,\n type SvgIconProps,\n} from '@swisper.ai/icons';\nimport { cn } from '@swisper.ai/web-core';\n\ntype IconProps = SvgIconProps;\n\n/** The file types the card has an icon for. `image` has no icon: show a `ChatMessageAttachmentCardPreview`. */\nexport type ChatMessageAttachmentCardIconType =\n 'spreadsheet' | 'pdf' | 'presentation' | 'document' | 'code' | 'image' | 'unknown';\n\nconst CHAT_ATTACHMENT_ICON_MAP: Record<\n Exclude<ChatMessageAttachmentCardIconType, 'image'>,\n {\n component: FunctionComponent<IconProps>;\n className?: string;\n }\n> = {\n spreadsheet: {\n component: XlsIcon,\n className: 'bg-data-d',\n },\n pdf: {\n component: PdfIcon,\n className: 'bg-data-a',\n },\n presentation: {\n component: PptIcon,\n className: 'bg-data-e',\n },\n document: {\n component: DocIcon,\n className: 'bg-data-c',\n },\n code: {\n component: CodeIcon,\n className: 'bg-data-f',\n },\n unknown: {\n component: DraftIcon,\n className: 'bg-data-f',\n },\n};\n\nexport interface ChatMessageAttachmentCardIconProps extends IconProps {\n /** The file type, which picks the icon and its background colour. `getAttachmentIcon(file)` returns it. */\n icon: Exclude<ChatMessageAttachmentCardIconType, 'image'>;\n}\n\n/** The file-type icon on its coloured tile. `className` goes to the tile, every other prop to the icon. */\nexport function ChatMessageAttachmentCardIcon({\n icon,\n className,\n ...rest\n}: ChatMessageAttachmentCardIconProps) {\n const { component: Icon, className: iconClassName } = CHAT_ATTACHMENT_ICON_MAP[icon];\n\n return (\n <span\n data-slot=\"chat-message-attachment-card-icon\"\n data-testid=\"chat-attachment-icon\"\n data-icon={icon}\n className={cn(\n 'inline-flex items-center justify-center',\n 'rounded-[8px]',\n 'p-8',\n 'size-promptbox-attachment-size-icon-container',\n 'text-icon-fill-inverse',\n '[&_svg]:size-[24px]',\n iconClassName,\n className,\n )}\n >\n <Icon {...rest} />\n </span>\n );\n}\n","import mime from 'mime';\n\nimport type { ChatMessageAttachmentCardIconType } from './chat-message-attachment-card-icon';\n\ntype IconType = Exclude<ChatMessageAttachmentCardIconType, 'image'>;\n\nconst MIME_TO_ICON: Record<string, IconType> = {\n 'application/pdf': 'pdf',\n 'application/vnd.ms-excel': 'spreadsheet',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'spreadsheet',\n 'text/csv': 'spreadsheet',\n 'application/vnd.ms-powerpoint': 'presentation',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'presentation',\n 'application/msword': 'document',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'document',\n 'text/plain': 'document',\n 'application/rtf': 'document',\n 'application/vnd.oasis.opendocument.text': 'document',\n};\n\n/** Picks the icon type for a file from its name's extension; a file it doesn't recognise is `unknown`. */\nexport function getAttachmentIcon(file: File): IconType {\n const mimeType = mime.getType(file.name);\n\n if (!mimeType) {\n return 'unknown';\n }\n\n if (mimeType in MIME_TO_ICON) {\n return MIME_TO_ICON[mimeType];\n }\n\n if (\n mimeType.startsWith('text/') ||\n mimeType.includes('javascript') ||\n mimeType.includes('json')\n ) {\n return 'code';\n }\n\n return 'unknown';\n}\n","import type { SwiTagName } from '../../types';\n\nexport function isCustomComponentTag(tag: string): tag is SwiTagName {\n return tag.startsWith('swi-');\n}\n","import { useMemo } from 'react';\nimport rehypeSanitize, { defaultSchema } from 'rehype-sanitize';\nimport { defaultRehypePlugins, defaultRemarkPlugins, type StreamdownProps } from 'streamdown';\nimport { type PluggableList } from 'unified';\n\nimport type { SwiTagName } from '../../types';\n\nimport type { CustomMarkdownViewerComponents, MarkdownViewerComponents } from './types';\nimport { isCustomComponentTag } from './utils';\n\nexport interface UseMarkdownViewerHookProps {\n customComponents: CustomMarkdownViewerComponents;\n}\n\ntype UseMarkdownViewerHook = Pick<\n StreamdownProps,\n 'components' | 'remarkPlugins' | 'rehypePlugins'\n>;\n\nexport function useMarkdownViewer({\n customComponents,\n}: UseMarkdownViewerHookProps): UseMarkdownViewerHook {\n const swiTags = useMemo<SwiTagName[]>(\n () =>\n Object.keys(customComponents).filter((key): key is SwiTagName => {\n if (!isCustomComponentTag(key)) {\n console.warn(`[MarkdownViewer] Invalid custom component tag: ${key}`);\n return false;\n }\n\n return true;\n }),\n [customComponents],\n );\n\n const remarkPlugins = useMemo<PluggableList>(() => [...Object.values(defaultRemarkPlugins)], []);\n const rehypePlugins = useMemo<PluggableList>(() => {\n return [\n ...Object.values(defaultRehypePlugins),\n [\n rehypeSanitize,\n {\n ...defaultSchema,\n tagNames: [...(defaultSchema?.tagNames || []), ...swiTags],\n protocols: {\n ...defaultSchema?.protocols,\n href: [...(defaultSchema?.protocols?.href ?? []), 'swisper', 'swisper://'],\n },\n },\n ],\n ];\n }, [swiTags]);\n\n return {\n components: customComponents satisfies MarkdownViewerComponents,\n remarkPlugins,\n rehypePlugins,\n };\n}\n","import { Streamdown } from 'streamdown';\n\nimport type { Markdown } from '../../types';\n\nimport { useMarkdownViewer } from './hooks';\nimport type { CustomMarkdownViewerComponents } from './types';\n\nimport 'katex/dist/katex.min.css';\n\nexport interface MarkdownViewerProps {\n /** The full markdown received so far: GFM, math and `<swi-*>` tags. */\n markdown: Markdown;\n /** Classes merged last onto the root element, e.g. `text-text-secondary` or a different block gap. */\n className?: string;\n /** Set while the text is still arriving: animates the last block and shows the caret. */\n isStreaming?: boolean;\n /** Shows a block caret after the last character while `isStreaming` is true. */\n hasCaret?: boolean;\n /** Renderers keyed by tag name: `<swi-*>` tags, or overrides for standard markdown elements. */\n customComponents?: CustomMarkdownViewerComponents;\n}\n\n/** Renders markdown through Streamdown, repairing half-received syntax and `<swi-*>` tags as it streams. */\nexport function MarkdownViewer({\n markdown,\n className,\n isStreaming = false,\n hasCaret = false,\n customComponents = {},\n}: MarkdownViewerProps) {\n const { components, remarkPlugins, rehypePlugins } = useMarkdownViewer({ customComponents });\n\n return (\n <Streamdown\n className={className}\n caret={hasCaret ? 'block' : undefined}\n isAnimating={isStreaming}\n components={components}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n linkSafety={{ enabled: false }}\n remend={{\n handlers: [\n {\n name: 'swi-tag-filter',\n handle: swiTagHandler,\n priority: 0,\n },\n ],\n }}\n >\n {markdown}\n </Streamdown>\n );\n}\n\nfunction swiTagHandler(text: string, separator = '|') {\n const incompleteRegex = /<swi-(\\w+)([^>]*)$/gm;\n const [incompleteMatch, tagName] = incompleteRegex.exec(text) ?? [];\n\n if (text.endsWith('<swi-')) {\n return text + '>';\n }\n\n if (incompleteMatch) {\n return text.replace(incompleteMatch, `<swi-${tagName}>`);\n }\n\n if (text.endsWith(separator)) {\n return text.slice(0, -1) + `</swi-${tagName}>`;\n }\n\n const openingTagRegex = /<swi-(\\w+)([^>]*)>/g;\n const openingTags: { name: string; index: number }[] = [];\n let match;\n\n openingTagRegex.lastIndex = 0;\n while ((match = openingTagRegex.exec(text)) !== null) {\n const tagName = match[1];\n const attributes = match[2];\n\n if (attributes.trim().endsWith('/')) {\n continue;\n }\n\n openingTags.push({\n name: tagName,\n index: match.index,\n });\n }\n\n if (openingTags.length > 0) {\n const lastTag = openingTags[openingTags.length - 1];\n const tagName = lastTag.name;\n const closingTag = `</swi-${tagName}>`;\n\n const textAfterOpening = text.substring(lastTag.index);\n if (!textAfterOpening.includes(closingTag)) {\n return text + closingTag;\n }\n }\n\n return text;\n}\n","import { useMemo } from 'react';\n\nimport type { Markdown } from '../../types';\nimport { MarkdownViewer, type CustomMarkdownViewerComponents } from '../markdown-viewer';\n\nexport interface ChatMessageResponseProps {\n message: Markdown;\n isStreaming?: boolean;\n}\n\nexport function ChatMessageResponse({ message, isStreaming }: ChatMessageResponseProps) {\n const customComponents = useMemo<CustomMarkdownViewerComponents>(() => {\n return {};\n }, []);\n\n return (\n <MarkdownViewer\n hasCaret={false}\n markdown={message}\n isStreaming={isStreaming}\n customComponents={customComponents}\n />\n );\n}\n","import { forwardRef, type ComponentProps, type ReactNode } from 'react';\n\nimport { IconButton, Tooltip, type IconButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatMessageToolbarProps extends ComponentProps<'div'> {\n /** The toolbar parts: a `ChatMessageToolbarTimestamp` and a `ChatMessageToolbarActions`. */\n children: ReactNode;\n /** Classes merged last onto the row. */\n className?: string;\n /** Flips the row, so the first part sits at the end. Set it under an end-aligned question. */\n reverse?: boolean;\n}\n\n/** The row under a chat message: its timestamp at one end, its icon actions at the other. */\nexport function ChatMessageToolbar({\n children,\n className,\n reverse = false,\n ...rest\n}: ChatMessageToolbarProps) {\n return (\n <div\n data-slot=\"chat-message-toolbar\"\n data-testid=\"chat-message-toolbar\"\n data-reverse={reverse}\n className={cn(\n 'flex items-center justify-between',\n 'gap-16',\n 'h-24',\n 'data-[reverse=true]:flex-row-reverse',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageToolbarActionsProps extends ComponentProps<'div'> {\n /** The actions, each a `ChatMessageToolbarActionButton`. */\n children: ReactNode;\n /** Classes merged last onto the group. */\n className?: string;\n}\n\n/** Groups the toolbar's action buttons in a `role=\"group\"` row. */\nexport function ChatMessageToolbarActions({\n children,\n className,\n ...rest\n}: ChatMessageToolbarActionsProps) {\n return (\n <div\n data-slot=\"chat-message-toolbar-actions\"\n data-testid=\"chat-message-toolbar-actions\"\n role=\"group\"\n className={cn('flex items-center gap-8', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageToolbarActionButtonProps extends Omit<\n IconButtonProps,\n 'variant' | 'size'\n> {\n /** The action's icon. */\n children: ReactNode;\n /** Classes merged last onto the button. */\n className?: string;\n /** Text of the hover tooltip. It is not the accessible name: pass `aria-label` as well. */\n tooltip?: string;\n}\n\n/**\n * One icon action in the toolbar: an extra-small tertiary `IconButton`, in a `Tooltip` when\n * `tooltip` is set. The ref reaches the button, so it can be an `asChild` menu or popover trigger.\n */\nexport const ChatMessageToolbarActionButton = forwardRef<\n HTMLButtonElement | HTMLSpanElement,\n ChatMessageToolbarActionButtonProps\n>(function ChatMessageToolbarActionButton({ children, className, tooltip, ...rest }, ref) {\n const content = (\n <IconButton\n ref={ref}\n variant=\"tertiary\"\n isSemantic={false}\n size=\"xs\"\n data-slot=\"chat-message-toolbar-action-button\"\n className={cn('text-action-active', className)}\n {...rest}\n >\n {children}\n </IconButton>\n );\n\n if (!tooltip) {\n return content;\n }\n\n return <Tooltip tooltip={tooltip}>{content}</Tooltip>;\n});\n\nChatMessageToolbarActionButton.displayName = 'ChatMessageToolbarActionButton';\n\nexport interface ChatMessageToolbarTimestampProps extends ComponentProps<'div'> {\n /** The time, already formatted. */\n children: ReactNode;\n /** Classes merged last onto the timestamp. */\n className?: string;\n}\n\n/** When the message was sent. Renders its children as given. */\nexport function ChatMessageToolbarTimestamp({\n className,\n children,\n ...rest\n}: ChatMessageToolbarTimestampProps) {\n return (\n <div\n data-slot=\"chat-message-toolbar-timestamp\"\n className={cn('text-action-active', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","export function getSnoozeUntilDate(minutes: number) {\n return new Date(Date.now() + minutes * 60 * 1000);\n}\n\nconst MINUTES_PER_HOUR = 60;\nconst MINUTES_PER_DAY = 24 * MINUTES_PER_HOUR;\nconst MILLISECONDS_PER_MINUTE = 60 * 1000;\n\nfunction formatDurationPart(value: number, unit: string) {\n return `${value} ${unit}${value === 1 ? '' : 's'}`;\n}\n\nexport function formatSnoozeDate(date: Date, prefix = 'in', now: Date = new Date()) {\n const totalMinutes = Math.max(\n 0,\n Math.ceil((date.getTime() - now.getTime()) / MILLISECONDS_PER_MINUTE),\n );\n const days = Math.floor(totalMinutes / MINUTES_PER_DAY);\n const hours = Math.floor((totalMinutes % MINUTES_PER_DAY) / MINUTES_PER_HOUR);\n const minutes = totalMinutes % MINUTES_PER_HOUR;\n const parts: string[] = [];\n\n if (days > 0) {\n parts.push(formatDurationPart(days, 'day'));\n }\n\n if (hours > 0) {\n parts.push(formatDurationPart(hours, 'hour'));\n }\n\n parts.push(formatDurationPart(minutes, 'minute'));\n\n return [prefix, ...parts].filter(Boolean).join(' ');\n}\n","import {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useMemo,\n useState,\n useEffect,\n type ComponentProps,\n type MouseEvent,\n type ReactNode,\n} from 'react';\n\nimport {\n ChevronDownIcon,\n ChevronUpIcon,\n CloseIcon,\n DeleteIcon,\n SignalReadIcon,\n SignalUnreadIcon,\n SnoozeIcon,\n} from '@swisper.ai/icons';\nimport { Button, Chip, IconButton, Typography } from '@swisper.ai/ui';\nimport type { ChipProps, IconButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { ChatNotificationCardPriority } from './types';\nimport { formatSnoozeDate } from './utils';\n\ninterface ChatNotificationCardContextValue {\n isExpanded: boolean;\n setExpanded: (expanded: boolean) => void;\n toggleExpanded: () => void;\n}\n\nconst ChatNotificationCardContext = createContext<ChatNotificationCardContextValue>(null!);\n\n/** The card's expanded state and its setters. Throws outside a `ChatNotificationCard`. */\nexport function useChatNotificationCardContext() {\n const context = useContext(ChatNotificationCardContext);\n\n if (!context) {\n throw new Error('\"useChatNotificationCardContext\" must be used within a ChatNotificationCard');\n }\n\n return context;\n}\n\nexport interface ChatNotificationCardProps {\n children?: ReactNode;\n /** `default` for a card in a list, `floating` (bordered) for a card shown on its own over the chat. */\n variant?: 'default' | 'floating';\n className?: string;\n /** Classes for the hover overlay (`data-slot=\"chat-notification-card-overlay\"`). */\n overlayClassName?: string;\n /** Initial expanded state when uncontrolled. */\n defaultExpanded?: boolean;\n /** Controlled expanded state; pair it with `onExpandedChange`. */\n expanded?: boolean;\n /** Called with the next expanded state when the expand button is toggled. */\n onExpandedChange?: (expanded: boolean) => void;\n /** Called on a click anywhere on the card except its buttons. */\n onClick?: () => void;\n}\n\n/**\n * Root of the notification card. Holds the expanded state and exposes it, with the variant, as\n * `data-expanded` and `data-variant`.\n */\nexport function ChatNotificationCard({\n children,\n variant = 'default',\n className,\n overlayClassName,\n defaultExpanded = false,\n expanded,\n onExpandedChange,\n onClick,\n}: ChatNotificationCardProps) {\n const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);\n const isExpanded = expanded ?? internalExpanded;\n\n const setExpanded = useCallback(\n (nextExpanded: boolean) => {\n if (expanded === undefined) {\n setInternalExpanded(nextExpanded);\n }\n\n onExpandedChange?.(nextExpanded);\n },\n [expanded, onExpandedChange],\n );\n\n const toggleExpanded = useCallback(() => {\n setExpanded(!isExpanded);\n }, [isExpanded, setExpanded]);\n\n const contextValue = useMemo(\n () => ({\n isExpanded,\n setExpanded,\n toggleExpanded,\n }),\n [isExpanded, setExpanded, toggleExpanded],\n );\n\n return (\n <ChatNotificationCardContext.Provider value={contextValue}>\n <div\n role=\"alert\"\n data-slot=\"chat-notification-card\"\n data-testid=\"chat-notification-card\"\n data-variant={variant}\n data-expanded={isExpanded}\n aria-expanded={isExpanded}\n className={cn(\n 'group/chat-notification-card',\n 'relative',\n 'p-[12px]',\n 'rounded-[12px] overflow-hidden',\n 'bg-paper-elevation-2',\n 'flex flex-col gap-8',\n 'bg-paper-elevation-2',\n 'data-[variant=floating]:border data-[variant=floating]:border-component-divider',\n className,\n )}\n onClick={onClick}\n >\n {children}\n\n <div\n data-slot=\"chat-notification-card-overlay\"\n className={cn(\n 'absolute inset-0 pointer-events-none bg-secondary-states-hover opacity-0 group-hover/chat-notification-card:opacity-100 transition-opacity duration-200 ease-in-out',\n overlayClassName,\n )}\n />\n </div>\n </ChatNotificationCardContext.Provider>\n );\n}\n\nexport interface ChatNotificationCardHeadProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Top row of the card: the header on the left, the actions on the right. */\nexport function ChatNotificationCardHead({ children, className }: ChatNotificationCardHeadProps) {\n return (\n <header\n data-slot=\"chat-notification-card-head\"\n data-testid=\"chat-notification-card-head\"\n className={cn(\n 'grid grid-cols-[minmax(0,1fr)_auto] items-center gap-8',\n 'min-h-[32px]',\n className,\n )}\n >\n {children}\n </header>\n );\n}\n\nexport interface ChatNotificationCardHeaderProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Left side of the head: the icon and the title. */\nexport function ChatNotificationCardHeader({\n children,\n className,\n}: ChatNotificationCardHeaderProps) {\n return (\n <div\n data-slot=\"chat-notification-card-header\"\n data-testid=\"chat-notification-card-header\"\n className={cn(\n 'min-w-0 flex items-center gap-8 overflow-hidden',\n 'text-layout-feedback-info-background-default',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardHeaderIconProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Icon that says what kind of notification this is. */\nexport function ChatNotificationCardHeaderIcon({\n children,\n className,\n}: ChatNotificationCardHeaderIconProps) {\n return (\n <div\n data-slot=\"chat-notification-card-header-icon\"\n data-testid=\"chat-notification-card-header-icon\"\n className={cn(\n 'shrink-0',\n 'inline-flex items-center justify-center',\n 'pointer-events-none',\n '[&_svg]:size-[20px]!',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardHeaderTitleProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Holds the title label and the status chip. */\nexport function ChatNotificationCardHeaderTitle({\n children,\n className,\n}: ChatNotificationCardHeaderTitleProps) {\n return (\n <div\n data-slot=\"chat-notification-card-header-title\"\n data-testid=\"chat-notification-card-header-title\"\n className={cn('min-w-0 flex flex-1 items-center gap-8 overflow-hidden', className)}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardHeaderTitleLabelProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Notification type or short subject: semibold, uppercase, truncated to one line. */\nexport function ChatNotificationCardHeaderTitleLabel({\n children,\n className,\n}: ChatNotificationCardHeaderTitleLabelProps) {\n return (\n <Typography\n variant=\"body-sm\"\n fontWeight=\"semibold\"\n data-slot=\"chat-notification-card-header-title-label\"\n data-testid=\"chat-notification-card-header-title-label\"\n className={cn('min-w-0 truncate', 'text-left text-inherit uppercase', className)}\n asChild\n >\n <span>{children}</span>\n </Typography>\n );\n}\n\nconst CHIP_PRIORITY_MAP: Record<ChatNotificationCardPriority, ChipProps['color']> = {\n low: 'info',\n medium: 'warning',\n high: 'error',\n};\n\nexport interface ChatNotificationCardHeaderStatusProps extends Omit<\n ChipProps,\n 'color' | 'variant' | 'size'\n> {\n children?: ReactNode;\n priority?: ChatNotificationCardPriority;\n className?: string;\n}\n\n/** Priority chip: `high` is an error chip, `medium` a warning chip, `low` renders nothing. */\nexport function ChatNotificationCardHeaderStatus({\n children,\n priority = 'medium',\n className,\n ...rest\n}: ChatNotificationCardHeaderStatusProps) {\n const color = CHIP_PRIORITY_MAP[priority];\n\n if (priority === 'low') {\n return null;\n }\n\n return (\n <Chip\n data-slot=\"chat-notification-card-header-status\"\n data-testid=\"chat-notification-card-header-status\"\n data-priority={priority}\n className={cn('text-text-secondary', 'shrink-0', className)}\n size=\"2xs\"\n color={color}\n variant=\"outlined\"\n {...rest}\n >\n {children}\n </Chip>\n );\n}\n\nexport interface ChatNotificationCardActionsProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Right side of the head: the timestamp and the buttons. */\nexport function ChatNotificationCardActions({\n children,\n className,\n}: ChatNotificationCardActionsProps) {\n return (\n <div\n data-slot=\"chat-notification-card-actions\"\n data-testid=\"chat-notification-card-actions\"\n role=\"group\"\n className={cn(\n 'flex flex-row items-center justify-end',\n 'shrink-0 justify-self-end',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardTimestampProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Relative time the notification arrived. */\nexport function ChatNotificationCardTimestamp({\n children,\n className,\n}: ChatNotificationCardTimestampProps) {\n return (\n <Typography\n variant=\"caption\"\n data-slot=\"chat-notification-card-timestamp\"\n data-testid=\"chat-notification-card-timestamp\"\n className={cn('text-text-secondary', 'inline-flex px-8', 'leading-[32px]', className)}\n asChild\n >\n <span>{children}</span>\n </Typography>\n );\n}\n\nexport interface ChatNotificationCardButtonsProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Group for the action buttons. Stops their clicks from reaching the card's `onClick`. */\nexport function ChatNotificationCardButtons({\n children,\n className,\n}: ChatNotificationCardButtonsProps) {\n function handleMouseDown(event: MouseEvent<HTMLDivElement>) {\n event.stopPropagation();\n }\n\n function handleClick(event: MouseEvent<HTMLDivElement>) {\n event.stopPropagation();\n }\n\n return (\n <div\n data-slot=\"chat-notification-card-buttons\"\n data-testid=\"chat-notification-card-buttons\"\n role=\"group\"\n className={cn('flex flex-row items-center justify-end', 'gap-8', className)}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n >\n {children}\n </div>\n );\n}\n\ninterface ChatNotificationCardActionButtonProps extends Omit<\n ComponentProps<typeof IconButton>,\n 'children' | 'size' | 'variant'\n> {}\n\nexport interface ChatNotificationCardReadActionButtonProps extends Omit<\n ChatNotificationCardActionButtonProps,\n 'onClick'\n> {\n children?: ReactNode;\n className?: string;\n /** Whether the notification is read. Swaps the icon and sets `data-read`. */\n isRead?: boolean;\n /** Called with the toggled read state on click. */\n onRead?: (isRead: boolean) => void;\n}\n\n/** Icon button that toggles the notification between read and unread. */\nexport const ChatNotificationCardReadActionButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardReadActionButtonProps\n>(function ChatNotificationCardReadActionButton(\n { className, isRead = false, onRead, ...rest },\n ref,\n) {\n function handleClick() {\n onRead?.(!isRead);\n }\n\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-read-action-button\"\n data-read={isRead}\n aria-label=\"Mark notifications as read\"\n size=\"sm\"\n variant=\"tertiary\"\n className={className}\n onClick={handleClick}\n {...rest}\n >\n {isRead ? <SignalUnreadIcon /> : <SignalReadIcon />}\n </IconButton>\n );\n});\n\nChatNotificationCardReadActionButton.displayName = 'ChatNotificationCardReadActionButton';\n\nexport interface ChatNotificationCardSnoozeButtonProps extends ChatNotificationCardActionButtonProps {\n children?: ReactNode;\n className?: string;\n /** Classes for the time-left label of the snoozed button (`data-slot=\"chat-notification-card-snooze-button-label\"`). */\n labelClassName?: string;\n /** Classes for the cancel label shown on hover (`data-slot=\"chat-notification-card-snooze-button-cancel-label\"`). */\n cancelLabelClassName?: string;\n /** When in the future, the button shows the time left and cancels the snooze on click. */\n snoozeUntilDate?: Date;\n /** Text that replaces the time left while the snoozed button is hovered. */\n cancelLabel?: ReactNode;\n /** Formats the time left. Defaults to `formatSnoozeDate` ('in 2 minutes'). */\n formatDate?: (date: Date) => ReactNode;\n /** Called when the snoozed button is clicked. */\n onCancel?: () => void;\n}\n\n/**\n * Snooze control. An icon button that calls `onClick`; while `snoozeUntilDate` is in the future, a\n * text button with the time left that calls `onCancel`. `data-snoozed` says which one is rendered.\n */\nexport const ChatNotificationCardSnoozeButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardSnoozeButtonProps\n>(function ChatNotificationCardSnoozeButton(\n {\n className,\n labelClassName,\n cancelLabelClassName,\n snoozeUntilDate,\n cancelLabel = 'Cancel',\n formatDate = formatSnoozeDate,\n onCancel,\n onClick,\n onMouseEnter,\n onMouseLeave,\n ...rest\n },\n ref,\n) {\n const [isHovered, setIsHovered] = useState(false);\n const isSnoozed = snoozeUntilDate && snoozeUntilDate > new Date();\n\n useEffect(() => {\n if (!isSnoozed) {\n setIsHovered(false);\n }\n }, [isSnoozed]);\n\n function handleMouseEnter(event: MouseEvent<HTMLButtonElement>) {\n setIsHovered(true);\n onMouseEnter?.(event);\n }\n\n function handleMouseLeave(event: MouseEvent<HTMLButtonElement>) {\n setIsHovered(false);\n onMouseLeave?.(event);\n }\n\n function handleCancel() {\n setIsHovered(false);\n onCancel?.();\n }\n\n if (isSnoozed) {\n return (\n <Button\n ref={ref}\n data-slot=\"chat-notification-card-snooze-button\"\n data-snoozed=\"true\"\n data-hover={isHovered}\n startIcon={isHovered ? <CloseIcon /> : <SnoozeIcon />}\n variant=\"tertiary\"\n size=\"md\"\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onClick={handleCancel}\n className={cn(\n 'group/snooze-button',\n 'text-chip-outlined-warning-text h-[32px]!',\n className,\n )}\n {...rest}\n >\n <span\n data-slot=\"chat-notification-card-snooze-button-label\"\n className={cn(\n 'group-data-[hover=true]/snooze-button:opacity-0',\n 'transition-opacity duration-200 ease-in-out',\n labelClassName,\n )}\n >\n {formatDate(snoozeUntilDate)}\n </span>\n <span\n data-slot=\"chat-notification-card-snooze-button-cancel-label\"\n className={cn(\n 'absolute left-0 w-full text-center pl-[16px]',\n 'transition-opacity duration-200 ease-in-out',\n 'opacity-0',\n 'group-data-[hover=true]/snooze-button:opacity-100',\n cancelLabelClassName,\n )}\n >\n {cancelLabel}\n </span>\n </Button>\n );\n }\n\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-snooze-button\"\n data-snoozed=\"false\"\n aria-label=\"Snooze notification\"\n size=\"sm\"\n variant=\"tertiary\"\n className={cn('group/snooze-button', className)}\n onClick={onClick}\n {...rest}\n >\n <SnoozeIcon />\n </IconButton>\n );\n});\n\nChatNotificationCardSnoozeButton.displayName = 'ChatNotificationCardSnoozeButton';\n\nexport interface ChatNotificationCardDeleteButtonProps extends ChatNotificationCardActionButtonProps {}\n\n/** Icon button that deletes the notification from a list. */\nexport const ChatNotificationCardDeleteButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardDeleteButtonProps\n>(function ChatNotificationCardDeleteButton({ className, ...rest }, ref) {\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-delete-button\"\n aria-label=\"Delete notification\"\n size=\"sm\"\n variant=\"tertiary\"\n className={className}\n {...rest}\n >\n <DeleteIcon />\n </IconButton>\n );\n});\n\nChatNotificationCardDeleteButton.displayName = 'ChatNotificationCardDeleteButton';\n\nexport interface ChatNotificationCardCloseButtonProps extends ChatNotificationCardActionButtonProps {}\n\n/** Icon button that dismisses a floating notification. */\nexport const ChatNotificationCardCloseButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardCloseButtonProps\n>(function ChatNotificationCardCloseButton({ className, ...rest }, ref) {\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-close-button\"\n aria-label=\"Close notification\"\n size=\"sm\"\n variant=\"tertiary\"\n className={className}\n {...rest}\n >\n <CloseIcon />\n </IconButton>\n );\n});\n\nChatNotificationCardCloseButton.displayName = 'ChatNotificationCardCloseButton';\n\nexport interface ChatNotificationCardContentProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Body of the card. Renders the expand button at its bottom-right corner. */\nexport function ChatNotificationCardContent({\n children,\n className,\n}: ChatNotificationCardContentProps) {\n return (\n <div\n data-slot=\"chat-notification-card-content\"\n data-testid=\"chat-notification-card-content\"\n className={cn('flex flex-col items-start text-left gap-4', 'relative pr-[40px]', className)}\n >\n {children}\n\n <ChatNotificationCardExpandButton />\n </div>\n );\n}\n\nexport interface ChatNotificationCardContentTitleProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Subject line of the notification, above the description. */\nexport function ChatNotificationCardContentTitle({\n children,\n className,\n}: ChatNotificationCardContentTitleProps) {\n return (\n <Typography\n variant=\"body-sm\"\n fontWeight=\"semibold\"\n data-slot=\"chat-notification-card-content-title\"\n data-testid=\"chat-notification-card-content-title\"\n className={cn('text-text-primary', 'text-left', className)}\n asChild\n >\n <span>{children}</span>\n </Typography>\n );\n}\n\nexport interface ChatNotificationCardContentDescriptionProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Notification text, clamped to two lines until the card is expanded. */\nexport function ChatNotificationCardContentDescription({\n children,\n className,\n}: ChatNotificationCardContentDescriptionProps) {\n return (\n <Typography\n variant=\"body-sm\"\n data-slot=\"chat-notification-card-content-description\"\n data-testid=\"chat-notification-card-content-description\"\n className={cn(\n 'text-text-primary',\n 'mt-8',\n 'group-data-[expanded=false]/chat-notification-card:line-clamp-2',\n 'w-full [&>div>*]:wrap-break-word',\n className,\n )}\n asChild\n >\n <div>{children}</div>\n </Typography>\n );\n}\n\nexport interface ChatNotificationCardContentActionsProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Follow-up actions, shown only while the card is expanded. */\nexport function ChatNotificationCardContentActions({\n children,\n className,\n}: ChatNotificationCardContentActionsProps) {\n return (\n <div\n data-slot=\"chat-notification-card-content-actions\"\n data-testid=\"chat-notification-card-content-actions\"\n role=\"group\"\n className={cn(\n 'hidden',\n 'group-data-[expanded=true]/chat-notification-card:flex',\n 'flex-row items-center gap-8',\n 'mt-4',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardExpandButtonProps extends Omit<\n IconButtonProps,\n 'children' | 'onClick'\n> {\n className?: string;\n onClick?: (event: MouseEvent<HTMLButtonElement>) => void;\n}\n\n/**\n * Chevron button that toggles the expanded state. `ChatNotificationCardContent` already renders\n * one, so a card needs no second.\n */\nexport const ChatNotificationCardExpandButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardExpandButtonProps\n>(function ChatNotificationCardExpandButton({ className, onMouseDown, onClick, ...rest }, ref) {\n const { isExpanded, toggleExpanded } = useChatNotificationCardContext();\n\n function handleMouseDown(event: MouseEvent<HTMLButtonElement>) {\n event.stopPropagation();\n onMouseDown?.(event);\n }\n\n function handleClick(event: MouseEvent<HTMLButtonElement>) {\n event.stopPropagation();\n toggleExpanded();\n onClick?.(event);\n }\n\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-expand-button\"\n data-testid=\"chat-notification-card-expand-button\"\n size=\"sm\"\n variant=\"tertiary\"\n aria-expanded={isExpanded}\n className={cn(\n 'my-4',\n 'h-auto! px-0!',\n 'absolute bottom-0 right-0',\n 'transition-opacity duration-200 ease-in',\n 'opacity-0 group-data-[expanded=true]/chat-notification-card:opacity-100 group-hover/chat-notification-card:opacity-100',\n className,\n )}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n {...rest}\n >\n {isExpanded ? <ChevronUpIcon /> : <ChevronDownIcon />}\n </IconButton>\n );\n});\n\nChatNotificationCardExpandButton.displayName = 'ChatNotificationCardExpandButton';\n\n/** Aliases kept for older imports; use the full part names. */\nexport const ChatNotificationCardIcon = ChatNotificationCardHeaderIcon;\nexport const ChatNotificationCardDescription = ChatNotificationCardContentDescription;\nexport const ChatNotificationCardTimeStamp = ChatNotificationCardTimestamp;\n","import { forwardRef, type ComponentProps } from 'react';\n\nimport { Popover, PopoverContent, PopoverTrigger } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatNotificationPopupProps extends ComponentProps<typeof Popover> {}\n\n/**\n * Root of the notification popup. Holds the open state, uncontrolled through `defaultOpen` or\n * controlled through `open` and `onOpenChange`. Renders no element of its own.\n */\nexport function ChatNotificationPopup({ children, ...rest }: ChatNotificationPopupProps) {\n return <Popover {...rest}>{children}</Popover>;\n}\n\nexport interface ChatNotificationPopupTriggerProps extends ComponentProps<typeof PopoverTrigger> {}\n\n/** The button that opens and closes the popup. Pass `asChild` to use your own button. */\nexport const ChatNotificationPopupTrigger = forwardRef<\n HTMLButtonElement,\n ChatNotificationPopupTriggerProps\n>(function ChatNotificationPopupTrigger({ children, ...rest }, ref) {\n return (\n <PopoverTrigger ref={ref} data-slot=\"chat-notification-popup-trigger\" {...rest}>\n {children}\n </PopoverTrigger>\n );\n});\n\nChatNotificationPopupTrigger.displayName = 'ChatNotificationPopupTrigger';\n\nexport interface ChatNotificationPopupContentProps extends ComponentProps<typeof PopoverContent> {}\n\n/** The panel that holds the notifications. Portalled, and 467px wide from `md` up. */\nexport const ChatNotificationPopupContent = forwardRef<\n HTMLDivElement,\n ChatNotificationPopupContentProps\n>(function ChatNotificationPopupContent({ children, className, ...rest }, ref) {\n return (\n <PopoverContent\n ref={ref}\n data-slot=\"chat-notification-popup-content\"\n className={cn('md:w-[467px]', className)}\n {...rest}\n >\n {children}\n </PopoverContent>\n );\n});\n\nChatNotificationPopupContent.displayName = 'ChatNotificationPopupContent';\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport { Chip, Typography, type TypographyProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatRepliesProps {\n /** The `ChatReply` rows. */\n children: ReactNode;\n /** Classes for the list (`data-slot=\"chat-replies\"`). */\n className?: string;\n /** Pads the list. Set `false` when the parent already provides the padding. */\n hasPadding?: boolean;\n}\n\n/** The list of rows that summarises a drafted reply; a `ul` that stacks its `ChatReply` rows. */\nexport function ChatReplies({ className, children, hasPadding = true }: ChatRepliesProps) {\n return (\n <ul\n data-testid=\"chat-replies\"\n data-slot=\"chat-replies\"\n data-padding={hasPadding}\n className={cn(\n 'flex flex-col justify-start items-start gap-8',\n 'data-[padding=true]:py-8 data-[padding=true]:px-16',\n className,\n )}\n >\n {children}\n </ul>\n );\n}\n\nexport interface ChatReplyProps extends ComponentProps<'li'> {\n /** A `ChatReplyLabel` followed by a `ChatReplyValue`. */\n children: ReactNode;\n /** Lets the row and its value wrap onto several lines, for a value that is a list of chips. */\n isMultiline?: boolean;\n}\n\n/** One row of the summary: a label and its value. An `li`, so it goes inside `ChatReplies`. */\nexport function ChatReply({ className, children, isMultiline = false, ...rest }: ChatReplyProps) {\n return (\n <li\n data-testid=\"chat-reply\"\n data-slot=\"chat-reply\"\n data-multiline={isMultiline}\n className={cn(\n 'group/chat-reply',\n 'flex gap-8 w-full min-h-[24px]',\n 'data-[multiline=false]:flex-row items-center',\n 'data-[multiline=true]:flex-wrap items-start',\n className,\n )}\n {...rest}\n >\n {children}\n </li>\n );\n}\n\nexport interface ChatReplyLabelProps extends ComponentProps<typeof Chip> {\n /** The field's name, one or two words. */\n children: ReactNode;\n}\n\n/** The name of the row's field, as an outlined chip that keeps its width. */\nexport function ChatReplyLabel({ className, children, ...rest }: ChatReplyLabelProps) {\n return (\n <Chip\n variant=\"outlined\"\n // @ts-expect-error TODO(design): Chip has no `sm` size since the size scale changed (md is the old sm); renders without size classes.\n size=\"sm\"\n // @ts-expect-error TODO(design): Chip has no `secondary` color any more; renders without color classes.\n color=\"secondary\"\n data-testid=\"chat-reply-label\"\n data-slot=\"chat-reply-label\"\n className={cn('shrink-0', className)}\n {...rest}\n >\n {children}\n </Chip>\n );\n}\n\nexport interface ChatReplyValueProps extends Omit<TypographyProps, 'variant'> {\n /** The field's content: text, or one chip per item in a multiline row. */\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** The row's value: secondary text cut to one line, or wrapping items when the row is multiline. */\nexport function ChatReplyValue({\n className,\n children,\n asChild = false,\n ...rest\n}: ChatReplyValueProps) {\n return (\n <Typography\n data-testid=\"chat-reply-value\"\n data-slot=\"chat-reply-value\"\n variant=\"body-sm\"\n className={cn(\n 'leading-[24px]',\n 'flex flex-1 min-w-0 text-text-secondary',\n 'items-start',\n 'group-data-[multiline=false]/chat-reply:flex-1 truncate',\n 'group-data-[multiline=true]/chat-reply:flex-wrap',\n 'group-data-[multiline=true]/chat-reply:gap-4',\n className,\n )}\n asChild\n {...rest}\n >\n <div>{children}</div>\n </Typography>\n );\n}\n","import {\n Children,\n cloneElement,\n createContext,\n forwardRef,\n isValidElement,\n useContext,\n useMemo,\n type MouseEvent,\n type ReactElement,\n type ReactNode,\n} from 'react';\n\nimport {\n List,\n ListItem,\n ListItemAction,\n ListItemTitle,\n ListItemTrigger,\n listItemVariants,\n Typography,\n type ListItemActionProps,\n type ListItemProps,\n type ListProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\ninterface ChatSuggestionContextValue {\n index?: number;\n}\n\nconst ChatSuggestionContext = createContext<ChatSuggestionContextValue>(null!);\n\nexport function useChatSuggestionContext() {\n const context = useContext(ChatSuggestionContext);\n\n if (!context) {\n throw new Error('\"useChatSuggestionContext\" must be used within a ChatSuggestion');\n }\n\n return context;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestions\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionsProps extends Omit<ListProps, 'asChild'> {}\n\n/**\n * The numbered list of suggestions, an `<ol>` built on `ui/List`: one Tab stop, arrow keys between\n * suggestions (wrapping at the ends unless `hasLoop={false}`), one highlighted suggestion. Name it\n * with `aria-label` or `aria-labelledby`. It gives each direct child its zero-based `index`.\n */\nexport const ChatSuggestions = forwardRef<HTMLOListElement, ChatSuggestionsProps>(\n function ChatSuggestions({ children, className, hasLoop = true, ...props }, ref) {\n return (\n <List asChild hasLoop={hasLoop} ref={ref} {...props}>\n <ol\n data-slot=\"chat-suggestions\"\n data-testid=\"chat-suggestions\"\n className={cn('m-0 p-0 list-none flex flex-col items-stretch gap-0', className)}\n >\n {Children.map(children, (child, index) => {\n if (!isValidElement(child)) {\n return child;\n }\n\n return cloneElement(child as ReactElement<ChatSuggestionProps>, { index });\n })}\n </ol>\n </List>\n );\n },\n);\n\nChatSuggestions.displayName = 'ChatSuggestions';\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestion\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionProps extends Omit<\n ListItemProps,\n 'asChild' | 'className' | 'isSelected'\n> {\n /** Zero-based position in the list. `ChatSuggestions` sets it on its direct children. */\n index?: number;\n className?: string;\n /** Classes for the overlay `role=\"button\"` that covers the suggestion. */\n triggerClassName?: string;\n /** The pointer entered the suggestion. Keyboard highlight does not call it. */\n onHover?: () => void;\n}\n\n/**\n * One suggestion: an `<li>` whose whole surface is the selectable element (an overlay\n * `role=\"button\"` named by `ChatSuggestionLabel`). `onSelect` fires on click, Enter and Space.\n * Controls in the row go in `ChatSuggestionAction`, which stacks above the overlay.\n */\nexport const ChatSuggestion = forwardRef<HTMLLIElement, ChatSuggestionProps>(\n function ChatSuggestion(\n { index, children, className, triggerClassName, onHover, onMouseEnter, ...props },\n ref,\n ) {\n const contextValue = useMemo(() => ({ index }), [index]);\n\n function handleMouseEnter(event: MouseEvent<HTMLLIElement>) {\n onMouseEnter?.(event);\n onHover?.();\n }\n\n return (\n <ChatSuggestionContext.Provider value={contextValue}>\n <ListItem\n ref={ref}\n data-slot=\"chat-suggestion\"\n className={listItemVariants(\n cn('relative items-start gap-0 p-4 text-typography-text-secondary', className),\n { highlighted: 'bg-layout-accent-low-background-hover-default' },\n )}\n {...props}\n onMouseEnter={handleMouseEnter}\n >\n <ListItemTrigger\n className={cn('absolute inset-0 rounded-[inherit] outline-none', triggerClassName)}\n />\n {children}\n </ListItem>\n </ChatSuggestionContext.Provider>\n );\n },\n);\n\nChatSuggestion.displayName = 'ChatSuggestion';\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestionLabelIcon / ChatSuggestionLabel\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionLabelIconProps {\n children?: ReactNode;\n className?: string;\n /** Classes for the 32px box that holds the number or the icon. */\n innerClassName?: string;\n}\n\n/** The leading slot: the suggestion's number, or the icon passed as children. */\nexport function ChatSuggestionLabelIcon({\n children,\n className,\n innerClassName,\n}: ChatSuggestionLabelIconProps) {\n const { index = 0 } = useChatSuggestionContext();\n\n return (\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-suggestion-label-icon\"\n className={cn(\n 'inline-flex flex-row justify-center items-center shrink-0 size-auto text-inherit',\n className,\n )}\n >\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-suggestion-label-icon-inner\"\n className={cn(\n 'size-[32px]',\n 'inline-flex items-center justify-center',\n 'px-8 py-[7px]',\n '[&_svg]:size-[18px]!',\n innerClassName,\n )}\n >\n {children || (\n <Typography\n variant=\"caption-md\"\n fontWeight=\"normal\"\n className=\"text-inherit leading-none\"\n asChild\n >\n <span>{index + 1}</span>\n </Typography>\n )}\n </span>\n </span>\n );\n}\n\nexport interface ChatSuggestionLabelProps {\n children: ReactNode;\n className?: string;\n isMultiline?: boolean;\n}\n\n/** The suggestion's text and its accessible name. Up to three lines, or one with `isMultiline={false}`. */\nexport function ChatSuggestionLabel({\n children,\n className,\n isMultiline = true,\n}: ChatSuggestionLabelProps) {\n return (\n <Typography\n variant=\"body-small-low\"\n data-slot=\"chat-suggestion-label\"\n data-multiline={isMultiline}\n className={cn(\n 'gap-0 px-4 my-[7px]',\n 'h-full min-w-0 flex-1 items-center justify-center text-left text-inherit',\n 'data-[multiline=false]:truncate',\n 'data-[multiline=true]:line-clamp-3',\n className,\n )}\n asChild\n >\n <ListItemTitle>{children}</ListItemTitle>\n </Typography>\n );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestionActions / ChatSuggestionAction\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionActionsProps {\n children: ReactNode;\n className?: string;\n}\n\n/**\n * The trailing slot, shown while the suggestion is highlighted (pointer over it or focus inside\n * it). Holds a hint icon, or controls each wrapped in `ChatSuggestionAction`.\n */\nexport function ChatSuggestionActions({ children, className }: ChatSuggestionActionsProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-suggestion-actions\"\n className={cn(\n 'shrink-0 flex items-center justify-center gap-8',\n 'self-start',\n 'min-w-[32px] h-[32px]',\n // Clicks on the hint icon fall through to the overlay trigger.\n 'pointer-events-none',\n '*:text-secondary-main',\n '[&>svg]:size-[18px]!',\n 'opacity-0',\n 'group-data-highlighted/list-item:opacity-100',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatSuggestionActionProps extends ListItemActionProps {}\n\n/**\n * Wraps one control in `ChatSuggestionActions` (a dismiss `IconButton`). The control stacks above\n * the suggestion's overlay, never selects the suggestion, and is in the Tab order only in the row\n * that holds the list's Tab stop.\n */\nexport const ChatSuggestionAction = forwardRef<HTMLElement, ChatSuggestionActionProps>(\n function ChatSuggestionAction({ className, children, ...rest }, ref) {\n return (\n <ListItemAction ref={ref} className={cn('pointer-events-auto', className)} {...rest}>\n {children}\n </ListItemAction>\n );\n },\n);\n\nChatSuggestionAction.displayName = 'ChatSuggestionAction';\n","import {\n MessageScroller as MessageScrollerPrimitive,\n useMessageScroller,\n useMessageScrollerScrollable,\n} from '@shadcn/react/message-scroller';\nimport {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ComponentProps,\n type ComponentPropsWithoutRef,\n type MutableRefObject,\n type ReactElement,\n type ReactNode,\n type Ref,\n} from 'react';\n\nimport { ChevronDownIcon } from '@swisper.ai/icons';\nimport { IconButton, Tooltip } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\n/**\n * `@shadcn/react` reads `ref` from props (React 19 style), but React 18 strips `ref` before props reach\n * a component. Calling the primitive directly from a `forwardRef` render puts `ref` back into its props.\n * Not used for Root: it spreads props after its own internal ref, so any `ref` prop (even `null`) replaces it.\n */\nfunction withForwardedRef<TProps>(\n Primitive: (props: TProps) => ReactElement | null,\n displayName: string,\n) {\n const Component = forwardRef<HTMLDivElement, Omit<TProps, 'ref'>>((props, ref) =>\n Primitive({ ...props, ref: ref } as TProps),\n );\n\n Component.displayName = displayName;\n\n return Component;\n}\n\nconst ViewportPrimitive = withForwardedRef(\n MessageScrollerPrimitive.Viewport,\n 'ChatThreadViewportPrimitive',\n);\nconst ContentPrimitive = withForwardedRef(\n MessageScrollerPrimitive.Content,\n 'ChatThreadContentPrimitive',\n);\nconst ItemPrimitive = withForwardedRef(MessageScrollerPrimitive.Item, 'ChatThreadItemPrimitive');\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n (ref as MutableRefObject<T | null>).current = value;\n }\n}\n\nconst DEFAULT_SCROLL_MARGIN = 12;\n\n/** CSS variable holding the height the latest group needs to fill the viewport once anchored at its top */\nconst GROUP_MIN_HEIGHT_VAR = '--chat-thread-group-min-height';\n\n// Commands\n\nexport type ChatThreadCommands = ReturnType<typeof useMessageScroller>;\n\nconst NOOP_COMMANDS: ChatThreadCommands = {\n scrollToEnd: () => false,\n scrollToMessage: () => false,\n scrollToStart: () => false,\n};\n\nconst ChatThreadCommandsContext = createContext<ChatThreadCommands | null>(null);\n\n/**\n * Scroll commands of the nearest `ChatThreadProvider`.\n * Safe outside a provider: commands become no-ops returning `false`.\n */\nexport function useChatThread(): ChatThreadCommands {\n return useContext(ChatThreadCommandsContext) ?? NOOP_COMMANDS;\n}\n\ninterface ChatThreadCommandsBridgeProps {\n children?: ReactNode;\n}\n\nfunction ChatThreadCommandsBridge({ children }: ChatThreadCommandsBridgeProps) {\n const { scrollToEnd, scrollToMessage, scrollToStart } = useMessageScroller();\n\n const commands = useMemo<ChatThreadCommands>(\n () => ({ scrollToEnd, scrollToMessage, scrollToStart }),\n [scrollToEnd, scrollToMessage, scrollToStart],\n );\n\n return (\n <ChatThreadCommandsContext.Provider value={commands}>\n {children}\n </ChatThreadCommandsContext.Provider>\n );\n}\n\n// Session\n\n/**\n * How the thread scrolls as messages arrive.\n * - `anchor`: question and answer chat. A new question settles at the top of the viewport and its answer\n * grows below it, so the reader reads each answer from its start.\n * - `follow`: terminal-style, for agent transcripts, tool runs and logs. New output is appended at the\n * bottom and pushes older content up; the view follows the latest output until the reader scrolls away,\n * and a new group brings it back to the end. A short thread sits at the bottom, next to the input.\n */\nexport type ChatThreadScrollMode = 'anchor' | 'follow';\n\ninterface ChatThreadSession {\n isStreaming: boolean;\n scrollMargin: number;\n scrollMode: ChatThreadScrollMode;\n /**\n * Ids of the groups the session opened with — history. Any other group is a new message and anchors.\n * `null` while the thread is empty.\n */\n knownGroupIds: ReadonlySet<string> | null;\n}\n\nconst ChatThreadSessionContext = createContext<ChatThreadSession | null>(null);\n\nfunction useChatThreadSession(component: string) {\n const session = useContext(ChatThreadSessionContext);\n\n if (!session) {\n throw new Error(`[web-chat-ui] <${component}> must be rendered inside <ChatThreadProvider>`);\n }\n\n return session;\n}\n\ntype ScrollerProviderProps = ComponentProps<typeof MessageScrollerPrimitive.Provider>;\n\nexport interface ChatThreadProviderProps extends ScrollerProviderProps {\n /** Identity of the conversation; changing it resets the thread so the new conversation opens at the end */\n conversationId?: string | null;\n /** Ids of the rendered groups, matching each `ChatThreadGroup`'s `groupId` */\n groupIds: readonly string[];\n /** Whether an answer is streaming into the thread */\n isStreaming?: boolean;\n /** How the thread scrolls as messages arrive; see `ChatThreadScrollMode`. Defaults to `anchor` */\n scrollMode?: ChatThreadScrollMode;\n /**\n * Keep following content that grows at the end (late cards, reply chips, images) until the reader scrolls\n * away. In `anchor` mode it defaults to following only while no answer is streaming, so a stream never\n * drags the view down; in `follow` mode it defaults to always following.\n */\n autoScroll?: boolean;\n}\n\ninterface ThreadSessionState {\n id: number;\n conversationId: string | null;\n knownGroupIds: ReadonlySet<string> | null;\n}\n\nfunction createSessionState(\n id: number,\n conversationId: string | null | undefined,\n groupIds: readonly string[],\n): ThreadSessionState {\n return {\n id,\n conversationId: conversationId ?? null,\n knownGroupIds: groupIds.length === 0 ? null : new Set(groupIds),\n };\n}\n\n/**\n * Holds the scroll session of one conversation: which groups are history and which are new, the scroll\n * mode, and the scroll commands `useChatThread` returns. Renders no element; wrap `ChatThread` and\n * anything that scrolls it.\n */\nexport function ChatThreadProvider({\n children,\n conversationId,\n groupIds,\n isStreaming = false,\n scrollMode = 'anchor',\n autoScroll = scrollMode === 'follow' || !isStreaming,\n defaultScrollPosition = 'end',\n scrollPreviousItemPeek = 0,\n scrollMargin = DEFAULT_SCROLL_MARGIN,\n ...rest\n}: ChatThreadProviderProps) {\n const [sessionState, setSessionState] = useState(() =>\n createSessionState(0, conversationId, groupIds),\n );\n\n // A new session per conversation, and whenever the thread empties or fills again: a chat switch renders\n // the old groups under the new id, clears them, then loads the new history — which must open at the end\n if (\n sessionState.conversationId !== (conversationId ?? null) ||\n (sessionState.knownGroupIds === null) !== (groupIds.length === 0)\n ) {\n setSessionState(createSessionState(sessionState.id + 1, conversationId, groupIds));\n }\n\n const { knownGroupIds } = sessionState;\n\n const session = useMemo<ChatThreadSession>(\n () => ({ isStreaming, scrollMargin, scrollMode, knownGroupIds }),\n [isStreaming, scrollMargin, scrollMode, knownGroupIds],\n );\n\n // Keyed on the session so the scroller remounts and applies its opening position again\n return (\n <MessageScrollerPrimitive.Provider\n key={sessionState.id}\n autoScroll={autoScroll}\n scrollPreviousItemPeek={scrollPreviousItemPeek}\n scrollMargin={scrollMargin}\n defaultScrollPosition={defaultScrollPosition}\n {...rest}\n >\n <ChatThreadSessionContext.Provider value={session}>\n {scrollMode === 'follow' && (\n <FollowNewGroups groupIds={groupIds} knownGroupIds={knownGroupIds} />\n )}\n <ChatThreadCommandsBridge>{children}</ChatThreadCommandsBridge>\n </ChatThreadSessionContext.Provider>\n </MessageScrollerPrimitive.Provider>\n );\n}\n\ninterface FollowNewGroupsProps {\n groupIds: readonly string[];\n knownGroupIds: ReadonlySet<string> | null;\n}\n\n/**\n * In `follow` mode, a new group (the reader sent a prompt) returns the view to the end and resumes following,\n * even when the reader had scrolled up to read earlier output.\n */\nfunction FollowNewGroups({ groupIds, knownGroupIds }: FollowNewGroupsProps) {\n const { scrollToEnd } = useMessageScroller();\n const lastGroupId = groupIds.at(-1);\n\n useLayoutEffect(() => {\n if (lastGroupId === undefined || knownGroupIds === null || knownGroupIds.has(lastGroupId))\n return;\n\n scrollToEnd({ behavior: 'auto' });\n }, [lastGroupId, knownGroupIds, scrollToEnd]);\n\n return null;\n}\n\n// Thread\n\nexport type ChatThreadError = Error | string;\n\nexport interface ChatThreadProps extends Omit<ComponentPropsWithoutRef<'div'>, 'children'> {\n children?: ReactNode;\n /** Classes on the scrolling viewport, the element between the root and the content */\n viewportClassName?: string;\n /** Classes on the scrolled content: its padding and the gap between groups */\n contentClassName?: string;\n viewportRef?: Ref<HTMLDivElement>;\n contentRef?: Ref<HTMLDivElement>;\n /** Renders the scroll-to-latest button */\n scrollButton?: boolean;\n /** Classes on the wrapper that positions the scroll-to-latest button */\n scrollButtonClassName?: string;\n scrollButtonTooltip?: string;\n isLoading?: boolean;\n hasError?: boolean;\n error?: ChatThreadError;\n /** Replaces the built-in error message */\n renderError?: (error?: ChatThreadError) => ReactNode;\n}\n\n/**\n * The scroller of a conversation: a viewport that scrolls the groups, the scroll-to-latest button and\n * the error state. Fills its parent, so the parent needs a definite height.\n */\nexport const ChatThread = forwardRef<HTMLDivElement, ChatThreadProps>(function ChatThread(\n {\n children,\n className,\n viewportClassName,\n contentClassName,\n viewportRef,\n contentRef,\n scrollButton = true,\n scrollButtonClassName,\n scrollButtonTooltip,\n isLoading = false,\n hasError = false,\n error,\n renderError,\n ...rest\n },\n ref,\n) {\n const { isStreaming, scrollMargin, scrollMode } = useChatThreadSession('ChatThread');\n const isAnchored = scrollMode === 'anchor';\n\n const viewportElementRef = useRef<HTMLDivElement | null>(null);\n const contentElementRef = useRef<HTMLDivElement | null>(null);\n\n const setViewport = useCallback(\n (element: HTMLDivElement | null) => {\n viewportElementRef.current = element;\n assignRef(viewportRef, element);\n // Root can't take `ref` without losing its internal one; the viewport is always its direct child\n assignRef(ref, (element?.parentElement as HTMLDivElement | null | undefined) ?? null);\n },\n [viewportRef, ref],\n );\n\n const setContent = useCallback(\n (element: HTMLDivElement | null) => {\n contentElementRef.current = element;\n assignRef(contentRef, element);\n },\n [contentRef],\n );\n\n useGroupMinHeight(viewportElementRef, contentElementRef, scrollMargin, isAnchored);\n\n return (\n <MessageScrollerPrimitive.Root\n data-slot=\"chat-thread\"\n data-testid=\"chat-thread\"\n data-scroll-mode={scrollMode}\n data-streaming={isStreaming}\n data-loading={isLoading}\n data-error={hasError}\n className={cn('relative flex flex-col flex-1 min-h-0 overflow-hidden', className)}\n {...rest}\n >\n <ViewportPrimitive\n ref={setViewport}\n data-slot=\"chat-thread-viewport\"\n aria-label=\"Chat message history\"\n className={cn(\n 'size-full overflow-x-hidden overflow-y-auto outline-none',\n 'will-change-scroll transform-gpu',\n // A continuous stream outruns smooth scrolling, so following jumps instead\n isAnchored && isStreaming && 'scroll-smooth',\n viewportClassName,\n )}\n style={{\n scrollbarGutter: 'stable both-edges',\n scrollbarWidth: 'thin',\n scrollbarColor: 'var(--color-scrollbar-thumb) transparent',\n }}\n >\n <ContentPrimitive\n ref={setContent}\n data-slot=\"chat-thread-content\"\n aria-busy={isStreaming}\n data-testid=\"chat-thread-content\"\n className={cn(\n 'relative flex flex-col gap-16',\n isAnchored\n ? // The primitive always appends its spacer, so the latest group is the second-to-last child\n '[&>[data-chat-thread-group]:nth-last-child(2)]:min-h-(--chat-thread-group-min-height)'\n : // Terminal-style: a short thread sits at the bottom, next to the input\n 'min-h-full justify-end',\n contentClassName,\n )}\n >\n {children}\n </ContentPrimitive>\n </ViewportPrimitive>\n\n {hasError && !isLoading && (\n <ChatThreadErrorState error={error}>{renderError?.(error)}</ChatThreadErrorState>\n )}\n\n {scrollButton && (\n <ChatThreadScrollButton className={scrollButtonClassName} tooltip={scrollButtonTooltip} />\n )}\n </MessageScrollerPrimitive.Root>\n );\n});\n\nChatThread.displayName = 'ChatThread';\n\n/**\n * Keeps the latest group at least as tall as the room below its anchored position, so a new message can\n * settle at the top of the viewport and the answer streams in without the scroll position jumping.\n * Only `anchor` mode needs it.\n */\nfunction useGroupMinHeight(\n viewportRef: MutableRefObject<HTMLDivElement | null>,\n contentRef: MutableRefObject<HTMLDivElement | null>,\n scrollMargin: number,\n isEnabled: boolean,\n) {\n useLayoutEffect(() => {\n const viewport = viewportRef.current;\n const content = contentRef.current;\n\n if (!viewport || !content) return;\n\n if (!isEnabled) {\n content.style.removeProperty(GROUP_MIN_HEIGHT_VAR);\n return;\n }\n\n const update = () => {\n const { paddingTop, paddingBottom } = window.getComputedStyle(content);\n const minHeight =\n viewport.clientHeight -\n (Number.parseFloat(paddingTop) || 0) -\n (Number.parseFloat(paddingBottom) || 0) -\n scrollMargin;\n\n content.style.setProperty(GROUP_MIN_HEIGHT_VAR, `${Math.max(0, minHeight)}px`);\n };\n\n update();\n\n if (typeof ResizeObserver === 'undefined') return;\n\n const observer = new ResizeObserver(update);\n observer.observe(viewport);\n observer.observe(content);\n\n return () => observer.disconnect();\n }, [viewportRef, contentRef, scrollMargin, isEnabled]);\n}\n\n// Groups\n\nexport interface ChatThreadGroupProps extends ComponentPropsWithoutRef<'div'> {\n groupId: string;\n}\n\n/**\n * One question with its answer. Groups the session opened with are history; in `anchor` mode any other\n * group is a new message and becomes the scroll anchor, settling at the top of the viewport. In `follow`\n * mode no group anchors.\n */\nexport const ChatThreadGroup = forwardRef<HTMLDivElement, ChatThreadGroupProps>(\n function ChatThreadGroup({ groupId, className, children, ...rest }, ref) {\n const { knownGroupIds, scrollMode } = useChatThreadSession('ChatThreadGroup');\n const isNew = scrollMode === 'anchor' && knownGroupIds !== null && !knownGroupIds.has(groupId);\n\n return (\n <ItemPrimitive\n ref={ref}\n // Namespaced: `data-message-id` is also how consumers find message bubbles\n messageId={`chat-thread-group-${groupId}`}\n scrollAnchor={isNew}\n data-slot=\"chat-thread-group\"\n data-chat-thread-group=\"\"\n className={cn('flex flex-col gap-16 w-full min-h-px mx-auto', className)}\n {...rest}\n >\n {children}\n </ItemPrimitive>\n );\n },\n);\n\nChatThreadGroup.displayName = 'ChatThreadGroup';\n\nexport interface ChatThreadMessageProps extends ComponentPropsWithoutRef<'div'> {\n messageId: string;\n}\n\n/** Marks the question of a group with its message id. Adds no styling. */\nexport const ChatThreadQuestion = forwardRef<HTMLDivElement, ChatThreadMessageProps>(\n function ChatThreadQuestion({ messageId, children, ...rest }, ref) {\n return (\n <div\n ref={ref}\n data-slot=\"chat-thread-question\"\n data-chat-thread-question=\"\"\n data-chat-thread-message-id={messageId}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n\nChatThreadQuestion.displayName = 'ChatThreadQuestion';\n\n/** Marks the answer of a group with its message id. Adds no styling. */\nexport const ChatThreadAnswer = forwardRef<HTMLDivElement, ChatThreadMessageProps>(\n function ChatThreadAnswer({ messageId, children, ...rest }, ref) {\n return (\n <div\n ref={ref}\n data-slot=\"chat-thread-answer\"\n data-chat-thread-answer=\"\"\n data-chat-thread-message-id={messageId}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n\nChatThreadAnswer.displayName = 'ChatThreadAnswer';\n\n// Parts\n\ninterface ChatThreadScrollButtonProps {\n className?: string;\n tooltip?: string;\n}\n\nfunction ChatThreadScrollButton({ className, tooltip }: ChatThreadScrollButtonProps) {\n const { end: hasContentBelow } = useMessageScrollerScrollable();\n\n return (\n <div\n data-slot=\"chat-thread-scroll-button\"\n data-testid=\"chat-message-history-scroll-button\"\n data-hidden={!hasContentBelow}\n aria-hidden={hasContentBelow ? undefined : true}\n className={cn(\n 'absolute',\n 'px-[12px]',\n 'bottom-0',\n 'right-0 -translate-x-[12px]',\n 'md:right-auto md:left-1/2 md:-translate-x-1/2',\n '-translate-y-[12px]',\n 'flex items-center justify-center',\n 'transition-opacity duration-200 ease-in-out',\n 'data-[hidden=true]:pointer-events-none',\n 'data-[hidden=true]:opacity-0 data-[hidden=false]:opacity-100',\n className,\n )}\n >\n <MessageScrollerPrimitive.Button\n direction=\"end\"\n // Render function (not element) so Tooltip's trigger gets IconButton's forwarded ref on React 18\n render={({ inert, children: _children, ...props }) => (\n <Tooltip tooltip={tooltip} side=\"top\">\n <IconButton\n {...props}\n // React 18 doesn't know the boolean `inert` prop\n {...{ inert: inert ? '' : undefined }}\n className=\"bg-paper-elevation-2\"\n color=\"primary\"\n size=\"md\"\n tabIndex={-1}\n aria-label={tooltip}\n >\n <ChevronDownIcon />\n </IconButton>\n </Tooltip>\n )}\n />\n </div>\n );\n}\n\nexport interface ChatThreadErrorStateProps {\n children?: ReactNode;\n error?: ChatThreadError;\n className?: string;\n}\n\n/**\n * Covers the thread with an alert when its messages failed to load. Shows `children` when given,\n * otherwise the error's message.\n */\nexport function ChatThreadErrorState({ children, error, className }: ChatThreadErrorStateProps) {\n return (\n <div\n data-slot=\"chat-thread-error-state\"\n data-testid=\"chat-message-history-error-state\"\n role=\"alert\"\n aria-live=\"assertive\"\n aria-label=\"Error loading messages\"\n className={cn('absolute inset-0 flex items-center justify-center', className)}\n >\n {children || (\n <div className=\"text-text-error-main\">\n {error instanceof Error ? error.message : error || 'An error occurred'}\n </div>\n )}\n </div>\n );\n}\n\nexport { useMessageScrollerScrollable as useChatThreadScrollable };\n","import { Slot } from '@radix-ui/react-slot';\nimport type { ComponentProps, MouseEvent, ReactNode } from 'react';\n\nimport { Card, CardAction, CardDescription, CardIcon, CardTitle } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatArtifactProps extends ComponentProps<'button'> {\n /** When true, merges props onto the single child instead of rendering a `button`. */\n asChild?: boolean;\n /** Classes merged last onto the root. */\n className?: string;\n /** The artifact parts: an icon, the content with title and caption, and the actions. */\n children?: ReactNode;\n}\n\n/** A message-row control for a generated artifact: icon, title, caption and trailing actions. */\nexport function ChatArtifact({ asChild = false, className, children, ...rest }: ChatArtifactProps) {\n const Comp = asChild ? Slot : 'button';\n\n return (\n <Card asChild>\n <Comp\n {...(asChild ? {} : { type: 'button' as const })}\n data-slot=\"chat-artifact\"\n data-testid=\"chat-artifact\"\n className={cn(\n 'cursor-pointer',\n 'w-full',\n 'flex-row items-start gap-card-header-gap',\n // card-header padding plus the header's hover-area inset, flattened so asChild keeps one element\n 'py-card-header-lvl-1',\n 'px-[calc(var(--spacing-card-header-lvl-1)+var(--spacing-card-header-hover-area))]',\n 'text-left',\n // the card-header hover area, drawn as an inset layer behind the content so asChild keeps one element\n 'isolate',\n 'before:absolute before:inset-card-header-lvl-1 before:-z-10 before:pointer-events-none',\n 'before:rounded-card-header before:transition-colors',\n 'hover:before:bg-layout-accent-low-background-hover-base',\n 'active:before:bg-layout-accent-low-background-pressed-base',\n 'focus-visible:before:bg-layout-accent-low-background-hover-base',\n // an action click does not activate the row, so the row does not light up under one\n 'has-[[data-slot=chat-artifact-actions]:hover]:before:bg-transparent',\n 'outline-none',\n 'focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-focus-visible',\n className,\n )}\n {...rest}\n >\n {children}\n </Comp>\n </Card>\n );\n}\n\nexport interface ChatArtifactIconProps {\n /** Classes merged last onto the icon wrapper. */\n className?: string;\n /** The icon or thumbnail to show. */\n children?: ReactNode;\n}\n\n/** Round 32px avatar slot for a consumer-supplied icon or thumbnail. */\nexport function ChatArtifactIcon({ className, children }: ChatArtifactIconProps) {\n return (\n <CardIcon\n data-slot=\"chat-artifact-icon\"\n data-testid=\"chat-artifact-icon\"\n className={cn('text-avatar-foreground', '[&_svg]:size-4.5', className)}\n >\n {children}\n </CardIcon>\n );\n}\n\nexport interface ChatArtifactContentProps {\n /** Classes merged last onto the content element. */\n className?: string;\n /** Usually a `ChatArtifactTitle` and optional `ChatArtifactCaption`. */\n children?: ReactNode;\n}\n\n/** The text column: takes the width left beside the icon and stacks title above caption. */\nexport function ChatArtifactContent({ className, children }: ChatArtifactContentProps) {\n return (\n <div\n data-slot=\"chat-artifact-content\"\n data-testid=\"chat-artifact-content\"\n className={cn(\n 'flex-1 min-w-0',\n 'flex flex-col items-start justify-center',\n // matches the icon row height: 32px icon plus 14px margins\n 'min-h-15 py-1.5',\n 'text-left',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatArtifactTitleProps {\n /** Classes merged last onto the title element. */\n className?: string;\n /** The artifact name. */\n children?: ReactNode;\n}\n\n/** The artifact name; wraps onto more lines when it is long. */\nexport function ChatArtifactTitle({ className, children }: ChatArtifactTitleProps) {\n return (\n <CardTitle\n data-slot=\"chat-artifact-title\"\n data-testid=\"chat-artifact-title\"\n className={cn('w-full wrap-break-word truncate', 'text-layout-foreground-base', className)}\n >\n {children}\n </CardTitle>\n );\n}\n\nexport interface ChatArtifactCaptionProps {\n /** Classes merged last onto the caption element. */\n className?: string;\n /** Secondary fact under the title, e.g. source or visibility. */\n children?: ReactNode;\n}\n\n/** A quieter secondary line under the title, truncated to one line. */\nexport function ChatArtifactCaption({ className, children }: ChatArtifactCaptionProps) {\n return (\n <CardDescription\n data-slot=\"chat-artifact-caption\"\n data-testid=\"chat-artifact-caption\"\n className={cn('min-w-0 w-full truncate', 'text-layout-foreground-light', className)}\n >\n {children}\n </CardDescription>\n );\n}\n\nexport interface ChatArtifactActionsProps {\n /** Classes merged last onto the actions wrapper. */\n className?: string;\n /** Consumer-supplied controls, e.g. share and open buttons with `isSemantic={false}`. */\n children?: ReactNode;\n}\n\n/** Trailing action slot on the right of the row; clicks here do not reach the root. */\nexport function ChatArtifactActions({ className, children }: ChatArtifactActionsProps) {\n // the root is a button, so an action click must not also activate the row\n const handleClick = (event: MouseEvent<HTMLDivElement>) => event.stopPropagation();\n\n return (\n <CardAction\n role=\"group\"\n data-slot=\"chat-artifact-actions\"\n data-testid=\"chat-artifact-actions\"\n className={cn(className)}\n onClick={handleClick}\n >\n {children}\n </CardAction>\n );\n}\n","import { useState, type ComponentProps, type ReactNode } from 'react';\n\nimport { MoreHorizontalIcon, OpenInFullIcon } from '@swisper.ai/icons';\nimport {\n Menu,\n MenuProvider,\n MenuTrigger,\n Panel,\n PanelActionButton,\n PanelActionCloseButton,\n PanelBody,\n PanelContent,\n PanelFooter,\n PanelHeader,\n PanelProvider,\n PanelTitle,\n panelBodyPadding,\n type IconButtonProps,\n type TypographyProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface CanvasShellProps extends ComponentProps<'section'> {}\n\n/**\n * The `ui` Panel as the canvas beside the chat: a three-row grid where header and footer size to\n * their content and the content row takes the rest of the shell's height. It does not collapse.\n */\nexport function CanvasShell({ className, children, ...props }: CanvasShellProps) {\n return (\n <PanelProvider isCollapsible={false}>\n <Panel data-slot=\"canvas-shell\" className={className} {...props}>\n {children}\n </Panel>\n </PanelProvider>\n );\n}\n\nexport interface CanvasShellHeaderProps extends ComponentProps<'header'> {\n /** Draw the separator under the header. Set false for a header that blends into the content. */\n hasBorder?: boolean;\n}\n\n/**\n * Static top row: the title, then the panel's icon buttons.\n */\nexport function CanvasShellHeader({\n className,\n children,\n hasBorder = true,\n ...props\n}: CanvasShellHeaderProps) {\n return (\n <PanelHeader\n data-slot=\"canvas-shell-header\"\n hasBorder={hasBorder}\n className={className}\n {...props}\n >\n {children}\n </PanelHeader>\n );\n}\n\nexport interface CanvasShellTitleProps extends Omit<TypographyProps, 'variant'> {}\n\n/**\n * Name of what the canvas shows. Takes the header's free width and truncates to one line.\n */\nexport function CanvasShellTitle({ className, children, ...props }: CanvasShellTitleProps) {\n return (\n <PanelTitle data-slot=\"canvas-shell-title\" className={className} {...props}>\n {children}\n </PanelTitle>\n );\n}\n\nexport interface CanvasShellCloseTriggerProps extends IconButtonProps {}\n\n/**\n * Icon-only close button; the host decides what closing means through `onClick`.\n */\nexport function CanvasShellCloseTrigger({\n className,\n children,\n ...props\n}: CanvasShellCloseTriggerProps) {\n return (\n <PanelActionCloseButton data-slot=\"canvas-shell-close-trigger\" className={className} {...props}>\n {children}\n </PanelActionCloseButton>\n );\n}\n\nexport interface CanvasShellFullScreenTriggerProps extends Omit<\n IconButtonProps,\n 'aria-label' | 'aria-pressed'\n> {\n /** Whether the canvas currently fills the viewport; drives `aria-pressed` and the label. */\n isFullScreen: boolean;\n /** Accessible names for each state; English by default. */\n labels?: { enter?: string; exit?: string };\n}\n\n/**\n * Toggle between the canvas width and the full viewport; the host owns the state and passes\n * `isFullScreen` and `onClick`. Desktop only: on mobile the canvas already spans the screen.\n */\nexport function CanvasShellFullScreenTrigger({\n className,\n children,\n isFullScreen,\n labels,\n ...props\n}: CanvasShellFullScreenTriggerProps) {\n return (\n <PanelActionButton\n data-slot=\"canvas-shell-full-screen-trigger\"\n aria-pressed={isFullScreen}\n aria-label={\n isFullScreen ? (labels?.exit ?? 'Exit full screen') : (labels?.enter ?? 'Full screen')\n }\n className={cn('max-md:hidden', className)}\n {...props}\n >\n {children || <OpenInFullIcon />}\n </PanelActionButton>\n );\n}\n\nexport interface CanvasShellOptionsButtonProps extends Omit<IconButtonProps, 'children'> {\n /** Menu contents, typically a `DropdownMenuList` of `DropdownMenuListItem`s. */\n children: ReactNode;\n /** Classes for the dropdown panel. */\n menuClassName?: string;\n /** Called with the menu's next open state. */\n onOpenChange?: (isOpen: boolean) => void;\n}\n\n/**\n * \"More options\" button that opens a dropdown of canvas actions passed as children.\n */\nexport function CanvasShellOptionsButton({\n className,\n children,\n menuClassName,\n onOpenChange,\n ...props\n}: CanvasShellOptionsButtonProps) {\n const [isOpen, setIsOpen] = useState(false);\n\n function handleOpenChange(open: boolean) {\n setIsOpen(open);\n onOpenChange?.(open);\n }\n\n return (\n <MenuProvider modal={false} onOpenChange={handleOpenChange}>\n <MenuTrigger asChild>\n <PanelActionButton\n data-slot=\"canvas-shell-options-button\"\n isActive={isOpen}\n aria-label=\"More options\"\n className={className}\n {...props}\n >\n <MoreHorizontalIcon />\n </PanelActionButton>\n </MenuTrigger>\n <Menu className={cn('w-[200px]', menuClassName)}>{children}</Menu>\n </MenuProvider>\n );\n}\n\nexport interface CanvasShellContentProps extends ComponentProps<'div'> {\n /** Classes for the inner body, the element that pads and scrolls the children. */\n bodyClassName?: string;\n /**\n * Apply the shell's horizontal padding (`canvasShellContentPadding`).\n * Set false for edge-to-edge children that pad themselves.\n */\n hasPadding?: boolean;\n /**\n * Scroll children that overflow the region, on either axis.\n * When false, the region clips overflow: for children that scroll themselves.\n */\n hasScroll?: boolean;\n}\n\n/**\n * Horizontal padding of the content region; reuse it to align custom scroll areas with the shell.\n */\nexport const canvasShellContentPadding = panelBodyPadding;\n\n/**\n * Middle row, the only part that moves: it scrolls or clips its children inside the shell's height.\n * `className` goes to the region, `bodyClassName` to the inner element that pads and scrolls.\n */\nexport function CanvasShellContent({\n className,\n children,\n bodyClassName,\n hasPadding = true,\n hasScroll = true,\n ...props\n}: CanvasShellContentProps) {\n return (\n <PanelContent\n data-slot=\"canvas-shell-content\"\n data-has-scroll={hasScroll}\n className={className}\n {...props}\n >\n <PanelBody\n data-slot=\"canvas-shell-content-body\"\n hasPadding={hasPadding}\n hasScroll={hasScroll}\n className={bodyClassName}\n >\n {children}\n </PanelBody>\n </PanelContent>\n );\n}\n\nexport interface CanvasShellFooterProps extends ComponentProps<'footer'> {}\n\n/**\n * Static bottom row; lines its children up at the end. Stack them with `flex-col items-stretch`.\n */\nexport function CanvasShellFooter({ className, children, ...props }: CanvasShellFooterProps) {\n return (\n <PanelFooter data-slot=\"canvas-shell-footer\" className={className} {...props}>\n {children}\n </PanelFooter>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport { forwardRef, type ComponentProps, type ReactNode } from 'react';\n\nimport { useChatContext } from '@/contexts';\n\ninterface NewChatTriggerProps extends ComponentProps<'button'> {\n asChild?: boolean;\n children: ReactNode;\n}\n\nexport const NewChatTrigger = forwardRef<HTMLButtonElement, NewChatTriggerProps>(\n ({ asChild = false, children, onClick, ...rest }, ref) => {\n const { goToNewChat } = useChatContext();\n const Component = asChild ? Slot : 'button';\n\n function handleClick(event: React.MouseEvent<HTMLButtonElement>) {\n onClick?.(event);\n goToNewChat();\n }\n\n return (\n <Component ref={ref} data-testid=\"new-chat-trigger\" onClick={handleClick} {...rest}>\n {children}\n </Component>\n );\n },\n);\n\nNewChatTrigger.displayName = 'NewChatTrigger';\n","import { AnimatePresence, motion } from 'motion/react';\nimport React, { forwardRef, type ComponentProps, type ReactNode, useMemo } from 'react';\n\nimport {\n Collapsible,\n CollapsibleChevron,\n CollapsibleContent,\n CollapsibleTrigger,\n Typography,\n type CollapsibleProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatThinkingProcessProps extends Omit<CollapsibleProps, 'isDisabled'> {\n children: ReactNode;\n className?: string;\n /** The model is still thinking: the label shimmers and, while collapsed, the last step is previewed. */\n isStreaming?: boolean;\n}\n\n/**\n * Collapsible disclosure of the assistant's reasoning or tool steps. Collapsed by default; exposes\n * `data-state` (`open` / `closed`) and `data-streaming` for its parts to style from.\n */\nexport const ChatThinkingProcess = forwardRef<HTMLDivElement, ChatThinkingProcessProps>(\n function ChatThinkingProcess(\n { children, className, defaultOpen = false, isStreaming = false, ...rest },\n ref,\n ) {\n return (\n <Collapsible defaultOpen={defaultOpen} asChild {...rest}>\n <div\n ref={ref}\n data-slot=\"chat-thinking-process\"\n data-testid=\"chat-thinking-process\"\n data-streaming={isStreaming}\n className={cn('group/thinking-process', 'flex flex-col', className)}\n >\n {children}\n </div>\n </Collapsible>\n );\n },\n);\n\nChatThinkingProcess.displayName = 'ChatThinkingProcess';\n\nexport interface ChatThinkingProcessTriggerProps extends ComponentProps<'button'> {\n children: ReactNode;\n className?: string;\n isLoading?: boolean;\n}\n\n/** The button that expands and collapses the steps; holds the icon, the label and the arrow. */\nexport function ChatThinkingProcessTrigger({\n children,\n className,\n ...rest\n}: ChatThinkingProcessTriggerProps) {\n return (\n <CollapsibleTrigger\n data-slot=\"chat-thinking-process-trigger\"\n data-testid=\"chat-thinking-process-trigger\"\n className={cn('flex w-full items-center gap-4', 'cursor-pointer text-left', className)}\n {...rest}\n >\n {children}\n\n <style>\n {`\n @keyframes shimmer {\n 100% {\n mask-position: left;\n }\n }\n `}\n </style>\n </CollapsibleTrigger>\n );\n}\n\nexport interface ChatThinkingProcessTriggerIconProps extends ComponentProps<'span'> {\n children: ReactNode;\n className?: string;\n}\n\n/** The icon before the label: what kind of work the process is. */\nexport function ChatThinkingProcessTriggerIcon({\n children,\n className,\n ...rest\n}: ChatThinkingProcessTriggerIconProps) {\n return (\n <span\n data-slot=\"chat-thinking-process-trigger-icon\"\n data-testid=\"chat-thinking-process-trigger-icon\"\n className={cn('inline-flex shrink-0 items-center justify-center', className)}\n {...rest}\n >\n {children}\n </span>\n );\n}\n\nexport interface ChatThinkingProcessTriggerLabelProps extends ComponentProps<'span'> {\n children: ReactNode;\n className?: string;\n}\n\n/** The trigger's text and accessible name; shimmers while the root is streaming. */\nexport function ChatThinkingProcessTriggerLabel({\n children,\n className,\n ...rest\n}: ChatThinkingProcessTriggerLabelProps) {\n return (\n <Typography\n asChild\n variant=\"body-sm\"\n data-slot=\"chat-thinking-process-trigger-label\"\n data-testid=\"chat-thinking-process-trigger-label\"\n className={cn(\n 'text-text-secondary',\n 'font-semibold',\n 'group-data-[streaming=true]/thinking-process:mask-[linear-gradient(-60deg,#000_30%,rgba(0,0,0,0.2),#192029_70%)]',\n 'group-data-[streaming=true]/thinking-process:mask-size-[300%_100%]',\n 'group-data-[streaming=true]/thinking-process:mask-right',\n 'group-data-[streaming=true]/thinking-process:animate-[shimmer_3.2s_infinite]',\n className,\n )}\n >\n <span {...rest}>{children}</span>\n </Typography>\n );\n}\n\nexport interface ChatThinkingProcessTriggerArrowProps extends ComponentProps<'span'> {\n className?: string;\n}\n\n/** The chevron after the label; points up while the steps are expanded. Hidden from assistive tech. */\nexport function ChatThinkingProcessTriggerArrow({\n className,\n ...rest\n}: ChatThinkingProcessTriggerArrowProps) {\n return (\n <CollapsibleChevron\n data-slot=\"chat-thinking-process-trigger-arrow\"\n data-testid=\"chat-thinking-process-trigger-arrow\"\n className={cn('items-center justify-center text-text-secondary', 'size-16', className)}\n {...rest}\n />\n );\n}\n\nexport interface ChatThinkingProcessContentProps extends ComponentProps<'div'> {\n children: ReactNode;\n /** Classes for the outer wrapper, which holds the preview and the list of steps. */\n className?: string;\n /** Classes for the expanded list of steps. */\n itemsClassName?: string;\n /** Classes for each timeline row: the marker column and the step beside it. */\n rowClassName?: string;\n /** Classes for the dot that marks each step. */\n markerClassName?: string;\n /** Classes for the line that joins a step's dot to the next one. */\n connectorClassName?: string;\n /** Classes for the faded preview of the last step. */\n previewClassName?: string;\n /** Previews the last step while the root is streaming and collapsed. */\n hasLastMessagePreview?: boolean;\n}\n\n/**\n * The steps. Each child becomes a timeline row in the expanded list, and the last child is\n * previewed while the root is streaming and collapsed.\n */\nexport function ChatThinkingProcessContent({\n children,\n className,\n itemsClassName,\n rowClassName,\n markerClassName,\n connectorClassName,\n previewClassName,\n hasLastMessagePreview = true,\n ...rest\n}: ChatThinkingProcessContentProps) {\n const { lastItemContent, lastItemIndex } = useMemo(() => {\n const childrenArray = React.Children.toArray(children);\n const lastItemContent = childrenArray.at(-1);\n const lastItemIndex = String(childrenArray.length);\n\n return { lastItemContent, lastItemIndex };\n }, [children]);\n\n return (\n <div\n data-slot=\"chat-thinking-process-content\"\n data-testid=\"chat-thinking-process-content\"\n data-preview={hasLastMessagePreview}\n className={cn('pt-8', className)}\n >\n {hasLastMessagePreview && lastItemContent && (\n <AnimatePresence mode=\"wait\">\n <ChatThinkingProcessContentPreview contentId={lastItemIndex} className={previewClassName}>\n {lastItemContent}\n </ChatThinkingProcessContentPreview>\n </AnimatePresence>\n )}\n\n <CollapsibleContent\n data-slot=\"chat-thinking-process-content-items\"\n data-testid=\"chat-thinking-process-content-items\"\n className={cn('flex flex-col', itemsClassName)}\n {...rest}\n >\n {React.Children.map(children, (child) => {\n return (\n <div\n data-slot=\"chat-thinking-process-content-row\"\n className={cn(\n 'relative flex gap-8 text-text-secondary text-sm last:pb-0',\n 'pl-8',\n 'last:[&>div:first-child>span:last-child]:hidden',\n rowClassName,\n )}\n >\n <div\n className=\"relative flex w-8 shrink-0 flex-col items-center self-stretch\"\n aria-hidden\n >\n <span\n data-slot=\"chat-thinking-process-content-marker\"\n className={cn(\n 'mt-[7px] size-[6px] shrink-0 rounded-full bg-text-secondary',\n markerClassName,\n )}\n />\n <span\n data-slot=\"chat-thinking-process-content-connector\"\n className={cn(\n 'absolute top-[16px] bottom-[-4px] left-1/2 w-px -translate-x-1/2 bg-component-divider',\n connectorClassName,\n )}\n />\n </div>\n\n <div className=\"min-w-0 flex-1 pb-8\">{child}</div>\n </div>\n );\n })}\n </CollapsibleContent>\n </div>\n );\n}\n\nexport interface ChatThinkingProcessContentPreviewProps {\n children: ReactNode;\n className?: string;\n contentId: string;\n}\n\nexport function ChatThinkingProcessContentPreview({\n children,\n className,\n contentId,\n}: ChatThinkingProcessContentPreviewProps) {\n return (\n <motion.div\n key={contentId}\n data-slot=\"chat-thinking-process-content-preview\"\n data-testid=\"chat-thinking-process-content-preview\"\n initial={{ opacity: 0 }}\n animate={{ opacity: 0.7 }}\n exit={{ opacity: 0 }}\n transition={{ duration: 0.25, ease: 'easeOut' }}\n className={cn(\n 'group-data-[streaming=false]/thinking-process:hidden',\n 'group-data-[state=open]/thinking-process:hidden',\n 'px-4',\n className,\n )}\n >\n {children}\n </motion.div>\n );\n}\n\nexport interface ChatThinkingProcessContentItemProps extends ComponentProps<'div'> {\n children: ReactNode;\n className?: string;\n}\n\n/** One step of the process: text, or any node such as streamed Markdown. */\nexport function ChatThinkingProcessContentItem({\n children,\n className,\n ...rest\n}: ChatThinkingProcessContentItemProps) {\n return (\n <div\n data-slot=\"chat-thinking-process-content-item\"\n data-testid=\"chat-thinking-process-content-item\"\n className={cn('text-text-secondary text-sm', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","// EmptyState moved to @swisper.ai/ui, so apps without the chat surface can use it too. These aliases\n// keep existing `@swisper.ai/web-chat-ui` imports compiling; the editor strikes them through.\n// A plain `export { … } from` would work at runtime but carries no @deprecated tag per symbol.\n// Kept as a flat file, not a component folder, so the echo-design reference build doesn't list\n// EmptyState under web-chat-ui as well.\nimport {\n EmptyState as UiEmptyState,\n EmptyStateActionRow as UiEmptyStateActionRow,\n EmptyStateDescription as UiEmptyStateDescription,\n EmptyStateIcon as UiEmptyStateIcon,\n EmptyStateTitle as UiEmptyStateTitle,\n type EmptyStateActionRowProps as UiEmptyStateActionRowProps,\n type EmptyStateDescriptionProps as UiEmptyStateDescriptionProps,\n type EmptyStateIconProps as UiEmptyStateIconProps,\n type EmptyStateProps as UiEmptyStateProps,\n type EmptyStateTitleProps as UiEmptyStateTitleProps,\n} from '@swisper.ai/ui';\n\n/** @deprecated Import `EmptyState` from `@swisper.ai/ui`. */\nexport const EmptyState = UiEmptyState;\n/** @deprecated Import `EmptyStateIcon` from `@swisper.ai/ui`. */\nexport const EmptyStateIcon = UiEmptyStateIcon;\n/** @deprecated Import `EmptyStateTitle` from `@swisper.ai/ui`. */\nexport const EmptyStateTitle = UiEmptyStateTitle;\n/** @deprecated Import `EmptyStateDescription` from `@swisper.ai/ui`. */\nexport const EmptyStateDescription = UiEmptyStateDescription;\n/** @deprecated Import `EmptyStateActionRow` from `@swisper.ai/ui`. */\nexport const EmptyStateActionRow = UiEmptyStateActionRow;\n\n/** @deprecated Import `EmptyStateProps` from `@swisper.ai/ui`. */\nexport type EmptyStateProps = UiEmptyStateProps;\n/** @deprecated Import `EmptyStateIconProps` from `@swisper.ai/ui`. */\nexport type EmptyStateIconProps = UiEmptyStateIconProps;\n/** @deprecated Import `EmptyStateTitleProps` from `@swisper.ai/ui`. */\nexport type EmptyStateTitleProps = UiEmptyStateTitleProps;\n/** @deprecated Import `EmptyStateDescriptionProps` from `@swisper.ai/ui`. */\nexport type EmptyStateDescriptionProps = UiEmptyStateDescriptionProps;\n/** @deprecated Import `EmptyStateActionRowProps` from `@swisper.ai/ui`. */\nexport type EmptyStateActionRowProps = UiEmptyStateActionRowProps;\n","import type { EditorThemeClasses } from 'lexical';\n\nexport const defaultEditorTheme: EditorThemeClasses = {\n paragraph: 'editor-paragraph',\n text: {\n bold: 'editor-text-bold',\n italic: 'editor-text-italic',\n underline: 'editor-text-underline',\n },\n} as const;\n","import {\n DecoratorNode,\n type DOMConversionMap,\n type DOMExportOutput,\n type LexicalNode,\n type NodeKey,\n type SerializedLexicalNode,\n type Spread,\n} from 'lexical';\nimport type { JSX } from 'react';\n\nexport type SerializedImageNode = Spread<{ src: string; altText: string }, SerializedLexicalNode>;\n\nexport class ImageNode extends DecoratorNode<JSX.Element> {\n __src: string;\n __altText: string;\n\n static override getType(): string {\n return 'image';\n }\n\n static override clone(node: ImageNode): ImageNode {\n return new ImageNode(node.__src, node.__altText, node.__key);\n }\n\n constructor(src: string, altText: string, key?: NodeKey) {\n super(key);\n this.__src = src;\n this.__altText = altText;\n }\n\n override createDOM(): HTMLElement {\n const span = document.createElement('span');\n span.style.display = 'inline-block';\n return span;\n }\n\n override updateDOM(): false {\n return false;\n }\n\n override decorate(): JSX.Element {\n return (\n <img\n src={this.__src}\n alt={this.__altText}\n style={{ maxWidth: '100%', display: 'block' }}\n draggable={false}\n />\n );\n }\n\n override exportDOM(): DOMExportOutput {\n const img = document.createElement('img');\n img.setAttribute('src', this.__src);\n img.setAttribute('alt', this.__altText);\n img.style.maxWidth = '100%';\n return { element: img };\n }\n\n static override importDOM(): DOMConversionMap | null {\n return {\n img: () => ({\n conversion: (domNode: HTMLElement) => {\n const src = domNode.getAttribute('src') || '';\n const alt = domNode.getAttribute('alt') || '';\n if (!src) return null;\n return { node: $createImageNode(src, alt) };\n },\n priority: 0,\n }),\n };\n }\n\n override exportJSON(): SerializedImageNode {\n return {\n ...super.exportJSON(),\n src: this.__src,\n altText: this.__altText,\n type: 'image',\n version: 1,\n };\n }\n\n static override importJSON(json: SerializedImageNode): ImageNode {\n return $createImageNode(json.src, json.altText);\n }\n\n override isInline(): boolean {\n return false;\n }\n}\n\nexport function $createImageNode(src: string, altText: string): ImageNode {\n return new ImageNode(src, altText);\n}\n\nexport function $isImageNode(node: LexicalNode | null | undefined): node is ImageNode {\n return node instanceof ImageNode;\n}\n","import {\n TRANSFORMERS,\n type TextMatchTransformer,\n type ElementTransformer,\n} from '@lexical/markdown';\nimport { $isParagraphNode, $isTextNode, $createTextNode, type ElementFormatType } from 'lexical';\n\nimport { ImageNode, $createImageNode, $isImageNode } from './nodes/image-node';\n\nexport { TRANSFORMERS as MARKDOWN_TRANSFORMERS };\n\nexport function extractFontStyles(style: string) {\n const fontSizeRegex = /font-size\\s*:\\s*([^;]+)/i;\n const fontFamilyRegex = /font-family\\s*:\\s*([^;]+)/i;\n const colorRegex = /(?<![\\w-])color\\s*:\\s*([^;]+)/i;\n\n const fontSizeMatch = fontSizeRegex.exec(style);\n const fontFamilyMatch = fontFamilyRegex.exec(style);\n const colorMatch = colorRegex.exec(style);\n\n return {\n fontSize: fontSizeMatch ? fontSizeMatch[1].trim() : null,\n fontFamily: fontFamilyMatch ? fontFamilyMatch[1].trim() : null,\n color: colorMatch ? colorMatch[1].trim() : null,\n };\n}\n\nexport const FONT_STYLE_EXPORT: TextMatchTransformer = {\n type: 'text-match',\n trigger: '', // not used for export\n regExp: /./, // not used for export\n importRegExp: /./, // not used for export\n dependencies: [],\n\n export: (node) => {\n if (!$isTextNode(node)) return null;\n\n const style = node.getStyle() ?? '';\n const text = node.getTextContent();\n const fontStyles = extractFontStyles(style);\n\n if (fontStyles.fontSize || fontStyles.fontFamily || fontStyles.color) {\n let styleStr = '';\n\n if (fontStyles.fontSize) {\n styleStr += `font-size: ${fontStyles.fontSize};`;\n }\n\n if (fontStyles.fontFamily) {\n styleStr += `font-family: ${fontStyles.fontFamily};`;\n }\n\n if (fontStyles.color) {\n styleStr += `color: ${fontStyles.color};`;\n }\n\n return `<span style=\"${styleStr}\">${text}</span>`;\n }\n\n return null;\n },\n};\n\nexport const FONT_STYLE_IMPORT: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /<span\\s+style=\"([^\"]+)\">(.+?)<\\/span>/,\n importRegExp: /<span\\s+style=\"([^\"]+)\">(.+?)<\\/span>/,\n dependencies: [],\n replace: (textNode, match) => {\n const [, style, content] = match;\n const newNode = $createTextNode(content);\n\n // Preserve existing format (bold/underline) from the original node\n newNode.setFormat(textNode.getFormat());\n newNode.setStyle(style);\n textNode.replace(newNode);\n return newNode;\n },\n};\n\nexport const UNDERLINE_TRANSFORMER: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /<ins>(.*?)<\\/ins>/,\n importRegExp: /<ins>(.*?)<\\/ins>/,\n dependencies: [],\n replace: (textNode, match) => {\n const newNode = $createTextNode(match[1]);\n newNode.setFormat(textNode.getFormat());\n if (!newNode.hasFormat('underline')) {\n newNode.toggleFormat('underline');\n }\n textNode.replace(newNode);\n return newNode;\n },\n export: (node) => {\n if (!$isTextNode(node) || !node.hasFormat('underline')) return null;\n return `<ins>${node.getTextContent()}</ins>`;\n },\n};\n\nconst getAlignment = (style: string) => {\n const alignmentRegex = /text-align:\\s*(\\w+)/i;\n const alignmentMatch = alignmentRegex.exec(style);\n return alignmentMatch ? (alignmentMatch[1].trim() as ElementFormatType) : null;\n};\n\nexport const ALIGNMENT_TRANSFORMER: ElementTransformer = {\n type: 'element',\n dependencies: [],\n regExp: /<div\\s+style=\"([^\"]+)\">(.*?)<\\/div>/,\n replace: (parentNode, children, match) => {\n const alignment = getAlignment(match[1]);\n if (!alignment) return false;\n\n if (!match[2]) return;\n\n const child = children[0];\n if ($isTextNode(child)) {\n child.setTextContent(match[2]);\n }\n\n parentNode.setFormat(alignment);\n parentNode.append(...children);\n },\n export: (node, exportChildren) => {\n if (!$isParagraphNode(node)) return null;\n const alignment = node.getFormatType();\n if (!alignment || alignment === 'left') return null;\n\n const children = exportChildren(node);\n return `<div style=\"text-align: ${alignment}\">${children}</div>`;\n },\n};\n\nexport const IMAGE_EXPORT_TRANSFORMER: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /./,\n importRegExp: /./,\n dependencies: [ImageNode],\n export: (node) => {\n if (!$isImageNode(node)) return null;\n return `<img src=\"${node.__src}\" alt=\"${node.__altText}\" />`;\n },\n};\n\nexport const IMAGE_IMPORT_TRANSFORMER: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /<img\\s+src=\"([^\"]+)\"\\s+alt=\"([^\"]*)\"[^>]*\\/?>/,\n importRegExp: /<img\\s+src=\"([^\"]+)\"\\s+alt=\"([^\"]*)\"[^>]*\\/?>/,\n dependencies: [ImageNode],\n replace: (textNode, match) => {\n const [, src, alt] = match;\n const imageNode = $createImageNode(src, alt);\n textNode.replace(imageNode);\n },\n};\n\nexport const EXPORT_TRANSFORMERS = [\n ...TRANSFORMERS,\n FONT_STYLE_EXPORT,\n UNDERLINE_TRANSFORMER,\n ALIGNMENT_TRANSFORMER,\n IMAGE_EXPORT_TRANSFORMER,\n];\nexport const IMPORT_TRANSFORMERS = [\n ...TRANSFORMERS,\n FONT_STYLE_IMPORT,\n UNDERLINE_TRANSFORMER,\n ALIGNMENT_TRANSFORMER,\n IMAGE_IMPORT_TRANSFORMER,\n];\n","import { $createListNode, $createListItemNode, ListNode, ListItemNode } from '@lexical/list';\nimport { $createHeadingNode, HeadingNode } from '@lexical/rich-text';\nimport { setNodeIndentFromDOM, isHTMLElement, $isTextNode } from 'lexical';\nimport type {\n DOMConversionMap,\n DOMConversionOutput,\n DOMExportOutput,\n DOMExportOutputMap,\n LexicalEditor,\n LexicalNode,\n ElementNode,\n} from 'lexical';\n\nimport { extractFontStyles } from './transformers';\n\nfunction convertHeadingElement(element: HTMLElement): DOMConversionOutput | null {\n const nodeName = element.nodeName.toLowerCase();\n if (\n nodeName !== 'h1' &&\n nodeName !== 'h2' &&\n nodeName !== 'h3' &&\n nodeName !== 'h4' &&\n nodeName !== 'h5' &&\n nodeName !== 'h6'\n ) {\n return null;\n }\n const node = $createHeadingNode(nodeName);\n const style = element.getAttribute('style') ?? '';\n node.setStyle(style);\n if (element.style) {\n const align = element.style.textAlign;\n if (\n align === 'left' ||\n align === 'right' ||\n align === 'center' ||\n align === 'justify' ||\n align === 'start' ||\n align === 'end'\n ) {\n node.setFormat(align);\n }\n setNodeIndentFromDOM(element, node);\n }\n return { node };\n}\n\nfunction isDomChecklist(domNode: HTMLElement): boolean {\n if (\n domNode.getAttribute('__lexicallisttype') === 'check' ||\n domNode.classList.contains('contains-task-list')\n ) {\n return true;\n }\n for (const child of domNode.childNodes) {\n if (isHTMLElement(child) && child.hasAttribute('aria-checked')) {\n return true;\n }\n }\n return false;\n}\n\nfunction convertListElement(domNode: HTMLElement): DOMConversionOutput | null {\n const nodeName = domNode.nodeName.toLowerCase();\n let node = null;\n if (nodeName === 'ol') {\n const start = (domNode as HTMLOListElement).start;\n node = $createListNode('number', start);\n } else if (nodeName === 'ul') {\n if (isDomChecklist(domNode)) {\n node = $createListNode('check');\n } else {\n node = $createListNode('bullet');\n }\n }\n if (!node) return null;\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n return { node };\n}\n\nfunction convertListItemElement(domNode: HTMLElement): DOMConversionOutput | null {\n const isGitHubCheckList = domNode.classList.contains('task-list-item');\n if (isGitHubCheckList) {\n for (const child of domNode.children) {\n if (child.tagName === 'INPUT') {\n const input = child as HTMLInputElement;\n const isCheckbox = input.getAttribute('type') === 'checkbox';\n if (isCheckbox) {\n const checked = input.hasAttribute('checked');\n const node = $createListItemNode(checked);\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n return { node };\n }\n }\n }\n }\n const ariaCheckedAttr = domNode.getAttribute('aria-checked');\n const checked =\n ariaCheckedAttr === 'true' ? true : ariaCheckedAttr === 'false' ? false : undefined;\n const node = $createListItemNode(checked);\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n return { node };\n}\n\nconst IMPORT_PRIORITY = 4;\n\nfunction convertSpanElementWithStyles(domNode: HTMLElement): DOMConversionOutput | null {\n const styleAttr = domNode.getAttribute('style') ?? '';\n const { color, fontSize, fontFamily } = extractFontStyles(styleAttr);\n\n if (!color && !fontSize && !fontFamily) {\n return null;\n }\n\n const domStyle = domNode.style;\n\n return {\n forChild: (lexicalNode) => {\n if (!$isTextNode(lexicalNode)) return lexicalNode;\n\n // Replicate Lexical's default text-format handling from applyTextFormatFromStyle\n const fontWeight = domStyle.fontWeight;\n const textDecoration = (domStyle.textDecoration || '').split(' ');\n if ((fontWeight === '700' || fontWeight === 'bold') && !lexicalNode.hasFormat('bold')) {\n lexicalNode.toggleFormat('bold');\n }\n if (textDecoration.includes('line-through') && !lexicalNode.hasFormat('strikethrough')) {\n lexicalNode.toggleFormat('strikethrough');\n }\n if (domStyle.fontStyle === 'italic' && !lexicalNode.hasFormat('italic')) {\n lexicalNode.toggleFormat('italic');\n }\n if (textDecoration.includes('underline') && !lexicalNode.hasFormat('underline')) {\n lexicalNode.toggleFormat('underline');\n }\n if (domStyle.verticalAlign === 'sub' && !lexicalNode.hasFormat('subscript')) {\n lexicalNode.toggleFormat('subscript');\n }\n if (domStyle.verticalAlign === 'super' && !lexicalNode.hasFormat('superscript')) {\n lexicalNode.toggleFormat('superscript');\n }\n\n // Apply inline CSS styles (color, font-size, font-family)\n let styleStr = '';\n if (fontSize) styleStr += `font-size: ${fontSize};`;\n if (fontFamily) styleStr += `font-family: ${fontFamily};`;\n if (color) styleStr += `color: ${color};`;\n lexicalNode.setStyle(styleStr);\n\n return lexicalNode;\n },\n node: null,\n };\n}\n\nexport const HTML_IMPORT_CONFIG: DOMConversionMap = {\n h1: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h2: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h3: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h4: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h5: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h6: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n ul: () => ({ conversion: convertListElement, priority: IMPORT_PRIORITY }),\n ol: () => ({ conversion: convertListElement, priority: IMPORT_PRIORITY }),\n li: () => ({ conversion: convertListItemElement, priority: IMPORT_PRIORITY }),\n span: () => ({ conversion: convertSpanElementWithStyles, priority: IMPORT_PRIORITY }),\n};\n\ntype NodeExportDOMFn = (editor: LexicalEditor) => DOMExportOutput;\n\nfunction wrapExportWithStyle(OriginalClass: {\n prototype: { exportDOM: NodeExportDOMFn };\n}): (editor: LexicalEditor, target: LexicalNode) => DOMExportOutput {\n return (editor: LexicalEditor, target: LexicalNode) => {\n const result = OriginalClass.prototype.exportDOM.call(target, editor);\n const elementNode = target as ElementNode;\n const style = elementNode.getStyle();\n if (result.element && style) {\n (result.element as HTMLElement).setAttribute('style', style);\n }\n return result;\n };\n}\n\nexport const HTML_EXPORT_CONFIG: DOMExportOutputMap = new Map<\n unknown,\n (editor: LexicalEditor, target: LexicalNode) => DOMExportOutput\n>([\n [HeadingNode, wrapExportWithStyle(HeadingNode)],\n [ListNode, wrapExportWithStyle(ListNode)],\n [ListItemNode, wrapExportWithStyle(ListItemNode)],\n]) as DOMExportOutputMap;\n","import {\n $createParagraphNode,\n $isTextNode,\n ElementNode,\n setNodeIndentFromDOM,\n type DOMConversionMap,\n type DOMConversionOutput,\n type EditorConfig,\n type LexicalUpdateJSON,\n type RangeSelection,\n type SerializedElementNode,\n type Spread,\n} from 'lexical';\n\nexport type SerializedDivBlockNode = Spread<\n {\n style?: string;\n },\n SerializedElementNode\n>;\n\nexport class DivBlockNode extends ElementNode {\n static override getType(): string {\n return 'div-block';\n }\n\n static override clone(node: DivBlockNode): DivBlockNode {\n return new DivBlockNode(node.__key);\n }\n\n override createDOM(_config: EditorConfig): HTMLElement {\n const div = document.createElement('div');\n const style = this.getStyle();\n if (style) {\n div.style.cssText = style;\n }\n return div;\n }\n\n override updateDOM(prevNode: DivBlockNode, dom: HTMLElement): boolean {\n const prevStyle = prevNode.getStyle();\n const nextStyle = this.getStyle();\n if (prevStyle !== nextStyle) {\n dom.style.cssText = nextStyle;\n return true;\n }\n return false;\n }\n\n static override importDOM(): DOMConversionMap | null {\n return {\n div: () => ({\n conversion: convertDivElement,\n priority: 4,\n }),\n };\n }\n\n override exportJSON(): SerializedDivBlockNode {\n const json = super.exportJSON();\n const style = this.getStyle();\n if (style) {\n return { ...json, style };\n }\n return json;\n }\n\n static override importJSON(serializedNode: SerializedDivBlockNode): DivBlockNode {\n const node = $createDivBlockNode().updateFromJSON(serializedNode);\n if (serializedNode.style !== undefined) {\n node.setStyle(serializedNode.style);\n }\n return node;\n }\n\n override updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedDivBlockNode>): this {\n const updated = super.updateFromJSON(serializedNode);\n if (serializedNode.style !== undefined) {\n updated.setStyle(serializedNode.style);\n }\n return updated;\n }\n\n override collapseAtStart(_selection: RangeSelection): boolean {\n const children = this.getChildren();\n const isEmptyOrBlank =\n children.length === 0 ||\n ($isTextNode(children[0]) && children[0].getTextContent().trim() === '');\n\n if (isEmptyOrBlank) {\n const nextSibling = this.getNextSibling();\n if (nextSibling !== null) {\n this.selectNext();\n this.remove();\n return true;\n }\n const prevSibling = this.getPreviousSibling();\n if (prevSibling !== null) {\n this.selectPrevious();\n this.remove();\n return true;\n }\n } else {\n const paragraph = $createParagraphNode();\n paragraph.setFormat(this.getFormatType());\n paragraph.setStyle(this.getStyle());\n paragraph.setIndent(this.getIndent());\n paragraph.setDirection(this.getDirection());\n children.forEach((child) => paragraph.append(child));\n this.replace(paragraph);\n return true;\n }\n\n return false;\n }\n}\n\nfunction convertDivElement(domNode: HTMLElement): DOMConversionOutput | null {\n const node = $createDivBlockNode();\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n if (domNode.style) {\n const align = domNode.style.textAlign;\n if (\n align === 'left' ||\n align === 'right' ||\n align === 'center' ||\n align === 'justify' ||\n align === 'start' ||\n align === 'end'\n ) {\n node.setFormat(align);\n }\n setNodeIndentFromDOM(domNode, node);\n }\n return { node };\n}\n\nexport function $createDivBlockNode(): DivBlockNode {\n return new DivBlockNode();\n}\n\nexport function $isDivBlockNode(node: unknown): node is DivBlockNode {\n return node instanceof DivBlockNode;\n}\n","import { $generateHtmlFromNodes } from '@lexical/html';\nimport { $convertToMarkdownString } from '@lexical/markdown';\nimport { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';\nimport { type EditorState, type LexicalEditor } from 'lexical';\nimport { type MutableRefObject, useCallback } from 'react';\n\nimport { EXPORT_TRANSFORMERS } from '../transformers';\n\nexport { MARKDOWN_TRANSFORMERS } from '../transformers';\n\n/** How many emitted values to remember; a parent that never echoes them back must not grow the list. */\nconst MAX_EMITTED_VALUES = 50;\n\ninterface ValuePluginProps {\n onChange?: (value: string) => void;\n source?: 'html' | 'markdown';\n /** Receives every value given to `onChange`, so `ControlledValuePlugin` can tell an echo of one. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ValuePlugin({ onChange, source = 'markdown', emittedValuesRef }: ValuePluginProps) {\n const handleChange = useCallback(\n (editorState: EditorState, editor: LexicalEditor, tags: Set<string>) => {\n if (tags.has('focus')) {\n return;\n }\n\n if (!onChange) {\n return;\n }\n\n try {\n editorState.read(() => {\n const value =\n source === 'html'\n ? $generateHtmlFromNodes(editor)\n : $convertToMarkdownString(EXPORT_TRANSFORMERS);\n\n if (emittedValuesRef) {\n emittedValuesRef.current.push(value);\n emittedValuesRef.current.splice(\n 0,\n emittedValuesRef.current.length - MAX_EMITTED_VALUES,\n );\n }\n\n onChange(value);\n });\n } catch (error) {\n if (import.meta.env.DEV) {\n console.error('ValuePlugin error:', error);\n }\n }\n },\n [onChange, source, emittedValuesRef],\n );\n\n return <OnChangePlugin onChange={handleChange} />;\n}\n","import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';\nimport { $getSelection } from 'lexical';\nimport { useCallback } from 'react';\n\nexport function useRichTextAreaEditor() {\n const [editor] = useLexicalComposerContext();\n\n return editor;\n}\n\nexport function useRichTextAreaSelectedText() {\n const [editor] = useLexicalComposerContext();\n\n return useCallback(() => {\n let selectedText = '';\n\n editor.getEditorState().read(() => {\n const selection = $getSelection();\n selectedText = selection?.getTextContent() ?? '';\n });\n\n return selectedText;\n }, [editor]);\n}\n","import { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\ninterface DisabledPluginProps {\n isDisabled?: boolean;\n}\n\nexport function DisabledPlugin({ isDisabled }: DisabledPluginProps) {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n editor.setEditable(!isDisabled);\n }, [editor, isDisabled]);\n\n return null;\n}\n","import { EditorRefPlugin } from '@lexical/react/LexicalEditorRefPlugin';\nimport { type LexicalEditor } from 'lexical';\nimport { useRef, useImperativeHandle, type Ref } from 'react';\n\ninterface ControlledPluginProps {\n controlledRef: Ref<HTMLInputElement | null>;\n}\n\nexport function ControlledPlugin({ controlledRef }: ControlledPluginProps) {\n const editorRef = useRef<LexicalEditor | null>(null);\n\n useImperativeHandle(controlledRef, (): HTMLInputElement | null => {\n return {\n focus: () => {\n Promise.resolve().then(() => {\n editorRef.current?.focus();\n });\n },\n } as unknown as HTMLInputElement;\n }, []);\n\n return <EditorRefPlugin editorRef={editorRef} />;\n}\n","import { $generateNodesFromDOM } from '@lexical/html';\nimport { type LexicalEditor, type LexicalNode } from 'lexical';\nimport {\n $getRoot,\n $isTextNode,\n $createParagraphNode,\n $createRangeSelection,\n $setSelection,\n $selectAll,\n $getSelection,\n $isRangeSelection,\n} from 'lexical';\n\nexport function scrollRichTextAreaToBottom(editor: LexicalEditor): void {\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n rootElement.scrollTop = rootElement.scrollHeight;\n}\n\nexport function $setSelectionToEnd() {\n const root = $getRoot();\n const lastDescendant = root.getLastDescendant();\n\n if (lastDescendant && $isTextNode(lastDescendant)) {\n const selection = $createRangeSelection();\n const endOffset = lastDescendant.getTextContentSize();\n selection.anchor.set(lastDescendant.getKey(), endOffset, 'text');\n selection.focus.set(lastDescendant.getKey(), endOffset, 'text');\n $setSelection(selection);\n } else {\n $selectAll();\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const focusNode = selection.focus.getNode();\n const focusOffset = $isTextNode(focusNode) ? focusNode.getTextContentSize() : 0;\n selection.anchor.set(selection.focus.key, selection.focus.offset, selection.focus.type);\n selection.focus.set(selection.focus.key, focusOffset, selection.focus.type);\n $setSelection(selection);\n }\n }\n}\n\nfunction getHTMLNodesFromValue(editor: LexicalEditor, html: string): LexicalNode[] {\n const parser = new DOMParser();\n const dom = parser.parseFromString(html, 'text/html');\n const nodes = $generateNodesFromDOM(editor, dom);\n\n return nodes.map((node) => {\n if ($isTextNode(node)) {\n const p = $createParagraphNode();\n p.append(node);\n return p;\n }\n return node;\n });\n}\n\nexport function $replaceEditorHTMLContent(editor: LexicalEditor, html: string): void {\n const root = $getRoot();\n root.clear();\n getHTMLNodesFromValue(editor, html).forEach((node) => root.append(node));\n}\n\nexport function $replaceEditorSelectionHTMLContent(editor: LexicalEditor, html: string): void {\n const selection = $getSelection();\n const nodes = getHTMLNodesFromValue(editor, html);\n\n if ($isRangeSelection(selection)) {\n selection.insertNodes(nodes);\n } else {\n const root = $getRoot();\n root.clear();\n nodes.forEach((node) => root.append(node));\n }\n}\n","import { $generateHtmlFromNodes } from '@lexical/html';\nimport { $convertToMarkdownString, $convertFromMarkdownString } from '@lexical/markdown';\nimport { $getRoot, $addUpdateTag, SKIP_DOM_SELECTION_TAG } from 'lexical';\nimport { type MutableRefObject, useEffect, useRef } from 'react';\n\nimport { useIsResolution } from '@swisper.ai/ui';\n\nimport { useRichTextAreaEditor } from '../hooks';\nimport { EXPORT_TRANSFORMERS, IMPORT_TRANSFORMERS } from '../transformers';\nimport {\n $replaceEditorHTMLContent,\n $setSelectionToEnd,\n scrollRichTextAreaToBottom,\n} from '../utils';\n\ninterface ControlledValuePluginProps {\n value?: string;\n source?: 'html' | 'markdown';\n /** The values `ValuePlugin` gave to `onChange` that the parent has not rendered back yet. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ControlledValuePlugin({\n value,\n source = 'markdown',\n emittedValuesRef,\n}: ControlledValuePluginProps) {\n const editor = useRichTextAreaEditor();\n const previousValueRef = useRef<string | undefined>();\n const shouldScrollOnInitialValueRef = useRef(Boolean(value?.trim()));\n const isDesktop = useIsResolution('desktop');\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n\n if (value === previousValueRef.current) {\n return;\n }\n\n previousValueRef.current = value;\n\n // The parent renders back each value `onChange` gave it, and that render can land after later\n // keystrokes. Such a value is an echo of an older edit, not a change to apply: applying it\n // would drop what was typed since.\n if (emittedValuesRef && value !== undefined) {\n const echoIndex = emittedValuesRef.current.lastIndexOf(value);\n emittedValuesRef.current.splice(0, echoIndex === -1 ? Infinity : echoIndex + 1);\n if (echoIndex !== -1) {\n return;\n }\n }\n\n let currentValue = '';\n editor.getEditorState().read(() => {\n currentValue =\n source === 'html'\n ? $generateHtmlFromNodes(editor)\n : $convertToMarkdownString(EXPORT_TRANSFORMERS);\n });\n\n if (value !== undefined && value !== currentValue) {\n if (value === '') {\n editor.update(\n () => {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n if (source === 'html') {\n $getRoot().clear();\n } else {\n $convertFromMarkdownString('', IMPORT_TRANSFORMERS);\n }\n $setSelectionToEnd();\n },\n {\n discrete: true,\n },\n );\n\n Promise.resolve().then(() => {\n if (isDesktop) {\n editor.focus();\n } else {\n editor.blur();\n }\n });\n\n return;\n }\n\n editor.update(() => {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n if (source === 'html') {\n $replaceEditorHTMLContent(editor, value);\n } else {\n $convertFromMarkdownString(value, IMPORT_TRANSFORMERS);\n }\n $setSelectionToEnd();\n });\n\n if (shouldScrollOnInitialValueRef.current) {\n shouldScrollOnInitialValueRef.current = false;\n Promise.resolve().then(() => {\n requestAnimationFrame(() => scrollRichTextAreaToBottom(editor));\n });\n }\n\n if (isDesktop) {\n // Focus after update completes\n Promise.resolve().then(() => {\n editor.focus();\n });\n }\n }\n }, [editor, value, source, isDesktop, emittedValuesRef]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\ninterface BlurPluginProps {\n onBlur?: () => void;\n}\n\nexport function BlurPlugin({ onBlur }: BlurPluginProps) {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n if (!onBlur) {\n return;\n }\n\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n\n function handleBlur(event: FocusEvent) {\n if (rootElement && onBlur && !rootElement.contains(event.relatedTarget as Node)) {\n onBlur();\n }\n }\n\n rootElement.addEventListener('blur', handleBlur, true);\n\n return () => {\n rootElement.removeEventListener('blur', handleBlur, true);\n };\n }, [editor, onBlur]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\ninterface FocusPluginProps {\n onFocusChange?: (isFocused: boolean) => void;\n}\n\nexport function FocusPlugin({ onFocusChange }: FocusPluginProps) {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n if (!onFocusChange) {\n return;\n }\n\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n\n function handleFocus() {\n if (rootElement && onFocusChange) {\n onFocusChange(true);\n }\n }\n\n function handleBlur(event: FocusEvent) {\n if (rootElement && onFocusChange && !rootElement.contains(event.relatedTarget as Node)) {\n onFocusChange(false);\n }\n }\n\n rootElement.addEventListener('focus', handleFocus, true);\n rootElement.addEventListener('blur', handleBlur, true);\n\n return () => {\n rootElement.removeEventListener('focus', handleFocus, true);\n rootElement.removeEventListener('blur', handleBlur, true);\n };\n }, [editor, onFocusChange]);\n\n return null;\n}\n","import { $insertNodes, COMMAND_PRIORITY_EDITOR, createCommand, type LexicalCommand } from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\nimport { $createImageNode } from '../nodes/image-node';\n\nexport interface InsertImagePayload {\n src: string;\n altText: string;\n}\n\nexport const INSERT_IMAGE_COMMAND: LexicalCommand<InsertImagePayload> =\n createCommand('INSERT_IMAGE_COMMAND');\n\nexport const INSERT_IMAGE_EVENT_NAME = 'helvetiq:insert-image';\n\nexport class ImageAddedEvent extends CustomEvent<InsertImagePayload> {\n constructor(payload: InsertImagePayload) {\n super(INSERT_IMAGE_EVENT_NAME, { detail: payload });\n }\n}\n\nexport function ImageDropPlugin() {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n return editor.registerCommand(\n INSERT_IMAGE_COMMAND,\n (payload: InsertImagePayload) => {\n editor.update(() => {\n const imageNode = $createImageNode(payload.src, payload.altText);\n $insertNodes([imageNode]);\n });\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n useEffect(() => {\n const rootElement = editor.getRootElement();\n if (!rootElement) return;\n\n function handleInsertImage(event: Event) {\n const customEvent = event as CustomEvent<InsertImagePayload>;\n editor.dispatchCommand(INSERT_IMAGE_COMMAND, customEvent.detail);\n }\n\n document.addEventListener(INSERT_IMAGE_EVENT_NAME, handleInsertImage);\n return () => {\n document.removeEventListener(INSERT_IMAGE_EVENT_NAME, handleInsertImage);\n };\n }, [editor]);\n\n return null;\n}\n","import { $generateNodesFromDOM } from '@lexical/html';\nimport {\n $getRoot,\n $insertNodes,\n COMMAND_PRIORITY_EDITOR,\n createCommand,\n type LexicalCommand,\n} from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\nexport interface PasteHtmlPayload {\n html: string;\n}\n\nexport interface InsertHtmlPayload {\n html: string;\n}\n\nexport const PASTE_HTML_COMMAND: LexicalCommand<PasteHtmlPayload> =\n createCommand('PASTE_HTML_COMMAND');\n\nexport const INSERT_HTML_COMMAND: LexicalCommand<InsertHtmlPayload> =\n createCommand('INSERT_HTML_COMMAND');\n\nexport const PASTE_HTML_EVENT = 'helvetiq:paste-html';\nexport const INSERT_HTML_EVENT = 'helvetiq:insert-html';\n\nexport class PasteHtmlEvent extends CustomEvent<PasteHtmlPayload> {\n constructor(payload: PasteHtmlPayload) {\n super(PASTE_HTML_EVENT, { detail: payload });\n }\n}\n\nexport class InsertHtmlEvent extends CustomEvent<InsertHtmlPayload> {\n constructor(payload: InsertHtmlPayload) {\n super(INSERT_HTML_EVENT, { detail: payload });\n }\n}\n\nexport function HtmlPastePlugin() {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n return editor.registerCommand(\n PASTE_HTML_COMMAND,\n (payload: PasteHtmlPayload) => {\n editor.update(() => {\n const root = $getRoot();\n root.clear();\n\n const parser = new DOMParser();\n const dom = parser.parseFromString(payload.html, 'text/html');\n const nodes = $generateNodesFromDOM(editor, dom);\n root.append(...nodes);\n });\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n useEffect(() => {\n return editor.registerCommand(\n INSERT_HTML_COMMAND,\n (payload: InsertHtmlPayload) => {\n editor.update(() => {\n const parser = new DOMParser();\n const dom = parser.parseFromString(payload.html, 'text/html');\n const nodes = $generateNodesFromDOM(editor, dom);\n $insertNodes(nodes);\n });\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n useEffect(() => {\n const rootElement = editor.getRootElement();\n if (!rootElement) return;\n\n function handlePasteHtml(event: Event) {\n const customEvent = event as PasteHtmlEvent;\n editor.dispatchCommand(PASTE_HTML_COMMAND, customEvent.detail);\n }\n\n function handleInsertHtml(event: Event) {\n const customEvent = event as InsertHtmlEvent;\n editor.dispatchCommand(INSERT_HTML_COMMAND, customEvent.detail);\n }\n\n document.addEventListener(PASTE_HTML_EVENT, handlePasteHtml);\n document.addEventListener(INSERT_HTML_EVENT, handleInsertHtml);\n\n return () => {\n document.removeEventListener(PASTE_HTML_EVENT, handlePasteHtml);\n document.removeEventListener(INSERT_HTML_EVENT, handleInsertHtml);\n };\n }, [editor]);\n\n return null;\n}\n","import {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n COMMAND_PRIORITY_CRITICAL,\n PASTE_COMMAND,\n} from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\nexport function MarkdownPlainPastePlugin() {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n return editor.registerCommand<ClipboardEvent>(\n PASTE_COMMAND,\n (event) => {\n const { clipboardData } = event;\n\n if (!clipboardData) {\n return false;\n }\n\n const plainText = clipboardData.getData('text/plain');\n\n if (!plainText) {\n return false;\n }\n\n event.preventDefault();\n\n editor.update(() => {\n const selection = $getSelection();\n\n if ($isRangeSelection(selection)) {\n selection.insertText(plainText);\n return;\n }\n\n const root = $getRoot();\n root.clear();\n\n const lines = plainText.split(/\\r?\\n/);\n lines.forEach((line) => {\n const paragraph = $createParagraphNode();\n if (line.length > 0) {\n paragraph.append($createTextNode(line));\n }\n root.append(paragraph);\n });\n });\n\n return true;\n },\n COMMAND_PRIORITY_CRITICAL,\n );\n }, [editor]);\n\n return null;\n}\n","import { COMMAND_PRIORITY_EDITOR, createCommand, type LexicalCommand } from 'lexical';\nimport { useEffect, useRef } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\nexport const ATTACH_FILE_COMMAND: LexicalCommand<void> = createCommand('ATTACH_FILE_COMMAND');\n\ninterface FileAttachmentPluginProps {\n acceptedFiles?: string[];\n isMultiple?: boolean;\n onFileAttach?: (files: File[]) => void;\n}\n\nexport function FileAttachmentPlugin({\n acceptedFiles = [],\n isMultiple = false,\n onFileAttach,\n}: FileAttachmentPluginProps) {\n const editor = useRichTextAreaEditor();\n const inputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n return editor.registerCommand(\n ATTACH_FILE_COMMAND,\n () => {\n inputRef.current?.click();\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n function handleChange(event: React.ChangeEvent<HTMLInputElement>) {\n const files = Array.from(event.target.files ?? []);\n\n if (!isMultiple) {\n const file = files[0];\n onFileAttach?.([file]);\n } else {\n onFileAttach?.(files);\n }\n\n event.target.value = '';\n }\n\n return (\n <input\n ref={inputRef}\n type=\"file\"\n multiple={isMultiple}\n aria-hidden=\"true\"\n className=\"hidden\"\n accept={acceptedFiles?.join(',')}\n onChange={handleChange}\n />\n );\n}\n","import { forwardRef, type HTMLAttributes, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\ninterface WrapperProps extends HTMLAttributes<HTMLDivElement> {\n children?: ReactNode;\n}\n\nexport const Wrapper = forwardRef<HTMLDivElement, WrapperProps>(\n ({ className, children, ...rest }, ref) => {\n return (\n <div\n ref={ref}\n className={cn(\n 'w-full resize-none border-none outline-none bg-transparent font-[inherit] text-[inherit] flex items-center [&_.editor-paragraph]:m-0 [&_.editor-paragraph]:min-h-[26px] [&_.editor-text-bold]:font-bold [&_.editor-text-italic]:italic [&_.editor-text-underline]:underline',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n\nWrapper.displayName = 'Wrapper';\n","import { CodeNode } from '@lexical/code';\nimport { LinkNode } from '@lexical/link';\nimport { ListNode, ListItemNode } from '@lexical/list';\nimport { type InitialConfigType, LexicalComposer } from '@lexical/react/LexicalComposer';\nimport { ContentEditable } from '@lexical/react/LexicalContentEditable';\nimport { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';\nimport { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';\nimport { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';\nimport { TablePlugin } from '@lexical/react/LexicalTablePlugin';\nimport { HeadingNode, QuoteNode } from '@lexical/rich-text';\nimport { TableCellNode, TableNode, TableRowNode } from '@lexical/table';\nimport { forwardRef, useRef } from 'react';\nimport type { KeyboardEvent, Ref, ReactNode } from 'react';\n\nimport { Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { defaultEditorTheme } from './constants';\nimport { HTML_IMPORT_CONFIG, HTML_EXPORT_CONFIG } from './html-config';\nimport { DivBlockNode } from './nodes/div-block-node';\nimport { ImageNode } from './nodes/image-node';\nimport {\n ValuePlugin,\n DisabledPlugin,\n ControlledPlugin,\n ControlledValuePlugin,\n BlurPlugin,\n FocusPlugin,\n MarkdownPlainPastePlugin,\n} from './plugins';\nimport { Wrapper } from './styled';\n\nexport const INITIAL_CONFIG: InitialConfigType = {\n namespace: 'helvetiq',\n theme: defaultEditorTheme,\n editable: true,\n nodes: [\n ListNode,\n ListItemNode,\n HeadingNode,\n QuoteNode,\n CodeNode,\n LinkNode,\n ImageNode,\n DivBlockNode,\n TableNode,\n TableCellNode,\n TableRowNode,\n ],\n html: {\n import: HTML_IMPORT_CONFIG,\n export: HTML_EXPORT_CONFIG,\n },\n onError: (error: Error) => {\n console.error('Lexical error:', error);\n },\n};\n\nexport interface RichTextAreaProps {\n /** Extra Lexical plugins. They render inside the composer, after the built-in ones. */\n children?: ReactNode;\n /** Written to the editable element as `data-name`. It does not create a form field. */\n name?: string;\n /** Controlled content, in the format `source` sets. `''` clears the editor. */\n value?: string;\n /** Format of `value` and of what `onChange` returns. Defaults to `markdown`. */\n source?: 'html' | 'markdown';\n /** Classes for the editable element (`data-slot=\"rich-text-area-editable\"`), not the root. */\n className?: string;\n /** Classes for the root wrapper (`data-slot=\"rich-text-area\"`). */\n containerClassName?: string;\n /** Classes for the placeholder (`data-slot=\"rich-text-area-placeholder\"`). */\n placeholderClassName?: string;\n /** Hint shown while the editor is empty. It is not the editor's accessible name. */\n placeholder?: string;\n /** Makes the editor non-editable and dims it; the root gets `data-disabled=\"true\"`. */\n isDisabled?: boolean;\n /** Called with the whole content, serialised as `source`, on every edit. */\n onChange?: (value: string) => void;\n /** Called when focus leaves the editable element. */\n onBlur?: () => void;\n /** Runs in the capture phase, before Lexical handles the key, so it can prevent `Enter`. */\n onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;\n /** Called with `true` when the editable element gains focus and `false` when it loses it. */\n onFocusChange?: (isFocused: boolean) => void;\n}\n\nfunction RichTextAreaImpl({\n children,\n name,\n value,\n source = 'markdown',\n className,\n containerClassName,\n placeholderClassName,\n placeholder = '',\n isDisabled = false,\n onChange,\n onBlur,\n onKeyDown,\n onFocusChange,\n forwardedRef,\n ...rest\n}: RichTextAreaProps & { forwardedRef?: Ref<HTMLInputElement> }) {\n const emittedValuesRef = useRef<string[]>([]);\n\n return (\n <LexicalComposer initialConfig={INITIAL_CONFIG}>\n <Wrapper\n data-slot=\"rich-text-area\"\n data-testid=\"rich-text-area\"\n aria-disabled={isDisabled}\n data-disabled={isDisabled}\n className={cn(\n 'relative size-full overflow-hidden',\n 'data-[disabled=true]:opacity-80',\n 'data-[disabled=true]:cursor-not-allowed data-[disabled=true]:select-none',\n containerClassName,\n )}\n {...rest}\n >\n <RichTextPlugin\n contentEditable={\n <ContentEditable\n data-slot=\"rich-text-area-editable\"\n className={cn('relative inset-0 overflow-y-auto', className)}\n data-name={name}\n aria-placeholder={placeholder}\n placeholder={\n <Typography\n variant=\"body\"\n className={cn(\n 'absolute left-0 top-0',\n 'text-text-tertiary',\n 'pointer-events-none user-select-none',\n placeholderClassName,\n )}\n asChild\n >\n {/* Typography stamps its own data-slot unless it renders as its child. */}\n <p data-slot=\"rich-text-area-placeholder\">{placeholder}</p>\n </Typography>\n }\n onKeyDownCapture={onKeyDown}\n style={{\n outline: 'none',\n minHeight: '20px',\n }}\n />\n }\n ErrorBoundary={LexicalErrorBoundary}\n />\n\n <DisabledPlugin isDisabled={isDisabled} />\n <ControlledValuePlugin value={value} source={source} emittedValuesRef={emittedValuesRef} />\n <ValuePlugin onChange={onChange} source={source} emittedValuesRef={emittedValuesRef} />\n <BlurPlugin onBlur={onBlur} />\n <HistoryPlugin />\n <ControlledPlugin controlledRef={forwardedRef ?? null} />\n <FocusPlugin onFocusChange={onFocusChange} />\n <TablePlugin />\n\n {source === 'markdown' && <MarkdownPlainPastePlugin />}\n {/* external plugins */}\n {children}\n </Wrapper>\n </LexicalComposer>\n );\n}\n\n/**\n * Toolbar-less Lexical editor whose value is Markdown or HTML. The ref exposes only `focus()`.\n * Pass extra Lexical plugins as children.\n */\nexport const RichTextArea = forwardRef<HTMLInputElement, RichTextAreaProps>((props, ref) => {\n return <RichTextAreaImpl {...props} forwardedRef={ref} />;\n});\n\nRichTextArea.displayName = 'RichTextArea';\n","export const DEFAULT_FONT_FAMILY = 'Arial, sans-serif' as const;\n\nexport const FONT_FAMILY_OPTIONS = [\n { value: 'Arial, sans-serif', label: 'Arial' },\n { value: 'Verdana, sans-serif', label: 'Verdana' },\n { value: 'Tahoma, sans-serif', label: 'Tahoma' },\n { value: '\"Trebuchet MS\", sans-serif', label: 'Trebuchet MS' },\n { value: '\"Times New Roman\", serif', label: 'Times New Roman' },\n { value: 'Georgia, serif', label: 'Georgia' },\n { value: 'Garamond, serif', label: 'Garamond' },\n { value: '\"Courier New\", monospace', label: 'Courier New' },\n { value: '\"Brush Script MT\", cursive', label: 'Brush Script MT' },\n] as const;\n\nexport const DEFAULT_FONT_FAMILY_VALUE = DEFAULT_FONT_FAMILY;\n\nexport const DEFAULT_FONT_SIZE = '16';\n\nexport const FONT_SIZE_OPTIONS = [\n { label: '10', value: '10' },\n { label: '12', value: '12' },\n { label: '16', value: '16' },\n { label: '20', value: '20' },\n { label: '24', value: '24' },\n { label: '34', value: '34' },\n { label: '48', value: '48' },\n] as const;\n\nexport const ALIGNMENT_OPTIONS = ['left', 'center', 'right'] as const;\n\nexport const DEFAULT_ALIGNMENT = 'left' as const;\n\nexport const DEFAULT_TEXT_COLOR = '#000000' as const;\n","import { SelectField, type SelectFieldProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ToolbarSelectProps extends SelectFieldProps {}\n\nexport function ToolbarSelect({ className, selectItemClassName, ...rest }: ToolbarSelectProps) {\n return (\n <SelectField\n fullWidth={false}\n size=\"small\"\n className={cn(className)}\n labelClassName={'border-none group-data-[state=open]/select:bg-secondary-states-hover!'}\n // chevronIconClassName={cn('text-secondary-main')}\n // selectItemClassName={cn('[&_svg]:size-[20px]', selectItemClassName)}\n // iconClassName={cn('h-16')}\n {...rest}\n />\n );\n}\n","import { mergeRegister } from '@lexical/utils';\nimport {\n $getSelection,\n $isElementNode,\n $isRangeSelection,\n COMMAND_PRIORITY_LOW,\n FORMAT_ELEMENT_COMMAND,\n type ElementFormatType,\n SELECTION_CHANGE_COMMAND,\n} from 'lexical';\nimport { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';\n\nimport {\n FormatAlignCenterIcon,\n FormatAlignLeftIcon,\n FormatAlignRightIcon,\n} from '@swisper.ai/icons';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useRichTextAreaEditor } from '../../rich-text-area/hooks';\nimport { DEFAULT_ALIGNMENT } from '../constants';\nimport { type RichTextFieldAlignment } from '../context';\n\nimport { ToolbarSelect } from './toolbar-select';\n\nfunction toAlignment(format: ElementFormatType): RichTextFieldAlignment {\n if (format === 'center' || format === 'right') {\n return format;\n }\n if (format === 'end') {\n return 'right';\n }\n return 'left';\n}\n\nconst ALIGNMENT_OPTIONS_MAP: Record<RichTextFieldAlignment, { label: string; icon: ReactNode }> = {\n left: { label: 'Left', icon: <FormatAlignLeftIcon fontSize=\"inherit\" /> },\n center: { label: 'Center', icon: <FormatAlignCenterIcon fontSize=\"inherit\" /> },\n right: { label: 'Right', icon: <FormatAlignRightIcon fontSize=\"inherit\" /> },\n};\n\nexport interface AlignmentSelectProps {\n className?: string;\n}\n\nexport function AlignmentSelect({ className }: AlignmentSelectProps) {\n const editor = useRichTextAreaEditor();\n const [value, setValue] = useState<RichTextFieldAlignment>(DEFAULT_ALIGNMENT);\n\n const options = useMemo(\n () =>\n Object.entries(ALIGNMENT_OPTIONS_MAP).map(([value, { label, icon }]) => ({\n value: value as RichTextFieldAlignment,\n label,\n icon,\n })),\n [],\n );\n\n const $updateValue = useCallback(() => {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const node = selection.anchor.getNode();\n const parent = node.getParent();\n const element = $isElementNode(node) ? node : parent;\n if ($isElementNode(element)) {\n setValue(toAlignment(element.getFormatType() || DEFAULT_ALIGNMENT));\n }\n }\n }, []);\n\n useEffect(() => {\n return mergeRegister(\n editor.registerUpdateListener(({ editorState }) => {\n editorState.read(() => {\n $updateValue();\n });\n }),\n editor.registerCommand(\n SELECTION_CHANGE_COMMAND,\n () => {\n $updateValue();\n return false;\n },\n COMMAND_PRIORITY_LOW,\n ),\n );\n }, [editor, $updateValue]);\n\n function handleChange(value: string) {\n editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, value as ElementFormatType);\n }\n\n return (\n <ToolbarSelect\n shouldShowOnlyIcon\n options={options}\n value={value}\n onChange={handleChange}\n className={cn('w-[56px]!', className)}\n />\n );\n}\n","import { IconButton, type IconButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ToolbarButtonProps extends IconButtonProps {\n isActive?: boolean;\n}\n\nexport function ToolbarButton({\n className,\n children,\n isActive,\n isDisabled = false,\n ...rest\n}: ToolbarButtonProps) {\n return (\n <IconButton\n isActive={isActive}\n className={cn('border-none bg-transparent', className)}\n size=\"sm\"\n variant=\"tertiary\"\n isDisabled={isDisabled}\n {...rest}\n >\n {children}\n </IconButton>\n );\n}\n","import { AttachmentsIcon } from '@swisper.ai/icons';\n\nimport { useRichTextAreaEditor } from '../../rich-text-area/hooks';\nimport { ATTACH_FILE_COMMAND } from '../../rich-text-area/plugins/file-attachment-plugin';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function AttachmentButton(props: ToolbarButtonProps) {\n const editor = useRichTextAreaEditor();\n\n function handleClick() {\n editor.dispatchCommand(ATTACH_FILE_COMMAND, undefined);\n }\n\n return (\n <ToolbarButton\n data-testid=\"attachment-button\"\n aria-label=\"Add Attachment\"\n onClick={handleClick}\n {...props}\n >\n <AttachmentsIcon />\n </ToolbarButton>\n );\n}\n","import { $isDecoratorBlockNode } from '@lexical/react/LexicalDecoratorBlockNode';\nimport { $isHeadingNode, $isQuoteNode } from '@lexical/rich-text';\nimport { $forEachSelectedTextNode, $isAtNodeEnd, $patchStyleText } from '@lexical/selection';\nimport { $isTableSelection } from '@lexical/table';\nimport { mergeRegister, $getNearestBlockElementAncestorOrThrow } from '@lexical/utils';\nimport type { PropertiesHyphenFallback } from 'csstype';\nimport InlineStyleParser from 'inline-style-parser';\nimport {\n $addUpdateTag,\n $caretRangeFromSelection,\n $createParagraphNode,\n $getNodeByKey,\n $getPreviousSelection,\n $getSelection,\n $getState,\n $isRangeSelection,\n $isTextNode,\n $setSelection,\n $setState,\n COMMAND_PRIORITY_EDITOR,\n createCommand,\n createState,\n type DOMConversionMap,\n type DOMExportOutput,\n type ElementNode,\n isDocumentFragment,\n isHTMLElement,\n type LexicalEditor,\n type LexicalNode,\n type RangeSelection,\n RootNode,\n SKIP_DOM_SELECTION_TAG,\n TextNode,\n type ValueOrUpdater,\n} from 'lexical';\n\n/**\n * Creates an object containing all the styles and their values provided in the CSS string.\n * @param css - The CSS string of styles and their values.\n * @returns The styleObject containing all the styles and their values.\n */\nexport function getStyleObjectFromRawCSS(css: string): StyleObject {\n let styleObject: undefined | Record<string, string>;\n for (const token of InlineStyleParser(css, { silent: true })) {\n if (token.type === 'declaration' && token.value) {\n styleObject = styleObject || {};\n styleObject[token.property] = token.value;\n }\n }\n return styleObject || NO_STYLE;\n}\n\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type StyleObject = Prettify<{\n [K in keyof PropertiesHyphenFallback]?:\n | undefined\n // This is simplified to not deal with arrays or numbers.\n // This is an example after all!\n | Extract<PropertiesHyphenFallback[K], string>;\n}>;\n\nexport type StyleTuple = Exclude<\n {\n [K in keyof StyleObject]: [K, null | Exclude<StyleObject[K], undefined>];\n }[keyof StyleObject],\n undefined\n>;\n\nexport const NO_STYLE: StyleObject = Object.freeze({});\n\nfunction parse(v: unknown): StyleObject {\n return typeof v === 'string' ? getStyleObjectFromRawCSS(v) : NO_STYLE;\n}\n\nfunction unparse(style: StyleObject): string {\n const styles: string[] = [];\n for (const [k, v] of Object.entries(style)) {\n if (k && v) {\n styles.push(`${k}: ${v};`);\n }\n }\n return styles.sort().join(' ');\n}\n\nfunction isEqualValue(\n a: StyleObject[keyof StyleObject],\n b: StyleObject[keyof StyleObject],\n): boolean {\n return a === b || (!a && !b);\n}\n\nfunction isEqual(a: StyleObject, b: StyleObject): boolean {\n if (a === b) {\n return true;\n }\n for (const k in a) {\n if (!(k in b && isEqualValue(a[k as keyof StyleObject], b[k as keyof StyleObject]))) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\nexport const styleState = createState('style', {\n isEqual,\n parse,\n unparse,\n});\n\nexport function $getStyleProperty<Prop extends keyof StyleObject>(\n node: LexicalNode,\n prop: Prop,\n): undefined | StyleObject[Prop] {\n return $getStyleObject(node)[prop];\n}\n\nexport function getStyleObjectDirect(node: LexicalNode): StyleObject {\n return $getState(node, styleState, 'direct');\n}\n\nexport function $getStyleObject(node: LexicalNode): StyleObject {\n return $getState(node, styleState);\n}\n\nexport function $setStyleObject<T extends LexicalNode>(\n node: T,\n valueOrUpdater: ValueOrUpdater<StyleObject>,\n): T {\n return $setState(node, styleState, valueOrUpdater);\n}\n\nexport function $removeStyleProperty<T extends LexicalNode, Prop extends keyof StyleObject>(\n node: T,\n prop: Prop,\n): T {\n return $setStyleObject(node, (prevStyle) => {\n if (prop in prevStyle) {\n const { [prop]: _ignore, ...nextStyle } = prevStyle;\n return nextStyle;\n }\n return prevStyle;\n });\n}\n\nexport function $setStyleProperty<T extends LexicalNode, Prop extends keyof StyleObject>(\n node: T,\n prop: Prop,\n value: ValueOrUpdater<StyleObject[Prop]>,\n): T {\n return $setStyleObject(node, (prevStyle) => {\n const prevValue = prevStyle[prop];\n const nextValue = typeof value === 'function' ? value(prevValue) : value;\n return prevValue === nextValue ? prevStyle : { ...prevStyle, [prop]: nextValue };\n });\n}\n\nexport function applyStyle(element: HTMLElement, styleObject: StyleObject): void {\n for (const k_ in styleObject) {\n const k = k_ as keyof StyleObject;\n element.style.setProperty(k, styleObject[k] ?? null);\n }\n}\n\nexport function diffStyleObjects(prevStyles: StyleObject, nextStyles: StyleObject): StyleObject {\n let styleDiff: undefined | Record<string, string | undefined>;\n if (prevStyles !== nextStyles) {\n for (const k_ in nextStyles) {\n const k = k_ as keyof StyleObject;\n const nextV = nextStyles[k];\n const prevV = prevStyles[k];\n if (!isEqualValue(nextV, prevV)) {\n styleDiff = styleDiff || {};\n styleDiff[k] = nextV;\n }\n }\n for (const k in prevStyles) {\n if (!(k in nextStyles)) {\n styleDiff = styleDiff || {};\n styleDiff[k] = undefined;\n }\n }\n }\n return styleDiff || NO_STYLE;\n}\n\nexport function mergeStyleObjects(prevStyles: StyleObject, nextStyles: StyleObject): StyleObject {\n return prevStyles === NO_STYLE || prevStyles === nextStyles\n ? nextStyles\n : { ...prevStyles, ...nextStyles };\n}\n\nexport function styleObjectToArray(styleObject: StyleObject): StyleTuple[] {\n const entries: StyleTuple[] = [];\n for (const k_ in styleObject) {\n const k = k_ as keyof StyleObject;\n entries.push([k, styleObject[k] ?? null] as StyleTuple);\n }\n entries.sort(([a], [b]) => a.localeCompare(b));\n return entries;\n}\n\nexport const PATCH_TEXT_STYLE_COMMAND = createCommand<\n StyleObject | ((prevStyles: StyleObject) => StyleObject)\n>('PATCH_TEXT_STYLE_COMMAND');\n\nfunction $nodeHasStyle(node: LexicalNode): boolean {\n return !isEqual(NO_STYLE, $getStyleObject(node));\n}\n\nexport function $selectionHasStyle(): boolean {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const caretRange = $caretRangeFromSelection(selection);\n for (const slice of caretRange.getTextSlices()) {\n if (slice && $nodeHasStyle(slice.caret.origin)) {\n return true;\n }\n }\n for (const caret of caretRange.iterNodeCarets('root')) {\n if ($isTextNode(caret.origin) && $nodeHasStyle(caret.origin)) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function $patchSelectedTextStyle(\n styleObjectOrCallback: StyleObject | ((prevStyles: StyleObject) => StyleObject),\n): boolean {\n let selection = $getSelection();\n if (!selection) {\n const prevSelection = $getPreviousSelection();\n if (!prevSelection) {\n return false;\n }\n selection = prevSelection.clone();\n $setSelection(selection);\n }\n const styleCallback =\n typeof styleObjectOrCallback === 'function'\n ? styleObjectOrCallback\n : (prevStyles: StyleObject) => mergeStyleObjects(prevStyles, styleObjectOrCallback);\n if ($isRangeSelection(selection) && selection.isCollapsed()) {\n const node = selection.focus.getNode();\n if ($isTextNode(node)) {\n $setStyleObject(node, styleCallback);\n }\n } else {\n $forEachSelectedTextNode((node) => $setStyleObject(node, styleCallback));\n }\n return true;\n}\n\nconst PREV_STYLE_STATE = Symbol.for('styleState');\ninterface HTMLElementWithManagedStyle extends HTMLElement {\n // Store the last reconciled style object directly on the DOM\n // so we don't have to track the previous DOM\n // which can happen even when nodeMutation is 'updated'\n [PREV_STYLE_STATE]?: StyleObject;\n}\n\ninterface LexicalNodeWithUnknownStyle extends LexicalNode {\n // This property exists on all TextNode and ElementNode\n // and likely also some DecoratorNode by convention.\n // We use it as a heuristic to see if the style has likely\n // been overwritten to see if we should apply a diff\n // or all styles.\n __style?: unknown;\n}\n\nfunction styleStringChanged(\n node: LexicalNodeWithUnknownStyle,\n prevNode: LexicalNodeWithUnknownStyle,\n): boolean {\n return typeof node.__style === 'string' && prevNode.__style !== node.__style;\n}\n\nfunction getPreviousStyleObject(\n node: LexicalNode,\n prevNode: null | LexicalNode,\n dom: HTMLElementWithManagedStyle,\n): StyleObject {\n const prevStyleObject = dom[PREV_STYLE_STATE];\n return prevStyleObject && prevNode && !styleStringChanged(node, prevNode)\n ? prevStyleObject\n : NO_STYLE;\n}\n\n// This applies the style to the DOM of any node\nfunction makeStyleUpdateListener(editor: LexicalEditor): () => void {\n return mergeRegister(\n editor.registerMutationListener(RootNode, () => {\n // UpdateListener will only get the mutatedNodes payload when\n // at least one MutationListener is registered\n }),\n editor.registerUpdateListener((payload) => {\n const { prevEditorState, mutatedNodes } = payload;\n editor.getEditorState().read(\n () => {\n if (mutatedNodes) {\n for (const nodes of mutatedNodes.values()) {\n for (const [nodeKey, nodeMutation] of nodes) {\n if (nodeMutation === 'destroyed') {\n continue;\n }\n const node = $getNodeByKey(nodeKey);\n const dom: null | HTMLElementWithManagedStyle = editor.getElementByKey(nodeKey);\n if (!dom || !node) {\n return;\n }\n const prevNode = $getNodeByKey(nodeKey, prevEditorState);\n const prevStyleObject = getPreviousStyleObject(node, prevNode, dom);\n const nextStyleObject = $getStyleObject(node);\n dom[PREV_STYLE_STATE] = nextStyleObject;\n applyStyle(dom, diffStyleObjects(prevStyleObject, nextStyleObject));\n }\n }\n }\n },\n { editor },\n );\n }),\n );\n}\n\n// TODO https://github.com/facebook/lexical/issues/7259\n// there should be a better way to do this, this does not compose with other exportDOM overrides\nexport function $exportNodeStyle(editor: LexicalEditor, target: LexicalNode): DOMExportOutput {\n const output = target.exportDOM(editor);\n const style = $getStyleObject(target);\n if (style === NO_STYLE) {\n return output;\n }\n return {\n ...output,\n after: (generatedElement) => {\n const el = output.after ? output.after(generatedElement) : generatedElement;\n if (isHTMLElement(el)) {\n applyStyle(el, style);\n } else if (isDocumentFragment(el)) {\n // Work around a bug in the type\n return el;\n }\n return el;\n },\n };\n}\n\nconst IGNORE_STYLES = new Set<keyof StyleObject>([\n 'font-weight',\n 'text-decoration',\n 'font-style',\n 'vertical-align',\n]);\n\nexport type StyleMapping = (input: StyleObject) => StyleObject;\n\n// TODO there's no reasonable way to hook into importDOM/exportDOM from a plug-in https://github.com/facebook/lexical/issues/7259\nexport function constructStyleImportMap(\n styleMapping: StyleMapping = (input) => input,\n): DOMConversionMap {\n const importMap: DOMConversionMap = {};\n\n // Wrap all TextNode importers with a function that also imports\n // styles that are not otherwise imported\n for (const [tag, fn] of Object.entries(TextNode.importDOM() || {})) {\n importMap[tag] = (importNode) => {\n const importer = fn(importNode);\n if (!importer) {\n return null;\n }\n return {\n ...importer,\n conversion: (element) => {\n const output = importer.conversion(element);\n if (\n output?.forChild === undefined ||\n output.after !== undefined ||\n output.node !== null ||\n !element.hasAttribute('style')\n ) {\n return output;\n }\n let extraStyles: undefined | Record<string, string>;\n for (const k of element.style) {\n if (IGNORE_STYLES.has(k as keyof StyleObject)) {\n continue;\n }\n extraStyles = extraStyles || {};\n extraStyles[k] = element.style.getPropertyValue(k);\n }\n if (extraStyles) {\n const { forChild } = output;\n return {\n ...output,\n forChild: (child, parent) => {\n const node = forChild(child, parent);\n return $isTextNode(node)\n ? $setStyleObject(node, styleMapping(extraStyles as StyleObject))\n : node;\n },\n };\n }\n return output;\n },\n };\n };\n }\n return importMap;\n}\n\nexport function registerStyleState(editor: LexicalEditor): () => void {\n return mergeRegister(\n editor.registerCommand(\n PATCH_TEXT_STYLE_COMMAND,\n $patchSelectedTextStyle,\n COMMAND_PRIORITY_EDITOR,\n ),\n makeStyleUpdateListener(editor),\n );\n}\n\nexport function getSelectedNode(selection: RangeSelection): TextNode | ElementNode {\n const anchor = selection.anchor;\n const focus = selection.focus;\n const anchorNode = selection.anchor.getNode();\n const focusNode = selection.focus.getNode();\n if (anchorNode === focusNode) {\n return anchorNode;\n }\n const isBackward = selection.isBackward();\n if (isBackward) {\n return $isAtNodeEnd(focus) ? anchorNode : focusNode;\n } else {\n return $isAtNodeEnd(anchor) ? anchorNode : focusNode;\n }\n}\n\n/**\n * Patches the selection with the updated font size.\n */\nexport const updateFontSizeInSelection = (\n editor: LexicalEditor,\n newFontSize: string | null,\n _updateType: unknown,\n skipRefocus: boolean,\n) => {\n editor.update(() => {\n if (skipRefocus) {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n }\n if (editor.isEditable()) {\n const selection = $getSelection();\n if (selection !== null) {\n $patchStyleText(selection, {\n 'font-size': newFontSize + 'px',\n });\n }\n }\n });\n};\n\nexport function clearFormatting(editor: LexicalEditor, skipRefocus = false) {\n editor.update(() => {\n if (skipRefocus) {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n }\n const selection = $getSelection();\n if ($isRangeSelection(selection) || $isTableSelection(selection)) {\n const anchor = selection.anchor;\n const focus = selection.focus;\n const nodes = selection.getNodes();\n const extractedNodes = selection.extract();\n\n if (anchor.key === focus.key && anchor.offset === focus.offset) {\n return;\n }\n\n nodes.forEach((node, idx) => {\n // We split the first and last node by the selection\n // So that we don't format unselected text inside those nodes\n if ($isTextNode(node)) {\n // Use a separate variable to ensure TS does not lose the refinement\n let textNode = node;\n if (idx === 0 && anchor.offset !== 0) {\n textNode = textNode.splitText(anchor.offset)[1] || textNode;\n }\n if (idx === nodes.length - 1) {\n textNode = textNode.splitText(focus.offset)[0] || textNode;\n }\n /**\n * If the selected text has one format applied\n * selecting a portion of the text, could\n * clear the format to the wrong portion of the text.\n *\n * The cleared text is based on the length of the selected text.\n */\n // We need this in case the selected text only has one format\n const extractedTextNode = extractedNodes[0];\n if (nodes.length === 1 && $isTextNode(extractedTextNode)) {\n textNode = extractedTextNode;\n }\n\n if (textNode.__style !== '') {\n textNode.setStyle('');\n }\n if (textNode.__format !== 0) {\n textNode.setFormat(0);\n }\n const nearestBlockElement = $getNearestBlockElementAncestorOrThrow(textNode);\n if (nearestBlockElement.__format !== 0) {\n nearestBlockElement.setFormat('');\n }\n if (nearestBlockElement.__indent !== 0) {\n nearestBlockElement.setIndent(0);\n }\n } else if ($isHeadingNode(node) || $isQuoteNode(node)) {\n node.replace($createParagraphNode(), true);\n } else if ($isDecoratorBlockNode(node)) {\n node.setFormat('');\n }\n });\n }\n });\n}\n","import { $isLinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';\nimport { $getSelectionStyleValueForProperty, $patchStyleText } from '@lexical/selection';\nimport { mergeRegister } from '@lexical/utils';\nimport {\n $getSelection,\n $isRangeSelection,\n SELECTION_CHANGE_COMMAND,\n COMMAND_PRIORITY_LOW,\n FORMAT_TEXT_COMMAND,\n $addUpdateTag,\n SKIP_SELECTION_FOCUS_TAG,\n} from 'lexical';\nimport type { ReactNode } from 'react';\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';\n\nimport { useRichTextAreaEditor } from '../rich-text-area/hooks';\n\nimport {\n type ALIGNMENT_OPTIONS,\n DEFAULT_FONT_FAMILY_VALUE,\n DEFAULT_FONT_SIZE,\n DEFAULT_TEXT_COLOR,\n} from './constants';\nimport { updateFontSizeInSelection, getSelectedNode } from './utils';\n\nexport type RichTextFieldAlignment = (typeof ALIGNMENT_OPTIONS)[number];\n\nexport interface RichTextFieldContextValue {\n fontFamily: string;\n fontSize: string;\n textColor: string;\n isBold: boolean;\n isItalic: boolean;\n isUnderline: boolean;\n isLink: boolean;\n onFontFamily: (value: string) => void;\n onFontSize: (value: string) => void;\n onTextColor: (value: string) => void;\n onBold: () => void;\n onItalic: () => void;\n onUnderline: () => void;\n onLink: () => void;\n}\n\nconst sanitizeUrl = (url: string) => {\n return url.startsWith('http') ? url : `https://${url}`;\n};\n\nexport const RichTextFieldContext = createContext<RichTextFieldContextValue>(null!);\n\nexport function useRichTextFieldContext() {\n const context = useContext(RichTextFieldContext);\n\n if (!context) {\n throw new Error('\"useRichTextFieldContext\" must be used within a RichTextFieldContextProvider');\n }\n\n return context;\n}\n\nexport interface RichTextFieldContextProviderProps {\n children: ReactNode;\n}\n\nfunction normalizeColorToHex(color: string): string {\n const trimmed = color.trim();\n\n // hex #rgb or #rrggbb\n const hexMatch = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(trimmed);\n if (hexMatch) {\n const value = hexMatch[1];\n if (value.length === 3) {\n const [r, g, b] = value;\n return `#${r}${r}${g}${g}${b}${b}`.toLowerCase();\n }\n return `#${value.toLowerCase()}`;\n }\n\n // rgb(...) or rgba(...)\n const rgbMatch = /^rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})/i.exec(trimmed);\n if (rgbMatch) {\n const clamp = (n: number) => Math.max(0, Math.min(255, n));\n const [r, g, b] = rgbMatch.slice(1, 4).map((v) => clamp(Number.parseInt(v, 10)));\n const toHex = (n: number) => n.toString(16).padStart(2, '0');\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n }\n\n return DEFAULT_TEXT_COLOR;\n}\n\nexport function RichTextFieldContextProvider({ children }: RichTextFieldContextProviderProps) {\n const editor = useRichTextAreaEditor();\n\n const [fontFamily, setFontFamily] = useState<string>(DEFAULT_FONT_FAMILY_VALUE);\n const [fontSize, setFontSize] = useState<string>(DEFAULT_FONT_SIZE);\n const [isBold, setIsBold] = useState(false);\n const [isItalic, setIsItalic] = useState(false);\n const [isUnderline, setIsUnderline] = useState(false);\n const [textColor, setTextColor] = useState<string>(DEFAULT_TEXT_COLOR);\n const [isLink, setIsLink] = useState(false);\n\n const $updateToolbar = useCallback(() => {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n // font family\n setFontFamily(\n $getSelectionStyleValueForProperty(selection, 'font-family', DEFAULT_FONT_FAMILY_VALUE),\n );\n // font size\n const fontSize = $getSelectionStyleValueForProperty(\n selection,\n 'font-size',\n DEFAULT_FONT_SIZE + 'px',\n );\n setFontSize(fontSize ? fontSize.replace('px', '') : DEFAULT_FONT_SIZE);\n // bold\n setIsBold(selection.hasFormat('bold'));\n // italic\n setIsItalic(selection.hasFormat('italic'));\n // underline\n setIsUnderline(selection.hasFormat('underline'));\n // text-color\n const rawColor =\n $getSelectionStyleValueForProperty(selection, 'color', DEFAULT_TEXT_COLOR) ||\n DEFAULT_TEXT_COLOR;\n setTextColor(normalizeColorToHex(rawColor));\n // link\n const node = getSelectedNode(selection);\n const parent = node.getParent();\n const isLink = $isLinkNode(parent) || $isLinkNode(node);\n setIsLink(isLink);\n }\n }, []);\n\n useEffect(() => {\n return mergeRegister(\n editor.registerUpdateListener(({ editorState }) => {\n editorState.read(() => {\n $updateToolbar();\n });\n }),\n\n editor.registerCommand(\n SELECTION_CHANGE_COMMAND,\n () => {\n $updateToolbar();\n return false;\n },\n COMMAND_PRIORITY_LOW,\n ),\n );\n }, [editor, $updateToolbar]);\n\n const onFontFamily = useCallback(\n (value: string) => {\n editor.update(() => {\n $addUpdateTag(SKIP_SELECTION_FOCUS_TAG);\n const selection = $getSelection();\n if (selection !== null) {\n $patchStyleText(selection, {\n ['font-family']: value,\n });\n }\n });\n },\n [editor],\n );\n\n const onFontSize = useCallback(\n (value: string) => {\n updateFontSizeInSelection(editor, value, null, false);\n },\n [editor],\n );\n\n const onBold = useCallback(() => {\n editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'bold');\n }, [editor]);\n\n const onItalic = useCallback(() => {\n editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'italic');\n }, [editor]);\n\n const onUnderline = useCallback(() => {\n editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'underline');\n }, [editor]);\n\n const onTextColor = useCallback(\n (value: string) => {\n editor.update(() => {\n $addUpdateTag(SKIP_SELECTION_FOCUS_TAG);\n const selection = $getSelection();\n if (selection !== null) {\n $patchStyleText(selection, {\n color: value,\n });\n }\n });\n },\n [editor],\n );\n\n const onLink = useCallback(() => {\n if (!isLink) {\n setIsLink(true);\n editor.dispatchCommand(TOGGLE_LINK_COMMAND, sanitizeUrl('https://'));\n } else {\n setIsLink(false);\n editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);\n }\n }, [isLink, setIsLink]);\n\n const contextValue = useMemo<RichTextFieldContextValue>(\n () => ({\n fontFamily,\n fontSize,\n textColor,\n isBold,\n isItalic,\n isUnderline,\n isLink,\n onFontFamily,\n onFontSize,\n onTextColor,\n onBold,\n onItalic,\n onUnderline,\n onLink,\n }),\n [\n fontFamily,\n fontSize,\n textColor,\n isBold,\n isItalic,\n isUnderline,\n isLink,\n onFontFamily,\n onFontSize,\n onTextColor,\n onBold,\n onItalic,\n onUnderline,\n onLink,\n ],\n );\n\n return (\n <RichTextFieldContext.Provider value={contextValue}>{children}</RichTextFieldContext.Provider>\n );\n}\n","import { FormatBoldIcon } from '@swisper.ai/icons';\n\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function BoldButton({ ...props }: ToolbarButtonProps) {\n const { isBold, onBold } = useRichTextFieldContext();\n\n return (\n <ToolbarButton\n data-testid=\"bold-button\"\n aria-label=\"Format Bold\"\n isActive={isBold}\n onClick={onBold}\n {...props}\n >\n <FormatBoldIcon />\n </ToolbarButton>\n );\n}\n","import { $getNearestBlockElementAncestorOrThrow } from '@lexical/utils';\nimport { $getSelection, $isRangeSelection, $isTextNode } from 'lexical';\nimport { useCallback } from 'react';\n\nimport { FormatCleanIcon } from '@swisper.ai/icons';\n\nimport { useRichTextAreaEditor } from '../../rich-text-area/hooks';\nimport { $patchSelectedTextStyle, NO_STYLE } from '../utils';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function CleanFormatButton({ ...props }: ToolbarButtonProps) {\n const editor = useRichTextAreaEditor();\n\n const handleClick = useCallback(() => {\n editor.update(() => {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n $patchSelectedTextStyle(() => NO_STYLE);\n\n for (const node of selection.extract()) {\n if ($isTextNode(node)) {\n node.setFormat(0);\n node.setStyle('');\n\n const blockElement = $getNearestBlockElementAncestorOrThrow(node);\n blockElement.setFormat('');\n }\n }\n }\n });\n }, [editor]);\n\n return (\n <ToolbarButton\n data-testid=\"clean-format-button\"\n aria-label=\"Reset Formatting\"\n onClick={handleClick}\n {...props}\n >\n <FormatCleanIcon />\n </ToolbarButton>\n );\n}\n","import { ImageIcon } from '@swisper.ai/icons';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function ImageButton({ ...props }: ToolbarButtonProps) {\n return (\n <ToolbarButton data-testid=\"image-button\" aria-label=\"Add Image\" {...props}>\n <ImageIcon />\n </ToolbarButton>\n );\n}\n","import { FormatItalicIcon } from '@swisper.ai/icons';\n\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function ItalicButton({ ...props }: ToolbarButtonProps) {\n const { isItalic, onItalic } = useRichTextFieldContext();\n\n return (\n <ToolbarButton\n data-testid=\"italic-button\"\n aria-label=\"Format Italics\"\n isActive={isItalic}\n onClick={onItalic}\n {...props}\n >\n <FormatItalicIcon />\n </ToolbarButton>\n );\n}\n","import { LinkOnIcon, LinkOffIcon } from '@swisper.ai/icons';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function LinkButton({ isActive, ...props }: ToolbarButtonProps) {\n return (\n <ToolbarButton data-testid=\"link-button\" aria-label=\"Add Link\" {...props}>\n {isActive ? <LinkOnIcon /> : <LinkOffIcon />}\n </ToolbarButton>\n );\n}\n","import { useMemo } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { FONT_SIZE_OPTIONS } from '../constants';\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarSelect } from './toolbar-select';\n\nexport interface SizeSelectProps {\n className?: string;\n}\n\nexport function SizeSelect({ className }: SizeSelectProps) {\n const { fontSize, onFontSize } = useRichTextFieldContext();\n const options = useMemo(() => [...FONT_SIZE_OPTIONS], []);\n\n return (\n <ToolbarSelect\n data-testid=\"size-select\"\n options={options}\n value={fontSize}\n onChange={onFontSize}\n className={cn('w-[72px] gap-0', className)}\n />\n );\n}\n","import { type ChangeEvent } from 'react';\n\nimport { FormatColorIcon } from '@swisper.ai/icons';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { DEFAULT_TEXT_COLOR } from '../constants';\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport interface TextColorButtonProps extends ToolbarButtonProps {\n /**\n * Classes for the element around the button and its colour input\n * (`data-slot=\"rich-text-field-text-color\"`), merged last. `className` lands on the button.\n */\n wrapperClassName?: string;\n}\n\n/**\n * Toolbar button that opens the browser's colour picker and applies the colour to the selected\n * text; its icon takes the colour at the caret. Works only inside a `RichTextField` toolbar.\n */\nexport function TextColorButton({ wrapperClassName, ...props }: TextColorButtonProps) {\n const { textColor, onTextColor } = useRichTextFieldContext();\n const isDefaultColor = textColor === DEFAULT_TEXT_COLOR;\n\n function handleColorChange(e: ChangeEvent<HTMLInputElement>) {\n onTextColor(e.target.value);\n }\n\n return (\n <div data-slot=\"rich-text-field-text-color\" className={cn('relative', wrapperClassName)}>\n <ToolbarButton data-testid=\"text-color-button\" aria-label=\"Text Color\" {...props}>\n <span style={!isDefaultColor ? { color: textColor } : {}}>\n <FormatColorIcon />\n </span>\n </ToolbarButton>\n <input\n type=\"color\"\n data-slot=\"rich-text-field-text-color-input\"\n value={textColor}\n onChange={handleColorChange}\n tabIndex={-1}\n style={{\n position: 'absolute',\n inset: 0,\n width: '100%',\n height: '100%',\n opacity: 0,\n cursor: 'pointer',\n }}\n />\n </div>\n );\n}\n","import { useMemo } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { FONT_FAMILY_OPTIONS } from '../constants';\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarSelect } from './toolbar-select';\n\nexport interface TypographySelectProps {\n className?: string;\n}\n\nexport function TypographySelect({ className }: TypographySelectProps) {\n const { fontFamily, onFontFamily } = useRichTextFieldContext();\n const options = useMemo(() => [...FONT_FAMILY_OPTIONS], []);\n\n return (\n <ToolbarSelect\n data-testid=\"typography-select\"\n options={options}\n value={fontFamily}\n onChange={onFontFamily}\n className={cn('w-[90px]', className)}\n />\n );\n}\n","import { FormatUnderlineIcon } from '@swisper.ai/icons';\n\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function UnderlineButton({ ...props }: ToolbarButtonProps) {\n const { isUnderline, onUnderline } = useRichTextFieldContext();\n\n return (\n <ToolbarButton\n data-testid=\"underline-button\"\n aria-label=\"Format Underline\"\n isActive={isUnderline}\n onClick={onUnderline}\n {...props}\n >\n <FormatUnderlineIcon />\n </ToolbarButton>\n );\n}\n","import type { ReactNode } from 'react';\n\nimport { Divider } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { AlignmentSelect } from './alignment-select';\nimport { AttachmentButton } from './attachment-button';\nimport { BoldButton } from './bold-button';\nimport { CleanFormatButton } from './clean-format-button';\nimport { ImageButton } from './image-button';\nimport { ItalicButton } from './italic-button';\nimport { LinkButton } from './link-button';\nimport { SizeSelect } from './size-select';\nimport { TextColorButton } from './text-color-button';\nimport { TypographySelect } from './typography-select';\nimport { UnderlineButton } from './underline-button';\n\nexport interface FormattingToolbarPluginProps {\n /** Classes for the toolbar (`data-slot=\"rich-text-field-toolbar\"`), merged last. */\n className?: string;\n /** Renders the toolbar controls from `{ hasAttachments }`. Defaults to the full control set. */\n children?: ({ hasAttachments }: { hasAttachments: boolean }) => ReactNode;\n /** Handed to `children`; the default controls enable the attachment button with it. */\n hasAttachments?: boolean;\n}\n\nconst DefaultFormattingToolbarChildren = ({ hasAttachments }: { hasAttachments: boolean }) => (\n <>\n <TypographySelect />\n <SizeSelect />\n\n <Divider orientation=\"vertical\" />\n\n <BoldButton />\n <ItalicButton />\n <UnderlineButton />\n <TextColorButton />\n\n <Divider orientation=\"vertical\" />\n <LinkButton isDisabled />\n <AttachmentButton isDisabled={!hasAttachments} />\n <ImageButton isDisabled />\n\n <Divider orientation=\"vertical\" />\n\n <AlignmentSelect />\n\n <Divider orientation=\"vertical\" />\n\n <CleanFormatButton />\n </>\n);\n\n/**\n * The toolbar row `RichTextField` renders. Its controls read the field's formatting context, so it\n * only works inside a `RichTextField`, which already renders one: pass controls through the\n * field's `toolbarChildren` instead of rendering this yourself.\n */\nexport function FormattingToolbarPlugin({\n className,\n children = DefaultFormattingToolbarChildren,\n hasAttachments = false,\n}: FormattingToolbarPluginProps) {\n return (\n <div\n data-testid=\"formatting-toolbar\"\n data-slot=\"rich-text-field-toolbar\"\n className={cn(\n 'flex items-center gap-[2px]',\n 'px-[16px] py-[8px] overflow-x-auto',\n 'bg-paper-elevation-1 border-b border-divider-border-base',\n className,\n )}\n >\n {children({ hasAttachments })}\n </div>\n );\n}\n","import { forwardRef, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { RichTextArea, type RichTextAreaProps } from '../rich-text-area';\nimport { FileAttachmentPlugin } from '../rich-text-area/plugins/file-attachment-plugin';\n\nimport { FormattingToolbarPlugin } from './components/formatting-toolbar-plugin';\nimport { RichTextFieldContextProvider } from './context';\n\n/** Where the formatting toolbar sits inside the field: above or below the text. */\nexport type RichTextFieldToolbarPlacement = 'top' | 'bottom';\n\nexport interface RichTextFieldProps extends Omit<RichTextAreaProps, 'children'> {\n /** Accepted for type compatibility with `RichTextArea` but not rendered; use `toolbarChildren`. */\n children?: ReactNode;\n /**\n * Puts the toolbar above or below the text. The text padding and the placeholder offset follow\n * it, and the root carries it as `data-toolbar-placement`.\n * @default 'top'\n */\n toolbarPlacement?: RichTextFieldToolbarPlacement;\n /** Classes for the toolbar (`data-slot=\"rich-text-field-toolbar\"`), merged last. */\n toolbarClassName?: string;\n /**\n * Replaces the default toolbar controls. Receives `{ hasAttachments }` (the `enableAttachments`\n * value) and returns the toolbar content, built from the exported buttons and selects.\n */\n toolbarChildren?: ({ hasAttachments }: { hasAttachments: boolean }) => ReactNode;\n /** Lets the file picker select several files; `onFileAttach` gets only the first otherwise. */\n isMultipleAttachments?: boolean;\n /** Enables the attachment button of the default toolbar; it is shown disabled otherwise. */\n enableAttachments?: boolean;\n /** File types the picker accepts, as extensions or MIME types (`['.pdf', 'image/*']`). */\n acceptedFiles?: string[];\n /** Called with the picked files after the attachment button opens the file picker. */\n onFileAttach?: (files: File[]) => void;\n}\n\n/**\n * A fixed-height rich-text editor with a formatting toolbar above or below the text, built on\n * `RichTextArea`. `className` styles the editable text, `containerClassName` the root\n * (`data-slot=\"rich-text-field\"`), `placeholderClassName` the placeholder and `toolbarClassName`\n * the toolbar; each is merged last.\n */\nexport const RichTextField = forwardRef<HTMLInputElement, RichTextFieldProps>(\n (\n {\n children,\n className,\n placeholderClassName,\n containerClassName,\n toolbarPlacement = 'top',\n toolbarChildren,\n toolbarClassName,\n isMultipleAttachments,\n enableAttachments,\n acceptedFiles,\n onFileAttach,\n ...rest\n },\n ref,\n ) => {\n const isToolbarTop = toolbarPlacement === 'top';\n\n return (\n <RichTextArea\n ref={ref}\n data-testid=\"rich-text-field\"\n data-slot=\"rich-text-field\"\n data-toolbar-placement={toolbarPlacement}\n placeholderClassName={cn(\n 'left-(--rich-text-field-editor-padding)',\n isToolbarTop\n ? 'top-[calc(var(--rich-text-field-toolbar-height)+var(--rich-text-field-editor-padding))]'\n : 'top-rich-text-field-editor-padding',\n placeholderClassName,\n )}\n containerClassName={cn(\n 'h-rich-text-field-height',\n 'rounded-rich-text-field-toolbar',\n isToolbarTop ? 'pt-rich-text-field-toolbar-height' : 'pb-rich-text-field-toolbar-height',\n containerClassName,\n )}\n className={cn(\n 'p-rich-text-field-editor-padding',\n 'bg-rich-text-field-background',\n 'size-full',\n className,\n )}\n {...rest}\n >\n <RichTextFieldContextProvider>\n <FormattingToolbarPlugin\n hasAttachments={enableAttachments}\n className={cn(\n 'absolute right-0 w-full',\n isToolbarTop ? 'top-0' : 'bottom-0',\n toolbarClassName,\n )}\n >\n {toolbarChildren}\n </FormattingToolbarPlugin>\n </RichTextFieldContextProvider>\n\n <FileAttachmentPlugin\n acceptedFiles={acceptedFiles}\n onFileAttach={onFileAttach}\n isMultiple={isMultipleAttachments}\n />\n </RichTextArea>\n );\n },\n);\n\nRichTextField.displayName = 'RichTextField';\n","import { cva, type VariantProps } from 'class-variance-authority';\nimport { type ComponentProps } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nconst topMenuActionsVariants = cva('flex shrink-0 items-center justify-end', {\n variants: {\n size: {\n md: ['px-[4px]', 'rounded-overlay-tools-wrapper bg-overlay-tools-background-base'],\n lg: [\n 'h-topmenu-height gap-topmenu-spacing-gap px-topmenu-spacing-padding',\n 'rounded-topmenu-base bg-topmenu-background',\n 'backdrop-blur-xs',\n ],\n },\n hasBorder: {\n true: '',\n false: '',\n },\n },\n compoundVariants: [{ size: 'lg', hasBorder: true, className: 'border border-topmenu-border' }],\n defaultVariants: {\n size: 'lg',\n hasBorder: true,\n },\n});\n\nexport interface TopMenuProps extends ComponentProps<'div'> {}\n\n/**\n * The root of a trailing action cluster. Positions itself at the top right of the nearest\n * positioned ancestor and stacks its `TopMenuActions` panels, aligned to the trailing edge.\n */\nexport function TopMenu({ className, children, ...rest }: TopMenuProps) {\n return (\n <div\n data-slot=\"topmenu\"\n role=\"group\"\n className={cn('absolute top-0 right-0', 'flex flex-col items-end w-fit', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface TopMenuActionsProps\n extends ComponentProps<'div'>, VariantProps<typeof topMenuActionsVariants> {}\n\n/**\n * One panel of icon actions inside `TopMenu`: the frosted 48px header panel at `lg` (the default),\n * the compact overlay-tools pill at `md`. `hasBorder` only applies to `lg`.\n */\nexport function TopMenuActions({\n className,\n size,\n hasBorder,\n children,\n ...rest\n}: TopMenuActionsProps) {\n return (\n <div\n data-slot=\"topmenu-actions\"\n data-size={size ?? 'lg'}\n className={cn(topMenuActionsVariants({ size, hasBorder }), className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","export const CHAT_ACTION_PROTOCOL = 'swisper';\n","import remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport { unified } from 'unified';\nimport { visit } from 'unist-util-visit';\n\nimport { CHAT_ACTION_PROTOCOL } from '../constants';\nimport type { ChatAction } from '../types';\n\ninterface LinkPhrasingChild {\n type: string;\n value?: string;\n}\n\nexport function createChatActionURL(action: string, params?: Record<string, string>): string {\n const url = `${CHAT_ACTION_PROTOCOL}://action/${action}`;\n\n if (!params) {\n return url;\n }\n\n const searchParams = new URLSearchParams(params);\n\n return `${url}?${searchParams.toString()}`;\n}\n\nexport function createChatActionLink({\n action,\n label,\n params,\n}: {\n action: string;\n label: string;\n params?: Record<string, string>;\n}): string {\n return `[${label}](${createChatActionURL(action, params)})`;\n}\n\nexport function isChatActionURL(uri: string | undefined): boolean {\n if (!uri?.startsWith(`${CHAT_ACTION_PROTOCOL}://`)) {\n return false;\n }\n\n const url = new URL(uri);\n\n return (\n url.protocol === CHAT_ACTION_PROTOCOL + ':' &&\n url.hostname === 'action' &&\n url.pathname.startsWith('/') &&\n url.pathname.split('/').length === 2\n );\n}\n\nexport function extractChatActionMetadataFromUrl(\n link: string,\n): Pick<ChatAction, 'option' | 'payload'> | null {\n let url;\n\n try {\n url = new URL(link);\n } catch (error) {\n return null;\n }\n\n if (!isChatActionURL(link)) {\n return null;\n }\n\n const option = url.pathname.replace('/', '');\n const payload = Object.fromEntries(url.searchParams.entries());\n\n return {\n option,\n payload,\n };\n}\n\nfunction extractLabelFromNode(children: LinkPhrasingChild[]): string | null {\n for (const child of children) {\n if (child.type === 'text' && typeof child.value === 'string') {\n return child.value;\n }\n }\n\n return null;\n}\n\nexport function extractChatActionFromLink(markdown: string) {\n const ast = unified().use(remarkParse).use(remarkGfm).parse(markdown);\n\n let action: ChatAction | null = null;\n visit(ast, (node) => {\n if (node.type !== 'link') {\n return;\n }\n\n const metadata = extractChatActionMetadataFromUrl(node.url);\n const label = extractLabelFromNode(node.children);\n\n if (metadata && label) {\n action = {\n label,\n option: metadata.option,\n payload: metadata.payload,\n raw: node.url,\n };\n\n return;\n }\n });\n\n return action;\n}\n","import { useMemo } from 'react';\n\nimport { type ChatAction } from '../types';\nimport { extractChatActionFromLink } from '../utils';\n\nexport function useChatActions(actions: string[]) {\n return useMemo<ChatAction[]>(() => {\n return actions\n .map((link) => {\n const action = extractChatActionFromLink(link);\n\n if (!action) {\n return {\n label: link,\n };\n }\n\n return action;\n })\n .filter((action): action is ChatAction => action !== null);\n }, [actions]);\n}\n","import { createParser, type EventSourceMessage } from 'eventsource-parser';\nimport { useCallback } from 'react';\n\nexport type ChatStreamTokenParser<ParsedToken = string> = (chunk: string) => ParsedToken | null;\n\nexport interface UseChatStreamMessageOptions<ParsedToken = string> {\n stream: ReadableStreamDefaultReader<Uint8Array>;\n abortController?: AbortController;\n timeout?: number;\n tokenParser?: ChatStreamTokenParser<ParsedToken>;\n onChunkReceived: (chunk: ParsedToken) => void;\n onAbort?: (error: Error) => void;\n onFinish?: (message: string) => void;\n onError?: (error: Error) => void;\n}\n\nfunction defaultTokenParser<ParsedToken>(data: string): ParsedToken {\n return JSON.parse(data) as ParsedToken;\n}\n\nfunction isAbortError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n return error.name === 'AbortError' || error.name === 'TimeoutError';\n}\n\nfunction toError(value: unknown, fallbackMessage: string): Error {\n return value instanceof Error ? value : new Error(fallbackMessage);\n}\n\n/**\n * Process a chat message from a stream.\n *\n * @param stream - The stream to read from.\n * @param abortController - Optional abort controller to cancel the stream.\n * @param timeout - Optional idle timeout in ms; timer resets on each parsed chunk.\n * @param tokenParser - The function to parse the token.\n * @param onChunkReceived - The function to call when a chunk is received.\n * @param onAbort - Called once when the stream is cancelled (external abort, idle timeout, or reader cancellation).\n * @param onFinish - The function to call when the stream is finished.\n * @param onError - The function to call when an unexpected error occurs.\n *\n * @returns The function to process a chat message from a stream.\n *\n * @example\n * const { streamMessage } = useChatStreamMessage();\n * const stream = await streamMessage({\n * stream: readerStream,\n * timeout: 30_000,\n * onChunkReceived: (chunk) => {\n * console.log('chunk', chunk);\n * },\n * onAbort: (error) => {\n * console.log('stream aborted', error);\n * },\n * });\n */\nexport function useChatStreamMessage() {\n const streamMessage = useCallback(\n async <ParsedToken = string>({\n stream,\n abortController,\n timeout = 20_000, // 20 seconds\n tokenParser,\n onChunkReceived,\n onAbort,\n onFinish,\n onError,\n }: UseChatStreamMessageOptions<ParsedToken>) => {\n const parseToken = tokenParser ?? defaultTokenParser<ParsedToken>;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let didHandleAbort = false;\n\n const clearStreamTimeout = () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n };\n\n const handleAbort = (error: Error) => {\n if (didHandleAbort) {\n return;\n }\n\n didHandleAbort = true;\n clearStreamTimeout();\n onAbort?.(error);\n };\n\n const resetStreamTimeout = () => {\n if (timeout === undefined) {\n return;\n }\n\n clearStreamTimeout();\n timeoutId = setTimeout(() => {\n const error = new DOMException(\n `Stream timed out after ${timeout}ms of inactivity`,\n 'TimeoutError',\n );\n\n // abort will close the stream, so we don't need to cancel it\n abortController?.abort(error);\n\n if (!abortController) {\n handleAbort(error);\n }\n }, timeout);\n };\n\n try {\n let message = '';\n const decoder = new TextDecoder('utf-8');\n\n const parser = createParser({\n onEvent(event: EventSourceMessage) {\n try {\n message += event.data;\n const token = parseToken(event.data);\n\n if (!token) {\n throw new Error(`Failed to parse SSE chunk: ${event.data}`);\n }\n\n if (!abortController?.signal.aborted) {\n onChunkReceived(token);\n resetStreamTimeout();\n }\n } catch (e) {\n abortController?.abort(e);\n console.warn('Failed to parse SSE chunk:', event.data, e);\n }\n },\n onError(error) {\n abortController?.abort(error);\n console.error('Error while parsing stream:', error);\n },\n });\n\n abortController?.signal.addEventListener(\n 'abort',\n () => {\n const error = toError(abortController.signal.reason, 'Stream aborted');\n handleAbort(error);\n },\n {\n once: true,\n },\n );\n\n resetStreamTimeout();\n\n while (!didHandleAbort) {\n const { value, done } = await stream.read();\n const chunk = decoder.decode(value, { stream: true });\n parser.feed(chunk);\n if (done) break;\n }\n\n clearStreamTimeout();\n\n if (!didHandleAbort && !abortController?.signal.aborted) {\n onFinish?.(message);\n }\n } catch (e) {\n const error = e as Error;\n\n if (didHandleAbort || abortController?.signal.aborted || isAbortError(error)) {\n if (!didHandleAbort) {\n handleAbort(toError(error, 'Stream aborted'));\n }\n return;\n }\n\n abortController?.abort(error);\n console.error('Error while reading stream:', error);\n onError?.(error);\n }\n },\n [],\n );\n\n return {\n streamMessage,\n };\n}\n","import { useEffect, useRef } from 'react';\n\nimport { useChatContext } from '@/contexts';\nimport type { ChatId } from '@/types';\n\ntype UseOnChatChangedOptions = (options: {\n chatId: ChatId;\n prevChatId: ChatId;\n isNewChat: boolean;\n}) => void;\n\nexport function useOnChatChanged(onChatChanged: UseOnChatChangedOptions) {\n const { chatId, isNewChat } = useChatContext();\n\n const isNewChatRef = useRef(isNewChat);\n const prevChatIdRef = useRef(chatId);\n const chatChangedFn = useRef(onChatChanged);\n\n chatChangedFn.current = onChatChanged;\n isNewChatRef.current = isNewChat;\n\n useEffect(() => {\n if (prevChatIdRef.current !== chatId) {\n chatChangedFn.current({\n chatId,\n prevChatId: prevChatIdRef.current,\n isNewChat: isNewChatRef.current,\n });\n\n prevChatIdRef.current = chatId;\n }\n }, [chatId]);\n}\n","import { useChatContext } from '@/contexts';\n\nexport function useCurrentChatId() {\n const { chatId } = useChatContext();\n return chatId;\n}\n","import { useChatContext } from '@/contexts';\n\nexport function useIsCurrentChatNew() {\n const { isNewChat } = useChatContext();\n return isNewChat;\n}\n","import { useCallback } from 'react';\n\nimport { useChatContext } from '@/contexts';\nimport type { ChatId } from '@/types';\n\ninterface UseLoadedChatIdsOptions {\n getIsChatLoaded: (chatId: ChatId) => boolean;\n markAsLoaded: (chatId: ChatId) => void;\n markAsUnloaded: (chatId: ChatId) => void;\n}\n\nexport function useChatLoadedIds(): UseLoadedChatIdsOptions {\n const { loadedChatIdsRef } = useChatContext();\n\n const getIsChatLoaded = useCallback((chatId: ChatId) => {\n return loadedChatIdsRef.current?.has(chatId) ?? false;\n }, []);\n\n const markAsLoaded = useCallback((chatId: ChatId) => {\n loadedChatIdsRef.current?.add(chatId);\n }, []);\n\n const markAsUnloaded = useCallback((chatId: ChatId) => {\n loadedChatIdsRef.current?.delete(chatId);\n }, []);\n\n return {\n getIsChatLoaded,\n markAsLoaded,\n markAsUnloaded,\n };\n}\n","import { useChatContext } from '@/contexts';\n\nexport function useChatPromptPlaceholder() {\n const { promptPlaceholder, setPromptPlaceholder, clearPromptPlaceholder } = useChatContext();\n\n return { promptPlaceholder, setPromptPlaceholder, clearPromptPlaceholder };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAMwC,KAAkBC,EAA2C,IAAI;AAEvE,SAAgBC,IAAqB;CACnC,IAAMC,IAAUC,EAAWJ,EAAe;CAE1C,IAAI,CAACG,GACH,MAAU,MACR,mKAEF;CAGF,OAAOA;AACT;AAEA,SAAgBE,GAAiB,EAC/B,UACA,eAIC;CACD,OAAO,kBAACL,GAAgB,UAAjB;EAAiC;EAAQ;CAAmC,CAAA;AACrF;;;ACPA,SAAgBM,GAAe,EAC7B,cACA,aACA,uBACA,GAAGC,KACmB;CACtB,IAAM,EAAE,kBAAe,aAAUL,EAAmB,GAE9CM,IACJ,kBAAC,OAAD;EACE,aAAU;EACV,WAAWC,E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AO;EAAE;EAAmB;EAAsB;CAAuB;AAC3E"}
1
+ {"version":3,"file":"index.es.js","names":["EXPORT_TRANSFORMERS","IMPORT_TRANSFORMERS","$setSelectionToEnd","ControlledValuePlugin","EXPORT_TRANSFORMERS","IMPORT_TRANSFORMERS","DisabledPlugin","FocusPlugin","MarkdownPlainPastePlugin","MAX_EMITTED_VALUES","ValuePlugin","EXPORT_TRANSFORMERS","DisabledPlugin","ControlledValuePlugin","ValuePlugin","MarkdownPlainPastePlugin","FocusPlugin","_Fragment","MessageScrollerPrimitive","UiEmptyState","UiEmptyStateIcon","UiEmptyStateTitle","UiEmptyStateDescription","UiEmptyStateActionRow","TRANSFORMERS","elementNode","_Fragment","EmptyState$1","EmptyStateActionRow$1","EmptyStateDescription$1","EmptyStateIcon$1","EmptyStateTitle$1","TRANSFORMERS$1","ScrollAreaPrimitive","mime","rehypeSanitize","InlineStyleParser","remarkGfm","remarkParse","ChatCardContext","createContext","useChatCardContext","context","useContext","ChatCardProvider","ChatCardHeader","rest","inner","cn","level","isCollapsible","hoverAreaClassName","className","CollapsibleTrigger","ChatCardIcon","ChatCardHeaderContent","ChatCardTitle","Typography","ChatCardSubTitle","ChatCardActions","ChatCardActionButton","handleClick","shouldPreventCollapse","onClick","content","IconButton","tooltip","Tooltip","ChatCardCollapsibleButton","CollapsibleChevron","ChatCardMedia","ChatCardBody","Component","asChild","Slot","CollapsibleContent","ChatCardContent","hasPadding","hasHeaderPadding","ChatCardPreview","ChatCardFooter","ChatCardFooterNotes","ChatCardFooterPrice","ChatCardFooterActions","ChatCardForm","forwardRef","ChatCardAttributes","ChatCardAttribute","ChatCardAttributeLabel","Chip","ChatCardAttributeValue","ChatCard","openProp","isControlled","uncontrolledOpen","setUncontrolledOpen","useState","defaultOpen","open","handleOpenChange","useCallback","next","onOpenChange","contextValue","useMemo","event","Collapsible","isSelected","variant","fullWidth","isRounded","useEditChatCard","isEditing","setIsEditing","defaultEditing","checkIsEditable","isEditable","startEdit","discard","toggleEdit","EditableChatCardContext","useEditableChatCardContext","EditableChatCardContextProvider","ChatCardContainer","inline","DEFAULT_CONTENT_WIDTH","SLOT_VARIABLES","toCssLength","value","ChatContainerContext","useChatContainerContext","ChatContainer","Comp","useElementMeasure","slotHeights","setSlotHeights","setSlotHeight","current","slot","slotHeight","containerStyle","width","height","contentWidth","style","useChatContainerSlot","useLayoutEffect","ref","ChatContainerPrompt","ChatContainerWelcome","AutoFocusPlugin","editor","useLexicalComposerContext","useEffect","autoFocus","activeElement","rootElement","defaultSelection","isDisabled","EXPORT_TRANSFORMERS$1","TRANSFORMERS","IMPORT_TRANSFORMERS$1","useChatInputEditor","$getEditorPlainText","$getRoot","$setSelectionToEnd$1","lastDescendant","$isTextNode","selection","$createRangeSelection","endOffset","$setSelection","$getSelection","$isRangeSelection","focusNode","focusOffset","ControlledValuePlugin$1","previousValueRef","useRef","emittedValuesRef","echoIndex","currentValue","$convertToMarkdownString","$addUpdateTag","SKIP_DOM_SELECTION_TAG","$convertFromMarkdownString","DisabledPlugin$1","isReadOnly","FocusPlugin$1","onFocusChange","handleFocus","handleBlur","getHasValue","hasValue","syncHasValue","lastHasValueRef","onHasValueChange","HasValuePlugin","MarkdownPlainPastePlugin$1","PASTE_COMMAND","clipboardData","plainText","root","paragraph","$createParagraphNode","line","$createTextNode","COMMAND_PRIORITY_CRITICAL","MAX_EMITTED_VALUES$1","ValuePlugin$1","handleChange","onChange","error","OnChangePlugin","ChatInputContext","useChatInputContext","DEFAULT_CONFIG","HeadingNode","QuoteNode","ListNode","ListItemNode","CodeNode","LinkNode","ChatInput","hasError","setHasError","setHasValue","isFocused","setIsFocused","LexicalComposer","ChatInputPlaceholder","ChatInputTextarea","isReadOnlyState","RichTextPlugin","ContentEditable","placeholder","placeholderClassName","LexicalErrorBoundary","HistoryPlugin","children","ChatListContext","useChatListContext","ChatList","hasMoreProp","ariaLabel","scrollElementRef","loadMoreContentRef","loadMoreVersion","setLoadMoreVersion","skeletonContainer","setSkeletonContainer","setScrollElementVersion","setScrollElement","node","version","bumpLoadMore","hasMore","totalCount","loadedCount","isEmpty","isLoading","isLoadingMore","onLoadMore","getItemKey","TITLE_WIDTHS","PREVIEW_WIDTHS","ChatListSkeleton","createPortal","rows","rowClassName","Skeleton","index","ChatListEmptyState","ChatListError","messageClassName","ChatListLoadMore","LOAD_MORE_KEY","ChatListItems","memo","loadMoreContent","showSkeleton","count","getItemKeyStable","virtualizer","useVirtualizer","estimateSize","virtualItems","lastItem","ScrollArea","MenuList","listClassName","isLoaderRow","virtualItem","ChatListItem","ChatPromptBoxContext","useChatPromptBoxContext","ChatPromptBoxContextProvider","focusInputRef","registerFocusInput","focus","unregisterFocusInput","focusInput","reportInputHeight","resetCompact","ChatPromptBoxFocusPlugin","COMPACT_INPUT_HEIGHT_THRESHOLD","INTERACTIVE_SELECTOR","shouldSkipFocus","target","ChatPromptBox","isCompact","setIsCompact","ChatPromptBoxContainer","props","handleMouseDown","onMouseDown","innerClassName","ChatPromptBoxFocusRadials","Fragment","ChatPromptBoxToolbar","ChatPromptBoxContent","ChatPromptBoxInput","measureRef","setRef","element","textareaClassName","ChatPromptBoxActionsLeft","ChatPromptBoxActionsRight","ChatMessage","isQuestion","ChatMessageContent","ChatMessageActions","getNewChatId","nanoid","ChatContext","useChatContext","ChatProvider","chatIdProp","newChatId","setNewChatId","promptPlaceholder","setPromptPlaceholderState","loadedChatIdsRef","chatId","isNewChat","goToNewChat","nextChatId","setPromptPlaceholder","clearPromptPlaceholder","LAST_ITEM_SCROLL_MAX_COUNT","USER_SCROLL_INTENT_IDLE_MS","ChatConversationContext","useChatConversationContext","ChatConversationProvider","_chatId","isAtBottom","setIsAtBottom","debugInfo","setDebugInfo","viewportNodeRef","bottomTriggerNodeRef","lastItemNodeRef","resizeObserverRef","viewportResizeObserverRef","bottomTriggerObserverRef","messageCountRef","isAtBottomRef","isSmoothScrollRef","hasUserEscapedRef","isProgrammaticScrollRef","userScrollIntentRef","userScrollIntentTimeoutRef","lastScrollTopRef","scrollStrategyRef","lastViewportScrollHeightRef","scrollRef","attachLastItemResizeObserverRef","detachLastItemResizeObserverRef","syncDebugInfoRef","debug","detachLastItemResizeObserver","detachBottomTriggerObserver","detachViewportResizeObserver","syncAtBottomFromViewportRef","clearProgrammaticScroll","clearUserScrollIntent","markUserScrollIntent","applyLastItemScrollStrategy","setHasUserEscaped","hasUserEscaped","scroll","behavior","stickScrollToEnd","scrollHeight","syncAtBottomFromViewport","atBottom","attachViewportResizeObserver","observer","attachLastItemResizeObserver","applyEndScrollStrategy","handleBottomTriggerVisibility","isVisible","handleScroll","lastScrollTop","currentScrollTop","isScrollingUp","handleWheel","handleTouchStart","handlePointerDown","attachBottomTriggerObserver","entry","viewportRef","bottomTriggerRef","lastItemRef","previousNode","setMessageCount","reset","scrollBottom","scrollToLatest","ChatMessagesContext","ChatMessagesListRowContext","useChatMessagesContext","ChatMessages","messageCount","gap","ChatMessagesList","lastIndex","scrollAreaClassName","viewportClassName","ChatMessagesListRow","bottomTriggerClassName","ChatMessagesScrollBar","isLast","ChatMessageListGroup","orientation","ChatMessagesScrollButton","buttonClassName","ChevronDownIcon","ChatMessageAttachmentCard","isPreview","isInteractive","ChatMessageAttachmentCardContent","ChatMessageAttachmentCardTitle","ChatMessageAttachmentCardPreview","previewSrc","imageClassName","ChatMessageAttachmentCardActions","onDelete","CloseIcon","CHAT_ATTACHMENT_ICON_MAP","XlsIcon","PdfIcon","PptIcon","DocIcon","CodeIcon","DraftIcon","ChatMessageAttachmentCardIcon","Icon","iconClassName","icon","MIME_TO_ICON","getAttachmentIcon","mimeType","file","isCustomComponentTag","tag","useMarkdownViewer","swiTags","customComponents","key","defaultRemarkPlugins","defaultRehypePlugins","defaultSchema","MarkdownViewer","Streamdown","hasCaret","isStreaming","swiTagHandler","markdown","incompleteMatch","tagName","text","separator","openingTagRegex","openingTags","match","lastTag","closingTag","ChatMessageResponse","message","ChatMessageToolbar","reverse","ChatMessageToolbarActions","ChatMessageToolbarActionButton","ChatMessageToolbarTimestamp","getSnoozeUntilDate","minutes","MINUTES_PER_HOUR","MINUTES_PER_DAY","MILLISECONDS_PER_MINUTE","formatDurationPart","unit","formatSnoozeDate","totalMinutes","date","now","days","hours","parts","prefix","ChatNotificationCardContext","useChatNotificationCardContext","ChatNotificationCard","internalExpanded","setInternalExpanded","defaultExpanded","isExpanded","expanded","setExpanded","nextExpanded","onExpandedChange","toggleExpanded","overlayClassName","ChatNotificationCardHead","ChatNotificationCardHeader","ChatNotificationCardHeaderIcon","ChatNotificationCardHeaderTitle","ChatNotificationCardHeaderTitleLabel","CHIP_PRIORITY_MAP","ChatNotificationCardHeaderStatus","color","priority","ChatNotificationCardActions","ChatNotificationCardTimestamp","ChatNotificationCardButtons","ChatNotificationCardReadActionButton","isRead","jsx","SignalUnreadIcon","SignalReadIcon","ChatNotificationCardSnoozeButton","isHovered","setIsHovered","isSnoozed","snoozeUntilDate","handleMouseEnter","onMouseEnter","handleMouseLeave","onMouseLeave","handleCancel","onCancel","Button","SnoozeIcon","labelClassName","formatDate","cancelLabelClassName","cancelLabel","ChatNotificationCardDeleteButton","DeleteIcon","ChatNotificationCardCloseButton","ChatNotificationCardContent","ChatNotificationCardExpandButton","ChatNotificationCardContentTitle","ChatNotificationCardContentDescription","ChatNotificationCardContentActions","ChevronUpIcon","ChatNotificationCardIcon","ChatNotificationCardDescription","ChatNotificationCardTimeStamp","ChatNotificationPopup","Popover","ChatNotificationPopupTrigger","PopoverTrigger","ChatNotificationPopupContent","PopoverContent","ChatReplies","ChatReply","isMultiline","ChatReplyLabel","ChatReplyValue","ChatSuggestionContext","useChatSuggestionContext","ChatSuggestions","List","Children","isValidElement","child","cloneElement","ChatSuggestion","onHover","ListItem","listItemVariants","ListItemTrigger","triggerClassName","ChatSuggestionLabelIcon","ChatSuggestionLabel","ListItemTitle","ChatSuggestionActions","ChatSuggestionAction","ListItemAction","withForwardedRef","Primitive","displayName","ViewportPrimitive","MessageScroller","ContentPrimitive","ItemPrimitive","assignRef","DEFAULT_SCROLL_MARGIN","GROUP_MIN_HEIGHT_VAR","NOOP_COMMANDS","ChatThreadCommandsContext","useChatThread","ChatThreadCommandsBridge","useMessageScroller","commands","scrollToEnd","scrollToMessage","scrollToStart","ChatThreadSessionContext","useChatThreadSession","session","component","createSessionState","conversationId","groupIds","ChatThreadProvider","scrollMode","sessionState","setSessionState","scrollMargin","knownGroupIds","FollowNewGroups","lastGroupId","ChatThread","isAnchored","viewportElementRef","contentElementRef","setViewport","setContent","contentRef","useGroupMinHeight","contentClassName","ChatThreadErrorState","renderError","scrollButton","ChatThreadScrollButton","scrollButtonClassName","scrollButtonTooltip","viewport","isEnabled","update","minHeight","paddingTop","paddingBottom","ChatThreadGroup","isNew","groupId","ChatThreadQuestion","messageId","ChatThreadAnswer","hasContentBelow","useMessageScrollerScrollable","_children","inert","ChatArtifact","Card","ChatArtifactIcon","CardIcon","ChatArtifactContent","ChatArtifactTitle","CardTitle","ChatArtifactCaption","CardDescription","ChatArtifactActions","CardAction","CanvasShell","PanelProvider","Panel","CanvasShellHeader","PanelHeader","CanvasShellTitle","PanelTitle","CanvasShellCloseTrigger","PanelActionCloseButton","CanvasShellFullScreenTrigger","PanelActionButton","isFullScreen","labels","OpenInFullIcon","CanvasShellOptionsButton","isOpen","setIsOpen","MenuProvider","MenuTrigger","MoreHorizontalIcon","Menu","menuClassName","canvasShellContentPadding","panelBodyPadding","CanvasShellContent","PanelContent","hasScroll","PanelBody","bodyClassName","CanvasShellFooter","PanelFooter","NewChatTrigger","ChatThinkingProcess","ChatThinkingProcessTrigger","ChatThinkingProcessTriggerIcon","ChatThinkingProcessTriggerLabel","ChatThinkingProcessTriggerArrow","ChatThinkingProcessContent","itemsClassName","ChatThinkingProcessContentItem","ChatThinkingProcessContentItemIcon","EmptyState","EmptyStateIcon","EmptyStateTitle","EmptyStateDescription","EmptyStateActionRow","defaultEditorTheme","ImageNode","DecoratorNode","src","altText","span","img","domNode","alt","$createImageNode","json","$isImageNode","extractFontStyles","fontSizeRegex","fontFamilyRegex","colorRegex","fontSizeMatch","fontFamilyMatch","colorMatch","FONT_STYLE_EXPORT","fontStyles","styleStr","FONT_STYLE_IMPORT","newNode","textNode","UNDERLINE_TRANSFORMER","getAlignment","alignmentMatch","ALIGNMENT_TRANSFORMER","alignment","parentNode","$isParagraphNode","exportChildren","IMAGE_EXPORT_TRANSFORMER","IMAGE_IMPORT_TRANSFORMER","imageNode","EXPORT_TRANSFORMERS","IMPORT_TRANSFORMERS","convertHeadingElement","nodeName","$createHeadingNode","align","setNodeIndentFromDOM","isDomChecklist","isHTMLElement","convertListElement","start","$createListNode","convertListItemElement","input","checked","$createListItemNode","ariaCheckedAttr","IMPORT_PRIORITY","convertSpanElementWithStyles","fontSize","fontFamily","domStyle","lexicalNode","fontWeight","textDecoration","HTML_IMPORT_CONFIG","wrapExportWithStyle","result","OriginalClass","HTML_EXPORT_CONFIG","DivBlockNode","ElementNode","div","prevStyle","prevNode","nextStyle","convertDivElement","$createDivBlockNode","serializedNode","updated","MAX_EMITTED_VALUES","ValuePlugin","source","$generateHtmlFromNodes","useRichTextAreaEditor","useRichTextAreaSelectedText","selectedText","DisabledPlugin","ControlledPlugin","editorRef","useImperativeHandle","controlledRef","EditorRefPlugin","scrollRichTextAreaToBottom","$setSelectionToEnd","getHTMLNodesFromValue","dom","html","$generateNodesFromDOM","p","$replaceEditorHTMLContent","$replaceEditorSelectionHTMLContent","nodes","ControlledValuePlugin","shouldScrollOnInitialValueRef","isDesktop","useIsResolution","BlurPlugin","onBlur","FocusPlugin","INSERT_IMAGE_COMMAND","createCommand","INSERT_IMAGE_EVENT_NAME","ImageAddedEvent","payload","ImageDropPlugin","COMMAND_PRIORITY_EDITOR","handleInsertImage","customEvent","PASTE_HTML_COMMAND","INSERT_HTML_COMMAND","PASTE_HTML_EVENT","INSERT_HTML_EVENT","PasteHtmlEvent","InsertHtmlEvent","HtmlPastePlugin","handlePasteHtml","handleInsertHtml","MarkdownPlainPastePlugin","ATTACH_FILE_COMMAND","FileAttachmentPlugin","inputRef","files","isMultiple","acceptedFiles","Wrapper","INITIAL_CONFIG","TableNode","TableCellNode","TableRowNode","RichTextAreaImpl","containerClassName","name","onKeyDown","forwardedRef","TablePlugin","RichTextArea","DEFAULT_FONT_FAMILY","FONT_FAMILY_OPTIONS","DEFAULT_FONT_FAMILY_VALUE","FONT_SIZE_OPTIONS","DEFAULT_ALIGNMENT","DEFAULT_TEXT_COLOR","ToolbarSelect","SelectField","toAlignment","format","ALIGNMENT_OPTIONS_MAP","FormatAlignLeftIcon","FormatAlignCenterIcon","FormatAlignRightIcon","AlignmentSelect","setValue","options","$updateValue","parent","$isElementNode","mergeRegister","SELECTION_CHANGE_COMMAND","COMMAND_PRIORITY_LOW","FORMAT_ELEMENT_COMMAND","ToolbarButton","AttachmentButton","AttachmentsIcon","getStyleObjectFromRawCSS","styleObject","token","css","NO_STYLE","parse","v","unparse","styles","k","isEqualValue","a","b","isEqual","styleState","createState","$setStyleObject","$setState","valueOrUpdater","mergeStyleObjects","prevStyles","nextStyles","$patchSelectedTextStyle","prevSelection","$getPreviousSelection","styleCallback","styleObjectOrCallback","getSelectedNode","anchor","anchorNode","$isAtNodeEnd","updateFontSizeInSelection","skipRefocus","$patchStyleText","newFontSize","sanitizeUrl","url","RichTextFieldContext","useRichTextFieldContext","normalizeColorToHex","trimmed","hexMatch","r","g","rgbMatch","clamp","n","toHex","RichTextFieldContextProvider","setFontFamily","setFontSize","isBold","setIsBold","isItalic","setIsItalic","isUnderline","setIsUnderline","textColor","setTextColor","isLink","setIsLink","$updateToolbar","$getSelectionStyleValueForProperty","rawColor","$isLinkNode","onFontFamily","SKIP_SELECTION_FOCUS_TAG","onFontSize","onBold","FORMAT_TEXT_COMMAND","onItalic","onUnderline","onTextColor","onLink","TOGGLE_LINK_COMMAND","BoldButton","FormatBoldIcon","CleanFormatButton","$getNearestBlockElementAncestorOrThrow","FormatCleanIcon","ImageButton","ImageIcon","ItalicButton","FormatItalicIcon","LinkButton","isActive","LinkOnIcon","LinkOffIcon","SizeSelect","TextColorButton","isDefaultColor","handleColorChange","wrapperClassName","FormatColorIcon","TypographySelect","UnderlineButton","FormatUnderlineIcon","DefaultFormattingToolbarChildren","Divider","hasAttachments","FormattingToolbarPlugin","RichTextField","isToolbarTop","toolbarPlacement","enableAttachments","toolbarClassName","toolbarChildren","isMultipleAttachments","topMenuActionsVariants","cva","TopMenu","TopMenuActions","size","CHAT_ACTION_PROTOCOL","createChatActionURL","action","params","createChatActionLink","label","isChatActionURL","uri","extractChatActionMetadataFromUrl","link","extractLabelFromNode","extractChatActionFromLink","ast","unified","visit","metadata","useChatActions","actions","defaultTokenParser","data","isAbortError","toError","fallbackMessage","useChatStreamMessage","parseToken","tokenParser","timeoutId","didHandleAbort","clearStreamTimeout","handleAbort","onAbort","resetStreamTimeout","timeout","abortController","decoder","parser","createParser","onChunkReceived","e","stream","chunk","done","onFinish","onError","useOnChatChanged","isNewChatRef","prevChatIdRef","chatChangedFn","onChatChanged","useCurrentChatId","useIsCurrentChatNew","useChatLoadedIds","useChatPromptPlaceholder"],"sources":["../src/components/chat-card/context.tsx","../src/components/chat-card/components/chat-card-header.tsx","../src/components/chat-card/components/chat-card-body.tsx","../src/components/chat-card/components/chat-card-footer.tsx","../src/components/chat-card/components/chat-card-form.tsx","../src/components/chat-card/chat-card.tsx","../src/components/chat-card/hooks.ts","../src/components/chat-card/contexts.tsx","../src/components/chat-card-container/chat-card-container.tsx","../src/components/chat-container/chat-container.tsx","../src/components/chat-input/plugins/auto-focus-plugin.tsx","../src/components/chat-input/transformers.ts","../src/components/chat-input/plugins/hooks.ts","../src/components/chat-input/plugins/utils.ts","../src/components/chat-input/plugins/controlled-value-plugin.tsx","../src/components/chat-input/plugins/disabled-plugin.tsx","../src/components/chat-input/plugins/focus-plugin.tsx","../src/components/chat-input/plugins/has-value-plugin.tsx","../src/components/chat-input/plugins/markdown-plain-paste-plugin.tsx","../src/components/chat-input/plugins/value-plugin.tsx","../src/components/chat-input/chat-input.tsx","../src/components/chat-list/chat-list.tsx","../src/components/chat-list/chat-list-items.tsx","../src/components/chat-list/chat-list-item.tsx","../src/components/chat-prompt-box/chat-prompt-box-context.tsx","../src/components/chat-prompt-box/chat-prompt-box-focus-plugin.tsx","../src/components/chat-prompt-box/chat-prompt-box.tsx","../src/components/chat-message/chat-message.tsx","../src/contexts/chat-context/utils.ts","../src/contexts/chat-context/chat-context.tsx","../src/contexts/chat-conversation-context/chat-conversation-context.tsx","../src/components/chat-messages/chat-messages.tsx","../src/components/chat-message-attachment-card/chat-message-attachment-card.tsx","../src/components/chat-message-attachment-card/chat-message-attachment-card-icon.tsx","../src/components/chat-message-attachment-card/utils.ts","../src/components/markdown-viewer/utils.ts","../src/components/markdown-viewer/hooks.ts","../src/components/markdown-viewer/markdown-viewer.tsx","../src/components/chat-message-response/chat-message-response.tsx","../src/components/chat-message-toolbar/chat-message-toolbar.tsx","../src/components/chat-notification-card/utils.ts","../src/components/chat-notification-card/chat-notification-card.tsx","../src/components/chat-notification-popup/chat-notification-popup.tsx","../src/components/chat-reply/chat-reply.tsx","../src/components/chat-suggestion/chat-suggestion.tsx","../src/components/chat-thread/chat-thread.tsx","../src/components/chat-artifact/chat-artifact.tsx","../src/components/canvas-shell/canvas-shell.tsx","../src/components/new-chat-trigger/new-chat-trigger.tsx","../src/components/chat-thinking-process/chat-thinking-process.tsx","../src/components/deprecated-empty-state.ts","../src/components/rich-text-area/constants/index.ts","../src/components/rich-text-area/nodes/image-node.tsx","../src/components/rich-text-area/transformers.ts","../src/components/rich-text-area/html-config.ts","../src/components/rich-text-area/nodes/div-block-node.tsx","../src/components/rich-text-area/plugins/value-plugin.tsx","../src/components/rich-text-area/hooks.ts","../src/components/rich-text-area/plugins/disabled-plugin.tsx","../src/components/rich-text-area/plugins/controlled-plugin.tsx","../src/components/rich-text-area/utils/index.ts","../src/components/rich-text-area/plugins/controlled-value-plugin.tsx","../src/components/rich-text-area/plugins/blur-plugin.tsx","../src/components/rich-text-area/plugins/focus-plugin.tsx","../src/components/rich-text-area/plugins/image-drop-plugin.tsx","../src/components/rich-text-area/plugins/html-paste-plugin.tsx","../src/components/rich-text-area/plugins/markdown-plain-paste-plugin.tsx","../src/components/rich-text-area/plugins/file-attachment-plugin.tsx","../src/components/rich-text-area/styled.tsx","../src/components/rich-text-area/rich-text-area.tsx","../src/components/rich-text-field/constants.ts","../src/components/rich-text-field/components/toolbar-select.tsx","../src/components/rich-text-field/components/alignment-select.tsx","../src/components/rich-text-field/components/toolbar-button.tsx","../src/components/rich-text-field/components/attachment-button.tsx","../src/components/rich-text-field/utils.ts","../src/components/rich-text-field/context.tsx","../src/components/rich-text-field/components/bold-button.tsx","../src/components/rich-text-field/components/clean-format-button.tsx","../src/components/rich-text-field/components/image-button.tsx","../src/components/rich-text-field/components/italic-button.tsx","../src/components/rich-text-field/components/link-button.tsx","../src/components/rich-text-field/components/size-select.tsx","../src/components/rich-text-field/components/text-color-button.tsx","../src/components/rich-text-field/components/typography-select.tsx","../src/components/rich-text-field/components/underline-button.tsx","../src/components/rich-text-field/components/formatting-toolbar-plugin.tsx","../src/components/rich-text-field/rich-text-field.tsx","../src/components/topmenu/topmenu.tsx","../src/domain/actions/constants.ts","../src/domain/actions/utils/index.ts","../src/domain/actions/hooks/index.ts","../src/hooks/use-chat-stream-message.ts","../src/hooks/use-on-chat-changed.ts","../src/hooks/use-current-chat-id.ts","../src/hooks/use-is-current-chat-new.ts","../src/hooks/use-loaded-chat-ids.ts","../src/hooks/use-chat-prompt-placeholder.ts"],"sourcesContent":["import { createContext, useContext, type ReactNode } from 'react';\n\nimport type { ChatCardLevel } from './types';\n\nexport interface ChatCardContextValue {\n isCollapsible: boolean;\n level: ChatCardLevel;\n open: boolean;\n}\n\nconst ChatCardContext = createContext<ChatCardContextValue | null>(null);\n\nexport function useChatCardContext() {\n const context = useContext(ChatCardContext);\n\n if (!context) {\n throw new Error(\n '[web-chat-ui] useChatCardContext() called outside ChatCard. ' +\n 'Wrap this component in <ChatCard>, or the provider and the caller resolved two copies of the package.',\n );\n }\n\n return context;\n}\n\nexport function ChatCardProvider({\n value,\n children,\n}: {\n value: ChatCardContextValue;\n children: ReactNode;\n}) {\n return <ChatCardContext.Provider value={value}>{children}</ChatCardContext.Provider>;\n}\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport {\n CollapsibleChevron,\n CollapsibleTrigger,\n IconButton,\n Tooltip,\n Typography,\n type IconButtonProps,\n type TypographyProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatCardContext } from '../context';\n\n/** @deprecated Use `CardHeaderProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardHeaderProps extends Omit<ComponentProps<'header'>, 'aria-label'> {\n children: ReactNode;\n /**\n * Classes for the inner row that wraps the children (`data-slot=\"chat-card-header-hover-area\"`):\n * the element that highlights on hover and, in a collapsible card, toggles it.\n */\n hoverAreaClassName?: string;\n}\n\n/** @deprecated Use `CardHeader` from `@swisper.ai/cards-ui`. */\nexport function ChatCardHeader({\n className,\n children,\n hoverAreaClassName,\n ...rest\n}: ChatCardHeaderProps) {\n const { isCollapsible, level } = useChatCardContext();\n\n const inner = (\n <div\n data-slot=\"chat-card-header-hover-area\"\n className={cn(\n 'w-full',\n 'flex flex-row items-start',\n 'gap-card-header-gap',\n level === 1 && 'px-card-header-hover-area rounded-card-header',\n level === 1 && isCollapsible && 'hover:bg-layout-accent-low-background-hover-base',\n level === 1 && 'group-hover/chat-card:bg-layout-accent-low-background-hover-base',\n !isCollapsible && 'cursor-default',\n hoverAreaClassName,\n )}\n >\n {children}\n </div>\n );\n\n return (\n <header\n data-slot=\"chat-card-header\"\n data-level={level}\n data-collapsible={isCollapsible}\n className={cn(\n 'flex items-start',\n level === 1 ? 'p-card-header-lvl-1' : 'px-card-header-lvl-2',\n className,\n )}\n {...rest}\n >\n {isCollapsible ? (\n <CollapsibleTrigger className=\"w-full\" asChild>\n {inner}\n </CollapsibleTrigger>\n ) : (\n inner\n )}\n </header>\n );\n}\n\n/** @deprecated Use `CardIconProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardIconProps extends ComponentProps<'div'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardIcon` from `@swisper.ai/cards-ui`. */\nexport function ChatCardIcon({ className, children, ...rest }: ChatCardIconProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n data-slot=\"chat-card-icon\"\n data-testid=\"chat-card-icon\"\n data-level={level}\n className={cn(\n 'shrink-0',\n 'inline-flex items-center justify-center self-center',\n 'size-[32px]',\n 'bg-avatar-background',\n 'rounded-full overflow-hidden',\n level === 1 ? 'my-[14px]' : 'my-4',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardHeaderContentProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardHeaderContentProps extends ComponentProps<'div'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardHeaderContent` from `@swisper.ai/cards-ui`. */\nexport function ChatCardHeaderContent({\n className,\n children,\n ...rest\n}: ChatCardHeaderContentProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n data-slot=\"chat-card-header-content\"\n data-testid=\"chat-card-header-content\"\n data-level={level}\n className={cn(\n 'flex-1',\n 'flex flex-col gap-0 items-start justify-center',\n level === 1 ? 'min-h-[60px] py-1.5' : 'min-h-[40px] py-4',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardTitleProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardTitleProps extends Omit<TypographyProps, 'variant'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardTitle` from `@swisper.ai/cards-ui`. */\nexport function ChatCardTitle({ className, children, ...rest }: ChatCardTitleProps) {\n return (\n <Typography\n data-testid=\"chat-card-title\"\n variant=\"body-medium\"\n className={cn(className)}\n {...rest}\n >\n {children}\n </Typography>\n );\n}\n\n/** @deprecated Use `CardSubTitleProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardSubTitleProps extends Omit<TypographyProps, 'variant'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardSubTitle` from `@swisper.ai/cards-ui`. */\nexport function ChatCardSubTitle({ className, children, ...rest }: ChatCardSubTitleProps) {\n return (\n <Typography\n data-testid=\"chat-card-sub-title\"\n variant=\"body-small-high\"\n className={cn('text-text-secondary', className)}\n {...rest}\n >\n {children}\n </Typography>\n );\n}\n\n/** @deprecated Use `CardActionsProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardActionsProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardActions` from `@swisper.ai/cards-ui`. */\nexport function ChatCardActions({ className, children, ...rest }: ChatCardActionsProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n role=\"group\"\n data-slot=\"chat-card-actions\"\n data-testid=\"chat-card-actions\"\n data-level={level}\n className={cn(\n 'ml-auto shrink-0',\n 'flex items-center self-center gap-card-header-gap-icon-buttons',\n 'min-h-[32px]',\n '[&>button]:text-secondary-main!',\n level === 1 ? 'my-[14px]' : 'my-4',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardActionButtonProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardActionButtonProps extends Omit<IconButtonProps, 'variant' | 'size'> {\n children: ReactNode;\n shouldPreventCollapse?: boolean;\n tooltip?: ReactNode;\n}\n\n/** @deprecated Use `CardActionButton` from `@swisper.ai/cards-ui`. */\nexport function ChatCardActionButton({\n className,\n children,\n shouldPreventCollapse = true,\n tooltip,\n onClick,\n ...rest\n}: ChatCardActionButtonProps) {\n function handleClick(e: React.MouseEvent<HTMLButtonElement>) {\n if (shouldPreventCollapse) {\n e.stopPropagation();\n }\n\n onClick?.(e);\n }\n\n const content = (\n <IconButton\n data-slot=\"chat-card-action-button\"\n variant=\"tertiary\"\n size=\"sm\"\n className={cn(className)}\n onClick={handleClick}\n {...rest}\n >\n {children}\n </IconButton>\n );\n\n if (!tooltip) {\n return content;\n }\n\n return <Tooltip tooltip={tooltip}>{content}</Tooltip>;\n}\n\n/** @deprecated Use `CardCollapsibleButtonProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardCollapsibleButtonProps extends Omit<\n ChatCardActionButtonProps,\n 'children' | 'shouldPreventCollapse'\n> {}\n\n/** @deprecated Use `CardCollapsibleButton` from `@swisper.ai/cards-ui`. */\nexport function ChatCardCollapsibleButton({ className, ...rest }: ChatCardCollapsibleButtonProps) {\n const { isCollapsible } = useChatCardContext();\n if (!isCollapsible) {\n return;\n }\n\n return (\n <ChatCardActionButton\n data-slot=\"chat-card-collapsible-button\"\n shouldPreventCollapse={false}\n isSemantic={false}\n className={className}\n {...rest}\n >\n <CollapsibleChevron className=\"size-16\" />\n </ChatCardActionButton>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport type { ComponentProps, ReactNode } from 'react';\n\nimport { CollapsibleContent } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatCardContext } from '../context';\n\n/** @deprecated Use `CardMediaProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardMediaProps extends Omit<ComponentProps<'figure'>, 'aria-label'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardMedia` from `@swisper.ai/cards-ui`. */\nexport function ChatCardMedia({ className, children, ...rest }: ChatCardMediaProps) {\n return (\n <figure\n data-slot=\"chat-card-media\"\n data-testid=\"chat-card-media\"\n className={cn('min-h-0 shrink-0 h-[222px]', className)}\n {...rest}\n >\n {children}\n </figure>\n );\n}\n\n/** @deprecated Use `CardBodyProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardBodyProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** @deprecated Use `CardBody` from `@swisper.ai/cards-ui`. */\nexport function ChatCardBody({ className, children, asChild = false, ...rest }: ChatCardBodyProps) {\n const Component = asChild ? Slot : 'div';\n\n return (\n <CollapsibleContent\n data-slot=\"chat-card-body\"\n data-testid=\"chat-card-body\"\n className={cn(\n 'flex flex-1 flex-col',\n 'min-h-0',\n 'md:group-data-[collapsible=true]/cards-ui-card:max-h-[calc(var(--chat-window-height)*0.9)]',\n 'overflow-hidden',\n className,\n )}\n asChild\n {...rest}\n >\n <Component>{children}</Component>\n </CollapsibleContent>\n );\n}\n\n/** @deprecated Use `CardContentProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardContentProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n asChild?: boolean;\n hasPadding?: boolean;\n hasHeaderPadding?: boolean;\n}\n\n/** @deprecated Use `CardContent` from `@swisper.ai/cards-ui`. */\nexport function ChatCardContent({\n className,\n children,\n asChild = false,\n hasPadding = true,\n hasHeaderPadding = true,\n ...rest\n}: ChatCardContentProps) {\n const { level } = useChatCardContext();\n const Component = asChild ? Slot : 'div';\n\n return (\n <Component\n data-slot=\"chat-card-content\"\n data-testid=\"chat-card-content\"\n data-padding={hasPadding}\n data-has-header-padding={hasHeaderPadding}\n data-level={level}\n className={cn(\n 'overflow-auto',\n 'gap-card-slots-gap',\n 'data-[level=1]:p-card-slots-lvl-1',\n 'data-[level=2]:p-card-slots-lvl-2',\n 'data-[has-header-padding=false]:pt-0',\n 'data-[padding=false]:p-0',\n className,\n )}\n {...rest}\n >\n {children}\n </Component>\n );\n}\n\n/** @deprecated Use `CardPreviewProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardPreviewProps extends ComponentProps<'div'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardPreview` from `@swisper.ai/cards-ui`. */\nexport function ChatCardPreview({ className, children, ...rest }: ChatCardPreviewProps) {\n const { level } = useChatCardContext();\n\n return (\n <div\n data-slot=\"chat-card-preview\"\n data-testid=\"chat-card-preview\"\n data-level={level}\n className={cn(\n 'group-data-[state=open]/collapsible:hidden',\n 'overflow-auto',\n 'pt-0',\n 'data-[level=1]:p-card-slots-lvl-1',\n 'data-[level=2]:p-card-slots-lvl-2',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatCardContext } from '../context';\n\n/** @deprecated Use `CardFooterProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterProps extends ComponentProps<'footer'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardFooter` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooter({ className, children, ...rest }: ChatCardFooterProps) {\n const { level } = useChatCardContext();\n\n return (\n <footer\n data-slot=\"chat-card-footer\"\n data-level={level}\n className={cn(\n 'mt-auto',\n 'flex flex-row items-center justify-end',\n 'gap-card-footer-gap',\n 'w-full',\n 'data-[level=1]:p-card-footer-lvl-1',\n 'data-[level=2]:p-card-footer-lvl-2',\n className,\n )}\n {...rest}\n >\n {children}\n </footer>\n );\n}\n\n/** @deprecated Put your own block in `CardFooterLeft` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterNotesProps {\n children: ReactNode;\n className?: string;\n}\n\n/** @deprecated Put your own block in `CardFooterLeft` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooterNotes({ className, children }: ChatCardFooterNotesProps) {\n return (\n <div\n data-slot=\"chat-card-footer-notes\"\n data-testid=\"chat-card-footer-notes\"\n className={cn(\n 'mr-auto shrink-0',\n 'flex flex-col items-start justify-center',\n 'gap-card-footer-gap-left-notes',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Put your own block in `CardFooterRight` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterPriceProps {\n children: ReactNode;\n className?: string;\n}\n\n/** @deprecated Put your own block in `CardFooterRight` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooterPrice({ className, children }: ChatCardFooterPriceProps) {\n return (\n <div\n data-slot=\"chat-card-footer-price\"\n data-testid=\"chat-card-footer-price\"\n className={cn(\n 'flex flex-col items-end justify-center',\n 'gap-card-footer-gap-prices',\n 'shrink-0',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\n/** @deprecated Use `CardFooterActionsProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFooterActionsProps extends Omit<ComponentProps<'div'>, 'aria-label'> {\n children: ReactNode;\n}\n\n/** @deprecated Use `CardFooterActions` from `@swisper.ai/cards-ui`. */\nexport function ChatCardFooterActions({\n className,\n children,\n ...rest\n}: ChatCardFooterActionsProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-card-footer-actions\"\n data-testid=\"chat-card-footer-actions\"\n className={cn('flex items-center gap-card-footer-gap shrink-0', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport { forwardRef } from 'react';\nimport type { ComponentProps, ReactNode } from 'react';\n\nimport { Chip, Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\n/** @deprecated Use `CardFieldsProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardFormProps extends ComponentProps<'form'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** @deprecated The props of `ChatCardForm` under the component's own name; use `ChatCardFormProps`. */\nexport interface ChatCardForm extends ChatCardFormProps {}\n\n/** @deprecated Use `CardFields` from `@swisper.ai/cards-ui`. */\nexport const ChatCardForm = forwardRef<HTMLFormElement, ChatCardFormProps>(function ChatCardForm(\n { className, children, asChild, ...rest },\n ref,\n) {\n const Component = asChild ? Slot : 'form';\n\n return (\n <Component\n ref={ref}\n data-slot=\"chat-card-form\"\n data-testid=\"chat-card-form\"\n className={cn(\n 'bg-steel-900 border border-steel-700',\n 'rounded-[12px]',\n 'm-8 mb-16 p-[12px]',\n 'overflow-hidden',\n className,\n )}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardForm.displayName = 'ChatCardForm';\n\n/** @deprecated Use `CardAttributesProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributesProps {\n children: ReactNode;\n className?: string;\n}\n\n/** @deprecated Use `CardAttributes` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttributes({ className, children }: ChatCardAttributesProps) {\n return (\n <ul\n data-slot=\"chat-card-attributes\"\n data-testid=\"chat-card-attributes\"\n className={cn('flex flex-col justify-start items-start gap-8', 'mb-24', className)}\n >\n {children}\n </ul>\n );\n}\n\n/** @deprecated Use `CardAttributeProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributeProps {\n className?: string;\n children: ReactNode;\n}\n\n/** @deprecated Use `CardAttribute` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttribute({ className, children, ...rest }: ChatCardAttributeProps) {\n return (\n <li\n data-slot=\"chat-card-attribute\"\n data-testid=\"chat-card-attribute-item\"\n className={cn('grid grid-cols-[66px_1fr] gap-8', 'w-full', 'min-h-24', className)}\n {...rest}\n >\n {children}\n </li>\n );\n}\n\n/** @deprecated Use `CardAttributeLabelProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributeLabelProps {\n children: ReactNode;\n className?: string;\n hasPadding?: boolean;\n}\n\n/** @deprecated Use `CardAttributeLabel` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttributeLabel({\n className,\n children,\n hasPadding = false,\n ...rest\n}: ChatCardAttributeLabelProps) {\n return (\n <Chip\n variant=\"outlined\"\n size=\"md\"\n color=\"info\"\n data-slot=\"chat-card-attribute-label\"\n data-has-padding={hasPadding}\n className={cn('w-full', 'data-[has-padding=true]:my-[5px]', className)}\n data-testid=\"chat-card-attribute-label\"\n {...rest}\n >\n {children}\n </Chip>\n );\n}\n\n/** @deprecated Use `CardAttributeValueProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardAttributeValueProps extends Omit<ComponentProps<'dt'>, 'aria-Value'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** @deprecated Use `CardAttributeValue` from `@swisper.ai/cards-ui`. */\nexport function ChatCardAttributeValue({\n className,\n children,\n asChild = false,\n ...rest\n}: ChatCardAttributeValueProps) {\n const Component = asChild ? Slot : Typography;\n\n return (\n <Component\n data-testid=\"chat-card-attribute-value\"\n variant=\"body-sm\"\n className={cn('flex-1 text-text-secondary', className)}\n {...rest}\n >\n {children}\n </Component>\n );\n}\n","import { forwardRef, useCallback, useMemo, useState } from 'react';\n\nimport { Collapsible } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { ChatCardProvider } from './context';\nimport type { ChatCardProps } from './types';\n\nexport { useChatCardContext } from './context';\n\n/** @deprecated Use `Card` from `@swisper.ai/cards-ui`. */\nexport const ChatCard = forwardRef<HTMLElement, ChatCardProps>(function ChatCard(\n {\n className,\n variant = 'default',\n level = 1,\n children,\n fullWidth = false,\n defaultOpen = true,\n open: openProp,\n isRounded = true,\n isCollapsible = true,\n isSelected = false,\n onOpenChange,\n onClick,\n ...rest\n },\n ref,\n) {\n const isControlled = openProp !== undefined;\n const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n const open = isControlled ? openProp : uncontrolledOpen;\n\n const handleOpenChange = useCallback(\n (next: boolean) => {\n if (!isControlled) {\n setUncontrolledOpen(next);\n }\n onOpenChange?.(next);\n },\n [isControlled, onOpenChange],\n );\n\n const contextValue = useMemo(\n () => ({\n isCollapsible,\n level,\n open,\n }),\n [isCollapsible, level, open],\n );\n\n function handleClick(event: React.MouseEvent<HTMLElement>) {\n onClick?.(event);\n if (event.defaultPrevented) {\n return;\n }\n\n // Closed surface is the expand hit target. Never toggle here: an expanded\n // body/footer click must not collapse the card.\n if (isCollapsible && !open) {\n handleOpenChange(true);\n }\n }\n\n return (\n <ChatCardProvider value={contextValue}>\n <Collapsible isDisabled={!isCollapsible} open={open} onOpenChange={handleOpenChange} asChild>\n <section\n ref={ref}\n role=\"region\"\n data-slot=\"chat-card\"\n aria-current={isSelected}\n data-testid=\"chat-card\"\n data-variant={variant}\n data-level={level}\n data-full-width={fullWidth}\n data-rounded={isRounded}\n data-selected={isSelected}\n data-collapsible={isCollapsible}\n onClick={handleClick}\n className={cn(\n 'group/chat-card',\n // keep card smaller width in a closed state\n 'w-full data-[state=closed]:max-w-(--message-list-content-width) data-[state=closed]:mx-auto',\n 'flex flex-col',\n 'relative overflow-hidden',\n 'border border-solid border-card-border-base',\n 'data-[level=1]:bg-card-background-base',\n 'data-[level=2]:bg-card-background-lvl-2',\n 'data-[full-width=true]:w-full',\n 'data-[level=1]:data-[rounded=true]:rounded-card-lvl-1',\n 'data-[level=2]:data-[rounded=true]:rounded-card-lvl-2',\n 'data-[selected=true]:border-primary-main',\n 'hover:data-[variant=action]:bg-secondary-states-hover',\n 'data-[collapsible=true]:data-[state=closed]:cursor-pointer',\n className,\n )}\n {...rest}\n >\n {children}\n </section>\n </Collapsible>\n </ChatCardProvider>\n );\n});\n\nChatCard.displayName = 'ChatCard';\n","import { useState } from 'react';\n\ninterface UseEditChatCardProps {\n isEditable: boolean;\n defaultEditing?: boolean;\n}\n\n/** @deprecated `@swisper.ai/cards-ui` holds no edit state: keep `isEditing` in the app and pass it to `Card`'s `isSelected`. */\nexport function useEditChatCard({ isEditable, defaultEditing = false }: UseEditChatCardProps) {\n const [isEditing, setIsEditing] = useState(defaultEditing);\n\n function checkIsEditable() {\n if (!isEditable) {\n console.warn('Chat card is not editable');\n return false;\n }\n\n return true;\n }\n\n function startEdit() {\n if (!checkIsEditable()) {\n return;\n }\n\n setIsEditing(true);\n }\n\n function discard() {\n if (!checkIsEditable()) {\n return;\n }\n\n setIsEditing(false);\n }\n\n function toggleEdit() {\n if (!checkIsEditable()) {\n return;\n }\n\n setIsEditing((e) => !e);\n }\n\n return {\n isEditable,\n isEditing,\n startEdit,\n discard,\n toggleEdit,\n };\n}\n","import { type ReactNode, createContext, useContext } from 'react';\n\nimport { useEditChatCard } from './hooks';\n\ntype EditableChatCardContextValue = ReturnType<typeof useEditChatCard>;\n\nconst EditableChatCardContext = createContext<EditableChatCardContextValue>(null!);\n\n/** @deprecated `@swisper.ai/cards-ui` holds no edit state: keep `isEditing` in the app and pass it to `Card`'s `isSelected`. */\nexport function useEditableChatCardContext() {\n const context = useContext(EditableChatCardContext);\n\n if (!context) {\n throw new Error(\n '\"useEditableChatCardContext\" must be used within a EditableChatCardContextProvider',\n );\n }\n\n return context;\n}\n\ninterface EditableChatCardContextProviderProps {\n children: ReactNode;\n defaultEditing?: boolean;\n isEditable?: boolean;\n}\n\n/** @deprecated `@swisper.ai/cards-ui` holds no edit state: keep `isEditing` in the app and pass it to `Card`'s `isSelected`. */\nexport function EditableChatCardContextProvider({\n children,\n defaultEditing = false,\n isEditable = false,\n}: EditableChatCardContextProviderProps) {\n const contextValue = useEditChatCard({\n isEditable,\n defaultEditing,\n });\n\n return (\n <EditableChatCardContext.Provider value={contextValue}>\n {children}\n </EditableChatCardContext.Provider>\n );\n}\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\n/** @deprecated Use `FlexibleContainerVariant` from `@swisper.ai/cards-ui`. */\nexport type ChatCardContainerVariant = 'fixed' | 'fluid' | 'full';\n\n/** @deprecated Use `FlexibleContainerProps` from `@swisper.ai/cards-ui`. */\nexport interface ChatCardContainerProps extends ComponentProps<'div'> {\n children: ReactNode;\n /**\n * How the card is sized against the chat window published by `ChatContainer`:\n *\n * - `fixed` — clamped to the reading column (`--message-list-content-width`) from\n * `md` up, so body cards line up with the message text.\n * - `fluid` — shrinks to its content from `md` up, still capped at the window.\n * - `full` — always the full chat window width.\n *\n * Below `md` (820px in this design system, not Tailwind's default 768px) all three\n * are full width. There is no room to distinguish them on a phone, and a card\n * narrower than the viewport there reads as a layout bug.\n */\n variant?: ChatCardContainerVariant;\n /**\n * Set when the card is rendered inside a message body rather than as its own block,\n * so it aligns with the surrounding text.\n *\n * This swaps the inset from margin to padding rather than adding a second one: the\n * width cap opens up to the full `--chat-window-width` and `px-message` supplies the\n * gutter, so the total inset stays at one `--spacing-message` either way. Applying\n * `px-message` on top of the block cap instead would inset an inlined card by two\n * gutters and it would visibly not line up with the text around it.\n */\n inline?: boolean;\n}\n\n/**\n * Sizes a card inside a `ChatContainer`, against the `--chat-window-width` and\n * `--message-list-content-width` variables that container publishes.\n *\n * `full` is the base behaviour and adds no classes of its own — every variant starts\n * at the window width less one `--spacing-message` gutter, and `fixed` and `fluid`\n * narrow it from `md` up.\n *\n * Both variables are read with a `100%` fallback, so a card rendered outside a\n * `ChatContainer` (a portal, a test, a Storybook story) degrades to its parent's width\n * instead of collapsing to zero.\n *\n * @deprecated Use `FlexibleContainer` from `@swisper.ai/cards-ui`.\n */\nexport function ChatCardContainer({\n children,\n variant = 'fixed',\n inline = false,\n className,\n ...rest\n}: ChatCardContainerProps) {\n return (\n <div\n data-slot=\"chat-card-container\"\n data-testid=\"chat-card-container\"\n data-variant={variant}\n data-inline={inline}\n className={cn(\n 'mx-auto w-full',\n 'max-w-[calc(var(--chat-window-width,100%)-var(--spacing-message))]',\n 'md:data-[variant=fixed]:max-w-[calc(var(--message-list-content-width,var(--spacing-chat-area))-var(--spacing-message))]',\n 'md:data-[variant=fluid]:min-w-[calc(var(--message-list-content-width,var(--spacing-chat-area))-var(--spacing-message))]',\n 'md:data-[variant=fluid]:w-fit',\n 'md:data-[variant=full]:max-w-full',\n 'data-[inline=true]:max-w-[var(--chat-window-width,100%)]',\n 'data-[inline=true]:px-message',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport {\n createContext,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useState,\n type ComponentProps,\n type CSSProperties,\n type ReactNode,\n} from 'react';\n\nimport { cn, useElementMeasure } from '@swisper.ai/web-core';\n\n/**\n * Width of the reading column when the consumer does not override it.\n *\n * Read from `--spacing-chat-area` (736px) rather than hardcoded, so a theme that\n * retunes the chat area token moves the reading column with it.\n */\nconst DEFAULT_CONTENT_WIDTH = 'var(--spacing-chat-area)';\n\n/**\n * The slots a child can measure itself into, and the custom property each publishes.\n *\n * These two heights cannot be measured by `ChatContainer` itself — they belong to\n * specific children whose size the rest of the layout has to react to (the composer\n * grows as the user types; the welcome box only exists on an empty chat). The slot\n * reports upward so the variable lands on the container, where *siblings* can read it\n * too; publishing it on the slot's own element would scope it to that subtree and the\n * message list could not size against it.\n */\nconst SLOT_VARIABLES = {\n prompt: '--type-window-height',\n welcome: '--welcome-screen-box-height',\n} as const;\n\ntype ChatContainerSlot = keyof typeof SLOT_VARIABLES;\n\ntype MeasuredLength = number | 'unset';\n\n/** `unset` mirrors the pre-measurement state; for a height it computes as `auto`. */\nfunction toCssLength(value: MeasuredLength): string {\n return value === 'unset' ? 'unset' : `${value}px`;\n}\n\ninterface ChatContainerContextValue {\n setSlotHeight: (slot: ChatContainerSlot, height: MeasuredLength) => void;\n}\n\nconst ChatContainerContext = createContext<ChatContainerContextValue | null>(null);\n\nfunction useChatContainerContext() {\n const context = useContext(ChatContainerContext);\n\n if (!context) {\n throw new Error(\n '[web-chat-ui] ChatContainer slot rendered outside a ChatContainer. ' +\n 'ChatContainerPrompt and ChatContainerWelcome report their measured height up ' +\n 'to the container, so one must be mounted above them. If it is mounted, check ' +\n 'the slot is not rendered through a portal that escapes the provider.',\n );\n }\n\n return context;\n}\n\nexport interface ChatContainerProps extends ComponentProps<'section'> {\n children: ReactNode;\n /**\n * Max width of the reading column, published as `--message-list-content-width` and\n * consumed by `ChatCardContainer`'s `fixed` variant. Any CSS length.\n *\n * The published value is clamped with `min()` against the measured window width, so\n * a container narrower than the reading column never sizes a child wider than\n * itself — the case that makes a card overflow horizontally in a split-pane layout.\n */\n contentWidth?: string;\n asChild?: boolean;\n}\n\n/**\n * Root of a chat surface. Measures its own box and republishes it as CSS custom\n * properties, so descendants size themselves against the chat window without a width\n * being prop-drilled through every layer:\n *\n * - `--chat-window-width` / `--chat-window-height` — the measured border box, or\n * `100%` until the first measurement lands.\n * - `--message-list-content-width` — the reading column (see `contentWidth`).\n * - `--type-window-height` / `--welcome-screen-box-height` — reported up by\n * `ChatContainerPrompt` and `ChatContainerWelcome`; `unset` while unmounted.\n *\n * Deliberately applies **no horizontal padding of its own**. `useElementMeasure`\n * reports the border box, so padding here would be counted inside\n * `--chat-window-width`, and every child sizing against that variable would overflow\n * by exactly that padding. Insetting is the child's job instead, through the\n * `--spacing-message` gutter that `ChatCardContainer` subtracts.\n *\n * Every read site carries a `100%` fallback, so children still lay out sensibly when\n * rendered outside a `ChatContainer` (portals, tests, Storybook).\n */\nexport function ChatContainer({\n asChild = false,\n children,\n className,\n contentWidth = DEFAULT_CONTENT_WIDTH,\n style,\n ...rest\n}: ChatContainerProps) {\n const Comp = asChild ? Slot : 'section';\n const { ref, width, height } = useElementMeasure<HTMLElement>();\n const [slotHeights, setSlotHeights] = useState<Record<ChatContainerSlot, MeasuredLength>>({\n prompt: 'unset',\n welcome: 'unset',\n });\n\n const setSlotHeight = useCallback((slot: ChatContainerSlot, slotHeight: MeasuredLength) => {\n // Returning the same object on an unchanged height keeps a slot's resize effect\n // from re-rendering the whole chat on every observer callback.\n setSlotHeights((current) =>\n current[slot] === slotHeight ? current : { ...current, [slot]: slotHeight },\n );\n }, []);\n\n const contextValue = useMemo<ChatContainerContextValue>(\n () => ({ setSlotHeight }),\n [setSlotHeight],\n );\n\n const containerStyle = useMemo(\n () =>\n ({\n '--chat-window-width': width === 'unset' ? '100%' : `${width}px`,\n '--chat-window-height': height === 'unset' ? '100%' : `${height}px`,\n '--message-list-content-width': `min(${contentWidth}, var(--chat-window-width))`,\n [SLOT_VARIABLES.prompt]: toCssLength(slotHeights.prompt),\n [SLOT_VARIABLES.welcome]: toCssLength(slotHeights.welcome),\n ...style,\n }) as CSSProperties,\n [width, height, contentWidth, slotHeights, style],\n );\n\n return (\n <ChatContainerContext.Provider value={contextValue}>\n <Comp\n ref={ref}\n data-slot=\"chat-container\"\n data-testid=\"chat-container\"\n className={cn('relative flex h-full min-h-0 w-full flex-col', className)}\n style={containerStyle}\n {...rest}\n >\n {children}\n </Comp>\n </ChatContainerContext.Provider>\n );\n}\n\n/** Measures the slot element and reports its height to the nearest `ChatContainer`. */\nfunction useChatContainerSlot(slot: ChatContainerSlot) {\n const { setSlotHeight } = useChatContainerContext();\n // `HTMLElement`, not `HTMLDivElement`: with `asChild` the measured node is whatever\n // element the consumer rendered, and the callback ref has to accept all of them.\n const { ref, height } = useElementMeasure<HTMLElement>();\n\n useLayoutEffect(() => {\n setSlotHeight(slot, height);\n\n // Reset on unmount so a layout that hides the welcome box after the first message\n // does not leave a stale height behind for the message list to reserve space for.\n return () => setSlotHeight(slot, 'unset');\n }, [slot, height, setSlotHeight]);\n\n return ref;\n}\n\nexport interface ChatContainerSlotProps extends ComponentProps<'div'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/**\n * Wraps the composer. Publishes its measured height as `--type-window-height` on the\n * container, so the message list can reserve room for a composer that grows as the\n * user types.\n */\nexport function ChatContainerPrompt({\n asChild = false,\n children,\n className,\n ...rest\n}: ChatContainerSlotProps) {\n const ref = useChatContainerSlot('prompt');\n const Comp = asChild ? Slot : 'div';\n\n return (\n <Comp\n ref={ref}\n data-slot=\"chat-container-prompt\"\n data-testid=\"chat-container-prompt\"\n className={cn('shrink-0', className)}\n {...rest}\n >\n {children}\n </Comp>\n );\n}\n\n/**\n * Wraps the empty-chat welcome box. Publishes its measured height as\n * `--welcome-screen-box-height` on the container.\n */\nexport function ChatContainerWelcome({\n asChild = false,\n children,\n className,\n ...rest\n}: ChatContainerSlotProps) {\n const ref = useChatContainerSlot('welcome');\n const Comp = asChild ? Slot : 'div';\n\n return (\n <Comp\n ref={ref}\n data-slot=\"chat-container-welcome\"\n data-testid=\"chat-container-welcome\"\n className={cn('shrink-0', className)}\n {...rest}\n >\n {children}\n </Comp>\n );\n}\n","import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';\nimport { useEffect } from 'react';\n\ninterface AutoFocusPluginProps {\n autoFocus?: boolean;\n isDisabled?: boolean;\n defaultSelection?: 'rootStart' | 'rootEnd';\n}\n\nexport function AutoFocusPlugin({\n defaultSelection = 'rootEnd',\n autoFocus,\n isDisabled,\n}: AutoFocusPluginProps) {\n const [editor] = useLexicalComposerContext();\n\n useEffect(() => {\n if (!autoFocus || isDisabled) {\n return;\n }\n\n editor.focus(\n () => {\n // If we try and move selection to the same point with setBaseAndExtent, it won't\n // trigger a re-focus on the element. So in the case this occurs, we'll need to correct it.\n // Normally this is fine, Selection API !== Focus API, but fore the intents of the naming\n // of this plugin, which should preserve focus too.\n const activeElement = document.activeElement;\n const rootElement = editor.getRootElement() as HTMLDivElement;\n if (\n rootElement !== null &&\n (activeElement === null || !rootElement.contains(activeElement))\n ) {\n // Note: preventScroll won't work in Webkit.\n rootElement.focus({ preventScroll: true });\n }\n },\n { defaultSelection },\n );\n }, [defaultSelection, editor, autoFocus, isDisabled]);\n\n return null;\n}\n","import { TRANSFORMERS } from '@lexical/markdown';\n\nexport const EXPORT_TRANSFORMERS = TRANSFORMERS;\nexport const IMPORT_TRANSFORMERS = TRANSFORMERS;\n","import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';\n\nexport function useChatInputEditor() {\n const [editor] = useLexicalComposerContext();\n\n return editor;\n}\n","import {\n $createParagraphNode,\n $createRangeSelection,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n $isTextNode,\n $selectAll,\n $setSelection,\n} from 'lexical';\n\nexport function $getEditorPlainText(): string {\n return $getRoot().getTextContent();\n}\n\nexport function $setEditorPlainText(value: string): void {\n const root = $getRoot();\n root.clear();\n const paragraph = $createParagraphNode();\n if (value) {\n paragraph.append($createTextNode(value));\n }\n root.append(paragraph);\n}\n\nexport function $setSelectionToEnd(): void {\n const root = $getRoot();\n const lastDescendant = root.getLastDescendant();\n\n if (lastDescendant && $isTextNode(lastDescendant)) {\n const selection = $createRangeSelection();\n const endOffset = lastDescendant.getTextContentSize();\n selection.anchor.set(lastDescendant.getKey(), endOffset, 'text');\n selection.focus.set(lastDescendant.getKey(), endOffset, 'text');\n $setSelection(selection);\n } else {\n $selectAll();\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const focusNode = selection.focus.getNode();\n const focusOffset = $isTextNode(focusNode) ? focusNode.getTextContentSize() : 0;\n selection.anchor.set(selection.focus.key, selection.focus.offset, selection.focus.type);\n selection.focus.set(selection.focus.key, focusOffset, selection.focus.type);\n $setSelection(selection);\n }\n }\n}\n","import { $convertFromMarkdownString, $convertToMarkdownString } from '@lexical/markdown';\nimport { $addUpdateTag, SKIP_DOM_SELECTION_TAG } from 'lexical';\nimport { type MutableRefObject, useEffect, useRef } from 'react';\n\nimport { EXPORT_TRANSFORMERS, IMPORT_TRANSFORMERS } from '../transformers';\n\nimport { useChatInputEditor } from './hooks';\nimport { $setSelectionToEnd } from './utils';\n\ninterface ControlledValuePluginProps {\n value?: string;\n /** The values `ValuePlugin` gave to `onChange` that the parent has not rendered back yet. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ControlledValuePlugin({ value, emittedValuesRef }: ControlledValuePluginProps) {\n const editor = useChatInputEditor();\n const previousValueRef = useRef<string | undefined>();\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n\n if (value === previousValueRef.current) {\n return;\n }\n\n previousValueRef.current = value;\n\n // The parent renders back each value `onChange` gave it, and that render can land after later\n // keystrokes. Such a value is an echo of an older edit, not a change to apply: applying it\n // would drop what was typed since.\n if (emittedValuesRef && value !== undefined) {\n const echoIndex = emittedValuesRef.current.lastIndexOf(value);\n emittedValuesRef.current.splice(0, echoIndex === -1 ? Infinity : echoIndex + 1);\n if (echoIndex !== -1) {\n return;\n }\n }\n\n let currentValue = '';\n editor.getEditorState().read(() => {\n currentValue = $convertToMarkdownString(EXPORT_TRANSFORMERS);\n });\n\n if (value !== undefined && value !== currentValue) {\n editor.update(\n () => {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n $convertFromMarkdownString(value ?? '', IMPORT_TRANSFORMERS);\n $setSelectionToEnd();\n },\n { discrete: true },\n );\n }\n }, [editor, value, emittedValuesRef]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useChatInputEditor } from './hooks';\n\ninterface DisabledPluginProps {\n isDisabled?: boolean;\n isReadOnly?: boolean;\n}\n\nexport function DisabledPlugin({ isDisabled, isReadOnly }: DisabledPluginProps) {\n const editor = useChatInputEditor();\n\n useEffect(() => {\n editor.setEditable(!isDisabled && !isReadOnly);\n }, [editor, isDisabled, isReadOnly]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useChatInputEditor } from './hooks';\n\ninterface FocusPluginProps {\n onFocusChange?: (isFocused: boolean) => void;\n}\n\nexport function FocusPlugin({ onFocusChange }: FocusPluginProps) {\n const editor = useChatInputEditor();\n\n useEffect(() => {\n if (!onFocusChange) {\n return;\n }\n\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n\n function handleFocus() {\n if (rootElement && onFocusChange) {\n onFocusChange(true);\n }\n }\n\n function handleBlur(event: FocusEvent) {\n if (rootElement && onFocusChange && !rootElement.contains(event.relatedTarget as Node)) {\n onFocusChange(false);\n }\n }\n\n rootElement.addEventListener('focus', handleFocus, true);\n rootElement.addEventListener('blur', handleBlur, true);\n\n return () => {\n rootElement.removeEventListener('focus', handleFocus, true);\n rootElement.removeEventListener('blur', handleBlur, true);\n };\n }, [editor, onFocusChange]);\n\n return null;\n}\n","import type { LexicalEditor } from 'lexical';\nimport { useEffect, useRef } from 'react';\n\nimport { useChatInputEditor } from './hooks';\nimport { $getEditorPlainText } from './utils';\n\ninterface HasValuePluginProps {\n onHasValueChange?: (hasValue: boolean) => void;\n}\n\nfunction getHasValue(editor: LexicalEditor): boolean {\n let hasValue = false;\n editor.getEditorState().read(() => {\n hasValue = $getEditorPlainText().length > 0;\n });\n return hasValue;\n}\n\nfunction syncHasValue(\n editor: LexicalEditor,\n onHasValueChange: ((hasValue: boolean) => void) | undefined,\n lastHasValueRef: { current: boolean | undefined },\n): void {\n const hasValue = getHasValue(editor);\n\n if (lastHasValueRef.current === hasValue) {\n return;\n }\n\n lastHasValueRef.current = hasValue;\n onHasValueChange?.(hasValue);\n}\n\nexport function HasValuePlugin({ onHasValueChange }: HasValuePluginProps) {\n const editor = useChatInputEditor();\n const lastHasValueRef = useRef<boolean | undefined>();\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n\n syncHasValue(editor, onHasValueChange, lastHasValueRef);\n\n return editor.registerUpdateListener(() => {\n syncHasValue(editor, onHasValueChange, lastHasValueRef);\n });\n }, [editor, onHasValueChange]);\n\n return null;\n}\n","import {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n COMMAND_PRIORITY_CRITICAL,\n PASTE_COMMAND,\n} from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useChatInputEditor } from './hooks';\n\nexport function MarkdownPlainPastePlugin() {\n const editor = useChatInputEditor();\n\n useEffect(() => {\n return editor.registerCommand<ClipboardEvent>(\n PASTE_COMMAND,\n (event) => {\n const { clipboardData } = event;\n\n if (!clipboardData) {\n return false;\n }\n\n const plainText = clipboardData.getData('text/plain');\n\n if (!plainText) {\n return false;\n }\n\n event.preventDefault();\n\n editor.update(() => {\n const selection = $getSelection();\n\n if ($isRangeSelection(selection)) {\n selection.insertText(plainText);\n return;\n }\n\n const root = $getRoot();\n root.clear();\n\n const lines = plainText.split(/\\r?\\n/);\n lines.forEach((line) => {\n const paragraph = $createParagraphNode();\n if (line.length > 0) {\n paragraph.append($createTextNode(line));\n }\n root.append(paragraph);\n });\n });\n\n return true;\n },\n COMMAND_PRIORITY_CRITICAL,\n );\n }, [editor]);\n\n return null;\n}\n","import { $convertToMarkdownString } from '@lexical/markdown';\nimport { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';\nimport type { EditorState, LexicalEditor } from 'lexical';\nimport { type MutableRefObject, useCallback } from 'react';\n\nimport { EXPORT_TRANSFORMERS } from '../transformers';\n\n/** How many emitted values to remember; a parent that never echoes them back must not grow the list. */\nconst MAX_EMITTED_VALUES = 50;\n\ninterface ValuePluginProps {\n onChange?: (value: string) => void;\n /** Receives every value given to `onChange`, so `ControlledValuePlugin` can tell an echo of one. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ValuePlugin({ onChange, emittedValuesRef }: ValuePluginProps) {\n const handleChange = useCallback(\n (editorState: EditorState, _editor: LexicalEditor, tags: Set<string>) => {\n if (tags.has('focus')) {\n return;\n }\n\n if (!onChange) {\n return;\n }\n\n try {\n editorState.read(() => {\n const value = $convertToMarkdownString(EXPORT_TRANSFORMERS);\n\n if (emittedValuesRef) {\n emittedValuesRef.current.push(value);\n emittedValuesRef.current.splice(\n 0,\n emittedValuesRef.current.length - MAX_EMITTED_VALUES,\n );\n }\n\n onChange(value);\n });\n } catch (error) {\n console.error('ValuePlugin error:', error);\n }\n },\n [onChange, emittedValuesRef],\n );\n\n return <OnChangePlugin onChange={handleChange} />;\n}\n","import { CodeNode } from '@lexical/code';\nimport { LinkNode } from '@lexical/link';\nimport { ListItemNode, ListNode } from '@lexical/list';\nimport { type InitialConfigType, LexicalComposer } from '@lexical/react/LexicalComposer';\nimport { ContentEditable } from '@lexical/react/LexicalContentEditable';\nimport { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';\nimport { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';\nimport { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';\nimport { HeadingNode, QuoteNode } from '@lexical/rich-text';\nimport { createContext, forwardRef, useContext, useMemo, useRef, useState } from 'react';\nimport type { CSSProperties, ComponentPropsWithoutRef, KeyboardEvent, ReactNode } from 'react';\n\nimport { Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport {\n AutoFocusPlugin,\n ControlledValuePlugin,\n DisabledPlugin,\n FocusPlugin,\n HasValuePlugin,\n MarkdownPlainPastePlugin,\n ValuePlugin,\n} from './plugins';\n\nexport type ChatInputConfig = InitialConfigType;\n\ninterface ChatInputContextValue {\n isFocused: boolean;\n hasError: boolean;\n hasValue: boolean;\n\n setIsFocused: (isFocused: boolean) => void;\n setHasError: (hasError: boolean) => void;\n setHasValue: (hasValue: boolean) => void;\n}\n\nconst ChatInputContext = createContext<ChatInputContextValue>(null!);\n\n/**\n * The editor state `ChatInput` tracks (`isFocused`, `hasValue`, `hasError`) and its setters.\n * Throws when called outside a `ChatInput`.\n */\nexport function useChatInputContext() {\n const context = useContext(ChatInputContext);\n\n if (!context) {\n throw new Error('\"useChatInputContext\" must be used within a ChatInputContextProvider');\n }\n\n return context;\n}\n\nexport const DEFAULT_CONFIG: ChatInputConfig = {\n namespace: 'chat-input',\n editable: true,\n nodes: [HeadingNode, QuoteNode, ListNode, ListItemNode, CodeNode, LinkNode],\n theme: {\n paragraph: 'm-0 min-h-[26px]',\n text: {\n bold: 'font-bold',\n italic: 'italic',\n underline: 'underline',\n },\n },\n onError: (error) => {\n console.error('ChatInput Lexical error:', error);\n },\n};\n\nexport interface ChatInputProps extends ComponentPropsWithoutRef<'div'> {\n /** Lexical composer config, read once on mount. Override only to add nodes or retheme. */\n initialConfig?: ChatInputConfig;\n}\n\n/**\n * Root of the composer: holds the Lexical editor and puts its state on the wrapper as\n * `data-focused`, `data-empty` and `data-error`. Ships unstyled.\n */\nexport const ChatInput = forwardRef<HTMLDivElement, ChatInputProps>(function ChatInput(\n { className, children, initialConfig = DEFAULT_CONFIG, ...rest },\n ref,\n) {\n const [hasError, setHasError] = useState(false);\n const [hasValue, setHasValue] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n\n const contextValue = useMemo(\n () => ({\n hasError,\n hasValue,\n isFocused,\n setHasError,\n setHasValue,\n setIsFocused,\n }),\n [hasError, hasValue, isFocused],\n );\n\n return (\n <ChatInputContext.Provider value={contextValue}>\n <LexicalComposer initialConfig={initialConfig}>\n <div\n ref={ref}\n data-slot=\"chat-input\"\n data-testid=\"chat-input\"\n data-focused={isFocused}\n data-empty={!hasValue}\n data-error={hasError}\n aria-invalid={hasError}\n className={cn('group/chat-input', 'relative', className)}\n {...rest}\n >\n {children}\n </div>\n </LexicalComposer>\n </ChatInputContext.Provider>\n );\n});\n\nChatInput.displayName = 'ChatInput';\n\nexport interface ChatInputPlaceholderProps extends ComponentPropsWithoutRef<'span'> {}\n\nexport const ChatInputPlaceholder = forwardRef<HTMLSpanElement, ChatInputPlaceholderProps>(\n function ChatInputPlaceholder({ className, children, ...rest }, ref) {\n return (\n <Typography\n ref={ref}\n variant=\"body\"\n className={cn(\n 'pointer-events-none absolute inset-0 z-0',\n 'min-h-[26px]',\n 'text-text-tertiary',\n className,\n )}\n asChild\n {...rest}\n >\n {/* Typography stamps its own data-slot unless it renders as its child. */}\n <p data-slot=\"chat-input-placeholder\">{children}</p>\n </Typography>\n );\n },\n);\n\nChatInputPlaceholder.displayName = 'ChatInputPlaceholder';\n\nexport interface ChatInputTextareaProps {\n /** Classes for the editable element (`data-slot=\"chat-input-editable\"`), not its wrapper. */\n className?: string;\n /** Inline styles for the wrapper around the editable element. */\n style?: CSSProperties | undefined;\n /** Classes for the placeholder (`data-slot=\"chat-input-placeholder\"`). */\n placeholderClassName?: string;\n /** Shown while the editor is empty; also the editable's `aria-placeholder`. */\n placeholder?: string;\n /** Custom Lexical plugins; rendered inside the composer, after the built-in ones. */\n children?: ReactNode;\n /**\n * Content as Markdown. When it differs from the editor's, it replaces the content; a late\n * render of a value `onChange` already emitted is ignored.\n */\n value?: string;\n /** Focuses the editor on mount, caret at the end. Skipped when disabled or read-only. */\n autoFocus?: boolean;\n /** Blocks editing and selection and dims the wrapper (`data-disabled`). */\n isDisabled?: boolean;\n /** Blocks editing but keeps the text selectable (`data-readonly`). */\n isReadOnly?: boolean;\n /** Called with the content as Markdown on every edit. */\n onChange?: (value: string) => void;\n /** Key handler on the editable element; implement send-on-Enter here. */\n onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;\n}\n\n/**\n * The editable area of a `ChatInput`. Its value is a Markdown string; paste inserts plain\n * text. Must be rendered inside a `ChatInput`.\n */\nexport const ChatInputTextarea = forwardRef<HTMLDivElement, ChatInputTextareaProps>(\n function ChatInputTextarea(\n {\n className,\n style,\n placeholderClassName,\n placeholder = 'Input your message...',\n children,\n value,\n autoFocus = true,\n isDisabled = false,\n isReadOnly = false,\n onChange,\n onKeyDown,\n ...rest\n },\n ref,\n ) {\n const { setHasValue, setIsFocused } = useChatInputContext();\n const isReadOnlyState = isReadOnly && !isDisabled;\n const emittedValuesRef = useRef<string[]>([]);\n\n return (\n <div\n data-slot=\"chat-input-textarea\"\n data-testid=\"chat-input-textarea\"\n data-disabled={isDisabled}\n data-readonly={isReadOnlyState}\n aria-disabled={isDisabled}\n aria-readonly={isReadOnlyState}\n className={cn(\n 'group/chat-input-textarea',\n 'relative',\n 'data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-80 data-[disabled=true]:select-none',\n 'data-[readonly=true]:text-text-secondary',\n )}\n style={style}\n {...rest}\n >\n <RichTextPlugin\n contentEditable={\n <ContentEditable\n ref={ref}\n data-slot=\"chat-input-editable\"\n className={cn('min-h-[26px]!', 'overflow-y-auto text-wrap outline-none', className)}\n aria-label=\"Chat input\"\n aria-placeholder={placeholder}\n placeholder={\n <ChatInputPlaceholder className={placeholderClassName}>\n {placeholder}\n </ChatInputPlaceholder>\n }\n onKeyDown={onKeyDown}\n />\n }\n ErrorBoundary={LexicalErrorBoundary}\n />\n\n <HistoryPlugin />\n <DisabledPlugin isDisabled={isDisabled} isReadOnly={isReadOnly} />\n <ControlledValuePlugin value={value} emittedValuesRef={emittedValuesRef} />\n <ValuePlugin onChange={onChange} emittedValuesRef={emittedValuesRef} />\n <MarkdownPlainPastePlugin />\n <HasValuePlugin onHasValueChange={setHasValue} />\n <FocusPlugin onFocusChange={setIsFocused} />\n <AutoFocusPlugin autoFocus={autoFocus} isDisabled={isDisabled || isReadOnly} />\n\n {children}\n </div>\n );\n },\n);\n\nChatInputTextarea.displayName = 'ChatInputTextarea';\n","import {\n createContext,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type MutableRefObject,\n type ReactNode,\n type RefObject,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\nimport { Skeleton } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatListContextValue {\n loadedCount: number;\n totalCount?: number;\n hasMore: boolean;\n isLoading: boolean;\n isLoadingMore: boolean;\n isEmpty: boolean;\n hasError: boolean;\n onLoadMore?: () => void;\n getItemKey: (index: number) => string | number;\n scrollElementRef: RefObject<HTMLDivElement | null>;\n setScrollElement: (node: HTMLDivElement | null) => void;\n loadMoreContentRef: MutableRefObject<ReactNode>;\n loadMoreVersion: number;\n bumpLoadMore: () => void;\n skeletonContainer: HTMLElement | null;\n setSkeletonContainer: (node: HTMLElement | null) => void;\n}\n\nconst ChatListContext = createContext<ChatListContextValue | null>(null);\n\n/** The list state `ChatList` shares with its parts. Throws when called outside a `ChatList`. */\nexport function useChatListContext() {\n const context = useContext(ChatListContext);\n\n if (!context) {\n throw new Error('\"useChatListContext\" must be used within a ChatList');\n }\n\n return context;\n}\n\nexport interface ChatListProps {\n /** The list parts: `ChatListItems`, `ChatListSkeleton`, `ChatListLoadMore`, `ChatListEmptyState` and `ChatListError`. */\n children: ReactNode;\n className?: string;\n /** Number of rows already loaded; `ChatListItems` renders this many. */\n loadedCount: number;\n /** Total rows on the server, when known; used to work out `hasMore`. */\n totalCount?: number;\n /** Whether another page can be loaded. Defaults to `loadedCount < totalCount`, and to false without `totalCount`. */\n hasMore?: boolean;\n /** The first page is loading: with no rows loaded, `ChatListSkeleton` shows in place of the rows. */\n isLoading?: boolean;\n /** The next page is loading: stops `onLoadMore` from firing again until it is false. */\n isLoadingMore?: boolean;\n /** Loading failed: with no rows loaded, `ChatListError` shows. */\n hasError?: boolean;\n /** Called when the last rendered row reaches the end of the loaded rows while `hasMore` is true. */\n onLoadMore?: () => void;\n /** Returns a stable key for the row at an index, e.g. the chat id. */\n getItemKey: (index: number) => string | number;\n /** Accessible name of the navigation landmark. Defaults to \"Chat list\". */\n 'aria-label'?: string;\n}\n\n/**\n * Root of the conversation list: a `role=\"navigation\"` landmark that holds the fetch state and\n * shares it with its parts. Give it a bounded height; `ChatListItems` scrolls inside it.\n */\nexport function ChatList({\n children,\n className,\n loadedCount,\n totalCount,\n hasMore: hasMoreProp,\n isLoading = false,\n isLoadingMore = false,\n hasError = false,\n onLoadMore,\n getItemKey,\n 'aria-label': ariaLabel = 'Chat list',\n}: ChatListProps) {\n const scrollElementRef = useRef<HTMLDivElement | null>(null);\n const loadMoreContentRef = useRef<ReactNode>(null);\n const [loadMoreVersion, setLoadMoreVersion] = useState(0);\n const [skeletonContainer, setSkeletonContainer] = useState<HTMLElement | null>(null);\n const [, setScrollElementVersion] = useState(0);\n\n const setScrollElement = useCallback((node: HTMLDivElement | null) => {\n scrollElementRef.current = node;\n setScrollElementVersion((version) => version + 1);\n }, []);\n\n const bumpLoadMore = useCallback(() => {\n setLoadMoreVersion((version) => version + 1);\n }, []);\n\n const hasMore = hasMoreProp ?? (totalCount != null ? loadedCount < totalCount : false);\n const isEmpty = loadedCount === 0 && !isLoading && !hasError;\n\n const contextValue = useMemo<ChatListContextValue>(\n () => ({\n loadedCount,\n totalCount,\n hasMore,\n isLoading,\n isLoadingMore,\n isEmpty,\n hasError,\n onLoadMore,\n getItemKey,\n scrollElementRef,\n setScrollElement,\n loadMoreContentRef,\n loadMoreVersion,\n bumpLoadMore,\n skeletonContainer,\n setSkeletonContainer,\n }),\n [\n loadedCount,\n totalCount,\n hasMore,\n isLoading,\n isLoadingMore,\n isEmpty,\n hasError,\n onLoadMore,\n getItemKey,\n setScrollElement,\n loadMoreVersion,\n bumpLoadMore,\n skeletonContainer,\n ],\n );\n\n return (\n <ChatListContext.Provider value={contextValue}>\n <div\n data-slot=\"chat-list\"\n data-testid=\"chat-list\"\n data-loading={isLoading}\n data-loading-more={isLoadingMore}\n data-empty={isEmpty}\n data-error={hasError}\n role=\"navigation\"\n aria-label={ariaLabel}\n className={cn('group/chat-list relative flex min-h-0 flex-1 flex-col', className)}\n >\n {children}\n </div>\n </ChatListContext.Provider>\n );\n}\n\nexport interface ChatListSkeletonProps {\n /** Your own placeholder rows. Leave it out to get `rows` default rows built from `Skeleton`. */\n children?: ReactNode;\n /** Number of default rows, used only when `children` is not passed. Rows past the list's height are clipped. */\n rows?: number;\n className?: string;\n /** Classes for each default row; merged after its defaults. Not used when `children` is passed. */\n rowClassName?: string;\n}\n\n// Title and preview widths alternate per row, so the placeholder reads as a list of chats.\nconst TITLE_WIDTHS = ['w-2/3', 'w-1/2'] as const;\nconst PREVIEW_WIDTHS = ['w-full', 'w-4/5'] as const;\n\n/**\n * Placeholder for the first page of chats. Renders only while `isLoading` is true and no chats are\n * loaded, in the space `ChatListItems` will fill. It is a `role=\"status\"` region named\n * \"Loading chats\"; its rows are `Skeleton`s from `@swisper.ai/ui`, which are `aria-hidden`.\n */\nexport function ChatListSkeleton({\n children,\n rows = 16,\n className,\n rowClassName,\n}: ChatListSkeletonProps) {\n const { isLoading, loadedCount, skeletonContainer } = useChatListContext();\n\n if (!(isLoading && loadedCount === 0) || !skeletonContainer) {\n return null;\n }\n\n return createPortal(\n <div\n data-slot=\"chat-list-skeleton\"\n data-testid=\"chat-list-skeleton\"\n role=\"status\"\n aria-busy=\"true\"\n aria-label=\"Loading chats\"\n className={cn('flex min-h-0 flex-1 flex-col gap-4 overflow-hidden', className)}\n >\n {children ??\n Array.from({ length: rows }, (_, index) => (\n <div\n key={index}\n data-slot=\"chat-list-skeleton-row\"\n className={cn('flex shrink-0 flex-col gap-4 px-12 py-8', rowClassName)}\n >\n <div className=\"flex h-20 items-center\">\n <Skeleton className={cn('h-12', TITLE_WIDTHS[index % 2])} />\n </div>\n <div className=\"flex h-16 items-center\">\n <Skeleton className={cn('h-10', PREVIEW_WIDTHS[index % 2])} />\n </div>\n </div>\n ))}\n </div>,\n skeletonContainer,\n );\n}\n\nexport interface ChatListEmptyStateProps {\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * What the list says when it has no chats. Renders only when nothing is loaded, nothing is loading\n * and there is no error, as a `role=\"status\"` region named \"No chats\".\n */\nexport function ChatListEmptyState({ children, className }: ChatListEmptyStateProps) {\n const { isEmpty } = useChatListContext();\n\n if (!isEmpty) {\n return null;\n }\n\n return (\n <div\n data-slot=\"chat-list-empty-state\"\n data-testid=\"chat-list-empty-state\"\n role=\"status\"\n aria-live=\"polite\"\n aria-label=\"No chats\"\n className={cn('flex flex-1 items-center justify-center', className)}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatListErrorProps {\n /** Your own error content. Leave it out to get the `error` message, or \"An error occurred\". */\n children?: ReactNode;\n /** The failure to show when `children` is not passed: an `Error`'s message, or the string itself. */\n error?: Error | string;\n className?: string;\n /** Classes for the default message; merged after its defaults. Not used when `children` is passed. */\n messageClassName?: string;\n}\n\n/**\n * What the list says when the first page fails. Renders only while `hasError` is true and no chats\n * are loaded, as a `role=\"alert\"` region named \"Error loading chats\".\n */\nexport function ChatListError({\n children,\n error,\n className,\n messageClassName,\n}: ChatListErrorProps) {\n const { hasError, loadedCount } = useChatListContext();\n\n if (!(hasError && loadedCount === 0)) {\n return null;\n }\n\n return (\n <div\n data-slot=\"chat-list-error\"\n data-testid=\"chat-list-error\"\n role=\"alert\"\n aria-live=\"assertive\"\n aria-label=\"Error loading chats\"\n className={cn('flex flex-1 items-center justify-center', className)}\n >\n {children || (\n <div\n data-slot=\"chat-list-error-message\"\n className={cn('text-text-error-main', messageClassName)}\n >\n {error instanceof Error ? error.message : error || 'An error occurred'}\n </div>\n )}\n </div>\n );\n}\n\nexport interface ChatListLoadMoreProps {\n /** Content of the load-more row, e.g. \"Loading more…\" or a few skeleton rows. */\n children?: ReactNode;\n}\n\n/**\n * Registers its children as the content of the row `ChatListItems` appends while `hasMore` is true.\n * It renders nothing where it is placed.\n */\nexport function ChatListLoadMore({ children }: ChatListLoadMoreProps) {\n const { loadMoreContentRef, bumpLoadMore } = useChatListContext();\n\n loadMoreContentRef.current = children ?? null;\n\n useLayoutEffect(() => {\n bumpLoadMore();\n\n return () => {\n loadMoreContentRef.current = null;\n bumpLoadMore();\n };\n }, [bumpLoadMore, loadMoreContentRef]);\n\n return null;\n}\n","import { useVirtualizer } from '@tanstack/react-virtual';\nimport { memo, useCallback, useEffect, type ReactNode } from 'react';\n\nimport { MenuList, ScrollArea } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useChatListContext } from './chat-list';\n\nconst LOAD_MORE_KEY = 'chat-list-load-more';\n\nexport interface ChatListItemsProps {\n /** Render function called with each loaded row's index; return a `ChatListItem`. */\n children: (index: number) => ReactNode;\n className?: string;\n /** Classes for the `ul` that holds the rows; merged after its defaults. */\n listClassName?: string;\n /** Classes for every `li`, the load-more row included; merged after its defaults. */\n rowClassName?: string;\n /** First guess of a row's height in pixels; rows are measured after they render. */\n estimateSize?: number;\n /** Rows rendered beyond the visible ones, above and below. */\n overscan?: number;\n /** Space between rows, in pixels. */\n gap?: number;\n}\n\n/**\n * The scrolling, virtualised rows of a `ChatList`. While `hasMore` is true it appends one row with\n * the `ChatListLoadMore` content and calls `onLoadMore` when that row comes into range.\n */\nexport const ChatListItems = memo(function ChatListItems({\n children,\n className,\n listClassName,\n rowClassName,\n estimateSize = 54,\n overscan = 6,\n gap = 4,\n}: ChatListItemsProps) {\n const {\n loadedCount,\n hasMore,\n isLoading,\n isLoadingMore,\n onLoadMore,\n getItemKey,\n scrollElementRef,\n setScrollElement,\n loadMoreContentRef,\n loadMoreVersion,\n setSkeletonContainer,\n } = useChatListContext();\n\n // Re-read registered sentinel content when ChatListLoadMore mounts/unmounts.\n const loadMoreContent = loadMoreVersion >= 0 ? loadMoreContentRef.current : null;\n\n const showSkeleton = isLoading && loadedCount === 0;\n const count = hasMore ? loadedCount + 1 : loadedCount;\n\n const getItemKeyStable = useCallback(\n (index: number) => {\n if (index >= loadedCount) {\n return LOAD_MORE_KEY;\n }\n\n return getItemKey(index);\n },\n [getItemKey, loadedCount],\n );\n\n const virtualizer = useVirtualizer({\n count: showSkeleton ? 0 : count,\n getScrollElement: () => scrollElementRef.current,\n estimateSize: () => estimateSize,\n overscan,\n gap,\n getItemKey: getItemKeyStable,\n });\n\n const virtualItems = virtualizer.getVirtualItems();\n\n useEffect(() => {\n if (showSkeleton) {\n return;\n }\n\n const [lastItem] = [...virtualItems].reverse();\n\n if (!lastItem) {\n return;\n }\n\n if (lastItem.index >= loadedCount - 1 && hasMore && !isLoadingMore) {\n onLoadMore?.();\n }\n }, [virtualItems, loadedCount, hasMore, isLoadingMore, onLoadMore, showSkeleton]);\n\n // The skeleton sits outside the ScrollArea: Radix wraps the viewport's content in a\n // `display: table` box, where the skeleton could neither fill the list height nor clip to it.\n if (showSkeleton) {\n return (\n <div\n ref={setSkeletonContainer}\n data-slot=\"chat-list-items\"\n data-testid=\"chat-list-items\"\n className={cn('flex min-h-0 flex-1 flex-col overflow-hidden', className)}\n />\n );\n }\n\n return (\n <ScrollArea\n ref={setScrollElement}\n data-slot=\"chat-list-items\"\n data-testid=\"chat-list-items\"\n className={cn('min-h-0 flex-1', 'overflow-auto', className)}\n >\n <MenuList\n data-slot=\"chat-list-items-list\"\n role=\"list\"\n aria-label=\"Chats\"\n className={cn(\n 'table relative w-full transform-gpu table-fixed',\n 'space-y-[4px]',\n listClassName,\n )}\n style={{\n height: `${virtualizer.getTotalSize()}px`,\n }}\n >\n {virtualItems.map((virtualItem) => {\n const isLoaderRow = virtualItem.index >= loadedCount;\n\n return (\n <li\n key={virtualItem.key}\n data-slot=\"chat-list-items-row\"\n data-index={virtualItem.index}\n data-load-more={isLoaderRow}\n ref={virtualizer.measureElement}\n role={isLoaderRow ? 'status' : 'listitem'}\n aria-live={isLoaderRow ? 'polite' : undefined}\n aria-busy={isLoaderRow ? isLoadingMore : undefined}\n className={rowClassName}\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n transform: `translateY(${virtualItem.start}px)`,\n }}\n >\n {isLoaderRow ? loadMoreContent : children(virtualItem.index)}\n </li>\n );\n })}\n </MenuList>\n </ScrollArea>\n );\n});\n","import { Slot } from '@radix-ui/react-slot';\nimport { forwardRef, type ComponentPropsWithoutRef, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatListItemProps extends ComponentPropsWithoutRef<'div'> {\n children?: ReactNode;\n /** Merges the item's props onto its only child, e.g. a link or a button, without adding a `div`. */\n asChild?: boolean;\n /** Marks the open conversation: sets `data-selected` and `aria-selected`. */\n isSelected?: boolean;\n}\n\n/**\n * One row's content, returned from the `ChatListItems` render function. It has no role, tab stop or\n * look of its own: render it `asChild` over a link or button and style that from `data-selected`.\n */\nexport const ChatListItem = forwardRef<HTMLDivElement, ChatListItemProps>(function ChatListItem(\n { children, className, asChild = false, isSelected = false, ...rest },\n ref,\n) {\n const Component = asChild ? Slot : 'div';\n\n return (\n <Component\n ref={ref}\n data-slot=\"chat-list-item\"\n data-testid=\"chat-list-item\"\n data-selected={isSelected}\n aria-selected={isSelected || undefined}\n className={cn('cursor-pointer outline-none', className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatListItem.displayName = 'ChatListItem';\n","import { createContext, useCallback, useContext, useMemo, useRef, type ReactNode } from 'react';\n\ninterface ChatPromptBoxContextValue {\n reportInputHeight: (height: number) => void;\n resetCompact: () => void;\n registerFocusInput: (focus: () => void) => void;\n unregisterFocusInput: () => void;\n focusInput: () => void;\n}\n\nconst ChatPromptBoxContext = createContext<ChatPromptBoxContextValue | null>(null);\n\nexport function useChatPromptBoxContext() {\n const context = useContext(ChatPromptBoxContext);\n\n if (!context) {\n throw new Error('\"useChatPromptBoxContext\" must be used within a ChatPromptBox');\n }\n\n return context;\n}\n\ninterface ChatPromptBoxContextProviderProps {\n children: ReactNode;\n reportInputHeight: (height: number) => void;\n resetCompact: () => void;\n}\n\nexport function ChatPromptBoxContextProvider({\n children,\n reportInputHeight,\n resetCompact,\n}: ChatPromptBoxContextProviderProps) {\n const focusInputRef = useRef<(() => void) | null>(null);\n\n const registerFocusInput = useCallback((focus: () => void) => {\n focusInputRef.current = focus;\n }, []);\n\n const unregisterFocusInput = useCallback(() => {\n focusInputRef.current = null;\n }, []);\n\n const focusInput = useCallback(() => {\n focusInputRef.current?.();\n }, []);\n\n const contextValue = useMemo(\n () => ({\n reportInputHeight,\n resetCompact,\n registerFocusInput,\n unregisterFocusInput,\n focusInput,\n }),\n [reportInputHeight, resetCompact, registerFocusInput, unregisterFocusInput, focusInput],\n );\n\n return (\n <ChatPromptBoxContext.Provider value={contextValue}>{children}</ChatPromptBoxContext.Provider>\n );\n}\n","import { useEffect } from 'react';\n\nimport { useChatInputEditor } from '../chat-input/plugins/hooks';\n\nimport { useChatPromptBoxContext } from './chat-prompt-box-context';\n\nexport function ChatPromptBoxFocusPlugin() {\n const editor = useChatInputEditor();\n const { registerFocusInput, unregisterFocusInput } = useChatPromptBoxContext();\n\n useEffect(() => {\n registerFocusInput(() => {\n editor.focus();\n });\n\n return () => {\n unregisterFocusInput();\n };\n }, [editor, registerFocusInput, unregisterFocusInput]);\n\n return null;\n}\n","import type { ComponentPropsWithoutRef, MouseEvent, ReactNode } from 'react';\nimport { forwardRef, useCallback, useLayoutEffect, useState } from 'react';\n\nimport { cn, useElementMeasure } from '@swisper.ai/web-core';\n\nimport { ChatInput, ChatInputTextarea, useChatInputContext } from '../chat-input';\nimport type { ChatInputProps, ChatInputTextareaProps } from '../chat-input';\n\nimport { ChatPromptBoxContextProvider, useChatPromptBoxContext } from './chat-prompt-box-context';\nimport { ChatPromptBoxFocusPlugin } from './chat-prompt-box-focus-plugin';\n\nexport interface ChatPromptBoxProps extends ChatInputProps {\n /** Classes merged last onto the inner surface, the element that carries the box's background and padding. */\n innerClassName?: string;\n}\n\nconst COMPACT_INPUT_HEIGHT_THRESHOLD = 40;\n\nconst INTERACTIVE_SELECTOR = 'button, a, input, select, textarea, [role=\"button\"]';\n\nfunction shouldSkipFocus(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) {\n return false;\n }\n\n return Boolean(target.closest(INTERACTIVE_SELECTOR));\n}\n\n/**\n * The styled chat composer: a `ChatInput` with the box's border, background and focus glow. Sets\n * `data-compact` on the root, which the parts read to move the actions under the text.\n */\nexport const ChatPromptBox = forwardRef<HTMLDivElement, ChatPromptBoxProps>(\n function ChatPromptBox(props, ref) {\n const [isCompact, setIsCompact] = useState(true);\n\n const reportInputHeight = useCallback((height: number) => {\n if (height > COMPACT_INPUT_HEIGHT_THRESHOLD) {\n setIsCompact(false);\n }\n }, []);\n\n const resetCompact = useCallback(() => {\n setIsCompact(true);\n }, []);\n\n return (\n <ChatPromptBoxContextProvider\n reportInputHeight={reportInputHeight}\n resetCompact={resetCompact}\n >\n <ChatPromptBoxContainer ref={ref} data-compact={isCompact} {...props} />\n </ChatPromptBoxContextProvider>\n );\n },\n);\n\nChatPromptBox.displayName = 'ChatPromptBox';\n\nconst ChatPromptBoxContainer = forwardRef<HTMLDivElement, ChatPromptBoxProps>(\n function ChatPromptBoxContainer(\n { className, innerClassName, children, onMouseDown, ...rest },\n ref,\n ) {\n const { focusInput } = useChatPromptBoxContext();\n\n const handleMouseDown = useCallback(\n (event: MouseEvent<HTMLDivElement>) => {\n if (!shouldSkipFocus(event.target)) {\n focusInput();\n }\n\n onMouseDown?.(event);\n },\n [focusInput, onMouseDown],\n );\n\n return (\n <ChatInput\n ref={ref}\n data-slot=\"chat-prompt-box\"\n className={cn(\n 'group/chat-prompt-box',\n 'relative overflow-hidden',\n 'cursor-text',\n 'p-px',\n 'rounded-[16px]',\n // border color\n 'bg-transparent',\n 'hover:bg-promptbox-background-border-base',\n 'data-[focused=true]:bg-promptbox-background-border-base',\n className,\n )}\n onMouseDown={handleMouseDown}\n {...rest}\n >\n <div\n data-slot=\"chat-prompt-box-inner\"\n className={cn(\n 'rounded-[15px]',\n 'p-[4px]',\n // regular bg\n 'bg-[#171A20]',\n // hover bg\n 'group-hover/chat-prompt-box:bg-[#252931]',\n // focused bg\n 'group-data-[focused=true]/chat-prompt-box:bg-[linear-gradient(var(--color-promptbox-background-hover),var(--color-promptbox-background-hover)),var(--color-promptbox-background-base)]',\n // focused & hover bg\n 'group-data-[focused=true]/chat-prompt-box:group-hover/chat-prompt-box:bg-[linear-gradient(var(--color-promptbox-background-hover),var(--color-promptbox-background-hover)),var(--color-promptbox-background-base)]',\n innerClassName,\n )}\n >\n {children}\n </div>\n\n <ChatPromptBoxFocusRadials />\n </ChatInput>\n );\n },\n);\n\nChatPromptBoxContainer.displayName = 'ChatPromptBoxContainer';\n\nfunction ChatPromptBoxFocusRadials() {\n return (\n <>\n <div\n data-slot=\"chat-prompt-box-glow-top\"\n className={cn(\n 'absolute left-1/2 top-[-40px]',\n 'translate-x-[-50%]',\n 'pointer-events-none',\n 'w-[380px] h-[72px]',\n 'opacity-0 group-data-[focused=true]/chat-prompt-box:opacity-50',\n )}\n style={{\n borderRadius: '380px',\n background:\n 'gradient(50% 50% at 50% 50%, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0.00) 100%)',\n }}\n />\n\n <div\n data-slot=\"chat-prompt-box-glow-bottom\"\n className={cn(\n 'absolute left-1/2 -bottom-22',\n 'translate-x-[-50%]',\n 'pointer-events-none',\n 'w-[1082px] h-[172px]',\n 'opacity-0 group-data-[focused=true]/chat-prompt-box:opacity-5',\n )}\n style={{\n borderRadius: '1082px',\n background:\n 'radial-gradient(50% 50% at 50% 50%, rgba(255, 255, 255, 0.80) 0%, #2979FF 28%, rgba(63, 70, 88, 0.00) 100%)',\n }}\n />\n </>\n );\n}\n\nexport interface ChatPromptBoxToolbarProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/** A row above the content for what the message carries, such as the attached files. */\nexport function ChatPromptBoxToolbar({ className, children, ...rest }: ChatPromptBoxToolbarProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-toolbar\"\n data-testid=\"chat-prompt-box-toolbar\"\n className={cn(className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatPromptBoxContentProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/** The row holding the input and both action groups. Reserves room under the text once the box expands. */\nexport function ChatPromptBoxContent({ className, children, ...rest }: ChatPromptBoxContentProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-content\"\n data-testid=\"chat-prompt-box-content\"\n className={cn(\n 'relative',\n 'px-[8px] py-[8px]',\n 'flex flex-row gap-[8px]',\n 'group-data-[compact=false]/chat-prompt-box:pb-[calc(8px+4px+40px)]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatPromptBoxInputProps extends ChatInputTextareaProps {\n /** Classes merged last onto the editable element, after its 72px max height. `className` goes to the wrapper around it. */\n textareaClassName?: string;\n}\n\n/**\n * The box's text input: a `ChatInputTextarea` that reports its height to the box and registers\n * click-to-focus. `children` are rendered inside the editor, for extra Lexical plugins.\n */\nexport const ChatPromptBoxInput = forwardRef<HTMLDivElement, ChatPromptBoxInputProps>(\n function ChatPromptBoxInput(\n { className, textareaClassName, placeholderClassName, children, ...rest },\n ref,\n ) {\n const { reportInputHeight, resetCompact } = useChatPromptBoxContext();\n const { hasValue } = useChatInputContext();\n const { ref: measureRef, height } = useElementMeasure<HTMLDivElement>();\n\n useLayoutEffect(() => {\n if (typeof height === 'number') {\n reportInputHeight(height);\n }\n }, [height, reportInputHeight]);\n\n useLayoutEffect(() => {\n return () => {\n resetCompact();\n };\n }, [resetCompact]);\n\n useLayoutEffect(() => {\n if (!hasValue) {\n resetCompact();\n }\n }, [hasValue, resetCompact]);\n\n const setRef = useCallback(\n (element: HTMLDivElement | null) => {\n measureRef(element);\n\n if (typeof ref === 'function') {\n ref(element);\n } else if (ref) {\n ref.current = element;\n }\n },\n [measureRef, ref],\n );\n\n return (\n <div\n data-slot=\"chat-prompt-box-input\"\n data-testid=\"chat-prompt-box-input\"\n className={cn(\n 'min-h-[40px]',\n 'inline-flex justify-center items-center',\n 'group-data-[compact=false]/chat-prompt-box:items-start',\n 'group-data-[compact=false]/chat-prompt-box:min-h-[48px]',\n 'order-2 grow min-w-0 flex-1',\n '[&>div]:flex-1 [&>div]:min-w-0',\n className,\n )}\n >\n <ChatInputTextarea\n ref={setRef}\n className={cn('max-h-[72px]!', textareaClassName)}\n placeholderClassName={cn('leading-[24px]!', placeholderClassName)}\n {...rest}\n >\n <ChatPromptBoxFocusPlugin />\n {children}\n </ChatInputTextarea>\n </div>\n );\n },\n);\n\nChatPromptBoxInput.displayName = 'ChatPromptBoxInput';\n\nexport interface ChatPromptBoxActionsLeftProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/**\n * The `role=\"group\"` of secondary actions before the text, e.g. attach. Moves to the bottom-left\n * when the box expands. Name it with `aria-label`.\n */\nexport function ChatPromptBoxActionsLeft({\n className,\n children,\n ...rest\n}: ChatPromptBoxActionsLeftProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-actions-left\"\n data-testid=\"chat-prompt-box-actions-left\"\n role=\"group\"\n className={cn(\n 'order-1 shrink-0',\n 'group-data-[compact=false]/chat-prompt-box:absolute',\n 'group-data-[compact=false]/chat-prompt-box:bottom-[8px]',\n 'group-data-[compact=false]/chat-prompt-box:left-[8px]',\n 'flex items-center gap-[8px]',\n '[grid-area:left]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatPromptBoxActionsRightProps extends ComponentPropsWithoutRef<'div'> {\n children: ReactNode;\n}\n\n/**\n * The `role=\"group\"` of actions after the text, ending in send. Moves to the bottom-right when the\n * box expands. Name it with `aria-label`.\n */\nexport function ChatPromptBoxActionsRight({\n className,\n children,\n ...rest\n}: ChatPromptBoxActionsRightProps) {\n return (\n <div\n data-slot=\"chat-prompt-box-actions-right\"\n data-testid=\"chat-prompt-box-actions-right\"\n role=\"group\"\n className={cn(\n 'order-3 shrink-0',\n 'group-data-[compact=false]/chat-prompt-box:order-3',\n 'group-data-[compact=false]/chat-prompt-box:absolute',\n 'group-data-[compact=false]/chat-prompt-box:bottom-[8px]',\n 'group-data-[compact=false]/chat-prompt-box:right-[8px]',\n 'flex items-center justify-end gap-[8px]',\n '[grid-area:right]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","import React from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatMessageProps {\n /** The message parts, usually a `ChatMessageContent` followed by an optional `ChatMessageActions`. */\n children: React.ReactNode;\n /** Classes merged last onto the root, e.g. `gap-12` to change the gap between the parts. */\n className?: string;\n /** Marks the message as the user's question: end-aligns it and turns its content into a filled bubble. */\n isQuestion?: boolean;\n}\n\n/** One message in a conversation: the user's question as an end-aligned bubble, or the assistant's answer. */\nexport function ChatMessage({ children, className, isQuestion }: ChatMessageProps) {\n return (\n <div\n data-slot=\"chat-message\"\n data-question={isQuestion}\n className={cn(\n 'group/message',\n 'flex flex-col',\n 'data-[question=true]:items-end',\n 'gap-8',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageContentProps {\n /** The message body: plain text, a `MarkdownViewer` or a `ChatCardContainer`. */\n children: React.ReactNode;\n /** Classes merged last onto the content element. */\n className?: string;\n}\n\n/** The body of a `ChatMessage`. Inside a question it renders as a padded, filled bubble. */\nexport function ChatMessageContent({ children, className }: ChatMessageContentProps) {\n return (\n <div\n data-slot=\"chat-message-content\"\n data-bubble={true}\n className={cn(\n 'w-fit',\n 'min-w-message-mobile-min md:min-w-auto',\n 'group-data-[question=true]/message:data-[bubble=true]:p-16',\n 'group-data-[question=true]/message:data-[bubble=true]:rounded-[20px]',\n 'group-data-[question=true]/message:data-[bubble=true]:bg-[#22283499]',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageActionsProps {\n /** The controls under the message, usually a `ChatMessageToolbar`. */\n children: React.ReactNode;\n /** Classes merged last onto the actions row. */\n className?: string;\n}\n\n/** A row under the message body. From `md` up it is hidden until its `ChatMessage` is hovered. */\nexport function ChatMessageActions({ children, className }: ChatMessageActionsProps) {\n return (\n <div\n data-slot=\"chat-message-actions\"\n className={cn(\n 'transition-opacity duration-300',\n 'md:opacity-0 group-hover/message:opacity-100',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n","import { nanoid } from 'nanoid';\n\nimport { type ChatId } from '@/types';\n\nexport function getNewChatId(): ChatId {\n return `__${nanoid()}__`;\n}\n","import {\n type ReactNode,\n type RefObject,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport type { ChatId } from '@/types';\n\nimport { getNewChatId } from './utils';\n\nexport interface ChatContextValue {\n chatId: ChatId;\n newChatId: ChatId;\n loadedChatIdsRef: RefObject<Set<ChatId>>;\n isNewChat: boolean;\n goToNewChat: () => ChatId;\n promptPlaceholder: string | undefined;\n setPromptPlaceholder: (placeholder: string) => void;\n clearPromptPlaceholder: () => void;\n}\n\nconst ChatContext = createContext<ChatContextValue>(null!);\n\nexport function useChatContext() {\n const context = useContext(ChatContext);\n\n if (!context) {\n throw new Error('\"useChatContext\" must be used within a ChatProvider');\n }\n\n return context;\n}\n\ninterface ChatProviderProps {\n children: ReactNode;\n chatId: ChatId | undefined;\n}\n\nexport function ChatProvider({ children, chatId: chatIdProp }: ChatProviderProps) {\n const [newChatId, setNewChatId] = useState<ChatId>(getNewChatId());\n const [promptPlaceholder, setPromptPlaceholderState] = useState<string | undefined>(undefined);\n const loadedChatIdsRef = useRef<Set<ChatId>>(new Set());\n const chatId: ChatId = chatIdProp || newChatId;\n const isNewChat: boolean = chatId === newChatId;\n\n const goToNewChat = useCallback(() => {\n const nextChatId = getNewChatId();\n setNewChatId(nextChatId);\n return nextChatId;\n }, [setNewChatId]);\n\n const setPromptPlaceholder = useCallback((placeholder: string) => {\n setPromptPlaceholderState(placeholder);\n }, []);\n\n const clearPromptPlaceholder = useCallback(() => {\n setPromptPlaceholderState(undefined);\n }, []);\n\n useEffect(\n function resetStateOnChatChange() {\n clearPromptPlaceholder();\n },\n [chatId, newChatId, clearPromptPlaceholder],\n );\n\n const contextValue = useMemo(\n () => ({\n newChatId,\n chatId,\n loadedChatIdsRef,\n isNewChat,\n goToNewChat,\n promptPlaceholder,\n setPromptPlaceholder,\n clearPromptPlaceholder,\n }),\n [\n chatId,\n loadedChatIdsRef,\n newChatId,\n isNewChat,\n goToNewChat,\n promptPlaceholder,\n setPromptPlaceholder,\n clearPromptPlaceholder,\n ],\n );\n\n return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n type ReactNode,\n useState,\n} from 'react';\n\nimport type { ChatId } from '@/types';\n\nconst LAST_ITEM_SCROLL_MAX_COUNT = 3;\nconst USER_SCROLL_INTENT_IDLE_MS = 250;\n\nexport interface ChatConversationContextValue {\n viewportRef: (node: HTMLDivElement | null) => void;\n bottomTriggerRef: (node: HTMLLIElement | null) => void;\n lastItemRef: (node: HTMLElement | null) => void;\n isAtBottom: boolean;\n setMessageCount: (count: number) => void;\n scrollBottom: () => void;\n scrollToLatest: () => void;\n}\n\nconst ChatConversationContext = createContext<ChatConversationContextValue | null>(null);\n\nexport function useChatConversationContext() {\n const context = useContext(ChatConversationContext);\n\n if (!context) {\n throw new Error('\"useChatConversationContext\" must be used within a ChatConversationProvider');\n }\n\n return context;\n}\n\ninterface ChatConversationProviderProps {\n children: ReactNode;\n chatId: ChatId;\n debug?: boolean;\n}\n\nexport function ChatConversationProvider({\n children,\n chatId: _chatId,\n debug = false,\n}: ChatConversationProviderProps) {\n const [isAtBottom, setIsAtBottom] = useState(true);\n const [debugInfo, setDebugInfo] = useState({\n isAtBottom: true,\n isSmoothScroll: false,\n hasUserEscaped: false,\n isProgrammaticScroll: false,\n userScrollIntent: false,\n scrollStrategy: 'lastItem' as 'end' | 'lastItem',\n });\n\n const viewportNodeRef = useRef<HTMLDivElement | null>(null);\n const bottomTriggerNodeRef = useRef<HTMLLIElement | null>(null);\n const lastItemNodeRef = useRef<HTMLElement | null>(null);\n const resizeObserverRef = useRef<ResizeObserver | null>(null);\n const viewportResizeObserverRef = useRef<ResizeObserver | null>(null);\n const bottomTriggerObserverRef = useRef<IntersectionObserver | null>(null);\n\n const messageCountRef = useRef(0);\n const isAtBottomRef = useRef(true);\n const isSmoothScrollRef = useRef<boolean>(false);\n const hasUserEscapedRef = useRef<boolean>(false);\n const isProgrammaticScrollRef = useRef<boolean>(false);\n const userScrollIntentRef = useRef<boolean>(false);\n const userScrollIntentTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const lastScrollTopRef = useRef<number | null>(null);\n const scrollStrategyRef = useRef<'end' | 'lastItem'>('lastItem');\n const lastViewportScrollHeightRef = useRef(0);\n const scrollRef = useRef<() => void>(() => {});\n const attachLastItemResizeObserverRef = useRef<(node: HTMLElement) => void>(() => {});\n const detachLastItemResizeObserverRef = useRef<() => void>(() => {});\n const syncDebugInfoRef = useRef<() => void>(() => {});\n\n const syncDebugInfo = useCallback(() => {\n if (!debug) {\n return;\n }\n\n setDebugInfo({\n isAtBottom: isAtBottomRef.current,\n isSmoothScroll: isSmoothScrollRef.current,\n hasUserEscaped: hasUserEscapedRef.current,\n isProgrammaticScroll: isProgrammaticScrollRef.current,\n userScrollIntent: userScrollIntentRef.current,\n scrollStrategy: scrollStrategyRef.current,\n });\n }, [debug]);\n\n syncDebugInfoRef.current = syncDebugInfo;\n\n const detachLastItemResizeObserver = useCallback(() => {\n resizeObserverRef.current?.disconnect();\n resizeObserverRef.current = null;\n }, []);\n\n detachLastItemResizeObserverRef.current = detachLastItemResizeObserver;\n\n const detachBottomTriggerObserver = useCallback(() => {\n bottomTriggerObserverRef.current?.disconnect();\n bottomTriggerObserverRef.current = null;\n }, []);\n\n const detachViewportResizeObserver = useCallback(() => {\n viewportResizeObserverRef.current?.disconnect();\n viewportResizeObserverRef.current = null;\n }, []);\n\n const syncAtBottomFromViewportRef = useRef<() => void>(() => {});\n\n const clearProgrammaticScroll = useCallback(() => {\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n isProgrammaticScrollRef.current = false;\n syncAtBottomFromViewportRef.current();\n syncDebugInfoRef.current();\n });\n });\n }, []);\n\n const clearUserScrollIntent = useCallback(() => {\n if (userScrollIntentTimeoutRef.current) {\n clearTimeout(userScrollIntentTimeoutRef.current);\n userScrollIntentTimeoutRef.current = null;\n }\n\n if (!userScrollIntentRef.current) {\n return;\n }\n\n userScrollIntentRef.current = false;\n syncDebugInfoRef.current();\n }, []);\n\n const markUserScrollIntent = useCallback(() => {\n userScrollIntentRef.current = true;\n if (userScrollIntentTimeoutRef.current) {\n clearTimeout(userScrollIntentTimeoutRef.current);\n }\n\n userScrollIntentTimeoutRef.current = setTimeout(() => {\n userScrollIntentTimeoutRef.current = null;\n userScrollIntentRef.current = false;\n syncDebugInfoRef.current();\n }, USER_SCROLL_INTENT_IDLE_MS);\n\n syncDebugInfoRef.current();\n }, []);\n\n const applyLastItemScrollStrategy = useCallback(() => {\n scrollStrategyRef.current = 'lastItem';\n detachLastItemResizeObserverRef.current();\n syncDebugInfoRef.current();\n }, []);\n\n const setHasUserEscaped = useCallback((hasUserEscaped: boolean) => {\n if (hasUserEscapedRef.current === hasUserEscaped) {\n return;\n }\n\n hasUserEscapedRef.current = hasUserEscaped;\n\n if (hasUserEscaped) {\n syncAtBottomFromViewportRef.current();\n }\n\n syncDebugInfoRef.current();\n }, []);\n\n const scroll = useCallback(() => {\n if (hasUserEscapedRef.current) {\n return;\n }\n\n isProgrammaticScrollRef.current = true;\n syncDebugInfoRef.current();\n\n const behavior = isSmoothScrollRef.current ? 'smooth' : 'instant';\n isSmoothScrollRef.current = true;\n\n requestAnimationFrame(() => {\n if (hasUserEscapedRef.current) {\n clearProgrammaticScroll();\n return;\n }\n\n if (scrollStrategyRef.current === 'lastItem') {\n lastItemNodeRef.current?.scrollIntoView({ behavior, block: 'start', inline: 'start' });\n } else {\n viewportNodeRef.current?.scrollTo({\n top: viewportNodeRef.current.scrollHeight,\n behavior,\n });\n }\n\n clearProgrammaticScroll();\n syncDebugInfoRef.current();\n });\n }, [clearProgrammaticScroll]);\n\n scrollRef.current = scroll;\n\n const stickScrollToEnd = useCallback(() => {\n const node = viewportNodeRef.current;\n\n if (!node) {\n return;\n }\n\n const scrollHeight = node.scrollHeight;\n const distanceFromBottom = scrollHeight - node.clientHeight - node.scrollTop;\n\n if (distanceFromBottom <= 1 && scrollHeight === lastViewportScrollHeightRef.current) {\n return;\n }\n\n lastViewportScrollHeightRef.current = scrollHeight;\n isProgrammaticScrollRef.current = true;\n syncDebugInfoRef.current();\n\n requestAnimationFrame(() => {\n node.scrollTo({\n top: scrollHeight,\n behavior: 'instant',\n });\n\n lastViewportScrollHeightRef.current = node.scrollHeight;\n clearProgrammaticScroll();\n syncDebugInfoRef.current();\n });\n }, [clearProgrammaticScroll]);\n\n const syncAtBottomFromViewport = useCallback(() => {\n const node = viewportNodeRef.current;\n\n if (!node) {\n return;\n }\n\n const atBottom = node.scrollHeight - node.clientHeight - node.scrollTop <= 1;\n\n if (!atBottom && !hasUserEscapedRef.current) {\n return;\n }\n\n isAtBottomRef.current = atBottom;\n setIsAtBottom(atBottom);\n\n if (scrollStrategyRef.current === 'end' && atBottom) {\n stickScrollToEnd();\n }\n\n syncDebugInfoRef.current();\n }, [stickScrollToEnd]);\n\n syncAtBottomFromViewportRef.current = syncAtBottomFromViewport;\n\n const attachViewportResizeObserver = useCallback(() => {\n detachViewportResizeObserver();\n\n const node = viewportNodeRef.current;\n\n if (!node) {\n return;\n }\n\n const observer = new ResizeObserver(() => {\n syncAtBottomFromViewportRef.current();\n });\n\n observer.observe(node);\n viewportResizeObserverRef.current = observer;\n }, [detachViewportResizeObserver]);\n\n const attachLastItemResizeObserver = useCallback(\n (node: HTMLElement) => {\n detachLastItemResizeObserver();\n\n if (scrollStrategyRef.current !== 'end') {\n return;\n }\n\n const observer = new ResizeObserver(() => {\n // check the scroll strategy allways in callback to avoid race condition\n if (scrollStrategyRef.current === 'end') {\n stickScrollToEnd();\n }\n });\n\n observer.observe(node);\n resizeObserverRef.current = observer;\n },\n [detachLastItemResizeObserver, stickScrollToEnd],\n );\n\n attachLastItemResizeObserverRef.current = attachLastItemResizeObserver;\n\n const applyEndScrollStrategy = useCallback(() => {\n if (!userScrollIntentRef.current || scrollStrategyRef.current === 'end') {\n return;\n }\n\n scrollStrategyRef.current = 'end';\n clearUserScrollIntent();\n\n const lastItem = lastItemNodeRef.current;\n\n if (lastItem) {\n attachLastItemResizeObserverRef.current(lastItem);\n }\n\n syncDebugInfoRef.current();\n }, [clearUserScrollIntent]);\n\n const handleBottomTriggerVisibility = useCallback(\n (isVisible: boolean) => {\n if (!isVisible && !hasUserEscapedRef.current) {\n syncDebugInfoRef.current();\n return;\n }\n\n isAtBottomRef.current = isVisible;\n setIsAtBottom(isVisible);\n\n if (isProgrammaticScrollRef.current) {\n syncDebugInfoRef.current();\n return;\n }\n\n if (isVisible) {\n setHasUserEscaped(false);\n applyEndScrollStrategy();\n }\n\n syncDebugInfoRef.current();\n },\n [applyEndScrollStrategy, setHasUserEscaped],\n );\n\n const handleScroll = useCallback(\n (event: Event) => {\n if (event.target !== viewportNodeRef.current) {\n return;\n }\n\n const node = event.target as HTMLDivElement;\n const lastScrollTop = lastScrollTopRef.current ?? node.scrollTop;\n const currentScrollTop = node.scrollTop;\n\n lastScrollTopRef.current = currentScrollTop;\n\n if (isProgrammaticScrollRef.current || !userScrollIntentRef.current) {\n return;\n }\n\n const isScrollingUp = currentScrollTop < lastScrollTop;\n const atBottom = node.scrollHeight - node.clientHeight - currentScrollTop <= 1;\n\n if (atBottom) {\n if (scrollStrategyRef.current !== 'end') {\n handleBottomTriggerVisibility(true);\n }\n\n return;\n }\n\n if (isScrollingUp) {\n setHasUserEscaped(true);\n applyLastItemScrollStrategy();\n }\n },\n [applyLastItemScrollStrategy, handleBottomTriggerVisibility, setHasUserEscaped],\n );\n\n const handleWheel = useCallback(\n (event: WheelEvent) => {\n const node = viewportNodeRef.current;\n\n if (event.deltaY < 0 && node && node.scrollHeight > node.clientHeight) {\n setHasUserEscaped(true);\n applyLastItemScrollStrategy();\n }\n\n markUserScrollIntent();\n },\n [applyLastItemScrollStrategy, markUserScrollIntent, setHasUserEscaped],\n );\n\n const handleTouchStart = useCallback(() => {\n markUserScrollIntent();\n }, [markUserScrollIntent]);\n\n const handlePointerDown = useCallback(() => {\n markUserScrollIntent();\n }, [markUserScrollIntent]);\n\n const attachBottomTriggerObserver = useCallback(() => {\n detachBottomTriggerObserver();\n\n const root = viewportNodeRef.current;\n const target = bottomTriggerNodeRef.current;\n\n if (!root || !target) {\n return;\n }\n\n const observer = new IntersectionObserver(\n ([entry]) => {\n if (!entry) {\n return;\n }\n\n handleBottomTriggerVisibility(entry.isIntersecting);\n },\n { root, threshold: 0 },\n );\n\n observer.observe(target);\n bottomTriggerObserverRef.current = observer;\n }, [detachBottomTriggerObserver, handleBottomTriggerVisibility]);\n\n const viewportRef = useCallback(\n (node: HTMLDivElement | null) => {\n if (viewportNodeRef.current) {\n viewportNodeRef.current.removeEventListener('scroll', handleScroll);\n viewportNodeRef.current.removeEventListener('wheel', handleWheel);\n viewportNodeRef.current.removeEventListener('touchstart', handleTouchStart);\n viewportNodeRef.current.removeEventListener('pointerdown', handlePointerDown);\n detachViewportResizeObserver();\n }\n\n viewportNodeRef.current = node;\n\n if (node) {\n lastScrollTopRef.current = node.scrollTop;\n lastViewportScrollHeightRef.current = node.scrollHeight;\n node.addEventListener('scroll', handleScroll, { passive: true });\n node.addEventListener('wheel', handleWheel, { passive: true });\n node.addEventListener('touchstart', handleTouchStart, { passive: true });\n node.addEventListener('pointerdown', handlePointerDown);\n attachBottomTriggerObserver();\n attachViewportResizeObserver();\n syncAtBottomFromViewport();\n } else {\n clearUserScrollIntent();\n detachBottomTriggerObserver();\n detachViewportResizeObserver();\n }\n },\n [\n attachBottomTriggerObserver,\n attachViewportResizeObserver,\n clearUserScrollIntent,\n detachBottomTriggerObserver,\n detachViewportResizeObserver,\n handlePointerDown,\n handleScroll,\n handleTouchStart,\n handleWheel,\n syncAtBottomFromViewport,\n ],\n );\n\n const bottomTriggerRef = useCallback(\n (node: HTMLLIElement | null) => {\n bottomTriggerNodeRef.current = node;\n\n if (node) {\n attachBottomTriggerObserver();\n } else {\n detachBottomTriggerObserver();\n }\n },\n [attachBottomTriggerObserver, detachBottomTriggerObserver],\n );\n\n const lastItemRef = useCallback(\n (node: HTMLElement | null) => {\n const previousNode = lastItemNodeRef.current;\n\n if (node === null) {\n detachLastItemResizeObserver();\n lastItemNodeRef.current = null;\n syncDebugInfoRef.current();\n return;\n }\n\n if (node === previousNode) {\n if (scrollStrategyRef.current === 'end') {\n attachLastItemResizeObserver(node);\n }\n\n return;\n }\n\n detachLastItemResizeObserver();\n lastItemNodeRef.current = node;\n\n // Intentional: on every new last-item node, reset to lastItem so the viewport\n // shows the head (start) of the new message. Do not change this.\n setHasUserEscaped(false);\n isAtBottomRef.current = true;\n setIsAtBottom(true);\n scrollStrategyRef.current = 'lastItem';\n\n if (node) {\n attachLastItemResizeObserver(node);\n }\n\n syncDebugInfoRef.current();\n },\n [attachLastItemResizeObserver, detachLastItemResizeObserver, setHasUserEscaped],\n );\n\n const setMessageCount = useCallback(\n (count: number) => {\n messageCountRef.current = count;\n\n if (count < LAST_ITEM_SCROLL_MAX_COUNT) {\n scrollStrategyRef.current = 'lastItem';\n detachLastItemResizeObserver();\n } else if (scrollStrategyRef.current === 'end') {\n const lastItem = lastItemNodeRef.current;\n\n if (lastItem) {\n attachLastItemResizeObserver(lastItem);\n }\n }\n\n syncDebugInfoRef.current();\n },\n [attachLastItemResizeObserver, detachLastItemResizeObserver],\n );\n\n const reset = useCallback(() => {\n setHasUserEscaped(false);\n\n if (messageCountRef.current < LAST_ITEM_SCROLL_MAX_COUNT) {\n scrollStrategyRef.current = 'lastItem';\n detachLastItemResizeObserver();\n }\n\n syncDebugInfoRef.current();\n }, [detachLastItemResizeObserver, setHasUserEscaped]);\n\n const scrollBottom = useCallback(() => {\n reset();\n markUserScrollIntent();\n applyEndScrollStrategy();\n isProgrammaticScrollRef.current = true;\n syncDebugInfoRef.current();\n\n const behavior = isSmoothScrollRef.current ? 'smooth' : 'instant';\n isSmoothScrollRef.current = true;\n\n requestAnimationFrame(() => {\n viewportNodeRef.current?.scrollTo({\n top: viewportNodeRef.current.scrollHeight,\n behavior,\n });\n\n clearProgrammaticScroll();\n syncDebugInfoRef.current();\n });\n }, [applyEndScrollStrategy, clearProgrammaticScroll, markUserScrollIntent, reset]);\n\n const scrollToLatest = useCallback(() => {\n scroll();\n }, [scroll]);\n\n const contextValue = useMemo<ChatConversationContextValue>(\n () => ({\n viewportRef,\n bottomTriggerRef,\n lastItemRef,\n isAtBottom,\n setMessageCount,\n scrollBottom,\n scrollToLatest,\n }),\n [\n viewportRef,\n bottomTriggerRef,\n lastItemRef,\n isAtBottom,\n setMessageCount,\n scrollBottom,\n scrollToLatest,\n ],\n );\n\n return (\n <ChatConversationContext.Provider value={contextValue}>\n {debug && (\n <code className=\"absolute top-0 left-0 z-50 w-full bg-red-500/90 p-8 text-white pointer-events-none\">\n {JSON.stringify(debugInfo, null, 2)}\n </code>\n )}\n {children}\n </ChatConversationContext.Provider>\n );\n}\n","import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';\nimport {\n createContext,\n memo,\n useContext,\n useLayoutEffect,\n useMemo,\n type CSSProperties,\n type ReactNode,\n type ComponentProps,\n} from 'react';\n\nimport { useChatConversationContext } from '@/contexts';\nimport { ChevronDownIcon } from '@swisper.ai/icons';\nimport { IconButton, Tooltip } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\ninterface ChatMessagesContextValue {\n messageCount: number;\n}\n\nconst ChatMessagesContext = createContext<ChatMessagesContextValue | null>(null);\n\nconst ChatMessagesListRowContext = createContext(false);\n\nfunction useChatMessagesContext() {\n const context = useContext(ChatMessagesContext);\n\n if (!context) {\n throw new Error('\"ChatMessagesList\" must be used within a ChatMessages');\n }\n\n return context;\n}\n\nexport interface ChatMessagesProps {\n /** A `ChatMessagesList` and an optional `ChatMessagesScrollButton`. */\n children: ReactNode;\n /** Classes merged last onto the root (`data-slot=\"chat-messages\"`). */\n className?: string;\n /** Number of rows `ChatMessagesList` renders; changing it scrolls the last row into view. */\n messageCount?: number;\n /** Space in px between rows and between the messages inside a `ChatMessageListGroup`. */\n gap?: number;\n}\n\n/**\n * Root of a conversation that scrolls itself. It holds the row count and the gap, and has to be\n * rendered inside a `ChatConversationProvider`, which owns the scroll state.\n */\nexport function ChatMessages({\n children,\n className,\n messageCount = 0,\n gap = 16,\n}: ChatMessagesProps) {\n const { setMessageCount } = useChatConversationContext();\n const contextValue = useMemo<ChatMessagesContextValue>(() => ({ messageCount }), [messageCount]);\n\n useLayoutEffect(() => {\n setMessageCount(messageCount);\n }, [messageCount, setMessageCount]);\n\n return (\n <ChatMessagesContext.Provider value={contextValue}>\n <div\n data-slot=\"chat-messages\"\n data-testid=\"chat-messages\"\n className={cn('relative flex min-h-0 flex-1 flex-col', className)}\n style={{ '--chat-messages-gap': `${gap}px` } as CSSProperties}\n >\n {children}\n </div>\n </ChatMessagesContext.Provider>\n );\n}\n\nexport interface ChatMessagesListProps {\n /** Render function for one row; it gets the row's index and returns a `ChatMessageListGroup`. */\n children: (index: number) => ReactNode;\n /** Classes merged last onto the `role=\"log\"` list (`data-slot=\"chat-messages-list\"`). */\n className?: string;\n /** Classes merged last onto the scroll container (`data-slot=\"chat-messages-scroll-area\"`). */\n scrollAreaClassName?: string;\n /** Classes merged last onto the scrolling viewport (`data-slot=\"chat-messages-viewport\"`). */\n viewportClassName?: string;\n /** Classes merged last onto the hidden end sentinel the list uses to detect the bottom. */\n bottomTriggerClassName?: string;\n}\n\n/**\n * The scrolling list: renders `messageCount` rows from its render function inside a `role=\"log\"`\n * list, and scrolls the last row to the top of the view when the count changes.\n */\nexport function ChatMessagesList({\n children,\n className,\n scrollAreaClassName,\n viewportClassName,\n bottomTriggerClassName,\n}: ChatMessagesListProps) {\n const { viewportRef, bottomTriggerRef, scrollToLatest } = useChatConversationContext();\n const { messageCount } = useChatMessagesContext();\n\n const rows = useMemo(() => {\n return Array.from({ length: messageCount }, (_, index) => index);\n }, [messageCount]);\n\n const lastIndex = messageCount - 1;\n\n useLayoutEffect(() => {\n scrollToLatest();\n }, [messageCount, scrollToLatest]);\n\n return (\n <ScrollAreaPrimitive.Root\n data-slot=\"chat-messages-scroll-area\"\n className={cn(\n 'min-h-0 flex-1',\n 'relative group/scroll-area',\n 'overflow-y-hidden',\n 'transform-gpu',\n scrollAreaClassName,\n )}\n >\n <ScrollAreaPrimitive.Viewport\n ref={viewportRef}\n data-slot=\"chat-messages-viewport\"\n className={cn('@container-[size]', 'will-change-scroll h-full w-full', viewportClassName)}\n style={{ scrollbarGutter: 'stable both-edges' }}\n >\n <ul\n data-slot=\"chat-messages-list\"\n data-testid=\"chat-messages-list\"\n role=\"log\"\n aria-label=\"Message list\"\n aria-atomic=\"false\"\n className={cn('m-0 flex flex-col gap-(--chat-messages-gap) p-0', className)}\n >\n {rows.map((index) => (\n <ChatMessagesListRow key={index} index={index} isLast={index === lastIndex}>\n {children}\n </ChatMessagesListRow>\n ))}\n\n <li\n ref={bottomTriggerRef}\n data-slot=\"chat-messages-bottom-trigger\"\n className={cn('h-px -mt-(--chat-messages-gap)', bottomTriggerClassName)}\n aria-hidden=\"true\"\n />\n </ul>\n </ScrollAreaPrimitive.Viewport>\n\n <ChatMessagesScrollBar orientation=\"vertical\" />\n </ScrollAreaPrimitive.Root>\n );\n}\n\ninterface ChatMessagesListRowProps {\n children: (index: number) => ReactNode;\n index: number;\n isLast: boolean;\n}\n\nconst ChatMessagesListRow = memo(function ChatMessagesListRow({\n children,\n index,\n isLast,\n}: ChatMessagesListRowProps) {\n return (\n <li data-slot=\"chat-messages-row\">\n <ChatMessagesListRowContext.Provider value={isLast}>\n {children(index)}\n </ChatMessagesListRowContext.Provider>\n </li>\n );\n});\n\nexport interface ChatMessageListGroupProps extends ComponentProps<'div'> {}\n\n/**\n * One row's content: a question with its answer. The last group is at least as tall as the\n * viewport, so a new question can settle at the top while its answer grows below it.\n */\nexport function ChatMessageListGroup({ children, className, ...rest }: ChatMessageListGroupProps) {\n const isLast = useContext(ChatMessagesListRowContext);\n const { lastItemRef } = useChatConversationContext();\n\n return (\n <div\n ref={isLast ? lastItemRef : undefined}\n data-slot=\"chat-message-list-group\"\n data-is-last={isLast}\n className={cn(\n 'flex flex-col gap-(--chat-messages-gap)',\n 'data-[is-last=true]:min-h-[calc(100cqh-var(--chat-messages-gap))]',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessagesScrollButtonProps {\n /** Classes merged last onto the positioned wrapper (`data-slot=\"chat-messages-scroll-button\"`). */\n className?: string;\n /** Classes merged last onto the icon button inside the wrapper. */\n buttonClassName?: string;\n /** The button's tooltip and its `aria-label`. */\n tooltip?: string;\n /** Replaces the chevron icon. */\n children?: ReactNode;\n}\n\ninterface ChatMessagesScrollBarProps extends ComponentProps<\n typeof ScrollAreaPrimitive.ScrollAreaScrollbar\n> {\n className?: string;\n orientation?: 'vertical' | 'horizontal';\n}\n\nfunction ChatMessagesScrollBar({\n className,\n orientation = 'vertical',\n ...rest\n}: ChatMessagesScrollBarProps) {\n return (\n <ScrollAreaPrimitive.ScrollAreaScrollbar\n data-slot=\"scroll-area-scrollbar\"\n orientation={orientation}\n className={cn(\n 'opacity-0 group-hover/scroll-area:opacity-100',\n 'rounded-[8px]',\n 'bg-scrollbar-track hover:bg-scrollbar-track-hover',\n 'transition-opacity duration-200 ease-in-out',\n 'flextouch-none select-none transition-colors',\n orientation === 'vertical' &&\n 'h-full w-scrollbar border-l border-l-transparent px-4 py-[12px]',\n orientation === 'horizontal' &&\n 'h-scrollbar w-full border-t border-t-transparent px-[12px] py-4',\n className,\n )}\n {...rest}\n >\n <ScrollAreaPrimitive.ScrollAreaThumb\n data-slot=\"scroll-area-thumb\"\n className={cn(\n 'relative flex-1 rounded-full',\n 'bg-scrollbar-thumb hover:bg-scrollbar-thumb-hover',\n orientation === 'vertical' && 'w-scrollbar-thumb!',\n orientation === 'horizontal' && 'h-scrollbar-thumb!',\n )}\n />\n </ScrollAreaPrimitive.ScrollAreaScrollbar>\n );\n}\n\n/**\n * Scroll-to-latest button over the list. It is hidden while the view is at the bottom and scrolls\n * there when clicked.\n */\nexport const ChatMessagesScrollButton = memo(function ChatMessagesScrollButton({\n className,\n buttonClassName,\n tooltip,\n children,\n}: ChatMessagesScrollButtonProps) {\n const { isAtBottom, scrollBottom } = useChatConversationContext();\n\n return (\n <div\n data-slot=\"chat-messages-scroll-button\"\n data-testid=\"chat-message-history-scroll-button\"\n data-hidden={isAtBottom}\n aria-hidden={isAtBottom ? true : undefined}\n className={cn(\n 'absolute',\n 'px-[12px]',\n 'bottom-0',\n 'right-0 -translate-x-[12px]',\n 'md:right-auto md:left-1/2 md:-translate-x-1/2',\n '-translate-y-[12px]',\n 'flex items-center justify-center',\n 'transition-opacity duration-200 ease-in-out',\n 'data-[hidden=true]:pointer-events-none',\n 'data-[hidden=true]:opacity-0 data-[hidden=false]:opacity-100',\n className,\n )}\n >\n <Tooltip tooltip={tooltip} side={'top'}>\n <IconButton\n className={cn('bg-paper-elevation-2', buttonClassName)}\n color=\"primary\"\n size=\"md\"\n onClick={() => scrollBottom()}\n tabIndex={-1}\n aria-label={tooltip}\n >\n {children || <ChevronDownIcon />}\n </IconButton>\n </Tooltip>\n </div>\n );\n});\n","import type { ReactNode } from 'react';\n\nimport { CloseIcon } from '@swisper.ai/icons';\nimport { IconButton, Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatMessageAttachmentCardProps {\n /** Classes merged last onto the card root, e.g. `w-fit max-w-60` to cap the chip's width. */\n className?: string;\n /** The card parts: an icon or a preview, the content with the file name, and the actions. */\n children?: ReactNode;\n /** Shrinks the card to a 56px square for an image shown through `ChatMessageAttachmentCardPreview`. */\n isPreview?: boolean;\n /** Shows a pointer cursor, a hover background and the remove action on hover. Set `false` for a sent message's attachments. */\n isInteractive?: boolean;\n}\n\n/** A compact chip for a file attached to a chat prompt or message. */\nexport function ChatMessageAttachmentCard({\n className,\n children,\n isPreview,\n isInteractive = true,\n}: ChatMessageAttachmentCardProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-message-attachment-card\"\n data-testid=\"chat-message-attachment-card\"\n data-preview={isPreview}\n data-interactive={isInteractive}\n className={cn(\n 'group/chat-message-attachment-card',\n 'relative',\n 'flex flex-row gap-8',\n 'p-8 rounded-promptbox-attachment',\n 'bg-promptbox-attachment-background',\n 'data-[interactive=true]:cursor-pointer',\n 'data-[interactive=true]:hover:bg-[linear-gradient(var(--color-promptbox-attachment-background-hover),var(--color-promptbox-attachment-background-hover)),linear-gradient(var(--color-promptbox-attachment-background),var(--color-promptbox-attachment-background))]',\n 'data-[preview=true]:m-px',\n 'data-[preview=true]:size-[56px]',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageAttachmentCardContentProps {\n /** Classes merged last onto the content element. */\n className?: string;\n /** The file name, usually a `ChatMessageAttachmentCardTitle`. */\n children?: ReactNode;\n}\n\n/** The text area of the card: takes the width left beside the icon and clips what overflows. */\nexport function ChatMessageAttachmentCardContent({\n className,\n children,\n}: ChatMessageAttachmentCardContentProps) {\n return (\n <div\n data-slot=\"chat-message-attachment-card-content\"\n data-testid=\"chat-message-attachment-card-content\"\n className={cn('flex-1', 'flex items-center', 'overflow-hidden', className)}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageAttachmentCardTitleProps {\n /** Classes merged last onto the title element. */\n className?: string;\n /** The file name as uploaded, including its extension. */\n children?: ReactNode;\n}\n\n/** The file name, truncated to one line. */\nexport function ChatMessageAttachmentCardTitle({\n className,\n children,\n}: ChatMessageAttachmentCardTitleProps) {\n return (\n <Typography\n variant=\"body-sm\"\n data-slot=\"chat-message-attachment-card-title\"\n data-testid=\"chat-message-attachment-card-title\"\n className={cn('truncate', className)}\n >\n {children}\n </Typography>\n );\n}\n\nexport interface ChatMessageAttachmentCardPreviewProps {\n /** Classes merged last onto the `figure` that covers the card. */\n className?: string;\n /** Classes merged last onto the image inside the figure, e.g. `object-contain`. */\n imageClassName?: string;\n /** URL of the image, e.g. a data URL read from the attached file. */\n previewSrc: string;\n}\n\n/** An image thumbnail that covers the whole card. Use it on a card with `isPreview`. */\nexport function ChatMessageAttachmentCardPreview({\n className,\n imageClassName,\n previewSrc,\n}: ChatMessageAttachmentCardPreviewProps) {\n return (\n <figure\n data-slot=\"chat-message-attachment-card-preview\"\n data-testid=\"chat-message-attachment-card-preview\"\n className={cn(\n 'absolute top-0 left-0',\n 'inset-0 w-full h-full',\n 'overflow-hidden rounded-promptbox-attachment',\n 'pointer-events-none',\n className,\n )}\n >\n <img\n data-slot=\"chat-message-attachment-card-preview-image\"\n src={previewSrc}\n alt=\"Preview\"\n className={cn('w-full h-full object-cover', imageClassName)}\n />\n </figure>\n );\n}\n\nexport interface ChatMessageAttachmentCardActionsProps {\n /** Classes merged last onto the wrapper pinned to the card's top-right corner. */\n className?: string;\n /** Classes merged last onto the remove button inside the wrapper. */\n buttonClassName?: string;\n /** Called when the remove button is clicked. The consumer removes the attachment. */\n onDelete?: () => void;\n}\n\n/** The remove button of an interactive card, shown while the card is hovered. */\nexport function ChatMessageAttachmentCardActions({\n className,\n buttonClassName,\n onDelete,\n}: ChatMessageAttachmentCardActionsProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-message-attachment-card-actions\"\n data-testid=\"chat-message-attachment-card-actions\"\n className={cn(\n 'absolute top-0 right-0',\n 'translate-x-1/2 -translate-y-1/2',\n 'hidden',\n 'group-data-[interactive=true]/chat-message-attachment-card:group-hover/chat-message-attachment-card:flex',\n 'rounded-overlay-tools-wrapper',\n 'bg-overlay-tools-background-base',\n className,\n )}\n >\n <IconButton\n variant=\"tertiary\"\n isSemantic={false}\n onClick={onDelete}\n size=\"xs\"\n className={cn('size-[24px]', 'text-icon-button-tertiary-icon', buttonClassName)}\n >\n <CloseIcon />\n </IconButton>\n </div>\n );\n}\n","import { type FunctionComponent } from 'react';\n\nimport {\n PdfIcon,\n PptIcon,\n CodeIcon,\n DocIcon,\n XlsIcon,\n DraftIcon,\n type SvgIconProps,\n} from '@swisper.ai/icons';\nimport { cn } from '@swisper.ai/web-core';\n\ntype IconProps = SvgIconProps;\n\n/** The file types the card has an icon for. `image` has no icon: show a `ChatMessageAttachmentCardPreview`. */\nexport type ChatMessageAttachmentCardIconType =\n 'spreadsheet' | 'pdf' | 'presentation' | 'document' | 'code' | 'image' | 'unknown';\n\nconst CHAT_ATTACHMENT_ICON_MAP: Record<\n Exclude<ChatMessageAttachmentCardIconType, 'image'>,\n {\n component: FunctionComponent<IconProps>;\n className?: string;\n }\n> = {\n spreadsheet: {\n component: XlsIcon,\n className: 'bg-data-d',\n },\n pdf: {\n component: PdfIcon,\n className: 'bg-data-a',\n },\n presentation: {\n component: PptIcon,\n className: 'bg-data-e',\n },\n document: {\n component: DocIcon,\n className: 'bg-data-c',\n },\n code: {\n component: CodeIcon,\n className: 'bg-data-f',\n },\n unknown: {\n component: DraftIcon,\n className: 'bg-data-f',\n },\n};\n\nexport interface ChatMessageAttachmentCardIconProps extends IconProps {\n /** The file type, which picks the icon and its background colour. `getAttachmentIcon(file)` returns it. */\n icon: Exclude<ChatMessageAttachmentCardIconType, 'image'>;\n}\n\n/** The file-type icon on its coloured tile. `className` goes to the tile, every other prop to the icon. */\nexport function ChatMessageAttachmentCardIcon({\n icon,\n className,\n ...rest\n}: ChatMessageAttachmentCardIconProps) {\n const { component: Icon, className: iconClassName } = CHAT_ATTACHMENT_ICON_MAP[icon];\n\n return (\n <span\n data-slot=\"chat-message-attachment-card-icon\"\n data-testid=\"chat-attachment-icon\"\n data-icon={icon}\n className={cn(\n 'inline-flex items-center justify-center',\n 'rounded-[8px]',\n 'p-8',\n 'size-promptbox-attachment-size-icon-container',\n 'text-icon-fill-inverse',\n '[&_svg]:size-[24px]',\n iconClassName,\n className,\n )}\n >\n <Icon {...rest} />\n </span>\n );\n}\n","import mime from 'mime';\n\nimport type { ChatMessageAttachmentCardIconType } from './chat-message-attachment-card-icon';\n\ntype IconType = Exclude<ChatMessageAttachmentCardIconType, 'image'>;\n\nconst MIME_TO_ICON: Record<string, IconType> = {\n 'application/pdf': 'pdf',\n 'application/vnd.ms-excel': 'spreadsheet',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'spreadsheet',\n 'text/csv': 'spreadsheet',\n 'application/vnd.ms-powerpoint': 'presentation',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'presentation',\n 'application/msword': 'document',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'document',\n 'text/plain': 'document',\n 'application/rtf': 'document',\n 'application/vnd.oasis.opendocument.text': 'document',\n};\n\n/** Picks the icon type for a file from its name's extension; a file it doesn't recognise is `unknown`. */\nexport function getAttachmentIcon(file: File): IconType {\n const mimeType = mime.getType(file.name);\n\n if (!mimeType) {\n return 'unknown';\n }\n\n if (mimeType in MIME_TO_ICON) {\n return MIME_TO_ICON[mimeType];\n }\n\n if (\n mimeType.startsWith('text/') ||\n mimeType.includes('javascript') ||\n mimeType.includes('json')\n ) {\n return 'code';\n }\n\n return 'unknown';\n}\n","import type { SwiTagName } from '../../types';\n\nexport function isCustomComponentTag(tag: string): tag is SwiTagName {\n return tag.startsWith('swi-');\n}\n","import { useMemo } from 'react';\nimport rehypeSanitize, { defaultSchema } from 'rehype-sanitize';\nimport { defaultRehypePlugins, defaultRemarkPlugins, type StreamdownProps } from 'streamdown';\nimport { type PluggableList } from 'unified';\n\nimport type { SwiTagName } from '../../types';\n\nimport type { CustomMarkdownViewerComponents, MarkdownViewerComponents } from './types';\nimport { isCustomComponentTag } from './utils';\n\nexport interface UseMarkdownViewerHookProps {\n customComponents: CustomMarkdownViewerComponents;\n}\n\ntype UseMarkdownViewerHook = Pick<\n StreamdownProps,\n 'components' | 'remarkPlugins' | 'rehypePlugins'\n>;\n\nexport function useMarkdownViewer({\n customComponents,\n}: UseMarkdownViewerHookProps): UseMarkdownViewerHook {\n const swiTags = useMemo<SwiTagName[]>(\n () =>\n Object.keys(customComponents).filter((key): key is SwiTagName => {\n if (!isCustomComponentTag(key)) {\n console.warn(`[MarkdownViewer] Invalid custom component tag: ${key}`);\n return false;\n }\n\n return true;\n }),\n [customComponents],\n );\n\n const remarkPlugins = useMemo<PluggableList>(() => [...Object.values(defaultRemarkPlugins)], []);\n const rehypePlugins = useMemo<PluggableList>(() => {\n return [\n ...Object.values(defaultRehypePlugins),\n [\n rehypeSanitize,\n {\n ...defaultSchema,\n tagNames: [...(defaultSchema?.tagNames || []), ...swiTags],\n protocols: {\n ...defaultSchema?.protocols,\n href: [...(defaultSchema?.protocols?.href ?? []), 'swisper', 'swisper://'],\n },\n },\n ],\n ];\n }, [swiTags]);\n\n return {\n components: customComponents satisfies MarkdownViewerComponents,\n remarkPlugins,\n rehypePlugins,\n };\n}\n","import { Streamdown } from 'streamdown';\n\nimport type { Markdown } from '../../types';\n\nimport { useMarkdownViewer } from './hooks';\nimport type { CustomMarkdownViewerComponents } from './types';\n\nimport 'katex/dist/katex.min.css';\n\nexport interface MarkdownViewerProps {\n /** The full markdown received so far: GFM, math and `<swi-*>` tags. */\n markdown: Markdown;\n /** Classes merged last onto the root element, e.g. `text-text-secondary` or a different block gap. */\n className?: string;\n /** Set while the text is still arriving: animates the last block and shows the caret. */\n isStreaming?: boolean;\n /** Shows a block caret after the last character while `isStreaming` is true. */\n hasCaret?: boolean;\n /** Renderers keyed by tag name: `<swi-*>` tags, or overrides for standard markdown elements. */\n customComponents?: CustomMarkdownViewerComponents;\n}\n\n/** Renders markdown through Streamdown, repairing half-received syntax and `<swi-*>` tags as it streams. */\nexport function MarkdownViewer({\n markdown,\n className,\n isStreaming = false,\n hasCaret = false,\n customComponents = {},\n}: MarkdownViewerProps) {\n const { components, remarkPlugins, rehypePlugins } = useMarkdownViewer({ customComponents });\n\n return (\n <Streamdown\n className={className}\n caret={hasCaret ? 'block' : undefined}\n isAnimating={isStreaming}\n components={components}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n linkSafety={{ enabled: false }}\n remend={{\n handlers: [\n {\n name: 'swi-tag-filter',\n handle: swiTagHandler,\n priority: 0,\n },\n ],\n }}\n >\n {markdown}\n </Streamdown>\n );\n}\n\nfunction swiTagHandler(text: string, separator = '|') {\n const incompleteRegex = /<swi-(\\w+)([^>]*)$/gm;\n const [incompleteMatch, tagName] = incompleteRegex.exec(text) ?? [];\n\n if (text.endsWith('<swi-')) {\n return text + '>';\n }\n\n if (incompleteMatch) {\n return text.replace(incompleteMatch, `<swi-${tagName}>`);\n }\n\n if (text.endsWith(separator)) {\n return text.slice(0, -1) + `</swi-${tagName}>`;\n }\n\n const openingTagRegex = /<swi-(\\w+)([^>]*)>/g;\n const openingTags: { name: string; index: number }[] = [];\n let match;\n\n openingTagRegex.lastIndex = 0;\n while ((match = openingTagRegex.exec(text)) !== null) {\n const tagName = match[1];\n const attributes = match[2];\n\n if (attributes.trim().endsWith('/')) {\n continue;\n }\n\n openingTags.push({\n name: tagName,\n index: match.index,\n });\n }\n\n if (openingTags.length > 0) {\n const lastTag = openingTags[openingTags.length - 1];\n const tagName = lastTag.name;\n const closingTag = `</swi-${tagName}>`;\n\n const textAfterOpening = text.substring(lastTag.index);\n if (!textAfterOpening.includes(closingTag)) {\n return text + closingTag;\n }\n }\n\n return text;\n}\n","import { useMemo } from 'react';\n\nimport type { Markdown } from '../../types';\nimport { MarkdownViewer, type CustomMarkdownViewerComponents } from '../markdown-viewer';\n\nexport interface ChatMessageResponseProps {\n message: Markdown;\n isStreaming?: boolean;\n}\n\nexport function ChatMessageResponse({ message, isStreaming }: ChatMessageResponseProps) {\n const customComponents = useMemo<CustomMarkdownViewerComponents>(() => {\n return {};\n }, []);\n\n return (\n <MarkdownViewer\n hasCaret={false}\n markdown={message}\n isStreaming={isStreaming}\n customComponents={customComponents}\n />\n );\n}\n","import { forwardRef, type ComponentProps, type ReactNode } from 'react';\n\nimport { IconButton, Tooltip, type IconButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatMessageToolbarProps extends ComponentProps<'div'> {\n /** The toolbar parts: a `ChatMessageToolbarTimestamp` and a `ChatMessageToolbarActions`. */\n children: ReactNode;\n /** Classes merged last onto the row. */\n className?: string;\n /** Flips the row, so the first part sits at the end. Set it under an end-aligned question. */\n reverse?: boolean;\n}\n\n/** The row under a chat message: its timestamp at one end, its icon actions at the other. */\nexport function ChatMessageToolbar({\n children,\n className,\n reverse = false,\n ...rest\n}: ChatMessageToolbarProps) {\n return (\n <div\n data-slot=\"chat-message-toolbar\"\n data-testid=\"chat-message-toolbar\"\n data-reverse={reverse}\n className={cn(\n 'flex items-center justify-between',\n 'gap-16',\n 'h-24',\n 'data-[reverse=true]:flex-row-reverse',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageToolbarActionsProps extends ComponentProps<'div'> {\n /** The actions, each a `ChatMessageToolbarActionButton`. */\n children: ReactNode;\n /** Classes merged last onto the group. */\n className?: string;\n}\n\n/** Groups the toolbar's action buttons in a `role=\"group\"` row. */\nexport function ChatMessageToolbarActions({\n children,\n className,\n ...rest\n}: ChatMessageToolbarActionsProps) {\n return (\n <div\n data-slot=\"chat-message-toolbar-actions\"\n data-testid=\"chat-message-toolbar-actions\"\n role=\"group\"\n className={cn('flex items-center gap-8', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageToolbarActionButtonProps extends Omit<\n IconButtonProps,\n 'variant' | 'size'\n> {\n /** The action's icon. */\n children: ReactNode;\n /** Classes merged last onto the button. */\n className?: string;\n /** Text of the hover tooltip. It is not the accessible name: pass `aria-label` as well. */\n tooltip?: string;\n}\n\n/**\n * One icon action in the toolbar: an extra-small tertiary `IconButton`, in a `Tooltip` when\n * `tooltip` is set. The ref reaches the button, so it can be an `asChild` menu or popover trigger.\n */\nexport const ChatMessageToolbarActionButton = forwardRef<\n HTMLButtonElement | HTMLSpanElement,\n ChatMessageToolbarActionButtonProps\n>(function ChatMessageToolbarActionButton({ children, className, tooltip, ...rest }, ref) {\n const content = (\n <IconButton\n ref={ref}\n variant=\"tertiary\"\n isSemantic={false}\n size=\"xs\"\n data-slot=\"chat-message-toolbar-action-button\"\n className={cn('text-action-active', className)}\n {...rest}\n >\n {children}\n </IconButton>\n );\n\n if (!tooltip) {\n return content;\n }\n\n return <Tooltip tooltip={tooltip}>{content}</Tooltip>;\n});\n\nChatMessageToolbarActionButton.displayName = 'ChatMessageToolbarActionButton';\n\nexport interface ChatMessageToolbarTimestampProps extends ComponentProps<'div'> {\n /** The time, already formatted. */\n children: ReactNode;\n /** Classes merged last onto the timestamp. */\n className?: string;\n}\n\n/** When the message was sent. Renders its children as given. */\nexport function ChatMessageToolbarTimestamp({\n className,\n children,\n ...rest\n}: ChatMessageToolbarTimestampProps) {\n return (\n <div\n data-slot=\"chat-message-toolbar-timestamp\"\n className={cn('text-action-active', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","export function getSnoozeUntilDate(minutes: number) {\n return new Date(Date.now() + minutes * 60 * 1000);\n}\n\nconst MINUTES_PER_HOUR = 60;\nconst MINUTES_PER_DAY = 24 * MINUTES_PER_HOUR;\nconst MILLISECONDS_PER_MINUTE = 60 * 1000;\n\nfunction formatDurationPart(value: number, unit: string) {\n return `${value} ${unit}${value === 1 ? '' : 's'}`;\n}\n\nexport function formatSnoozeDate(date: Date, prefix = 'in', now: Date = new Date()) {\n const totalMinutes = Math.max(\n 0,\n Math.ceil((date.getTime() - now.getTime()) / MILLISECONDS_PER_MINUTE),\n );\n const days = Math.floor(totalMinutes / MINUTES_PER_DAY);\n const hours = Math.floor((totalMinutes % MINUTES_PER_DAY) / MINUTES_PER_HOUR);\n const minutes = totalMinutes % MINUTES_PER_HOUR;\n const parts: string[] = [];\n\n if (days > 0) {\n parts.push(formatDurationPart(days, 'day'));\n }\n\n if (hours > 0) {\n parts.push(formatDurationPart(hours, 'hour'));\n }\n\n parts.push(formatDurationPart(minutes, 'minute'));\n\n return [prefix, ...parts].filter(Boolean).join(' ');\n}\n","import {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useMemo,\n useState,\n useEffect,\n type ComponentProps,\n type MouseEvent,\n type ReactNode,\n} from 'react';\n\nimport {\n ChevronDownIcon,\n ChevronUpIcon,\n CloseIcon,\n DeleteIcon,\n SignalReadIcon,\n SignalUnreadIcon,\n SnoozeIcon,\n} from '@swisper.ai/icons';\nimport { Button, Chip, IconButton, Typography } from '@swisper.ai/ui';\nimport type { ChipProps, IconButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport type { ChatNotificationCardPriority } from './types';\nimport { formatSnoozeDate } from './utils';\n\ninterface ChatNotificationCardContextValue {\n isExpanded: boolean;\n setExpanded: (expanded: boolean) => void;\n toggleExpanded: () => void;\n}\n\nconst ChatNotificationCardContext = createContext<ChatNotificationCardContextValue>(null!);\n\n/** The card's expanded state and its setters. Throws outside a `ChatNotificationCard`. */\nexport function useChatNotificationCardContext() {\n const context = useContext(ChatNotificationCardContext);\n\n if (!context) {\n throw new Error('\"useChatNotificationCardContext\" must be used within a ChatNotificationCard');\n }\n\n return context;\n}\n\nexport interface ChatNotificationCardProps {\n children?: ReactNode;\n /** `default` for a card in a list, `floating` (bordered) for a card shown on its own over the chat. */\n variant?: 'default' | 'floating';\n className?: string;\n /** Classes for the hover overlay (`data-slot=\"chat-notification-card-overlay\"`). */\n overlayClassName?: string;\n /** Initial expanded state when uncontrolled. */\n defaultExpanded?: boolean;\n /** Controlled expanded state; pair it with `onExpandedChange`. */\n expanded?: boolean;\n /** Called with the next expanded state when the expand button is toggled. */\n onExpandedChange?: (expanded: boolean) => void;\n /** Called on a click anywhere on the card except its buttons. */\n onClick?: () => void;\n}\n\n/**\n * Root of the notification card. Holds the expanded state and exposes it, with the variant, as\n * `data-expanded` and `data-variant`.\n */\nexport function ChatNotificationCard({\n children,\n variant = 'default',\n className,\n overlayClassName,\n defaultExpanded = false,\n expanded,\n onExpandedChange,\n onClick,\n}: ChatNotificationCardProps) {\n const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);\n const isExpanded = expanded ?? internalExpanded;\n\n const setExpanded = useCallback(\n (nextExpanded: boolean) => {\n if (expanded === undefined) {\n setInternalExpanded(nextExpanded);\n }\n\n onExpandedChange?.(nextExpanded);\n },\n [expanded, onExpandedChange],\n );\n\n const toggleExpanded = useCallback(() => {\n setExpanded(!isExpanded);\n }, [isExpanded, setExpanded]);\n\n const contextValue = useMemo(\n () => ({\n isExpanded,\n setExpanded,\n toggleExpanded,\n }),\n [isExpanded, setExpanded, toggleExpanded],\n );\n\n return (\n <ChatNotificationCardContext.Provider value={contextValue}>\n <div\n role=\"alert\"\n data-slot=\"chat-notification-card\"\n data-testid=\"chat-notification-card\"\n data-variant={variant}\n data-expanded={isExpanded}\n aria-expanded={isExpanded}\n className={cn(\n 'group/chat-notification-card',\n 'relative',\n 'p-[12px]',\n 'rounded-[12px] overflow-hidden',\n 'bg-paper-elevation-2',\n 'flex flex-col gap-8',\n 'bg-paper-elevation-2',\n 'data-[variant=floating]:border data-[variant=floating]:border-component-divider',\n className,\n )}\n onClick={onClick}\n >\n {children}\n\n <div\n data-slot=\"chat-notification-card-overlay\"\n className={cn(\n 'absolute inset-0 pointer-events-none bg-secondary-states-hover opacity-0 group-hover/chat-notification-card:opacity-100 transition-opacity duration-200 ease-in-out',\n overlayClassName,\n )}\n />\n </div>\n </ChatNotificationCardContext.Provider>\n );\n}\n\nexport interface ChatNotificationCardHeadProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Top row of the card: the header on the left, the actions on the right. */\nexport function ChatNotificationCardHead({ children, className }: ChatNotificationCardHeadProps) {\n return (\n <header\n data-slot=\"chat-notification-card-head\"\n data-testid=\"chat-notification-card-head\"\n className={cn(\n 'grid grid-cols-[minmax(0,1fr)_auto] items-center gap-8',\n 'min-h-[32px]',\n className,\n )}\n >\n {children}\n </header>\n );\n}\n\nexport interface ChatNotificationCardHeaderProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Left side of the head: the icon and the title. */\nexport function ChatNotificationCardHeader({\n children,\n className,\n}: ChatNotificationCardHeaderProps) {\n return (\n <div\n data-slot=\"chat-notification-card-header\"\n data-testid=\"chat-notification-card-header\"\n className={cn(\n 'min-w-0 flex items-center gap-8 overflow-hidden',\n 'text-layout-feedback-info-background-default',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardHeaderIconProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Icon that says what kind of notification this is. */\nexport function ChatNotificationCardHeaderIcon({\n children,\n className,\n}: ChatNotificationCardHeaderIconProps) {\n return (\n <div\n data-slot=\"chat-notification-card-header-icon\"\n data-testid=\"chat-notification-card-header-icon\"\n className={cn(\n 'shrink-0',\n 'inline-flex items-center justify-center',\n 'pointer-events-none',\n '[&_svg]:size-[20px]!',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardHeaderTitleProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Holds the title label and the status chip. */\nexport function ChatNotificationCardHeaderTitle({\n children,\n className,\n}: ChatNotificationCardHeaderTitleProps) {\n return (\n <div\n data-slot=\"chat-notification-card-header-title\"\n data-testid=\"chat-notification-card-header-title\"\n className={cn('min-w-0 flex flex-1 items-center gap-8 overflow-hidden', className)}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardHeaderTitleLabelProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Notification type or short subject: semibold, uppercase, truncated to one line. */\nexport function ChatNotificationCardHeaderTitleLabel({\n children,\n className,\n}: ChatNotificationCardHeaderTitleLabelProps) {\n return (\n <Typography\n variant=\"body-sm\"\n fontWeight=\"semibold\"\n data-slot=\"chat-notification-card-header-title-label\"\n data-testid=\"chat-notification-card-header-title-label\"\n className={cn('min-w-0 truncate', 'text-left text-inherit uppercase', className)}\n asChild\n >\n <span>{children}</span>\n </Typography>\n );\n}\n\nconst CHIP_PRIORITY_MAP: Record<ChatNotificationCardPriority, ChipProps['color']> = {\n low: 'info',\n medium: 'warning',\n high: 'error',\n};\n\nexport interface ChatNotificationCardHeaderStatusProps extends Omit<\n ChipProps,\n 'color' | 'variant' | 'size'\n> {\n children?: ReactNode;\n priority?: ChatNotificationCardPriority;\n className?: string;\n}\n\n/** Priority chip: `high` is an error chip, `medium` a warning chip, `low` renders nothing. */\nexport function ChatNotificationCardHeaderStatus({\n children,\n priority = 'medium',\n className,\n ...rest\n}: ChatNotificationCardHeaderStatusProps) {\n const color = CHIP_PRIORITY_MAP[priority];\n\n if (priority === 'low') {\n return null;\n }\n\n return (\n <Chip\n data-slot=\"chat-notification-card-header-status\"\n data-testid=\"chat-notification-card-header-status\"\n data-priority={priority}\n className={cn('text-text-secondary', 'shrink-0', className)}\n size=\"2xs\"\n color={color}\n variant=\"outlined\"\n {...rest}\n >\n {children}\n </Chip>\n );\n}\n\nexport interface ChatNotificationCardActionsProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Right side of the head: the timestamp and the buttons. */\nexport function ChatNotificationCardActions({\n children,\n className,\n}: ChatNotificationCardActionsProps) {\n return (\n <div\n data-slot=\"chat-notification-card-actions\"\n data-testid=\"chat-notification-card-actions\"\n role=\"group\"\n className={cn(\n 'flex flex-row items-center justify-end',\n 'shrink-0 justify-self-end',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardTimestampProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Relative time the notification arrived. */\nexport function ChatNotificationCardTimestamp({\n children,\n className,\n}: ChatNotificationCardTimestampProps) {\n return (\n <Typography\n variant=\"caption\"\n data-slot=\"chat-notification-card-timestamp\"\n data-testid=\"chat-notification-card-timestamp\"\n className={cn('text-text-secondary', 'inline-flex px-8', 'leading-[32px]', className)}\n asChild\n >\n <span>{children}</span>\n </Typography>\n );\n}\n\nexport interface ChatNotificationCardButtonsProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Group for the action buttons. Stops their clicks from reaching the card's `onClick`. */\nexport function ChatNotificationCardButtons({\n children,\n className,\n}: ChatNotificationCardButtonsProps) {\n function handleMouseDown(event: MouseEvent<HTMLDivElement>) {\n event.stopPropagation();\n }\n\n function handleClick(event: MouseEvent<HTMLDivElement>) {\n event.stopPropagation();\n }\n\n return (\n <div\n data-slot=\"chat-notification-card-buttons\"\n data-testid=\"chat-notification-card-buttons\"\n role=\"group\"\n className={cn('flex flex-row items-center justify-end', 'gap-8', className)}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n >\n {children}\n </div>\n );\n}\n\ninterface ChatNotificationCardActionButtonProps extends Omit<\n ComponentProps<typeof IconButton>,\n 'children' | 'size' | 'variant'\n> {}\n\nexport interface ChatNotificationCardReadActionButtonProps extends Omit<\n ChatNotificationCardActionButtonProps,\n 'onClick'\n> {\n children?: ReactNode;\n className?: string;\n /** Whether the notification is read. Swaps the icon and sets `data-read`. */\n isRead?: boolean;\n /** Called with the toggled read state on click. */\n onRead?: (isRead: boolean) => void;\n}\n\n/** Icon button that toggles the notification between read and unread. */\nexport const ChatNotificationCardReadActionButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardReadActionButtonProps\n>(function ChatNotificationCardReadActionButton(\n { className, isRead = false, onRead, ...rest },\n ref,\n) {\n function handleClick() {\n onRead?.(!isRead);\n }\n\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-read-action-button\"\n data-read={isRead}\n aria-label=\"Mark notifications as read\"\n size=\"sm\"\n variant=\"tertiary\"\n className={className}\n onClick={handleClick}\n {...rest}\n >\n {isRead ? <SignalUnreadIcon /> : <SignalReadIcon />}\n </IconButton>\n );\n});\n\nChatNotificationCardReadActionButton.displayName = 'ChatNotificationCardReadActionButton';\n\nexport interface ChatNotificationCardSnoozeButtonProps extends ChatNotificationCardActionButtonProps {\n children?: ReactNode;\n className?: string;\n /** Classes for the time-left label of the snoozed button (`data-slot=\"chat-notification-card-snooze-button-label\"`). */\n labelClassName?: string;\n /** Classes for the cancel label shown on hover (`data-slot=\"chat-notification-card-snooze-button-cancel-label\"`). */\n cancelLabelClassName?: string;\n /** When in the future, the button shows the time left and cancels the snooze on click. */\n snoozeUntilDate?: Date;\n /** Text that replaces the time left while the snoozed button is hovered. */\n cancelLabel?: ReactNode;\n /** Formats the time left. Defaults to `formatSnoozeDate` ('in 2 minutes'). */\n formatDate?: (date: Date) => ReactNode;\n /** Called when the snoozed button is clicked. */\n onCancel?: () => void;\n}\n\n/**\n * Snooze control. An icon button that calls `onClick`; while `snoozeUntilDate` is in the future, a\n * text button with the time left that calls `onCancel`. `data-snoozed` says which one is rendered.\n */\nexport const ChatNotificationCardSnoozeButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardSnoozeButtonProps\n>(function ChatNotificationCardSnoozeButton(\n {\n className,\n labelClassName,\n cancelLabelClassName,\n snoozeUntilDate,\n cancelLabel = 'Cancel',\n formatDate = formatSnoozeDate,\n onCancel,\n onClick,\n onMouseEnter,\n onMouseLeave,\n ...rest\n },\n ref,\n) {\n const [isHovered, setIsHovered] = useState(false);\n const isSnoozed = snoozeUntilDate && snoozeUntilDate > new Date();\n\n useEffect(() => {\n if (!isSnoozed) {\n setIsHovered(false);\n }\n }, [isSnoozed]);\n\n function handleMouseEnter(event: MouseEvent<HTMLButtonElement>) {\n setIsHovered(true);\n onMouseEnter?.(event);\n }\n\n function handleMouseLeave(event: MouseEvent<HTMLButtonElement>) {\n setIsHovered(false);\n onMouseLeave?.(event);\n }\n\n function handleCancel() {\n setIsHovered(false);\n onCancel?.();\n }\n\n if (isSnoozed) {\n return (\n <Button\n ref={ref}\n data-slot=\"chat-notification-card-snooze-button\"\n data-snoozed=\"true\"\n data-hover={isHovered}\n startIcon={isHovered ? <CloseIcon /> : <SnoozeIcon />}\n variant=\"tertiary\"\n size=\"md\"\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n onClick={handleCancel}\n className={cn(\n 'group/snooze-button',\n 'text-chip-outlined-warning-text h-[32px]!',\n className,\n )}\n {...rest}\n >\n <span\n data-slot=\"chat-notification-card-snooze-button-label\"\n className={cn(\n 'group-data-[hover=true]/snooze-button:opacity-0',\n 'transition-opacity duration-200 ease-in-out',\n labelClassName,\n )}\n >\n {formatDate(snoozeUntilDate)}\n </span>\n <span\n data-slot=\"chat-notification-card-snooze-button-cancel-label\"\n className={cn(\n 'absolute left-0 w-full text-center pl-[16px]',\n 'transition-opacity duration-200 ease-in-out',\n 'opacity-0',\n 'group-data-[hover=true]/snooze-button:opacity-100',\n cancelLabelClassName,\n )}\n >\n {cancelLabel}\n </span>\n </Button>\n );\n }\n\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-snooze-button\"\n data-snoozed=\"false\"\n aria-label=\"Snooze notification\"\n size=\"sm\"\n variant=\"tertiary\"\n className={cn('group/snooze-button', className)}\n onClick={onClick}\n {...rest}\n >\n <SnoozeIcon />\n </IconButton>\n );\n});\n\nChatNotificationCardSnoozeButton.displayName = 'ChatNotificationCardSnoozeButton';\n\nexport interface ChatNotificationCardDeleteButtonProps extends ChatNotificationCardActionButtonProps {}\n\n/** Icon button that deletes the notification from a list. */\nexport const ChatNotificationCardDeleteButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardDeleteButtonProps\n>(function ChatNotificationCardDeleteButton({ className, ...rest }, ref) {\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-delete-button\"\n aria-label=\"Delete notification\"\n size=\"sm\"\n variant=\"tertiary\"\n className={className}\n {...rest}\n >\n <DeleteIcon />\n </IconButton>\n );\n});\n\nChatNotificationCardDeleteButton.displayName = 'ChatNotificationCardDeleteButton';\n\nexport interface ChatNotificationCardCloseButtonProps extends ChatNotificationCardActionButtonProps {}\n\n/** Icon button that dismisses a floating notification. */\nexport const ChatNotificationCardCloseButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardCloseButtonProps\n>(function ChatNotificationCardCloseButton({ className, ...rest }, ref) {\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-close-button\"\n aria-label=\"Close notification\"\n size=\"sm\"\n variant=\"tertiary\"\n className={className}\n {...rest}\n >\n <CloseIcon />\n </IconButton>\n );\n});\n\nChatNotificationCardCloseButton.displayName = 'ChatNotificationCardCloseButton';\n\nexport interface ChatNotificationCardContentProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Body of the card. Renders the expand button at its bottom-right corner. */\nexport function ChatNotificationCardContent({\n children,\n className,\n}: ChatNotificationCardContentProps) {\n return (\n <div\n data-slot=\"chat-notification-card-content\"\n data-testid=\"chat-notification-card-content\"\n className={cn('flex flex-col items-start text-left gap-4', 'relative pr-[40px]', className)}\n >\n {children}\n\n <ChatNotificationCardExpandButton />\n </div>\n );\n}\n\nexport interface ChatNotificationCardContentTitleProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Subject line of the notification, above the description. */\nexport function ChatNotificationCardContentTitle({\n children,\n className,\n}: ChatNotificationCardContentTitleProps) {\n return (\n <Typography\n variant=\"body-sm\"\n fontWeight=\"semibold\"\n data-slot=\"chat-notification-card-content-title\"\n data-testid=\"chat-notification-card-content-title\"\n className={cn('text-text-primary', 'text-left', className)}\n asChild\n >\n <span>{children}</span>\n </Typography>\n );\n}\n\nexport interface ChatNotificationCardContentDescriptionProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Notification text, clamped to two lines until the card is expanded. */\nexport function ChatNotificationCardContentDescription({\n children,\n className,\n}: ChatNotificationCardContentDescriptionProps) {\n return (\n <Typography\n variant=\"body-sm\"\n data-slot=\"chat-notification-card-content-description\"\n data-testid=\"chat-notification-card-content-description\"\n className={cn(\n 'text-text-primary',\n 'mt-8',\n 'group-data-[expanded=false]/chat-notification-card:line-clamp-2',\n 'w-full [&>div>*]:wrap-break-word',\n className,\n )}\n asChild\n >\n <div>{children}</div>\n </Typography>\n );\n}\n\nexport interface ChatNotificationCardContentActionsProps {\n children?: ReactNode;\n className?: string;\n}\n\n/** Follow-up actions, shown only while the card is expanded. */\nexport function ChatNotificationCardContentActions({\n children,\n className,\n}: ChatNotificationCardContentActionsProps) {\n return (\n <div\n data-slot=\"chat-notification-card-content-actions\"\n data-testid=\"chat-notification-card-content-actions\"\n role=\"group\"\n className={cn(\n 'hidden',\n 'group-data-[expanded=true]/chat-notification-card:flex',\n 'flex-row items-center gap-8',\n 'mt-4',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatNotificationCardExpandButtonProps extends Omit<\n IconButtonProps,\n 'children' | 'onClick'\n> {\n className?: string;\n onClick?: (event: MouseEvent<HTMLButtonElement>) => void;\n}\n\n/**\n * Chevron button that toggles the expanded state. `ChatNotificationCardContent` already renders\n * one, so a card needs no second.\n */\nexport const ChatNotificationCardExpandButton = forwardRef<\n HTMLButtonElement,\n ChatNotificationCardExpandButtonProps\n>(function ChatNotificationCardExpandButton({ className, onMouseDown, onClick, ...rest }, ref) {\n const { isExpanded, toggleExpanded } = useChatNotificationCardContext();\n\n function handleMouseDown(event: MouseEvent<HTMLButtonElement>) {\n event.stopPropagation();\n onMouseDown?.(event);\n }\n\n function handleClick(event: MouseEvent<HTMLButtonElement>) {\n event.stopPropagation();\n toggleExpanded();\n onClick?.(event);\n }\n\n return (\n <IconButton\n ref={ref}\n data-slot=\"chat-notification-card-expand-button\"\n data-testid=\"chat-notification-card-expand-button\"\n size=\"sm\"\n variant=\"tertiary\"\n aria-expanded={isExpanded}\n className={cn(\n 'my-4',\n 'h-auto! px-0!',\n 'absolute bottom-0 right-0',\n 'transition-opacity duration-200 ease-in',\n 'opacity-0 group-data-[expanded=true]/chat-notification-card:opacity-100 group-hover/chat-notification-card:opacity-100',\n className,\n )}\n onMouseDown={handleMouseDown}\n onClick={handleClick}\n {...rest}\n >\n {isExpanded ? <ChevronUpIcon /> : <ChevronDownIcon />}\n </IconButton>\n );\n});\n\nChatNotificationCardExpandButton.displayName = 'ChatNotificationCardExpandButton';\n\n/** Aliases kept for older imports; use the full part names. */\nexport const ChatNotificationCardIcon = ChatNotificationCardHeaderIcon;\nexport const ChatNotificationCardDescription = ChatNotificationCardContentDescription;\nexport const ChatNotificationCardTimeStamp = ChatNotificationCardTimestamp;\n","import { forwardRef, type ComponentProps } from 'react';\n\nimport { Popover, PopoverContent, PopoverTrigger } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatNotificationPopupProps extends ComponentProps<typeof Popover> {}\n\n/**\n * Root of the notification popup. Holds the open state, uncontrolled through `defaultOpen` or\n * controlled through `open` and `onOpenChange`. Renders no element of its own.\n */\nexport function ChatNotificationPopup({ children, ...rest }: ChatNotificationPopupProps) {\n return <Popover {...rest}>{children}</Popover>;\n}\n\nexport interface ChatNotificationPopupTriggerProps extends ComponentProps<typeof PopoverTrigger> {}\n\n/** The button that opens and closes the popup. Pass `asChild` to use your own button. */\nexport const ChatNotificationPopupTrigger = forwardRef<\n HTMLButtonElement,\n ChatNotificationPopupTriggerProps\n>(function ChatNotificationPopupTrigger({ children, ...rest }, ref) {\n return (\n <PopoverTrigger ref={ref} data-slot=\"chat-notification-popup-trigger\" {...rest}>\n {children}\n </PopoverTrigger>\n );\n});\n\nChatNotificationPopupTrigger.displayName = 'ChatNotificationPopupTrigger';\n\nexport interface ChatNotificationPopupContentProps extends ComponentProps<typeof PopoverContent> {}\n\n/** The panel that holds the notifications. Portalled, and 467px wide from `md` up. */\nexport const ChatNotificationPopupContent = forwardRef<\n HTMLDivElement,\n ChatNotificationPopupContentProps\n>(function ChatNotificationPopupContent({ children, className, ...rest }, ref) {\n return (\n <PopoverContent\n ref={ref}\n data-slot=\"chat-notification-popup-content\"\n className={cn('md:w-[467px]', className)}\n {...rest}\n >\n {children}\n </PopoverContent>\n );\n});\n\nChatNotificationPopupContent.displayName = 'ChatNotificationPopupContent';\n","import type { ComponentProps, ReactNode } from 'react';\n\nimport { Chip, Typography, type TypographyProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatRepliesProps {\n /** The `ChatReply` rows. */\n children: ReactNode;\n /** Classes for the list (`data-slot=\"chat-replies\"`). */\n className?: string;\n /** Pads the list. Set `false` when the parent already provides the padding. */\n hasPadding?: boolean;\n}\n\n/** The list of rows that summarises a drafted reply; a `ul` that stacks its `ChatReply` rows. */\nexport function ChatReplies({ className, children, hasPadding = true }: ChatRepliesProps) {\n return (\n <ul\n data-testid=\"chat-replies\"\n data-slot=\"chat-replies\"\n data-padding={hasPadding}\n className={cn(\n 'flex flex-col justify-start items-start gap-8',\n 'data-[padding=true]:py-8 data-[padding=true]:px-16',\n className,\n )}\n >\n {children}\n </ul>\n );\n}\n\nexport interface ChatReplyProps extends ComponentProps<'li'> {\n /** A `ChatReplyLabel` followed by a `ChatReplyValue`. */\n children: ReactNode;\n /** Lets the row and its value wrap onto several lines, for a value that is a list of chips. */\n isMultiline?: boolean;\n}\n\n/** One row of the summary: a label and its value. An `li`, so it goes inside `ChatReplies`. */\nexport function ChatReply({ className, children, isMultiline = false, ...rest }: ChatReplyProps) {\n return (\n <li\n data-testid=\"chat-reply\"\n data-slot=\"chat-reply\"\n data-multiline={isMultiline}\n className={cn(\n 'group/chat-reply',\n 'flex gap-8 w-full min-h-[24px]',\n 'data-[multiline=false]:flex-row items-center',\n 'data-[multiline=true]:flex-wrap items-start',\n className,\n )}\n {...rest}\n >\n {children}\n </li>\n );\n}\n\nexport interface ChatReplyLabelProps extends ComponentProps<typeof Chip> {\n /** The field's name, one or two words. */\n children: ReactNode;\n}\n\n/** The name of the row's field, as an outlined chip that keeps its width. */\nexport function ChatReplyLabel({ className, children, ...rest }: ChatReplyLabelProps) {\n return (\n <Chip\n variant=\"outlined\"\n // @ts-expect-error TODO(design): Chip has no `sm` size since the size scale changed (md is the old sm); renders without size classes.\n size=\"sm\"\n // @ts-expect-error TODO(design): Chip has no `secondary` color any more; renders without color classes.\n color=\"secondary\"\n data-testid=\"chat-reply-label\"\n data-slot=\"chat-reply-label\"\n className={cn('shrink-0', className)}\n {...rest}\n >\n {children}\n </Chip>\n );\n}\n\nexport interface ChatReplyValueProps extends Omit<TypographyProps, 'variant'> {\n /** The field's content: text, or one chip per item in a multiline row. */\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** The row's value: secondary text cut to one line, or wrapping items when the row is multiline. */\nexport function ChatReplyValue({\n className,\n children,\n asChild = false,\n ...rest\n}: ChatReplyValueProps) {\n return (\n <Typography\n data-testid=\"chat-reply-value\"\n data-slot=\"chat-reply-value\"\n variant=\"body-sm\"\n className={cn(\n 'leading-[24px]',\n 'flex flex-1 min-w-0 text-text-secondary',\n 'items-start',\n 'group-data-[multiline=false]/chat-reply:flex-1 truncate',\n 'group-data-[multiline=true]/chat-reply:flex-wrap',\n 'group-data-[multiline=true]/chat-reply:gap-4',\n className,\n )}\n asChild\n {...rest}\n >\n <div>{children}</div>\n </Typography>\n );\n}\n","import {\n Children,\n cloneElement,\n createContext,\n forwardRef,\n isValidElement,\n useContext,\n useMemo,\n type MouseEvent,\n type ReactElement,\n type ReactNode,\n} from 'react';\n\nimport {\n List,\n ListItem,\n ListItemAction,\n ListItemTitle,\n ListItemTrigger,\n listItemVariants,\n Typography,\n type ListItemActionProps,\n type ListItemProps,\n type ListProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\ninterface ChatSuggestionContextValue {\n index?: number;\n}\n\nconst ChatSuggestionContext = createContext<ChatSuggestionContextValue>(null!);\n\nexport function useChatSuggestionContext() {\n const context = useContext(ChatSuggestionContext);\n\n if (!context) {\n throw new Error('\"useChatSuggestionContext\" must be used within a ChatSuggestion');\n }\n\n return context;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestions\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionsProps extends Omit<ListProps, 'asChild'> {}\n\n/**\n * The numbered list of suggestions, an `<ol>` built on `ui/List`: one Tab stop, arrow keys between\n * suggestions (wrapping at the ends unless `hasLoop={false}`), one highlighted suggestion. Name it\n * with `aria-label` or `aria-labelledby`. It gives each direct child its zero-based `index`.\n */\nexport const ChatSuggestions = forwardRef<HTMLOListElement, ChatSuggestionsProps>(\n function ChatSuggestions({ children, className, hasLoop = true, ...props }, ref) {\n return (\n <List asChild hasLoop={hasLoop} ref={ref} {...props}>\n <ol\n data-slot=\"chat-suggestions\"\n data-testid=\"chat-suggestions\"\n className={cn('m-0 p-0 list-none flex flex-col items-stretch gap-0', className)}\n >\n {Children.map(children, (child, index) => {\n if (!isValidElement(child)) {\n return child;\n }\n\n return cloneElement(child as ReactElement<ChatSuggestionProps>, { index });\n })}\n </ol>\n </List>\n );\n },\n);\n\nChatSuggestions.displayName = 'ChatSuggestions';\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestion\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionProps extends Omit<\n ListItemProps,\n 'asChild' | 'className' | 'isSelected'\n> {\n /** Zero-based position in the list. `ChatSuggestions` sets it on its direct children. */\n index?: number;\n className?: string;\n /** Classes for the overlay `role=\"button\"` that covers the suggestion. */\n triggerClassName?: string;\n /** The pointer entered the suggestion. Keyboard highlight does not call it. */\n onHover?: () => void;\n}\n\n/**\n * One suggestion: an `<li>` whose whole surface is the selectable element (an overlay\n * `role=\"button\"` named by `ChatSuggestionLabel`). `onSelect` fires on click, Enter and Space.\n * Controls in the row go in `ChatSuggestionAction`, which stacks above the overlay.\n */\nexport const ChatSuggestion = forwardRef<HTMLLIElement, ChatSuggestionProps>(\n function ChatSuggestion(\n { index, children, className, triggerClassName, onHover, onMouseEnter, ...props },\n ref,\n ) {\n const contextValue = useMemo(() => ({ index }), [index]);\n\n function handleMouseEnter(event: MouseEvent<HTMLLIElement>) {\n onMouseEnter?.(event);\n onHover?.();\n }\n\n return (\n <ChatSuggestionContext.Provider value={contextValue}>\n <ListItem\n ref={ref}\n data-slot=\"chat-suggestion\"\n className={listItemVariants(\n cn('relative items-start gap-0 p-4 text-typography-text-secondary', className),\n { highlighted: 'bg-layout-accent-low-background-hover-default' },\n )}\n {...props}\n onMouseEnter={handleMouseEnter}\n >\n <ListItemTrigger\n className={cn('absolute inset-0 rounded-[inherit] outline-none', triggerClassName)}\n />\n {children}\n </ListItem>\n </ChatSuggestionContext.Provider>\n );\n },\n);\n\nChatSuggestion.displayName = 'ChatSuggestion';\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestionLabelIcon / ChatSuggestionLabel\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionLabelIconProps {\n children?: ReactNode;\n className?: string;\n /** Classes for the 32px box that holds the number or the icon. */\n innerClassName?: string;\n}\n\n/** The leading slot: the suggestion's number, or the icon passed as children. */\nexport function ChatSuggestionLabelIcon({\n children,\n className,\n innerClassName,\n}: ChatSuggestionLabelIconProps) {\n const { index = 0 } = useChatSuggestionContext();\n\n return (\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-suggestion-label-icon\"\n className={cn(\n 'inline-flex flex-row justify-center items-center shrink-0 size-auto text-inherit',\n className,\n )}\n >\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-suggestion-label-icon-inner\"\n className={cn(\n 'size-[32px]',\n 'inline-flex items-center justify-center',\n 'px-8 py-[7px]',\n '[&_svg]:size-[18px]!',\n innerClassName,\n )}\n >\n {children || (\n <Typography\n variant=\"caption-md\"\n fontWeight=\"normal\"\n className=\"text-inherit leading-none\"\n asChild\n >\n <span>{index + 1}</span>\n </Typography>\n )}\n </span>\n </span>\n );\n}\n\nexport interface ChatSuggestionLabelProps {\n children: ReactNode;\n className?: string;\n isMultiline?: boolean;\n}\n\n/** The suggestion's text and its accessible name. Up to three lines, or one with `isMultiline={false}`. */\nexport function ChatSuggestionLabel({\n children,\n className,\n isMultiline = true,\n}: ChatSuggestionLabelProps) {\n return (\n <Typography\n variant=\"body-small-low\"\n data-slot=\"chat-suggestion-label\"\n data-multiline={isMultiline}\n className={cn(\n 'gap-0 px-4 my-[7px]',\n 'h-full min-w-0 flex-1 items-center justify-center text-left text-inherit',\n 'data-[multiline=false]:truncate',\n 'data-[multiline=true]:line-clamp-3',\n className,\n )}\n asChild\n >\n <ListItemTitle>{children}</ListItemTitle>\n </Typography>\n );\n}\n\n/* -------------------------------------------------------------------------------------------------\n * ChatSuggestionActions / ChatSuggestionAction\n * -----------------------------------------------------------------------------------------------*/\n\nexport interface ChatSuggestionActionsProps {\n children: ReactNode;\n className?: string;\n}\n\n/**\n * The trailing slot, shown while the suggestion is highlighted (pointer over it or focus inside\n * it). Holds a hint icon, or controls each wrapped in `ChatSuggestionAction`.\n */\nexport function ChatSuggestionActions({ children, className }: ChatSuggestionActionsProps) {\n return (\n <div\n role=\"group\"\n data-slot=\"chat-suggestion-actions\"\n className={cn(\n 'shrink-0 flex items-center justify-center gap-8',\n 'self-start',\n 'min-w-[32px] h-[32px]',\n // Clicks on the hint icon fall through to the overlay trigger.\n 'pointer-events-none',\n '*:text-secondary-main',\n '[&>svg]:size-[18px]!',\n 'opacity-0',\n 'group-data-highlighted/list-item:opacity-100',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatSuggestionActionProps extends ListItemActionProps {}\n\n/**\n * Wraps one control in `ChatSuggestionActions` (a dismiss `IconButton`). The control stacks above\n * the suggestion's overlay, never selects the suggestion, and is in the Tab order only in the row\n * that holds the list's Tab stop.\n */\nexport const ChatSuggestionAction = forwardRef<HTMLElement, ChatSuggestionActionProps>(\n function ChatSuggestionAction({ className, children, ...rest }, ref) {\n return (\n <ListItemAction ref={ref} className={cn('pointer-events-auto', className)} {...rest}>\n {children}\n </ListItemAction>\n );\n },\n);\n\nChatSuggestionAction.displayName = 'ChatSuggestionAction';\n","import {\n MessageScroller as MessageScrollerPrimitive,\n useMessageScroller,\n useMessageScrollerScrollable,\n} from '@shadcn/react/message-scroller';\nimport {\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ComponentProps,\n type ComponentPropsWithoutRef,\n type MutableRefObject,\n type ReactElement,\n type ReactNode,\n type Ref,\n} from 'react';\n\nimport { ChevronDownIcon } from '@swisper.ai/icons';\nimport { IconButton, Tooltip } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\n/**\n * `@shadcn/react` reads `ref` from props (React 19 style), but React 18 strips `ref` before props reach\n * a component. Calling the primitive directly from a `forwardRef` render puts `ref` back into its props.\n * Not used for Root: it spreads props after its own internal ref, so any `ref` prop (even `null`) replaces it.\n */\nfunction withForwardedRef<TProps>(\n Primitive: (props: TProps) => ReactElement | null,\n displayName: string,\n) {\n const Component = forwardRef<HTMLDivElement, Omit<TProps, 'ref'>>((props, ref) =>\n Primitive({ ...props, ref: ref } as TProps),\n );\n\n Component.displayName = displayName;\n\n return Component;\n}\n\nconst ViewportPrimitive = withForwardedRef(\n MessageScrollerPrimitive.Viewport,\n 'ChatThreadViewportPrimitive',\n);\nconst ContentPrimitive = withForwardedRef(\n MessageScrollerPrimitive.Content,\n 'ChatThreadContentPrimitive',\n);\nconst ItemPrimitive = withForwardedRef(MessageScrollerPrimitive.Item, 'ChatThreadItemPrimitive');\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref) {\n (ref as MutableRefObject<T | null>).current = value;\n }\n}\n\nconst DEFAULT_SCROLL_MARGIN = 12;\n\n/** CSS variable holding the height the latest group needs to fill the viewport once anchored at its top */\nconst GROUP_MIN_HEIGHT_VAR = '--chat-thread-group-min-height';\n\n// Commands\n\nexport type ChatThreadCommands = ReturnType<typeof useMessageScroller>;\n\nconst NOOP_COMMANDS: ChatThreadCommands = {\n scrollToEnd: () => false,\n scrollToMessage: () => false,\n scrollToStart: () => false,\n};\n\nconst ChatThreadCommandsContext = createContext<ChatThreadCommands | null>(null);\n\n/**\n * Scroll commands of the nearest `ChatThreadProvider`.\n * Safe outside a provider: commands become no-ops returning `false`.\n */\nexport function useChatThread(): ChatThreadCommands {\n return useContext(ChatThreadCommandsContext) ?? NOOP_COMMANDS;\n}\n\ninterface ChatThreadCommandsBridgeProps {\n children?: ReactNode;\n}\n\nfunction ChatThreadCommandsBridge({ children }: ChatThreadCommandsBridgeProps) {\n const { scrollToEnd, scrollToMessage, scrollToStart } = useMessageScroller();\n\n const commands = useMemo<ChatThreadCommands>(\n () => ({ scrollToEnd, scrollToMessage, scrollToStart }),\n [scrollToEnd, scrollToMessage, scrollToStart],\n );\n\n return (\n <ChatThreadCommandsContext.Provider value={commands}>\n {children}\n </ChatThreadCommandsContext.Provider>\n );\n}\n\n// Session\n\n/**\n * How the thread scrolls as messages arrive.\n * - `anchor`: question and answer chat. A new question settles at the top of the viewport and its answer\n * grows below it, so the reader reads each answer from its start.\n * - `follow`: terminal-style, for agent transcripts, tool runs and logs. New output is appended at the\n * bottom and pushes older content up; the view follows the latest output until the reader scrolls away,\n * and a new group brings it back to the end. A short thread sits at the bottom, next to the input.\n */\nexport type ChatThreadScrollMode = 'anchor' | 'follow';\n\ninterface ChatThreadSession {\n isStreaming: boolean;\n scrollMargin: number;\n scrollMode: ChatThreadScrollMode;\n /**\n * Ids of the groups the session opened with — history. Any other group is a new message and anchors.\n * `null` while the thread is empty.\n */\n knownGroupIds: ReadonlySet<string> | null;\n}\n\nconst ChatThreadSessionContext = createContext<ChatThreadSession | null>(null);\n\nfunction useChatThreadSession(component: string) {\n const session = useContext(ChatThreadSessionContext);\n\n if (!session) {\n throw new Error(`[web-chat-ui] <${component}> must be rendered inside <ChatThreadProvider>`);\n }\n\n return session;\n}\n\ntype ScrollerProviderProps = ComponentProps<typeof MessageScrollerPrimitive.Provider>;\n\nexport interface ChatThreadProviderProps extends ScrollerProviderProps {\n /** Identity of the conversation; changing it resets the thread so the new conversation opens at the end */\n conversationId?: string | null;\n /** Ids of the rendered groups, matching each `ChatThreadGroup`'s `groupId` */\n groupIds: readonly string[];\n /** Whether an answer is streaming into the thread */\n isStreaming?: boolean;\n /** How the thread scrolls as messages arrive; see `ChatThreadScrollMode`. Defaults to `anchor` */\n scrollMode?: ChatThreadScrollMode;\n /**\n * Keep following content that grows at the end (late cards, reply chips, images) until the reader scrolls\n * away. In `anchor` mode it defaults to following only while no answer is streaming, so a stream never\n * drags the view down; in `follow` mode it defaults to always following.\n */\n autoScroll?: boolean;\n}\n\ninterface ThreadSessionState {\n id: number;\n conversationId: string | null;\n knownGroupIds: ReadonlySet<string> | null;\n}\n\nfunction createSessionState(\n id: number,\n conversationId: string | null | undefined,\n groupIds: readonly string[],\n): ThreadSessionState {\n return {\n id,\n conversationId: conversationId ?? null,\n knownGroupIds: groupIds.length === 0 ? null : new Set(groupIds),\n };\n}\n\n/**\n * Holds the scroll session of one conversation: which groups are history and which are new, the scroll\n * mode, and the scroll commands `useChatThread` returns. Renders no element; wrap `ChatThread` and\n * anything that scrolls it.\n */\nexport function ChatThreadProvider({\n children,\n conversationId,\n groupIds,\n isStreaming = false,\n scrollMode = 'anchor',\n autoScroll = scrollMode === 'follow' || !isStreaming,\n defaultScrollPosition = 'end',\n scrollPreviousItemPeek = 0,\n scrollMargin = DEFAULT_SCROLL_MARGIN,\n ...rest\n}: ChatThreadProviderProps) {\n const [sessionState, setSessionState] = useState(() =>\n createSessionState(0, conversationId, groupIds),\n );\n\n // A new session per conversation, and whenever the thread empties or fills again: a chat switch renders\n // the old groups under the new id, clears them, then loads the new history — which must open at the end\n if (\n sessionState.conversationId !== (conversationId ?? null) ||\n (sessionState.knownGroupIds === null) !== (groupIds.length === 0)\n ) {\n setSessionState(createSessionState(sessionState.id + 1, conversationId, groupIds));\n }\n\n const { knownGroupIds } = sessionState;\n\n const session = useMemo<ChatThreadSession>(\n () => ({ isStreaming, scrollMargin, scrollMode, knownGroupIds }),\n [isStreaming, scrollMargin, scrollMode, knownGroupIds],\n );\n\n // Keyed on the session so the scroller remounts and applies its opening position again\n return (\n <MessageScrollerPrimitive.Provider\n key={sessionState.id}\n autoScroll={autoScroll}\n scrollPreviousItemPeek={scrollPreviousItemPeek}\n scrollMargin={scrollMargin}\n defaultScrollPosition={defaultScrollPosition}\n {...rest}\n >\n <ChatThreadSessionContext.Provider value={session}>\n {scrollMode === 'follow' && (\n <FollowNewGroups groupIds={groupIds} knownGroupIds={knownGroupIds} />\n )}\n <ChatThreadCommandsBridge>{children}</ChatThreadCommandsBridge>\n </ChatThreadSessionContext.Provider>\n </MessageScrollerPrimitive.Provider>\n );\n}\n\ninterface FollowNewGroupsProps {\n groupIds: readonly string[];\n knownGroupIds: ReadonlySet<string> | null;\n}\n\n/**\n * In `follow` mode, a new group (the reader sent a prompt) returns the view to the end and resumes following,\n * even when the reader had scrolled up to read earlier output.\n */\nfunction FollowNewGroups({ groupIds, knownGroupIds }: FollowNewGroupsProps) {\n const { scrollToEnd } = useMessageScroller();\n const lastGroupId = groupIds.at(-1);\n\n useLayoutEffect(() => {\n if (lastGroupId === undefined || knownGroupIds === null || knownGroupIds.has(lastGroupId))\n return;\n\n scrollToEnd({ behavior: 'auto' });\n }, [lastGroupId, knownGroupIds, scrollToEnd]);\n\n return null;\n}\n\n// Thread\n\nexport type ChatThreadError = Error | string;\n\nexport interface ChatThreadProps extends Omit<ComponentPropsWithoutRef<'div'>, 'children'> {\n children?: ReactNode;\n /** Classes on the scrolling viewport, the element between the root and the content */\n viewportClassName?: string;\n /** Classes on the scrolled content: its padding and the gap between groups */\n contentClassName?: string;\n viewportRef?: Ref<HTMLDivElement>;\n contentRef?: Ref<HTMLDivElement>;\n /** Renders the scroll-to-latest button */\n scrollButton?: boolean;\n /** Classes on the wrapper that positions the scroll-to-latest button */\n scrollButtonClassName?: string;\n scrollButtonTooltip?: string;\n isLoading?: boolean;\n hasError?: boolean;\n error?: ChatThreadError;\n /** Replaces the built-in error message */\n renderError?: (error?: ChatThreadError) => ReactNode;\n}\n\n/**\n * The scroller of a conversation: a viewport that scrolls the groups, the scroll-to-latest button and\n * the error state. Fills its parent, so the parent needs a definite height.\n */\nexport const ChatThread = forwardRef<HTMLDivElement, ChatThreadProps>(function ChatThread(\n {\n children,\n className,\n viewportClassName,\n contentClassName,\n viewportRef,\n contentRef,\n scrollButton = true,\n scrollButtonClassName,\n scrollButtonTooltip,\n isLoading = false,\n hasError = false,\n error,\n renderError,\n ...rest\n },\n ref,\n) {\n const { isStreaming, scrollMargin, scrollMode } = useChatThreadSession('ChatThread');\n const isAnchored = scrollMode === 'anchor';\n\n const viewportElementRef = useRef<HTMLDivElement | null>(null);\n const contentElementRef = useRef<HTMLDivElement | null>(null);\n\n const setViewport = useCallback(\n (element: HTMLDivElement | null) => {\n viewportElementRef.current = element;\n assignRef(viewportRef, element);\n // Root can't take `ref` without losing its internal one; the viewport is always its direct child\n assignRef(ref, (element?.parentElement as HTMLDivElement | null | undefined) ?? null);\n },\n [viewportRef, ref],\n );\n\n const setContent = useCallback(\n (element: HTMLDivElement | null) => {\n contentElementRef.current = element;\n assignRef(contentRef, element);\n },\n [contentRef],\n );\n\n useGroupMinHeight(viewportElementRef, contentElementRef, scrollMargin, isAnchored);\n\n return (\n <MessageScrollerPrimitive.Root\n data-slot=\"chat-thread\"\n data-testid=\"chat-thread\"\n data-scroll-mode={scrollMode}\n data-streaming={isStreaming}\n data-loading={isLoading}\n data-error={hasError}\n className={cn('relative flex flex-col flex-1 min-h-0 overflow-hidden', className)}\n {...rest}\n >\n <ViewportPrimitive\n ref={setViewport}\n data-slot=\"chat-thread-viewport\"\n aria-label=\"Chat message history\"\n className={cn(\n 'size-full overflow-x-hidden overflow-y-auto outline-none',\n 'will-change-scroll transform-gpu',\n // A continuous stream outruns smooth scrolling, so following jumps instead\n isAnchored && isStreaming && 'scroll-smooth',\n viewportClassName,\n )}\n style={{\n scrollbarGutter: 'stable both-edges',\n scrollbarWidth: 'thin',\n scrollbarColor: 'var(--color-scrollbar-thumb) transparent',\n }}\n >\n <ContentPrimitive\n ref={setContent}\n data-slot=\"chat-thread-content\"\n aria-busy={isStreaming}\n data-testid=\"chat-thread-content\"\n className={cn(\n 'relative flex flex-col gap-16',\n isAnchored\n ? // The primitive always appends its spacer, so the latest group is the second-to-last child\n '[&>[data-chat-thread-group]:nth-last-child(2)]:min-h-(--chat-thread-group-min-height)'\n : // Terminal-style: a short thread sits at the bottom, next to the input\n 'min-h-full justify-end',\n contentClassName,\n )}\n >\n {children}\n </ContentPrimitive>\n </ViewportPrimitive>\n\n {hasError && !isLoading && (\n <ChatThreadErrorState error={error}>{renderError?.(error)}</ChatThreadErrorState>\n )}\n\n {scrollButton && (\n <ChatThreadScrollButton className={scrollButtonClassName} tooltip={scrollButtonTooltip} />\n )}\n </MessageScrollerPrimitive.Root>\n );\n});\n\nChatThread.displayName = 'ChatThread';\n\n/**\n * Keeps the latest group at least as tall as the room below its anchored position, so a new message can\n * settle at the top of the viewport and the answer streams in without the scroll position jumping.\n * Only `anchor` mode needs it.\n */\nfunction useGroupMinHeight(\n viewportRef: MutableRefObject<HTMLDivElement | null>,\n contentRef: MutableRefObject<HTMLDivElement | null>,\n scrollMargin: number,\n isEnabled: boolean,\n) {\n useLayoutEffect(() => {\n const viewport = viewportRef.current;\n const content = contentRef.current;\n\n if (!viewport || !content) return;\n\n if (!isEnabled) {\n content.style.removeProperty(GROUP_MIN_HEIGHT_VAR);\n return;\n }\n\n const update = () => {\n const { paddingTop, paddingBottom } = window.getComputedStyle(content);\n const minHeight =\n viewport.clientHeight -\n (Number.parseFloat(paddingTop) || 0) -\n (Number.parseFloat(paddingBottom) || 0) -\n scrollMargin;\n\n content.style.setProperty(GROUP_MIN_HEIGHT_VAR, `${Math.max(0, minHeight)}px`);\n };\n\n update();\n\n if (typeof ResizeObserver === 'undefined') return;\n\n const observer = new ResizeObserver(update);\n observer.observe(viewport);\n observer.observe(content);\n\n return () => observer.disconnect();\n }, [viewportRef, contentRef, scrollMargin, isEnabled]);\n}\n\n// Groups\n\nexport interface ChatThreadGroupProps extends ComponentPropsWithoutRef<'div'> {\n groupId: string;\n}\n\n/**\n * One question with its answer. Groups the session opened with are history; in `anchor` mode any other\n * group is a new message and becomes the scroll anchor, settling at the top of the viewport. In `follow`\n * mode no group anchors.\n */\nexport const ChatThreadGroup = forwardRef<HTMLDivElement, ChatThreadGroupProps>(\n function ChatThreadGroup({ groupId, className, children, ...rest }, ref) {\n const { knownGroupIds, scrollMode } = useChatThreadSession('ChatThreadGroup');\n const isNew = scrollMode === 'anchor' && knownGroupIds !== null && !knownGroupIds.has(groupId);\n\n return (\n <ItemPrimitive\n ref={ref}\n // Namespaced: `data-message-id` is also how consumers find message bubbles\n messageId={`chat-thread-group-${groupId}`}\n scrollAnchor={isNew}\n data-slot=\"chat-thread-group\"\n data-chat-thread-group=\"\"\n className={cn('flex flex-col gap-16 w-full min-h-px mx-auto', className)}\n {...rest}\n >\n {children}\n </ItemPrimitive>\n );\n },\n);\n\nChatThreadGroup.displayName = 'ChatThreadGroup';\n\nexport interface ChatThreadMessageProps extends ComponentPropsWithoutRef<'div'> {\n messageId: string;\n}\n\n/** Marks the question of a group with its message id. Adds no styling. */\nexport const ChatThreadQuestion = forwardRef<HTMLDivElement, ChatThreadMessageProps>(\n function ChatThreadQuestion({ messageId, children, ...rest }, ref) {\n return (\n <div\n ref={ref}\n data-slot=\"chat-thread-question\"\n data-chat-thread-question=\"\"\n data-chat-thread-message-id={messageId}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n\nChatThreadQuestion.displayName = 'ChatThreadQuestion';\n\n/** Marks the answer of a group with its message id. Adds no styling. */\nexport const ChatThreadAnswer = forwardRef<HTMLDivElement, ChatThreadMessageProps>(\n function ChatThreadAnswer({ messageId, children, ...rest }, ref) {\n return (\n <div\n ref={ref}\n data-slot=\"chat-thread-answer\"\n data-chat-thread-answer=\"\"\n data-chat-thread-message-id={messageId}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n\nChatThreadAnswer.displayName = 'ChatThreadAnswer';\n\n// Parts\n\ninterface ChatThreadScrollButtonProps {\n className?: string;\n tooltip?: string;\n}\n\nfunction ChatThreadScrollButton({ className, tooltip }: ChatThreadScrollButtonProps) {\n const { end: hasContentBelow } = useMessageScrollerScrollable();\n\n return (\n <div\n data-slot=\"chat-thread-scroll-button\"\n data-testid=\"chat-message-history-scroll-button\"\n data-hidden={!hasContentBelow}\n aria-hidden={hasContentBelow ? undefined : true}\n className={cn(\n 'absolute',\n 'px-[12px]',\n 'bottom-0',\n 'right-0 -translate-x-[12px]',\n 'md:right-auto md:left-1/2 md:-translate-x-1/2',\n '-translate-y-[12px]',\n 'flex items-center justify-center',\n 'transition-opacity duration-200 ease-in-out',\n 'data-[hidden=true]:pointer-events-none',\n 'data-[hidden=true]:opacity-0 data-[hidden=false]:opacity-100',\n className,\n )}\n >\n <MessageScrollerPrimitive.Button\n direction=\"end\"\n // Render function (not element) so Tooltip's trigger gets IconButton's forwarded ref on React 18\n render={({ inert, children: _children, ...props }) => (\n <Tooltip tooltip={tooltip} side=\"top\">\n <IconButton\n {...props}\n // React 18 doesn't know the boolean `inert` prop\n {...{ inert: inert ? '' : undefined }}\n className=\"bg-paper-elevation-2\"\n color=\"primary\"\n size=\"md\"\n tabIndex={-1}\n aria-label={tooltip}\n >\n <ChevronDownIcon />\n </IconButton>\n </Tooltip>\n )}\n />\n </div>\n );\n}\n\nexport interface ChatThreadErrorStateProps {\n children?: ReactNode;\n error?: ChatThreadError;\n className?: string;\n}\n\n/**\n * Covers the thread with an alert when its messages failed to load. Shows `children` when given,\n * otherwise the error's message.\n */\nexport function ChatThreadErrorState({ children, error, className }: ChatThreadErrorStateProps) {\n return (\n <div\n data-slot=\"chat-thread-error-state\"\n data-testid=\"chat-message-history-error-state\"\n role=\"alert\"\n aria-live=\"assertive\"\n aria-label=\"Error loading messages\"\n className={cn('absolute inset-0 flex items-center justify-center', className)}\n >\n {children || (\n <div className=\"text-text-error-main\">\n {error instanceof Error ? error.message : error || 'An error occurred'}\n </div>\n )}\n </div>\n );\n}\n\nexport { useMessageScrollerScrollable as useChatThreadScrollable };\n","import { Slot } from '@radix-ui/react-slot';\nimport type { ComponentProps, MouseEvent, ReactNode } from 'react';\n\nimport { Card, CardAction, CardDescription, CardIcon, CardTitle } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatArtifactProps extends ComponentProps<'button'> {\n /** When true, merges props onto the single child instead of rendering a `button`. */\n asChild?: boolean;\n /** Classes merged last onto the root. */\n className?: string;\n /** The artifact parts: an icon, the content with title and caption, and the actions. */\n children?: ReactNode;\n}\n\n/** A message-row control for a generated artifact: icon, title, caption and trailing actions. */\nexport function ChatArtifact({ asChild = false, className, children, ...rest }: ChatArtifactProps) {\n const Comp = asChild ? Slot : 'button';\n\n return (\n <Card asChild>\n <Comp\n {...(asChild ? {} : { type: 'button' as const })}\n data-slot=\"chat-artifact\"\n data-testid=\"chat-artifact\"\n className={cn(\n 'cursor-pointer',\n 'w-full',\n 'flex-row items-start gap-card-header-gap',\n // card-header padding plus the header's hover-area inset, flattened so asChild keeps one element\n 'py-card-header-lvl-1',\n 'px-[calc(var(--spacing-card-header-lvl-1)+var(--spacing-card-header-hover-area))]',\n 'text-left',\n // the card-header hover area, drawn as an inset layer behind the content so asChild keeps one element\n 'isolate',\n 'before:absolute before:inset-card-header-lvl-1 before:-z-10 before:pointer-events-none',\n 'before:rounded-card-header before:transition-colors',\n 'hover:before:bg-layout-accent-low-background-hover-base',\n 'active:before:bg-layout-accent-low-background-pressed-base',\n 'focus-visible:before:bg-layout-accent-low-background-hover-base',\n // an action click does not activate the row, so the row does not light up under one\n 'has-[[data-slot=chat-artifact-actions]:hover]:before:bg-transparent',\n 'outline-none',\n 'focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-focus-visible',\n className,\n )}\n {...rest}\n >\n {children}\n </Comp>\n </Card>\n );\n}\n\nexport interface ChatArtifactIconProps {\n /** Classes merged last onto the icon wrapper. */\n className?: string;\n /** The icon or thumbnail to show. */\n children?: ReactNode;\n}\n\n/** Round 32px avatar slot for a consumer-supplied icon or thumbnail. */\nexport function ChatArtifactIcon({ className, children }: ChatArtifactIconProps) {\n return (\n <CardIcon\n data-slot=\"chat-artifact-icon\"\n data-testid=\"chat-artifact-icon\"\n className={cn('text-avatar-foreground', '[&_svg]:size-4.5', className)}\n >\n {children}\n </CardIcon>\n );\n}\n\nexport interface ChatArtifactContentProps {\n /** Classes merged last onto the content element. */\n className?: string;\n /** Usually a `ChatArtifactTitle` and optional `ChatArtifactCaption`. */\n children?: ReactNode;\n}\n\n/** The text column: takes the width left beside the icon and stacks title above caption. */\nexport function ChatArtifactContent({ className, children }: ChatArtifactContentProps) {\n return (\n <div\n data-slot=\"chat-artifact-content\"\n data-testid=\"chat-artifact-content\"\n className={cn(\n 'flex-1 min-w-0',\n 'flex flex-col items-start justify-center',\n // matches the icon row height: 32px icon plus 14px margins\n 'min-h-15 py-1.5',\n 'text-left',\n className,\n )}\n >\n {children}\n </div>\n );\n}\n\nexport interface ChatArtifactTitleProps {\n /** Classes merged last onto the title element. */\n className?: string;\n /** The artifact name. */\n children?: ReactNode;\n}\n\n/** The artifact name; wraps onto more lines when it is long. */\nexport function ChatArtifactTitle({ className, children }: ChatArtifactTitleProps) {\n return (\n <CardTitle\n data-slot=\"chat-artifact-title\"\n data-testid=\"chat-artifact-title\"\n className={cn('w-full wrap-break-word truncate', 'text-layout-foreground-base', className)}\n >\n {children}\n </CardTitle>\n );\n}\n\nexport interface ChatArtifactCaptionProps {\n /** Classes merged last onto the caption element. */\n className?: string;\n /** Secondary fact under the title, e.g. source or visibility. */\n children?: ReactNode;\n}\n\n/** A quieter secondary line under the title, truncated to one line. */\nexport function ChatArtifactCaption({ className, children }: ChatArtifactCaptionProps) {\n return (\n <CardDescription\n data-slot=\"chat-artifact-caption\"\n data-testid=\"chat-artifact-caption\"\n className={cn('min-w-0 w-full truncate', 'text-layout-foreground-light', className)}\n >\n {children}\n </CardDescription>\n );\n}\n\nexport interface ChatArtifactActionsProps {\n /** Classes merged last onto the actions wrapper. */\n className?: string;\n /** Consumer-supplied controls, e.g. share and open buttons with `isSemantic={false}`. */\n children?: ReactNode;\n}\n\n/** Trailing action slot on the right of the row; clicks here do not reach the root. */\nexport function ChatArtifactActions({ className, children }: ChatArtifactActionsProps) {\n // the root is a button, so an action click must not also activate the row\n const handleClick = (event: MouseEvent<HTMLDivElement>) => event.stopPropagation();\n\n return (\n <CardAction\n role=\"group\"\n data-slot=\"chat-artifact-actions\"\n data-testid=\"chat-artifact-actions\"\n className={cn(className)}\n onClick={handleClick}\n >\n {children}\n </CardAction>\n );\n}\n","import { useState, type ComponentProps, type ReactNode } from 'react';\n\nimport { MoreHorizontalIcon, OpenInFullIcon } from '@swisper.ai/icons';\nimport {\n Menu,\n MenuProvider,\n MenuTrigger,\n Panel,\n PanelActionButton,\n PanelActionCloseButton,\n PanelBody,\n PanelContent,\n PanelFooter,\n PanelHeader,\n PanelProvider,\n PanelTitle,\n panelBodyPadding,\n type IconButtonProps,\n type TypographyProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface CanvasShellProps extends ComponentProps<'section'> {}\n\n/**\n * The `ui` Panel as the canvas beside the chat: a three-row grid where header and footer size to\n * their content and the content row takes the rest of the shell's height. It does not collapse.\n */\nexport function CanvasShell({ className, children, ...props }: CanvasShellProps) {\n return (\n <PanelProvider isCollapsible={false}>\n <Panel data-slot=\"canvas-shell\" className={className} {...props}>\n {children}\n </Panel>\n </PanelProvider>\n );\n}\n\nexport interface CanvasShellHeaderProps extends ComponentProps<'header'> {\n /** Draw the separator under the header. Set false for a header that blends into the content. */\n hasBorder?: boolean;\n}\n\n/**\n * Static top row: the title, then the panel's icon buttons.\n */\nexport function CanvasShellHeader({\n className,\n children,\n hasBorder = true,\n ...props\n}: CanvasShellHeaderProps) {\n return (\n <PanelHeader\n data-slot=\"canvas-shell-header\"\n hasBorder={hasBorder}\n className={className}\n {...props}\n >\n {children}\n </PanelHeader>\n );\n}\n\nexport interface CanvasShellTitleProps extends Omit<TypographyProps, 'variant'> {}\n\n/**\n * Name of what the canvas shows. Takes the header's free width and truncates to one line.\n */\nexport function CanvasShellTitle({ className, children, ...props }: CanvasShellTitleProps) {\n return (\n <PanelTitle data-slot=\"canvas-shell-title\" className={className} {...props}>\n {children}\n </PanelTitle>\n );\n}\n\nexport interface CanvasShellCloseTriggerProps extends IconButtonProps {}\n\n/**\n * Icon-only close button; the host decides what closing means through `onClick`.\n */\nexport function CanvasShellCloseTrigger({\n className,\n children,\n ...props\n}: CanvasShellCloseTriggerProps) {\n return (\n <PanelActionCloseButton data-slot=\"canvas-shell-close-trigger\" className={className} {...props}>\n {children}\n </PanelActionCloseButton>\n );\n}\n\nexport interface CanvasShellFullScreenTriggerProps extends Omit<\n IconButtonProps,\n 'aria-label' | 'aria-pressed'\n> {\n /** Whether the canvas currently fills the viewport; drives `aria-pressed` and the label. */\n isFullScreen: boolean;\n /** Accessible names for each state; English by default. */\n labels?: { enter?: string; exit?: string };\n}\n\n/**\n * Toggle between the canvas width and the full viewport; the host owns the state and passes\n * `isFullScreen` and `onClick`. Desktop only: on mobile the canvas already spans the screen.\n */\nexport function CanvasShellFullScreenTrigger({\n className,\n children,\n isFullScreen,\n labels,\n ...props\n}: CanvasShellFullScreenTriggerProps) {\n return (\n <PanelActionButton\n data-slot=\"canvas-shell-full-screen-trigger\"\n aria-pressed={isFullScreen}\n aria-label={\n isFullScreen ? (labels?.exit ?? 'Exit full screen') : (labels?.enter ?? 'Full screen')\n }\n className={cn('max-md:hidden', className)}\n {...props}\n >\n {children || <OpenInFullIcon />}\n </PanelActionButton>\n );\n}\n\nexport interface CanvasShellOptionsButtonProps extends Omit<IconButtonProps, 'children'> {\n /** Menu contents, typically a `DropdownMenuList` of `DropdownMenuListItem`s. */\n children: ReactNode;\n /** Classes for the dropdown panel. */\n menuClassName?: string;\n /** Called with the menu's next open state. */\n onOpenChange?: (isOpen: boolean) => void;\n}\n\n/**\n * \"More options\" button that opens a dropdown of canvas actions passed as children.\n */\nexport function CanvasShellOptionsButton({\n className,\n children,\n menuClassName,\n onOpenChange,\n ...props\n}: CanvasShellOptionsButtonProps) {\n const [isOpen, setIsOpen] = useState(false);\n\n function handleOpenChange(open: boolean) {\n setIsOpen(open);\n onOpenChange?.(open);\n }\n\n return (\n <MenuProvider modal={false} onOpenChange={handleOpenChange}>\n <MenuTrigger asChild>\n <PanelActionButton\n data-slot=\"canvas-shell-options-button\"\n isActive={isOpen}\n aria-label=\"More options\"\n className={className}\n {...props}\n >\n <MoreHorizontalIcon />\n </PanelActionButton>\n </MenuTrigger>\n <Menu className={cn('w-[200px]', menuClassName)}>{children}</Menu>\n </MenuProvider>\n );\n}\n\nexport interface CanvasShellContentProps extends ComponentProps<'div'> {\n /** Classes for the inner body, the element that pads and scrolls the children. */\n bodyClassName?: string;\n /**\n * Apply the shell's horizontal padding (`canvasShellContentPadding`).\n * Set false for edge-to-edge children that pad themselves.\n */\n hasPadding?: boolean;\n /**\n * Scroll children that overflow the region, on either axis.\n * When false, the region clips overflow: for children that scroll themselves.\n */\n hasScroll?: boolean;\n}\n\n/**\n * Horizontal padding of the content region; reuse it to align custom scroll areas with the shell.\n */\nexport const canvasShellContentPadding = panelBodyPadding;\n\n/**\n * Middle row, the only part that moves: it scrolls or clips its children inside the shell's height.\n * `className` goes to the region, `bodyClassName` to the inner element that pads and scrolls.\n */\nexport function CanvasShellContent({\n className,\n children,\n bodyClassName,\n hasPadding = true,\n hasScroll = true,\n ...props\n}: CanvasShellContentProps) {\n return (\n <PanelContent\n data-slot=\"canvas-shell-content\"\n data-has-scroll={hasScroll}\n className={className}\n {...props}\n >\n <PanelBody\n data-slot=\"canvas-shell-content-body\"\n hasPadding={hasPadding}\n hasScroll={hasScroll}\n className={bodyClassName}\n >\n {children}\n </PanelBody>\n </PanelContent>\n );\n}\n\nexport interface CanvasShellFooterProps extends ComponentProps<'footer'> {}\n\n/**\n * Static bottom row; lines its children up at the end. Stack them with `flex-col items-stretch`.\n */\nexport function CanvasShellFooter({ className, children, ...props }: CanvasShellFooterProps) {\n return (\n <PanelFooter data-slot=\"canvas-shell-footer\" className={className} {...props}>\n {children}\n </PanelFooter>\n );\n}\n","import { Slot } from '@radix-ui/react-slot';\nimport { forwardRef, type ComponentProps, type ReactNode } from 'react';\n\nimport { useChatContext } from '@/contexts';\n\ninterface NewChatTriggerProps extends ComponentProps<'button'> {\n asChild?: boolean;\n children: ReactNode;\n}\n\nexport const NewChatTrigger = forwardRef<HTMLButtonElement, NewChatTriggerProps>(\n ({ asChild = false, children, onClick, ...rest }, ref) => {\n const { goToNewChat } = useChatContext();\n const Component = asChild ? Slot : 'button';\n\n function handleClick(event: React.MouseEvent<HTMLButtonElement>) {\n onClick?.(event);\n goToNewChat();\n }\n\n return (\n <Component ref={ref} data-testid=\"new-chat-trigger\" onClick={handleClick} {...rest}>\n {children}\n </Component>\n );\n },\n);\n\nNewChatTrigger.displayName = 'NewChatTrigger';\n","import { forwardRef, type ComponentProps, type ReactNode } from 'react';\n\nimport {\n Collapsible,\n CollapsibleChevron,\n CollapsibleContent,\n CollapsibleTrigger,\n Typography,\n type CollapsibleProps,\n} from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ChatThinkingProcessProps extends Omit<CollapsibleProps, 'isDisabled'> {\n children: ReactNode;\n className?: string;\n /** The model is still thinking: the label shimmers. */\n isStreaming?: boolean;\n}\n\n/**\n * Collapsible disclosure of the assistant's reasoning or tool steps. Collapsed by default; exposes\n * `data-state` (`open` / `closed`) and `data-streaming` for its parts to style from.\n */\nexport const ChatThinkingProcess = forwardRef<HTMLDivElement, ChatThinkingProcessProps>(\n function ChatThinkingProcess(\n { children, className, defaultOpen = false, isStreaming = false, ...rest },\n ref,\n ) {\n return (\n <Collapsible defaultOpen={defaultOpen} asChild {...rest}>\n <div\n ref={ref}\n data-slot=\"chat-thinking-process\"\n data-testid=\"chat-thinking-process\"\n data-streaming={isStreaming}\n className={cn('group/thinking-process', 'flex flex-col py-6', className)}\n >\n {children}\n </div>\n </Collapsible>\n );\n },\n);\n\nChatThinkingProcess.displayName = 'ChatThinkingProcess';\n\nexport interface ChatThinkingProcessTriggerProps extends ComponentProps<'button'> {\n children: ReactNode;\n className?: string;\n isLoading?: boolean;\n}\n\n/** The button that expands and collapses the steps; holds the icon and the label. */\nexport function ChatThinkingProcessTrigger({\n children,\n className,\n ...rest\n}: ChatThinkingProcessTriggerProps) {\n return (\n <CollapsibleTrigger\n data-slot=\"chat-thinking-process-trigger\"\n data-testid=\"chat-thinking-process-trigger\"\n className={cn('flex w-full items-center gap-8', 'cursor-pointer text-left', className)}\n {...rest}\n >\n {children}\n\n <style>\n {`\n @keyframes shimmer {\n 100% {\n mask-position: left;\n }\n }\n `}\n </style>\n </CollapsibleTrigger>\n );\n}\n\nexport interface ChatThinkingProcessTriggerIconProps extends ComponentProps<'span'> {\n children: ReactNode;\n className?: string;\n}\n\n/** The icon before the label: what kind of work the process is. */\nexport function ChatThinkingProcessTriggerIcon({\n children,\n className,\n ...rest\n}: ChatThinkingProcessTriggerIconProps) {\n return (\n <span\n data-slot=\"chat-thinking-process-trigger-icon\"\n data-testid=\"chat-thinking-process-trigger-icon\"\n className={cn(\n 'inline-flex size-20 shrink-0 items-center justify-center',\n 'text-layout-foreground-light',\n '[&>svg]:size-20',\n className,\n )}\n {...rest}\n >\n {children}\n </span>\n );\n}\n\nexport interface ChatThinkingProcessTriggerLabelProps extends ComponentProps<'span'> {\n children: ReactNode;\n className?: string;\n}\n\n/** The trigger's text and accessible name; shimmers while the root is streaming. */\nexport function ChatThinkingProcessTriggerLabel({\n children,\n className,\n ...rest\n}: ChatThinkingProcessTriggerLabelProps) {\n return (\n <Typography\n asChild\n variant=\"body-small-low\"\n data-slot=\"chat-thinking-process-trigger-label\"\n data-testid=\"chat-thinking-process-trigger-label\"\n className={cn(\n 'text-layout-foreground-light',\n 'group-data-[streaming=true]/thinking-process:mask-[linear-gradient(-60deg,#000_30%,rgba(0,0,0,0.2),#192029_70%)]',\n 'group-data-[streaming=true]/thinking-process:mask-size-[300%_100%]',\n 'group-data-[streaming=true]/thinking-process:mask-right',\n 'group-data-[streaming=true]/thinking-process:animate-[shimmer_3.2s_infinite]',\n className,\n )}\n >\n <span {...rest}>{children}</span>\n </Typography>\n );\n}\n\nexport interface ChatThinkingProcessTriggerArrowProps extends ComponentProps<'span'> {\n className?: string;\n}\n\n/**\n * The chevron after the label; points up while the steps are expanded. Hidden from assistive tech.\n *\n * @deprecated The trigger no longer shows an arrow; leave it out. Kept so existing imports compile.\n */\nexport function ChatThinkingProcessTriggerArrow({\n className,\n ...rest\n}: ChatThinkingProcessTriggerArrowProps) {\n return (\n <CollapsibleChevron\n data-slot=\"chat-thinking-process-trigger-arrow\"\n data-testid=\"chat-thinking-process-trigger-arrow\"\n className={cn(\n 'items-center justify-center text-layout-foreground-light',\n 'size-16',\n className,\n )}\n {...rest}\n />\n );\n}\n\nexport interface ChatThinkingProcessContentProps extends ComponentProps<'div'> {\n children: ReactNode;\n /** Classes for the outer wrapper, which holds the list of steps. */\n className?: string;\n /** Classes for the expanded list of steps. */\n itemsClassName?: string;\n}\n\n/** The steps, listed under the label once expanded. Nothing shows while collapsed. */\nexport function ChatThinkingProcessContent({\n children,\n className,\n itemsClassName,\n ...rest\n}: ChatThinkingProcessContentProps) {\n return (\n <div\n data-slot=\"chat-thinking-process-content\"\n data-testid=\"chat-thinking-process-content\"\n className={cn('pl-[28px]', className)}\n >\n <CollapsibleContent\n data-slot=\"chat-thinking-process-content-items\"\n data-testid=\"chat-thinking-process-content-items\"\n className={cn('flex flex-col gap-4 pt-2', itemsClassName)}\n {...rest}\n >\n {children}\n </CollapsibleContent>\n </div>\n );\n}\n\nexport interface ChatThinkingProcessContentItemProps extends ComponentProps<'div'> {\n children: ReactNode;\n className?: string;\n}\n\n/** One step of the process: text, or any node such as streamed Markdown, after an optional icon. */\nexport function ChatThinkingProcessContentItem({\n children,\n className,\n ...rest\n}: ChatThinkingProcessContentItemProps) {\n return (\n <Typography\n asChild\n variant=\"body-small-low\"\n data-slot=\"chat-thinking-process-content-item\"\n data-testid=\"chat-thinking-process-content-item\"\n className={cn('flex items-center gap-4 italic text-layout-foreground-subtle', className)}\n >\n <div {...rest}>{children}</div>\n </Typography>\n );\n}\n\nexport interface ChatThinkingProcessContentItemIconProps extends ComponentProps<'span'> {\n children: ReactNode;\n className?: string;\n}\n\n/** The logo or icon before a step's text: which tool the step used. The height is fixed; a logo's width follows its image. */\nexport function ChatThinkingProcessContentItemIcon({\n children,\n className,\n ...rest\n}: ChatThinkingProcessContentItemIconProps) {\n return (\n <span\n data-slot=\"chat-thinking-process-content-item-icon\"\n data-testid=\"chat-thinking-process-content-item-icon\"\n className={cn(\n 'inline-flex h-[14px] shrink-0 items-center justify-center',\n '[&>img]:h-full [&>img]:w-auto',\n '[&>svg]:size-[14px]',\n className,\n )}\n {...rest}\n >\n {children}\n </span>\n );\n}\n","// EmptyState moved to @swisper.ai/ui, so apps without the chat surface can use it too. These aliases\n// keep existing `@swisper.ai/web-chat-ui` imports compiling; the editor strikes them through.\n// A plain `export { … } from` would work at runtime but carries no @deprecated tag per symbol.\n// Kept as a flat file, not a component folder, so the echo-design reference build doesn't list\n// EmptyState under web-chat-ui as well.\nimport {\n EmptyState as UiEmptyState,\n EmptyStateActionRow as UiEmptyStateActionRow,\n EmptyStateDescription as UiEmptyStateDescription,\n EmptyStateIcon as UiEmptyStateIcon,\n EmptyStateTitle as UiEmptyStateTitle,\n type EmptyStateActionRowProps as UiEmptyStateActionRowProps,\n type EmptyStateDescriptionProps as UiEmptyStateDescriptionProps,\n type EmptyStateIconProps as UiEmptyStateIconProps,\n type EmptyStateProps as UiEmptyStateProps,\n type EmptyStateTitleProps as UiEmptyStateTitleProps,\n} from '@swisper.ai/ui';\n\n/** @deprecated Import `EmptyState` from `@swisper.ai/ui`. */\nexport const EmptyState = UiEmptyState;\n/** @deprecated Import `EmptyStateIcon` from `@swisper.ai/ui`. */\nexport const EmptyStateIcon = UiEmptyStateIcon;\n/** @deprecated Import `EmptyStateTitle` from `@swisper.ai/ui`. */\nexport const EmptyStateTitle = UiEmptyStateTitle;\n/** @deprecated Import `EmptyStateDescription` from `@swisper.ai/ui`. */\nexport const EmptyStateDescription = UiEmptyStateDescription;\n/** @deprecated Import `EmptyStateActionRow` from `@swisper.ai/ui`. */\nexport const EmptyStateActionRow = UiEmptyStateActionRow;\n\n/** @deprecated Import `EmptyStateProps` from `@swisper.ai/ui`. */\nexport type EmptyStateProps = UiEmptyStateProps;\n/** @deprecated Import `EmptyStateIconProps` from `@swisper.ai/ui`. */\nexport type EmptyStateIconProps = UiEmptyStateIconProps;\n/** @deprecated Import `EmptyStateTitleProps` from `@swisper.ai/ui`. */\nexport type EmptyStateTitleProps = UiEmptyStateTitleProps;\n/** @deprecated Import `EmptyStateDescriptionProps` from `@swisper.ai/ui`. */\nexport type EmptyStateDescriptionProps = UiEmptyStateDescriptionProps;\n/** @deprecated Import `EmptyStateActionRowProps` from `@swisper.ai/ui`. */\nexport type EmptyStateActionRowProps = UiEmptyStateActionRowProps;\n","import type { EditorThemeClasses } from 'lexical';\n\nexport const defaultEditorTheme: EditorThemeClasses = {\n paragraph: 'editor-paragraph',\n text: {\n bold: 'editor-text-bold',\n italic: 'editor-text-italic',\n underline: 'editor-text-underline',\n },\n} as const;\n","import {\n DecoratorNode,\n type DOMConversionMap,\n type DOMExportOutput,\n type LexicalNode,\n type NodeKey,\n type SerializedLexicalNode,\n type Spread,\n} from 'lexical';\nimport type { JSX } from 'react';\n\nexport type SerializedImageNode = Spread<{ src: string; altText: string }, SerializedLexicalNode>;\n\nexport class ImageNode extends DecoratorNode<JSX.Element> {\n __src: string;\n __altText: string;\n\n static override getType(): string {\n return 'image';\n }\n\n static override clone(node: ImageNode): ImageNode {\n return new ImageNode(node.__src, node.__altText, node.__key);\n }\n\n constructor(src: string, altText: string, key?: NodeKey) {\n super(key);\n this.__src = src;\n this.__altText = altText;\n }\n\n override createDOM(): HTMLElement {\n const span = document.createElement('span');\n span.style.display = 'inline-block';\n return span;\n }\n\n override updateDOM(): false {\n return false;\n }\n\n override decorate(): JSX.Element {\n return (\n <img\n src={this.__src}\n alt={this.__altText}\n style={{ maxWidth: '100%', display: 'block' }}\n draggable={false}\n />\n );\n }\n\n override exportDOM(): DOMExportOutput {\n const img = document.createElement('img');\n img.setAttribute('src', this.__src);\n img.setAttribute('alt', this.__altText);\n img.style.maxWidth = '100%';\n return { element: img };\n }\n\n static override importDOM(): DOMConversionMap | null {\n return {\n img: () => ({\n conversion: (domNode: HTMLElement) => {\n const src = domNode.getAttribute('src') || '';\n const alt = domNode.getAttribute('alt') || '';\n if (!src) return null;\n return { node: $createImageNode(src, alt) };\n },\n priority: 0,\n }),\n };\n }\n\n override exportJSON(): SerializedImageNode {\n return {\n ...super.exportJSON(),\n src: this.__src,\n altText: this.__altText,\n type: 'image',\n version: 1,\n };\n }\n\n static override importJSON(json: SerializedImageNode): ImageNode {\n return $createImageNode(json.src, json.altText);\n }\n\n override isInline(): boolean {\n return false;\n }\n}\n\nexport function $createImageNode(src: string, altText: string): ImageNode {\n return new ImageNode(src, altText);\n}\n\nexport function $isImageNode(node: LexicalNode | null | undefined): node is ImageNode {\n return node instanceof ImageNode;\n}\n","import {\n TRANSFORMERS,\n type TextMatchTransformer,\n type ElementTransformer,\n} from '@lexical/markdown';\nimport { $isParagraphNode, $isTextNode, $createTextNode, type ElementFormatType } from 'lexical';\n\nimport { ImageNode, $createImageNode, $isImageNode } from './nodes/image-node';\n\nexport { TRANSFORMERS as MARKDOWN_TRANSFORMERS };\n\nexport function extractFontStyles(style: string) {\n const fontSizeRegex = /font-size\\s*:\\s*([^;]+)/i;\n const fontFamilyRegex = /font-family\\s*:\\s*([^;]+)/i;\n const colorRegex = /(?<![\\w-])color\\s*:\\s*([^;]+)/i;\n\n const fontSizeMatch = fontSizeRegex.exec(style);\n const fontFamilyMatch = fontFamilyRegex.exec(style);\n const colorMatch = colorRegex.exec(style);\n\n return {\n fontSize: fontSizeMatch ? fontSizeMatch[1].trim() : null,\n fontFamily: fontFamilyMatch ? fontFamilyMatch[1].trim() : null,\n color: colorMatch ? colorMatch[1].trim() : null,\n };\n}\n\nexport const FONT_STYLE_EXPORT: TextMatchTransformer = {\n type: 'text-match',\n trigger: '', // not used for export\n regExp: /./, // not used for export\n importRegExp: /./, // not used for export\n dependencies: [],\n\n export: (node) => {\n if (!$isTextNode(node)) return null;\n\n const style = node.getStyle() ?? '';\n const text = node.getTextContent();\n const fontStyles = extractFontStyles(style);\n\n if (fontStyles.fontSize || fontStyles.fontFamily || fontStyles.color) {\n let styleStr = '';\n\n if (fontStyles.fontSize) {\n styleStr += `font-size: ${fontStyles.fontSize};`;\n }\n\n if (fontStyles.fontFamily) {\n styleStr += `font-family: ${fontStyles.fontFamily};`;\n }\n\n if (fontStyles.color) {\n styleStr += `color: ${fontStyles.color};`;\n }\n\n return `<span style=\"${styleStr}\">${text}</span>`;\n }\n\n return null;\n },\n};\n\nexport const FONT_STYLE_IMPORT: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /<span\\s+style=\"([^\"]+)\">(.+?)<\\/span>/,\n importRegExp: /<span\\s+style=\"([^\"]+)\">(.+?)<\\/span>/,\n dependencies: [],\n replace: (textNode, match) => {\n const [, style, content] = match;\n const newNode = $createTextNode(content);\n\n // Preserve existing format (bold/underline) from the original node\n newNode.setFormat(textNode.getFormat());\n newNode.setStyle(style);\n textNode.replace(newNode);\n return newNode;\n },\n};\n\nexport const UNDERLINE_TRANSFORMER: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /<ins>(.*?)<\\/ins>/,\n importRegExp: /<ins>(.*?)<\\/ins>/,\n dependencies: [],\n replace: (textNode, match) => {\n const newNode = $createTextNode(match[1]);\n newNode.setFormat(textNode.getFormat());\n if (!newNode.hasFormat('underline')) {\n newNode.toggleFormat('underline');\n }\n textNode.replace(newNode);\n return newNode;\n },\n export: (node) => {\n if (!$isTextNode(node) || !node.hasFormat('underline')) return null;\n return `<ins>${node.getTextContent()}</ins>`;\n },\n};\n\nconst getAlignment = (style: string) => {\n const alignmentRegex = /text-align:\\s*(\\w+)/i;\n const alignmentMatch = alignmentRegex.exec(style);\n return alignmentMatch ? (alignmentMatch[1].trim() as ElementFormatType) : null;\n};\n\nexport const ALIGNMENT_TRANSFORMER: ElementTransformer = {\n type: 'element',\n dependencies: [],\n regExp: /<div\\s+style=\"([^\"]+)\">(.*?)<\\/div>/,\n replace: (parentNode, children, match) => {\n const alignment = getAlignment(match[1]);\n if (!alignment) return false;\n\n if (!match[2]) return;\n\n const child = children[0];\n if ($isTextNode(child)) {\n child.setTextContent(match[2]);\n }\n\n parentNode.setFormat(alignment);\n parentNode.append(...children);\n },\n export: (node, exportChildren) => {\n if (!$isParagraphNode(node)) return null;\n const alignment = node.getFormatType();\n if (!alignment || alignment === 'left') return null;\n\n const children = exportChildren(node);\n return `<div style=\"text-align: ${alignment}\">${children}</div>`;\n },\n};\n\nexport const IMAGE_EXPORT_TRANSFORMER: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /./,\n importRegExp: /./,\n dependencies: [ImageNode],\n export: (node) => {\n if (!$isImageNode(node)) return null;\n return `<img src=\"${node.__src}\" alt=\"${node.__altText}\" />`;\n },\n};\n\nexport const IMAGE_IMPORT_TRANSFORMER: TextMatchTransformer = {\n type: 'text-match',\n trigger: '',\n regExp: /<img\\s+src=\"([^\"]+)\"\\s+alt=\"([^\"]*)\"[^>]*\\/?>/,\n importRegExp: /<img\\s+src=\"([^\"]+)\"\\s+alt=\"([^\"]*)\"[^>]*\\/?>/,\n dependencies: [ImageNode],\n replace: (textNode, match) => {\n const [, src, alt] = match;\n const imageNode = $createImageNode(src, alt);\n textNode.replace(imageNode);\n },\n};\n\nexport const EXPORT_TRANSFORMERS = [\n ...TRANSFORMERS,\n FONT_STYLE_EXPORT,\n UNDERLINE_TRANSFORMER,\n ALIGNMENT_TRANSFORMER,\n IMAGE_EXPORT_TRANSFORMER,\n];\nexport const IMPORT_TRANSFORMERS = [\n ...TRANSFORMERS,\n FONT_STYLE_IMPORT,\n UNDERLINE_TRANSFORMER,\n ALIGNMENT_TRANSFORMER,\n IMAGE_IMPORT_TRANSFORMER,\n];\n","import { $createListNode, $createListItemNode, ListNode, ListItemNode } from '@lexical/list';\nimport { $createHeadingNode, HeadingNode } from '@lexical/rich-text';\nimport { setNodeIndentFromDOM, isHTMLElement, $isTextNode } from 'lexical';\nimport type {\n DOMConversionMap,\n DOMConversionOutput,\n DOMExportOutput,\n DOMExportOutputMap,\n LexicalEditor,\n LexicalNode,\n ElementNode,\n} from 'lexical';\n\nimport { extractFontStyles } from './transformers';\n\nfunction convertHeadingElement(element: HTMLElement): DOMConversionOutput | null {\n const nodeName = element.nodeName.toLowerCase();\n if (\n nodeName !== 'h1' &&\n nodeName !== 'h2' &&\n nodeName !== 'h3' &&\n nodeName !== 'h4' &&\n nodeName !== 'h5' &&\n nodeName !== 'h6'\n ) {\n return null;\n }\n const node = $createHeadingNode(nodeName);\n const style = element.getAttribute('style') ?? '';\n node.setStyle(style);\n if (element.style) {\n const align = element.style.textAlign;\n if (\n align === 'left' ||\n align === 'right' ||\n align === 'center' ||\n align === 'justify' ||\n align === 'start' ||\n align === 'end'\n ) {\n node.setFormat(align);\n }\n setNodeIndentFromDOM(element, node);\n }\n return { node };\n}\n\nfunction isDomChecklist(domNode: HTMLElement): boolean {\n if (\n domNode.getAttribute('__lexicallisttype') === 'check' ||\n domNode.classList.contains('contains-task-list')\n ) {\n return true;\n }\n for (const child of domNode.childNodes) {\n if (isHTMLElement(child) && child.hasAttribute('aria-checked')) {\n return true;\n }\n }\n return false;\n}\n\nfunction convertListElement(domNode: HTMLElement): DOMConversionOutput | null {\n const nodeName = domNode.nodeName.toLowerCase();\n let node = null;\n if (nodeName === 'ol') {\n const start = (domNode as HTMLOListElement).start;\n node = $createListNode('number', start);\n } else if (nodeName === 'ul') {\n if (isDomChecklist(domNode)) {\n node = $createListNode('check');\n } else {\n node = $createListNode('bullet');\n }\n }\n if (!node) return null;\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n return { node };\n}\n\nfunction convertListItemElement(domNode: HTMLElement): DOMConversionOutput | null {\n const isGitHubCheckList = domNode.classList.contains('task-list-item');\n if (isGitHubCheckList) {\n for (const child of domNode.children) {\n if (child.tagName === 'INPUT') {\n const input = child as HTMLInputElement;\n const isCheckbox = input.getAttribute('type') === 'checkbox';\n if (isCheckbox) {\n const checked = input.hasAttribute('checked');\n const node = $createListItemNode(checked);\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n return { node };\n }\n }\n }\n }\n const ariaCheckedAttr = domNode.getAttribute('aria-checked');\n const checked =\n ariaCheckedAttr === 'true' ? true : ariaCheckedAttr === 'false' ? false : undefined;\n const node = $createListItemNode(checked);\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n return { node };\n}\n\nconst IMPORT_PRIORITY = 4;\n\nfunction convertSpanElementWithStyles(domNode: HTMLElement): DOMConversionOutput | null {\n const styleAttr = domNode.getAttribute('style') ?? '';\n const { color, fontSize, fontFamily } = extractFontStyles(styleAttr);\n\n if (!color && !fontSize && !fontFamily) {\n return null;\n }\n\n const domStyle = domNode.style;\n\n return {\n forChild: (lexicalNode) => {\n if (!$isTextNode(lexicalNode)) return lexicalNode;\n\n // Replicate Lexical's default text-format handling from applyTextFormatFromStyle\n const fontWeight = domStyle.fontWeight;\n const textDecoration = (domStyle.textDecoration || '').split(' ');\n if ((fontWeight === '700' || fontWeight === 'bold') && !lexicalNode.hasFormat('bold')) {\n lexicalNode.toggleFormat('bold');\n }\n if (textDecoration.includes('line-through') && !lexicalNode.hasFormat('strikethrough')) {\n lexicalNode.toggleFormat('strikethrough');\n }\n if (domStyle.fontStyle === 'italic' && !lexicalNode.hasFormat('italic')) {\n lexicalNode.toggleFormat('italic');\n }\n if (textDecoration.includes('underline') && !lexicalNode.hasFormat('underline')) {\n lexicalNode.toggleFormat('underline');\n }\n if (domStyle.verticalAlign === 'sub' && !lexicalNode.hasFormat('subscript')) {\n lexicalNode.toggleFormat('subscript');\n }\n if (domStyle.verticalAlign === 'super' && !lexicalNode.hasFormat('superscript')) {\n lexicalNode.toggleFormat('superscript');\n }\n\n // Apply inline CSS styles (color, font-size, font-family)\n let styleStr = '';\n if (fontSize) styleStr += `font-size: ${fontSize};`;\n if (fontFamily) styleStr += `font-family: ${fontFamily};`;\n if (color) styleStr += `color: ${color};`;\n lexicalNode.setStyle(styleStr);\n\n return lexicalNode;\n },\n node: null,\n };\n}\n\nexport const HTML_IMPORT_CONFIG: DOMConversionMap = {\n h1: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h2: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h3: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h4: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h5: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n h6: () => ({ conversion: convertHeadingElement, priority: IMPORT_PRIORITY }),\n ul: () => ({ conversion: convertListElement, priority: IMPORT_PRIORITY }),\n ol: () => ({ conversion: convertListElement, priority: IMPORT_PRIORITY }),\n li: () => ({ conversion: convertListItemElement, priority: IMPORT_PRIORITY }),\n span: () => ({ conversion: convertSpanElementWithStyles, priority: IMPORT_PRIORITY }),\n};\n\ntype NodeExportDOMFn = (editor: LexicalEditor) => DOMExportOutput;\n\nfunction wrapExportWithStyle(OriginalClass: {\n prototype: { exportDOM: NodeExportDOMFn };\n}): (editor: LexicalEditor, target: LexicalNode) => DOMExportOutput {\n return (editor: LexicalEditor, target: LexicalNode) => {\n const result = OriginalClass.prototype.exportDOM.call(target, editor);\n const elementNode = target as ElementNode;\n const style = elementNode.getStyle();\n if (result.element && style) {\n (result.element as HTMLElement).setAttribute('style', style);\n }\n return result;\n };\n}\n\nexport const HTML_EXPORT_CONFIG: DOMExportOutputMap = new Map<\n unknown,\n (editor: LexicalEditor, target: LexicalNode) => DOMExportOutput\n>([\n [HeadingNode, wrapExportWithStyle(HeadingNode)],\n [ListNode, wrapExportWithStyle(ListNode)],\n [ListItemNode, wrapExportWithStyle(ListItemNode)],\n]) as DOMExportOutputMap;\n","import {\n $createParagraphNode,\n $isTextNode,\n ElementNode,\n setNodeIndentFromDOM,\n type DOMConversionMap,\n type DOMConversionOutput,\n type EditorConfig,\n type LexicalUpdateJSON,\n type RangeSelection,\n type SerializedElementNode,\n type Spread,\n} from 'lexical';\n\nexport type SerializedDivBlockNode = Spread<\n {\n style?: string;\n },\n SerializedElementNode\n>;\n\nexport class DivBlockNode extends ElementNode {\n static override getType(): string {\n return 'div-block';\n }\n\n static override clone(node: DivBlockNode): DivBlockNode {\n return new DivBlockNode(node.__key);\n }\n\n override createDOM(_config: EditorConfig): HTMLElement {\n const div = document.createElement('div');\n const style = this.getStyle();\n if (style) {\n div.style.cssText = style;\n }\n return div;\n }\n\n override updateDOM(prevNode: DivBlockNode, dom: HTMLElement): boolean {\n const prevStyle = prevNode.getStyle();\n const nextStyle = this.getStyle();\n if (prevStyle !== nextStyle) {\n dom.style.cssText = nextStyle;\n return true;\n }\n return false;\n }\n\n static override importDOM(): DOMConversionMap | null {\n return {\n div: () => ({\n conversion: convertDivElement,\n priority: 4,\n }),\n };\n }\n\n override exportJSON(): SerializedDivBlockNode {\n const json = super.exportJSON();\n const style = this.getStyle();\n if (style) {\n return { ...json, style };\n }\n return json;\n }\n\n static override importJSON(serializedNode: SerializedDivBlockNode): DivBlockNode {\n const node = $createDivBlockNode().updateFromJSON(serializedNode);\n if (serializedNode.style !== undefined) {\n node.setStyle(serializedNode.style);\n }\n return node;\n }\n\n override updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedDivBlockNode>): this {\n const updated = super.updateFromJSON(serializedNode);\n if (serializedNode.style !== undefined) {\n updated.setStyle(serializedNode.style);\n }\n return updated;\n }\n\n override collapseAtStart(_selection: RangeSelection): boolean {\n const children = this.getChildren();\n const isEmptyOrBlank =\n children.length === 0 ||\n ($isTextNode(children[0]) && children[0].getTextContent().trim() === '');\n\n if (isEmptyOrBlank) {\n const nextSibling = this.getNextSibling();\n if (nextSibling !== null) {\n this.selectNext();\n this.remove();\n return true;\n }\n const prevSibling = this.getPreviousSibling();\n if (prevSibling !== null) {\n this.selectPrevious();\n this.remove();\n return true;\n }\n } else {\n const paragraph = $createParagraphNode();\n paragraph.setFormat(this.getFormatType());\n paragraph.setStyle(this.getStyle());\n paragraph.setIndent(this.getIndent());\n paragraph.setDirection(this.getDirection());\n children.forEach((child) => paragraph.append(child));\n this.replace(paragraph);\n return true;\n }\n\n return false;\n }\n}\n\nfunction convertDivElement(domNode: HTMLElement): DOMConversionOutput | null {\n const node = $createDivBlockNode();\n const style = domNode.getAttribute('style') ?? '';\n node.setStyle(style);\n if (domNode.style) {\n const align = domNode.style.textAlign;\n if (\n align === 'left' ||\n align === 'right' ||\n align === 'center' ||\n align === 'justify' ||\n align === 'start' ||\n align === 'end'\n ) {\n node.setFormat(align);\n }\n setNodeIndentFromDOM(domNode, node);\n }\n return { node };\n}\n\nexport function $createDivBlockNode(): DivBlockNode {\n return new DivBlockNode();\n}\n\nexport function $isDivBlockNode(node: unknown): node is DivBlockNode {\n return node instanceof DivBlockNode;\n}\n","import { $generateHtmlFromNodes } from '@lexical/html';\nimport { $convertToMarkdownString } from '@lexical/markdown';\nimport { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';\nimport { type EditorState, type LexicalEditor } from 'lexical';\nimport { type MutableRefObject, useCallback } from 'react';\n\nimport { EXPORT_TRANSFORMERS } from '../transformers';\n\nexport { MARKDOWN_TRANSFORMERS } from '../transformers';\n\n/** How many emitted values to remember; a parent that never echoes them back must not grow the list. */\nconst MAX_EMITTED_VALUES = 50;\n\ninterface ValuePluginProps {\n onChange?: (value: string) => void;\n source?: 'html' | 'markdown';\n /** Receives every value given to `onChange`, so `ControlledValuePlugin` can tell an echo of one. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ValuePlugin({ onChange, source = 'markdown', emittedValuesRef }: ValuePluginProps) {\n const handleChange = useCallback(\n (editorState: EditorState, editor: LexicalEditor, tags: Set<string>) => {\n if (tags.has('focus')) {\n return;\n }\n\n if (!onChange) {\n return;\n }\n\n try {\n editorState.read(() => {\n const value =\n source === 'html'\n ? $generateHtmlFromNodes(editor)\n : $convertToMarkdownString(EXPORT_TRANSFORMERS);\n\n if (emittedValuesRef) {\n emittedValuesRef.current.push(value);\n emittedValuesRef.current.splice(\n 0,\n emittedValuesRef.current.length - MAX_EMITTED_VALUES,\n );\n }\n\n onChange(value);\n });\n } catch (error) {\n if (import.meta.env.DEV) {\n console.error('ValuePlugin error:', error);\n }\n }\n },\n [onChange, source, emittedValuesRef],\n );\n\n return <OnChangePlugin onChange={handleChange} />;\n}\n","import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';\nimport { $getSelection } from 'lexical';\nimport { useCallback } from 'react';\n\nexport function useRichTextAreaEditor() {\n const [editor] = useLexicalComposerContext();\n\n return editor;\n}\n\nexport function useRichTextAreaSelectedText() {\n const [editor] = useLexicalComposerContext();\n\n return useCallback(() => {\n let selectedText = '';\n\n editor.getEditorState().read(() => {\n const selection = $getSelection();\n selectedText = selection?.getTextContent() ?? '';\n });\n\n return selectedText;\n }, [editor]);\n}\n","import { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\ninterface DisabledPluginProps {\n isDisabled?: boolean;\n}\n\nexport function DisabledPlugin({ isDisabled }: DisabledPluginProps) {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n editor.setEditable(!isDisabled);\n }, [editor, isDisabled]);\n\n return null;\n}\n","import { EditorRefPlugin } from '@lexical/react/LexicalEditorRefPlugin';\nimport { type LexicalEditor } from 'lexical';\nimport { useRef, useImperativeHandle, type Ref } from 'react';\n\ninterface ControlledPluginProps {\n controlledRef: Ref<HTMLInputElement | null>;\n}\n\nexport function ControlledPlugin({ controlledRef }: ControlledPluginProps) {\n const editorRef = useRef<LexicalEditor | null>(null);\n\n useImperativeHandle(controlledRef, (): HTMLInputElement | null => {\n return {\n focus: () => {\n Promise.resolve().then(() => {\n editorRef.current?.focus();\n });\n },\n } as unknown as HTMLInputElement;\n }, []);\n\n return <EditorRefPlugin editorRef={editorRef} />;\n}\n","import { $generateNodesFromDOM } from '@lexical/html';\nimport { type LexicalEditor, type LexicalNode } from 'lexical';\nimport {\n $getRoot,\n $isTextNode,\n $createParagraphNode,\n $createRangeSelection,\n $setSelection,\n $selectAll,\n $getSelection,\n $isRangeSelection,\n} from 'lexical';\n\nexport function scrollRichTextAreaToBottom(editor: LexicalEditor): void {\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n rootElement.scrollTop = rootElement.scrollHeight;\n}\n\nexport function $setSelectionToEnd() {\n const root = $getRoot();\n const lastDescendant = root.getLastDescendant();\n\n if (lastDescendant && $isTextNode(lastDescendant)) {\n const selection = $createRangeSelection();\n const endOffset = lastDescendant.getTextContentSize();\n selection.anchor.set(lastDescendant.getKey(), endOffset, 'text');\n selection.focus.set(lastDescendant.getKey(), endOffset, 'text');\n $setSelection(selection);\n } else {\n $selectAll();\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const focusNode = selection.focus.getNode();\n const focusOffset = $isTextNode(focusNode) ? focusNode.getTextContentSize() : 0;\n selection.anchor.set(selection.focus.key, selection.focus.offset, selection.focus.type);\n selection.focus.set(selection.focus.key, focusOffset, selection.focus.type);\n $setSelection(selection);\n }\n }\n}\n\nfunction getHTMLNodesFromValue(editor: LexicalEditor, html: string): LexicalNode[] {\n const parser = new DOMParser();\n const dom = parser.parseFromString(html, 'text/html');\n const nodes = $generateNodesFromDOM(editor, dom);\n\n return nodes.map((node) => {\n if ($isTextNode(node)) {\n const p = $createParagraphNode();\n p.append(node);\n return p;\n }\n return node;\n });\n}\n\nexport function $replaceEditorHTMLContent(editor: LexicalEditor, html: string): void {\n const root = $getRoot();\n root.clear();\n getHTMLNodesFromValue(editor, html).forEach((node) => root.append(node));\n}\n\nexport function $replaceEditorSelectionHTMLContent(editor: LexicalEditor, html: string): void {\n const selection = $getSelection();\n const nodes = getHTMLNodesFromValue(editor, html);\n\n if ($isRangeSelection(selection)) {\n selection.insertNodes(nodes);\n } else {\n const root = $getRoot();\n root.clear();\n nodes.forEach((node) => root.append(node));\n }\n}\n","import { $generateHtmlFromNodes } from '@lexical/html';\nimport { $convertToMarkdownString, $convertFromMarkdownString } from '@lexical/markdown';\nimport { $getRoot, $addUpdateTag, SKIP_DOM_SELECTION_TAG } from 'lexical';\nimport { type MutableRefObject, useEffect, useRef } from 'react';\n\nimport { useIsResolution } from '@swisper.ai/ui';\n\nimport { useRichTextAreaEditor } from '../hooks';\nimport { EXPORT_TRANSFORMERS, IMPORT_TRANSFORMERS } from '../transformers';\nimport {\n $replaceEditorHTMLContent,\n $setSelectionToEnd,\n scrollRichTextAreaToBottom,\n} from '../utils';\n\ninterface ControlledValuePluginProps {\n value?: string;\n source?: 'html' | 'markdown';\n /** The values `ValuePlugin` gave to `onChange` that the parent has not rendered back yet. */\n emittedValuesRef?: MutableRefObject<string[]>;\n}\n\nexport function ControlledValuePlugin({\n value,\n source = 'markdown',\n emittedValuesRef,\n}: ControlledValuePluginProps) {\n const editor = useRichTextAreaEditor();\n const previousValueRef = useRef<string | undefined>();\n const shouldScrollOnInitialValueRef = useRef(Boolean(value?.trim()));\n const isDesktop = useIsResolution('desktop');\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n\n if (value === previousValueRef.current) {\n return;\n }\n\n previousValueRef.current = value;\n\n // The parent renders back each value `onChange` gave it, and that render can land after later\n // keystrokes. Such a value is an echo of an older edit, not a change to apply: applying it\n // would drop what was typed since.\n if (emittedValuesRef && value !== undefined) {\n const echoIndex = emittedValuesRef.current.lastIndexOf(value);\n emittedValuesRef.current.splice(0, echoIndex === -1 ? Infinity : echoIndex + 1);\n if (echoIndex !== -1) {\n return;\n }\n }\n\n let currentValue = '';\n editor.getEditorState().read(() => {\n currentValue =\n source === 'html'\n ? $generateHtmlFromNodes(editor)\n : $convertToMarkdownString(EXPORT_TRANSFORMERS);\n });\n\n if (value !== undefined && value !== currentValue) {\n if (value === '') {\n editor.update(\n () => {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n if (source === 'html') {\n $getRoot().clear();\n } else {\n $convertFromMarkdownString('', IMPORT_TRANSFORMERS);\n }\n $setSelectionToEnd();\n },\n {\n discrete: true,\n },\n );\n\n Promise.resolve().then(() => {\n if (isDesktop) {\n editor.focus();\n } else {\n editor.blur();\n }\n });\n\n return;\n }\n\n editor.update(() => {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n if (source === 'html') {\n $replaceEditorHTMLContent(editor, value);\n } else {\n $convertFromMarkdownString(value, IMPORT_TRANSFORMERS);\n }\n $setSelectionToEnd();\n });\n\n if (shouldScrollOnInitialValueRef.current) {\n shouldScrollOnInitialValueRef.current = false;\n Promise.resolve().then(() => {\n requestAnimationFrame(() => scrollRichTextAreaToBottom(editor));\n });\n }\n\n if (isDesktop) {\n // Focus after update completes\n Promise.resolve().then(() => {\n editor.focus();\n });\n }\n }\n }, [editor, value, source, isDesktop, emittedValuesRef]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\ninterface BlurPluginProps {\n onBlur?: () => void;\n}\n\nexport function BlurPlugin({ onBlur }: BlurPluginProps) {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n if (!onBlur) {\n return;\n }\n\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n\n function handleBlur(event: FocusEvent) {\n if (rootElement && onBlur && !rootElement.contains(event.relatedTarget as Node)) {\n onBlur();\n }\n }\n\n rootElement.addEventListener('blur', handleBlur, true);\n\n return () => {\n rootElement.removeEventListener('blur', handleBlur, true);\n };\n }, [editor, onBlur]);\n\n return null;\n}\n","import { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\ninterface FocusPluginProps {\n onFocusChange?: (isFocused: boolean) => void;\n}\n\nexport function FocusPlugin({ onFocusChange }: FocusPluginProps) {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n if (!onFocusChange) {\n return;\n }\n\n const rootElement = editor.getRootElement();\n if (!rootElement) {\n return;\n }\n\n function handleFocus() {\n if (rootElement && onFocusChange) {\n onFocusChange(true);\n }\n }\n\n function handleBlur(event: FocusEvent) {\n if (rootElement && onFocusChange && !rootElement.contains(event.relatedTarget as Node)) {\n onFocusChange(false);\n }\n }\n\n rootElement.addEventListener('focus', handleFocus, true);\n rootElement.addEventListener('blur', handleBlur, true);\n\n return () => {\n rootElement.removeEventListener('focus', handleFocus, true);\n rootElement.removeEventListener('blur', handleBlur, true);\n };\n }, [editor, onFocusChange]);\n\n return null;\n}\n","import { $insertNodes, COMMAND_PRIORITY_EDITOR, createCommand, type LexicalCommand } from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\nimport { $createImageNode } from '../nodes/image-node';\n\nexport interface InsertImagePayload {\n src: string;\n altText: string;\n}\n\nexport const INSERT_IMAGE_COMMAND: LexicalCommand<InsertImagePayload> =\n createCommand('INSERT_IMAGE_COMMAND');\n\nexport const INSERT_IMAGE_EVENT_NAME = 'helvetiq:insert-image';\n\nexport class ImageAddedEvent extends CustomEvent<InsertImagePayload> {\n constructor(payload: InsertImagePayload) {\n super(INSERT_IMAGE_EVENT_NAME, { detail: payload });\n }\n}\n\nexport function ImageDropPlugin() {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n return editor.registerCommand(\n INSERT_IMAGE_COMMAND,\n (payload: InsertImagePayload) => {\n editor.update(() => {\n const imageNode = $createImageNode(payload.src, payload.altText);\n $insertNodes([imageNode]);\n });\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n useEffect(() => {\n const rootElement = editor.getRootElement();\n if (!rootElement) return;\n\n function handleInsertImage(event: Event) {\n const customEvent = event as CustomEvent<InsertImagePayload>;\n editor.dispatchCommand(INSERT_IMAGE_COMMAND, customEvent.detail);\n }\n\n document.addEventListener(INSERT_IMAGE_EVENT_NAME, handleInsertImage);\n return () => {\n document.removeEventListener(INSERT_IMAGE_EVENT_NAME, handleInsertImage);\n };\n }, [editor]);\n\n return null;\n}\n","import { $generateNodesFromDOM } from '@lexical/html';\nimport {\n $getRoot,\n $insertNodes,\n COMMAND_PRIORITY_EDITOR,\n createCommand,\n type LexicalCommand,\n} from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\nexport interface PasteHtmlPayload {\n html: string;\n}\n\nexport interface InsertHtmlPayload {\n html: string;\n}\n\nexport const PASTE_HTML_COMMAND: LexicalCommand<PasteHtmlPayload> =\n createCommand('PASTE_HTML_COMMAND');\n\nexport const INSERT_HTML_COMMAND: LexicalCommand<InsertHtmlPayload> =\n createCommand('INSERT_HTML_COMMAND');\n\nexport const PASTE_HTML_EVENT = 'helvetiq:paste-html';\nexport const INSERT_HTML_EVENT = 'helvetiq:insert-html';\n\nexport class PasteHtmlEvent extends CustomEvent<PasteHtmlPayload> {\n constructor(payload: PasteHtmlPayload) {\n super(PASTE_HTML_EVENT, { detail: payload });\n }\n}\n\nexport class InsertHtmlEvent extends CustomEvent<InsertHtmlPayload> {\n constructor(payload: InsertHtmlPayload) {\n super(INSERT_HTML_EVENT, { detail: payload });\n }\n}\n\nexport function HtmlPastePlugin() {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n return editor.registerCommand(\n PASTE_HTML_COMMAND,\n (payload: PasteHtmlPayload) => {\n editor.update(() => {\n const root = $getRoot();\n root.clear();\n\n const parser = new DOMParser();\n const dom = parser.parseFromString(payload.html, 'text/html');\n const nodes = $generateNodesFromDOM(editor, dom);\n root.append(...nodes);\n });\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n useEffect(() => {\n return editor.registerCommand(\n INSERT_HTML_COMMAND,\n (payload: InsertHtmlPayload) => {\n editor.update(() => {\n const parser = new DOMParser();\n const dom = parser.parseFromString(payload.html, 'text/html');\n const nodes = $generateNodesFromDOM(editor, dom);\n $insertNodes(nodes);\n });\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n useEffect(() => {\n const rootElement = editor.getRootElement();\n if (!rootElement) return;\n\n function handlePasteHtml(event: Event) {\n const customEvent = event as PasteHtmlEvent;\n editor.dispatchCommand(PASTE_HTML_COMMAND, customEvent.detail);\n }\n\n function handleInsertHtml(event: Event) {\n const customEvent = event as InsertHtmlEvent;\n editor.dispatchCommand(INSERT_HTML_COMMAND, customEvent.detail);\n }\n\n document.addEventListener(PASTE_HTML_EVENT, handlePasteHtml);\n document.addEventListener(INSERT_HTML_EVENT, handleInsertHtml);\n\n return () => {\n document.removeEventListener(PASTE_HTML_EVENT, handlePasteHtml);\n document.removeEventListener(INSERT_HTML_EVENT, handleInsertHtml);\n };\n }, [editor]);\n\n return null;\n}\n","import {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n COMMAND_PRIORITY_CRITICAL,\n PASTE_COMMAND,\n} from 'lexical';\nimport { useEffect } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\nexport function MarkdownPlainPastePlugin() {\n const editor = useRichTextAreaEditor();\n\n useEffect(() => {\n return editor.registerCommand<ClipboardEvent>(\n PASTE_COMMAND,\n (event) => {\n const { clipboardData } = event;\n\n if (!clipboardData) {\n return false;\n }\n\n const plainText = clipboardData.getData('text/plain');\n\n if (!plainText) {\n return false;\n }\n\n event.preventDefault();\n\n editor.update(() => {\n const selection = $getSelection();\n\n if ($isRangeSelection(selection)) {\n selection.insertText(plainText);\n return;\n }\n\n const root = $getRoot();\n root.clear();\n\n const lines = plainText.split(/\\r?\\n/);\n lines.forEach((line) => {\n const paragraph = $createParagraphNode();\n if (line.length > 0) {\n paragraph.append($createTextNode(line));\n }\n root.append(paragraph);\n });\n });\n\n return true;\n },\n COMMAND_PRIORITY_CRITICAL,\n );\n }, [editor]);\n\n return null;\n}\n","import { COMMAND_PRIORITY_EDITOR, createCommand, type LexicalCommand } from 'lexical';\nimport { useEffect, useRef } from 'react';\n\nimport { useRichTextAreaEditor } from '../hooks';\n\nexport const ATTACH_FILE_COMMAND: LexicalCommand<void> = createCommand('ATTACH_FILE_COMMAND');\n\ninterface FileAttachmentPluginProps {\n acceptedFiles?: string[];\n isMultiple?: boolean;\n onFileAttach?: (files: File[]) => void;\n}\n\nexport function FileAttachmentPlugin({\n acceptedFiles = [],\n isMultiple = false,\n onFileAttach,\n}: FileAttachmentPluginProps) {\n const editor = useRichTextAreaEditor();\n const inputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n return editor.registerCommand(\n ATTACH_FILE_COMMAND,\n () => {\n inputRef.current?.click();\n return true;\n },\n COMMAND_PRIORITY_EDITOR,\n );\n }, [editor]);\n\n function handleChange(event: React.ChangeEvent<HTMLInputElement>) {\n const files = Array.from(event.target.files ?? []);\n\n if (!isMultiple) {\n const file = files[0];\n onFileAttach?.([file]);\n } else {\n onFileAttach?.(files);\n }\n\n event.target.value = '';\n }\n\n return (\n <input\n ref={inputRef}\n type=\"file\"\n multiple={isMultiple}\n aria-hidden=\"true\"\n className=\"hidden\"\n accept={acceptedFiles?.join(',')}\n onChange={handleChange}\n />\n );\n}\n","import { forwardRef, type HTMLAttributes, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\ninterface WrapperProps extends HTMLAttributes<HTMLDivElement> {\n children?: ReactNode;\n}\n\nexport const Wrapper = forwardRef<HTMLDivElement, WrapperProps>(\n ({ className, children, ...rest }, ref) => {\n return (\n <div\n ref={ref}\n className={cn(\n 'w-full resize-none border-none outline-none bg-transparent font-[inherit] text-[inherit] flex items-center [&_.editor-paragraph]:m-0 [&_.editor-paragraph]:min-h-[26px] [&_.editor-text-bold]:font-bold [&_.editor-text-italic]:italic [&_.editor-text-underline]:underline',\n className,\n )}\n {...rest}\n >\n {children}\n </div>\n );\n },\n);\n\nWrapper.displayName = 'Wrapper';\n","import { CodeNode } from '@lexical/code';\nimport { LinkNode } from '@lexical/link';\nimport { ListNode, ListItemNode } from '@lexical/list';\nimport { type InitialConfigType, LexicalComposer } from '@lexical/react/LexicalComposer';\nimport { ContentEditable } from '@lexical/react/LexicalContentEditable';\nimport { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary';\nimport { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';\nimport { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';\nimport { TablePlugin } from '@lexical/react/LexicalTablePlugin';\nimport { HeadingNode, QuoteNode } from '@lexical/rich-text';\nimport { TableCellNode, TableNode, TableRowNode } from '@lexical/table';\nimport { forwardRef, useRef } from 'react';\nimport type { KeyboardEvent, Ref, ReactNode } from 'react';\n\nimport { Typography } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { defaultEditorTheme } from './constants';\nimport { HTML_IMPORT_CONFIG, HTML_EXPORT_CONFIG } from './html-config';\nimport { DivBlockNode } from './nodes/div-block-node';\nimport { ImageNode } from './nodes/image-node';\nimport {\n ValuePlugin,\n DisabledPlugin,\n ControlledPlugin,\n ControlledValuePlugin,\n BlurPlugin,\n FocusPlugin,\n MarkdownPlainPastePlugin,\n} from './plugins';\nimport { Wrapper } from './styled';\n\nexport const INITIAL_CONFIG: InitialConfigType = {\n namespace: 'helvetiq',\n theme: defaultEditorTheme,\n editable: true,\n nodes: [\n ListNode,\n ListItemNode,\n HeadingNode,\n QuoteNode,\n CodeNode,\n LinkNode,\n ImageNode,\n DivBlockNode,\n TableNode,\n TableCellNode,\n TableRowNode,\n ],\n html: {\n import: HTML_IMPORT_CONFIG,\n export: HTML_EXPORT_CONFIG,\n },\n onError: (error: Error) => {\n console.error('Lexical error:', error);\n },\n};\n\nexport interface RichTextAreaProps {\n /** Extra Lexical plugins. They render inside the composer, after the built-in ones. */\n children?: ReactNode;\n /** Written to the editable element as `data-name`. It does not create a form field. */\n name?: string;\n /** Controlled content, in the format `source` sets. `''` clears the editor. */\n value?: string;\n /** Format of `value` and of what `onChange` returns. Defaults to `markdown`. */\n source?: 'html' | 'markdown';\n /** Classes for the editable element (`data-slot=\"rich-text-area-editable\"`), not the root. */\n className?: string;\n /** Classes for the root wrapper (`data-slot=\"rich-text-area\"`). */\n containerClassName?: string;\n /** Classes for the placeholder (`data-slot=\"rich-text-area-placeholder\"`). */\n placeholderClassName?: string;\n /** Hint shown while the editor is empty. It is not the editor's accessible name. */\n placeholder?: string;\n /** Makes the editor non-editable and dims it; the root gets `data-disabled=\"true\"`. */\n isDisabled?: boolean;\n /** Called with the whole content, serialised as `source`, on every edit. */\n onChange?: (value: string) => void;\n /** Called when focus leaves the editable element. */\n onBlur?: () => void;\n /** Runs in the capture phase, before Lexical handles the key, so it can prevent `Enter`. */\n onKeyDown?: (event: KeyboardEvent<HTMLDivElement>) => void;\n /** Called with `true` when the editable element gains focus and `false` when it loses it. */\n onFocusChange?: (isFocused: boolean) => void;\n}\n\nfunction RichTextAreaImpl({\n children,\n name,\n value,\n source = 'markdown',\n className,\n containerClassName,\n placeholderClassName,\n placeholder = '',\n isDisabled = false,\n onChange,\n onBlur,\n onKeyDown,\n onFocusChange,\n forwardedRef,\n ...rest\n}: RichTextAreaProps & { forwardedRef?: Ref<HTMLInputElement> }) {\n const emittedValuesRef = useRef<string[]>([]);\n\n return (\n <LexicalComposer initialConfig={INITIAL_CONFIG}>\n <Wrapper\n data-slot=\"rich-text-area\"\n data-testid=\"rich-text-area\"\n aria-disabled={isDisabled}\n data-disabled={isDisabled}\n className={cn(\n 'relative size-full overflow-hidden',\n 'data-[disabled=true]:opacity-80',\n 'data-[disabled=true]:cursor-not-allowed data-[disabled=true]:select-none',\n containerClassName,\n )}\n {...rest}\n >\n <RichTextPlugin\n contentEditable={\n <ContentEditable\n data-slot=\"rich-text-area-editable\"\n className={cn('relative inset-0 overflow-y-auto', className)}\n data-name={name}\n aria-placeholder={placeholder}\n placeholder={\n <Typography\n variant=\"body\"\n className={cn(\n 'absolute left-0 top-0',\n 'text-text-tertiary',\n 'pointer-events-none user-select-none',\n placeholderClassName,\n )}\n asChild\n >\n {/* Typography stamps its own data-slot unless it renders as its child. */}\n <p data-slot=\"rich-text-area-placeholder\">{placeholder}</p>\n </Typography>\n }\n onKeyDownCapture={onKeyDown}\n style={{\n outline: 'none',\n minHeight: '20px',\n }}\n />\n }\n ErrorBoundary={LexicalErrorBoundary}\n />\n\n <DisabledPlugin isDisabled={isDisabled} />\n <ControlledValuePlugin value={value} source={source} emittedValuesRef={emittedValuesRef} />\n <ValuePlugin onChange={onChange} source={source} emittedValuesRef={emittedValuesRef} />\n <BlurPlugin onBlur={onBlur} />\n <HistoryPlugin />\n <ControlledPlugin controlledRef={forwardedRef ?? null} />\n <FocusPlugin onFocusChange={onFocusChange} />\n <TablePlugin />\n\n {source === 'markdown' && <MarkdownPlainPastePlugin />}\n {/* external plugins */}\n {children}\n </Wrapper>\n </LexicalComposer>\n );\n}\n\n/**\n * Toolbar-less Lexical editor whose value is Markdown or HTML. The ref exposes only `focus()`.\n * Pass extra Lexical plugins as children.\n */\nexport const RichTextArea = forwardRef<HTMLInputElement, RichTextAreaProps>((props, ref) => {\n return <RichTextAreaImpl {...props} forwardedRef={ref} />;\n});\n\nRichTextArea.displayName = 'RichTextArea';\n","export const DEFAULT_FONT_FAMILY = 'Arial, sans-serif' as const;\n\nexport const FONT_FAMILY_OPTIONS = [\n { value: 'Arial, sans-serif', label: 'Arial' },\n { value: 'Verdana, sans-serif', label: 'Verdana' },\n { value: 'Tahoma, sans-serif', label: 'Tahoma' },\n { value: '\"Trebuchet MS\", sans-serif', label: 'Trebuchet MS' },\n { value: '\"Times New Roman\", serif', label: 'Times New Roman' },\n { value: 'Georgia, serif', label: 'Georgia' },\n { value: 'Garamond, serif', label: 'Garamond' },\n { value: '\"Courier New\", monospace', label: 'Courier New' },\n { value: '\"Brush Script MT\", cursive', label: 'Brush Script MT' },\n] as const;\n\nexport const DEFAULT_FONT_FAMILY_VALUE = DEFAULT_FONT_FAMILY;\n\nexport const DEFAULT_FONT_SIZE = '16';\n\nexport const FONT_SIZE_OPTIONS = [\n { label: '10', value: '10' },\n { label: '12', value: '12' },\n { label: '16', value: '16' },\n { label: '20', value: '20' },\n { label: '24', value: '24' },\n { label: '34', value: '34' },\n { label: '48', value: '48' },\n] as const;\n\nexport const ALIGNMENT_OPTIONS = ['left', 'center', 'right'] as const;\n\nexport const DEFAULT_ALIGNMENT = 'left' as const;\n\nexport const DEFAULT_TEXT_COLOR = '#000000' as const;\n","import { SelectField, type SelectFieldProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ToolbarSelectProps extends SelectFieldProps {}\n\nexport function ToolbarSelect({ className, selectItemClassName, ...rest }: ToolbarSelectProps) {\n return (\n <SelectField\n fullWidth={false}\n size=\"small\"\n className={cn(className)}\n labelClassName={'border-none group-data-[state=open]/select:bg-secondary-states-hover!'}\n // chevronIconClassName={cn('text-secondary-main')}\n // selectItemClassName={cn('[&_svg]:size-[20px]', selectItemClassName)}\n // iconClassName={cn('h-16')}\n {...rest}\n />\n );\n}\n","import { mergeRegister } from '@lexical/utils';\nimport {\n $getSelection,\n $isElementNode,\n $isRangeSelection,\n COMMAND_PRIORITY_LOW,\n FORMAT_ELEMENT_COMMAND,\n type ElementFormatType,\n SELECTION_CHANGE_COMMAND,\n} from 'lexical';\nimport { type ReactNode, useCallback, useEffect, useMemo, useState } from 'react';\n\nimport {\n FormatAlignCenterIcon,\n FormatAlignLeftIcon,\n FormatAlignRightIcon,\n} from '@swisper.ai/icons';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { useRichTextAreaEditor } from '../../rich-text-area/hooks';\nimport { DEFAULT_ALIGNMENT } from '../constants';\nimport { type RichTextFieldAlignment } from '../context';\n\nimport { ToolbarSelect } from './toolbar-select';\n\nfunction toAlignment(format: ElementFormatType): RichTextFieldAlignment {\n if (format === 'center' || format === 'right') {\n return format;\n }\n if (format === 'end') {\n return 'right';\n }\n return 'left';\n}\n\nconst ALIGNMENT_OPTIONS_MAP: Record<RichTextFieldAlignment, { label: string; icon: ReactNode }> = {\n left: { label: 'Left', icon: <FormatAlignLeftIcon fontSize=\"inherit\" /> },\n center: { label: 'Center', icon: <FormatAlignCenterIcon fontSize=\"inherit\" /> },\n right: { label: 'Right', icon: <FormatAlignRightIcon fontSize=\"inherit\" /> },\n};\n\nexport interface AlignmentSelectProps {\n className?: string;\n}\n\nexport function AlignmentSelect({ className }: AlignmentSelectProps) {\n const editor = useRichTextAreaEditor();\n const [value, setValue] = useState<RichTextFieldAlignment>(DEFAULT_ALIGNMENT);\n\n const options = useMemo(\n () =>\n Object.entries(ALIGNMENT_OPTIONS_MAP).map(([value, { label, icon }]) => ({\n value: value as RichTextFieldAlignment,\n label,\n icon,\n })),\n [],\n );\n\n const $updateValue = useCallback(() => {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const node = selection.anchor.getNode();\n const parent = node.getParent();\n const element = $isElementNode(node) ? node : parent;\n if ($isElementNode(element)) {\n setValue(toAlignment(element.getFormatType() || DEFAULT_ALIGNMENT));\n }\n }\n }, []);\n\n useEffect(() => {\n return mergeRegister(\n editor.registerUpdateListener(({ editorState }) => {\n editorState.read(() => {\n $updateValue();\n });\n }),\n editor.registerCommand(\n SELECTION_CHANGE_COMMAND,\n () => {\n $updateValue();\n return false;\n },\n COMMAND_PRIORITY_LOW,\n ),\n );\n }, [editor, $updateValue]);\n\n function handleChange(value: string) {\n editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, value as ElementFormatType);\n }\n\n return (\n <ToolbarSelect\n shouldShowOnlyIcon\n options={options}\n value={value}\n onChange={handleChange}\n className={cn('w-[56px]!', className)}\n />\n );\n}\n","import { IconButton, type IconButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nexport interface ToolbarButtonProps extends IconButtonProps {\n isActive?: boolean;\n}\n\nexport function ToolbarButton({\n className,\n children,\n isActive,\n isDisabled = false,\n ...rest\n}: ToolbarButtonProps) {\n return (\n <IconButton\n isActive={isActive}\n className={cn('border-none bg-transparent', className)}\n size=\"sm\"\n variant=\"tertiary\"\n isDisabled={isDisabled}\n {...rest}\n >\n {children}\n </IconButton>\n );\n}\n","import { AttachmentsIcon } from '@swisper.ai/icons';\n\nimport { useRichTextAreaEditor } from '../../rich-text-area/hooks';\nimport { ATTACH_FILE_COMMAND } from '../../rich-text-area/plugins/file-attachment-plugin';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function AttachmentButton(props: ToolbarButtonProps) {\n const editor = useRichTextAreaEditor();\n\n function handleClick() {\n editor.dispatchCommand(ATTACH_FILE_COMMAND, undefined);\n }\n\n return (\n <ToolbarButton\n data-testid=\"attachment-button\"\n aria-label=\"Add Attachment\"\n onClick={handleClick}\n {...props}\n >\n <AttachmentsIcon />\n </ToolbarButton>\n );\n}\n","import { $isDecoratorBlockNode } from '@lexical/react/LexicalDecoratorBlockNode';\nimport { $isHeadingNode, $isQuoteNode } from '@lexical/rich-text';\nimport { $forEachSelectedTextNode, $isAtNodeEnd, $patchStyleText } from '@lexical/selection';\nimport { $isTableSelection } from '@lexical/table';\nimport { mergeRegister, $getNearestBlockElementAncestorOrThrow } from '@lexical/utils';\nimport type { PropertiesHyphenFallback } from 'csstype';\nimport InlineStyleParser from 'inline-style-parser';\nimport {\n $addUpdateTag,\n $caretRangeFromSelection,\n $createParagraphNode,\n $getNodeByKey,\n $getPreviousSelection,\n $getSelection,\n $getState,\n $isRangeSelection,\n $isTextNode,\n $setSelection,\n $setState,\n COMMAND_PRIORITY_EDITOR,\n createCommand,\n createState,\n type DOMConversionMap,\n type DOMExportOutput,\n type ElementNode,\n isDocumentFragment,\n isHTMLElement,\n type LexicalEditor,\n type LexicalNode,\n type RangeSelection,\n RootNode,\n SKIP_DOM_SELECTION_TAG,\n TextNode,\n type ValueOrUpdater,\n} from 'lexical';\n\n/**\n * Creates an object containing all the styles and their values provided in the CSS string.\n * @param css - The CSS string of styles and their values.\n * @returns The styleObject containing all the styles and their values.\n */\nexport function getStyleObjectFromRawCSS(css: string): StyleObject {\n let styleObject: undefined | Record<string, string>;\n for (const token of InlineStyleParser(css, { silent: true })) {\n if (token.type === 'declaration' && token.value) {\n styleObject = styleObject || {};\n styleObject[token.property] = token.value;\n }\n }\n return styleObject || NO_STYLE;\n}\n\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type StyleObject = Prettify<{\n [K in keyof PropertiesHyphenFallback]?:\n | undefined\n // This is simplified to not deal with arrays or numbers.\n // This is an example after all!\n | Extract<PropertiesHyphenFallback[K], string>;\n}>;\n\nexport type StyleTuple = Exclude<\n {\n [K in keyof StyleObject]: [K, null | Exclude<StyleObject[K], undefined>];\n }[keyof StyleObject],\n undefined\n>;\n\nexport const NO_STYLE: StyleObject = Object.freeze({});\n\nfunction parse(v: unknown): StyleObject {\n return typeof v === 'string' ? getStyleObjectFromRawCSS(v) : NO_STYLE;\n}\n\nfunction unparse(style: StyleObject): string {\n const styles: string[] = [];\n for (const [k, v] of Object.entries(style)) {\n if (k && v) {\n styles.push(`${k}: ${v};`);\n }\n }\n return styles.sort().join(' ');\n}\n\nfunction isEqualValue(\n a: StyleObject[keyof StyleObject],\n b: StyleObject[keyof StyleObject],\n): boolean {\n return a === b || (!a && !b);\n}\n\nfunction isEqual(a: StyleObject, b: StyleObject): boolean {\n if (a === b) {\n return true;\n }\n for (const k in a) {\n if (!(k in b && isEqualValue(a[k as keyof StyleObject], b[k as keyof StyleObject]))) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\nexport const styleState = createState('style', {\n isEqual,\n parse,\n unparse,\n});\n\nexport function $getStyleProperty<Prop extends keyof StyleObject>(\n node: LexicalNode,\n prop: Prop,\n): undefined | StyleObject[Prop] {\n return $getStyleObject(node)[prop];\n}\n\nexport function getStyleObjectDirect(node: LexicalNode): StyleObject {\n return $getState(node, styleState, 'direct');\n}\n\nexport function $getStyleObject(node: LexicalNode): StyleObject {\n return $getState(node, styleState);\n}\n\nexport function $setStyleObject<T extends LexicalNode>(\n node: T,\n valueOrUpdater: ValueOrUpdater<StyleObject>,\n): T {\n return $setState(node, styleState, valueOrUpdater);\n}\n\nexport function $removeStyleProperty<T extends LexicalNode, Prop extends keyof StyleObject>(\n node: T,\n prop: Prop,\n): T {\n return $setStyleObject(node, (prevStyle) => {\n if (prop in prevStyle) {\n const { [prop]: _ignore, ...nextStyle } = prevStyle;\n return nextStyle;\n }\n return prevStyle;\n });\n}\n\nexport function $setStyleProperty<T extends LexicalNode, Prop extends keyof StyleObject>(\n node: T,\n prop: Prop,\n value: ValueOrUpdater<StyleObject[Prop]>,\n): T {\n return $setStyleObject(node, (prevStyle) => {\n const prevValue = prevStyle[prop];\n const nextValue = typeof value === 'function' ? value(prevValue) : value;\n return prevValue === nextValue ? prevStyle : { ...prevStyle, [prop]: nextValue };\n });\n}\n\nexport function applyStyle(element: HTMLElement, styleObject: StyleObject): void {\n for (const k_ in styleObject) {\n const k = k_ as keyof StyleObject;\n element.style.setProperty(k, styleObject[k] ?? null);\n }\n}\n\nexport function diffStyleObjects(prevStyles: StyleObject, nextStyles: StyleObject): StyleObject {\n let styleDiff: undefined | Record<string, string | undefined>;\n if (prevStyles !== nextStyles) {\n for (const k_ in nextStyles) {\n const k = k_ as keyof StyleObject;\n const nextV = nextStyles[k];\n const prevV = prevStyles[k];\n if (!isEqualValue(nextV, prevV)) {\n styleDiff = styleDiff || {};\n styleDiff[k] = nextV;\n }\n }\n for (const k in prevStyles) {\n if (!(k in nextStyles)) {\n styleDiff = styleDiff || {};\n styleDiff[k] = undefined;\n }\n }\n }\n return styleDiff || NO_STYLE;\n}\n\nexport function mergeStyleObjects(prevStyles: StyleObject, nextStyles: StyleObject): StyleObject {\n return prevStyles === NO_STYLE || prevStyles === nextStyles\n ? nextStyles\n : { ...prevStyles, ...nextStyles };\n}\n\nexport function styleObjectToArray(styleObject: StyleObject): StyleTuple[] {\n const entries: StyleTuple[] = [];\n for (const k_ in styleObject) {\n const k = k_ as keyof StyleObject;\n entries.push([k, styleObject[k] ?? null] as StyleTuple);\n }\n entries.sort(([a], [b]) => a.localeCompare(b));\n return entries;\n}\n\nexport const PATCH_TEXT_STYLE_COMMAND = createCommand<\n StyleObject | ((prevStyles: StyleObject) => StyleObject)\n>('PATCH_TEXT_STYLE_COMMAND');\n\nfunction $nodeHasStyle(node: LexicalNode): boolean {\n return !isEqual(NO_STYLE, $getStyleObject(node));\n}\n\nexport function $selectionHasStyle(): boolean {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n const caretRange = $caretRangeFromSelection(selection);\n for (const slice of caretRange.getTextSlices()) {\n if (slice && $nodeHasStyle(slice.caret.origin)) {\n return true;\n }\n }\n for (const caret of caretRange.iterNodeCarets('root')) {\n if ($isTextNode(caret.origin) && $nodeHasStyle(caret.origin)) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function $patchSelectedTextStyle(\n styleObjectOrCallback: StyleObject | ((prevStyles: StyleObject) => StyleObject),\n): boolean {\n let selection = $getSelection();\n if (!selection) {\n const prevSelection = $getPreviousSelection();\n if (!prevSelection) {\n return false;\n }\n selection = prevSelection.clone();\n $setSelection(selection);\n }\n const styleCallback =\n typeof styleObjectOrCallback === 'function'\n ? styleObjectOrCallback\n : (prevStyles: StyleObject) => mergeStyleObjects(prevStyles, styleObjectOrCallback);\n if ($isRangeSelection(selection) && selection.isCollapsed()) {\n const node = selection.focus.getNode();\n if ($isTextNode(node)) {\n $setStyleObject(node, styleCallback);\n }\n } else {\n $forEachSelectedTextNode((node) => $setStyleObject(node, styleCallback));\n }\n return true;\n}\n\nconst PREV_STYLE_STATE = Symbol.for('styleState');\ninterface HTMLElementWithManagedStyle extends HTMLElement {\n // Store the last reconciled style object directly on the DOM\n // so we don't have to track the previous DOM\n // which can happen even when nodeMutation is 'updated'\n [PREV_STYLE_STATE]?: StyleObject;\n}\n\ninterface LexicalNodeWithUnknownStyle extends LexicalNode {\n // This property exists on all TextNode and ElementNode\n // and likely also some DecoratorNode by convention.\n // We use it as a heuristic to see if the style has likely\n // been overwritten to see if we should apply a diff\n // or all styles.\n __style?: unknown;\n}\n\nfunction styleStringChanged(\n node: LexicalNodeWithUnknownStyle,\n prevNode: LexicalNodeWithUnknownStyle,\n): boolean {\n return typeof node.__style === 'string' && prevNode.__style !== node.__style;\n}\n\nfunction getPreviousStyleObject(\n node: LexicalNode,\n prevNode: null | LexicalNode,\n dom: HTMLElementWithManagedStyle,\n): StyleObject {\n const prevStyleObject = dom[PREV_STYLE_STATE];\n return prevStyleObject && prevNode && !styleStringChanged(node, prevNode)\n ? prevStyleObject\n : NO_STYLE;\n}\n\n// This applies the style to the DOM of any node\nfunction makeStyleUpdateListener(editor: LexicalEditor): () => void {\n return mergeRegister(\n editor.registerMutationListener(RootNode, () => {\n // UpdateListener will only get the mutatedNodes payload when\n // at least one MutationListener is registered\n }),\n editor.registerUpdateListener((payload) => {\n const { prevEditorState, mutatedNodes } = payload;\n editor.getEditorState().read(\n () => {\n if (mutatedNodes) {\n for (const nodes of mutatedNodes.values()) {\n for (const [nodeKey, nodeMutation] of nodes) {\n if (nodeMutation === 'destroyed') {\n continue;\n }\n const node = $getNodeByKey(nodeKey);\n const dom: null | HTMLElementWithManagedStyle = editor.getElementByKey(nodeKey);\n if (!dom || !node) {\n return;\n }\n const prevNode = $getNodeByKey(nodeKey, prevEditorState);\n const prevStyleObject = getPreviousStyleObject(node, prevNode, dom);\n const nextStyleObject = $getStyleObject(node);\n dom[PREV_STYLE_STATE] = nextStyleObject;\n applyStyle(dom, diffStyleObjects(prevStyleObject, nextStyleObject));\n }\n }\n }\n },\n { editor },\n );\n }),\n );\n}\n\n// TODO https://github.com/facebook/lexical/issues/7259\n// there should be a better way to do this, this does not compose with other exportDOM overrides\nexport function $exportNodeStyle(editor: LexicalEditor, target: LexicalNode): DOMExportOutput {\n const output = target.exportDOM(editor);\n const style = $getStyleObject(target);\n if (style === NO_STYLE) {\n return output;\n }\n return {\n ...output,\n after: (generatedElement) => {\n const el = output.after ? output.after(generatedElement) : generatedElement;\n if (isHTMLElement(el)) {\n applyStyle(el, style);\n } else if (isDocumentFragment(el)) {\n // Work around a bug in the type\n return el;\n }\n return el;\n },\n };\n}\n\nconst IGNORE_STYLES = new Set<keyof StyleObject>([\n 'font-weight',\n 'text-decoration',\n 'font-style',\n 'vertical-align',\n]);\n\nexport type StyleMapping = (input: StyleObject) => StyleObject;\n\n// TODO there's no reasonable way to hook into importDOM/exportDOM from a plug-in https://github.com/facebook/lexical/issues/7259\nexport function constructStyleImportMap(\n styleMapping: StyleMapping = (input) => input,\n): DOMConversionMap {\n const importMap: DOMConversionMap = {};\n\n // Wrap all TextNode importers with a function that also imports\n // styles that are not otherwise imported\n for (const [tag, fn] of Object.entries(TextNode.importDOM() || {})) {\n importMap[tag] = (importNode) => {\n const importer = fn(importNode);\n if (!importer) {\n return null;\n }\n return {\n ...importer,\n conversion: (element) => {\n const output = importer.conversion(element);\n if (\n output?.forChild === undefined ||\n output.after !== undefined ||\n output.node !== null ||\n !element.hasAttribute('style')\n ) {\n return output;\n }\n let extraStyles: undefined | Record<string, string>;\n for (const k of element.style) {\n if (IGNORE_STYLES.has(k as keyof StyleObject)) {\n continue;\n }\n extraStyles = extraStyles || {};\n extraStyles[k] = element.style.getPropertyValue(k);\n }\n if (extraStyles) {\n const { forChild } = output;\n return {\n ...output,\n forChild: (child, parent) => {\n const node = forChild(child, parent);\n return $isTextNode(node)\n ? $setStyleObject(node, styleMapping(extraStyles as StyleObject))\n : node;\n },\n };\n }\n return output;\n },\n };\n };\n }\n return importMap;\n}\n\nexport function registerStyleState(editor: LexicalEditor): () => void {\n return mergeRegister(\n editor.registerCommand(\n PATCH_TEXT_STYLE_COMMAND,\n $patchSelectedTextStyle,\n COMMAND_PRIORITY_EDITOR,\n ),\n makeStyleUpdateListener(editor),\n );\n}\n\nexport function getSelectedNode(selection: RangeSelection): TextNode | ElementNode {\n const anchor = selection.anchor;\n const focus = selection.focus;\n const anchorNode = selection.anchor.getNode();\n const focusNode = selection.focus.getNode();\n if (anchorNode === focusNode) {\n return anchorNode;\n }\n const isBackward = selection.isBackward();\n if (isBackward) {\n return $isAtNodeEnd(focus) ? anchorNode : focusNode;\n } else {\n return $isAtNodeEnd(anchor) ? anchorNode : focusNode;\n }\n}\n\n/**\n * Patches the selection with the updated font size.\n */\nexport const updateFontSizeInSelection = (\n editor: LexicalEditor,\n newFontSize: string | null,\n _updateType: unknown,\n skipRefocus: boolean,\n) => {\n editor.update(() => {\n if (skipRefocus) {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n }\n if (editor.isEditable()) {\n const selection = $getSelection();\n if (selection !== null) {\n $patchStyleText(selection, {\n 'font-size': newFontSize + 'px',\n });\n }\n }\n });\n};\n\nexport function clearFormatting(editor: LexicalEditor, skipRefocus = false) {\n editor.update(() => {\n if (skipRefocus) {\n $addUpdateTag(SKIP_DOM_SELECTION_TAG);\n }\n const selection = $getSelection();\n if ($isRangeSelection(selection) || $isTableSelection(selection)) {\n const anchor = selection.anchor;\n const focus = selection.focus;\n const nodes = selection.getNodes();\n const extractedNodes = selection.extract();\n\n if (anchor.key === focus.key && anchor.offset === focus.offset) {\n return;\n }\n\n nodes.forEach((node, idx) => {\n // We split the first and last node by the selection\n // So that we don't format unselected text inside those nodes\n if ($isTextNode(node)) {\n // Use a separate variable to ensure TS does not lose the refinement\n let textNode = node;\n if (idx === 0 && anchor.offset !== 0) {\n textNode = textNode.splitText(anchor.offset)[1] || textNode;\n }\n if (idx === nodes.length - 1) {\n textNode = textNode.splitText(focus.offset)[0] || textNode;\n }\n /**\n * If the selected text has one format applied\n * selecting a portion of the text, could\n * clear the format to the wrong portion of the text.\n *\n * The cleared text is based on the length of the selected text.\n */\n // We need this in case the selected text only has one format\n const extractedTextNode = extractedNodes[0];\n if (nodes.length === 1 && $isTextNode(extractedTextNode)) {\n textNode = extractedTextNode;\n }\n\n if (textNode.__style !== '') {\n textNode.setStyle('');\n }\n if (textNode.__format !== 0) {\n textNode.setFormat(0);\n }\n const nearestBlockElement = $getNearestBlockElementAncestorOrThrow(textNode);\n if (nearestBlockElement.__format !== 0) {\n nearestBlockElement.setFormat('');\n }\n if (nearestBlockElement.__indent !== 0) {\n nearestBlockElement.setIndent(0);\n }\n } else if ($isHeadingNode(node) || $isQuoteNode(node)) {\n node.replace($createParagraphNode(), true);\n } else if ($isDecoratorBlockNode(node)) {\n node.setFormat('');\n }\n });\n }\n });\n}\n","import { $isLinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';\nimport { $getSelectionStyleValueForProperty, $patchStyleText } from '@lexical/selection';\nimport { mergeRegister } from '@lexical/utils';\nimport {\n $getSelection,\n $isRangeSelection,\n SELECTION_CHANGE_COMMAND,\n COMMAND_PRIORITY_LOW,\n FORMAT_TEXT_COMMAND,\n $addUpdateTag,\n SKIP_SELECTION_FOCUS_TAG,\n} from 'lexical';\nimport type { ReactNode } from 'react';\nimport { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';\n\nimport { useRichTextAreaEditor } from '../rich-text-area/hooks';\n\nimport {\n type ALIGNMENT_OPTIONS,\n DEFAULT_FONT_FAMILY_VALUE,\n DEFAULT_FONT_SIZE,\n DEFAULT_TEXT_COLOR,\n} from './constants';\nimport { updateFontSizeInSelection, getSelectedNode } from './utils';\n\nexport type RichTextFieldAlignment = (typeof ALIGNMENT_OPTIONS)[number];\n\nexport interface RichTextFieldContextValue {\n fontFamily: string;\n fontSize: string;\n textColor: string;\n isBold: boolean;\n isItalic: boolean;\n isUnderline: boolean;\n isLink: boolean;\n onFontFamily: (value: string) => void;\n onFontSize: (value: string) => void;\n onTextColor: (value: string) => void;\n onBold: () => void;\n onItalic: () => void;\n onUnderline: () => void;\n onLink: () => void;\n}\n\nconst sanitizeUrl = (url: string) => {\n return url.startsWith('http') ? url : `https://${url}`;\n};\n\nexport const RichTextFieldContext = createContext<RichTextFieldContextValue>(null!);\n\nexport function useRichTextFieldContext() {\n const context = useContext(RichTextFieldContext);\n\n if (!context) {\n throw new Error('\"useRichTextFieldContext\" must be used within a RichTextFieldContextProvider');\n }\n\n return context;\n}\n\nexport interface RichTextFieldContextProviderProps {\n children: ReactNode;\n}\n\nfunction normalizeColorToHex(color: string): string {\n const trimmed = color.trim();\n\n // hex #rgb or #rrggbb\n const hexMatch = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(trimmed);\n if (hexMatch) {\n const value = hexMatch[1];\n if (value.length === 3) {\n const [r, g, b] = value;\n return `#${r}${r}${g}${g}${b}${b}`.toLowerCase();\n }\n return `#${value.toLowerCase()}`;\n }\n\n // rgb(...) or rgba(...)\n const rgbMatch = /^rgba?\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})/i.exec(trimmed);\n if (rgbMatch) {\n const clamp = (n: number) => Math.max(0, Math.min(255, n));\n const [r, g, b] = rgbMatch.slice(1, 4).map((v) => clamp(Number.parseInt(v, 10)));\n const toHex = (n: number) => n.toString(16).padStart(2, '0');\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n }\n\n return DEFAULT_TEXT_COLOR;\n}\n\nexport function RichTextFieldContextProvider({ children }: RichTextFieldContextProviderProps) {\n const editor = useRichTextAreaEditor();\n\n const [fontFamily, setFontFamily] = useState<string>(DEFAULT_FONT_FAMILY_VALUE);\n const [fontSize, setFontSize] = useState<string>(DEFAULT_FONT_SIZE);\n const [isBold, setIsBold] = useState(false);\n const [isItalic, setIsItalic] = useState(false);\n const [isUnderline, setIsUnderline] = useState(false);\n const [textColor, setTextColor] = useState<string>(DEFAULT_TEXT_COLOR);\n const [isLink, setIsLink] = useState(false);\n\n const $updateToolbar = useCallback(() => {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n // font family\n setFontFamily(\n $getSelectionStyleValueForProperty(selection, 'font-family', DEFAULT_FONT_FAMILY_VALUE),\n );\n // font size\n const fontSize = $getSelectionStyleValueForProperty(\n selection,\n 'font-size',\n DEFAULT_FONT_SIZE + 'px',\n );\n setFontSize(fontSize ? fontSize.replace('px', '') : DEFAULT_FONT_SIZE);\n // bold\n setIsBold(selection.hasFormat('bold'));\n // italic\n setIsItalic(selection.hasFormat('italic'));\n // underline\n setIsUnderline(selection.hasFormat('underline'));\n // text-color\n const rawColor =\n $getSelectionStyleValueForProperty(selection, 'color', DEFAULT_TEXT_COLOR) ||\n DEFAULT_TEXT_COLOR;\n setTextColor(normalizeColorToHex(rawColor));\n // link\n const node = getSelectedNode(selection);\n const parent = node.getParent();\n const isLink = $isLinkNode(parent) || $isLinkNode(node);\n setIsLink(isLink);\n }\n }, []);\n\n useEffect(() => {\n return mergeRegister(\n editor.registerUpdateListener(({ editorState }) => {\n editorState.read(() => {\n $updateToolbar();\n });\n }),\n\n editor.registerCommand(\n SELECTION_CHANGE_COMMAND,\n () => {\n $updateToolbar();\n return false;\n },\n COMMAND_PRIORITY_LOW,\n ),\n );\n }, [editor, $updateToolbar]);\n\n const onFontFamily = useCallback(\n (value: string) => {\n editor.update(() => {\n $addUpdateTag(SKIP_SELECTION_FOCUS_TAG);\n const selection = $getSelection();\n if (selection !== null) {\n $patchStyleText(selection, {\n ['font-family']: value,\n });\n }\n });\n },\n [editor],\n );\n\n const onFontSize = useCallback(\n (value: string) => {\n updateFontSizeInSelection(editor, value, null, false);\n },\n [editor],\n );\n\n const onBold = useCallback(() => {\n editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'bold');\n }, [editor]);\n\n const onItalic = useCallback(() => {\n editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'italic');\n }, [editor]);\n\n const onUnderline = useCallback(() => {\n editor.dispatchCommand(FORMAT_TEXT_COMMAND, 'underline');\n }, [editor]);\n\n const onTextColor = useCallback(\n (value: string) => {\n editor.update(() => {\n $addUpdateTag(SKIP_SELECTION_FOCUS_TAG);\n const selection = $getSelection();\n if (selection !== null) {\n $patchStyleText(selection, {\n color: value,\n });\n }\n });\n },\n [editor],\n );\n\n const onLink = useCallback(() => {\n if (!isLink) {\n setIsLink(true);\n editor.dispatchCommand(TOGGLE_LINK_COMMAND, sanitizeUrl('https://'));\n } else {\n setIsLink(false);\n editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);\n }\n }, [isLink, setIsLink]);\n\n const contextValue = useMemo<RichTextFieldContextValue>(\n () => ({\n fontFamily,\n fontSize,\n textColor,\n isBold,\n isItalic,\n isUnderline,\n isLink,\n onFontFamily,\n onFontSize,\n onTextColor,\n onBold,\n onItalic,\n onUnderline,\n onLink,\n }),\n [\n fontFamily,\n fontSize,\n textColor,\n isBold,\n isItalic,\n isUnderline,\n isLink,\n onFontFamily,\n onFontSize,\n onTextColor,\n onBold,\n onItalic,\n onUnderline,\n onLink,\n ],\n );\n\n return (\n <RichTextFieldContext.Provider value={contextValue}>{children}</RichTextFieldContext.Provider>\n );\n}\n","import { FormatBoldIcon } from '@swisper.ai/icons';\n\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function BoldButton({ ...props }: ToolbarButtonProps) {\n const { isBold, onBold } = useRichTextFieldContext();\n\n return (\n <ToolbarButton\n data-testid=\"bold-button\"\n aria-label=\"Format Bold\"\n isActive={isBold}\n onClick={onBold}\n {...props}\n >\n <FormatBoldIcon />\n </ToolbarButton>\n );\n}\n","import { $getNearestBlockElementAncestorOrThrow } from '@lexical/utils';\nimport { $getSelection, $isRangeSelection, $isTextNode } from 'lexical';\nimport { useCallback } from 'react';\n\nimport { FormatCleanIcon } from '@swisper.ai/icons';\n\nimport { useRichTextAreaEditor } from '../../rich-text-area/hooks';\nimport { $patchSelectedTextStyle, NO_STYLE } from '../utils';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function CleanFormatButton({ ...props }: ToolbarButtonProps) {\n const editor = useRichTextAreaEditor();\n\n const handleClick = useCallback(() => {\n editor.update(() => {\n const selection = $getSelection();\n if ($isRangeSelection(selection)) {\n $patchSelectedTextStyle(() => NO_STYLE);\n\n for (const node of selection.extract()) {\n if ($isTextNode(node)) {\n node.setFormat(0);\n node.setStyle('');\n\n const blockElement = $getNearestBlockElementAncestorOrThrow(node);\n blockElement.setFormat('');\n }\n }\n }\n });\n }, [editor]);\n\n return (\n <ToolbarButton\n data-testid=\"clean-format-button\"\n aria-label=\"Reset Formatting\"\n onClick={handleClick}\n {...props}\n >\n <FormatCleanIcon />\n </ToolbarButton>\n );\n}\n","import { ImageIcon } from '@swisper.ai/icons';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function ImageButton({ ...props }: ToolbarButtonProps) {\n return (\n <ToolbarButton data-testid=\"image-button\" aria-label=\"Add Image\" {...props}>\n <ImageIcon />\n </ToolbarButton>\n );\n}\n","import { FormatItalicIcon } from '@swisper.ai/icons';\n\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function ItalicButton({ ...props }: ToolbarButtonProps) {\n const { isItalic, onItalic } = useRichTextFieldContext();\n\n return (\n <ToolbarButton\n data-testid=\"italic-button\"\n aria-label=\"Format Italics\"\n isActive={isItalic}\n onClick={onItalic}\n {...props}\n >\n <FormatItalicIcon />\n </ToolbarButton>\n );\n}\n","import { LinkOnIcon, LinkOffIcon } from '@swisper.ai/icons';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function LinkButton({ isActive, ...props }: ToolbarButtonProps) {\n return (\n <ToolbarButton data-testid=\"link-button\" aria-label=\"Add Link\" {...props}>\n {isActive ? <LinkOnIcon /> : <LinkOffIcon />}\n </ToolbarButton>\n );\n}\n","import { useMemo } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { FONT_SIZE_OPTIONS } from '../constants';\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarSelect } from './toolbar-select';\n\nexport interface SizeSelectProps {\n className?: string;\n}\n\nexport function SizeSelect({ className }: SizeSelectProps) {\n const { fontSize, onFontSize } = useRichTextFieldContext();\n const options = useMemo(() => [...FONT_SIZE_OPTIONS], []);\n\n return (\n <ToolbarSelect\n data-testid=\"size-select\"\n options={options}\n value={fontSize}\n onChange={onFontSize}\n className={cn('w-[72px] gap-0', className)}\n />\n );\n}\n","import { type ChangeEvent } from 'react';\n\nimport { FormatColorIcon } from '@swisper.ai/icons';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { DEFAULT_TEXT_COLOR } from '../constants';\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport interface TextColorButtonProps extends ToolbarButtonProps {\n /**\n * Classes for the element around the button and its colour input\n * (`data-slot=\"rich-text-field-text-color\"`), merged last. `className` lands on the button.\n */\n wrapperClassName?: string;\n}\n\n/**\n * Toolbar button that opens the browser's colour picker and applies the colour to the selected\n * text; its icon takes the colour at the caret. Works only inside a `RichTextField` toolbar.\n */\nexport function TextColorButton({ wrapperClassName, ...props }: TextColorButtonProps) {\n const { textColor, onTextColor } = useRichTextFieldContext();\n const isDefaultColor = textColor === DEFAULT_TEXT_COLOR;\n\n function handleColorChange(e: ChangeEvent<HTMLInputElement>) {\n onTextColor(e.target.value);\n }\n\n return (\n <div data-slot=\"rich-text-field-text-color\" className={cn('relative', wrapperClassName)}>\n <ToolbarButton data-testid=\"text-color-button\" aria-label=\"Text Color\" {...props}>\n <span style={!isDefaultColor ? { color: textColor } : {}}>\n <FormatColorIcon />\n </span>\n </ToolbarButton>\n <input\n type=\"color\"\n data-slot=\"rich-text-field-text-color-input\"\n value={textColor}\n onChange={handleColorChange}\n tabIndex={-1}\n style={{\n position: 'absolute',\n inset: 0,\n width: '100%',\n height: '100%',\n opacity: 0,\n cursor: 'pointer',\n }}\n />\n </div>\n );\n}\n","import { useMemo } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { FONT_FAMILY_OPTIONS } from '../constants';\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarSelect } from './toolbar-select';\n\nexport interface TypographySelectProps {\n className?: string;\n}\n\nexport function TypographySelect({ className }: TypographySelectProps) {\n const { fontFamily, onFontFamily } = useRichTextFieldContext();\n const options = useMemo(() => [...FONT_FAMILY_OPTIONS], []);\n\n return (\n <ToolbarSelect\n data-testid=\"typography-select\"\n options={options}\n value={fontFamily}\n onChange={onFontFamily}\n className={cn('w-[90px]', className)}\n />\n );\n}\n","import { FormatUnderlineIcon } from '@swisper.ai/icons';\n\nimport { useRichTextFieldContext } from '../context';\n\nimport { ToolbarButton, type ToolbarButtonProps } from './toolbar-button';\n\nexport function UnderlineButton({ ...props }: ToolbarButtonProps) {\n const { isUnderline, onUnderline } = useRichTextFieldContext();\n\n return (\n <ToolbarButton\n data-testid=\"underline-button\"\n aria-label=\"Format Underline\"\n isActive={isUnderline}\n onClick={onUnderline}\n {...props}\n >\n <FormatUnderlineIcon />\n </ToolbarButton>\n );\n}\n","import type { ReactNode } from 'react';\n\nimport { Divider } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\nimport { AlignmentSelect } from './alignment-select';\nimport { AttachmentButton } from './attachment-button';\nimport { BoldButton } from './bold-button';\nimport { CleanFormatButton } from './clean-format-button';\nimport { ImageButton } from './image-button';\nimport { ItalicButton } from './italic-button';\nimport { LinkButton } from './link-button';\nimport { SizeSelect } from './size-select';\nimport { TextColorButton } from './text-color-button';\nimport { TypographySelect } from './typography-select';\nimport { UnderlineButton } from './underline-button';\n\nexport interface FormattingToolbarPluginProps {\n /** Classes for the toolbar (`data-slot=\"rich-text-field-toolbar\"`), merged last. */\n className?: string;\n /** Renders the toolbar controls from `{ hasAttachments }`. Defaults to the full control set. */\n children?: ({ hasAttachments }: { hasAttachments: boolean }) => ReactNode;\n /** Handed to `children`; the default controls enable the attachment button with it. */\n hasAttachments?: boolean;\n}\n\nconst DefaultFormattingToolbarChildren = ({ hasAttachments }: { hasAttachments: boolean }) => (\n <>\n <TypographySelect />\n <SizeSelect />\n\n <Divider orientation=\"vertical\" />\n\n <BoldButton />\n <ItalicButton />\n <UnderlineButton />\n <TextColorButton />\n\n <Divider orientation=\"vertical\" />\n <LinkButton isDisabled />\n <AttachmentButton isDisabled={!hasAttachments} />\n <ImageButton isDisabled />\n\n <Divider orientation=\"vertical\" />\n\n <AlignmentSelect />\n\n <Divider orientation=\"vertical\" />\n\n <CleanFormatButton />\n </>\n);\n\n/**\n * The toolbar row `RichTextField` renders. Its controls read the field's formatting context, so it\n * only works inside a `RichTextField`, which already renders one: pass controls through the\n * field's `toolbarChildren` instead of rendering this yourself.\n */\nexport function FormattingToolbarPlugin({\n className,\n children = DefaultFormattingToolbarChildren,\n hasAttachments = false,\n}: FormattingToolbarPluginProps) {\n return (\n <div\n data-testid=\"formatting-toolbar\"\n data-slot=\"rich-text-field-toolbar\"\n className={cn(\n 'flex items-center gap-[2px]',\n 'px-[16px] py-[8px] overflow-x-auto',\n 'bg-paper-elevation-1 border-b border-divider-border-base',\n className,\n )}\n >\n {children({ hasAttachments })}\n </div>\n );\n}\n","import { forwardRef, type ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport { RichTextArea, type RichTextAreaProps } from '../rich-text-area';\nimport { FileAttachmentPlugin } from '../rich-text-area/plugins/file-attachment-plugin';\n\nimport { FormattingToolbarPlugin } from './components/formatting-toolbar-plugin';\nimport { RichTextFieldContextProvider } from './context';\n\n/** Where the formatting toolbar sits inside the field: above or below the text. */\nexport type RichTextFieldToolbarPlacement = 'top' | 'bottom';\n\nexport interface RichTextFieldProps extends Omit<RichTextAreaProps, 'children'> {\n /** Accepted for type compatibility with `RichTextArea` but not rendered; use `toolbarChildren`. */\n children?: ReactNode;\n /**\n * Puts the toolbar above or below the text. The text padding and the placeholder offset follow\n * it, and the root carries it as `data-toolbar-placement`.\n * @default 'top'\n */\n toolbarPlacement?: RichTextFieldToolbarPlacement;\n /** Classes for the toolbar (`data-slot=\"rich-text-field-toolbar\"`), merged last. */\n toolbarClassName?: string;\n /**\n * Replaces the default toolbar controls. Receives `{ hasAttachments }` (the `enableAttachments`\n * value) and returns the toolbar content, built from the exported buttons and selects.\n */\n toolbarChildren?: ({ hasAttachments }: { hasAttachments: boolean }) => ReactNode;\n /** Lets the file picker select several files; `onFileAttach` gets only the first otherwise. */\n isMultipleAttachments?: boolean;\n /** Enables the attachment button of the default toolbar; it is shown disabled otherwise. */\n enableAttachments?: boolean;\n /** File types the picker accepts, as extensions or MIME types (`['.pdf', 'image/*']`). */\n acceptedFiles?: string[];\n /** Called with the picked files after the attachment button opens the file picker. */\n onFileAttach?: (files: File[]) => void;\n}\n\n/**\n * A fixed-height rich-text editor with a formatting toolbar above or below the text, built on\n * `RichTextArea`. `className` styles the editable text, `containerClassName` the root\n * (`data-slot=\"rich-text-field\"`), `placeholderClassName` the placeholder and `toolbarClassName`\n * the toolbar; each is merged last.\n */\nexport const RichTextField = forwardRef<HTMLInputElement, RichTextFieldProps>(\n (\n {\n children,\n className,\n placeholderClassName,\n containerClassName,\n toolbarPlacement = 'top',\n toolbarChildren,\n toolbarClassName,\n isMultipleAttachments,\n enableAttachments,\n acceptedFiles,\n onFileAttach,\n ...rest\n },\n ref,\n ) => {\n const isToolbarTop = toolbarPlacement === 'top';\n\n return (\n <RichTextArea\n ref={ref}\n data-testid=\"rich-text-field\"\n data-slot=\"rich-text-field\"\n data-toolbar-placement={toolbarPlacement}\n placeholderClassName={cn(\n 'left-(--rich-text-field-editor-padding)',\n isToolbarTop\n ? 'top-[calc(var(--rich-text-field-toolbar-height)+var(--rich-text-field-editor-padding))]'\n : 'top-rich-text-field-editor-padding',\n placeholderClassName,\n )}\n containerClassName={cn(\n 'h-rich-text-field-height',\n 'rounded-rich-text-field-toolbar',\n isToolbarTop ? 'pt-rich-text-field-toolbar-height' : 'pb-rich-text-field-toolbar-height',\n containerClassName,\n )}\n className={cn(\n 'p-rich-text-field-editor-padding',\n 'bg-rich-text-field-background',\n 'size-full',\n className,\n )}\n {...rest}\n >\n <RichTextFieldContextProvider>\n <FormattingToolbarPlugin\n hasAttachments={enableAttachments}\n className={cn(\n 'absolute right-0 w-full',\n isToolbarTop ? 'top-0' : 'bottom-0',\n toolbarClassName,\n )}\n >\n {toolbarChildren}\n </FormattingToolbarPlugin>\n </RichTextFieldContextProvider>\n\n <FileAttachmentPlugin\n acceptedFiles={acceptedFiles}\n onFileAttach={onFileAttach}\n isMultiple={isMultipleAttachments}\n />\n </RichTextArea>\n );\n },\n);\n\nRichTextField.displayName = 'RichTextField';\n","import { cva, type VariantProps } from 'class-variance-authority';\nimport { type ComponentProps } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nconst topMenuActionsVariants = cva('flex shrink-0 items-center justify-end', {\n variants: {\n size: {\n md: ['px-[4px]', 'rounded-overlay-tools-wrapper bg-overlay-tools-background-base'],\n lg: [\n 'h-topmenu-height gap-topmenu-spacing-gap px-topmenu-spacing-padding',\n 'rounded-topmenu-base bg-topmenu-background',\n 'backdrop-blur-xs',\n ],\n },\n hasBorder: {\n true: '',\n false: '',\n },\n },\n compoundVariants: [{ size: 'lg', hasBorder: true, className: 'border border-topmenu-border' }],\n defaultVariants: {\n size: 'lg',\n hasBorder: true,\n },\n});\n\nexport interface TopMenuProps extends ComponentProps<'div'> {}\n\n/**\n * The root of a trailing action cluster. Positions itself at the top right of the nearest\n * positioned ancestor and stacks its `TopMenuActions` panels, aligned to the trailing edge.\n */\nexport function TopMenu({ className, children, ...rest }: TopMenuProps) {\n return (\n <div\n data-slot=\"topmenu\"\n role=\"group\"\n className={cn('absolute top-0 right-0', 'flex flex-col items-end w-fit', className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n\nexport interface TopMenuActionsProps\n extends ComponentProps<'div'>, VariantProps<typeof topMenuActionsVariants> {}\n\n/**\n * One panel of icon actions inside `TopMenu`: the frosted 48px header panel at `lg` (the default),\n * the compact overlay-tools pill at `md`. `hasBorder` only applies to `lg`.\n */\nexport function TopMenuActions({\n className,\n size,\n hasBorder,\n children,\n ...rest\n}: TopMenuActionsProps) {\n return (\n <div\n data-slot=\"topmenu-actions\"\n data-size={size ?? 'lg'}\n className={cn(topMenuActionsVariants({ size, hasBorder }), className)}\n {...rest}\n >\n {children}\n </div>\n );\n}\n","export const CHAT_ACTION_PROTOCOL = 'swisper';\n","import remarkGfm from 'remark-gfm';\nimport remarkParse from 'remark-parse';\nimport { unified } from 'unified';\nimport { visit } from 'unist-util-visit';\n\nimport { CHAT_ACTION_PROTOCOL } from '../constants';\nimport type { ChatAction } from '../types';\n\ninterface LinkPhrasingChild {\n type: string;\n value?: string;\n}\n\nexport function createChatActionURL(action: string, params?: Record<string, string>): string {\n const url = `${CHAT_ACTION_PROTOCOL}://action/${action}`;\n\n if (!params) {\n return url;\n }\n\n const searchParams = new URLSearchParams(params);\n\n return `${url}?${searchParams.toString()}`;\n}\n\nexport function createChatActionLink({\n action,\n label,\n params,\n}: {\n action: string;\n label: string;\n params?: Record<string, string>;\n}): string {\n return `[${label}](${createChatActionURL(action, params)})`;\n}\n\nexport function isChatActionURL(uri: string | undefined): boolean {\n if (!uri?.startsWith(`${CHAT_ACTION_PROTOCOL}://`)) {\n return false;\n }\n\n const url = new URL(uri);\n\n return (\n url.protocol === CHAT_ACTION_PROTOCOL + ':' &&\n url.hostname === 'action' &&\n url.pathname.startsWith('/') &&\n url.pathname.split('/').length === 2\n );\n}\n\nexport function extractChatActionMetadataFromUrl(\n link: string,\n): Pick<ChatAction, 'option' | 'payload'> | null {\n let url;\n\n try {\n url = new URL(link);\n } catch (error) {\n return null;\n }\n\n if (!isChatActionURL(link)) {\n return null;\n }\n\n const option = url.pathname.replace('/', '');\n const payload = Object.fromEntries(url.searchParams.entries());\n\n return {\n option,\n payload,\n };\n}\n\nfunction extractLabelFromNode(children: LinkPhrasingChild[]): string | null {\n for (const child of children) {\n if (child.type === 'text' && typeof child.value === 'string') {\n return child.value;\n }\n }\n\n return null;\n}\n\nexport function extractChatActionFromLink(markdown: string) {\n const ast = unified().use(remarkParse).use(remarkGfm).parse(markdown);\n\n let action: ChatAction | null = null;\n visit(ast, (node) => {\n if (node.type !== 'link') {\n return;\n }\n\n const metadata = extractChatActionMetadataFromUrl(node.url);\n const label = extractLabelFromNode(node.children);\n\n if (metadata && label) {\n action = {\n label,\n option: metadata.option,\n payload: metadata.payload,\n raw: node.url,\n };\n\n return;\n }\n });\n\n return action;\n}\n","import { useMemo } from 'react';\n\nimport { type ChatAction } from '../types';\nimport { extractChatActionFromLink } from '../utils';\n\nexport function useChatActions(actions: string[]) {\n return useMemo<ChatAction[]>(() => {\n return actions\n .map((link) => {\n const action = extractChatActionFromLink(link);\n\n if (!action) {\n return {\n label: link,\n };\n }\n\n return action;\n })\n .filter((action): action is ChatAction => action !== null);\n }, [actions]);\n}\n","import { createParser, type EventSourceMessage } from 'eventsource-parser';\nimport { useCallback } from 'react';\n\nexport type ChatStreamTokenParser<ParsedToken = string> = (chunk: string) => ParsedToken | null;\n\nexport interface UseChatStreamMessageOptions<ParsedToken = string> {\n stream: ReadableStreamDefaultReader<Uint8Array>;\n abortController?: AbortController;\n timeout?: number;\n tokenParser?: ChatStreamTokenParser<ParsedToken>;\n onChunkReceived: (chunk: ParsedToken) => void;\n onAbort?: (error: Error) => void;\n onFinish?: (message: string) => void;\n onError?: (error: Error) => void;\n}\n\nfunction defaultTokenParser<ParsedToken>(data: string): ParsedToken {\n return JSON.parse(data) as ParsedToken;\n}\n\nfunction isAbortError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n\n return error.name === 'AbortError' || error.name === 'TimeoutError';\n}\n\nfunction toError(value: unknown, fallbackMessage: string): Error {\n return value instanceof Error ? value : new Error(fallbackMessage);\n}\n\n/**\n * Process a chat message from a stream.\n *\n * @param stream - The stream to read from.\n * @param abortController - Optional abort controller to cancel the stream.\n * @param timeout - Optional idle timeout in ms; timer resets on each parsed chunk.\n * @param tokenParser - The function to parse the token.\n * @param onChunkReceived - The function to call when a chunk is received.\n * @param onAbort - Called once when the stream is cancelled (external abort, idle timeout, or reader cancellation).\n * @param onFinish - The function to call when the stream is finished.\n * @param onError - The function to call when an unexpected error occurs.\n *\n * @returns The function to process a chat message from a stream.\n *\n * @example\n * const { streamMessage } = useChatStreamMessage();\n * const stream = await streamMessage({\n * stream: readerStream,\n * timeout: 30_000,\n * onChunkReceived: (chunk) => {\n * console.log('chunk', chunk);\n * },\n * onAbort: (error) => {\n * console.log('stream aborted', error);\n * },\n * });\n */\nexport function useChatStreamMessage() {\n const streamMessage = useCallback(\n async <ParsedToken = string>({\n stream,\n abortController,\n timeout = 20_000, // 20 seconds\n tokenParser,\n onChunkReceived,\n onAbort,\n onFinish,\n onError,\n }: UseChatStreamMessageOptions<ParsedToken>) => {\n const parseToken = tokenParser ?? defaultTokenParser<ParsedToken>;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let didHandleAbort = false;\n\n const clearStreamTimeout = () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n timeoutId = undefined;\n }\n };\n\n const handleAbort = (error: Error) => {\n if (didHandleAbort) {\n return;\n }\n\n didHandleAbort = true;\n clearStreamTimeout();\n onAbort?.(error);\n };\n\n const resetStreamTimeout = () => {\n if (timeout === undefined) {\n return;\n }\n\n clearStreamTimeout();\n timeoutId = setTimeout(() => {\n const error = new DOMException(\n `Stream timed out after ${timeout}ms of inactivity`,\n 'TimeoutError',\n );\n\n // abort will close the stream, so we don't need to cancel it\n abortController?.abort(error);\n\n if (!abortController) {\n handleAbort(error);\n }\n }, timeout);\n };\n\n try {\n let message = '';\n const decoder = new TextDecoder('utf-8');\n\n const parser = createParser({\n onEvent(event: EventSourceMessage) {\n try {\n message += event.data;\n const token = parseToken(event.data);\n\n if (!token) {\n throw new Error(`Failed to parse SSE chunk: ${event.data}`);\n }\n\n if (!abortController?.signal.aborted) {\n onChunkReceived(token);\n resetStreamTimeout();\n }\n } catch (e) {\n abortController?.abort(e);\n console.warn('Failed to parse SSE chunk:', event.data, e);\n }\n },\n onError(error) {\n abortController?.abort(error);\n console.error('Error while parsing stream:', error);\n },\n });\n\n abortController?.signal.addEventListener(\n 'abort',\n () => {\n const error = toError(abortController.signal.reason, 'Stream aborted');\n handleAbort(error);\n },\n {\n once: true,\n },\n );\n\n resetStreamTimeout();\n\n while (!didHandleAbort) {\n const { value, done } = await stream.read();\n const chunk = decoder.decode(value, { stream: true });\n parser.feed(chunk);\n if (done) break;\n }\n\n clearStreamTimeout();\n\n if (!didHandleAbort && !abortController?.signal.aborted) {\n onFinish?.(message);\n }\n } catch (e) {\n const error = e as Error;\n\n if (didHandleAbort || abortController?.signal.aborted || isAbortError(error)) {\n if (!didHandleAbort) {\n handleAbort(toError(error, 'Stream aborted'));\n }\n return;\n }\n\n abortController?.abort(error);\n console.error('Error while reading stream:', error);\n onError?.(error);\n }\n },\n [],\n );\n\n return {\n streamMessage,\n };\n}\n","import { useEffect, useRef } from 'react';\n\nimport { useChatContext } from '@/contexts';\nimport type { ChatId } from '@/types';\n\ntype UseOnChatChangedOptions = (options: {\n chatId: ChatId;\n prevChatId: ChatId;\n isNewChat: boolean;\n}) => void;\n\nexport function useOnChatChanged(onChatChanged: UseOnChatChangedOptions) {\n const { chatId, isNewChat } = useChatContext();\n\n const isNewChatRef = useRef(isNewChat);\n const prevChatIdRef = useRef(chatId);\n const chatChangedFn = useRef(onChatChanged);\n\n chatChangedFn.current = onChatChanged;\n isNewChatRef.current = isNewChat;\n\n useEffect(() => {\n if (prevChatIdRef.current !== chatId) {\n chatChangedFn.current({\n chatId,\n prevChatId: prevChatIdRef.current,\n isNewChat: isNewChatRef.current,\n });\n\n prevChatIdRef.current = chatId;\n }\n }, [chatId]);\n}\n","import { useChatContext } from '@/contexts';\n\nexport function useCurrentChatId() {\n const { chatId } = useChatContext();\n return chatId;\n}\n","import { useChatContext } from '@/contexts';\n\nexport function useIsCurrentChatNew() {\n const { isNewChat } = useChatContext();\n return isNewChat;\n}\n","import { useCallback } from 'react';\n\nimport { useChatContext } from '@/contexts';\nimport type { ChatId } from '@/types';\n\ninterface UseLoadedChatIdsOptions {\n getIsChatLoaded: (chatId: ChatId) => boolean;\n markAsLoaded: (chatId: ChatId) => void;\n markAsUnloaded: (chatId: ChatId) => void;\n}\n\nexport function useChatLoadedIds(): UseLoadedChatIdsOptions {\n const { loadedChatIdsRef } = useChatContext();\n\n const getIsChatLoaded = useCallback((chatId: ChatId) => {\n return loadedChatIdsRef.current?.has(chatId) ?? false;\n }, []);\n\n const markAsLoaded = useCallback((chatId: ChatId) => {\n loadedChatIdsRef.current?.add(chatId);\n }, []);\n\n const markAsUnloaded = useCallback((chatId: ChatId) => {\n loadedChatIdsRef.current?.delete(chatId);\n }, []);\n\n return {\n getIsChatLoaded,\n markAsLoaded,\n markAsUnloaded,\n };\n}\n","import { useChatContext } from '@/contexts';\n\nexport function useChatPromptPlaceholder() {\n const { promptPlaceholder, setPromptPlaceholder, clearPromptPlaceholder } = useChatContext();\n\n return { promptPlaceholder, setPromptPlaceholder, clearPromptPlaceholder };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAMuC,KAAkBC,EAA2C,IAAI;AAEvE,SAAgBC,IAAqB;CACnC,IAAMC,IAAUC,EAAWJ,EAAe;CAE1C,IAAI,CAACG,GACH,MAAU,MACR,mKAEF;CAGF,OAAOA;AACT;AAEA,SAAgBE,GAAiB,EAC/B,UACA,eAIC;CACD,OAAO,kBAACL,GAAgB,UAAjB;EAAiC;EAAQ;CAAmC,CAAA;AACrF;;;ACPA,SAAgBM,GAAe,EAC7B,cACA,aACA,uBACA,GAAGC,KACmB;CACtB,IAAM,EAAE,kBAAe,aAAUL,EAAmB,GAE9CM,IAC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