@swisper.ai/web-chat-ui 0.1.0 → 0.2.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.
- package/README.md +2 -5
- package/dist/components/chat-card/chat-card.stories.d.ts.map +1 -1
- package/dist/components/chat-card-container/chat-card-container.stories.d.ts.map +1 -1
- package/dist/components/rich-text-field/rich-text-field.stories.d.ts.map +1 -1
- package/dist/components/rich-text-field/utils.d.ts +36 -36
- package/dist/index.css +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +1566 -1810
- package/dist/index.es.js.map +1 -1
- package/package.json +4 -4
- package/src/components/chat-card/chat-card.json +6 -6
- package/src/components/chat-card/chat-card.stories.tsx +6 -14
- package/src/components/chat-card/components/chat-card-body.tsx +1 -1
- package/src/components/chat-card-container/chat-card-container.json +6 -6
- package/src/components/chat-card-container/chat-card-container.stories.tsx +10 -18
- package/src/components/chat-container/chat-container.json +1 -1
- package/src/components/chat-list/chat-list-items.tsx +3 -3
- package/src/components/rich-text-field/rich-text-field.stories.tsx +3 -1
- package/src/index.ts +0 -1
- package/dist/layouts/chat-card-list-layout/chat-card-list-layout.d.ts +0 -97
- package/dist/layouts/chat-card-list-layout/chat-card-list-layout.d.ts.map +0 -1
- package/dist/layouts/chat-card-list-layout/chat-card-list-layout.stories.d.ts +0 -52
- package/dist/layouts/chat-card-list-layout/chat-card-list-layout.stories.d.ts.map +0 -1
- package/dist/layouts/chat-card-list-layout/index.d.ts +0 -3
- package/dist/layouts/chat-card-list-layout/index.d.ts.map +0 -1
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.d.ts +0 -89
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.d.ts.map +0 -1
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.sizing.d.ts +0 -44
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.sizing.d.ts.map +0 -1
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.stories.d.ts +0 -62
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.stories.d.ts.map +0 -1
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.variants.d.ts +0 -81
- package/dist/layouts/chat-card-three-column-layout/chat-card-three-column-layout.variants.d.ts.map +0 -1
- package/dist/layouts/chat-card-three-column-layout/index.d.ts +0 -5
- package/dist/layouts/chat-card-three-column-layout/index.d.ts.map +0 -1
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.d.ts +0 -37
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.d.ts.map +0 -1
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.sizing.d.ts +0 -12
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.sizing.d.ts.map +0 -1
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.stories.d.ts +0 -40
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.stories.d.ts.map +0 -1
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.variants.d.ts +0 -35
- package/dist/layouts/chat-card-two-column-layout/chat-card-two-column-layout.variants.d.ts.map +0 -1
- package/dist/layouts/chat-card-two-column-layout/index.d.ts +0 -4
- package/dist/layouts/chat-card-two-column-layout/index.d.ts.map +0 -1
- package/dist/layouts/index.d.ts +0 -4
- package/dist/layouts/index.d.ts.map +0 -1
- package/src/layouts/chat-card-list-layout/__stories__/fixtures.ts +0 -112
- package/src/layouts/chat-card-list-layout/__stories__/result-card.tsx +0 -36
- package/src/layouts/chat-card-list-layout/__stories__/types.ts +0 -31
- package/src/layouts/chat-card-list-layout/__tests__/chat-card-list-layout.spec.tsx +0 -204
- package/src/layouts/chat-card-list-layout/chat-card-list-layout.json +0 -129
- package/src/layouts/chat-card-list-layout/chat-card-list-layout.stories.tsx +0 -422
- package/src/layouts/chat-card-list-layout/chat-card-list-layout.tsx +0 -254
- package/src/layouts/chat-card-list-layout/index.ts +0 -11
- package/src/layouts/chat-card-three-column-layout/__stories__/fixtures.ts +0 -117
- package/src/layouts/chat-card-three-column-layout/__stories__/resizable-chat-window.tsx +0 -18
- package/src/layouts/chat-card-three-column-layout/__stories__/stay-details.tsx +0 -85
- package/src/layouts/chat-card-three-column-layout/__stories__/stay-list.tsx +0 -47
- package/src/layouts/chat-card-three-column-layout/__stories__/stay-map.tsx +0 -44
- package/src/layouts/chat-card-three-column-layout/__stories__/stay-rooms.tsx +0 -61
- package/src/layouts/chat-card-three-column-layout/__stories__/types.ts +0 -35
- package/src/layouts/chat-card-three-column-layout/__tests__/chat-card-three-column-layout.sizing.test.ts +0 -71
- package/src/layouts/chat-card-three-column-layout/__tests__/chat-card-three-column-layout.spec.tsx +0 -327
- package/src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.json +0 -153
- package/src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.sizing.ts +0 -76
- package/src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.stories.tsx +0 -658
- package/src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.tsx +0 -293
- package/src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.variants.ts +0 -146
- package/src/layouts/chat-card-three-column-layout/index.ts +0 -24
- package/src/layouts/chat-card-two-column-layout/__stories__/connection-itinerary.tsx +0 -51
- package/src/layouts/chat-card-two-column-layout/__stories__/fixtures.ts +0 -83
- package/src/layouts/chat-card-two-column-layout/__stories__/route-map.tsx +0 -24
- package/src/layouts/chat-card-two-column-layout/__stories__/types.ts +0 -15
- package/src/layouts/chat-card-two-column-layout/__tests__/chat-card-two-column-layout.spec.tsx +0 -109
- package/src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.json +0 -109
- package/src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.sizing.ts +0 -21
- package/src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.stories.tsx +0 -439
- package/src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.tsx +0 -141
- package/src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.variants.ts +0 -65
- package/src/layouts/chat-card-two-column-layout/index.ts +0 -17
- package/src/layouts/index.ts +0 -3
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":["_Fragment","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","React","EmptyState$1","EmptyStateActionRow$1","EmptyStateDescription$1","EmptyStateIcon$1","EmptyStateTitle$1","TRANSFORMERS$1","ScrollAreaPrimitive","mime","rehypeSanitize","InlineStyleParser","remarkGfm","remarkParse","DEFAULT_VISIBLE_COUNT","ChatCardListLayoutContext","createContext","useChatCardListLayoutContext","context","useContext","ChatCardListLayout","forwardRef","rest","internalExpanded","setInternalExpanded","useState","defaultExpanded","hiddenCount","setHiddenCount","isExpanded","expanded","expand","useCallback","onExpandedChange","contextValue","useMemo","visibleCount","Component","asChild","Slot","cn","className","ChatCardListLayoutItems","items","Children","children","useLayoutEffect","Fragment","ChatCardListLayoutShowMore","handleClick","onClick","event","Button","getSize","width","resolveLayout","size","detailsPlacement","DEFAULT_DETAILS_PLACEMENT","chatCardThreeColumnLayoutVariants","cva","chatCardThreeColumnLayoutListVariants","chatCardThreeColumnLayoutMainVariants","chatCardThreeColumnLayoutDetailsVariants","chatCardThreeColumnLayoutPanelVariants","chatCardThreeColumnLayoutCardVariants","ChatCardThreeColumnLayoutContext","useChatCardThreeColumnLayoutContext","part","renderPane","isFloating","useMergedRef","first","node","second","ChatCardThreeColumnLayout","measureRef","useElementMeasure","mergedRef","ref","isDetailsFloating","isDetailsSheet","ChatCardThreeColumnLayoutList","ChatCardThreeColumnLayoutMain","ChatCardThreeColumnLayoutDetails","ChatCardThreeColumnLayoutPanel","chatCardTwoColumnLayoutVariants","chatCardTwoColumnLayoutGridVariants","chatCardTwoColumnLayoutAsideVariants","chatCardTwoColumnLayoutMainVariants","chatCardTwoColumnLayoutCardVariants","ChatCardTwoColumnLayoutContext","useChatCardTwoColumnLayoutContext","ChatCardTwoColumnLayout","gridClassName","ChatCardTwoColumnLayoutAside","ChatCardTwoColumnLayoutMain","ChatCardContext","useChatCardContext","ChatCardProvider","ChatCardHeader","inner","level","isCollapsible","hoverAreaClassName","CollapsibleTrigger","ChatCardIcon","ChatCardHeaderContent","ChatCardTitle","Typography","ChatCardSubTitle","ChatCardActions","ChatCardActionButton","shouldPreventCollapse","content","IconButton","tooltip","Tooltip","ChatCardCollapsibleButton","CollapsibleChevron","ChatCardMedia","ChatCardBody","CollapsibleContent","ChatCardContent","hasPadding","hasHeaderPadding","ChatCardPreview","ChatCardFooter","ChatCardFooterNotes","ChatCardFooterPrice","ChatCardFooterActions","ChatCardForm","ChatCardAttributes","ChatCardAttribute","ChatCardAttributeLabel","Chip","ChatCardAttributeValue","ChatCard","openProp","isControlled","uncontrolledOpen","setUncontrolledOpen","defaultOpen","open","handleOpenChange","next","onOpenChange","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","slotHeights","setSlotHeights","setSlotHeight","current","slot","slotHeight","containerStyle","height","contentWidth","style","useChatContainerSlot","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","ChatListContext","useChatListContext","ChatList","hasMoreProp","ariaLabel","scrollElementRef","loadMoreContentRef","loadMoreVersion","setLoadMoreVersion","skeletonContainer","setSkeletonContainer","setScrollElementVersion","setScrollElement","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","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","ChatPromptBoxToolbar","ChatPromptBoxContent","ChatPromptBoxInput","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","setExpanded","nextExpanded","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","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","isValidElement","child","cloneElement","ChatSuggestion","onHover","ListItem","listItemVariants","ListItemTrigger","triggerClassName","ChatSuggestionLabelIcon","OrderChip","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","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","TopMenu","TopMenuActions","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/layouts/chat-card-list-layout/chat-card-list-layout.tsx","../src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.sizing.ts","../src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.variants.ts","../src/layouts/chat-card-three-column-layout/chat-card-three-column-layout.tsx","../src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.variants.ts","../src/layouts/chat-card-two-column-layout/chat-card-two-column-layout.tsx","../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/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 { Slot } from '@radix-ui/react-slot';\nimport type { ComponentProps, MouseEvent, ReactNode } from 'react';\nimport {\n Children,\n createContext,\n forwardRef,\n useCallback,\n useContext,\n useLayoutEffect,\n useMemo,\n useState,\n} from 'react';\n\nimport { Button } from '@swisper.ai/ui';\nimport type { ButtonProps } from '@swisper.ai/ui';\nimport { cn } from '@swisper.ai/web-core';\n\n/**\n * How many items are rendered before the reveal.\n *\n * Three, because the collapsed list has to read as \"there is more here\" at a glance.\n * One or two look like the whole answer and the button gets ignored; from five up the\n * collapsed state is already taller than a phone viewport, which is the thing this\n * layout exists to prevent.\n */\nconst DEFAULT_VISIBLE_COUNT = 3;\n\ninterface ChatCardListLayoutContextValue {\n visibleCount: number;\n isExpanded: boolean;\n expand: () => void;\n hiddenCount: number;\n setHiddenCount: (count: number) => void;\n}\n\nconst ChatCardListLayoutContext = createContext<ChatCardListLayoutContextValue>(null!);\n\n/**\n * Reads the layout's state from any descendant.\n *\n * Exported so a consumer can put the hidden count in their own label (\"Show 5 more\") or\n * build a trigger that isn't a `Button`. `hiddenCount` is `0` on the first render and\n * correct from the first layout effect onwards — see `ChatCardListLayoutItems`.\n */\nexport function useChatCardListLayoutContext() {\n const context = useContext(ChatCardListLayoutContext);\n\n if (!context) {\n throw new Error(\n '[web-chat-ui] \"useChatCardListLayoutContext\" must be used within a ChatCardListLayout. ' +\n 'ChatCardListLayoutItems and ChatCardListLayoutShowMore both read it, so both must be ' +\n 'rendered inside the ChatCardListLayout element, not as siblings of it.',\n );\n }\n\n return context;\n}\n\nexport interface ChatCardListLayoutProps extends ComponentProps<'div'> {\n children: ReactNode;\n /**\n * How many items `ChatCardListLayoutItems` renders while collapsed.\n *\n * Clamped at zero: a negative value would reach `Array.slice` as a count from the end\n * and quietly render the *last* n items, which is the opposite of what the caller\n * asked for.\n */\n visibleCount?: number;\n /**\n * Expanded state for the uncontrolled case. Set it when the surrounding message is\n * restored from history and the reader had already expanded this list.\n */\n defaultExpanded?: boolean;\n /**\n * Controlled expanded state. Pass it only if something outside owns the state —\n * driving it back to `false` re-collapses the list and brings the button back, which\n * the uncontrolled component deliberately cannot do.\n */\n expanded?: boolean;\n onExpandedChange?: (expanded: boolean) => void;\n asChild?: boolean;\n}\n\n/**\n * Holds a list of chat cards and reveals the overflow behind a one-way \"show more\".\n *\n * Structure and state only. By default the root stacks its children in a left-aligned\n * column with an 8px gap; `className` is merged last, so the consumer's direction, gap and\n * alignment replace those and the same layout serves a stacked card list and a horizontal\n * strip without a variant prop. The `group/chat-card-list-layout` marker paints nothing\n * and exists so descendants can react to the expanded state with\n * `group-data-[expanded=true]/chat-card-list-layout:…`.\n *\n * The three parts exist because the pieces of information live in different places: only\n * `ChatCardListLayoutItems` knows how many children there are, only\n * `ChatCardListLayoutShowMore` needs to know whether any are hidden, and this root owns\n * the state that joins them. Slicing here instead would mean telling item children apart\n * from the button by inspecting `child.type`, which breaks the moment either is wrapped.\n */\nexport const ChatCardListLayout = forwardRef<HTMLDivElement, ChatCardListLayoutProps>(\n function ChatCardListLayout(\n {\n children,\n className,\n visibleCount = DEFAULT_VISIBLE_COUNT,\n defaultExpanded = false,\n expanded,\n onExpandedChange,\n asChild = false,\n ...rest\n },\n ref,\n ) {\n const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);\n const [hiddenCount, setHiddenCount] = useState(0);\n\n const isExpanded = expanded ?? internalExpanded;\n\n const expand = useCallback(() => {\n if (expanded === undefined) {\n setInternalExpanded(true);\n }\n\n onExpandedChange?.(true);\n }, [expanded, onExpandedChange]);\n\n const contextValue = useMemo(\n () => ({\n visibleCount: Math.max(0, visibleCount),\n isExpanded,\n expand,\n hiddenCount,\n setHiddenCount,\n }),\n [visibleCount, isExpanded, expand, hiddenCount],\n );\n\n const Component = asChild ? Slot : 'div';\n\n return (\n <ChatCardListLayoutContext.Provider value={contextValue}>\n <Component\n ref={ref}\n data-slot=\"chat-card-list-layout\"\n data-testid=\"chat-card-list-layout\"\n data-expanded={isExpanded}\n className={cn(\n 'group/chat-card-list-layout',\n 'flex flex-col items-start gap-[8px]',\n className,\n )}\n {...rest}\n >\n {children}\n </Component>\n </ChatCardListLayoutContext.Provider>\n );\n },\n);\n\nChatCardListLayout.displayName = 'ChatCardListLayout';\n\nexport interface ChatCardListLayoutItemsProps {\n children: ReactNode;\n}\n\n/**\n * Renders the visible slice of the list, and nothing else — no wrapper element.\n *\n * A `div` here would sit between the root's `className` and the cards, so a consumer's\n * `flex`/`grid` on the root would apply to this one wrapper instead of to the items and\n * the layout would silently collapse to a single column. There is no `className` prop\n * for the same reason: there is no node to hang it on.\n *\n * Hidden items are sliced away rather than hidden with CSS, so they never mount: no DOM,\n * no image or data fetches from cards nobody has asked for, and nothing invisible in the\n * tab order.\n *\n * Only one of these per layout. Two would race on `hiddenCount` and the last effect\n * would win; summing across instances is buildable but nothing needs it yet.\n */\nexport function ChatCardListLayoutItems({ children }: ChatCardListLayoutItemsProps) {\n const { visibleCount, isExpanded, setHiddenCount } = useChatCardListLayoutContext();\n\n // `Children.toArray` flattens fragments and drops `null`/`undefined`/booleans, so a\n // conditionally rendered card counts only when it actually renders. Reading\n // `Children.count` instead would count the holes and the button would offer to reveal\n // items that do not exist.\n const items = Children.toArray(children);\n const hiddenCount = isExpanded ? 0 : Math.max(0, items.length - visibleCount);\n\n // A layout effect, not `useEffect`: `hiddenCount` starts at 0, so the button renders\n // `null` on the first pass and this correction has to land before the browser paints.\n // With `useEffect` the button would visibly pop in after the list.\n useLayoutEffect(() => {\n setHiddenCount(hiddenCount);\n }, [hiddenCount, setHiddenCount]);\n\n return <>{isExpanded ? items : items.slice(0, visibleCount)}</>;\n}\n\nexport interface ChatCardListLayoutShowMoreProps extends Omit<ButtonProps, 'children'> {\n /**\n * The label. Required on purpose: a default `'Show more'` baked into the package would\n * be untranslatable by the app that ships it, and this is the one string in the layout\n * a reader actually sees.\n */\n children: ReactNode;\n}\n\n/**\n * The reveal trigger. Renders nothing once there is nothing left to reveal — either the\n * list is expanded, or it never overflowed — which is what makes the button a one-shot\n * affordance rather than a toggle.\n *\n * By default it is a small tertiary `Button` centred under the cards. Every `Button` prop\n * is forwarded after those defaults and `className` is merged last, so a consumer's\n * `variant`, `size` or classes win.\n */\nexport const ChatCardListLayoutShowMore = forwardRef<\n // The same element union `Button` forwards: it renders a `span` when `isSemantic` is\n // false, and narrowing to `HTMLButtonElement` here would make a plain object ref fail\n // to type-check against it.\n HTMLButtonElement | HTMLSpanElement,\n ChatCardListLayoutShowMoreProps\n>(function ChatCardListLayoutShowMore({ children, onClick, className, ...rest }, ref) {\n const { isExpanded, hiddenCount, expand } = useChatCardListLayoutContext();\n\n function handleClick(event: MouseEvent<HTMLButtonElement>) {\n expand();\n onClick?.(event);\n }\n\n if (isExpanded || hiddenCount === 0) {\n return null;\n }\n\n return (\n <Button\n ref={ref}\n variant=\"tertiary\"\n size=\"sm\"\n data-slot=\"chat-card-list-layout-show-more\"\n data-testid=\"chat-card-list-layout-show-more\"\n onClick={handleClick}\n className={cn('mx-auto', className)}\n {...rest}\n >\n {children}\n </Button>\n );\n});\n\nChatCardListLayoutShowMore.displayName = 'ChatCardListLayoutShowMore';\n","import type { ChatCardThreeColumnLayoutDetailsPlacement } from './chat-card-three-column-layout.variants';\n\n/*\n * Pane widths are fixed pixels per size tier, as in the places card this layout came from:\n * List is 290px at `lg` and 358px at `xl`, and Details is always 358px. The recipes in\n * `chat-card-three-column-layout.variants.ts` write them out as literal `290px` / `358px`,\n * because Tailwind cannot read a constant, so change both together.\n */\nexport const LIST_WIDTH_LG = 290;\n/** List at `xl`, and Details at every tier (as a column and as a pinned floating pane). */\nexport const PANE_WIDTH_XL = 358;\n\n/**\n * Narrowest Main may get before a pane has to float over it instead of sitting beside it.\n * Main is usually a map or a chart, and below ~400px a map shows too little context to\n * pick a place from. This is the one number to tune when a card feels cramped.\n */\nexport const MIN_MAIN_WIDTH = 400;\n\n/** Must equal the `gap-[8px]` on the root grid, or the thresholds are off by that much. */\nexport const GAP = 8;\n\n/**\n * Below this, a floating Details is a bottom sheet (`sm`). Pinned to Main's right edge at\n * 358px, it would leave a sliver of Main too thin to read or tap.\n */\nexport const MD_MIN_WIDTH = 640;\n\n/** `lg`: a 290px List column fits beside a usable Main. */\nexport const LG_MIN_WIDTH = LIST_WIDTH_LG + GAP + MIN_MAIN_WIDTH;\n\n/**\n * `xl`: a Details column fits beside a 358px List and a usable Main. List widens to 358px at\n * the same point, as in the original, where both changed at the `xl` breakpoint.\n */\nexport const XL_MIN_WIDTH = PANE_WIDTH_XL * 2 + GAP * 2 + MIN_MAIN_WIDTH;\n\n/** Size tier, named after the viewport breakpoints the original card used. */\nexport type ChatCardThreeColumnLayoutSize = 'sm' | 'md' | 'lg' | 'xl';\n\nexport interface ChatCardThreeColumnLayoutResolved {\n size: ChatCardThreeColumnLayoutSize;\n isDetailsFloating: boolean;\n isDetailsSheet: boolean;\n}\n\nfunction getSize(width: number): ChatCardThreeColumnLayoutSize {\n if (width >= XL_MIN_WIDTH) return 'xl';\n if (width >= LG_MIN_WIDTH) return 'lg';\n if (width >= MD_MIN_WIDTH) return 'md';\n return 'sm';\n}\n\n/**\n * Where each pane goes, given the width the layout actually has.\n *\n * The tiers are the original card's `md` / `lg` / `xl`, but measured on the layout, not\n * the viewport. The card is sized by the chat window, and a sidebar, a split view or the\n * Storybook panel all make the viewport claim room the card doesn't have (or the reverse).\n *\n * `'unset'` means the layout has not been measured yet (on the server, or before the first\n * layout effect). It resolves to `xl`: SSR HTML is mostly seen on desktops, and on the\n * client the measurement lands before paint.\n */\nexport function resolveLayout(\n width: number | 'unset',\n detailsPlacement: ChatCardThreeColumnLayoutDetailsPlacement,\n): ChatCardThreeColumnLayoutResolved {\n const size = width === 'unset' ? 'xl' : getSize(width);\n\n return {\n size,\n isDetailsFloating: detailsPlacement === 'floating' || size !== 'xl',\n isDetailsSheet: size === 'sm',\n };\n}\n","import { cva } from 'class-variance-authority';\n\n/**\n * Whether Details may take its own right column.\n *\n * - `responsive` — a column whenever the layout is wide enough for List, Details and a\n * usable Main side by side; floating over Main otherwise.\n * - `floating` — always over Main, for a pane that is secondary at every size.\n *\n * There is no \"always a column\": at widths where it would not fit, Main would be squeezed\n * below usefulness, which is exactly what the width check exists to prevent.\n */\nexport type ChatCardThreeColumnLayoutDetailsPlacement = 'responsive' | 'floating';\n\n/**\n * `responsive` because it uses the room when it is there: `floating` would cover Main on\n * a card with space to spare.\n */\nexport const DEFAULT_DETAILS_PLACEMENT: ChatCardThreeColumnLayoutDetailsPlacement = 'responsive';\n\n/*\n * Every recipe below keys on data attributes the components set from the layout's measured\n * width (`data-size`, `data-details-floating` on the root; `data-size` on List and Panel;\n * `data-floating`, `data-sheet` on Details). `290px` and `358px` are `LIST_WIDTH_LG` and\n * `PANE_WIDTH_XL` from `chat-card-three-column-layout.sizing.ts`, written out because\n * Tailwind cannot read a constant. Change both together.\n *\n * The tiers are the original card's `md` / `lg` / `xl`, but none of the recipes uses viewport\n * breakpoints: the card is sized by the chat window, not the viewport, so `lg:` / `xl:`\n * would switch panes at the wrong widths.\n *\n * Using a recipe without its component means setting those attributes yourself.\n *\n * Class strings are written out in full because Tailwind finds classes by scanning source;\n * a class assembled from a constant is never generated.\n */\n\n/**\n * Root grid.\n *\n * The third track needs both \"Details fits\" (`data-details-floating=false`, from the\n * width) and \"Details is mounted\" (`:has(> [data-slot=…-details])`). The second is CSS, not\n * a prop, because consumers mount Details conditionally and a `hasDetails` prop could\n * disagree with what is rendered.\n */\nexport const chatCardThreeColumnLayoutVariants = cva([\n 'relative grid gap-[8px]',\n // sm + md — Main only; there is no List column and Details floats over Main\n \"grid-cols-[1fr] [grid-template-areas:'main']\",\n \"data-[size=lg]:grid-cols-[290px_1fr] data-[size=lg]:[grid-template-areas:'list_main']\",\n \"data-[size=xl]:grid-cols-[358px_1fr] data-[size=xl]:[grid-template-areas:'list_main']\",\n // xl with a mounted Details that is allowed a column\n 'data-[details-floating=false]:has-[>[data-slot=chat-card-three-column-layout-details]]:grid-cols-[358px_1fr_358px]',\n \"data-[details-floating=false]:has-[>[data-slot=chat-card-three-column-layout-details]]:[grid-template-areas:'list_main_details']\",\n]);\n\n/**\n * Column 1 at `lg` and `xl`. Below that the grid has no `list` area, so the column classes\n * are keyed on the size: naming a missing area would add a stray track. `hideOnMobile`\n * hides the pane at those sizes, without unmounting it.\n *\n * In the column, `min-h-0` + `overflow-hidden` keep a long list inside the row. Without them\n * the grid item grows to its content and the card gets taller instead of scrolling.\n */\nexport const chatCardThreeColumnLayoutListVariants = cva(\n [\n 'min-w-0',\n 'data-[size=lg]:[grid-area:list] data-[size=lg]:min-h-0 data-[size=lg]:h-full data-[size=lg]:overflow-hidden',\n 'data-[size=xl]:[grid-area:list] data-[size=xl]:min-h-0 data-[size=xl]:h-full data-[size=xl]:overflow-hidden',\n ],\n {\n variants: {\n hideOnMobile: {\n true: 'data-[size=sm]:hidden data-[size=md]:hidden',\n false: '',\n },\n },\n defaultVariants: {\n hideOnMobile: false,\n },\n },\n);\n\n/**\n * Column 2, the flexible `1fr` track. `min-w-0` because a grid item's minimum width is its\n * content by default: a map or a wide table would push the track past the card. `relative`\n * so the consumer can anchor their own overlays to Main.\n */\nexport const chatCardThreeColumnLayoutMainVariants = cva([\n '[grid-area:main] relative min-w-0 min-h-0 h-full',\n]);\n\n/**\n * Column 3, or floating over Main. Floating shares Main's grid area instead of being\n * `absolute`, so it is sized by the same track Main is.\n *\n * - pinned: the right edge of Main, at the same width the column would have, inset 12px\n * - sheet: on a narrow layout, a bottom sheet at a fixed 85% height, so the pane does not\n * change height as its content changes (the content scrolls instead)\n *\n * `z-20` keeps a floating Details above Main's own overlays. `min-w-0` + `max-w-full` stop\n * the fixed width from widening the `1fr` track past the card.\n */\nexport const chatCardThreeColumnLayoutDetailsVariants = cva([\n 'min-h-0 min-w-0 max-w-full',\n 'data-[floating=false]:[grid-area:details] data-[floating=false]:h-full',\n 'data-[floating=true]:z-20 data-[floating=true]:[grid-area:main]',\n 'data-[floating=true]:data-[sheet=false]:w-[358px] data-[floating=true]:data-[sheet=false]:h-full data-[floating=true]:data-[sheet=false]:justify-self-end data-[floating=true]:data-[sheet=false]:self-stretch data-[floating=true]:data-[sheet=false]:p-[12px]',\n 'data-[sheet=true]:w-full data-[sheet=true]:h-[85%] data-[sheet=true]:justify-self-start data-[sheet=true]:self-end',\n]);\n\n/**\n * An overlay over everything but the List column, inset 12px, for a view that takes over the\n * card (all reviews, a filter form) while Main and Details stay mounted underneath.\n *\n * It spans columns in row 1 instead of being `absolute`, so it follows the grid template:\n * from column 2 to the last one when List is a column (`lg`, `xl`), all of them otherwise.\n * It never adds a track, so mounting it doesn't move Main. `z-30` keeps it above floating\n * Details (`z-20`).\n */\nexport const chatCardThreeColumnLayoutPanelVariants = cva([\n 'relative z-30 min-w-0 min-h-0 h-full p-[12px] row-1',\n 'col-span-full',\n 'data-[size=lg]:col-[2/-1] data-[size=xl]:col-[2/-1]',\n]);\n\n/**\n * Width recipe for the `ChatCard` that wraps the layout.\n *\n * A grid of `1fr` tracks has no intrinsic width, so inside a shrink-to-fit message the card\n * would collapse to nothing. It takes the whole chat window instead, minus the message\n * gutter on both sides, up to 1432px (four 358px columns). The layout then decides which\n * panes fit in whatever width that gives it. `ChatContainer` sets both variables.\n *\n * One cap, not a ladder of viewport steps: a step like `lg:min-w-[1074px]` held the card\n * narrower than the chat window between breakpoints, and Details floated for no reason.\n *\n * Gated on `data-state=open`, which `ChatCard`'s `Collapsible` puts on the card element\n * itself: a collapsed card is only a header, and holding it at full width would leave a\n * wide empty bar in the thread. A non-collapsible card is always `open`.\n */\nexport const chatCardThreeColumnLayoutCardVariants = cva([\n 'data-[state=open]:w-(--message-list-content-width) data-[state=open]:mx-0',\n // `100%` fallback, like every other read of the variable, for a card outside `ChatContainer`\n 'data-[state=open]:min-w-[min(1432px,calc(var(--chat-window-width,100%)-var(--spacing-message)*2))]',\n]);\n","import { Slot } from '@radix-ui/react-slot';\nimport { createContext, forwardRef, useCallback, useContext, useMemo } from 'react';\nimport type { ComponentProps, ForwardedRef, ReactNode } from 'react';\n\nimport { cn, useElementMeasure } from '@swisper.ai/web-core';\n\nimport { resolveLayout } from './chat-card-three-column-layout.sizing';\nimport type { ChatCardThreeColumnLayoutSize } from './chat-card-three-column-layout.sizing';\nimport {\n DEFAULT_DETAILS_PLACEMENT,\n chatCardThreeColumnLayoutDetailsVariants,\n chatCardThreeColumnLayoutListVariants,\n chatCardThreeColumnLayoutMainVariants,\n chatCardThreeColumnLayoutPanelVariants,\n chatCardThreeColumnLayoutVariants,\n} from './chat-card-three-column-layout.variants';\nimport type { ChatCardThreeColumnLayoutDetailsPlacement } from './chat-card-three-column-layout.variants';\n\ninterface ChatCardThreeColumnLayoutContextValue {\n size: ChatCardThreeColumnLayoutSize;\n isDetailsFloating: boolean;\n isDetailsSheet: boolean;\n}\n\nconst ChatCardThreeColumnLayoutContext = createContext<ChatCardThreeColumnLayoutContextValue>(\n null!,\n);\n\nfunction useChatCardThreeColumnLayoutContext(part: string) {\n const context = useContext(ChatCardThreeColumnLayoutContext);\n\n if (!context) {\n throw new Error(\n `[web-chat-ui] \"${part}\" must be used within a ChatCardThreeColumnLayout. ` +\n 'It reads its placement from the layout, so render ' +\n 'it as a child of the ChatCardThreeColumnLayout element, not as a sibling of it.',\n );\n }\n\n return context;\n}\n\n/**\n * The Details pane's content, or a function of whether the pane is currently floating.\n *\n * The function form exists because a floating pane can need different content, not just\n * different styling: a surface with a shadow over Main, a flat one in the column. CSS alone\n * cannot swap the component tree.\n */\nexport type ChatCardThreeColumnLayoutPaneChildren =\n ReactNode | ((isFloating: boolean) => ReactNode);\n\nfunction renderPane(children: ChatCardThreeColumnLayoutPaneChildren, isFloating: boolean) {\n return typeof children === 'function' ? children(isFloating) : children;\n}\n\nexport interface ChatCardThreeColumnLayoutProps extends ComponentProps<'div'> {\n children: ReactNode;\n /**\n * Whether Details may take its own column. See `ChatCardThreeColumnLayoutDetailsPlacement`.\n * It is on the root, not on Details, because the root's grid template has to change\n * with it.\n */\n detailsPlacement?: ChatCardThreeColumnLayoutDetailsPlacement;\n asChild?: boolean;\n}\n\n/** Hands one element to the measuring ref and the consumer's forwarded ref alike. */\nfunction useMergedRef<T>(first: (node: T | null) => void, second: ForwardedRef<T>) {\n return useCallback(\n (node: T | null) => {\n first(node);\n\n if (typeof second === 'function') {\n second(node);\n } else if (second) {\n second.current = node;\n }\n },\n [first, second],\n );\n}\n\n/**\n * A three-pane card body: List (fixed column), Main (flexible), Details (floating or a\n * right column).\n *\n * Which panes fit is decided by the layout's **own measured width**, not by viewport\n * breakpoints. The card is sized by the chat window, and a sidebar, a split view or the\n * Storybook panel all make the viewport claim room the card doesn't have (or the\n * reverse). The root measures itself, resolves the panes once (`resolveLayout`), and\n * publishes the result twice: as data attributes for the CSS, and through context for\n * Details' render prop. Both read the same numbers, so the content the render prop picks\n * always matches where the pane is drawn.\n *\n * Height is not set here, because it belongs to the content (a map needs a fixed height, a\n * table might not), so pass it in `className`.\n */\nexport const ChatCardThreeColumnLayout = forwardRef<HTMLDivElement, ChatCardThreeColumnLayoutProps>(\n function ChatCardThreeColumnLayout(\n { children, className, detailsPlacement = DEFAULT_DETAILS_PLACEMENT, asChild = false, ...rest },\n ref,\n ) {\n const { ref: measureRef, width } = useElementMeasure<HTMLDivElement>();\n const mergedRef = useMergedRef(measureRef, ref);\n\n const { size, isDetailsFloating, isDetailsSheet } = resolveLayout(width, detailsPlacement);\n\n const contextValue = useMemo(\n () => ({ size, isDetailsFloating, isDetailsSheet }),\n [size, isDetailsFloating, isDetailsSheet],\n );\n\n const Component = asChild ? Slot : 'div';\n\n return (\n <ChatCardThreeColumnLayoutContext.Provider value={contextValue}>\n <Component\n ref={mergedRef}\n data-testid=\"chat-card-three-column-layout\"\n data-slot=\"chat-card-three-column-layout\"\n data-details-placement={detailsPlacement}\n data-size={size}\n data-details-floating={isDetailsFloating}\n className={cn(chatCardThreeColumnLayoutVariants(), className)}\n {...rest}\n >\n {children}\n </Component>\n </ChatCardThreeColumnLayoutContext.Provider>\n );\n },\n);\n\nChatCardThreeColumnLayout.displayName = 'ChatCardThreeColumnLayout';\n\nexport interface ChatCardThreeColumnLayoutListProps extends ComponentProps<'aside'> {\n children: ReactNode;\n /**\n * Hides the pane while the layout is too narrow for the List column (`sm` and `md`). It\n * stays mounted, so its state is still there when the column comes back.\n */\n hideOnMobile?: boolean;\n asChild?: boolean;\n}\n\n/**\n * Column 1 when the layout has room for it beside a usable Main (`lg` and `xl`). Below that\n * the layout does not place it: pass `hideOnMobile` to hide it there.\n *\n * `data-size` is set too, for styling the pane by the layout's tier.\n */\nexport const ChatCardThreeColumnLayoutList = forwardRef<\n HTMLDivElement,\n ChatCardThreeColumnLayoutListProps\n>(function ChatCardThreeColumnLayoutList(\n { children, className, hideOnMobile = false, asChild = false, ...rest },\n ref,\n) {\n const { size } = useChatCardThreeColumnLayoutContext('ChatCardThreeColumnLayoutList');\n\n const Component = asChild ? Slot : 'aside';\n\n return (\n <Component\n ref={ref}\n data-testid=\"chat-card-three-column-layout-list\"\n data-slot=\"chat-card-three-column-layout-list\"\n data-size={size}\n className={cn(chatCardThreeColumnLayoutListVariants({ hideOnMobile }), className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardThreeColumnLayoutList.displayName = 'ChatCardThreeColumnLayoutList';\n\nexport interface ChatCardThreeColumnLayoutMainProps extends ComponentProps<'main'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/**\n * Column 2, the flexible track. It never floats, so it takes plain children. It still\n * requires the layout, because outside the grid its `[grid-area:main]` means nothing and\n * the pane collapses without any error.\n */\nexport const ChatCardThreeColumnLayoutMain = forwardRef<\n HTMLDivElement,\n ChatCardThreeColumnLayoutMainProps\n>(function ChatCardThreeColumnLayoutMain({ children, className, asChild = false, ...rest }, ref) {\n useChatCardThreeColumnLayoutContext('ChatCardThreeColumnLayoutMain');\n\n const Component = asChild ? Slot : 'main';\n\n return (\n <Component\n ref={ref}\n data-testid=\"chat-card-three-column-layout-main\"\n data-slot=\"chat-card-three-column-layout-main\"\n className={cn(chatCardThreeColumnLayoutMainVariants(), className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardThreeColumnLayoutMain.displayName = 'ChatCardThreeColumnLayoutMain';\n\nexport interface ChatCardThreeColumnLayoutDetailsProps extends Omit<\n ComponentProps<'aside'>,\n 'children'\n> {\n children: ChatCardThreeColumnLayoutPaneChildren;\n asChild?: boolean;\n}\n\n/**\n * Column 3. Mount it only while there is something to show: its presence is what adds the\n * third grid track, so rendering it empty would reserve a blank column.\n *\n * It takes a column when the layout is wide enough and `detailsPlacement` allows it, and\n * floats over Main otherwise: pinned to Main's right edge, or a bottom sheet on a narrow\n * layout (`data-sheet`). `isFloating` in the render prop reflects all of that.\n */\nexport const ChatCardThreeColumnLayoutDetails = forwardRef<\n HTMLDivElement,\n ChatCardThreeColumnLayoutDetailsProps\n>(function ChatCardThreeColumnLayoutDetails(\n { children, className, asChild = false, ...rest },\n ref,\n) {\n const { isDetailsFloating, isDetailsSheet } = useChatCardThreeColumnLayoutContext(\n 'ChatCardThreeColumnLayoutDetails',\n );\n\n const Component = asChild ? Slot : 'aside';\n\n return (\n <Component\n ref={ref}\n data-testid=\"chat-card-three-column-layout-details\"\n data-slot=\"chat-card-three-column-layout-details\"\n data-floating={isDetailsFloating}\n data-sheet={isDetailsSheet}\n className={cn(chatCardThreeColumnLayoutDetailsVariants(), className)}\n {...rest}\n >\n {renderPane(children, isDetailsFloating)}\n </Component>\n );\n});\n\nChatCardThreeColumnLayoutDetails.displayName = 'ChatCardThreeColumnLayoutDetails';\n\nexport interface ChatCardThreeColumnLayoutPanelProps extends ComponentProps<'section'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/**\n * An overlay covering everything but the List column (the whole layout when there is no\n * List column), inset 12px. Mount it only while it is open. Main and Details stay mounted\n * under it, so a map keeps its viewport and the open Details item survives closing the Panel.\n *\n * The pane is transparent: draw the surface (background, radius, shadow) in its content,\n * as for Details.\n */\nexport const ChatCardThreeColumnLayoutPanel = forwardRef<\n HTMLElement,\n ChatCardThreeColumnLayoutPanelProps\n>(function ChatCardThreeColumnLayoutPanel({ children, className, asChild = false, ...rest }, ref) {\n const { size } = useChatCardThreeColumnLayoutContext('ChatCardThreeColumnLayoutPanel');\n const Component = asChild ? Slot : 'section';\n\n return (\n <Component\n ref={ref}\n data-testid=\"chat-card-three-column-layout-panel\"\n data-slot=\"chat-card-three-column-layout-panel\"\n data-size={size}\n className={cn(chatCardThreeColumnLayoutPanelVariants(), className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardThreeColumnLayoutPanel.displayName = 'ChatCardThreeColumnLayoutPanel';\n","import { cva } from 'class-variance-authority';\n\n/*\n * The layout switches on a container query against its own width, not on viewport\n * breakpoints: the card is sized by the chat window, and a sidebar or split view makes the\n * viewport claim room the card doesn't have. `336px` and `744px` are `ASIDE_WIDTH` and\n * `TWO_COLUMN_MIN_WIDTH` from `chat-card-two-column-layout.sizing.ts`, written out because\n * Tailwind cannot read a constant. Change both together.\n *\n * The container is named so a two-column layout nested in another container still queries\n * its own root, not the nearest ancestor.\n *\n * Class strings are written out in full because Tailwind finds classes by scanning source;\n * a class assembled from a constant is never generated.\n */\n\n/**\n * Root: the query container, nothing else. An element cannot match a container query\n * against its own width, so the grid lives one level down, in `…GridVariants`.\n */\nexport const chatCardTwoColumnLayoutVariants = cva(['@container/chat-card-two-column-layout']);\n\n/**\n * The grid, rendered by the root around its children.\n *\n * Stacked, the rows are `auto 1fr`, so with a height on the root Main takes whatever Aside\n * leaves. Side by side there is one `1fr` row; the stacked template would otherwise leave an\n * empty `1fr` second row taking the height.\n */\nexport const chatCardTwoColumnLayoutGridVariants = cva([\n 'grid h-full gap-16',\n 'grid-cols-[minmax(0,1fr)] grid-rows-[auto_1fr]',\n '@[744px]/chat-card-two-column-layout:grid-cols-[336px_minmax(0,1fr)] @[744px]/chat-card-two-column-layout:grid-rows-[minmax(0,1fr)]',\n]);\n\n/**\n * Row 1 when stacked, column 1 when side by side. In the column, `min-h-0` + `overflow-hidden`\n * keep a long list inside the row. Without them the grid item grows to its content and the\n * card gets taller instead of scrolling.\n */\nexport const chatCardTwoColumnLayoutAsideVariants = cva([\n 'min-w-0 min-h-0',\n '@[744px]/chat-card-two-column-layout:h-full @[744px]/chat-card-two-column-layout:overflow-hidden',\n]);\n\n/**\n * The flexible track. `min-w-0` because a grid item's minimum width is its content by\n * default: a map or a wide table would push the track past the card. `relative` so the\n * consumer can anchor their own overlays to Main.\n */\nexport const chatCardTwoColumnLayoutMainVariants = cva(['relative min-w-0 min-h-0 h-full']);\n\n/**\n * Width recipe for the `ChatCard` that wraps the layout. The same recipe, for the same\n * reason, as `chatCardThreeColumnLayoutCardVariants`: a grid of `1fr` tracks has no intrinsic\n * width, so inside a shrink-to-fit message the card would collapse to nothing. It takes the\n * whole chat window instead, and the layout decides whether two columns fit.\n *\n * Gated on `data-state=open` so a collapsed card goes back to header width.\n */\nexport const chatCardTwoColumnLayoutCardVariants = cva([\n 'data-[state=open]:w-full data-[state=open]:mx-0',\n // `100%` fallback, like every other read of the variable, for a card outside `ChatContainer`\n 'data-[state=open]:min-w-[min(1130px,calc(var(--chat-window-width,100%)-var(--spacing-message)*2))]',\n]);\n","import { Slot } from '@radix-ui/react-slot';\nimport { createContext, forwardRef, useContext } from 'react';\nimport type { ComponentProps, ReactNode } from 'react';\n\nimport { cn } from '@swisper.ai/web-core';\n\nimport {\n chatCardTwoColumnLayoutAsideVariants,\n chatCardTwoColumnLayoutGridVariants,\n chatCardTwoColumnLayoutMainVariants,\n chatCardTwoColumnLayoutVariants,\n} from './chat-card-two-column-layout.variants';\n\n/**\n * Carries nothing but \"inside the layout\". The panes' container queries only match inside\n * the root's named container, so a pane outside it would stay stacked forever without any\n * error. The check turns that into one.\n */\nconst ChatCardTwoColumnLayoutContext = createContext(false);\n\nfunction useChatCardTwoColumnLayoutContext(part: string) {\n if (!useContext(ChatCardTwoColumnLayoutContext)) {\n throw new Error(\n `[web-chat-ui] \"${part}\" must be used within a ChatCardTwoColumnLayout. ` +\n 'Its columns come from the layout’s container query, so render it as a child of ' +\n 'the ChatCardTwoColumnLayout element, not as a sibling of it.',\n );\n }\n}\n\nexport interface ChatCardTwoColumnLayoutProps extends ComponentProps<'div'> {\n children: ReactNode;\n /**\n * Classes for the grid the root renders around its children, merged after its defaults, e.g.\n * `gap-8` for a tighter gutter. Keep the column and row templates: the panes rely on them.\n */\n gridClassName?: string;\n asChild?: boolean;\n}\n\n/**\n * A two-pane card body: Aside (a 336px column) beside Main (flexible), stacked as Aside over\n * Main when the layout is narrower than 744px.\n *\n * The switch is a container query on the layout's **own width**, not a viewport breakpoint,\n * because the card is sized by the chat window, not the viewport. Nothing floats, so unlike\n * the three-column layout there is no measuring and no render prop.\n *\n * The root is the query container and renders the grid inside itself: an element cannot\n * query its own width. `className` goes on the root, so a height set there reaches the grid.\n * Height is not set here, because it belongs to the content, so pass it in `className`.\n * `gridClassName` reaches the grid itself.\n */\nexport const ChatCardTwoColumnLayout = forwardRef<HTMLDivElement, ChatCardTwoColumnLayoutProps>(\n function ChatCardTwoColumnLayout(\n { children, className, gridClassName, asChild = false, ...rest },\n ref,\n ) {\n const Component = asChild ? Slot : 'div';\n\n return (\n <ChatCardTwoColumnLayoutContext.Provider value>\n <Component\n ref={ref}\n data-testid=\"chat-card-two-column-layout\"\n data-slot=\"chat-card-two-column-layout\"\n className={cn(chatCardTwoColumnLayoutVariants(), className)}\n {...rest}\n >\n <div\n data-testid=\"chat-card-two-column-layout-grid\"\n data-slot=\"chat-card-two-column-layout-grid\"\n className={cn(chatCardTwoColumnLayoutGridVariants(), gridClassName)}\n >\n {children}\n </div>\n </Component>\n </ChatCardTwoColumnLayoutContext.Provider>\n );\n },\n);\n\nChatCardTwoColumnLayout.displayName = 'ChatCardTwoColumnLayout';\n\nexport interface ChatCardTwoColumnLayoutAsideProps extends ComponentProps<'aside'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** Column 1 (336px) when the layout is at least 744px wide; the first row below that. */\nexport const ChatCardTwoColumnLayoutAside = forwardRef<\n HTMLElement,\n ChatCardTwoColumnLayoutAsideProps\n>(function ChatCardTwoColumnLayoutAside({ children, className, asChild = false, ...rest }, ref) {\n useChatCardTwoColumnLayoutContext('ChatCardTwoColumnLayoutAside');\n\n const Component = asChild ? Slot : 'aside';\n\n return (\n <Component\n ref={ref}\n data-testid=\"chat-card-two-column-layout-aside\"\n data-slot=\"chat-card-two-column-layout-aside\"\n className={cn(chatCardTwoColumnLayoutAsideVariants(), className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardTwoColumnLayoutAside.displayName = 'ChatCardTwoColumnLayoutAside';\n\nexport interface ChatCardTwoColumnLayoutMainProps extends ComponentProps<'main'> {\n children: ReactNode;\n asChild?: boolean;\n}\n\n/** The flexible track: column 2 side by side, the second row (taking the rest) stacked. */\nexport const ChatCardTwoColumnLayoutMain = forwardRef<\n HTMLElement,\n ChatCardTwoColumnLayoutMainProps\n>(function ChatCardTwoColumnLayoutMain({ children, className, asChild = false, ...rest }, ref) {\n useChatCardTwoColumnLayoutContext('ChatCardTwoColumnLayoutMain');\n\n const Component = asChild ? Slot : 'main';\n\n return (\n <Component\n ref={ref}\n data-testid=\"chat-card-two-column-layout-main\"\n data-slot=\"chat-card-two-column-layout-main\"\n className={cn(chatCardTwoColumnLayoutMainVariants(), className)}\n {...rest}\n >\n {children}\n </Component>\n );\n});\n\nChatCardTwoColumnLayoutMain.displayName = 'ChatCardTwoColumnLayoutMain';\n","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 />\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]/chat-card:max-h-[90vh]',\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 { 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 <ul\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 </ul>\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 { SvgIconProps } from '@mui/material/SvgIcon';\nimport { type FunctionComponent } from 'react';\n\nimport { PdfIcon, PptIcon, CodeIcon, DocIcon, XlsIcon, DraftIcon } 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 OrderChip,\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 in an `OrderChip`, 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 <OrderChip>\n <Typography variant=\"caption-md\" fontWeight=\"semibold\" className=\"text-inherit\" asChild>\n <span>{index + 1}</span>\n </Typography>\n </OrderChip>\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 { 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', 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAMyC,KAAwB,GAUxBC,KAA4BC,EAA8C,IAAK;AASrF,SAAgBC,KAA+B;CAC7C,IAAMC,IAAUC,EAAWJ,EAAyB;CAEpD,IAAI,CA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a;EAC1B,CAAC,GAED,EAAc,UAAUzrB;CAE5B,GAAG,CAACA,CAAM,CAAC;AACb;;;AC9BA,SAAgB6rB,KAAmB;CACjC,IAAM,EAAE,cAAWrsB,EAAe;CAClC,OAAOQ;AACT;;;ACHA,SAAgB8rB,KAAsB;CACpC,IAAM,EAAE,iBAActsB,EAAe;CACrC,OAAOS;AACT;;;ACMA,SAAgB8rB,KAA4C;CAC1D,IAAM,EAAE,wBAAqBvsB,EAAe;CAc5C,OAAO;EACL,iBAbsB/U,GAAa,MAC5BsV,EAAiB,SAAS,IAAIC,CAAM,KAAK,IAC/C,CAAC,CAWF;EACA,cAVmBvV,GAAa,MAAmB;GACnD,EAAiB,SAAS,IAAIuV,CAAM;EACtC,GAAG,CAAC,CAQF;EACA,gBAPqBvV,GAAa,MAAmB;GACrD,EAAiB,SAAS,OAAOuV,CAAM;EACzC,GAAG,CAAC,CAKF;CACF;AACF;;;AC7BA,SAAgBgsB,KAA2B;CACzC,IAAM,EAAE,sBAAmB,yBAAsB,8BAA2BxsB,EAAe;CAE3F,OAAO;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","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","OrderChip","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","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/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 />\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 { SvgIconProps } from '@mui/material/SvgIcon';\nimport { type FunctionComponent } from 'react';\n\nimport { PdfIcon, PptIcon, CodeIcon, DocIcon, XlsIcon, DraftIcon } 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 OrderChip,\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 in an `OrderChip`, 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 <OrderChip>\n <Typography variant=\"caption-md\" fontWeight=\"semibold\" className=\"text-inherit\" asChild>\n <span>{index + 1}</span>\n </Typography>\n </OrderChip>\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 { 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', 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,c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