@langchain/macaw-components 1.7.9 → 1.7.11
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/dist/catalog.json +772 -757
- package/dist/components/ChatComposer/ChatComposer.d.ts +10 -1
- package/dist/components/ChatComposer/ChatComposer.js +16 -9
- package/dist/components/ChatComposer/ChatComposer.js.map +1 -1
- package/dist/components/ChatComposer/ChatComposerContext.d.ts +1 -1
- package/dist/components/ChatComposer/ChatComposerContext.js.map +1 -1
- package/dist/components/ChatComposer/ChatComposerRichInput.js +13 -2
- package/dist/components/ChatComposer/ChatComposerRichInput.js.map +1 -1
- package/dist/components/ChatConversation/ChatConversation.d.ts +16 -3
- package/dist/components/ChatConversation/ChatConversation.js +209 -41
- package/dist/components/ChatConversation/ChatConversation.js.map +1 -1
- package/dist/components/ChatMessage/ChatMessage.d.ts +7 -4
- package/dist/components/ChatMessage/ChatMessage.js +21 -7
- package/dist/components/ChatMessage/ChatMessage.js.map +1 -1
- package/dist/components/ChatMessage/ChatMessage.types.d.ts +2 -0
- package/dist/components/ChatPlan/ChatPlan.d.ts +27 -0
- package/dist/components/ChatPlan/ChatPlan.js +156 -0
- package/dist/components/ChatPlan/ChatPlan.js.map +1 -0
- package/dist/components/ChatPlan/index.d.ts +2 -0
- package/dist/components/ChatPlan/index.js +2 -0
- package/dist/components/ChatRichContent/ChatRichContent.js +79 -28
- package/dist/components/ChatRichContent/ChatRichContent.js.map +1 -1
- package/dist/components/ChatRichContent/ChatRichContent.types.d.ts +18 -0
- package/dist/components/ChatRichContent/index.d.ts +1 -1
- package/dist/components/ChatState/ChatState.d.ts +12 -1
- package/dist/components/ChatState/ChatState.js +5 -4
- package/dist/components/ChatState/ChatState.js.map +1 -1
- package/dist/components/ChatState/ChatStateTimer.d.ts +3 -1
- package/dist/components/ChatState/ChatStateTimer.js +24 -11
- package/dist/components/ChatState/ChatStateTimer.js.map +1 -1
- package/dist/components/ChatState/formatChatDuration.d.ts +16 -0
- package/dist/components/ChatState/formatChatDuration.js +19 -0
- package/dist/components/ChatState/formatChatDuration.js.map +1 -0
- package/dist/components/ChatState/index.d.ts +2 -0
- package/dist/components/ChatState/index.js +2 -1
- package/dist/components/ChatToolCall/ChatToolCall.d.ts +7 -1
- package/dist/components/ChatToolCall/ChatToolCall.js +3 -1
- package/dist/components/ChatToolCall/ChatToolCall.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallAccordion.d.ts +3 -1
- package/dist/components/ChatToolCall/ChatToolCallAccordion.js +33 -26
- package/dist/components/ChatToolCall/ChatToolCallAccordion.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallGroup.d.ts +20 -2
- package/dist/components/ChatToolCall/ChatToolCallGroup.js +8 -5
- package/dist/components/ChatToolCall/ChatToolCallGroup.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallReasoning.d.ts +10 -2
- package/dist/components/ChatToolCall/ChatToolCallReasoning.js +13 -5
- package/dist/components/ChatToolCall/ChatToolCallReasoning.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallStatusRow.d.ts +3 -1
- package/dist/components/ChatToolCall/ChatToolCallStatusRow.js +29 -18
- package/dist/components/ChatToolCall/ChatToolCallStatusRow.js.map +1 -1
- package/dist/utilities.css +1 -1
- package/docs/CHAT.md +50 -0
- package/docs/DESIGN.md +10 -6
- package/package.json +6 -2
|
@@ -2,7 +2,11 @@ import type { ComponentPropsWithRef, ReactNode } from 'react';
|
|
|
2
2
|
import type { IconButtonProps } from '../IconButton/index.js';
|
|
3
3
|
export type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';
|
|
4
4
|
export type ChatComposerProps = ComponentPropsWithRef<'form'> & {
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Supplementary content attached above the editor, inside the composer form.
|
|
7
|
+
* Several items, such as a plan and a question, stack with dividers; put the
|
|
8
|
+
* one the input answers last, next to it.
|
|
9
|
+
*/
|
|
6
10
|
drawer?: ReactNode;
|
|
7
11
|
/**
|
|
8
12
|
* Drawer surface color. Color alone doesn't convey severity, so the drawer
|
|
@@ -23,6 +27,11 @@ export type ChatComposerProps = ComponentPropsWithRef<'form'> & {
|
|
|
23
27
|
} | {
|
|
24
28
|
action: 'stop';
|
|
25
29
|
onStop: () => void;
|
|
30
|
+
}
|
|
31
|
+
/** A stop request is pending; Stop shows progress and sending stays blocked. */
|
|
32
|
+
| {
|
|
33
|
+
action: 'stopping';
|
|
34
|
+
onStop?: never;
|
|
26
35
|
});
|
|
27
36
|
export declare function ChatComposer({ children, drawer, drawerIntent, className, ref, disabled, submitDisabled, action, onStop, onSubmit, onFilesSelected, onDragOver, onDragLeave, onDropCapture, onPasteCapture, noValidate, ...props }: ChatComposerProps): import("react").JSX.Element;
|
|
28
37
|
export interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {
|
|
@@ -8,14 +8,15 @@ import { jsx, jsxs } from "react/jsx-runtime";
|
|
|
8
8
|
import { StopIcon } from "@phosphor-icons/react/dist/ssr/Stop";
|
|
9
9
|
//#region packages/components/src/components/ChatComposer/ChatComposer.tsx
|
|
10
10
|
var DRAWER_INTENT_CLASSES = {
|
|
11
|
-
neutral: "border-subtle bg-surface-level-2",
|
|
12
|
-
info: "border-brand-subtle bg-brand-subtle",
|
|
13
|
-
warning: "border-warning bg-warning",
|
|
14
|
-
error: "border-error bg-error"
|
|
11
|
+
neutral: "border-subtle divide-subtle bg-surface-level-2",
|
|
12
|
+
info: "border-brand-subtle divide-brand-subtle bg-brand-subtle",
|
|
13
|
+
warning: "border-warning divide-warning bg-warning",
|
|
14
|
+
error: "border-error divide-error bg-error"
|
|
15
15
|
};
|
|
16
16
|
function isAttachmentTargetBlocked(target) {
|
|
17
17
|
return target instanceof Element && target.closest(":disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]") !== null;
|
|
18
18
|
}
|
|
19
|
+
var COMPOSER_CLICK_TARGET_SELECTOR = "a[href], button, input, select, textarea, label, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"]), [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"option\"], [role=\"combobox\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"switch\"], [role=\"tab\"]";
|
|
19
20
|
function reportFieldsetValidity(fieldset) {
|
|
20
21
|
for (const element of fieldset?.elements ?? []) if ((element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement) && !element.reportValidity()) return false;
|
|
21
22
|
return true;
|
|
@@ -87,11 +88,15 @@ function ChatComposer({ children, drawer, drawerIntent = "neutral", className, r
|
|
|
87
88
|
},
|
|
88
89
|
children: [hasDrawer && /* @__PURE__ */ jsx("fieldset", {
|
|
89
90
|
disabled,
|
|
90
|
-
className: cn("mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none", DRAWER_INTENT_CLASSES[drawerIntent], disabled && "border-disabled"),
|
|
91
|
+
className: cn("mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 divide-y overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none", DRAWER_INTENT_CLASSES[drawerIntent], disabled && "border-disabled divide-disabled"),
|
|
91
92
|
children: drawer
|
|
92
93
|
}), /* @__PURE__ */ jsx("fieldset", {
|
|
93
94
|
ref: fieldsetRef,
|
|
94
95
|
disabled: disabled && action !== "stop",
|
|
96
|
+
onClick: (event) => {
|
|
97
|
+
if (event.defaultPrevented || !(event.target instanceof Element) || event.target.closest(COMPOSER_CLICK_TARGET_SELECTOR) || window.getSelection()?.isCollapsed === false) return;
|
|
98
|
+
inputFocusRef.current?.();
|
|
99
|
+
},
|
|
95
100
|
className: cn("relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-lg border border-subtle bg-elevated p-space-2 transition-[border-color,box-shadow,background-color] duration-normal motion-reduce:transition-none", "has-[:is(textarea,[contenteditable=true]):focus]:border-focus has-[:is(textarea,[contenteditable=true]):focus]:shadow-[0_0_0_1px_var(--border-focus)]", disabled && "border-disabled bg-input-disabled", isDropTarget && !disabled && "border-focus bg-surface-level-2 shadow-[0_0_0_1px_var(--border-focus)]"),
|
|
96
101
|
children
|
|
97
102
|
})]
|
|
@@ -117,22 +122,24 @@ function ChatComposerToolbar({ children, modelSelector, actions = /* @__PURE__ *
|
|
|
117
122
|
var ACTION_LABELS = {
|
|
118
123
|
send: "Send message",
|
|
119
124
|
sending: "Sending message",
|
|
120
|
-
stop: "Stop response"
|
|
125
|
+
stop: "Stop response",
|
|
126
|
+
stopping: "Stopping response"
|
|
121
127
|
};
|
|
122
128
|
function ChatComposerAction({ disabled, label, ...props }) {
|
|
123
129
|
const composer = useChatComposerContext();
|
|
124
130
|
const isStop = composer.action === "stop";
|
|
131
|
+
const isStopping = composer.action === "stopping";
|
|
125
132
|
return /* @__PURE__ */ jsx(IconButton, {
|
|
126
133
|
size: "sm",
|
|
127
134
|
round: true,
|
|
128
135
|
color: "primary",
|
|
129
136
|
iconWeight: "regular",
|
|
130
137
|
...props,
|
|
131
|
-
type: isStop ? "button" : "submit",
|
|
132
|
-
icon: isStop ? StopIcon : ArrowUpIcon,
|
|
138
|
+
type: isStop || isStopping ? "button" : "submit",
|
|
139
|
+
icon: isStop || isStopping ? StopIcon : ArrowUpIcon,
|
|
133
140
|
label: label ?? ACTION_LABELS[composer.action],
|
|
134
141
|
disabled: disabled || !isStop && !composer.canSubmit,
|
|
135
|
-
loading: composer.action === "sending",
|
|
142
|
+
loading: composer.action === "sending" || isStopping,
|
|
136
143
|
onClick: isStop ? composer.onStop : void 0
|
|
137
144
|
});
|
|
138
145
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatComposer.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposer.tsx"],"sourcesContent":["import type { ComponentPropsWithRef, ReactNode } from 'react';\nimport { useRef, useState } from 'react';\n\nimport { ArrowUpIcon } from '@phosphor-icons/react/dist/ssr/ArrowUp';\nimport { StopIcon } from '@phosphor-icons/react/dist/ssr/Stop';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { IconButton } from '../IconButton';\nimport type { IconButtonProps } from '../IconButton';\nimport {\n ChatComposerContext,\n type ChatComposerContextValue,\n useChatComposerContext,\n} from './ChatComposerContext';\n\nexport type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';\n\nconst DRAWER_INTENT_CLASSES: Record<ChatComposerDrawerIntent, string> = {\n neutral: 'border-subtle bg-surface-level-2',\n info: 'border-brand-subtle bg-brand-subtle',\n warning: 'border-warning bg-warning',\n error: 'border-error bg-error',\n};\n\nexport type ChatComposerProps = ComponentPropsWithRef<'form'> & {\n /** Supplementary content attached above the editor, inside the composer form. */\n drawer?: ReactNode;\n /**\n * Drawer surface color. Color alone doesn't convey severity, so the drawer\n * content should also say it in text or with an icon.\n */\n drawerIntent?: ChatComposerDrawerIntent;\n /**\n * Blocks writing and sending. Stop stays available while `action` is\n * `stop`, so host controls inside the composer must take `disabled`\n * themselves to stay disabled during a response.\n */\n disabled?: boolean;\n submitDisabled?: boolean;\n onFilesSelected?: (files: File[]) => void;\n} & (\n | { action?: 'send' | 'sending'; onStop?: never }\n | { action: 'stop'; onStop: () => void }\n );\n\n// A disabled or read-only part of the composer, such as a read-only message\n// input, does not accept input, so files dropped or pasted onto it are not\n// attached either.\nfunction isAttachmentTargetBlocked(target: EventTarget) {\n return (\n target instanceof Element &&\n target.closest(\n ':disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]'\n ) !== null\n );\n}\n\n// A fieldset is barred from constraint validation, so its own\n// reportValidity() never inspects the controls inside it.\nfunction reportFieldsetValidity(fieldset: HTMLFieldSetElement | null) {\n for (const element of fieldset?.elements ?? []) {\n if (\n (element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement) &&\n !element.reportValidity()\n )\n return false;\n }\n return true;\n}\n\nexport function ChatComposer({\n children,\n drawer,\n drawerIntent = 'neutral',\n className,\n ref,\n disabled = false,\n submitDisabled = false,\n action = 'send',\n onStop,\n onSubmit,\n onFilesSelected,\n onDragOver,\n onDragLeave,\n onDropCapture,\n onPasteCapture,\n noValidate,\n ...props\n}: ChatComposerProps) {\n const formRef = useRef<HTMLFormElement>(null);\n const [isDropTarget, setIsDropTarget] = useState(false);\n const canSubmit =\n !disabled && !submitDisabled && action === 'send' && !!onSubmit;\n const hasDrawer = Boolean(drawer);\n const fieldsetRef = useRef<HTMLFieldSetElement>(null);\n const inputFocusRef = useRef<(() => boolean) | null>(null);\n // Inert drawer fields cannot be focused to report errors, so the drawer's\n // host validates them; fields outside the drawer keep native checks.\n const validatesFieldsetOnly = noValidate === undefined && hasDrawer;\n\n return (\n <ChatComposerContext.Provider\n value={{\n disabled,\n canSubmit,\n action,\n onStop,\n onFilesSelected,\n inputFocusRef,\n submit: onSubmit\n ? () => {\n if (canSubmit) formRef.current?.requestSubmit();\n }\n : undefined,\n }}\n >\n <form\n {...props}\n ref={mergeRefs([formRef, ref])}\n noValidate={noValidate ?? hasDrawer}\n className={cn('isolate w-full min-w-0 @container/composer', className)}\n onSubmit={(event) => {\n event.preventDefault();\n if (!canSubmit) return;\n if (\n validatesFieldsetOnly &&\n !reportFieldsetValidity(fieldsetRef.current)\n )\n return;\n onSubmit?.(event);\n }}\n onDragOver={(event) => {\n onDragOver?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n if (!event.dataTransfer.types.includes('Files')) return;\n event.preventDefault();\n const canAttach =\n !disabled && !isAttachmentTargetBlocked(event.target);\n event.dataTransfer.dropEffect = canAttach ? 'copy' : 'none';\n setIsDropTarget(canAttach);\n }}\n onDragLeave={(event) => {\n onDragLeave?.(event);\n if (\n !(event.relatedTarget instanceof Node) ||\n !event.currentTarget.contains(event.relatedTarget)\n ) {\n setIsDropTarget(false);\n }\n }}\n onDropCapture={(event) => {\n onDropCapture?.(event);\n setIsDropTarget(false);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.dataTransfer.files);\n if (!files.length) return;\n event.preventDefault();\n if (!disabled && !isAttachmentTargetBlocked(event.target)) {\n onFilesSelected(files);\n }\n }}\n onPasteCapture={(event) => {\n onPasteCapture?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.clipboardData.files);\n if (!files.length) return;\n if (disabled || isAttachmentTargetBlocked(event.target)) {\n event.preventDefault();\n return;\n }\n // Let the focused editor preserve mixed-paste text and its selection.\n if (!event.clipboardData.getData('text/plain')) {\n event.preventDefault();\n }\n onFilesSelected(files);\n }}\n >\n {hasDrawer && (\n <fieldset\n disabled={disabled}\n className={cn(\n // Extends under the composer's rounded top so the seam stays hidden.\n 'mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none',\n DRAWER_INTENT_CLASSES[drawerIntent],\n disabled && 'border-disabled'\n )}\n >\n {drawer}\n </fieldset>\n )}\n <fieldset\n ref={fieldsetRef}\n // A disabled fieldset would also disable Stop; the composer's own\n // parts read `disabled` from context instead.\n disabled={disabled && action !== 'stop'}\n className={cn(\n 'relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-lg border border-subtle bg-elevated p-space-2 transition-[border-color,box-shadow,background-color] duration-normal motion-reduce:transition-none',\n // Toolbar menus portal out, so focus-within would flash as focus\n // moves from their trigger to the menu; only typing shows focus.\n 'has-[:is(textarea,[contenteditable=true]):focus]:border-focus has-[:is(textarea,[contenteditable=true]):focus]:shadow-[0_0_0_1px_var(--border-focus)]',\n disabled && 'border-disabled bg-input-disabled',\n isDropTarget &&\n !disabled &&\n 'border-focus bg-surface-level-2 shadow-[0_0_0_1px_var(--border-focus)]'\n )}\n >\n {children}\n </fieldset>\n </form>\n </ChatComposerContext.Provider>\n );\n}\n\nexport interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {\n modelSelector?: ReactNode;\n actions?: ReactNode;\n}\n\nexport function ChatComposerToolbar({\n children,\n modelSelector,\n actions = <ChatComposerAction />,\n className,\n ...props\n}: ChatComposerToolbarProps) {\n return (\n <div\n {...props}\n className={cn('flex min-w-0 items-center gap-space-2', className)}\n >\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-space-1 @[440px]/composer:gap-space-2\">\n {children}\n {modelSelector != null && (\n <div className=\"min-w-0 max-w-full [&>*]:max-w-full\">\n {modelSelector}\n </div>\n )}\n </div>\n <div className=\"flex shrink-0 items-center gap-space-1\">{actions}</div>\n </div>\n );\n}\n\nconst ACTION_LABELS = {\n send: 'Send message',\n sending: 'Sending message',\n stop: 'Stop response',\n} satisfies Record<ChatComposerContextValue['action'], string>;\n\n// Pending sends use the composer's action=\"sending\", which also blocks the\n// send shortcuts; a button-level loading state would only block clicks.\nexport type ChatComposerActionProps = Omit<\n IconButtonProps,\n 'icon' | 'type' | 'onClick' | 'asChild' | 'label' | 'loading'\n> & { label?: string };\n\nexport function ChatComposerAction({\n disabled,\n label,\n ...props\n}: ChatComposerActionProps) {\n const composer = useChatComposerContext();\n const isStop = composer.action === 'stop';\n return (\n <IconButton\n size=\"sm\"\n round\n color=\"primary\"\n iconWeight=\"regular\"\n {...props}\n type={isStop ? 'button' : 'submit'}\n icon={isStop ? StopIcon : ArrowUpIcon}\n label={label ?? ACTION_LABELS[composer.action]}\n // canSubmit already accounts for a disabled composer; Stop ignores it.\n disabled={disabled || (!isStop && !composer.canSubmit)}\n loading={composer.action === 'sending'}\n onClick={isStop ? composer.onStop : undefined}\n />\n );\n}\n"],"mappings":";;;;;;;;;AAkBA,IAAM,wBAAkE;CACtE,SAAS;CACT,MAAM;CACN,SAAS;CACT,OAAO;AACT;AA0BA,SAAS,0BA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B;CAC3B,OACE,qBAAC,OAAD;EACE,GAAI;EACJ,WAAW,GAAG,yCAAyC,SAAS;EAFlE,UAAA,CAIE,qBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACG,UACA,iBAAiB,QAChB,oBAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,CAEJ;EACL,CAAA,GAAA,oBAAC,OAAD;GAAK,WAAU;GAA0C,UAAA;EAAa,CAAA,CACnE;;AAET;AAEA,IAAM,gBAAgB;CACpB,MAAM;CACN,SAAS;CACT,MAAM;AACR;AASA,SAAgB,mBAAmB,EACjC,UACA,OACA,GAAG,SACuB;CAC1B,MAAM,WAAW,uBAAuB;CACxC,MAAM,SAAS,SAAS,WAAW;CACnC,OACE,oBAAC,YAAD;EACE,MAAK;EACL,OAAA;EACA,OAAM;EACN,YAAW;EACX,GAAI;EACJ,MAAM,SAAS,WAAW;EAC1B,MAAM,SAAS,WAAW;EAC1B,OAAO,SAAS,cAAc,SAAS;EAEvC,UAAU,YAAa,CAAC,UAAU,CAAC,SAAS;EAC5C,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,SAAS,SAAS,KAAA;CACrC,CAAA;AAEL"}
|
|
1
|
+
{"version":3,"file":"ChatComposer.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposer.tsx"],"sourcesContent":["import type { ComponentPropsWithRef, ReactNode } from 'react';\nimport { useRef, useState } from 'react';\n\nimport { ArrowUpIcon } from '@phosphor-icons/react/dist/ssr/ArrowUp';\nimport { StopIcon } from '@phosphor-icons/react/dist/ssr/Stop';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { IconButton } from '../IconButton';\nimport type { IconButtonProps } from '../IconButton';\nimport {\n ChatComposerContext,\n type ChatComposerContextValue,\n useChatComposerContext,\n} from './ChatComposerContext';\n\nexport type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';\n\n// Dividers match the drawer border, so stacked drawer content reads as one surface.\nconst DRAWER_INTENT_CLASSES: Record<ChatComposerDrawerIntent, string> = {\n neutral: 'border-subtle divide-subtle bg-surface-level-2',\n info: 'border-brand-subtle divide-brand-subtle bg-brand-subtle',\n warning: 'border-warning divide-warning bg-warning',\n error: 'border-error divide-error bg-error',\n};\n\nexport type ChatComposerProps = ComponentPropsWithRef<'form'> & {\n /**\n * Supplementary content attached above the editor, inside the composer form.\n * Several items, such as a plan and a question, stack with dividers; put the\n * one the input answers last, next to it.\n */\n drawer?: ReactNode;\n /**\n * Drawer surface color. Color alone doesn't convey severity, so the drawer\n * content should also say it in text or with an icon.\n */\n drawerIntent?: ChatComposerDrawerIntent;\n /**\n * Blocks writing and sending. Stop stays available while `action` is\n * `stop`, so host controls inside the composer must take `disabled`\n * themselves to stay disabled during a response.\n */\n disabled?: boolean;\n submitDisabled?: boolean;\n onFilesSelected?: (files: File[]) => void;\n} & (\n | { action?: 'send' | 'sending'; onStop?: never }\n | { action: 'stop'; onStop: () => void }\n /** A stop request is pending; Stop shows progress and sending stays blocked. */\n | { action: 'stopping'; onStop?: never }\n );\n\n// A disabled or read-only part of the composer, such as a read-only message\n// input, does not accept input, so files dropped or pasted onto it are not\n// attached either.\nfunction isAttachmentTargetBlocked(target: EventTarget) {\n return (\n target instanceof Element &&\n target.closest(\n ':disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]'\n ) !== null\n );\n}\n\n// Clicks on the composer's own empty space go to the message input; clicks on\n// controls, fields, links, and the editor itself keep their behavior.\nconst COMPOSER_CLICK_TARGET_SELECTOR =\n 'a[href], button, input, select, textarea, label, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"]), [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"option\"], [role=\"combobox\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"switch\"], [role=\"tab\"]';\n\n// A fieldset is barred from constraint validation, so its own\n// reportValidity() never inspects the controls inside it.\nfunction reportFieldsetValidity(fieldset: HTMLFieldSetElement | null) {\n for (const element of fieldset?.elements ?? []) {\n if (\n (element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement) &&\n !element.reportValidity()\n )\n return false;\n }\n return true;\n}\n\nexport function ChatComposer({\n children,\n drawer,\n drawerIntent = 'neutral',\n className,\n ref,\n disabled = false,\n submitDisabled = false,\n action = 'send',\n onStop,\n onSubmit,\n onFilesSelected,\n onDragOver,\n onDragLeave,\n onDropCapture,\n onPasteCapture,\n noValidate,\n ...props\n}: ChatComposerProps) {\n const formRef = useRef<HTMLFormElement>(null);\n const [isDropTarget, setIsDropTarget] = useState(false);\n const canSubmit =\n !disabled && !submitDisabled && action === 'send' && !!onSubmit;\n const hasDrawer = Boolean(drawer);\n const fieldsetRef = useRef<HTMLFieldSetElement>(null);\n const inputFocusRef = useRef<(() => boolean) | null>(null);\n // Inert drawer fields cannot be focused to report errors, so the drawer's\n // host validates them; fields outside the drawer keep native checks.\n const validatesFieldsetOnly = noValidate === undefined && hasDrawer;\n\n return (\n <ChatComposerContext.Provider\n value={{\n disabled,\n canSubmit,\n action,\n onStop,\n onFilesSelected,\n inputFocusRef,\n submit: onSubmit\n ? () => {\n if (canSubmit) formRef.current?.requestSubmit();\n }\n : undefined,\n }}\n >\n <form\n {...props}\n ref={mergeRefs([formRef, ref])}\n noValidate={noValidate ?? hasDrawer}\n className={cn('isolate w-full min-w-0 @container/composer', className)}\n onSubmit={(event) => {\n event.preventDefault();\n if (!canSubmit) return;\n if (\n validatesFieldsetOnly &&\n !reportFieldsetValidity(fieldsetRef.current)\n )\n return;\n onSubmit?.(event);\n }}\n onDragOver={(event) => {\n onDragOver?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n if (!event.dataTransfer.types.includes('Files')) return;\n event.preventDefault();\n const canAttach =\n !disabled && !isAttachmentTargetBlocked(event.target);\n event.dataTransfer.dropEffect = canAttach ? 'copy' : 'none';\n setIsDropTarget(canAttach);\n }}\n onDragLeave={(event) => {\n onDragLeave?.(event);\n if (\n !(event.relatedTarget instanceof Node) ||\n !event.currentTarget.contains(event.relatedTarget)\n ) {\n setIsDropTarget(false);\n }\n }}\n onDropCapture={(event) => {\n onDropCapture?.(event);\n setIsDropTarget(false);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.dataTransfer.files);\n if (!files.length) return;\n event.preventDefault();\n if (!disabled && !isAttachmentTargetBlocked(event.target)) {\n onFilesSelected(files);\n }\n }}\n onPasteCapture={(event) => {\n onPasteCapture?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.clipboardData.files);\n if (!files.length) return;\n if (disabled || isAttachmentTargetBlocked(event.target)) {\n event.preventDefault();\n return;\n }\n // Let the focused editor preserve mixed-paste text and its selection.\n if (!event.clipboardData.getData('text/plain')) {\n event.preventDefault();\n }\n onFilesSelected(files);\n }}\n >\n {hasDrawer && (\n <fieldset\n disabled={disabled}\n className={cn(\n // Extends under the composer's rounded top so the seam stays hidden.\n 'mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 divide-y overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none',\n DRAWER_INTENT_CLASSES[drawerIntent],\n disabled && 'border-disabled divide-disabled'\n )}\n >\n {drawer}\n </fieldset>\n )}\n <fieldset\n ref={fieldsetRef}\n // A disabled fieldset would also disable Stop; the composer's own\n // parts read `disabled` from context instead.\n disabled={disabled && action !== 'stop'}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n !(event.target instanceof Element) ||\n event.target.closest(COMPOSER_CLICK_TARGET_SELECTOR) ||\n // Finishing a drag selection, such as in an attachment name.\n window.getSelection()?.isCollapsed === false\n )\n return;\n inputFocusRef.current?.();\n }}\n className={cn(\n 'relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-lg border border-subtle bg-elevated p-space-2 transition-[border-color,box-shadow,background-color] duration-normal motion-reduce:transition-none',\n // Toolbar menus portal out, so focus-within would flash as focus\n // moves from their trigger to the menu; only typing shows focus.\n 'has-[:is(textarea,[contenteditable=true]):focus]:border-focus has-[:is(textarea,[contenteditable=true]):focus]:shadow-[0_0_0_1px_var(--border-focus)]',\n disabled && 'border-disabled bg-input-disabled',\n isDropTarget &&\n !disabled &&\n 'border-focus bg-surface-level-2 shadow-[0_0_0_1px_var(--border-focus)]'\n )}\n >\n {children}\n </fieldset>\n </form>\n </ChatComposerContext.Provider>\n );\n}\n\nexport interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {\n modelSelector?: ReactNode;\n actions?: ReactNode;\n}\n\nexport function ChatComposerToolbar({\n children,\n modelSelector,\n actions = <ChatComposerAction />,\n className,\n ...props\n}: ChatComposerToolbarProps) {\n return (\n <div\n {...props}\n className={cn('flex min-w-0 items-center gap-space-2', className)}\n >\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-space-1 @[440px]/composer:gap-space-2\">\n {children}\n {modelSelector != null && (\n <div className=\"min-w-0 max-w-full [&>*]:max-w-full\">\n {modelSelector}\n </div>\n )}\n </div>\n <div className=\"flex shrink-0 items-center gap-space-1\">{actions}</div>\n </div>\n );\n}\n\nconst ACTION_LABELS = {\n send: 'Send message',\n sending: 'Sending message',\n stop: 'Stop response',\n stopping: 'Stopping response',\n} satisfies Record<ChatComposerContextValue['action'], string>;\n\n// Pending sends use the composer's action=\"sending\", which also blocks the\n// send shortcuts; a button-level loading state would only block clicks.\nexport type ChatComposerActionProps = Omit<\n IconButtonProps,\n 'icon' | 'type' | 'onClick' | 'asChild' | 'label' | 'loading'\n> & { label?: string };\n\nexport function ChatComposerAction({\n disabled,\n label,\n ...props\n}: ChatComposerActionProps) {\n const composer = useChatComposerContext();\n const isStop = composer.action === 'stop';\n const isStopping = composer.action === 'stopping';\n return (\n <IconButton\n size=\"sm\"\n round\n color=\"primary\"\n iconWeight=\"regular\"\n {...props}\n type={isStop || isStopping ? 'button' : 'submit'}\n icon={isStop || isStopping ? StopIcon : ArrowUpIcon}\n label={label ?? ACTION_LABELS[composer.action]}\n // canSubmit is false while disabled, sending, or stopping, so this also\n // disables Stop once a stop is pending; Stop ignores `disabled` otherwise.\n disabled={disabled || (!isStop && !composer.canSubmit)}\n loading={composer.action === 'sending' || isStopping}\n onClick={isStop ? composer.onStop : undefined}\n />\n );\n}\n"],"mappings":";;;;;;;;;AAmBA,IAAM,wBAAkE;CACtE,SAAS;CACT,MAAM;CACN,SAAS;CACT,OAAO;AACT;AAgCA,SAAS,0BAA0B,QAAqB;CACtD,OACE,kBAAkB,WAClB,OAAO,QACL,2EACF,MAAM;AAEV;AAIA,IAAM,iCACJ;AAIF,SAAS,uBAAuB,UAAsC;CACpE,KAAK,MAAM,WAAW,UAAU,YAAY,CAAC,GAC3C,KACG,mBAAmB,oBAClB,mBAAmB,qBACnB,mBAAmB,wBACrB,CAAC,QAAQ,eAAe,GAExB,OAAO;CAEX,OAAO;AACT;AAEA,SAAgB,aAAa,EAC3B,UACA,QACA,eAAe,WACf,WACA,KACA,WAAW,OACX,iBAAiB,OACjB,SAAS,QACT,QACA,UACA,iBACA,YACA,aACA,eACA,gBACA,YACA,GAAG,SACiB;CACpB,MAAM,UAAU,OAAwB,IAAI;CAC5C,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CACtD,MAAM,YACJ,CAAC,YAAY,CAAC,kBAAkB,WAAW,UAAU,CAAC,CAAC;CACzD,MAAM,YAAY,QAAQ,MAAM;CAChC,MAAM,cAAc,OAA4B,IAAI;CACpD,MAAM,gBAAgB,OAA+B,IAAI;CAGzD,MAAM,wBAAwB,eAAe,KAAA,KAAa;CAE1D,OACE,oBAAC,oBAAoB,UAArB;EACE,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACA,QAAQ,iBACE;IACJ,IAAI,WAAW,QAAQ,SAAS,cAAc;GAChD,IACA,KAAA;EACN;EAEA,UAAA,qBAAC,QAAD;GACE,GAAI;GACJ,KAAK,UAAU,CAAC,SAAS,GAAG,CAAC;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Aa;EAC1C,SAAS,SAAS,SAAS,SAAS,KAAA;CACrC,CAAA;AAEL"}
|
|
@@ -2,7 +2,7 @@ import { type RefObject } from 'react';
|
|
|
2
2
|
export interface ChatComposerContextValue {
|
|
3
3
|
disabled: boolean;
|
|
4
4
|
canSubmit: boolean;
|
|
5
|
-
action: 'send' | 'sending' | 'stop';
|
|
5
|
+
action: 'send' | 'sending' | 'stop' | 'stopping';
|
|
6
6
|
submit?: () => void;
|
|
7
7
|
onStop?: () => void;
|
|
8
8
|
onFilesSelected?: (files: File[]) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatComposerContext.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerContext.ts"],"sourcesContent":["import { createContext, useContext, type RefObject } from 'react';\n\nexport interface ChatComposerContextValue {\n disabled: boolean;\n canSubmit: boolean;\n action: 'send' | 'sending' | 'stop';\n submit?: () => void;\n onStop?: () => void;\n onFilesSelected?: (files: File[]) => void;\n /** Set by ChatComposerInput; returns false when the input cannot take focus. */\n inputFocusRef?: RefObject<(() => boolean) | null>;\n}\n\nexport const ChatComposerContext =\n createContext<ChatComposerContextValue | null>(null);\n\n// Node views render through portals and need input-level editability updates.\nexport const ChatComposerInputEditableContext = createContext(false);\n\nexport function useChatComposerContext() {\n const context = useContext(ChatComposerContext);\n if (!context) {\n throw new Error('ChatComposer parts must be inside a ChatComposer.');\n }\n return context;\n}\n\nexport function isComposerSubmitKey(event: KeyboardEvent, multiline = false) {\n return (\n event.key === 'Enter' &&\n !event.shiftKey &&\n !event.altKey &&\n !event.isComposing &&\n // Safari can end composition before dispatching the confirming Enter.\n event.keyCode !== 229 &&\n (!multiline || event.metaKey || event.ctrlKey)\n );\n}\n"],"mappings":";;AAaA,IAAa,sBACX,cAA+C,IAAI;AAGrD,IAAa,mCAAmC,cAAc,KAAK;AAEnE,SAAgB,yBAAyB;CACvC,MAAM,UAAU,WAAW,mBAAmB;CAC9C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAAsB,YAAY,OAAO;CAC3E,OACE,MAAM,QAAQ,WACd,CAAC,MAAM,YACP,CAAC,MAAM,UACP,CAAC,MAAM,eAEP,MAAM,YAAY,QACjB,CAAC,aAAa,MAAM,WAAW,MAAM;AAE1C"}
|
|
1
|
+
{"version":3,"file":"ChatComposerContext.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerContext.ts"],"sourcesContent":["import { createContext, useContext, type RefObject } from 'react';\n\nexport interface ChatComposerContextValue {\n disabled: boolean;\n canSubmit: boolean;\n action: 'send' | 'sending' | 'stop' | 'stopping';\n submit?: () => void;\n onStop?: () => void;\n onFilesSelected?: (files: File[]) => void;\n /** Set by ChatComposerInput; returns false when the input cannot take focus. */\n inputFocusRef?: RefObject<(() => boolean) | null>;\n}\n\nexport const ChatComposerContext =\n createContext<ChatComposerContextValue | null>(null);\n\n// Node views render through portals and need input-level editability updates.\nexport const ChatComposerInputEditableContext = createContext(false);\n\nexport function useChatComposerContext() {\n const context = useContext(ChatComposerContext);\n if (!context) {\n throw new Error('ChatComposer parts must be inside a ChatComposer.');\n }\n return context;\n}\n\nexport function isComposerSubmitKey(event: KeyboardEvent, multiline = false) {\n return (\n event.key === 'Enter' &&\n !event.shiftKey &&\n !event.altKey &&\n !event.isComposing &&\n // Safari can end composition before dispatching the confirming Enter.\n event.keyCode !== 229 &&\n (!multiline || event.metaKey || event.ctrlKey)\n );\n}\n"],"mappings":";;AAaA,IAAa,sBACX,cAA+C,IAAI;AAGrD,IAAa,mCAAmC,cAAc,KAAK;AAEnE,SAAgB,yBAAyB;CACvC,MAAM,UAAU,WAAW,mBAAmB;CAC9C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAAsB,YAAY,OAAO;CAC3E,OACE,MAAM,QAAQ,WACd,CAAC,MAAM,YACP,CAAC,MAAM,UACP,CAAC,MAAM,eAEP,MAAM,YAAY,QACjB,CAAC,aAAa,MAAM,WAAW,MAAM;AAE1C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { cn } from "../../utils/cn.js";
|
|
2
2
|
import { ChatComposerInputEditableContext, useChatComposerContext } from "./ChatComposerContext.js";
|
|
3
3
|
import { useChatComposerEditor } from "./useChatComposerEditor.js";
|
|
4
|
-
import { useImperativeHandle } from "react";
|
|
4
|
+
import { useEffect, useImperativeHandle, useRef } from "react";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
6
6
|
import { EditorContent } from "@tiptap/react";
|
|
7
7
|
var ChatComposerRichInput_module_default = { editor: "_editor_1jx45_3" };
|
|
@@ -33,9 +33,20 @@ function ChatComposerRichInput({ ref, value, onChange, placeholder = "Write a me
|
|
|
33
33
|
useImperativeHandle(ref, () => ({ focus: () => {
|
|
34
34
|
if (editable) editor?.commands.focus("end");
|
|
35
35
|
} }), [editor, editable]);
|
|
36
|
+
const hasFocusedRef = useRef(false);
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
if (!editor) return;
|
|
39
|
+
const markFocused = () => {
|
|
40
|
+
hasFocusedRef.current = true;
|
|
41
|
+
};
|
|
42
|
+
editor.on("focus", markFocused);
|
|
43
|
+
return () => {
|
|
44
|
+
editor.off("focus", markFocused);
|
|
45
|
+
};
|
|
46
|
+
}, [editor]);
|
|
36
47
|
useImperativeHandle(composer.inputFocusRef, () => () => {
|
|
37
48
|
if (!editable || !editor) return false;
|
|
38
|
-
editor.commands.focus("end");
|
|
49
|
+
editor.commands.focus(hasFocusedRef.current ? null : "end");
|
|
39
50
|
return true;
|
|
40
51
|
}, [editor, editable]);
|
|
41
52
|
return /* @__PURE__ */ jsx("div", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatComposerRichInput.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerRichInput.module.css","../../../src/components/ChatComposer/ChatComposerRichInput.tsx"],"sourcesContent":["@reference \"../../styles/tailwind.css\";\n\n.editor :global(p.is-editor-empty:first-child)::before {\n @apply pointer-events-none float-left h-0 text-placeholder;\n content: attr(data-placeholder);\n}\n\n.editor p {\n @apply m-0;\n}\n\n.editor > * + * {\n @apply mt-space-2;\n}\n\n.editor h1,\n.editor h2,\n.editor h3,\n.editor h4,\n.editor h5,\n.editor h6 {\n @apply text-base font-semibold;\n}\n\n.editor ul {\n @apply list-outside list-disc pl-space-5;\n}\n\n.editor ol {\n @apply list-outside list-decimal pl-space-5;\n}\n\n.editor a {\n @apply text-link underline underline-offset-2;\n}\n\n.editor blockquote {\n @apply border-l-2 border-default pl-space-3 text-secondary;\n}\n\n.editor :not(pre) > code {\n @apply rounded-sm bg-surface-level-2 px-space-1 font-mono;\n}\n\n.editor pre code {\n @apply bg-transparent p-0;\n}\n\n.editor hr {\n @apply border-default;\n}\n","import { useImperativeHandle } from 'react';\n\nimport { EditorContent } from '@tiptap/react';\n\nimport { cn } from '../../utils/cn';\nimport {\n ChatComposerInputEditableContext,\n useChatComposerContext,\n} from './ChatComposerContext';\nimport type { ChatComposerInputProps } from './ChatComposerInput';\nimport { useChatComposerEditor } from './useChatComposerEditor';\n\nimport styles from './ChatComposerRichInput.module.css';\n\ninterface ChatComposerRichInputProps extends ChatComposerInputProps {\n minHeight: number;\n maxHeight: number;\n}\n\nexport function ChatComposerRichInput({\n ref,\n value,\n onChange,\n placeholder = 'Write a message…',\n disabled = false,\n readOnly = false,\n autoFocus = false,\n minHeight,\n maxHeight,\n className,\n 'aria-label': ariaLabel = 'Message',\n 'aria-describedby': ariaDescribedBy,\n}: ChatComposerRichInputProps) {\n 'use no memo';\n\n const composer = useChatComposerContext();\n const isDisabled = composer.disabled || disabled;\n const editable = !isDisabled && !readOnly;\n const { editor } = useChatComposerEditor({\n value,\n onChange,\n onSubmit: composer.submit,\n placeholder,\n editable,\n autofocus: autoFocus,\n editorClassName: cn(\n styles.editor,\n 'min-w-0 break-words px-space-1 text-sm leading-relaxed text-primary outline-hidden',\n // Read-only text is still the user's message, such as a prefilled draft\n // being typed in, so only disabled input looks unavailable.\n isDisabled && 'text-disabled'\n ),\n editorAttributes: {\n role: 'textbox',\n style: `min-height: ${minHeight}px`,\n 'aria-label': ariaLabel,\n 'aria-multiline': 'true',\n 'aria-disabled': String(isDisabled),\n 'aria-readonly': String(readOnly),\n ...(ariaDescribedBy ? { 'aria-describedby': ariaDescribedBy } : {}),\n },\n });\n\n useImperativeHandle(\n ref,\n () => ({\n focus: () => {\n if (editable) editor?.commands.focus('end');\n },\n }),\n [editor, editable]\n );\n\n useImperativeHandle(\n composer.inputFocusRef,\n () => () => {\n if (!editable || !editor) return false;\n editor.commands.focus('end');\n return true;\n },\n [editor, editable]\n );\n\n return (\n <div\n className={cn('min-w-0 overflow-y-auto overscroll-contain', className)}\n style={{ maxHeight }}\n >\n <ChatComposerInputEditableContext.Provider value={editable}>\n <EditorContent editor={editor} />\n </ChatComposerInputEditableContext.Provider>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;ACmBA,SAAgB,sBAAsB,EACpC,KACA,OACA,UACA,cAAc,oBACd,WAAW,OACX,WAAW,OACX,YAAY,OACZ,WACA,WACA,WACA,cAAc,YAAY,WAC1B,oBAAoB,mBACS;CAC7B;CAEA,MAAM,WAAW,uBAAuB;CACxC,MAAM,aAAa,SAAS,YAAY;CACxC,MAAM,WAAW,CAAC,cAAc,CAAC;CACjC,MAAM,EAAE,WAAW,sBAAsB;EACvC;EACA;EACA,UAAU,SAAS;EACnB;EACA;EACA,WAAW;EACX,iBAAiB,GACf,qCAAO,QACP,sFAGA,cAAc,eAChB;EACA,kBAAkB;GAChB,MAAM;GACN,OAAO,eAAe,UAAU;GAChC,cAAc;GACd,kBAAkB;GAClB,iBAAiB,OAAO,UAAU;GAClC,iBAAiB,OAAO,QAAQ;GAChC,GAAI,kBAAkB,EAAE,oBAAoB,gBAAgB,IAAI,CAAC;EACnE;CACF,CAAC;CAED,oBACE,YACO,EACL,aAAa;EACX,IAAI,UAAU,QAAQ,SAAS,MAAM,KAAK;CAC5C,EACF,IACA,CAAC,QAAQ,QAAQ,CACnB;
|
|
1
|
+
{"version":3,"file":"ChatComposerRichInput.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerRichInput.module.css","../../../src/components/ChatComposer/ChatComposerRichInput.tsx"],"sourcesContent":["@reference \"../../styles/tailwind.css\";\n\n.editor :global(p.is-editor-empty:first-child)::before {\n @apply pointer-events-none float-left h-0 text-placeholder;\n content: attr(data-placeholder);\n}\n\n.editor p {\n @apply m-0;\n}\n\n.editor > * + * {\n @apply mt-space-2;\n}\n\n.editor h1,\n.editor h2,\n.editor h3,\n.editor h4,\n.editor h5,\n.editor h6 {\n @apply text-base font-semibold;\n}\n\n.editor ul {\n @apply list-outside list-disc pl-space-5;\n}\n\n.editor ol {\n @apply list-outside list-decimal pl-space-5;\n}\n\n.editor a {\n @apply text-link underline underline-offset-2;\n}\n\n.editor blockquote {\n @apply border-l-2 border-default pl-space-3 text-secondary;\n}\n\n.editor :not(pre) > code {\n @apply rounded-sm bg-surface-level-2 px-space-1 font-mono;\n}\n\n.editor pre code {\n @apply bg-transparent p-0;\n}\n\n.editor hr {\n @apply border-default;\n}\n","import { useEffect, useImperativeHandle, useRef } from 'react';\n\nimport { EditorContent } from '@tiptap/react';\n\nimport { cn } from '../../utils/cn';\nimport {\n ChatComposerInputEditableContext,\n useChatComposerContext,\n} from './ChatComposerContext';\nimport type { ChatComposerInputProps } from './ChatComposerInput';\nimport { useChatComposerEditor } from './useChatComposerEditor';\n\nimport styles from './ChatComposerRichInput.module.css';\n\ninterface ChatComposerRichInputProps extends ChatComposerInputProps {\n minHeight: number;\n maxHeight: number;\n}\n\nexport function ChatComposerRichInput({\n ref,\n value,\n onChange,\n placeholder = 'Write a message…',\n disabled = false,\n readOnly = false,\n autoFocus = false,\n minHeight,\n maxHeight,\n className,\n 'aria-label': ariaLabel = 'Message',\n 'aria-describedby': ariaDescribedBy,\n}: ChatComposerRichInputProps) {\n 'use no memo';\n\n const composer = useChatComposerContext();\n const isDisabled = composer.disabled || disabled;\n const editable = !isDisabled && !readOnly;\n const { editor } = useChatComposerEditor({\n value,\n onChange,\n onSubmit: composer.submit,\n placeholder,\n editable,\n autofocus: autoFocus,\n editorClassName: cn(\n styles.editor,\n 'min-w-0 break-words px-space-1 text-sm leading-relaxed text-primary outline-hidden',\n // Read-only text is still the user's message, such as a prefilled draft\n // being typed in, so only disabled input looks unavailable.\n isDisabled && 'text-disabled'\n ),\n editorAttributes: {\n role: 'textbox',\n style: `min-height: ${minHeight}px`,\n 'aria-label': ariaLabel,\n 'aria-multiline': 'true',\n 'aria-disabled': String(isDisabled),\n 'aria-readonly': String(readOnly),\n ...(ariaDescribedBy ? { 'aria-describedby': ariaDescribedBy } : {}),\n },\n });\n\n useImperativeHandle(\n ref,\n () => ({\n focus: () => {\n if (editable) editor?.commands.focus('end');\n },\n }),\n [editor, editable]\n );\n\n // Until the user first places the caret, ProseMirror's selection sits at the\n // start of the draft, so composer-level focus starts at the end instead.\n const hasFocusedRef = useRef(false);\n useEffect(() => {\n if (!editor) return;\n const markFocused = () => {\n hasFocusedRef.current = true;\n };\n editor.on('focus', markFocused);\n return () => {\n editor.off('focus', markFocused);\n };\n }, [editor]);\n\n useImperativeHandle(\n composer.inputFocusRef,\n () => () => {\n if (!editable || !editor) return false;\n editor.commands.focus(hasFocusedRef.current ? null : 'end');\n return true;\n },\n [editor, editable]\n );\n\n return (\n <div\n className={cn('min-w-0 overflow-y-auto overscroll-contain', className)}\n style={{ maxHeight }}\n >\n <ChatComposerInputEditableContext.Provider value={editable}>\n <EditorContent editor={editor} />\n </ChatComposerInputEditableContext.Provider>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;ACmBA,SAAgB,sBAAsB,EACpC,KACA,OACA,UACA,cAAc,oBACd,WAAW,OACX,WAAW,OACX,YAAY,OACZ,WACA,WACA,WACA,cAAc,YAAY,WAC1B,oBAAoB,mBACS;CAC7B;CAEA,MAAM,WAAW,uBAAuB;CACxC,MAAM,aAAa,SAAS,YAAY;CACxC,MAAM,WAAW,CAAC,cAAc,CAAC;CACjC,MAAM,EAAE,WAAW,sBAAsB;EACvC;EACA;EACA,UAAU,SAAS;EACnB;EACA;EACA,WAAW;EACX,iBAAiB,GACf,qCAAO,QACP,sFAGA,cAAc,eAChB;EACA,kBAAkB;GAChB,MAAM;GACN,OAAO,eAAe,UAAU;GAChC,cAAc;GACd,kBAAkB;GAClB,iBAAiB,OAAO,UAAU;GAClC,iBAAiB,OAAO,QAAQ;GAChC,GAAI,kBAAkB,EAAE,oBAAoB,gBAAgB,IAAI,CAAC;EACnE;CACF,CAAC;CAED,oBACE,YACO,EACL,aAAa;EACX,IAAI,UAAU,QAAQ,SAAS,MAAM,KAAK;CAC5C,EACF,IACA,CAAC,QAAQ,QAAQ,CACnB;CAIA,MAAM,gBAAgB,OAAO,KAAK;CAClC,gBAAgB;EACd,IAAI,CAAC,QAAQ;EACb,MAAM,oBAAoB;GACxB,cAAc,UAAU;EAC1B;EACA,OAAO,GAAG,SAAS,WAAW;EAC9B,aAAa;GACX,OAAO,IAAI,SAAS,WAAW;EACjC;CACF,GAAG,CAAC,MAAM,CAAC;CAEX,oBACE,SAAS,2BACG;EACV,IAAI,CAAC,YAAY,CAAC,QAAQ,OAAO;EACjC,OAAO,SAAS,MAAM,cAAc,UAAU,OAAO,KAAK;EAC1D,OAAO;CACT,GACA,CAAC,QAAQ,QAAQ,CACnB;CAEA,OACE,oBAAC,OAAD;EACE,WAAW,GAAG,8CAA8C,SAAS;EACrE,OAAO,EAAE,UAAU;EAEnB,UAAA,oBAAC,iCAAiC,UAAlC;GAA2C,OAAO;GAChD,UAAA,oBAAC,eAAD,EAAuB,OAAS,CAAA;EACS,CAAA;CACxC,CAAA;AAET"}
|
|
@@ -10,8 +10,21 @@ export interface ChatConversationProps {
|
|
|
10
10
|
label?: string;
|
|
11
11
|
className?: string;
|
|
12
12
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
13
|
+
* `bottom` (default) keeps the newest content in view while the reader is at
|
|
14
|
+
* the bottom. `none` never scrolls on its own; Jump to latest still appears.
|
|
15
|
+
*/
|
|
16
|
+
follow?: 'bottom' | 'none';
|
|
17
|
+
/**
|
|
18
|
+
* ID of a message to bring to the top, usually the one just sent. Each new ID
|
|
19
|
+
* scrolls it up once and reserves space below for the reply. Following
|
|
20
|
+
* resumes at the bottom or on Jump to latest. Matches `data-chat-message-id`,
|
|
21
|
+
* which `ChatMessage` sets.
|
|
22
|
+
*/
|
|
23
|
+
pinnedMessageId?: string;
|
|
24
|
+
/**
|
|
25
|
+
* The scrolling element, for hosts that track or restore the reading
|
|
26
|
+
* position. Content inserted above the first visible message, such as older
|
|
27
|
+
* messages, keeps that message in place.
|
|
15
28
|
*/
|
|
16
29
|
viewportRef?: Ref<HTMLDivElement>;
|
|
17
30
|
}
|
|
@@ -23,4 +36,4 @@ export interface ChatConversationProps {
|
|
|
23
36
|
* text would be read out word by word. Announce completed replies from a
|
|
24
37
|
* polite `role="status"` region in the host.
|
|
25
38
|
*/
|
|
26
|
-
export declare function ChatConversation({ children, header, footer, label, className, viewportRef: externalViewportRef, }: ChatConversationProps): import("react").JSX.Element;
|
|
39
|
+
export declare function ChatConversation({ children, header, footer, label, className, follow, pinnedMessageId, viewportRef: externalViewportRef, }: ChatConversationProps): import("react").JSX.Element;
|
|
@@ -7,8 +7,14 @@ import { jsx, jsxs } from "react/jsx-runtime";
|
|
|
7
7
|
//#region packages/components/src/components/ChatConversation/ChatConversation.tsx
|
|
8
8
|
/** Distance from the bottom, in px, that still counts as reading the latest output. */
|
|
9
9
|
var FOLLOW_THRESHOLD = 48;
|
|
10
|
+
var MESSAGE_ID_ATTRIBUTE = "data-chat-message-id";
|
|
11
|
+
var MESSAGE_SELECTOR = `[${MESSAGE_ID_ATTRIBUTE}]`;
|
|
10
12
|
var COLUMN_CLASS_NAME = "mx-auto w-full min-w-0 max-w-3xl px-space-4";
|
|
11
|
-
var
|
|
13
|
+
var TOP_FADE = "2rem";
|
|
14
|
+
var VIEWPORT_STYLE = {
|
|
15
|
+
"--scroll-mask-fade-from-t": `calc(100% - ${TOP_FADE})`,
|
|
16
|
+
scrollPaddingTop: TOP_FADE
|
|
17
|
+
};
|
|
12
18
|
/**
|
|
13
19
|
* Bounded-height chat layout that follows new output while the reader is at
|
|
14
20
|
* the bottom. Remount with a conversation `key` when switching threads.
|
|
@@ -17,48 +23,34 @@ var VIEWPORT_MASK_STYLE = { "--scroll-mask-fade-from-t": "calc(100% - 2rem)" };
|
|
|
17
23
|
* text would be read out word by word. Announce completed replies from a
|
|
18
24
|
* polite `role="status"` region in the host.
|
|
19
25
|
*/
|
|
20
|
-
function ChatConversation({ children, header, footer, label = "Conversation", className, viewportRef: externalViewportRef }) {
|
|
26
|
+
function ChatConversation({ children, header, footer, label = "Conversation", className, follow = "bottom", pinnedMessageId, viewportRef: externalViewportRef }) {
|
|
21
27
|
const viewportRef = useRef(null);
|
|
22
28
|
const contentRef = useRef(null);
|
|
23
|
-
const
|
|
24
|
-
const
|
|
29
|
+
const spacerRef = useRef(null);
|
|
30
|
+
const scrollRef = useRef(null);
|
|
31
|
+
const [showJump, setShowJump] = useState(false);
|
|
25
32
|
const mergedViewportRef = useMemo(() => mergeRefs([viewportRef, externalViewportRef]), [externalViewportRef]);
|
|
26
33
|
useLayoutEffect(() => {
|
|
27
34
|
const viewport = viewportRef.current;
|
|
28
35
|
const content = contentRef.current;
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
};
|
|
34
|
-
let lastScrollTop = viewport.scrollTop;
|
|
35
|
-
const handleScroll = () => {
|
|
36
|
-
const { scrollTop, scrollHeight, clientHeight } = viewport;
|
|
37
|
-
const nearBottom = scrollHeight - clientHeight - scrollTop <= FOLLOW_THRESHOLD;
|
|
38
|
-
followingRef.current = nearBottom || followingRef.current && scrollTop >= lastScrollTop;
|
|
39
|
-
lastScrollTop = scrollTop;
|
|
40
|
-
setIsNearBottom(followingRef.current);
|
|
41
|
-
};
|
|
42
|
-
followContent();
|
|
43
|
-
const observer = new ResizeObserver(() => {
|
|
44
|
-
followContent();
|
|
45
|
-
handleScroll();
|
|
46
|
-
});
|
|
47
|
-
observer.observe(viewport);
|
|
48
|
-
observer.observe(content);
|
|
49
|
-
viewport.addEventListener("scroll", handleScroll, { passive: true });
|
|
36
|
+
const spacer = spacerRef.current;
|
|
37
|
+
if (!viewport || !content || !spacer) return;
|
|
38
|
+
const scroll = connectConversationScroll(viewport, content, spacer, setShowJump);
|
|
39
|
+
scrollRef.current = scroll;
|
|
50
40
|
return () => {
|
|
51
|
-
|
|
52
|
-
|
|
41
|
+
scroll.disconnect();
|
|
42
|
+
scrollRef.current = null;
|
|
53
43
|
};
|
|
54
44
|
}, []);
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
45
|
+
useLayoutEffect(() => {
|
|
46
|
+
scrollRef.current?.setFollow(follow);
|
|
47
|
+
}, [follow]);
|
|
48
|
+
useLayoutEffect(() => {
|
|
49
|
+
if (pinnedMessageId !== void 0) scrollRef.current?.pin(pinnedMessageId);
|
|
50
|
+
}, [pinnedMessageId]);
|
|
51
|
+
function jumpToLatest() {
|
|
52
|
+
scrollRef.current?.jumpToLatest();
|
|
53
|
+
viewportRef.current?.focus({ preventScroll: true });
|
|
62
54
|
}
|
|
63
55
|
return /* @__PURE__ */ jsxs("section", {
|
|
64
56
|
"aria-label": label,
|
|
@@ -71,32 +63,35 @@ function ChatConversation({ children, header, footer, label = "Conversation", cl
|
|
|
71
63
|
/* @__PURE__ */ jsxs("div", {
|
|
72
64
|
className: "relative flex min-h-0 flex-1 flex-col",
|
|
73
65
|
children: [
|
|
74
|
-
/* @__PURE__ */
|
|
66
|
+
/* @__PURE__ */ jsxs("div", {
|
|
75
67
|
ref: mergedViewportRef,
|
|
76
68
|
role: "log",
|
|
77
69
|
"aria-label": `${label} messages`,
|
|
78
70
|
"aria-live": "off",
|
|
79
71
|
tabIndex: 0,
|
|
80
|
-
style:
|
|
81
|
-
className: "peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [scrollbar-gutter:stable_both-edges]",
|
|
82
|
-
children: /* @__PURE__ */ jsx("div", {
|
|
72
|
+
style: VIEWPORT_STYLE,
|
|
73
|
+
className: "peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [overflow-anchor:none] [scrollbar-gutter:stable_both-edges]",
|
|
74
|
+
children: [/* @__PURE__ */ jsx("div", {
|
|
83
75
|
ref: contentRef,
|
|
84
76
|
className: cn(COLUMN_CLASS_NAME, "flex min-h-full flex-col gap-space-6 py-space-5 pb-space-9"),
|
|
85
77
|
children
|
|
86
|
-
})
|
|
78
|
+
}), /* @__PURE__ */ jsx("div", {
|
|
79
|
+
ref: spacerRef,
|
|
80
|
+
"aria-hidden": "true"
|
|
81
|
+
})]
|
|
87
82
|
}),
|
|
88
83
|
/* @__PURE__ */ jsx("div", {
|
|
89
84
|
"aria-hidden": true,
|
|
90
85
|
className: "pointer-events-none absolute inset-0 ring-inset ring-focus peer-focus-visible:ring-2"
|
|
91
86
|
}),
|
|
92
|
-
|
|
87
|
+
showJump && /* @__PURE__ */ jsx("div", {
|
|
93
88
|
className: "pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-space-3",
|
|
94
89
|
children: /* @__PURE__ */ jsx(Button, {
|
|
95
90
|
color: "secondary",
|
|
96
91
|
size: "md",
|
|
97
92
|
leftDecorator: CaretDownIcon,
|
|
98
93
|
className: "pointer-events-auto shadow-md hover:bg-elevated pointer-coarse:h-11",
|
|
99
|
-
onClick:
|
|
94
|
+
onClick: jumpToLatest,
|
|
100
95
|
children: "Jump to latest"
|
|
101
96
|
})
|
|
102
97
|
})
|
|
@@ -109,6 +104,179 @@ function ChatConversation({ children, header, footer, label = "Conversation", cl
|
|
|
109
104
|
]
|
|
110
105
|
});
|
|
111
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Owns the log's scroll position: following the bottom, holding a pinned
|
|
109
|
+
* message at the top, and keeping the reader's place when content above it
|
|
110
|
+
* changes size. Every scroll it makes is instant.
|
|
111
|
+
*/
|
|
112
|
+
function connectConversationScroll(viewport, content, spacer, onShowJumpChange) {
|
|
113
|
+
let follow;
|
|
114
|
+
/** Scroll to the bottom whenever the content or viewport resizes. */
|
|
115
|
+
let following = false;
|
|
116
|
+
let lastScrollTop = viewport.scrollTop;
|
|
117
|
+
let spacerHeight = 0;
|
|
118
|
+
/** A pin whose message hasn't rendered yet. */
|
|
119
|
+
let pendingPinId;
|
|
120
|
+
let pinnedId;
|
|
121
|
+
let pinned = null;
|
|
122
|
+
/** Keeps the pinned message at the top until the reader scrolls. */
|
|
123
|
+
let holdingPin = false;
|
|
124
|
+
/** The first visible message and its offset within the scrolled content. */
|
|
125
|
+
let anchor = null;
|
|
126
|
+
/** Keeps a pinned message clear of the top fade. */
|
|
127
|
+
const pinInset = parseFloat(getComputedStyle(viewport).scrollPaddingTop) || 0;
|
|
128
|
+
function offsetTop(element) {
|
|
129
|
+
return element.getBoundingClientRect().top - viewport.getBoundingClientRect().top + viewport.scrollTop;
|
|
130
|
+
}
|
|
131
|
+
/** Distance from the viewport's bottom edge to the end of the content, not counting the spacer. */
|
|
132
|
+
function distanceToEnd() {
|
|
133
|
+
return viewport.scrollHeight - spacerHeight - viewport.clientHeight - viewport.scrollTop;
|
|
134
|
+
}
|
|
135
|
+
function findMessage(id) {
|
|
136
|
+
return content.querySelector(`[${MESSAGE_ID_ATTRIBUTE}="${CSS.escape(id)}"]`);
|
|
137
|
+
}
|
|
138
|
+
function isVisible(element, viewportTop) {
|
|
139
|
+
const rect = element.getBoundingClientRect();
|
|
140
|
+
return rect.height > 0 && rect.bottom > viewportTop;
|
|
141
|
+
}
|
|
142
|
+
function firstVisible(viewportTop) {
|
|
143
|
+
const messages = content.querySelectorAll(MESSAGE_SELECTOR);
|
|
144
|
+
for (const element of messages.length > 0 ? messages : content.children) if (isVisible(element, viewportTop)) return element;
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
function setSpacer(height) {
|
|
148
|
+
if (height === spacerHeight) return;
|
|
149
|
+
spacerHeight = height;
|
|
150
|
+
spacer.style.height = height > 0 ? `${height}px` : "";
|
|
151
|
+
}
|
|
152
|
+
function tryPendingPin() {
|
|
153
|
+
if (pendingPinId === void 0) return;
|
|
154
|
+
const element = findMessage(pendingPinId);
|
|
155
|
+
if (!element) return;
|
|
156
|
+
pinnedId = pendingPinId;
|
|
157
|
+
pinned = element;
|
|
158
|
+
pendingPinId = void 0;
|
|
159
|
+
holdingPin = true;
|
|
160
|
+
following = false;
|
|
161
|
+
pendingPinObserver.disconnect();
|
|
162
|
+
}
|
|
163
|
+
function unpin() {
|
|
164
|
+
pinnedId = void 0;
|
|
165
|
+
pinned = null;
|
|
166
|
+
holdingPin = false;
|
|
167
|
+
setSpacer(0);
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Sizes the spacer so the pinned message can reach the top of the viewport,
|
|
171
|
+
* and holds it there until the reader scrolls. The spacer shrinks as the
|
|
172
|
+
* reply grows and is gone once the reply fills the viewport.
|
|
173
|
+
*/
|
|
174
|
+
function layoutPin() {
|
|
175
|
+
if (pinnedId === void 0) return;
|
|
176
|
+
if (!pinned?.isConnected || pinned.getAttribute(MESSAGE_ID_ATTRIBUTE) !== pinnedId) pinned = findMessage(pinnedId);
|
|
177
|
+
if (!pinned) {
|
|
178
|
+
unpin();
|
|
179
|
+
following = follow === "bottom" && distanceToEnd() <= FOLLOW_THRESHOLD;
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const target = Math.max(0, offsetTop(pinned) - pinInset);
|
|
183
|
+
const contentHeight = viewport.scrollHeight - spacerHeight;
|
|
184
|
+
setSpacer(Math.max(0, Math.ceil(target + viewport.clientHeight - contentHeight)));
|
|
185
|
+
if (holdingPin) viewport.scrollTop = target;
|
|
186
|
+
}
|
|
187
|
+
/** Moves with content that changed size above the first visible message. */
|
|
188
|
+
function restoreAnchor() {
|
|
189
|
+
if (!anchor?.element.isConnected) return;
|
|
190
|
+
const shift = offsetTop(anchor.element) - anchor.top;
|
|
191
|
+
if (Math.abs(shift) >= 1) viewport.scrollTop += shift;
|
|
192
|
+
}
|
|
193
|
+
function snapshotAnchor(rescan) {
|
|
194
|
+
if (following) {
|
|
195
|
+
anchor = null;
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const viewportTop = viewport.getBoundingClientRect().top;
|
|
199
|
+
let element = rescan ? null : anchor?.element;
|
|
200
|
+
if (!element?.isConnected || !isVisible(element, viewportTop)) element = firstVisible(viewportTop);
|
|
201
|
+
anchor = element ? {
|
|
202
|
+
element,
|
|
203
|
+
top: offsetTop(element)
|
|
204
|
+
} : null;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Records where the reader is after a scroll event, a resize, or a
|
|
208
|
+
* reposition the component made itself. Only a scroll event can be the
|
|
209
|
+
* reader's own movement: `lastScrollTop` is synced after every scroll the
|
|
210
|
+
* component makes, so the events those scrolls fire read as no movement.
|
|
211
|
+
*/
|
|
212
|
+
function update(source) {
|
|
213
|
+
const { scrollTop } = viewport;
|
|
214
|
+
const atEnd = distanceToEnd() <= FOLLOW_THRESHOLD;
|
|
215
|
+
const clamped = scrollTop < lastScrollTop && viewport.scrollHeight - viewport.clientHeight - scrollTop <= 1;
|
|
216
|
+
if (pinnedId !== void 0) {
|
|
217
|
+
if (source === "scroll" && scrollTop !== lastScrollTop && !clamped) {
|
|
218
|
+
holdingPin = false;
|
|
219
|
+
if (scrollTop > lastScrollTop && atEnd && spacerHeight === 0) {
|
|
220
|
+
unpin();
|
|
221
|
+
following = follow === "bottom";
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
} else if (follow === "bottom") following = atEnd || following && scrollTop >= lastScrollTop;
|
|
225
|
+
lastScrollTop = scrollTop;
|
|
226
|
+
onShowJumpChange(!following && !atEnd);
|
|
227
|
+
snapshotAnchor(source !== "resize");
|
|
228
|
+
}
|
|
229
|
+
const handleScroll = () => update("scroll");
|
|
230
|
+
function relayout() {
|
|
231
|
+
tryPendingPin();
|
|
232
|
+
layoutPin();
|
|
233
|
+
if (following) viewport.scrollTop = viewport.scrollHeight;
|
|
234
|
+
else if (!holdingPin) restoreAnchor();
|
|
235
|
+
update("resize");
|
|
236
|
+
}
|
|
237
|
+
const observer = new ResizeObserver(relayout);
|
|
238
|
+
const pendingPinObserver = new MutationObserver(() => {
|
|
239
|
+
if (pendingPinId !== void 0 && findMessage(pendingPinId)) relayout();
|
|
240
|
+
});
|
|
241
|
+
observer.observe(viewport);
|
|
242
|
+
observer.observe(content);
|
|
243
|
+
viewport.addEventListener("scroll", handleScroll, { passive: true });
|
|
244
|
+
return {
|
|
245
|
+
setFollow(nextFollow) {
|
|
246
|
+
const isFirst = follow === void 0;
|
|
247
|
+
follow = nextFollow;
|
|
248
|
+
if (pinnedId === void 0) {
|
|
249
|
+
following = nextFollow === "bottom" && (isFirst || distanceToEnd() <= FOLLOW_THRESHOLD);
|
|
250
|
+
if (following) viewport.scrollTop = viewport.scrollHeight;
|
|
251
|
+
}
|
|
252
|
+
update("reposition");
|
|
253
|
+
},
|
|
254
|
+
pin(id) {
|
|
255
|
+
pendingPinId = id;
|
|
256
|
+
tryPendingPin();
|
|
257
|
+
if (pendingPinId !== void 0) pendingPinObserver.observe(content, {
|
|
258
|
+
childList: true,
|
|
259
|
+
subtree: true
|
|
260
|
+
});
|
|
261
|
+
layoutPin();
|
|
262
|
+
update("reposition");
|
|
263
|
+
},
|
|
264
|
+
jumpToLatest() {
|
|
265
|
+
pendingPinId = void 0;
|
|
266
|
+
pendingPinObserver.disconnect();
|
|
267
|
+
unpin();
|
|
268
|
+
following = follow === "bottom";
|
|
269
|
+
viewport.scrollTop = viewport.scrollHeight;
|
|
270
|
+
update("reposition");
|
|
271
|
+
},
|
|
272
|
+
disconnect() {
|
|
273
|
+
observer.disconnect();
|
|
274
|
+
pendingPinObserver.disconnect();
|
|
275
|
+
viewport.removeEventListener("scroll", handleScroll);
|
|
276
|
+
setSpacer(0);
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
112
280
|
//#endregion
|
|
113
281
|
export { ChatConversation };
|
|
114
282
|
|