@langchain/macaw-components 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/catalog.json +826 -556
  2. package/dist/components/ChatComposer/ChatComposer.d.ts +31 -0
  3. package/dist/components/ChatComposer/ChatComposer.js +142 -0
  4. package/dist/components/ChatComposer/ChatComposer.js.map +1 -0
  5. package/dist/components/ChatComposer/ChatComposerAttachments.d.ts +17 -0
  6. package/dist/components/ChatComposer/ChatComposerAttachments.js +117 -0
  7. package/dist/components/ChatComposer/ChatComposerAttachments.js.map +1 -0
  8. package/dist/components/ChatComposer/ChatComposerCodeBlock.d.ts +2 -0
  9. package/dist/components/ChatComposer/ChatComposerCodeBlock.js +100 -0
  10. package/dist/components/ChatComposer/ChatComposerCodeBlock.js.map +1 -0
  11. package/dist/components/ChatComposer/ChatComposerCodeBlockAdapter.d.ts +19 -0
  12. package/dist/components/ChatComposer/ChatComposerCodeBlockAdapter.js +107 -0
  13. package/dist/components/ChatComposer/ChatComposerCodeBlockAdapter.js.map +1 -0
  14. package/dist/components/ChatComposer/ChatComposerCodeBlockView.d.ts +5 -0
  15. package/dist/components/ChatComposer/ChatComposerCodeBlockView.js +104 -0
  16. package/dist/components/ChatComposer/ChatComposerCodeBlockView.js.map +1 -0
  17. package/dist/components/ChatComposer/ChatComposerContext.d.ts +15 -0
  18. package/dist/components/ChatComposer/ChatComposerContext.js +16 -0
  19. package/dist/components/ChatComposer/ChatComposerContext.js.map +1 -0
  20. package/dist/components/ChatComposer/ChatComposerInput.d.ts +19 -0
  21. package/dist/components/ChatComposer/ChatComposerInput.js +38 -0
  22. package/dist/components/ChatComposer/ChatComposerInput.js.map +1 -0
  23. package/dist/components/ChatComposer/ChatComposerModelSelect.d.ts +3 -0
  24. package/dist/components/ChatComposer/ChatComposerModelSelect.js +56 -0
  25. package/dist/components/ChatComposer/ChatComposerModelSelect.js.map +1 -0
  26. package/dist/components/ChatComposer/ChatComposerPlainInput.d.ts +8 -0
  27. package/dist/components/ChatComposer/ChatComposerPlainInput.js +48 -0
  28. package/dist/components/ChatComposer/ChatComposerPlainInput.js.map +1 -0
  29. package/dist/components/ChatComposer/ChatComposerRichInput.d.ts +7 -0
  30. package/dist/components/ChatComposer/ChatComposerRichInput.js +53 -0
  31. package/dist/components/ChatComposer/ChatComposerRichInput.js.map +1 -0
  32. package/dist/components/ChatComposer/index.d.ts +10 -0
  33. package/dist/components/ChatComposer/index.js +6 -0
  34. package/dist/components/ChatComposer/useChatComposerEditor.d.ts +21 -0
  35. package/dist/components/ChatComposer/useChatComposerEditor.js +113 -0
  36. package/dist/components/ChatComposer/useChatComposerEditor.js.map +1 -0
  37. package/dist/components/ChatMessage/ChatMessage.js +1 -1
  38. package/dist/components/ChatState/ChatState.d.ts +16 -0
  39. package/dist/components/ChatState/ChatState.js +96 -0
  40. package/dist/components/ChatState/ChatState.js.map +1 -0
  41. package/dist/components/ChatState/ChatStateTimer.d.ts +11 -0
  42. package/dist/components/ChatState/ChatStateTimer.js +57 -0
  43. package/dist/components/ChatState/ChatStateTimer.js.map +1 -0
  44. package/dist/components/ChatState/index.d.ts +2 -0
  45. package/dist/components/ChatState/index.js +2 -0
  46. package/dist/components/ChatToolCall/ChatToolCall.d.ts +23 -0
  47. package/dist/components/ChatToolCall/ChatToolCall.js +98 -0
  48. package/dist/components/ChatToolCall/ChatToolCall.js.map +1 -0
  49. package/dist/components/ChatToolCall/ChatToolCall.types.d.ts +10 -0
  50. package/dist/components/ChatToolCall/ChatToolCall.types.js +0 -0
  51. package/dist/components/ChatToolCall/ChatToolCall.value.d.ts +2 -0
  52. package/dist/components/ChatToolCall/ChatToolCall.value.js +82 -0
  53. package/dist/components/ChatToolCall/ChatToolCall.value.js.map +1 -0
  54. package/dist/components/ChatToolCall/ChatToolCallAccordion.d.ts +17 -0
  55. package/dist/components/ChatToolCall/ChatToolCallAccordion.js +56 -0
  56. package/dist/components/ChatToolCall/ChatToolCallAccordion.js.map +1 -0
  57. package/dist/components/ChatToolCall/ChatToolCallDetails.d.ts +4 -0
  58. package/dist/components/ChatToolCall/ChatToolCallDetails.js +66 -0
  59. package/dist/components/ChatToolCall/ChatToolCallDetails.js.map +1 -0
  60. package/dist/components/ChatToolCall/ChatToolCallGroup.d.ts +11 -0
  61. package/dist/components/ChatToolCall/ChatToolCallGroup.js +63 -0
  62. package/dist/components/ChatToolCall/ChatToolCallGroup.js.map +1 -0
  63. package/dist/components/ChatToolCall/ChatToolCallReasoning.d.ts +18 -0
  64. package/dist/components/ChatToolCall/ChatToolCallReasoning.js +45 -0
  65. package/dist/components/ChatToolCall/ChatToolCallReasoning.js.map +1 -0
  66. package/dist/components/ChatToolCall/ChatToolCallStatusRow.d.ts +11 -0
  67. package/dist/components/ChatToolCall/ChatToolCallStatusRow.js +36 -0
  68. package/dist/components/ChatToolCall/ChatToolCallStatusRow.js.map +1 -0
  69. package/dist/components/ChatToolCall/index.d.ts +7 -0
  70. package/dist/components/ChatToolCall/index.js +4 -0
  71. package/dist/components/Code/CodeLite.js +1 -1
  72. package/dist/components/Code/index.js +7 -8
  73. package/dist/components/Code/index.js.map +1 -1
  74. package/dist/components/Input/Input.js +1 -1
  75. package/dist/components/Select/Select.d.ts +5 -0
  76. package/dist/components/Select/Select.js +2 -1
  77. package/dist/components/Select/Select.js.map +1 -1
  78. package/dist/components/TextWithLinks.js +1 -1
  79. package/dist/components/index.d.ts +2 -0
  80. package/dist/components/index.js +7 -2
  81. package/dist/components.css +2 -0
  82. package/dist/icons/LongTailPhosphorIcons.js +1 -1
  83. package/dist/icons/WeightedPhosphorIcons.js +1 -1
  84. package/dist/index.js +7 -2
  85. package/dist/utilities.css +1 -1
  86. package/dist/utils/componentUtils.d.ts +2 -0
  87. package/dist/utils/componentUtils.js +8 -0
  88. package/dist/utils/componentUtils.js.map +1 -0
  89. package/docs/CHAT.md +31 -0
  90. package/docs/DESIGN.md +44 -0
  91. package/package.json +29 -2
@@ -0,0 +1,31 @@
1
+ import type { ComponentPropsWithRef, ReactNode } from 'react';
2
+ import type { IconButtonProps } from '../IconButton/index.js';
3
+ export type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';
4
+ export type ChatComposerProps = ComponentPropsWithRef<'form'> & {
5
+ /** Supplementary content attached above the editor, inside the composer form. */
6
+ drawer?: ReactNode;
7
+ /**
8
+ * Drawer surface color. Color alone doesn't convey severity, so the drawer
9
+ * content should also say it in text or with an icon.
10
+ */
11
+ drawerIntent?: ChatComposerDrawerIntent;
12
+ disabled?: boolean;
13
+ submitDisabled?: boolean;
14
+ onFilesSelected?: (files: File[]) => void;
15
+ } & ({
16
+ action?: 'send' | 'sending';
17
+ onStop?: never;
18
+ } | {
19
+ action: 'stop';
20
+ onStop: () => void;
21
+ });
22
+ 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;
23
+ export interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {
24
+ modelSelector?: ReactNode;
25
+ actions?: ReactNode;
26
+ }
27
+ export declare function ChatComposerToolbar({ children, modelSelector, actions, className, ...props }: ChatComposerToolbarProps): import("react").JSX.Element;
28
+ export type ChatComposerActionProps = Omit<IconButtonProps, 'icon' | 'type' | 'onClick' | 'asChild' | 'label' | 'loading'> & {
29
+ label?: string;
30
+ };
31
+ export declare function ChatComposerAction({ disabled, label, ...props }: ChatComposerActionProps): import("react").JSX.Element;
@@ -0,0 +1,142 @@
1
+ import { cn } from "../../utils/cn.js";
2
+ import { IconButton } from "../IconButton/IconButton.js";
3
+ import { mergeRefs } from "../../utils/merge-refs.js";
4
+ import { ChatComposerContext, useChatComposerContext } from "./ChatComposerContext.js";
5
+ import { useRef, useState } from "react";
6
+ import { ArrowUpIcon } from "@phosphor-icons/react/dist/ssr/ArrowUp";
7
+ import { jsx, jsxs } from "react/jsx-runtime";
8
+ import { StopIcon } from "@phosphor-icons/react/dist/ssr/Stop";
9
+ //#region packages/components/src/components/ChatComposer/ChatComposer.tsx
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"
15
+ };
16
+ function isAttachmentTargetBlocked(target) {
17
+ return target instanceof Element && target.closest(":disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]") !== null;
18
+ }
19
+ function reportFieldsetValidity(fieldset) {
20
+ for (const element of fieldset?.elements ?? []) if ((element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement) && !element.reportValidity()) return false;
21
+ return true;
22
+ }
23
+ function ChatComposer({ children, drawer, drawerIntent = "neutral", className, ref, disabled = false, submitDisabled = false, action = "send", onStop, onSubmit, onFilesSelected, onDragOver, onDragLeave, onDropCapture, onPasteCapture, noValidate, ...props }) {
24
+ const formRef = useRef(null);
25
+ const [isDropTarget, setIsDropTarget] = useState(false);
26
+ const canSubmit = !disabled && !submitDisabled && action === "send" && !!onSubmit;
27
+ const hasDrawer = Boolean(drawer);
28
+ const fieldsetRef = useRef(null);
29
+ const inputFocusRef = useRef(null);
30
+ const validatesFieldsetOnly = noValidate === void 0 && hasDrawer;
31
+ return /* @__PURE__ */ jsx(ChatComposerContext.Provider, {
32
+ value: {
33
+ disabled,
34
+ canSubmit,
35
+ action,
36
+ onStop,
37
+ onFilesSelected,
38
+ inputFocusRef,
39
+ submit: onSubmit ? () => {
40
+ if (canSubmit) formRef.current?.requestSubmit();
41
+ } : void 0
42
+ },
43
+ children: /* @__PURE__ */ jsxs("form", {
44
+ ...props,
45
+ ref: mergeRefs([formRef, ref]),
46
+ noValidate: noValidate ?? hasDrawer,
47
+ className: cn("isolate w-full min-w-0 @container/composer", className),
48
+ onSubmit: (event) => {
49
+ event.preventDefault();
50
+ if (!canSubmit) return;
51
+ if (validatesFieldsetOnly && !reportFieldsetValidity(fieldsetRef.current)) return;
52
+ onSubmit?.(event);
53
+ },
54
+ onDragOver: (event) => {
55
+ onDragOver?.(event);
56
+ if (event.defaultPrevented || !onFilesSelected) return;
57
+ if (!event.dataTransfer.types.includes("Files")) return;
58
+ event.preventDefault();
59
+ const canAttach = !disabled && !isAttachmentTargetBlocked(event.target);
60
+ event.dataTransfer.dropEffect = canAttach ? "copy" : "none";
61
+ setIsDropTarget(canAttach);
62
+ },
63
+ onDragLeave: (event) => {
64
+ onDragLeave?.(event);
65
+ if (!(event.relatedTarget instanceof Node) || !event.currentTarget.contains(event.relatedTarget)) setIsDropTarget(false);
66
+ },
67
+ onDropCapture: (event) => {
68
+ onDropCapture?.(event);
69
+ setIsDropTarget(false);
70
+ if (event.defaultPrevented || !onFilesSelected) return;
71
+ const files = Array.from(event.dataTransfer.files);
72
+ if (!files.length) return;
73
+ event.preventDefault();
74
+ if (!disabled && !isAttachmentTargetBlocked(event.target)) onFilesSelected(files);
75
+ },
76
+ onPasteCapture: (event) => {
77
+ onPasteCapture?.(event);
78
+ if (event.defaultPrevented || !onFilesSelected) return;
79
+ const files = Array.from(event.clipboardData.files);
80
+ if (!files.length) return;
81
+ if (disabled || isAttachmentTargetBlocked(event.target)) {
82
+ event.preventDefault();
83
+ return;
84
+ }
85
+ if (!event.clipboardData.getData("text/plain")) event.preventDefault();
86
+ onFilesSelected(files);
87
+ },
88
+ children: [hasDrawer && /* @__PURE__ */ jsx("fieldset", {
89
+ disabled,
90
+ className: cn("mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 overflow-y-auto overscroll-contain rounded-t-xl 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
+ children: drawer
92
+ }), /* @__PURE__ */ jsx("fieldset", {
93
+ ref: fieldsetRef,
94
+ disabled,
95
+ className: cn("relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-xl 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
+ children
97
+ })]
98
+ })
99
+ });
100
+ }
101
+ function ChatComposerToolbar({ children, modelSelector, actions = /* @__PURE__ */ jsx(ChatComposerAction, {}), className, ...props }) {
102
+ return /* @__PURE__ */ jsxs("div", {
103
+ ...props,
104
+ className: cn("flex min-w-0 items-center gap-space-2", className),
105
+ children: [/* @__PURE__ */ jsxs("div", {
106
+ className: "flex min-w-0 flex-1 flex-wrap items-center gap-space-1 @[440px]/composer:gap-space-2",
107
+ children: [children, modelSelector != null && /* @__PURE__ */ jsx("div", {
108
+ className: "min-w-0 max-w-full [&>*]:max-w-full",
109
+ children: modelSelector
110
+ })]
111
+ }), /* @__PURE__ */ jsx("div", {
112
+ className: "flex shrink-0 items-center gap-space-1",
113
+ children: actions
114
+ })]
115
+ });
116
+ }
117
+ var ACTION_LABELS = {
118
+ send: "Send message",
119
+ sending: "Sending message",
120
+ stop: "Stop response"
121
+ };
122
+ function ChatComposerAction({ disabled, label, ...props }) {
123
+ const composer = useChatComposerContext();
124
+ const isStop = composer.action === "stop";
125
+ return /* @__PURE__ */ jsx(IconButton, {
126
+ size: "sm",
127
+ round: true,
128
+ color: "primary",
129
+ iconWeight: "regular",
130
+ ...props,
131
+ type: isStop ? "button" : "submit",
132
+ icon: isStop ? StopIcon : ArrowUpIcon,
133
+ label: label ?? ACTION_LABELS[composer.action],
134
+ disabled: composer.disabled || disabled || !isStop && !composer.canSubmit,
135
+ loading: composer.action === "sending",
136
+ onClick: isStop ? composer.onStop : void 0
137
+ });
138
+ }
139
+ //#endregion
140
+ export { ChatComposer, ChatComposerAction, ChatComposerToolbar };
141
+
142
+ //# sourceMappingURL=ChatComposer.js.map
@@ -0,0 +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 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-xl 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 disabled={disabled}\n className={cn(\n 'relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-xl 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 disabled={\n composer.disabled || disabled || (!isStop && !composer.canSubmit)\n }\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;AAqBA,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ACE,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;EACvC,UACE,SAAS,YAAY,YAAa,CAAC,UAAU,CAAC,SAAS;EAEzD,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,SAAS,SAAS,KAAA;CACrC,CAAA;AAEL"}
@@ -0,0 +1,17 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { AttachmentProps, AttachmentListProps } from '../Attachment/index.js';
3
+ import type { IconButtonProps } from '../IconButton/index.js';
4
+ export interface ChatComposerAttachmentMenuProps {
5
+ accept?: string;
6
+ size?: IconButtonProps['size'];
7
+ multiple?: boolean;
8
+ disabled?: boolean;
9
+ label?: string;
10
+ children?: ReactNode;
11
+ }
12
+ export declare function ChatComposerAttachmentMenu({ accept, size, multiple, disabled, label, children, }: ChatComposerAttachmentMenuProps): import("react").JSX.Element;
13
+ export interface ChatComposerAttachmentsProps extends AttachmentListProps, Pick<AttachmentProps, 'size' | 'variant'> {
14
+ }
15
+ export declare function ChatComposerAttachments({ className, layout, size, variant, ...props }: ChatComposerAttachmentsProps): import("react").JSX.Element;
16
+ export type ChatComposerAttachmentProps = AttachmentProps;
17
+ export declare function ChatComposerAttachment({ disabled, size, variant, ...props }: ChatComposerAttachmentProps): import("react").JSX.Element;
@@ -0,0 +1,117 @@
1
+ import { cn } from "../../utils/cn.js";
2
+ import { Text } from "../Text/Text.js";
3
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "../DropdownMenu/DropdownMenu.js";
4
+ import { IconButton } from "../IconButton/IconButton.js";
5
+ import { Attachment } from "../Attachment/Attachment.js";
6
+ import { AttachmentList } from "../Attachment/AttachmentList.js";
7
+ import { useChatComposerContext } from "./ChatComposerContext.js";
8
+ import { createContext, useContext, useRef, useState } from "react";
9
+ import { PlusIcon } from "@phosphor-icons/react/dist/ssr/Plus";
10
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
11
+ import { PaperclipIcon } from "@phosphor-icons/react/dist/ssr/Paperclip";
12
+ //#region packages/components/src/components/ChatComposer/ChatComposerAttachments.tsx
13
+ function ChatComposerAttachmentMenu({ accept, size = "sm", multiple = true, disabled = false, label = "Add attachments", children }) {
14
+ const composer = useChatComposerContext();
15
+ const fileInputRef = useRef(null);
16
+ const isDisabled = composer.disabled || disabled;
17
+ const [menuOpen, setMenuOpen] = useState(false);
18
+ const [tooltipOpen, setTooltipOpen] = useState(false);
19
+ const pointerOverTrigger = useRef(false);
20
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsxs(DropdownMenu, {
21
+ modal: false,
22
+ open: menuOpen,
23
+ onOpenChange: (open) => {
24
+ setMenuOpen(open);
25
+ setTooltipOpen(false);
26
+ },
27
+ children: [/* @__PURE__ */ jsx(DropdownMenuTrigger, {
28
+ asChild: true,
29
+ disabled: isDisabled,
30
+ children: /* @__PURE__ */ jsx(IconButton, {
31
+ type: "button",
32
+ icon: PlusIcon,
33
+ iconWeight: "regular",
34
+ label,
35
+ size,
36
+ color: "secondary",
37
+ variant: "plain",
38
+ disabled: isDisabled,
39
+ onPointerEnter: () => {
40
+ pointerOverTrigger.current = true;
41
+ },
42
+ onPointerLeave: () => {
43
+ pointerOverTrigger.current = false;
44
+ },
45
+ tooltipProps: {
46
+ open: tooltipOpen,
47
+ onOpenChange: (open) => setTooltipOpen(open && pointerOverTrigger.current && !menuOpen)
48
+ }
49
+ })
50
+ }), /* @__PURE__ */ jsxs(DropdownMenuContent, {
51
+ side: "top",
52
+ align: "start",
53
+ collisionPadding: 16,
54
+ className: "max-w-[var(--radix-dropdown-menu-content-available-width)]",
55
+ children: [/* @__PURE__ */ jsxs(DropdownMenuItem, {
56
+ disabled: isDisabled || !composer.onFilesSelected,
57
+ className: "gap-space-2",
58
+ onSelect: () => {
59
+ if (!isDisabled) fileInputRef.current?.click();
60
+ },
61
+ children: [/* @__PURE__ */ jsx(PaperclipIcon, {
62
+ size: 16,
63
+ weight: "regular",
64
+ "aria-hidden": true
65
+ }), /* @__PURE__ */ jsx(Text, {
66
+ as: "span",
67
+ variant: "sm",
68
+ children: "Upload files"
69
+ })]
70
+ }), children]
71
+ })]
72
+ }), /* @__PURE__ */ jsx("input", {
73
+ ref: fileInputRef,
74
+ type: "file",
75
+ "aria-label": "Upload files",
76
+ className: "hidden",
77
+ accept,
78
+ multiple,
79
+ disabled: isDisabled,
80
+ onChange: (event) => {
81
+ const files = Array.from(event.currentTarget.files ?? []);
82
+ event.currentTarget.value = "";
83
+ if (!isDisabled && files.length) composer.onFilesSelected?.(files);
84
+ }
85
+ })] });
86
+ }
87
+ var AttachmentAppearanceContext = createContext({
88
+ size: "md",
89
+ variant: "file"
90
+ });
91
+ function ChatComposerAttachments({ className, layout = "scroll", size = "md", variant = "file", ...props }) {
92
+ return /* @__PURE__ */ jsx(AttachmentAppearanceContext.Provider, {
93
+ value: {
94
+ size,
95
+ variant
96
+ },
97
+ children: /* @__PURE__ */ jsx(AttachmentList, {
98
+ ...props,
99
+ layout,
100
+ className: cn("no-scrollbar scroll-mask-l scroll-mask-r", className)
101
+ })
102
+ });
103
+ }
104
+ function ChatComposerAttachment({ disabled, size, variant, ...props }) {
105
+ const composer = useChatComposerContext();
106
+ const appearance = useContext(AttachmentAppearanceContext);
107
+ return /* @__PURE__ */ jsx(Attachment, {
108
+ ...props,
109
+ size: size ?? appearance.size,
110
+ variant: variant ?? appearance.variant,
111
+ disabled: composer.disabled || disabled
112
+ });
113
+ }
114
+ //#endregion
115
+ export { ChatComposerAttachment, ChatComposerAttachmentMenu, ChatComposerAttachments };
116
+
117
+ //# sourceMappingURL=ChatComposerAttachments.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatComposerAttachments.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerAttachments.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { createContext, useContext, useRef, useState } from 'react';\n\nimport { PaperclipIcon } from '@phosphor-icons/react/dist/ssr/Paperclip';\nimport { PlusIcon } from '@phosphor-icons/react/dist/ssr/Plus';\n\nimport { cn } from '../../utils/cn';\nimport { Attachment, AttachmentList } from '../Attachment';\nimport type { AttachmentProps, AttachmentListProps } from '../Attachment';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from '../DropdownMenu';\nimport { IconButton } from '../IconButton';\nimport type { IconButtonProps } from '../IconButton';\nimport { Text } from '../Text';\nimport { useChatComposerContext } from './ChatComposerContext';\n\nexport interface ChatComposerAttachmentMenuProps {\n accept?: string;\n size?: IconButtonProps['size'];\n multiple?: boolean;\n disabled?: boolean;\n label?: string;\n children?: ReactNode;\n}\n\nexport function ChatComposerAttachmentMenu({\n accept,\n size = 'sm',\n multiple = true,\n disabled = false,\n label = 'Add attachments',\n children,\n}: ChatComposerAttachmentMenuProps) {\n const composer = useChatComposerContext();\n const fileInputRef = useRef<HTMLInputElement>(null);\n const isDisabled = composer.disabled || disabled;\n const [menuOpen, setMenuOpen] = useState(false);\n const [tooltipOpen, setTooltipOpen] = useState(false);\n const pointerOverTrigger = useRef(false);\n\n return (\n <>\n {/* Non-modal like the model select, so an outside click reaches its\n target instead of only closing the menu. */}\n <DropdownMenu\n modal={false}\n open={menuOpen}\n onOpenChange={(open) => {\n setMenuOpen(open);\n setTooltipOpen(false);\n }}\n >\n {/* Radix opens menus on pointerdown, which disabled buttons still get. */}\n <DropdownMenuTrigger asChild disabled={isDisabled}>\n <IconButton\n type=\"button\"\n icon={PlusIcon}\n iconWeight=\"regular\"\n label={label}\n size={size}\n color=\"secondary\"\n variant=\"plain\"\n disabled={isDisabled}\n onPointerEnter={() => {\n pointerOverTrigger.current = true;\n }}\n onPointerLeave={() => {\n pointerOverTrigger.current = false;\n }}\n // Hover only, and never over the open menu: Radix also opens\n // tooltips on focus, which the menu returns here when it closes.\n tooltipProps={{\n open: tooltipOpen,\n onOpenChange: (open) =>\n setTooltipOpen(open && pointerOverTrigger.current && !menuOpen),\n }}\n />\n </DropdownMenuTrigger>\n <DropdownMenuContent\n side=\"top\"\n align=\"start\"\n collisionPadding={16}\n className=\"max-w-[var(--radix-dropdown-menu-content-available-width)]\"\n >\n <DropdownMenuItem\n disabled={isDisabled || !composer.onFilesSelected}\n className=\"gap-space-2\"\n onSelect={() => {\n if (!isDisabled) fileInputRef.current?.click();\n }}\n >\n <PaperclipIcon size={16} weight=\"regular\" aria-hidden />\n <Text as=\"span\" variant=\"sm\">\n Upload files\n </Text>\n </DropdownMenuItem>\n {children}\n </DropdownMenuContent>\n </DropdownMenu>\n <input\n ref={fileInputRef}\n type=\"file\"\n aria-label=\"Upload files\"\n className=\"hidden\"\n accept={accept}\n multiple={multiple}\n disabled={isDisabled}\n onChange={(event) => {\n const files = Array.from(event.currentTarget.files ?? []);\n event.currentTarget.value = '';\n if (!isDisabled && files.length) composer.onFilesSelected?.(files);\n }}\n />\n </>\n );\n}\n\nconst AttachmentAppearanceContext = createContext<\n Pick<AttachmentProps, 'size' | 'variant'>\n>({\n size: 'md',\n variant: 'file',\n});\n\nexport interface ChatComposerAttachmentsProps\n extends AttachmentListProps, Pick<AttachmentProps, 'size' | 'variant'> {}\n\nexport function ChatComposerAttachments({\n className,\n layout = 'scroll',\n size = 'md',\n variant = 'file',\n ...props\n}: ChatComposerAttachmentsProps) {\n return (\n <AttachmentAppearanceContext.Provider value={{ size, variant }}>\n <AttachmentList\n {...props}\n layout={layout}\n className={cn('no-scrollbar scroll-mask-l scroll-mask-r', className)}\n />\n </AttachmentAppearanceContext.Provider>\n );\n}\n\nexport type ChatComposerAttachmentProps = AttachmentProps;\n\nexport function ChatComposerAttachment({\n disabled,\n size,\n variant,\n ...props\n}: ChatComposerAttachmentProps) {\n const composer = useChatComposerContext();\n const appearance = useContext(AttachmentAppearanceContext);\n return (\n <Attachment\n {...props}\n size={size ?? appearance.size}\n variant={variant ?? appearance.variant}\n disabled={composer.disabled || disabled}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;AA6BA,SAAgB,2BAA2B,EACzC,QACA,OAAO,MACP,WAAW,MACX,WAAW,OACX,QAAQ,mBACR,YACkC;CAClC,MAAM,WAAW,uBAAuB;CACxC,MAAM,eAAe,OAAyB,IAAI;CAClD,MAAM,aAAa,SAAS,YAAY;CACxC,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,aAAa,kBAAkB,SAAS,KAAK;CACpD,MAAM,qBAAqB,OAAO,KAAK;CAEvC,OACE,qBAAA,YAAA,EAAA,UAAA,CAGE,qBAAC,cAAD;EACE,OAAO;EACP,MAAM;EACN,eAAe,SAAS;GACtB,YAAY,IAAI;GAChB,eAAe,KAAK;EACtB;EANF,UAAA,CASE,oBAAC,qBAAD;GAAqB,SAAA;GAAQ,UAAU;GACrC,UAAA,oBAAC,YAAD;IACE,MAAK;IACL,MAAM;IACN,YAAW;IACJ;IACD;IACN,OAAM;IACN,SAAQ;IACR,UAAU;IACV,sBAAsB;KACpB,mBAAmB,UAAU;IAC/B;IACA,sBAAsB;KACpB,mBAAmB,UAAU;IAC/B;IAGA,cAAc;KACZ,MAAM;KACN,eA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ACJ,MAAM,QAAQ,WAAW;EACzB,SAAS,WAAW,WAAW;EAC/B,UAAU,SAAS,YAAY;CAChC,CAAA;AAEL"}
@@ -0,0 +1,2 @@
1
+ export declare const COMPOSER_CODE_FENCE: RegExp;
2
+ export declare const ChatComposerCodeBlock: import("@tiptap/core").Node<import("@tiptap/extension-code-block").CodeBlockOptions, any>;
@@ -0,0 +1,100 @@
1
+ import { ComposerCodeBlockAdapter } from "./ChatComposerCodeBlockAdapter.js";
2
+ import { ComposerCodeBlockView } from "./ChatComposerCodeBlockView.js";
3
+ import { jsx } from "react/jsx-runtime";
4
+ import { InputRule } from "@tiptap/core";
5
+ import CodeBlock from "@tiptap/extension-code-block";
6
+ import { Fragment as Fragment$1 } from "@tiptap/pm/model";
7
+ import { TextSelection } from "@tiptap/pm/state";
8
+ import { ReactNodeViewRenderer } from "@tiptap/react";
9
+ //#region packages/components/src/components/ChatComposer/ChatComposerCodeBlock.tsx
10
+ var COMPOSER_CODE_FENCE = /^(?:```|~~~)([\w+-]*)$/;
11
+ var renderComposerCodeBlock = (props) => {
12
+ const adapter = new ComposerCodeBlockAdapter(props.editor, props.getPos);
13
+ const nodeView = ReactNodeViewRenderer((nodeProps) => /* @__PURE__ */ jsx(ComposerCodeBlockView, {
14
+ ...nodeProps,
15
+ adapter
16
+ }))(props);
17
+ return {
18
+ dom: nodeView.dom,
19
+ contentDOM: null,
20
+ update: (node, decorations, innerDecorations) => {
21
+ const updated = nodeView.update?.(node, decorations, innerDecorations) ?? false;
22
+ if (updated) adapter.syncFromComposer();
23
+ return updated;
24
+ },
25
+ setSelection: () => adapter.focus(),
26
+ selectNode: () => nodeView.selectNode?.(),
27
+ deselectNode: () => nodeView.deselectNode?.(),
28
+ stopEvent: () => true,
29
+ ignoreMutation: () => true,
30
+ destroy: () => {
31
+ adapter.destroy();
32
+ nodeView.destroy?.();
33
+ }
34
+ };
35
+ };
36
+ var ChatComposerCodeBlock = CodeBlock.extend({
37
+ priority: 110,
38
+ addNodeView() {
39
+ return renderComposerCodeBlock;
40
+ },
41
+ addInputRules() {
42
+ return [new InputRule({
43
+ find: /(?:```|~~~)$/,
44
+ handler: ({ state, range }) => {
45
+ const { tr, selection } = state;
46
+ const $from = tr.doc.resolve(range.from);
47
+ const $to = tr.doc.resolve(range.to);
48
+ if (!this.editor.isEditable || !selection.empty || $from.parent.type.name !== "paragraph" || !$from.sameParent($to)) return null;
49
+ const paragraph = $from.parent;
50
+ let before = paragraph.content.cut(0, $from.parentOffset);
51
+ let after = paragraph.content.cut($to.parentOffset);
52
+ if (before.lastChild?.type.name === "hardBreak") before = before.cut(0, before.size - 1);
53
+ if (after.firstChild?.type.name === "hardBreak") after = after.cut(1);
54
+ const parent = $from.node(-1);
55
+ const index = $from.index(-1);
56
+ const prefix = before.size > 0 || parent.type.name === "listItem" && index === 0 ? [paragraph.copy(before)] : [];
57
+ const replacement = Fragment$1.fromArray([
58
+ ...prefix,
59
+ this.type.create({ language: "" }),
60
+ ...after.size > 0 ? [paragraph.copy(after)] : []
61
+ ]);
62
+ if (!parent.canReplace(index, index + 1, replacement)) return null;
63
+ const start = $from.before();
64
+ tr.replaceWith(start, $from.after(), replacement);
65
+ if (tr.doc.lastChild?.type === this.type) tr.insert(tr.doc.content.size, paragraph.type.create());
66
+ tr.setSelection(TextSelection.create(tr.doc, start + (prefix[0]?.nodeSize ?? 0) + 1));
67
+ tr.setStoredMarks([]);
68
+ }
69
+ }), ...this.parent?.() ?? []];
70
+ },
71
+ addKeyboardShortcuts() {
72
+ const inherited = this.parent?.();
73
+ return {
74
+ ...inherited,
75
+ "Shift-Enter": ({ editor }) => {
76
+ if (!editor.isEditable || editor.view.composing) return false;
77
+ return editor.commands.first(({ commands }) => [
78
+ () => commands.newlineInCode(),
79
+ () => commands.splitListItem("listItem"),
80
+ () => commands.createParagraphNear(),
81
+ () => commands.liftEmptyBlock(),
82
+ () => commands.splitBlock()
83
+ ]);
84
+ },
85
+ Enter: ({ editor }) => {
86
+ const { $from, empty } = editor.state.selection;
87
+ const fence = COMPOSER_CODE_FENCE.exec($from.parent.textContent);
88
+ if (empty && $from.parent.type.name === "paragraph" && $from.parentOffset === $from.parent.content.size && fence) return editor.chain().deleteRange({
89
+ from: $from.start(),
90
+ to: $from.end()
91
+ }).setCodeBlock({ language: fence[1] ?? "" }).run();
92
+ return inherited?.Enter?.({ editor }) ?? false;
93
+ }
94
+ };
95
+ }
96
+ });
97
+ //#endregion
98
+ export { COMPOSER_CODE_FENCE, ChatComposerCodeBlock };
99
+
100
+ //# sourceMappingURL=ChatComposerCodeBlock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatComposerCodeBlock.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerCodeBlock.tsx"],"sourcesContent":["import type { NodeViewRenderer } from '@tiptap/core';\nimport { InputRule } from '@tiptap/core';\nimport CodeBlock from '@tiptap/extension-code-block';\nimport { Fragment } from '@tiptap/pm/model';\nimport { TextSelection } from '@tiptap/pm/state';\nimport { ReactNodeViewRenderer } from '@tiptap/react';\n\nimport { ComposerCodeBlockAdapter } from './ChatComposerCodeBlockAdapter';\nimport { ComposerCodeBlockView } from './ChatComposerCodeBlockView';\n\nexport const COMPOSER_CODE_FENCE = /^(?:```|~~~)([\\w+-]*)$/;\n\nconst renderComposerCodeBlock: NodeViewRenderer = (props) => {\n const adapter = new ComposerCodeBlockAdapter(props.editor, props.getPos);\n const render = ReactNodeViewRenderer((nodeProps) => (\n <ComposerCodeBlockView {...nodeProps} adapter={adapter} />\n ));\n const nodeView = render(props);\n return {\n dom: nodeView.dom,\n // CodeMirror owns the editable DOM; Tiptap still owns the document/history.\n contentDOM: null,\n update: (node, decorations, innerDecorations) => {\n const updated =\n nodeView.update?.(node, decorations, innerDecorations) ?? false;\n if (updated) adapter.syncFromComposer();\n return updated;\n },\n setSelection: () => adapter.focus(),\n selectNode: () => nodeView.selectNode?.(),\n deselectNode: () => nodeView.deselectNode?.(),\n stopEvent: () => true,\n ignoreMutation: () => true,\n destroy: () => {\n adapter.destroy();\n nodeView.destroy?.();\n },\n };\n};\n\nexport const ChatComposerCodeBlock = CodeBlock.extend({\n priority: 110,\n addNodeView() {\n return renderComposerCodeBlock;\n },\n addInputRules() {\n return [\n new InputRule({\n find: /(?:```|~~~)$/,\n handler: ({ state, range }) => {\n const { tr, selection } = state;\n const $from = tr.doc.resolve(range.from);\n const $to = tr.doc.resolve(range.to);\n if (\n !this.editor.isEditable ||\n !selection.empty ||\n $from.parent.type.name !== 'paragraph' ||\n !$from.sameParent($to)\n ) {\n return null;\n }\n\n const paragraph = $from.parent;\n let before = paragraph.content.cut(0, $from.parentOffset);\n let after = paragraph.content.cut($to.parentOffset);\n // The code block itself supplies the line boundary beside a soft break.\n if (before.lastChild?.type.name === 'hardBreak') {\n before = before.cut(0, before.size - 1);\n }\n if (after.firstChild?.type.name === 'hardBreak') {\n after = after.cut(1);\n }\n\n const parent = $from.node(-1);\n const index = $from.index(-1);\n // List items must start with a paragraph, even when it is empty.\n const keepBefore =\n before.size > 0 || (parent.type.name === 'listItem' && index === 0);\n const prefix = keepBefore ? [paragraph.copy(before)] : [];\n const replacement = Fragment.fromArray([\n ...prefix,\n this.type.create({ language: '' }),\n ...(after.size > 0 ? [paragraph.copy(after)] : []),\n ]);\n if (!parent.canReplace(index, index + 1, replacement)) return null;\n\n const start = $from.before();\n tr.replaceWith(start, $from.after(), replacement);\n // A separate trailing-node transaction would clear input-rule undo.\n if (tr.doc.lastChild?.type === this.type) {\n tr.insert(tr.doc.content.size, paragraph.type.create());\n }\n tr.setSelection(\n TextSelection.create(tr.doc, start + (prefix[0]?.nodeSize ?? 0) + 1)\n );\n tr.setStoredMarks([]);\n },\n }),\n ...(this.parent?.() ?? []),\n ];\n },\n addKeyboardShortcuts() {\n const inherited = this.parent?.();\n return {\n ...inherited,\n 'Shift-Enter': ({ editor }) => {\n if (!editor.isEditable || editor.view.composing) return false;\n // Call editing commands directly: a synthetic Enter can submit the draft.\n return editor.commands.first(({ commands }) => [\n () => commands.newlineInCode(),\n () => commands.splitListItem('listItem'),\n () => commands.createParagraphNear(),\n () => commands.liftEmptyBlock(),\n () => commands.splitBlock(),\n ]);\n },\n Enter: ({ editor }) => {\n const { $from, empty } = editor.state.selection;\n const fence = COMPOSER_CODE_FENCE.exec($from.parent.textContent);\n if (\n empty &&\n $from.parent.type.name === 'paragraph' &&\n $from.parentOffset === $from.parent.content.size &&\n fence\n ) {\n return editor\n .chain()\n .deleteRange({ from: $from.start(), to: $from.end() })\n .setCodeBlock({ language: fence[1] ?? '' })\n .run();\n }\n return inherited?.Enter?.({ editor }) ?? false;\n },\n };\n },\n});\n"],"mappings":";;;;;;;;;AAUA,IAAa,sBAAsB;AAEnC,IAAM,2BAA6C,UAAU;CAC3D,MAAM,UAAU,IAAI,yBAAyB,MAAM,QAAQ,MAAM,MAAM;CAIvE,MAAM,WAHS,uBAAuB,cACpC,oBAAC,uBAAD;EAAuB,GAAI;EAAoB;CAAU,CAAA,CAE1C,CAAA,CAAO,KAAK;CAC7B,OAAO;EACL,KAAK,SAAS;EAEd,YAAY;EACZ,SAAS,MAAM,aAAa,qBAAqB;GAC/C,MAAM,UACJ,SAAS,SAAS,MAAM,aAAa,gBAAgB,KAAK;GAC5D,IAAI,SAAS,QAAQ,iBAAiB;GACtC,OAAO;EACT;EACA,oBAAoB,QAAQ,MAAM;EAClC,kBAAkB,SAAS,aAAa;EACxC,oBAAoB,SAAS,eAAe;EAC5C,iBAAiB;EACjB,sBAAsB;EACtB,eAAe;GACb,QAAQ,QAAQ;GAChB,SAAS,UAAU;EACrB;CACF;AACF;AAEA,IAAa,wBAAwB,UAAU,OAAO;CACpD,UAAU;CACV,cAAc;EACZ,OAAO;CACT;CACA,gBAAgB;EACd,OAAO,CACL,IAAI,UAAU;GACZ,MAAM;GACN,UAAU,EAAE,OAAO,YAAY;IAC7B,MAAM,EAAE,IAAI,cAAc;IAC1B,MAAM,QAAQ,GAAG,IAAI,QAAQ,MAAM,IAAI;IACvC,MAA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CAC1B;CACF;CACA,uBAAuB;EACrB,MAAM,YAAY,KAAK,SAAS;EAChC,OAAO;GACL,GAAG;GACH,gBAAgB,EAAE,aAAa;IAC7B,IAAI,CAAC,OAAO,cAAc,OAAO,KAAK,WAAW,OAAO;IAExD,OAAO,OAAO,SAAS,OAAO,EAAE,eAAe;WACvC,SAAS,cAAc;WACvB,SAAS,cAAc,UAAU;WACjC,SAAS,oBAAoB;WAC7B,SAAS,eAAe;WACxB,SAAS,WAAW;IAC5B,CAAC;GACH;GACA,QAAQ,EAAE,aAAa;IACrB,MAAM,EAAE,OAAO,UAAU,OAAO,MAAM;IACtC,MAAM,QAAQ,oBAAoB,KAAK,MAAM,OAAO,WAAW;IAC/D,IACE,SACA,MAAM,OAAO,KAAK,SAAS,eAC3B,MAAM,iBAAiB,MAAM,OAAO,QAAQ,QAC5C,OAEA,OAAO,OACJ,MAAM,CAAC,CACP,YAAY;KAAE,MAAM,MAAM,MAAM;KAAG,IAAI,MAAM,IAAI;IAAE,CAAC,CAAC,CACrD,aAAa,EAAE,UAAU,MAAM,MAAM,GAAG,CAAC,CAAC,CAC1C,IAAI;IAET,OAAO,WAAW,QAAQ,EAAE,OAAO,CAAC,KAAK;GAC3C;EACF;CACF;AACF,CAAC"}
@@ -0,0 +1,19 @@
1
+ import type { EditorState } from '@codemirror/state';
2
+ import type { EditorView, ViewUpdate } from '@codemirror/view';
3
+ import type { Editor } from '@tiptap/core';
4
+ export declare function moveSelectionOutsideCodeBlock(editor: Editor, position: number, codeState: EditorState, key: string): boolean;
5
+ export declare function syncCodeToComposer(editor: Editor, position: number, update: Pick<ViewUpdate, 'startState' | 'state' | 'changes'>): void;
6
+ export declare class ComposerCodeBlockAdapter {
7
+ private editor;
8
+ private getPos;
9
+ view: EditorView | null;
10
+ private syncing;
11
+ private destroyed;
12
+ private pendingFocus;
13
+ constructor(editor: Editor, getPos: () => number | undefined);
14
+ attach(view: EditorView): void;
15
+ forwardUpdate: (update: ViewUpdate) => void;
16
+ focus(): void;
17
+ syncFromComposer(focus?: boolean): void;
18
+ destroy(): void;
19
+ }
@@ -0,0 +1,107 @@
1
+ import { Selection, TextSelection } from "@tiptap/pm/state";
2
+ //#region packages/components/src/components/ChatComposer/ChatComposerCodeBlockAdapter.ts
3
+ function moveSelectionOutsideCodeBlock(editor, position, codeState, key) {
4
+ const { head, empty } = codeState.selection.main;
5
+ if (editor.isDestroyed || !editor.isEditable || !empty) return false;
6
+ const node = editor.state.doc.nodeAt(position);
7
+ if (node?.type.name !== "codeBlock") return false;
8
+ const direction = head === 0 && (key === "ArrowLeft" || key === "ArrowUp") ? -1 : head === codeState.doc.length && (key === "ArrowRight" || key === "ArrowDown") ? 1 : 0;
9
+ if (!direction) return false;
10
+ const target = direction < 0 ? position : position + node.nodeSize;
11
+ const selection = Selection.near(editor.state.doc.resolve(target), direction);
12
+ if (selection.from > position && selection.to < position + node.nodeSize) {
13
+ if (direction < 0) return editor.chain().insertContentAt(position, { type: "paragraph" }).setTextSelection(position + 1).run();
14
+ return editor.commands.exitCode();
15
+ }
16
+ editor.view.dispatch(editor.state.tr.setSelection(selection).scrollIntoView());
17
+ return true;
18
+ }
19
+ function syncCodeToComposer(editor, position, update) {
20
+ if (editor.isDestroyed || !editor.isEditable) return;
21
+ const node = editor.state.doc.nodeAt(position);
22
+ if (node?.type.name !== "codeBlock" || node.textContent !== update.startState.doc.toString()) return;
23
+ const tr = editor.state.tr;
24
+ let offset = position + 1;
25
+ update.changes.iterChanges((from, to, _newFrom, _newTo, inserted) => {
26
+ tr.insertText(inserted.toString(), offset + from, offset + to);
27
+ offset += inserted.length - (to - from);
28
+ });
29
+ const { anchor, head } = update.state.selection.main;
30
+ const selection = TextSelection.create(tr.doc, position + 1 + anchor, position + 1 + head);
31
+ if (tr.docChanged || !editor.state.selection.eq(selection)) editor.view.dispatch(tr.setSelection(selection));
32
+ }
33
+ var ComposerCodeBlockAdapter = class {
34
+ editor;
35
+ getPos;
36
+ view = null;
37
+ syncing = false;
38
+ destroyed = false;
39
+ pendingFocus = false;
40
+ constructor(editor, getPos) {
41
+ this.editor = editor;
42
+ this.getPos = getPos;
43
+ }
44
+ attach(view) {
45
+ if (this.destroyed) return;
46
+ this.view = view;
47
+ this.syncFromComposer(this.pendingFocus && this.editor.view.hasFocus());
48
+ this.pendingFocus = false;
49
+ }
50
+ forwardUpdate = (update) => {
51
+ if (this.syncing || this.destroyed || !update.view.hasFocus) return;
52
+ const position = this.getPos();
53
+ if (position === void 0) return;
54
+ this.syncing = true;
55
+ try {
56
+ syncCodeToComposer(this.editor, position, update);
57
+ } finally {
58
+ this.syncing = false;
59
+ }
60
+ };
61
+ focus() {
62
+ if (this.destroyed || this.editor.isDestroyed) return;
63
+ if (!this.view) {
64
+ this.pendingFocus = true;
65
+ return;
66
+ }
67
+ this.syncFromComposer(true);
68
+ }
69
+ syncFromComposer(focus = false) {
70
+ const view = this.view;
71
+ if (!view || this.syncing || this.destroyed || this.editor.isDestroyed) return;
72
+ const position = this.getPos();
73
+ if (position === void 0) return;
74
+ const node = this.editor.state.doc.nodeAt(position);
75
+ if (node?.type.name !== "codeBlock") return;
76
+ const { from, to, anchor, head } = this.editor.state.selection;
77
+ const inside = from > position && to < position + node.nodeSize;
78
+ const selection = inside ? {
79
+ anchor: anchor - position - 1,
80
+ head: head - position - 1
81
+ } : void 0;
82
+ const changed = view.state.doc.toString() !== node.textContent;
83
+ const selectionChanged = selection && (selection.anchor !== view.state.selection.main.anchor || selection.head !== view.state.selection.main.head);
84
+ this.syncing = true;
85
+ try {
86
+ if (changed || selectionChanged) view.dispatch({
87
+ changes: changed ? {
88
+ from: 0,
89
+ to: view.state.doc.length,
90
+ insert: node.textContent
91
+ } : void 0,
92
+ selection
93
+ });
94
+ if (focus && inside && this.editor.isEditable) view.focus();
95
+ } finally {
96
+ this.syncing = false;
97
+ }
98
+ }
99
+ destroy() {
100
+ this.destroyed = true;
101
+ this.view = null;
102
+ }
103
+ };
104
+ //#endregion
105
+ export { ComposerCodeBlockAdapter, moveSelectionOutsideCodeBlock, syncCodeToComposer };
106
+
107
+ //# sourceMappingURL=ChatComposerCodeBlockAdapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ChatComposerCodeBlockAdapter.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerCodeBlockAdapter.ts"],"sourcesContent":["import type { EditorState } from '@codemirror/state';\nimport type { EditorView, ViewUpdate } from '@codemirror/view';\nimport type { Editor } from '@tiptap/core';\nimport { Selection, TextSelection } from '@tiptap/pm/state';\n\nexport function moveSelectionOutsideCodeBlock(\n editor: Editor,\n position: number,\n codeState: EditorState,\n key: string\n) {\n const { head, empty } = codeState.selection.main;\n if (editor.isDestroyed || !editor.isEditable || !empty) return false;\n const node = editor.state.doc.nodeAt(position);\n if (node?.type.name !== 'codeBlock') return false;\n // Logical lines can wrap; let CodeMirror navigate until the document edge.\n const direction =\n head === 0 && (key === 'ArrowLeft' || key === 'ArrowUp')\n ? -1\n : head === codeState.doc.length &&\n (key === 'ArrowRight' || key === 'ArrowDown')\n ? 1\n : 0;\n if (!direction) return false;\n const target = direction < 0 ? position : position + node.nodeSize;\n const selection = Selection.near(editor.state.doc.resolve(target), direction);\n if (selection.from > position && selection.to < position + node.nodeSize) {\n if (direction < 0) {\n return editor\n .chain()\n .insertContentAt(position, { type: 'paragraph' })\n .setTextSelection(position + 1)\n .run();\n }\n return editor.commands.exitCode();\n }\n editor.view.dispatch(\n editor.state.tr.setSelection(selection).scrollIntoView()\n );\n return true;\n}\n\nexport function syncCodeToComposer(\n editor: Editor,\n position: number,\n update: Pick<ViewUpdate, 'startState' | 'state' | 'changes'>\n) {\n if (editor.isDestroyed || !editor.isEditable) return;\n const node = editor.state.doc.nodeAt(position);\n // Controlled replacements and undo can overtake a CodeMirror update.\n if (\n node?.type.name !== 'codeBlock' ||\n node.textContent !== update.startState.doc.toString()\n ) {\n return;\n }\n\n const tr = editor.state.tr;\n let offset = position + 1;\n update.changes.iterChanges((from, to, _newFrom, _newTo, inserted) => {\n tr.insertText(inserted.toString(), offset + from, offset + to);\n offset += inserted.length - (to - from);\n });\n const { anchor, head } = update.state.selection.main;\n const selection = TextSelection.create(\n tr.doc,\n position + 1 + anchor,\n position + 1 + head\n );\n if (tr.docChanged || !editor.state.selection.eq(selection)) {\n editor.view.dispatch(tr.setSelection(selection));\n }\n}\n\nexport class ComposerCodeBlockAdapter {\n view: EditorView | null = null;\n private syncing = false;\n private destroyed = false;\n private pendingFocus = false;\n\n constructor(\n private editor: Editor,\n private getPos: () => number | undefined\n ) {}\n\n attach(view: EditorView) {\n if (this.destroyed) return;\n this.view = view;\n this.syncFromComposer(this.pendingFocus && this.editor.view.hasFocus());\n this.pendingFocus = false;\n }\n\n forwardUpdate = (update: ViewUpdate) => {\n if (this.syncing || this.destroyed || !update.view.hasFocus) return;\n const position = this.getPos();\n if (position === undefined) return;\n this.syncing = true;\n try {\n syncCodeToComposer(this.editor, position, update);\n } finally {\n this.syncing = false;\n }\n };\n\n focus() {\n if (this.destroyed || this.editor.isDestroyed) return;\n if (!this.view) {\n this.pendingFocus = true;\n return;\n }\n this.syncFromComposer(true);\n }\n\n syncFromComposer(focus = false) {\n const view = this.view;\n if (!view || this.syncing || this.destroyed || this.editor.isDestroyed) {\n return;\n }\n const position = this.getPos();\n if (position === undefined) return;\n const node = this.editor.state.doc.nodeAt(position);\n if (node?.type.name !== 'codeBlock') return;\n const { from, to, anchor, head } = this.editor.state.selection;\n const inside = from > position && to < position + node.nodeSize;\n const selection = inside\n ? { anchor: anchor - position - 1, head: head - position - 1 }\n : undefined;\n const changed = view.state.doc.toString() !== node.textContent;\n const selectionChanged =\n selection &&\n (selection.anchor !== view.state.selection.main.anchor ||\n selection.head !== view.state.selection.main.head);\n\n this.syncing = true;\n try {\n if (changed || selectionChanged) {\n view.dispatch({\n changes: changed\n ? { from: 0, to: view.state.doc.length, insert: node.textContent }\n : undefined,\n selection,\n });\n }\n if (focus && inside && this.editor.isEditable) view.focus();\n } finally {\n this.syncing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AO,KAAK,OAAO,MAAM,IAAI,OAAO,QAAQ;EAClD,IAAI,MAAM,KAAK,SAAS,aAAa;EACrC,MAAM,EAAE,MAAM,IAAI,QAAQ,SAAS,KAAK,OAAO,MAAM;EACrD,MAAM,SAAS,OAAO,YAAY,KAAK,WAAW,KAAK;EACvD,MAAM,YAAY,SACd;GAAE,QAAQ,SAAS,WAAW;GAAG,MAAM,OAAO,WAAW;EAAE,IAC3D,KAAA;EACJ,MAAM,UAAU,KAAK,MAAM,IAAI,SAAS,MAAM,KAAK;EACnD,MAAM,mBACJ,cACC,UAAU,WAAW,KAAK,MAAM,UAAU,KAAK,UAC9C,UAAU,SAAS,KAAK,MAAM,UAAU,KAAK;EAEjD,KAAK,UAAU;EACf,IAAI;GACF,IAAI,WAAW,kBACb,KAAK,SAAS;IACZ,SAAS,UACL;KAAE,MAAM;KAAG,IAAI,KAAK,MAAM,IAAI;KAAQ,QAAQ,KAAK;IAAY,IAC/D,KAAA;IACJ;GACF,CAAC;GAEH,IAAI,SAAS,UAAU,KAAK,OAAO,YAAY,KAAK,MAAM;EAC5D,UAAU;GACR,KAAK,UAAU;EACjB;CACF;CAEA,UAAU;EACR,KAAK,YAAY;EACjB,KAAK,OAAO;CACd;AACF"}
@@ -0,0 +1,5 @@
1
+ import type { ReactNodeViewProps } from '@tiptap/react';
2
+ import type { ComposerCodeBlockAdapter } from './ChatComposerCodeBlockAdapter.js';
3
+ export declare function ComposerCodeBlockView({ node, updateAttributes, editor, getPos, adapter, }: ReactNodeViewProps & {
4
+ adapter: ComposerCodeBlockAdapter;
5
+ }): import("react").JSX.Element;