@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
tsx 2,058 lines 74.5 KB
Raw
1 import { useNativeFileDrag } from "../useNativeFileDrag";
2 import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
3 import { useAtomValue } from "@effect/atom-react";
4 import { documentChipKindForFileName } from "~/pierre-icons";
5 import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills";
6 import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills";
7 import {
8 Extension,
9 findChildren,
10 InputRule,
11 Node,
12 wrappingInputRule,
13 type JSONContent,
14 type TiptapEditorHTMLElement,
15 } from "@tiptap/core";
16 import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
17 import StarterKit from "@tiptap/starter-kit";
18 import { useGT } from "gt-react";
19 import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands";
20 import { isHistoryTransaction } from "@tiptap/pm/history";
21 import {
22 type EditorState,
23 NodeSelection,
24 Plugin,
25 PluginKey,
26 TextSelection,
27 type Transaction,
28 } from "@tiptap/pm/state";
29 import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
30 import type { NodeType, ResolvedPos } from "@tiptap/pm/model";
31 import type {
32 AssistantCitation,
33 ComposerContextClipboardFragment,
34 ServerProviderSkill,
35 } from "@t3tools/contracts";
36 import {
37 serializeAssistantCitation,
38 withAssistantCitationComment,
39 } from "@t3tools/shared/assistantCitations";
40 import {
41 COMPOSER_CONTEXT_CLIPBOARD_MIME,
42 encodeComposerContextClipboardHtml,
43 } from "@t3tools/shared/composerContextClipboard";
44 import {
45 createContext,
46 use,
47 useEffect,
48 useEffectEvent,
49 useImperativeHandle,
50 useLayoutEffect,
51 useRef,
52 useState,
53 type KeyboardEvent as ReactKeyboardEvent,
54 type ReactNode,
55 type RefObject,
56 } from "react";
57 import { EditorContent, useEditor } from "@tiptap/react";
58
59 import {
60 clampCollapsedComposerCursor,
61 collapseExpandedComposerCursor,
62 expandCollapsedComposerCursor,
63 pastedPathQueryLength,
64 } from "~/composer-logic";
65 import { useStableCallback } from "~/hooks/useStableCallback";
66 import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction";
67 import {
68 collapseShownMarkdownSource,
69 ComposerMarkdownSourceExtension,
70 } from "~/composer-markdown-source";
71 import { MARKDOWN_SOURCE_MARK } from "~/composer-rich-text";
72 import {
73 collectComposerPromptInlineTokens,
74 selectionTouchesMentionBoundary,
75 } from "~/composer-editor-mentions";
76 import {
77 buildDocJson,
78 ComposerBlockExtensions,
79 ComposerCodeBlockExtension,
80 ComposerListExtensions,
81 buildTiptapContent,
82 convertBulletItemToTask,
83 ComposerCodeExtension,
84 ComposerBoldExtension,
85 ComposerItalicExtension,
86 ComposerStrikeExtension,
87 ComposerTaskItemExtension,
88 ComposerTaskListExtension,
89 flatToMarkdown,
90 flatToPm,
91 markdownToFlat,
92 pmToFlat,
93 serializeEditorDoc,
94 serializedMarkdownOffset,
95 serializeSelection,
96 skillChipReplacements,
97 splitOrLiftListItem,
98 surroundSelectionWithMark,
99 stepCaretAcrossStyledEdge,
100 type IsKnownModel,
101 type SkillMeta,
102 } from "~/composer-rich-text-doc";
103 import {
104 convertCodeFenceOnEnter,
105 exitCodeBlockOnClosingFence,
106 exitCodeBlockOnTrailingBlankLines,
107 indentCodeBlock,
108 indentedNewlineInCodeBlock,
109 selectionInOneCodeBlock,
110 } from "~/composer-code-block";
111 import {
112 COMPOSER_UNDO_GROUP_DELAY,
113 type ComposerChangeKind,
114 groupUndoByChangeKind,
115 markAsClipboardEdit,
116 } from "~/composer-undo-grouping";
117 import { collectInlineContextIds } from "~/lib/composerContextReferences";
118 import { resolveDiffThemeName } from "~/lib/diffRendering";
119 import { isRichTextFormattingShortcut } from "~/keybindings";
120 import { cn, isMacPlatform } from "~/lib/utils";
121 import { isThreadNavigationShortcut } from "~/keybindings";
122 import { appAtomRegistry } from "~/rpc/atomRegistry";
123 import { primaryServerKeybindingsAtom } from "~/state/server";
124 import { hasCommandForKeyDown } from "~/shortcuts/dispatcher";
125 import { basenameOfPath } from "~/pierre-icons";
126 import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon";
127 import { FileTagChipContent } from "./chat/FileTagChip";
128 import { SkillChipPopover, skillPopoverDescription } from "./chat/SkillInlineText";
129 import { AssistantCitationChip } from "./chat/AssistantCitationChip";
130 import { ModelMentionChip, modelMentionKey, modelMentionKeysAtom } from "./chat/ModelMentionChip";
131 import { getTimelinePageScrollKey } from "./chat/pageScrollController";
132 import { ContextChip } from "./ContextChip";
133 import {
134 ComposerContextActionsContext,
135 ComposerContextReferenceChip,
136 ComposerContextRecordsContext,
137 } from "./composerContextPresentation";
138 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
139 import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
140 import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView";
141 import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal";
142 import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight";
143 import {
144 importPastedComposerText,
145 readPastedComposerContext,
146 readPastedPlainText,
147 } from "./composerInlineTokenPaste";
148 import { didComposerSelectionChangeVisibly } from "./composerSelection";
149 import {
150 captureComposerAttachmentInsertion,
151 type ComposerAttachmentInsertion,
152 } from "./composerAttachmentInsertion";
153 import type { ComposerDraftContextRecords } from "./composerContextPresentation";
154
155 export interface ComposerPromptEditorHandle {
156 focus: () => void;
157 focusAt: (cursor: number) => void;
158 focusAtEnd: () => void;
159 readSelectionRange: () => { start: number; end: number };
160 captureAttachmentInsertion: () => ComposerAttachmentInsertion | undefined;
161 requestCitationComment: (request: ComposerCitationCommentRequest) => void;
162 readSnapshot: () => {
163 value: string;
164 cursor: number;
165 expandedCursor: number;
166 contextIds: string[];
167 };
168 isCaretOnVisualEdge: (edge: "start" | "end") => boolean;
169 }
170
171 export interface ComposerPromptEditorProps {
172 draftKey?: string;
173 value: string;
174 cursor: number;
175 richTextEnabled?: boolean;
176 literalText?: boolean;
177 contextRecords: ComposerDraftContextRecords;
178 buildContextClipboardFragment?:
179 | ((contextIds: ReadonlyArray<string>) => string | null)
180 | undefined;
181 importContextFragment?:
182 | ((fragment: ComposerContextClipboardFragment) => ReadonlyMap<string, string>)
183 | undefined;
184 skills: ReadonlyArray<ServerProviderSkill>;
185 disabled: boolean;
186 placeholder: string;
187 /** Rendered after the placeholder text, such as a key hint. */
188 placeholderSuffix?: ReactNode;
189 ariaLabel?: string | undefined;
190 suggestionListId?: string | undefined;
191 activeSuggestionId?: string | undefined;
192 isPathQueryActive?: () => boolean;
193 containerClassName?: string;
194 className?: string;
195 placeholderClassName?: string;
196 onChange: (
197 nextValue: string,
198 nextCursor: number,
199 expandedCursor: number,
200 cursorAdjacentToMention: boolean,
201 contextIds: string[],
202 /** False when only the caret or selection moved. */
203 textChanged: boolean,
204 ) => void;
205 onVisibleSelectionChange?: () => void;
206 onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean;
207 onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void;
208 onPageScrollKeyUp?: (key: string) => void;
209 onPageScrollRelease?: () => void;
210 onCitationSubmitAndSend?: () => boolean;
211 /** Saves unsaved citation text into replacedValue when a controlled rewrite replaces the document. */
212 onCitationDraftSave?: (replacedValue: string, savedValue: string) => void;
213 onPaste: React.ClipboardEventHandler<HTMLElement>;
214 editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
215 }
216
217 export type ComposerCitationCommentRequest = {
218 previousValue: string;
219 value: string;
220 citationStart: number;
221 sourceAnchor: AssistantCitationSourceAnchor;
222 insertedSpaces: CitationInsertedSpaces;
223 };
224
225 type CitationInsertedSpaces = { before: boolean; after: boolean };
226
227 type OpenCitationComment = {
228 key: string;
229 sourceAnchor?: AssistantCitationSourceAnchor;
230 removeOnCancel?: CitationInsertedSpaces;
231 };
232
233 const ComposerCitationCommentContext = createContext<{
234 openComment: OpenCitationComment | null;
235 onOpenChange: (citeKey: string, open: boolean) => void;
236 onDraftChange: (citeKey: string, comment: string) => void;
237 onSubmitAndSend: () => boolean;
238 }>({
239 openComment: null,
240 onOpenChange: () => {},
241 onDraftChange: () => {},
242 onSubmitAndSend: () => false,
243 });
244
245 const RichComposerSkillsContext = createContext<ReadonlyArray<ServerProviderSkill>>([]);
246
247 const SURROUND_CLOSE: Record<string, string> = {
248 "(": ")",
249 "[": "]",
250 "{": "}",
251 "'": "'",
252 '"': '"',
253 "“": "”",
254 "`": "`",
255 "<": ">",
256 "«": "»",
257 "*": "*",
258 _: "_",
259 };
260
261 function resolvedThemeFromDocument(): "light" | "dark" {
262 return document.documentElement.classList.contains("dark") ? "dark" : "light";
263 }
264
265 const CHIP_NODE_SELECTION_CLASS_NAME =
266 "relative inline-flex min-w-0 max-w-full select-none items-baseline data-[composer-chip-selected]:after:pointer-events-none data-[composer-chip-selected]:after:absolute data-[composer-chip-selected]:after:inset-0 data-[composer-chip-selected]:after:rounded-sm data-[composer-chip-selected]:after:bg-[Highlight] data-[composer-chip-selected]:after:opacity-30 data-[composer-chip-selected]:after:content-['']";
267
268 const ComposerMentionExtension = Node.create({
269 name: "composer-mention",
270 group: "inline",
271 inline: true,
272 atom: true,
273 selectable: true,
274 addAttributes() {
275 return {
276 path: { default: "" },
277 source: { default: "" },
278 };
279 },
280 parseHTML() {
281 return [{ tag: "span[data-composer-mention]" }];
282 },
283 renderHTML({ HTMLAttributes }) {
284 return ["span", { "data-composer-mention": "", ...HTMLAttributes }];
285 },
286 addNodeView() {
287 return ReactNodeViewRenderer(ComposerMentionNodeView);
288 },
289 });
290
291 function ComposerMentionNodeView({ node }: NodeViewProps) {
292 const gt = useGT();
293 const actions = use(ComposerContextActionsContext);
294 const path = (node.attrs.path as string) ?? "";
295 const nativeDrag = useNativeFileDrag(actions.environmentId, () =>
296 resolvePathLinkTarget(path, actions.cwd ?? ""),
297 );
298 const chip = (
299 <ContextChip
300 {...nativeDrag}
301 kind={documentChipKindForFileName(path) ?? "mention"}
302 dir="ltr"
303 render={<button type="button" />}
304 onClick={() => actions.openMention(path)}
305 aria-label={gt("Preview {path}", { path })}
306 contentEditable={false}
307 spellCheck={false}
308 data-composer-mention-chip="true"
309 >
310 <FileTagChipContent
311 path={path}
312 environmentId={actions.environmentId}
313 cwd={actions.cwd}
314 label={basenameOfPath(path)}
315 theme={resolvedThemeFromDocument()}
316 />
317 </ContextChip>
318 );
319 return (
320 <NodeViewWrapper as="span" className={CHIP_NODE_SELECTION_CLASS_NAME}>
321 <Tooltip>
322 <TooltipTrigger render={chip} />
323 <TooltipPopup side="top">
324 <WorkspaceEntryTooltip
325 path={path}
326 environmentId={actions.environmentId}
327 cwd={actions.cwd}
328 />
329 </TooltipPopup>
330 </Tooltip>
331 </NodeViewWrapper>
332 );
333 }
334
335 const ComposerSkillExtension = Node.create({
336 name: "composer-skill",
337 group: "inline",
338 inline: true,
339 atom: true,
340 selectable: true,
341 addAttributes() {
342 return {
343 skillName: { default: "" },
344 skillLabel: { default: "" },
345 skillDescription: { default: null },
346 };
347 },
348 parseHTML() {
349 return [{ tag: "span[data-composer-skill]" }];
350 },
351 renderHTML({ HTMLAttributes }) {
352 return ["span", { "data-composer-skill": "", ...HTMLAttributes }];
353 },
354 addNodeView() {
355 return ReactNodeViewRenderer(ComposerSkillNodeView);
356 },
357 });
358
359 function ComposerModelNodeView({ node }: NodeViewProps) {
360 const actions = use(ComposerContextActionsContext);
361 return (
362 <NodeViewWrapper as="span" className={CHIP_NODE_SELECTION_CLASS_NAME}>
363 <ModelMentionChip
364 environmentId={actions.environmentId}
365 instanceId={String(node.attrs.instanceId)}
366 model={String(node.attrs.model)}
367 source={String(node.attrs.source)}
368 />
369 </NodeViewWrapper>
370 );
371 }
372
373 /** `model:<instance>/<model>` from the `@` menu; `source` is the exact prompt text. */
374 const ComposerModelExtension = Node.create({
375 name: "composer-model",
376 group: "inline",
377 inline: true,
378 atom: true,
379 selectable: true,
380 addAttributes() {
381 return {
382 instanceId: { default: "" },
383 model: { default: "" },
384 source: { default: "" },
385 };
386 },
387 parseHTML() {
388 return [{ tag: "span[data-composer-model]" }];
389 },
390 renderHTML({ HTMLAttributes }) {
391 return ["span", { "data-composer-model": "", ...HTMLAttributes }];
392 },
393 addNodeView() {
394 return ReactNodeViewRenderer(ComposerModelNodeView);
395 },
396 });
397
398 /** Chip presentation for `$name`, or null when the provider does not offer it to users. */
399 function composerSkillMeta(
400 skills: ReadonlyArray<ServerProviderSkill>,
401 name: string,
402 ): SkillMeta | null {
403 const skill = skills.find(
404 (candidate) => candidate.name === name && isProviderSkillUserInvocable(candidate),
405 );
406 if (!skill) return null;
407 const shortDescription = skill.shortDescription?.trim();
408 return {
409 label: formatProviderSkillDisplayName(skill),
410 description: shortDescription || skill.description?.trim() || null,
411 };
412 }
413
414 function ComposerSkillNodeView({ node }: NodeViewProps) {
415 const actions = use(ComposerContextActionsContext);
416 const skills = use(RichComposerSkillsContext);
417 const skillName = (node.attrs.skillName as string) ?? "";
418 const skillDescription = (node.attrs.skillDescription as string | null) ?? null;
419 const skill = skills.find(
420 (candidate) => candidate.name === skillName && isProviderSkillUserInvocable(candidate),
421 );
422 // The node outlives a provider switch, so its stored label can be another provider's.
423 const skillLabel = skill
424 ? formatProviderSkillDisplayName(skill)
425 : (node.attrs.skillLabel as string) || skillName;
426 return (
427 <NodeViewWrapper as="span" className={CHIP_NODE_SELECTION_CLASS_NAME}>
428 <SkillChipPopover
429 label={skillLabel}
430 description={skill ? skillPopoverDescription(skill) : skillDescription}
431 onViewInstructions={
432 skill?.path && actions.environmentId ? () => actions.openMention(skill.path) : undefined
433 }
434 />
435 </NodeViewWrapper>
436 );
437 }
438
439 const ComposerCitationExtension = Node.create({
440 name: "composer-citation",
441 group: "inline",
442 inline: true,
443 atom: true,
444 selectable: true,
445 addAttributes() {
446 return {
447 citation: { default: null },
448 source: { default: "" },
449 citeKey: { default: "" },
450 };
451 },
452 parseHTML() {
453 return [{ tag: "span[data-composer-citation]" }];
454 },
455 renderHTML({ HTMLAttributes }) {
456 return ["span", { "data-composer-citation": "", ...HTMLAttributes }];
457 },
458 addNodeView() {
459 return ReactNodeViewRenderer(ComposerCitationNodeView);
460 },
461 });
462
463 function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
464 const commentContext = use(ComposerCitationCommentContext);
465 const citation = node.attrs.citation as AssistantCitation;
466 const citeKey = node.attrs.citeKey as string;
467 const commentTarget =
468 commentContext.openComment?.key === citeKey ? commentContext.openComment : null;
469
470 const nodePos = () => {
471 const pos = typeof getPos === "function" ? getPos() : null;
472 return typeof pos === "number" ? pos : null;
473 };
474
475 const onSaveComment = (comment: string): boolean => {
476 if (!editor.isEditable) return false;
477 const pos = nodePos();
478 if (pos === null) return false;
479 const current = editor.state.doc.nodeAt(pos);
480 if (!current || current.type.name !== "composer-citation") return false;
481 const currentCitation = current.attrs.citation as AssistantCitation;
482 const next = withAssistantCitationComment(currentCitation, comment);
483 const tr = editor.state.tr.setNodeMarkup(pos, undefined, {
484 ...current.attrs,
485 citation: next,
486 source: serializeAssistantCitation(next),
487 });
488 editor.view.dispatch(tr);
489 return true;
490 };
491
492 const removeOnCancel = commentTarget?.removeOnCancel;
493 const onRemove = () => {
494 if (!removeOnCancel) return;
495 const pos = nodePos();
496 if (pos === null) return;
497 const { doc } = editor.state;
498 const current = doc.nodeAt(pos);
499 if (!current) return;
500 const end = pos + current.nodeSize;
501 const from = removeOnCancel.before && doc.textBetween(pos - 1, pos) === " " ? pos - 1 : pos;
502 const to = removeOnCancel.after && doc.textBetween(end, end + 1) === " " ? end + 1 : end;
503 // A read-only composer (dictation) can still receive a new citation, so Cancel must undo it.
504 const chain = editor.chain();
505 (editor.isEditable ? chain.focus() : chain).deleteRange({ from, to }).run();
506 };
507
508 const sentRef = useRef(false);
509 const onRestoreFocus = () => {
510 const sent = sentRef.current;
511 sentRef.current = false;
512 if (!editor.isEditable) return;
513 const pos = nodePos();
514 const current = pos === null ? null : editor.state.doc.nodeAt(pos);
515 if (pos === null || current?.type.name !== "composer-citation") {
516 if (sent) editor.view.focus();
517 return;
518 }
519 // The send's controlled rewrite may still be pending; emitting this caret move would restore the old prompt.
520 editor
521 .chain()
522 .setMeta(SILENT_SELECTION_META, sent)
523 .focus(pos + current.nodeSize)
524 .run();
525 };
526
527 return (
528 <NodeViewWrapper
529 as="span"
530 className={CHIP_NODE_SELECTION_CLASS_NAME}
531 contentEditable={false}
532 spellCheck={false}
533 data-composer-citation-chip="true"
534 onKeyDown={(event: ReactKeyboardEvent<HTMLElement>) => {
535 if (
536 !editor.isEditable ||
537 event.key !== "Tab" ||
538 event.shiftKey ||
539 event.altKey ||
540 event.metaKey ||
541 event.ctrlKey ||
542 !(event.target instanceof HTMLElement) ||
543 event.target.dataset.citationCommentTrigger === undefined
544 ) {
545 return;
546 }
547 event.preventDefault();
548 onRestoreFocus();
549 }}
550 >
551 <AssistantCitationChip
552 citation={citation}
553 commentEditor={{
554 open: commentTarget !== null,
555 sourceAnchor: commentTarget?.sourceAnchor,
556 onOpenChange: (open) => {
557 if (open && !editor.isEditable) return;
558 commentContext.onOpenChange(citeKey, open);
559 },
560 ...(removeOnCancel ? { onCancel: onRemove } : {}),
561 onSave: onSaveComment,
562 onDraftChange: (comment) => commentContext.onDraftChange(citeKey, comment),
563 onSaveAndSend: (comment) => {
564 if (!onSaveComment(comment)) return false;
565 sentRef.current = commentContext.onSubmitAndSend();
566 return true;
567 },
568 onRestoreFocus,
569 }}
570 />
571 </NodeViewWrapper>
572 );
573 }
574
575 const ComposerContextReferenceExtension = Node.create({
576 name: "composer-context-reference",
577 group: "inline",
578 inline: true,
579 atom: true,
580 selectable: true,
581 addAttributes() {
582 return {
583 kind: { default: "" },
584 contextId: { default: "" },
585 label: { default: "" },
586 source: { default: "" },
587 };
588 },
589 parseHTML() {
590 return [{ tag: "span[data-composer-context-reference]" }];
591 },
592 renderHTML({ HTMLAttributes }) {
593 return ["span", { "data-composer-context-reference": "", ...HTMLAttributes }];
594 },
595 addNodeView() {
596 return ReactNodeViewRenderer(ComposerContextReferenceNodeView);
597 },
598 });
599
600 function ComposerContextReferenceNodeView({ node }: NodeViewProps) {
601 return (
602 <NodeViewWrapper as="span" className={CHIP_NODE_SELECTION_CLASS_NAME}>
603 <ComposerContextReferenceChip
604 kind={(node.attrs.kind as string) ?? ""}
605 contextId={(node.attrs.contextId as string) ?? ""}
606 label={(node.attrs.label as string) ?? ""}
607 />
608 </NodeViewWrapper>
609 );
610 }
611
612 /** Wait for a character after '- ' so task markers reach their input rule before becoming bullets. */
613 function listMarkerInputRule(find: RegExp, listType: "bulletList" | "orderedList"): InputRule {
614 return new InputRule({
615 find,
616 handler: ({ state, range, match, chain }) => {
617 const marker = match.groups?.marker ?? "-";
618 const space = match.groups?.space ?? " ";
619 const carried = match.groups?.carried ?? "";
620 // Nested lists would serialize flat, so accept only top-level paragraphs.
621 const $from = state.doc.resolve(range.from);
622 if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
623 const command = chain()
624 .deleteRange(range)
625 .wrapInList(
626 listType,
627 listType === "orderedList" ? { start: Number.parseInt(marker, 10) || 1 } : {},
628 )
629 .updateAttributes("listItem", { marker, space });
630 (carried ? command.insertContent(carried) : command).run();
631 return undefined;
632 },
633 });
634 }
635
636 const bulletToTaskInputRule = new InputRule({
637 find: /^\[([ xX])\] $/,
638 handler: ({ state, range, match, chain }) => {
639 const $from = state.doc.resolve(range.from);
640 const item = $from.node(-1);
641 if ($from.parent.type.name !== "paragraph" || item?.type.name !== "listItem") return null;
642 if (!["-", "*", "+"].includes((item.attrs as { marker?: string }).marker ?? "")) return null;
643 const checked = (match[1] ?? " ").toLowerCase() === "x";
644 chain()
645 .command(({ tr }) => {
646 convertBulletItemToTask(tr, range.from, range.to, checked);
647 return true;
648 })
649 .run();
650 return undefined;
651 },
652 });
653
654 function taskInputRule(type: NodeType): InputRule {
655 const rule = wrappingInputRule({
656 find: /^- \[([ xX])\] $/,
657 type,
658 getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),
659 });
660 return new InputRule({
661 find: rule.find,
662 handler: (props) =>
663 props.state.doc.resolve(props.range.from).depth === 1 ? rule.handler(props) : null,
664 });
665 }
666
667 function hasAncestor($pos: ResolvedPos, name: string): boolean {
668 for (let depth = $pos.depth; depth > 0; depth -= 1) {
669 if ($pos.node(depth).type.name === name) return true;
670 }
671 return false;
672 }
673
674 const blockquoteInputRule = new InputRule({
675 find: /^>(\s)$/,
676 handler: ({ state, range, match, chain }) => {
677 const $from = state.doc.resolve(range.from);
678 if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
679 chain()
680 .deleteRange(range)
681 .wrapIn("blockquote", { prefix: `>${match[1] ?? " "}` })
682 .run();
683 return undefined;
684 },
685 });
686
687 /** Require a space after *** or ___ to preserve bold typing. Lists and quotes cannot serialize rules. */
688 const horizontalRuleInputRule = new InputRule({
689 find: /^(---|\*\*\*|___)\s?$/,
690 handler: ({ state, range, match, chain }) => {
691 const source = match[0] ?? "---";
692 if (!source.startsWith("---") && !/\s$/.test(source)) return null;
693 const $from = state.doc.resolve(range.from);
694 if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
695 chain()
696 .deleteRange(range)
697 .setHorizontalRule()
698 .command(({ tr }) => {
699 const $pos = tr.selection.$from;
700 const index = $pos.index(0) - 1;
701 if (index < 0) return true;
702 const rulePos = $pos.posAtIndex(index, 0);
703 const rule = tr.doc.nodeAt(rulePos);
704 if (rule?.type.name === "horizontalRule") {
705 tr.setNodeMarkup(rulePos, undefined, { ...rule.attrs, source });
706 }
707 return true;
708 })
709 .run();
710 return undefined;
711 },
712 });
713
714 /** Require a space to preserve PR references; lists and quotes cannot serialize headings. */
715 const headingInputRule = new InputRule({
716 find: /^(#{1,6})(\s)$/,
717 handler: ({ state, range, match, chain }) => {
718 const $from = state.doc.resolve(range.from);
719 if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;
720 chain()
721 .deleteRange(range)
722 .setNode("heading", { level: match[1]?.length ?? 1, space: match[2] ?? " " })
723 .run();
724 return undefined;
725 },
726 });
727
728 function isInCodeBlock(view: EditorView): boolean {
729 return view.state.selection.$from.parent.type.spec.code === true;
730 }
731
732 const ChipSelectionPluginKey = new PluginKey<DecorationSet>("composer-chip-range-selection");
733
734 /** Highlights chips inside a text selection; their node views draw no native highlight. */
735 const ComposerChipSelectionExtension = Extension.create({
736 name: "composer-chip-range-selection",
737 addProseMirrorPlugins() {
738 return [
739 new Plugin<DecorationSet>({
740 key: ChipSelectionPluginKey,
741 state: {
742 init: (_, state) => chipSelectionDecorations(state),
743 apply: (tr, old, _, state) =>
744 tr.docChanged || tr.selectionSet ? chipSelectionDecorations(state) : old,
745 },
746 props: {
747 decorations: (state) => ChipSelectionPluginKey.getState(state),
748 },
749 }),
750 ];
751 },
752 });
753
754 function chipSelectionDecorations({ doc, selection }: EditorState): DecorationSet {
755 if (selection.empty) return DecorationSet.empty;
756 const decorations: Decoration[] = [];
757 doc.nodesBetween(selection.from, selection.to, (node, pos) => {
758 if (!node.type.name.startsWith("composer-")) return true;
759 decorations.push(
760 Decoration.node(pos, pos + node.nodeSize, { class: "composer-chip-range-selected" }),
761 );
762 return false;
763 });
764 return DecorationSet.create(doc, decorations);
765 }
766
767 type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;
768
769 const SILENT_SELECTION_META = "composerSilentSelection";
770
771 function replaceSkillChips(
772 editor: TiptapEditor,
773 replacements: ReturnType<typeof skillChipReplacements>,
774 ): void {
775 const transaction = editor.state.tr.setMeta("addToHistory", false);
776 for (const { from, to, node } of replacements) transaction.replaceWith(from, to, node);
777 editor.view.dispatch(transaction);
778 }
779
780 export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) {
781 const restoreFocusRef = useRef(false);
782 const { onChange: onPromptChange } = props;
783 const [selection, setSelection] = useState<{
784 value: string;
785 cursor: number;
786 expandedCursor: number;
787 } | null>(null);
788 const onChange: ComposerPromptEditorProps["onChange"] = (
789 value,
790 cursor,
791 expandedCursor,
792 ...rest
793 ) => {
794 setSelection({ value, cursor, expandedCursor });
795 onPromptChange(value, cursor, expandedCursor, ...rest);
796 };
797 // Changing text mode remounts the editor. Its collapsed cursor cannot represent
798 // a caret inside unknown `$name` text, so retain the exact Markdown offset here.
799 return (
800 <ComposerPromptEditorTiptapInner
801 key={`${props.draftKey ?? ""}:${props.literalText ? "literal" : props.richTextEnabled ? "rich" : "plain"}`}
802 {...props}
803 restoreFocusRef={restoreFocusRef}
804 initialExpandedCursor={
805 selection?.value === props.value && selection.cursor === props.cursor
806 ? selection.expandedCursor
807 : expandCollapsedComposerCursor(props.value, props.cursor, props.literalText)
808 }
809 onChange={onChange}
810 />
811 );
812 }
813
814 /** Decide grouping in dispatch middleware before the history plugin applies the transaction. */
815 const ComposerUndoGroupingExtension = Extension.create<
816 Record<string, never>,
817 { previous: ComposerChangeKind | null }
818 >({
819 name: "composer-undo-grouping",
820 addStorage() {
821 return { previous: null };
822 },
823 dispatchTransaction({ transaction, next }) {
824 this.storage.previous = groupUndoByChangeKind(transaction, this.storage.previous);
825 next(transaction);
826 },
827 });
828
829 // Module scope keeps extension identity stable; Tiptap hooks read config through this.
830 function createComposerExtensions(richText: boolean) {
831 return [
832 StarterKit.configure({
833 blockquote: false,
834 bulletList: false,
835 codeBlock: false,
836 heading: false,
837 horizontalRule: false,
838 listItem: false,
839 link: false,
840 orderedList: false,
841 underline: false,
842 dropcursor: false,
843 gapcursor: false,
844 trailingNode: false,
845 code: false,
846 listKeymap: false,
847 undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY },
848 italic: false,
849 bold: false,
850 strike: false,
851 }),
852 ComposerUndoGroupingExtension,
853 ComposerTextDirectionExtension,
854 ComposerMentionExtension,
855 ComposerSkillExtension,
856 ComposerModelExtension,
857 ComposerCitationExtension,
858 ComposerContextReferenceExtension,
859 ComposerChipSelectionExtension,
860 ...(richText
861 ? [
862 ComposerMarkdownSourceExtension,
863 ComposerItalicExtension,
864 ComposerBoldExtension,
865 ComposerStrikeExtension,
866 ComposerCodeExtension,
867 ComposerCodeBlockExtension.extend({
868 addNodeView() {
869 return ReactNodeViewRenderer(ComposerCodeBlockNodeView, {
870 // Tiptap shields only the button; header clicks would move ProseMirror's selection.
871 stopEvent: ({ event }) =>
872 event.target instanceof Element &&
873 event.target.closest(".chat-markdown-codeblock-header") !== null,
874 });
875 },
876 // Tiptap's fence rule allows unserializable lists/quotes; use top-level Enter instead.
877 addInputRules() {
878 return [];
879 },
880 }),
881 composerCodeBlockHighlight({
882 resolveTheme: () =>
883 resolveDiffThemeName(
884 document.documentElement.classList.contains("dark") ? "dark" : "light",
885 ),
886 }),
887 ...ComposerBlockExtensions.map((extension) =>
888 extension.name === "blockquote"
889 ? extension.extend({
890 addInputRules() {
891 return [blockquoteInputRule];
892 },
893 })
894 : extension.name === "horizontalRule"
895 ? extension.extend({
896 addInputRules() {
897 return [horizontalRuleInputRule];
898 },
899 })
900 : extension.name === "heading"
901 ? extension.extend({
902 addInputRules() {
903 return [headingInputRule];
904 },
905 })
906 : extension,
907 ),
908 ...ComposerListExtensions.map((extension) =>
909 extension.name === "listItem"
910 ? extension
911 : extension.extend({
912 addInputRules() {
913 return this.name === "bulletList"
914 ? [
915 listMarkerInputRule(/^(?<marker>[*+])(?<space>\s)$/, "bulletList"),
916 listMarkerInputRule(
917 /^(?<marker>-)(?<space>[ \t]+)(?<carried>[^\s[])$/,
918 "bulletList",
919 ),
920 ]
921 : [listMarkerInputRule(/^(?<marker>\d+[.)])(?<space>\s)$/, "orderedList")];
922 },
923 }),
924 ),
925 ComposerTaskListExtension,
926 ComposerTaskItemExtension.extend({
927 addInputRules() {
928 return [taskInputRule(this.type), bulletToTaskInputRule];
929 },
930 }),
931 ]
932 : []),
933 ];
934 }
935
936 const RICH_TEXT_EXTENSIONS = createComposerExtensions(true);
937 const PLAIN_TEXT_EXTENSIONS = createComposerExtensions(false);
938
939 function ComposerPromptEditorTiptapInner(
940 props: ComposerPromptEditorProps & {
941 initialExpandedCursor: number;
942 restoreFocusRef: RefObject<boolean>;
943 },
944 ) {
945 const {
946 value,
947 cursor,
948 richTextEnabled,
949 literalText = false,
950 contextRecords,
951 buildContextClipboardFragment,
952 importContextFragment,
953 skills,
954 disabled,
955 placeholder,
956 ariaLabel,
957 suggestionListId,
958 activeSuggestionId,
959 isPathQueryActive,
960 containerClassName,
961 className,
962 placeholderClassName,
963 placeholderSuffix,
964 onChange,
965 onVisibleSelectionChange,
966 onCommandKeyDown,
967 onPageScrollKeyDown,
968 onPageScrollKeyUp,
969 onPageScrollRelease,
970 onCitationSubmitAndSend,
971 onCitationDraftSave,
972 onPaste,
973 editorRef,
974 restoreFocusRef,
975 } = props;
976 const richText = !literalText && (richTextEnabled ?? false);
977 const clampEditorCursor = (text: string, position: number) =>
978 literalText
979 ? Math.max(
980 0,
981 Math.min(text.length, Number.isFinite(position) ? Math.floor(position) : text.length),
982 )
983 : clampCollapsedComposerCursor(text, position);
984 const expandEditorCursor = (text: string, position: number) =>
985 literalText ? position : expandCollapsedComposerCursor(text, position);
986
987 const latestValueRef = useRef(value);
988 // The editor config is built once, so its handlers reach the current callbacks through here.
989 const readCallbacks = useStableCallback(() => ({
990 onChange,
991 onVisibleSelectionChange,
992 onCommandKeyDown,
993 isPathQueryActive,
994 importContextFragment,
995 }));
996
997 const { environmentId } = use(ComposerContextActionsContext);
998 const modelKeys = useAtomValue(modelMentionKeysAtom(environmentId ?? ""));
999 // Stable so a skills or models refresh does not rerun the controlled-value effect.
1000 const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name));
1001 const isKnownModel = useStableCallback((instanceId: string, model: string) =>
1002 modelKeys.has(modelMentionKey(instanceId, model)),
1003 );
1004
1005 const initialCursor = clampEditorCursor(value, cursor);
1006 const initialExpandedCursor = Math.max(0, Math.min(value.length, props.initialExpandedCursor));
1007 const snapshotRef = useRef({
1008 value,
1009 cursor: initialCursor,
1010 expandedCursor: initialExpandedCursor,
1011 contextIds: literalText ? [] : collectInlineContextIds(value),
1012 });
1013 const selectionRangeRef = useRef({ start: initialExpandedCursor, end: initialExpandedCursor });
1014 const isApplyingControlledUpdateRef = useRef(false);
1015 const hasAppliedControlledSelectionRef = useRef(false);
1016 const citationRequestRef = useRef<ComposerCitationCommentRequest | null>(null);
1017 const [openCitation, setOpenCitation] = useState<OpenCitationComment | null>(null);
1018 const citationDraftRef = useRef<{ key: string; comment: string } | null>(null);
1019 const [isEmpty, setIsEmpty] = useState(value.length === 0);
1020
1021 const citationCommentActions = {
1022 openComment: openCitation,
1023 onOpenChange: (nodeKey: string, open: boolean) => {
1024 if (!open && citationDraftRef.current?.key === nodeKey) citationDraftRef.current = null;
1025 setOpenCitation((current) => {
1026 if (open) {
1027 if (current?.key === nodeKey) return current;
1028 return { key: nodeKey };
1029 }
1030 return current?.key === nodeKey ? null : current;
1031 });
1032 },
1033 onDraftChange: (nodeKey: string, comment: string) => {
1034 citationDraftRef.current = { key: nodeKey, comment };
1035 },
1036 onSubmitAndSend: onCitationSubmitAndSend ?? (() => false),
1037 };
1038
1039 const handleEditorChange = (updated: TiptapEditor, transaction: Transaction) => {
1040 const map = serializeEditorDoc(updated.state.doc);
1041 const contextIds = literalText ? [] : [...map.contextIds];
1042 const { from, to } = updated.state.selection;
1043 const fromFlat = pmToFlat(map, from);
1044 const toFlat = pmToFlat(map, to);
1045 const nextValue = map.value;
1046 const nextExpandedCursor = Math.max(
1047 0,
1048 Math.min(map.value.length, flatToMarkdown(map, fromFlat)),
1049 );
1050 const nextCursor = collapseExpandedComposerCursor(map.value, nextExpandedCursor, literalText);
1051 const nextSelectionRange = {
1052 start: Math.min(nextExpandedCursor, flatToMarkdown(map, toFlat)),
1053 end: Math.max(nextExpandedCursor, flatToMarkdown(map, toFlat)),
1054 };
1055 const previousSelectionRange = selectionRangeRef.current;
1056 selectionRangeRef.current = nextSelectionRange;
1057 setIsEmpty(nextValue.length === 0);
1058 const previousSnapshot = snapshotRef.current;
1059 const snapshotChanged = !(
1060 previousSnapshot.value === nextValue &&
1061 previousSnapshot.cursor === nextCursor &&
1062 previousSnapshot.expandedCursor === nextExpandedCursor &&
1063 previousSnapshot.contextIds.length === contextIds.length &&
1064 previousSnapshot.contextIds.every((id, index) => id === contextIds[index])
1065 );
1066 if (isApplyingControlledUpdateRef.current || transaction.getMeta(SILENT_SELECTION_META)) return;
1067 if (!snapshotChanged) {
1068 if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) {
1069 readCallbacks().onVisibleSelectionChange?.();
1070 }
1071 return;
1072 }
1073 // Ignore selection-only updates while a controlled rewrite is pending to avoid overwriting the new
1074 // prompt.
1075 if (previousSnapshot.value === nextValue && nextValue !== latestValueRef.current) {
1076 return;
1077 }
1078 snapshotRef.current = {
1079 value: nextValue,
1080 cursor: nextCursor,
1081 expandedCursor: nextExpandedCursor,
1082 contextIds,
1083 };
1084 const inCodeBlock = updated.state.selection.$from.parent.type.spec.code === true;
1085 const suppressTrigger =
1086 literalText ||
1087 inCodeBlock ||
1088 [updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some(
1089 (node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak",
1090 );
1091 readCallbacks().onChange(
1092 nextValue,
1093 nextCursor,
1094 nextExpandedCursor,
1095 suppressTrigger,
1096 contextIds,
1097 previousSnapshot.value !== nextValue,
1098 );
1099 };
1100
1101 const editorAttributes = {
1102 class: cn(
1103 "composer-tiptap -m-1 block max-h-52 min-h-[calc(2lh+--spacing(2))] overflow-y-auto p-1 whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none",
1104 className,
1105 ),
1106 "data-testid": "composer-editor",
1107 "data-composer-rich-text": richText ? "true" : "false",
1108 role: "textbox",
1109 "aria-multiline": "true",
1110 ...(ariaLabel ? { "aria-label": ariaLabel } : {}),
1111 ...(disabled ? { "aria-readonly": "true" } : {}),
1112 ...(!disabled && suggestionListId
1113 ? {
1114 "aria-autocomplete": "list",
1115 "aria-haspopup": "listbox",
1116 ...(activeSuggestionId
1117 ? {
1118 "aria-controls": suggestionListId,
1119 "aria-activedescendant": activeSuggestionId,
1120 }
1121 : {}),
1122 }
1123 : {}),
1124 "aria-placeholder": placeholder,
1125 };
1126
1127 const editor = useEditor(
1128 {
1129 extensions: richText ? RICH_TEXT_EXTENSIONS : PLAIN_TEXT_EXTENSIONS,
1130 content: buildDocJson(value, (name) => composerSkillMeta(skills, name), {
1131 styling: richText,
1132 literalText,
1133 isKnownModel: (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)),
1134 }),
1135 editable: !disabled,
1136 editorProps: {
1137 attributes: editorAttributes,
1138 handleDOMEvents: {
1139 // Composer commands keep precedence; otherwise true skips the editor's keymaps without
1140 // preventDefault, so a bound app command still runs.
1141 keydown: (_view, event) => {
1142 if (!isRichTextFormattingShortcut(event)) return false;
1143 if (readCallbacks().onCommandKeyDown?.(event.key, event)) {
1144 event.preventDefault();
1145 event.stopPropagation();
1146 return true;
1147 }
1148 return hasCommandForKeyDown(event);
1149 },
1150 },
1151 handleKeyDown: (view, event) => {
1152 // In a right-to-left line the start is on the right.
1153 const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft";
1154 const boundary = event.metaKey
1155 ? event.key === "ArrowLeft" || event.key === "ArrowRight"
1156 ? "lineboundary"
1157 : event.key === "ArrowUp" || event.key === "ArrowDown"
1158 ? "documentboundary"
1159 : null
1160 : event.key === "Home" || event.key === "End"
1161 ? "lineboundary"
1162 : null;
1163 if (
1164 isMacPlatform(navigator.platform) &&
1165 boundary &&
1166 !event.altKey &&
1167 !event.ctrlKey &&
1168 !event.isComposing
1169 ) {
1170 if (
1171 isThreadNavigationShortcut(event, appAtomRegistry.get(primaryServerKeybindingsAtom), {
1172 context: { editableFocus: true },
1173 })
1174 ) {
1175 return false;
1176 }
1177 const selection = window.getSelection();
1178 if (
1179 selection?.anchorNode &&
1180 view.dom.contains(selection.anchorNode) &&
1181 typeof selection.modify === "function"
1182 ) {
1183 event.preventDefault();
1184 event.stopPropagation();
1185 const backward =
1186 event.key === "Home" || event.key === "ArrowUp" || event.key === backArrow;
1187 selection.modify(
1188 event.shiftKey ? "extend" : "move",
1189 backward ? "backward" : "forward",
1190 boundary,
1191 );
1192 if (selection.anchorNode && selection.focusNode) {
1193 const tr = view.state.tr.setSelection(
1194 TextSelection.create(
1195 view.state.doc,
1196 view.posAtDOM(selection.anchorNode, selection.anchorOffset),
1197 view.posAtDOM(selection.focusNode, selection.focusOffset),
1198 ),
1199 );
1200 // A marker has two caret stops at one document position. Keep
1201 // the outer stop when native navigation reaches a boundary.
1202 if (richText && tr.selection.empty) {
1203 const { $head } = tr.selection;
1204 tr.setStoredMarks((backward ? $head.nodeBefore : $head.nodeAfter)?.marks ?? []);
1205 }
1206 view.dispatch(tr.scrollIntoView());
1207 }
1208 return true;
1209 }
1210 }
1211 if (
1212 ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) &&
1213 !event.shiftKey &&
1214 !event.altKey &&
1215 !event.metaKey &&
1216 !event.ctrlKey &&
1217 !event.isComposing &&
1218 view.state.selection.empty
1219 ) {
1220 const { $from } = view.state.selection;
1221 const direction = event.key === "ArrowUp" || event.key === backArrow ? -1 : 1;
1222 const horizontal = event.key === "ArrowLeft" || event.key === "ArrowRight";
1223 // At document edges, Up/Down may cross markers without changing position; record the stop to
1224 // preserve the caret.
1225 const atDocumentEdge =
1226 $from.pos ===
1227 (direction === -1
1228 ? TextSelection.atStart(view.state.doc).from
1229 : TextSelection.atEnd(view.state.doc).to);
1230 // Visit the styled edge's other stop before a chip so the plain stop stays reachable.
1231 const step =
1232 horizontal || atDocumentEdge
1233 ? stepCaretAcrossStyledEdge(view.state, direction)
1234 : null;
1235 if (step) {
1236 event.preventDefault();
1237 event.stopPropagation();
1238 view.dispatch(step);
1239 return true;
1240 }
1241 const adjacent = direction === -1 ? $from.nodeBefore : $from.nodeAfter;
1242 if (horizontal && adjacent?.type.name.startsWith("composer-")) {
1243 event.preventDefault();
1244 event.stopPropagation();
1245 view.dispatch(
1246 view.state.tr
1247 .setSelection(
1248 TextSelection.create(view.state.doc, $from.pos + direction * adjacent.nodeSize),
1249 )
1250 .scrollIntoView(),
1251 );
1252 return true;
1253 }
1254 }
1255 // Native tab order skips citation comment buttons inside the editor.
1256 if (
1257 event.key === "Tab" &&
1258 event.shiftKey &&
1259 !event.altKey &&
1260 !event.metaKey &&
1261 !event.ctrlKey &&
1262 view.state.selection.empty
1263 ) {
1264 const { $from } = view.state.selection;
1265 const citation = $from.nodeBefore;
1266 if (citation?.type.name === "composer-citation") {
1267 const chip = view.nodeDOM($from.pos - citation.nodeSize);
1268 const commentButton =
1269 chip instanceof HTMLElement
1270 ? chip.querySelector<HTMLElement>("[data-citation-comment-trigger]")
1271 : null;
1272 if (commentButton) {
1273 event.preventDefault();
1274 event.stopPropagation();
1275 commentButton.focus();
1276 return true;
1277 }
1278 }
1279 }
1280 if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) {
1281 event.stopPropagation();
1282 return true;
1283 }
1284 if (event.key === "Enter" && event.target instanceof HTMLInputElement) {
1285 event.preventDefault();
1286 return true;
1287 }
1288 if (
1289 event.key === "Tab" &&
1290 !event.metaKey &&
1291 !event.ctrlKey &&
1292 selectionInOneCodeBlock(view.state)
1293 ) {
1294 event.preventDefault();
1295 event.stopPropagation();
1296 return indentCodeBlock(view.state, event.shiftKey ? "out" : "in", (tr) =>
1297 view.dispatch(tr),
1298 );
1299 }
1300 if (
1301 event.key === "Enter" &&
1302 richText &&
1303 !event.metaKey &&
1304 !event.ctrlKey &&
1305 !event.isComposing
1306 ) {
1307 if (selectionInOneCodeBlock(view.state)) {
1308 event.preventDefault();
1309 event.stopPropagation();
1310 const dispatch = (tr: typeof view.state.tr) => view.dispatch(tr.scrollIntoView());
1311 return (
1312 exitCodeBlockOnClosingFence(view.state, dispatch) ||
1313 exitCodeBlockOnTrailingBlankLines(view) ||
1314 indentedNewlineInCodeBlock(view.state, dispatch) ||
1315 newlineInCode(view.state, dispatch)
1316 );
1317 }
1318 if (convertCodeFenceOnEnter(view.state, (tr) => view.dispatch(tr))) {
1319 event.preventDefault();
1320 event.stopPropagation();
1321 return true;
1322 }
1323 }
1324 const handler = readCallbacks().onCommandKeyDown;
1325 if (event.key === "Enter") {
1326 const instance = (view.dom as TiptapEditorHTMLElement).editor;
1327 const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);
1328 const isListItem = richText && (instance?.isActive("listItem") ?? false);
1329 const handled = handler?.("Enter", event, isTaskItem || isListItem) ?? false;
1330 if (handled) {
1331 event.preventDefault();
1332 event.stopPropagation();
1333 return true;
1334 }
1335 event.preventDefault();
1336 if (
1337 (isTaskItem || isListItem) &&
1338 instance &&
1339 splitOrLiftListItem(instance, collapseShownMarkdownSource)
1340 ) {
1341 return true;
1342 }
1343 if (
1344 richText &&
1345 instance &&
1346 hasAncestor(view.state.selection.$from, "blockquote") &&
1347 view.state.selection.$from.parent.content.size === 0 &&
1348 instance.commands.lift("blockquote")
1349 ) {
1350 return true;
1351 }
1352 // Parse shown Markdown first, or the split leaves each half with one delimiter.
1353 if (instance) {
1354 return instance
1355 .chain()
1356 .command(collapseShownMarkdownSource)
1357 .command(({ state, dispatch }) => splitBlockKeepMarks(state, dispatch))
1358 .scrollIntoView()
1359 .run();
1360 }
1361 return splitBlockKeepMarks(view.state, (tr) => {
1362 view.dispatch(tr.scrollIntoView());
1363 });
1364 }
1365 if (!handler) return false;
1366 const handled = handler(event.key, event);
1367 if (handled) {
1368 event.preventDefault();
1369 event.stopPropagation();
1370 }
1371 return handled;
1372 },
1373 handleTextInput: (view, from, to, text) => {
1374 if (literalText || view.composing || text.length !== 1) return false;
1375 const closer = SURROUND_CLOSE[text];
1376 const { selection } = view.state;
1377 // Compose preedit updates replace a range even without a user selection.
1378 if (
1379 !closer ||
1380 !(selection instanceof TextSelection) ||
1381 selection.empty ||
1382 selection.from !== from ||
1383 selection.to !== to
1384 ) {
1385 return false;
1386 }
1387 // Do not wrap chips, atoms, or styled text; default replacement preserves marks.
1388 // Shown Markdown source is plain text, so typed delimiters wrap it.
1389 let touchesSpecial = false;
1390 view.state.doc.nodesBetween(from, to, (node) => {
1391 if (
1392 (node.isAtom && node.isInline && !node.isText) ||
1393 (node.isText && node.marks.some((mark) => mark.type.name !== MARKDOWN_SOURCE_MARK))
1394 ) {
1395 touchesSpecial = true;
1396 return false;
1397 }
1398 return true;
1399 });
1400 if (touchesSpecial) return false;
1401 const map = serializeEditorDoc(view.state.doc);
1402 const startMd = flatToMarkdown(map, pmToFlat(map, from));
1403 const endMd = flatToMarkdown(map, pmToFlat(map, to));
1404 if (selectionTouchesMentionBoundary(map.value, startMd, endMd)) return false;
1405 const markTr = surroundSelectionWithMark(view.state, from, to, text);
1406 if (markTr) {
1407 view.dispatch(markTr);
1408 return true;
1409 }
1410 const tr = view.state.tr.insertText(closer, to).insertText(text, from);
1411 tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));
1412 view.dispatch(tr);
1413 return true;
1414 },
1415 handlePaste: (view, event) => {
1416 const clipboardData = event.clipboardData;
1417 if (!clipboardData) return false;
1418 if (
1419 clipboardData.files.length > 0 &&
1420 (literalText || !readPastedComposerContext(clipboardData)?.records.length)
1421 )
1422 return false;
1423 const pastedText = readPastedPlainText(clipboardData);
1424 if (!pastedText) return false;
1425 event.preventDefault();
1426 // Paste verbatim inside fences; markdown parsing would split blocks and create unsupported chips.
1427 if (isInCodeBlock(view)) {
1428 const { from, to } = view.state.selection;
1429 view.dispatch(
1430 markAsClipboardEdit(
1431 view.state.tr.insertText(pastedText, from, to),
1432 "paste",
1433 ).scrollIntoView(),
1434 );
1435 return true;
1436 }
1437 // Shown Markdown source is parsed when the caret leaves, so paste one line into it as text.
1438 const sourceType = view.state.schema.marks[MARKDOWN_SOURCE_MARK];
1439 const { from: pasteFrom, to: pasteTo, $from: $pasteFrom } = view.state.selection;
1440 if (
1441 sourceType?.isInSet($pasteFrom.marks()) &&
1442 !pastedText.includes("\n") &&
1443 collectComposerPromptInlineTokens(`${pastedText}\n`).length === 0
1444 ) {
1445 view.dispatch(
1446 markAsClipboardEdit(
1447 view.state.tr.insertText(pastedText, pasteFrom, pasteTo),
1448 "paste",
1449 ).scrollIntoView(),
1450 );
1451 return true;
1452 }
1453 const importFragment = readCallbacks().importContextFragment;
1454 let text =
1455 !literalText && importFragment
1456 ? importPastedComposerText(clipboardData, importFragment)
1457 : pastedText;
1458 const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`);
1459 const isChip = (token: (typeof tokens)[number] | undefined) =>
1460 token?.type === "mention" ||
1461 (token?.type === "skill" && skillLabelFor(token.value) !== null) ||
1462 (token?.type === "model" && isKnownModel(token.instanceId, token.model));
1463 const lastToken = tokens.at(-1);
1464 if (isChip(lastToken) && lastToken?.end === text.length) {
1465 text += " ";
1466 }
1467 if (isChip(tokens[0]) && tokens[0]?.start === 0) {
1468 const map = serializeEditorDoc(view.state.doc);
1469 const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from));
1470 if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`;
1471 }
1472 const { $from } = view.state.selection;
1473 const lineBefore = $from.parent.textBetween(0, $from.parentOffset, undefined, "\uFFFC");
1474 const literalLength = literalText
1475 ? 0
1476 : pastedPathQueryLength(lineBefore, text, readCallbacks().isPathQueryActive?.());
1477 const editorInstance = (view.dom as TiptapEditorHTMLElement).editor;
1478 if (editorInstance) {
1479 const $paste = view.state.selection.$from;
1480 const nested = ["listItem", "taskItem", "blockquote"].some((name) =>
1481 hasAncestor($paste, name),
1482 );
1483 insertMarkdownParagraphs(
1484 text,
1485 skillLabelFor,
1486 { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel },
1487 (content) => {
1488 editorInstance
1489 .chain()
1490 .command(({ tr }) => {
1491 markAsClipboardEdit(tr, "paste");
1492 return true;
1493 })
1494 // Pasted chips and lines would split shown Markdown, so parse it first.
1495 .command(collapseShownMarkdownSource)
1496 .insertContent(content)
1497 .command(({ tr }) => {
1498 // Move after a pasted rule so the next keystroke cannot replace it; add a trailing line
1499 // if needed.
1500 const { selection } = tr;
1501 if (!(selection instanceof NodeSelection) || !selection.node.isBlock) {
1502 return true;
1503 }
1504 if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) {
1505 tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create());
1506 }
1507 tr.setSelection(TextSelection.create(tr.doc, selection.to + 1));
1508 return true;
1509 })
1510 .run();
1511 },
1512 );
1513 scrollTiptapCaretIntoView(editorInstance);
1514 }
1515 return true;
1516 },
1517 },
1518 onUpdate: ({ editor: updated, transaction }) => {
1519 // Undo can restore a chip for a skill or model the environment no longer offers.
1520 if (!literalText && isHistoryTransaction(transaction)) {
1521 const stale = skillChipReplacements(
1522 updated.state.doc,
1523 skillLabelFor,
1524 isKnownModel,
1525 ).filter(({ node }) => node.isText);
1526 if (stale.length > 0) {
1527 replaceSkillChips(updated, stale);
1528 return;
1529 }
1530 }
1531 handleEditorChange(updated, transaction);
1532 },
1533 onSelectionUpdate: ({ editor: updated, transaction }) => {
1534 handleEditorChange(updated, transaction);
1535 },
1536 },
1537 [],
1538 );
1539
1540 const resumeEditingFocusRef = useRef(false);
1541 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- preserves native selection focus across temporarily making the editor read-only for dictation
1542 useEffect(() => {
1543 if (!editor) return;
1544 if (disabled && editor.isEditable) resumeEditingFocusRef.current = editor.view.hasFocus();
1545 editor.setEditable(!disabled);
1546 if (!resumeEditingFocusRef.current) return;
1547
1548 const editorDom = editor.view.dom;
1549 const ownerDocument = editorDom.ownerDocument;
1550 if (disabled) {
1551 const cancelFocusRestore = (event: FocusEvent) => {
1552 if (!event.composedPath().includes(editorDom)) {
1553 resumeEditingFocusRef.current = false;
1554 }
1555 };
1556 ownerDocument.addEventListener("focusin", cancelFocusRestore, true);
1557 return () => ownerDocument.removeEventListener("focusin", cancelFocusRestore, true);
1558 }
1559
1560 resumeEditingFocusRef.current = false;
1561 if (
1562 ownerDocument.activeElement === ownerDocument.body ||
1563 ownerDocument.activeElement === editorDom
1564 ) {
1565 editor.view.focus();
1566 }
1567 }, [disabled, editor]);
1568
1569 // Push attributes before layout measurements; Tiptap updates them later in a passive effect.
1570 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes DOM attributes into the ProseMirror view before layout measurements read them
1571 useLayoutEffect(() => {
1572 if (!editor?.isInitialized) return;
1573 editor.view.setProps({ attributes: editorAttributes });
1574 }, [editor, editorAttributes]);
1575
1576 const readSnapshot = () => {
1577 const snapshot = snapshotRef.current;
1578 if (!editor) return snapshot;
1579 const map = serializeEditorDoc(editor.state.doc);
1580 const { from, to } = editor.state.selection;
1581 const fromFlat = pmToFlat(map, from);
1582 const expandedCursor = Math.max(0, Math.min(map.value.length, flatToMarkdown(map, fromFlat)));
1583 const next: typeof snapshot = {
1584 value: map.value,
1585 cursor: collapseExpandedComposerCursor(map.value, expandedCursor, literalText),
1586 expandedCursor,
1587 contextIds: literalText ? [] : [...map.contextIds],
1588 };
1589 const toFlat = pmToFlat(map, to);
1590 selectionRangeRef.current = {
1591 start: Math.min(next.expandedCursor, flatToMarkdown(map, toFlat)),
1592 end: Math.max(next.expandedCursor, flatToMarkdown(map, toFlat)),
1593 };
1594 snapshotRef.current = next;
1595 return next;
1596 };
1597
1598 // Save citation drafts before controlled rewrites unmount their node views.
1599 const saveCitationDraft = useEffectEvent((current: TiptapEditor, replacedValue: string) => {
1600 const draft = citationDraftRef.current;
1601 citationDraftRef.current = null;
1602 if (!draft || !onCitationDraftSave) return;
1603 const [target] = findChildren(
1604 current.state.doc,
1605 (node) => node.type.name === "composer-citation" && node.attrs.citeKey === draft.key,
1606 );
1607 if (!target) return;
1608 const { node, pos } = target;
1609 const citation = node.attrs.citation as AssistantCitation;
1610 const dismissal = resolveAssistantCitationCommentDismissal({
1611 reason: "none",
1612 draft: draft.comment,
1613 savedComment: citation.comment,
1614 });
1615 if (dismissal.kind !== "commit") return;
1616 const next = withAssistantCitationComment(citation, dismissal.comment);
1617 current.view.dispatch(
1618 current.state.tr
1619 .setNodeMarkup(pos, undefined, {
1620 ...node.attrs,
1621 citation: next,
1622 source: serializeAssistantCitation(next),
1623 })
1624 .setMeta("addToHistory", false),
1625 );
1626 onCitationDraftSave(replacedValue, serializeEditorDoc(current.state.doc).value);
1627 });
1628
1629 // The one place the controlled value reaches the editor. Imperative handlers compare against
1630 // the committed value, so it is recorded here even before the editor exists.
1631 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the controlled value and cursor into the Tiptap document before paint
1632 useLayoutEffect(() => {
1633 latestValueRef.current = value;
1634 if (!editor) return;
1635 const initialSelection = !hasAppliedControlledSelectionRef.current;
1636 hasAppliedControlledSelectionRef.current = true;
1637 const normalizedCursor = clampEditorCursor(value, cursor);
1638 const previousSnapshot = snapshotRef.current;
1639 if (
1640 !initialSelection &&
1641 previousSnapshot.value === value &&
1642 previousSnapshot.cursor === normalizedCursor
1643 ) {
1644 return;
1645 }
1646 const normalizedExpandedCursor = initialSelection
1647 ? initialExpandedCursor
1648 : expandEditorCursor(value, normalizedCursor);
1649 snapshotRef.current = {
1650 value,
1651 cursor: normalizedCursor,
1652 expandedCursor: normalizedExpandedCursor,
1653 contextIds: collectInlineContextIds(value),
1654 };
1655 selectionRangeRef.current = {
1656 start: normalizedExpandedCursor,
1657 end: normalizedExpandedCursor,
1658 };
1659 setIsEmpty(value.length === 0);
1660 const rootElement = editor.view.dom;
1661 const isFocused = Boolean(rootElement && document.activeElement === rootElement);
1662 if (!initialSelection && previousSnapshot.value === value && !isFocused) return;
1663
1664 isApplyingControlledUpdateRef.current = true;
1665 const pendingCitation =
1666 citationRequestRef.current?.value === value ? citationRequestRef.current : null;
1667 if (previousSnapshot.value !== value) {
1668 saveCitationDraft(editor, previousSnapshot.value);
1669 editor.commands.setContent(
1670 buildDocJson(value, skillLabelFor, { styling: richText, literalText, isKnownModel }),
1671 {
1672 emitUpdate: false,
1673 },
1674 );
1675 }
1676 selectMarkdownOffset(editor, value, normalizedExpandedCursor);
1677 const map = serializeEditorDoc(editor.state.doc);
1678 if (isFocused) scrollTiptapCaretIntoView(editor);
1679 // A redraw later in this commit drops the editor's scroll offset, so reveal on the next frame.
1680 else if (initialSelection) {
1681 window.requestAnimationFrame(() => {
1682 if (!editor.isDestroyed) revealCaretInEditor(editor);
1683 });
1684 }
1685 if (pendingCitation) {
1686 citationRequestRef.current = null;
1687 const target = map.runs.find(
1688 (run) =>
1689 run.kind === "token" &&
1690 run.nodeName === "composer-citation" &&
1691 run.mdStart === pendingCitation.citationStart,
1692 );
1693 if (target) {
1694 const node = editor.state.doc.nodeAt(target.pmPos);
1695 const citeKey = (node?.attrs as { citeKey?: string } | undefined)?.citeKey;
1696 if (citeKey) {
1697 setOpenCitation({
1698 key: citeKey,
1699 sourceAnchor: pendingCitation.sourceAnchor,
1700 removeOnCancel: pendingCitation.insertedSpaces,
1701 });
1702 }
1703 }
1704 }
1705 queueMicrotask(() => {
1706 isApplyingControlledUpdateRef.current = false;
1707 });
1708 }, [
1709 clampEditorCursor,
1710 cursor,
1711 editor,
1712 expandEditorCursor,
1713 initialExpandedCursor,
1714 literalText,
1715 richText,
1716 skillLabelFor,
1717 isKnownModel,
1718 value,
1719 ]);
1720
1721 // Reconcile loaded or switched provider skills and models without rebuilding citation node views.
1722 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces skill and model chip nodes in the Tiptap document when the provider skill or model list loads or changes
1723 useEffect(() => {
1724 if (!editor || literalText) return;
1725 const replacements = skillChipReplacements(
1726 editor.state.doc,
1727 (name) => composerSkillMeta(skills, name),
1728 (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)),
1729 );
1730 if (replacements.length > 0) replaceSkillChips(editor, replacements);
1731 }, [editor, literalText, modelKeys, skills]);
1732
1733 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown
1734 useLayoutEffect(() => {
1735 if (!editor) return;
1736 if (restoreFocusRef.current) {
1737 restoreFocusRef.current = false;
1738 editor.view.focus();
1739 scrollTiptapCaretIntoView(editor);
1740 }
1741 return () => {
1742 // Capture focus before the keyed editor's DOM is removed.
1743 restoreFocusRef.current = editor.view.hasFocus();
1744 };
1745 }, [editor, restoreFocusRef]);
1746
1747 const focusAt = (nextCursor: number, exactExpandedCursor?: number) => {
1748 if (!editor) return;
1749 // view.focus() writes selection immediately; bare DOM focus waits 20ms and can misplace fast dictation.
1750 editor.view.focus();
1751 if (snapshotRef.current.value !== latestValueRef.current) return;
1752 const boundedCursor = clampEditorCursor(snapshotRef.current.value, nextCursor);
1753 const expandedCursor =
1754 exactExpandedCursor ?? expandEditorCursor(snapshotRef.current.value, boundedCursor);
1755 selectMarkdownOffset(editor, snapshotRef.current.value, expandedCursor);
1756 scrollTiptapCaretIntoView(editor);
1757 if (boundedCursor === snapshotRef.current.cursor) return;
1758 snapshotRef.current = {
1759 value: snapshotRef.current.value,
1760 cursor: boundedCursor,
1761 expandedCursor,
1762 contextIds: snapshotRef.current.contextIds,
1763 };
1764 selectionRangeRef.current = {
1765 start: snapshotRef.current.expandedCursor,
1766 end: snapshotRef.current.expandedCursor,
1767 };
1768 readCallbacks().onChange(
1769 snapshotRef.current.value,
1770 boundedCursor,
1771 snapshotRef.current.expandedCursor,
1772 literalText,
1773 snapshotRef.current.contextIds,
1774 false,
1775 );
1776 };
1777
1778 useImperativeHandle(
1779 editorRef,
1780 () => ({
1781 focus: () => {
1782 // The collapsed cursor cannot say where inside `$name` text a caret
1783 // sits, so restoring the caret passes along its exact offset.
1784 focusAt(snapshotRef.current.cursor, snapshotRef.current.expandedCursor);
1785 },
1786 focusAt: (cursor) => focusAt(cursor),
1787 focusAtEnd: () => {
1788 focusAt(
1789 literalText
1790 ? snapshotRef.current.value.length
1791 : collapseExpandedComposerCursor(
1792 snapshotRef.current.value,
1793 snapshotRef.current.value.length,
1794 ),
1795 );
1796 },
1797 readSelectionRange: () => {
1798 readSnapshot();
1799 return selectionRangeRef.current;
1800 },
1801 captureAttachmentInsertion: () =>
1802 editor ? captureComposerAttachmentInsertion(editor) : undefined,
1803 requestCitationComment: (request) => {
1804 citationRequestRef.current = request;
1805 if (!editor) return;
1806 const map = serializeEditorDoc(editor.state.doc);
1807 if (map.value !== request.value) return;
1808 const target = map.runs.find(
1809 (run) =>
1810 run.kind === "token" &&
1811 run.nodeName === "composer-citation" &&
1812 run.mdStart === request.citationStart,
1813 );
1814 if (!target) return;
1815 const node = editor.state.doc.nodeAt(target.pmPos);
1816 const citeKey = (node?.attrs as { citeKey?: string } | undefined)?.citeKey;
1817 if (citeKey) {
1818 citationRequestRef.current = null;
1819 setOpenCitation({
1820 key: citeKey,
1821 sourceAnchor: request.sourceAnchor,
1822 removeOnCancel: request.insertedSpaces,
1823 });
1824 }
1825 },
1826 readSnapshot,
1827 isCaretOnVisualEdge: (edge) => {
1828 const snapshot = readSnapshot();
1829 if (snapshot.value.length === 0) return true;
1830 const beforeCaret = snapshot.value.slice(0, snapshot.expandedCursor);
1831 const afterCaret = snapshot.value.slice(snapshot.expandedCursor);
1832 if (edge === "start" ? beforeCaret.includes("\n") : afterCaret.includes("\n")) {
1833 return false;
1834 }
1835 const rootElement = editor?.view.dom;
1836 const selection = window.getSelection();
1837 if (
1838 !rootElement ||
1839 !selection ||
1840 !selection.isCollapsed ||
1841 selection.rangeCount === 0 ||
1842 !selection.anchorNode ||
1843 !rootElement.contains(selection.anchorNode)
1844 ) {
1845 return false;
1846 }
1847 const caretRect = caretLineRect(selection.getRangeAt(0), edge);
1848 if (!caretRect) return false;
1849 const edgeElement =
1850 edge === "start" ? rootElement.firstElementChild : rootElement.lastElementChild;
1851 const edgeRect = (edgeElement ?? rootElement).getBoundingClientRect();
1852 const threshold = caretRect.height / 2;
1853 return edge === "start"
1854 ? caretRect.top - edgeRect.top < threshold
1855 : edgeRect.bottom - caretRect.bottom < threshold;
1856 },
1857 }),
1858 [editor, focusAt, literalText, readSnapshot],
1859 );
1860
1861 const handleCopyCut = (event: React.ClipboardEvent, cut: boolean) => {
1862 const build = buildContextClipboardFragment;
1863 if (!editor || (cut && !editor.isEditable)) return;
1864 const clipboardData = event.clipboardData;
1865 const { from, to } = editor.state.selection;
1866 if (from === to) return;
1867 const text = serializeSelection(editor.state.doc, from, to);
1868 const contextIds = literalText ? [] : Array.from(new Set(collectInlineContextIds(text)));
1869 const fragment = contextIds.length > 0 ? build?.(contextIds) : null;
1870 event.preventDefault();
1871 clipboardData.setData("text/plain", text);
1872 if (fragment) {
1873 clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
1874 clipboardData.setData("text/html", encodeComposerContextClipboardHtml(text, fragment));
1875 }
1876 if (cut) {
1877 editor
1878 .chain()
1879 .focus()
1880 .command(({ tr }) => {
1881 markAsClipboardEdit(tr, "cut");
1882 return true;
1883 })
1884 .deleteSelection()
1885 .run();
1886 }
1887 };
1888
1889 return (
1890 <RichComposerSkillsContext value={skills}>
1891 <ComposerContextRecordsContext value={contextRecords}>
1892 <ComposerCitationCommentContext value={citationCommentActions}>
1893 <div
1894 className={cn(
1895 "relative flow-root font-(family-name:--font-composer,var(--font-sans)) text-(length:--font-size-prompt,var(--text-sm)) max-sm:pointer-coarse:text-(length:--font-size-prompt-touch)",
1896 containerClassName,
1897 )}
1898 >
1899 <EditorContent
1900 editor={editor}
1901 onKeyDown={(event) => {
1902 if (
1903 event.key === "Control" ||
1904 event.key === "Meta" ||
1905 event.key === "Alt" ||
1906 event.key === "Shift"
1907 ) {
1908 onPageScrollRelease?.();
1909 }
1910 if (event.key !== "PageUp" && event.key !== "PageDown") return;
1911 const target = event.currentTarget.querySelector(
1912 '[data-testid="composer-editor"]',
1913 ) as HTMLElement | null;
1914 if (!target) return;
1915 const pageScrollKey = getTimelinePageScrollKey({
1916 altKey: event.altKey,
1917 clientHeight: target.clientHeight,
1918 ctrlKey: event.ctrlKey,
1919 defaultPrevented: event.defaultPrevented,
1920 isComposing: event.nativeEvent.isComposing,
1921 key: event.key,
1922 keyCode: event.keyCode,
1923 metaKey: event.metaKey,
1924 scrollHeight: target.scrollHeight,
1925 scrollTop: target.scrollTop,
1926 shiftKey: event.shiftKey,
1927 });
1928 if (!pageScrollKey) {
1929 onPageScrollRelease?.();
1930 return;
1931 }
1932 if (!onPageScrollKeyDown) return;
1933 event.preventDefault();
1934 onPageScrollKeyDown(pageScrollKey);
1935 }}
1936 onKeyUp={(event) => onPageScrollKeyUp?.(event.key)}
1937 onBlur={onPageScrollRelease}
1938 onPasteCapture={onPaste}
1939 onCopyCapture={(event) => handleCopyCut(event, false)}
1940 onCutCapture={(event) => handleCopyCut(event, true)}
1941 />
1942 {isEmpty && contextRecords.size === 0 && placeholder ? (
1943 <div
1944 className={cn(
1945 "pointer-events-none absolute inset-0 leading-relaxed text-placeholder",
1946 placeholderClassName,
1947 )}
1948 >
1949 {placeholder}
1950 {placeholderSuffix}
1951 </div>
1952 ) : null}
1953 </div>
1954 </ComposerCitationCommentContext>
1955 </ComposerContextRecordsContext>
1956 </RichComposerSkillsContext>
1957 );
1958 }
1959
1960 /** Split newlines into paragraphs; trailing hard breaks render no visible line. */
1961 function insertMarkdownParagraphs(
1962 value: string,
1963 skillLabelFor: (name: string) => SkillMeta | null,
1964 options: {
1965 styling: boolean;
1966 blocks?: boolean;
1967 literalText?: boolean;
1968 literalLength?: number;
1969 isKnownModel?: IsKnownModel;
1970 },
1971 insertContent: (content: JSONContent[] | JSONContent) => void,
1972 ): void {
1973 const blocks = buildTiptapContent(value, skillLabelFor, options);
1974 if (blocks.length === 1 && blocks[0]?.type === "paragraph") {
1975 const inline = (blocks[0]?.content ?? []) as JSONContent[];
1976 if (inline.length === 0) return;
1977 insertContent(inline);
1978 return;
1979 }
1980 insertContent(blocks as JSONContent[]);
1981 }
1982
1983 /** Placing the caret can show Markdown markers, so place it again in the shown source. */
1984 function selectMarkdownOffset(editor: TiptapEditor, source: string, offset: number): void {
1985 for (let pass = 0; pass < 2; pass += 1) {
1986 const map = serializeEditorDoc(editor.state.doc);
1987 const pos = flatToPm(
1988 map,
1989 markdownToFlat(map, serializedMarkdownOffset(source, map.value, offset)),
1990 );
1991 const { selection } = editor.state;
1992 if (pass > 0 && selection.empty && selection.from === pos) return;
1993 editor.commands.setTextSelection(pos);
1994 }
1995 }
1996
1997 /** Native scrolling follows only real input; explicitly reveal programmatically placed carets. */
1998 function scrollTiptapCaretIntoView(editor: TiptapEditor): void {
1999 editor.view.dispatch(editor.state.tr.scrollIntoView());
2000 }
2001
2002 /** Scrolls only the editor's own box: a mounting composer must not move the timeline or page. */
2003 function revealCaretInEditor(editor: TiptapEditor): void {
2004 const scroller = editor.view.dom;
2005 const caret = editor.view.coordsAtPos(editor.state.selection.head);
2006 const box = scroller.getBoundingClientRect();
2007 // Padding can be reserved for controls drawn over the box, such as mobile pending-answer actions.
2008 const style = getComputedStyle(scroller);
2009 const bottom = box.bottom - parseFloat(style.paddingBottom);
2010 const top = box.top + parseFloat(style.paddingTop);
2011 if (caret.bottom > bottom) scroller.scrollTop += caret.bottom - bottom;
2012 else if (caret.top < top) scroller.scrollTop -= top - caret.top;
2013 }
2014
2015 function caretLineRect(range: Range, edge: "start" | "end"): DOMRect | null {
2016 const collapsedRects = Array.from(range.getClientRects()).filter((rect) => rect.height > 0);
2017 const collapsedRect = edge === "start" ? collapsedRects.at(-1) : collapsedRects[0];
2018 if (collapsedRect) return collapsedRect;
2019
2020 const container = range.startContainer;
2021 if (container.nodeType === 3) {
2022 const textNode = container as Text;
2023 if (textNode.data.length === 0) return null;
2024 const probeStart = Math.max(
2025 0,
2026 Math.min(
2027 edge === "start" ? range.startOffset : range.startOffset - 1,
2028 textNode.data.length - 1,
2029 ),
2030 );
2031 const probeRange = document.createRange();
2032 probeRange.setStart(textNode, probeStart);
2033 probeRange.setEnd(textNode, probeStart + 1);
2034 const probeRect = Array.from(probeRange.getClientRects()).find((rect) => rect.height > 0);
2035 if (probeRect) return probeRect;
2036 const boundingRect = probeRange.getBoundingClientRect();
2037 return boundingRect.height > 0 ? boundingRect : null;
2038 }
2039
2040 if (!(container instanceof HTMLElement)) return null;
2041 const neighbour =
2042 container.childNodes[Math.max(0, range.startOffset - 1)] ??
2043 container.childNodes[range.startOffset];
2044 if (neighbour instanceof HTMLElement) {
2045 const neighbourRect = neighbour.getBoundingClientRect();
2046 if (neighbourRect.height > 0) return neighbourRect;
2047 } else if (neighbour instanceof Text && neighbour.data.length > 0) {
2048 const isBeforeCaret = neighbour === container.childNodes[range.startOffset - 1];
2049 const probeStart = isBeforeCaret ? neighbour.data.length - 1 : 0;
2050 const probeRange = document.createRange();
2051 probeRange.setStart(neighbour, probeStart);
2052 probeRange.setEnd(neighbour, probeStart + 1);
2053 const probeRect = Array.from(probeRange.getClientRects()).find((rect) => rect.height > 0);
2054 if (probeRect) return probeRect;
2055 }
2056 const containerRect = container.getBoundingClientRect();
2057 return containerRect.height > 0 ? containerRect : null;
2058 }