Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ComposerPromptEditorTiptap.tsx

1,395 lines48.9 KB

1import { Extension, Node, wrappingInputRule, type JSONContent } from "@tiptap/core";
2import { TaskList } from "@tiptap/extension-task-list";
3import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";
4import StarterKit from "@tiptap/starter-kit";
5import { type Node as ProseMirrorNode } from "@tiptap/pm/model";
6import { splitBlockKeepMarks } from "@tiptap/pm/commands";
7import { Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
8import { Decoration, DecorationSet } from "@tiptap/pm/view";
9import type {
10 AssistantCitation,
11 ComposerContextClipboardFragment,
12 ServerProviderSkill,
13} from "@t3tools/contracts";
14import {
15 serializeAssistantCitation,
16 withAssistantCitationComment,
17} from "@t3tools/shared/assistantCitations";
18import {
19 COMPOSER_CONTEXT_CLIPBOARD_MIME,
20 encodeComposerContextClipboardHtml,
21} from "@t3tools/shared/composerContextClipboard";
22import {
23 createContext,
24 use,
25 useCallback,
26 useEffect,
27 useImperativeHandle,
28 useLayoutEffect,
29 useMemo,
30 useRef,
31 useState,
32} from "react";
33import { EditorContent, useEditor } from "@tiptap/react";
34​
35import {
36 clampCollapsedComposerCursor,
37 collapseExpandedComposerCursor,
38 expandCollapsedComposerCursor,
39 isCollapsedCursorAdjacentToInlineToken,
40} from "~/composer-logic";
41import {
42 collectComposerPromptInlineTokens,
43 selectionTouchesMentionBoundary,
44} from "~/composer-editor-mentions";
45import {
46 buildDocJson,
47 buildTiptapContent,
48 collapsedToFlat,
49 ComposerCodeExtension,
50 ComposerTaskItemExtension,
51 flatToCollapsed,
52 flatToMarkdown,
53 flatToPm,
54 pmToFlat,
55 serializeEditorDoc,
56 type SkillMeta,
57} from "~/composer-rich-text-doc";
58import { collectInlineContextIds } from "~/lib/composerContextReferences";
59import { cn, isMacPlatform } from "~/lib/utils";
60import { basenameOfPath } from "~/pierre-icons";
61import {
62 COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME,
63 COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
64 COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
65 COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME,
66 SKILL_CHIP_ICON_SVG,
67} from "./composerInlineChip";
68import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
69import { AssistantCitationChip } from "./chat/AssistantCitationChip";
70import { getTimelinePageScrollKey } from "./chat/pageScrollController";
71import { ContextChipPopover } from "./contextChipParts";
72import { Button } from "./ui/button";
73import {
74 ComposerContextActionsContext,
75 ComposerContextReferenceChip,
76 ComposerContextRecordsContext,
77} from "./composerContextPresentation";
78import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
79import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";
80import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
81import { importPastedComposerText } from "./composerInlineTokenPaste";
82import { didComposerSelectionChangeVisibly } from "./composerSelection";
83import type { ComposerDraftContextRecords } from "./composerContextPresentation";
84​
85export interface ComposerPromptEditorHandle {
86 focus: () => void;
87 focusAt: (cursor: number) => void;
88 focusAtEnd: () => void;
89 readSelectionRange: () => { start: number; end: number };
90 requestCitationComment: (request: ComposerCitationCommentRequest) => void;
91 readSnapshot: () => {
92 value: string;
93 cursor: number;
94 expandedCursor: number;
95 contextIds: string[];
96 };
97 /**
98 * True when a collapsed caret sits on the first ("start") or last ("end")
99 * visual line, counting soft wraps. Prompt history only claims ArrowUp and
100 * ArrowDown at these edges so arrows still move the caret inside multiline
101 * text.
102 */
103 isCaretOnVisualEdge: (edge: "start" | "end") => boolean;
105​
106export interface ComposerPromptEditorProps {
107 value: string;
108 cursor: number;
109 /**
110 * Render Markdown styling (bold, italic, code, strike, task checkboxes).
111 * Off renders the same Tiptap engine as plain text: every marker stays a
112 * literal character.
113 */
114 richTextEnabled?: boolean;
115 /** Draft records behind the prompt's context references, keyed by context id. */
116 contextRecords: ComposerDraftContextRecords;
117 /** Structured clipboard payload for the given referenced ids, or null to skip. */
118 buildContextClipboardFragment?:
119 | ((contextIds: ReadonlyArray<string>) => string | null)
120 | undefined;
121 /** Imports a structured paste's records; returns ids that changed. */
122 importContextFragment?:
123 | ((fragment: ComposerContextClipboardFragment) => ReadonlyMap<string, string>)
124 | undefined;
125 skills: ReadonlyArray<ServerProviderSkill>;
126 disabled: boolean;
127 placeholder: string;
128 containerClassName?: string;
129 className?: string;
130 placeholderClassName?: string;
131 onChange: (
132 nextValue: string,
133 nextCursor: number,
134 expandedCursor: number,
135 cursorAdjacentToMention: boolean,
136 contextIds: string[],
137 ) => void;
138 onVisibleSelectionChange?: () => void;
139 onCommandKeyDown?: (
140 key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab" | "Escape",
141 event: KeyboardEvent,
142 isTaskItem?: boolean,
143 ) => boolean;
144 onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void;
145 onPageScrollKeyUp?: (key: string) => void;
146 onPageScrollRelease?: () => void;
147 onCitationSubmitAndSend?: () => void;
148 onPaste: React.ClipboardEventHandler<HTMLElement>;
149 editorRef: React.RefObject<ComposerPromptEditorHandle | null>;
151​
152export type ComposerCitationCommentRequest = {
153 previousValue: string;
154 value: string;
155 citationStart: number;
156 sourceAnchor: AssistantCitationSourceAnchor;
157};
158​
159type OpenCitationComment = {
160 key: string;
161 sourceAnchor?: AssistantCitationSourceAnchor;
162 removeOnCancel?: boolean;
163};
164​
165const ComposerCitationCommentContext = createContext<{
166 openComment: OpenCitationComment | null;
167 onOpenChange: (citeKey: string, open: boolean) => void;
168 onSubmitAndSend: () => void;
169}>({ openComment: null, onOpenChange: () => {}, onSubmitAndSend: () => {} });
170​
171const RichComposerSkillsContext = createContext<ReadonlyArray<ServerProviderSkill>>([]);
172​
173const SURROUND_CLOSE: Record<string, string> = {
174 "(": ")",
175 "[": "]",
176 "{": "}",
177 "'": "'",
178 '"': '"',
179 "“": "”",
180 "`": "`",
181 "<": ">",
182 "«": "»",
183 "*": "*",
184 _: "_",
185};
186​
187function resolvedThemeFromDocument(): "light" | "dark" {
188 return document.documentElement.classList.contains("dark") ? "dark" : "light";
190​
191// ── Inline atom nodes (chips) ─────────────────────────────────────────────
192​
193const ComposerMentionExtension = Node.create({
194 name: "composer-mention",
195 group: "inline",
196 inline: true,
197 atom: true,
198 selectable: true,
199 addAttributes() {
200 return {
201 path: { default: "" },
202 source: { default: "" },
203 };
204 },
205 parseHTML() {
206 return [{ tag: "span[data-composer-mention]" }];
207 },
208 renderHTML({ HTMLAttributes }) {
209 return ["span", { "data-composer-mention": "", ...HTMLAttributes }];
210 },
211 addNodeView() {
212 return ReactNodeViewRenderer(ComposerMentionNodeView);
213 },
214});
215​
216function ComposerMentionNodeView({ node }: NodeViewProps) {
217 const actions = use(ComposerContextActionsContext);
218 const path = (node.attrs.path as string) ?? "";
219 const chip = (
220 <Button
221 variant="chip"
222 onClick={() => actions.openMention(path)}
223 aria-label={`Preview ${path}`}
224 className={`${FILE_TAG_CHIP_CLASS_NAME} cursor-pointer focus-visible:outline-2`}
225 contentEditable={false}
226 spellCheck={false}
227 data-composer-mention-chip="true"
228 >
229 <FileTagChipContent
230 path={path}
231 label={basenameOfPath(path)}
232 theme={resolvedThemeFromDocument()}
233 />
234 </Button>
235 );
236 return (
237 <NodeViewWrapper as="span" className={COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME}>
238 <Tooltip>
239 <TooltipTrigger render={chip} />
240 <TooltipPopup side="top">{path}</TooltipPopup>
241 </Tooltip>
242 </NodeViewWrapper>
243 );
245​
246const ComposerSkillExtension = Node.create({
247 name: "composer-skill",
248 group: "inline",
249 inline: true,
250 atom: true,
251 selectable: true,
252 addAttributes() {
253 return {
254 skillName: { default: "" },
255 skillLabel: { default: "" },
256 skillDescription: { default: null },
257 };
258 },
259 parseHTML() {
260 return [{ tag: "span[data-composer-skill]" }];
261 },
262 renderHTML({ HTMLAttributes }) {
263 return ["span", { "data-composer-skill": "", ...HTMLAttributes }];
264 },
265 addNodeView() {
266 return ReactNodeViewRenderer(ComposerSkillNodeView);
267 },
268});
269​
270function ComposerSkillNodeView({ node }: NodeViewProps) {
271 const actions = use(ComposerContextActionsContext);
272 const skills = use(RichComposerSkillsContext);
273 const skillName = (node.attrs.skillName as string) ?? "";
274 const skillLabel = (node.attrs.skillLabel as string) || skillName;
275 const skillDescription = (node.attrs.skillDescription as string | null) ?? null;
276 const skill = skills.find((candidate) => candidate.name === skillName);
277 return (
278 <NodeViewWrapper as="span" className={COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME}>
279 <ContextChipPopover
280 accessibleLabel={`Skill ${skillLabel}`}
281 triggerClassName={COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME}
282 chip={
283 <>
284 <span
285 aria-hidden="true"
286 className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME}
287 dangerouslySetInnerHTML={{ __html: SKILL_CHIP_ICON_SVG }}
288 />
289 <span className={COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME}>{skillLabel}</span>
290 </>
291 }
292 >
293 <div className="space-y-3 p-2 text-sm">
294 <p className="font-medium">{skillLabel}</p>
295 <p>
296 {skill?.description ??
297 skillDescription ??
298 "No description is available for this skill."}
299 </p>
300 {skill?.path ? (
301 <Button variant="outline" size="sm" onClick={() => actions.openMention(skill.path)}>
302 View instructions
303 </Button>
304 ) : null}
305 </div>
306 </ContextChipPopover>
307 </NodeViewWrapper>
308 );
310​
311const ComposerCitationExtension = Node.create({
312 name: "composer-citation",
313 group: "inline",
314 inline: true,
315 atom: true,
316 selectable: true,
317 addAttributes() {
318 return {
319 citation: { default: null },
320 source: { default: "" },
321 citeKey: { default: "" },
322 };
323 },
324 parseHTML() {
325 return [{ tag: "span[data-composer-citation]" }];
326 },
327 renderHTML({ HTMLAttributes }) {
328 return ["span", { "data-composer-citation": "", ...HTMLAttributes }];
329 },
330 addNodeView() {
331 return ReactNodeViewRenderer(ComposerCitationNodeView);
332 },
333});
334​
335function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
336 const commentContext = use(ComposerCitationCommentContext);
337 const citation = node.attrs.citation as AssistantCitation;
338 const citeKey = node.attrs.citeKey as string;
339 const commentTarget =
340 commentContext.openComment?.key === citeKey ? commentContext.openComment : null;
341​
342 const nodePos = useCallback(() => {
343 const pos = typeof getPos === "function" ? getPos() : null;
344 return typeof pos === "number" ? pos : null;
345 }, [getPos]);
346​
347 const onSaveComment = useCallback(
348 (comment: string): boolean => {
349 if (!editor.isEditable) return false;
350 const pos = nodePos();
351 if (pos === null) return false;
352 const current = editor.state.doc.nodeAt(pos);
353 if (!current || current.type.name !== "composer-citation") return false;
354 const currentCitation = current.attrs.citation as AssistantCitation;
355 const next = withAssistantCitationComment(currentCitation, comment);
356 const tr = editor.state.tr.setNodeMarkup(pos, undefined, {
357 ...current.attrs,
358 citation: next,
359 source: serializeAssistantCitation(next),
360 });
361 editor.view.dispatch(tr);
362 return true;
363 },
364 [editor, nodePos],
365 );
366​
367 const onRemove = useCallback(() => {
368 if (!editor.isEditable) return;
369 const pos = nodePos();
370 if (pos === null) return;
371 const current = editor.state.doc.nodeAt(pos);
372 if (!current) return;
373 editor
374 .chain()
375 .focus()
376 .deleteRange({ from: pos, to: pos + current.nodeSize })
377 .run();
378 }, [editor, nodePos]);
379​
380 return (
381 <NodeViewWrapper
382 as="span"
383 className="inline-flex min-w-0 max-w-full"
384 contentEditable={false}
385 spellCheck={false}
386 data-composer-citation-chip="true"
387 >
388 <AssistantCitationChip
389 citation={citation}
390 composer
391 commentEditor={{
392 open: commentTarget !== null,
393 sourceAnchor: commentTarget?.sourceAnchor,
394 onOpenChange: (open) => {
395 if (open && !editor.isEditable) return;
396 commentContext.onOpenChange(citeKey, open);
397 },
398 ...(commentTarget?.removeOnCancel ? { onCancel: onRemove } : {}),
399 onSave: onSaveComment,
400 onSaveAndSend: (comment) => {
401 if (!onSaveComment(comment)) return false;
402 commentContext.onSubmitAndSend();
403 return true;
404 },
405 }}
406 />
407 </NodeViewWrapper>
408 );
410​
411const ComposerContextReferenceExtension = Node.create({
412 name: "composer-context-reference",
413 group: "inline",
414 inline: true,
415 atom: true,
416 selectable: true,
417 addAttributes() {
418 return {
419 kind: { default: "" },
420 contextId: { default: "" },
421 label: { default: "" },
422 source: { default: "" },
423 };
424 },
425 parseHTML() {
426 return [{ tag: "span[data-composer-context-reference]" }];
427 },
428 renderHTML({ HTMLAttributes }) {
429 return ["span", { "data-composer-context-reference": "", ...HTMLAttributes }];
430 },
431 addNodeView() {
432 return ReactNodeViewRenderer(ComposerContextReferenceNodeView);
433 },
434});
435​
436function ComposerContextReferenceNodeView({ node }: NodeViewProps) {
437 return (
438 <NodeViewWrapper as="span" className={COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME}>
439 <ComposerContextReferenceChip
440 kind={(node.attrs.kind as string) ?? ""}
441 contextId={(node.attrs.contextId as string) ?? ""}
442 label={(node.attrs.label as string) ?? ""}
443 />
444 </NodeViewWrapper>
445 );
447​
448// ── Marker reveal (show ** when the cursor is on styled text) ──────────────
449​
450type StyledRange = {
451 from: number;
452 to: number;
453 markers: { at: number; side: number; text: string }[];
454};
455​
456function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {
457 const ranges: StyledRange[] = [];
458 const map = serializeEditorDoc(doc);
459 let range: StyledRange | null = null;
460 let openLength = 0;
461 for (const run of map.runs) {
462 if (run.openLen > 0) {
463 range ??= { from: run.pmPos, to: run.pmPos, markers: [] };
464 range.markers.push({
465 at: run.pmPos,
466 side: -1,
467 text: map.value.slice(run.mdStart, run.mdStart + run.openLen),
468 });
469 }
470 if (range === null) continue;
471 range.to = run.pmPos + run.docLen;
472 if (run.closeLen > 0) {
473 const end = run.mdStart + run.mdLen;
474 range.markers.push({
475 at: range.to,
476 side: -2,
477 text: map.value.slice(end - run.closeLen, end),
478 });
479 }
480 openLength += run.openLen - run.closeLen;
481 if (openLength === 0) {
482 ranges.push(range);
483 range = null;
484 }
485 }
486 return ranges;
488​
489const MarkerPluginKey = new PluginKey("composer-rich-markers");
490​
491const ComposerMarkerPlugin = new Plugin({
492 key: MarkerPluginKey,
493 state: {
494 init: (_, state) => decorationsForSelection(state.doc, state.selection),
495 apply: (tr, old) =>
496 tr.docChanged || tr.selectionSet ? decorationsForSelection(tr.doc, tr.selection) : old,
497 },
498 props: {
499 decorations(state) {
500 return MarkerPluginKey.getState(state);
501 },
502 },
503});
504​
505function decorationsForSelection(
506 doc: ProseMirrorNode,
507 selection: { from: number; to: number; empty: boolean },
508): DecorationSet {
509 const decorations: Decoration[] = [];
510 if (!selection.empty) {
511 doc.nodesBetween(selection.from, selection.to, (node, pos) => {
512 if (node.type.name.startsWith("composer-")) {
513 decorations.push(
514 Decoration.node(pos, pos + node.nodeSize, { class: "composer-chip-range-selected" }),
515 );
516 return false;
517 }
518 return true;
519 });
520 }
521 for (const range of collectStyledRanges(doc)) {
522 const active = selection.empty
523 ? selection.from >= range.from && selection.from <= range.to
524 : selection.from < range.to && selection.to > range.from;
525 if (!active) continue;
526 for (const { at, side, text } of range.markers) {
527 const marker = document.createElement("span");
528 marker.className = "composer-rich-marker";
529 marker.textContent = text;
530 marker.setAttribute("aria-hidden", "true");
531 decorations.push(
532 Decoration.widget(at, marker, { side, key: `marker-${at}-${side}-${marker.textContent}` }),
533 );
534 }
535 }
536 return DecorationSet.create(doc, decorations);
538​
539const ComposerMarkersExtension = Extension.create({
540 name: "composer-rich-markers",
541 addProseMirrorPlugins() {
542 return [ComposerMarkerPlugin];
543 },
544});
545​
546// Document model (markdown ⇄ ProseMirror) lives in ~/composer-rich-text-doc so
547// unit tests can round-trip it without a browser.
548// ── Editor component ───────────────────────────────────────────────────────
549​
550type TiptapEditor = NonNullable<ReturnType<typeof useEditor>>;
551​
552export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) {
553 // Extensions are creation-time: flipping the setting remounts the editor.
554 // Both halves initialize from the controlled Markdown value, so the draft
555 // survives the flip.
556 return (
557 <ComposerPromptEditorTiptapInner key={props.richTextEnabled ? "rich" : "plain"} {...props} />
558 );
560​
561function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {
562 const {
563 value,
564 cursor,
565 richTextEnabled,
566 contextRecords,
567 buildContextClipboardFragment,
568 importContextFragment,
569 skills,
570 disabled,
571 placeholder,
572 containerClassName,
573 className,
574 placeholderClassName,
575 onChange,
576 onVisibleSelectionChange,
577 onCommandKeyDown,
578 onPageScrollKeyDown,
579 onPageScrollKeyUp,
580 onPageScrollRelease,
581 onCitationSubmitAndSend,
582 onPaste,
583 editorRef,
584 } = props;
585 // The setting toggles styling, not the engine: both modes are Tiptap.
586 // Plain mode disables the mark extensions, so markers stay literal text.
587 const richText = richTextEnabled ?? false;
588​
589 const onChangeRef = useRef(onChange);
590 const onVisibleSelectionChangeRef = useRef(onVisibleSelectionChange);
591 const onCommandKeyDownRef = useRef(onCommandKeyDown);
592 const buildFragmentRef = useRef(buildContextClipboardFragment);
593 const importFragmentRef = useRef(importContextFragment);
594 const skillsRef = useRef(skills);
595 const latestValueRef = useRef(value);
596 // The editor instance for callbacks created before it exists (paste).
597 // Effects flush before any user interaction, so this is always set.
598 const editorHolder = useRef<TiptapEditor | null>(null);
599​
600 useEffect(() => {
601 onChangeRef.current = onChange;
602 }, [onChange]);
603 useEffect(() => {
604 onVisibleSelectionChangeRef.current = onVisibleSelectionChange;
605 }, [onVisibleSelectionChange]);
606 useEffect(() => {
607 onCommandKeyDownRef.current = onCommandKeyDown;
608 }, [onCommandKeyDown]);
609 useEffect(() => {
610 buildFragmentRef.current = buildContextClipboardFragment;
611 }, [buildContextClipboardFragment]);
612 useEffect(() => {
613 importFragmentRef.current = importContextFragment;
614 }, [importContextFragment]);
615 useEffect(() => {
616 skillsRef.current = skills;
617 }, [skills]);
618 useLayoutEffect(() => {
619 latestValueRef.current = value;
620 }, [value]);
621​
622 const skillLabelFor = useCallback((name: string): SkillMeta => {
623 const normalized = name.startsWith("$") ? name.slice(1) : name;
624 const skill = skillsRef.current.find((candidate) => candidate.name === normalized);
625 if (!skill) {
626 return { label: formatProviderSkillDisplayName({ name: normalized }), description: null };
627 }
628 const shortDescription = skill.shortDescription?.trim();
629 return {
630 label: formatProviderSkillDisplayName(skill),
631 description: shortDescription || skill.description?.trim() || null,
632 };
633 }, []);
634​
635 const initialCursor = clampCollapsedComposerCursor(value, cursor);
636 const initialExpandedCursor = expandCollapsedComposerCursor(value, initialCursor);
637 const snapshotRef = useRef({
638 value,
639 cursor: initialCursor,
640 expandedCursor: initialExpandedCursor,
641 contextIds: collectInlineContextIds(value),
642 });
643 const selectionRangeRef = useRef({ start: initialExpandedCursor, end: initialExpandedCursor });
644 const isApplyingControlledUpdateRef = useRef(false);
645 const hasAppliedControlledSelectionRef = useRef(false);
646 const citationRequestRef = useRef<ComposerCitationCommentRequest | null>(null);
647 const [openCitation, setOpenCitation] = useState<OpenCitationComment | null>(null);
648 const [isEmpty, setIsEmpty] = useState(value.length === 0);
649​
650 const citationCommentActions = useMemo(
651 () => ({
652 openComment: openCitation,
653 onOpenChange: (nodeKey: string, open: boolean) => {
654 setOpenCitation((current) => {
655 if (open) {
656 if (current?.key === nodeKey) return current;
657 return { key: nodeKey };
658 }
659 return current?.key === nodeKey ? null : current;
660 });
661 },
662 onSubmitAndSend: onCitationSubmitAndSend ?? (() => {}),
663 }),
664 [onCitationSubmitAndSend, openCitation],
665 );
666​
667 const handleEditorChange = useCallback((updated: TiptapEditor) => {
668 const map = serializeEditorDoc(updated.state.doc);
669 const { from, to } = updated.state.selection;
670 const fromFlat = pmToFlat(map, from);
671 const toFlat = pmToFlat(map, to);
672 const nextValue = map.value;
673 const nextCursor = clampCollapsedComposerCursor(map.value, flatToCollapsed(map, fromFlat));
674 const nextExpandedCursor = Math.max(
675 0,
676 Math.min(map.value.length, flatToMarkdown(map, fromFlat)),
677 );
678 const nextSelectionRange = {
679 start: Math.min(nextExpandedCursor, flatToMarkdown(map, toFlat)),
680 end: Math.max(nextExpandedCursor, flatToMarkdown(map, toFlat)),
681 };
682 const previousSelectionRange = selectionRangeRef.current;
683 selectionRangeRef.current = nextSelectionRange;
684 setIsEmpty(nextValue.length === 0);
685 const previousSnapshot = snapshotRef.current;
686 const snapshotChanged = !(
687 previousSnapshot.value === nextValue &&
688 previousSnapshot.cursor === nextCursor &&
689 previousSnapshot.expandedCursor === nextExpandedCursor &&
690 previousSnapshot.contextIds.length === map.contextIds.length &&
691 previousSnapshot.contextIds.every((id, index) => id === map.contextIds[index])
692 );
693 if (isApplyingControlledUpdateRef.current) return;
694 if (!snapshotChanged) {
695 if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) {
696 onVisibleSelectionChangeRef.current?.();
697 }
698 return;
699 }
700 // A selection-only update while a newer prompt waits to be applied (a chip
701 // was just inserted through the store) would report stale text and clobber
702 // the prompt. Let the controlled rewrite land instead.
703 if (previousSnapshot.value === nextValue && nextValue !== latestValueRef.current) {
704 return;
705 }
706 snapshotRef.current = {
707 value: nextValue,
708 cursor: nextCursor,
709 expandedCursor: nextExpandedCursor,
710 contextIds: map.contextIds,
711 };
712 const cursorAdjacentToMention =
713 isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
714 isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
715 onChangeRef.current(
716 nextValue,
717 nextCursor,
718 nextExpandedCursor,
719 cursorAdjacentToMention,
720 map.contextIds,
721 );
722 }, []);
723​
724 const editorAttributes = useMemo(
725 () => ({
726 class: cn(
727 "composer-tiptap block max-h-50 min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap wrap-break-word bg-transparent leading-relaxed text-foreground focus:outline-none",
728 className,
729 ),
730 "data-testid": "composer-editor",
731 "data-composer-rich-text": richText ? "true" : "false",
732 "aria-placeholder": placeholder,
733 }),
734 [className, placeholder, richText],
735 );
736​
737 const editor = useEditor(
738 {
739 extensions: [
740 StarterKit.configure({
741 blockquote: false,
742 bulletList: false,
743 codeBlock: false,
744 heading: false,
745 horizontalRule: false,
746 listItem: false,
747 link: false,
748 orderedList: false,
749 underline: false,
750 dropcursor: false,
751 gapcursor: false,
752 trailingNode: false,
753 code: false,
754 // Plain mode has no marks: typed markers stay literal characters.
755 ...(richText ? {} : { bold: false, italic: false, strike: false }),
756 }),
757 ComposerMentionExtension,
758 ComposerSkillExtension,
759 ComposerCitationExtension,
760 ComposerContextReferenceExtension,
761 ComposerMarkersExtension,
762 ...(richText
763 ? [
764 ComposerCodeExtension,
765 TaskList,
766 ComposerTaskItemExtension.extend({
767 addInputRules() {
768 return [
769 wrappingInputRule({
770 find: /^- \[([ xX])\] $/,
771 type: this.type,
772 getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),
773 }),
774 ];
775 },
776 }),
777 ]
778 : []),
779 ],
780 content: buildDocJson(
781 value,
782 (name) => {
783 const normalized = name.startsWith("$") ? name.slice(1) : name;
784 const found = skills.find((candidate) => candidate.name === normalized);
785 if (!found) {
786 return {
787 label: formatProviderSkillDisplayName({ name: normalized }),
788 description: null,
789 };
790 }
791 const shortDescription = found.shortDescription?.trim();
792 return {
793 label: formatProviderSkillDisplayName(found),
794 description: shortDescription || found.description?.trim() || null,
795 };
796 },
797 { styling: richText },
798 ),
799 editable: !disabled,
800 editorProps: {
801 attributes: editorAttributes,
802 handleKeyDown: (view, event) => {
803 if (
804 isMacPlatform(navigator.platform) &&
805 (event.key === "Home" || event.key === "End") &&
806 !event.altKey &&
807 !event.metaKey &&
808 !event.ctrlKey &&
809 !event.isComposing
810 ) {
811 const selection = window.getSelection();
812 if (
813 selection?.anchorNode &&
814 view.dom.contains(selection.anchorNode) &&
815 typeof selection.modify === "function"
816 ) {
817 event.preventDefault();
818 event.stopPropagation();
819 selection.modify(
820 event.shiftKey ? "extend" : "move",
821 event.key === "Home" ? "backward" : "forward",
822 "lineboundary",
823 );
824 if (selection.anchorNode && selection.focusNode) {
825 view.dispatch(
826 view.state.tr
827 .setSelection(
828 TextSelection.create(
829 view.state.doc,
830 view.posAtDOM(selection.anchorNode, selection.anchorOffset),
831 view.posAtDOM(selection.focusNode, selection.focusOffset),
832 ),
833 )
834 .scrollIntoView(),
835 );
836 }
837 return true;
838 }
839 }
840 if (
841 (event.key === "ArrowLeft" || event.key === "ArrowRight") &&
842 !event.shiftKey &&
843 !event.altKey &&
844 !event.metaKey &&
845 !event.ctrlKey &&
846 !event.isComposing &&
847 view.state.selection.empty
848 ) {
849 const { $from } = view.state.selection;
850 const direction = event.key === "ArrowLeft" ? -1 : 1;
851 const adjacent = direction === -1 ? $from.nodeBefore : $from.nodeAfter;
852 if (adjacent?.type.name.startsWith("composer-")) {
853 event.preventDefault();
854 event.stopPropagation();
855 view.dispatch(
856 view.state.tr
857 .setSelection(
858 TextSelection.create(view.state.doc, $from.pos + direction * adjacent.nodeSize),
859 )
860 .scrollIntoView(),
861 );
862 return true;
863 }
864 }
865 if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) {
866 event.stopPropagation();
867 return true;
868 }
869 // Enter on a focused task checkbox must not send the prompt (or
870 // split anything): Space toggles it, Enter does nothing.
871 if (event.key === "Enter" && event.target instanceof HTMLInputElement) {
872 event.preventDefault();
873 return true;
874 }
875 const handler = onCommandKeyDownRef.current;
876 if (event.key === "Enter") {
877 const instance = editorHolder.current;
878 const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);
879 const handled = handler?.("Enter", event, isTaskItem) ?? false;
880 if (handled) {
881 event.preventDefault();
882 event.stopPropagation();
883 return true;
884 }
885 event.preventDefault();
886 if (
887 isTaskItem &&
888 instance &&
889 (instance.commands.splitListItem("taskItem", { checked: false }) ||
890 (view.state.selection.$from.parent.content.size === 0 &&
891 instance.commands.liftListItem("taskItem")))
892 ) {
893 return true;
894 }
895 // Split the paragraph so a single newline visibly advances the caret.
896 return splitBlockKeepMarks(view.state, (tr) => {
897 // The split is programmatic, so the browser won't follow the
898 // caret into view on its own.
899 view.dispatch(tr.scrollIntoView());
900 });
901 }
902 if (!handler) return false;
903 const key =
904 event.key === "Tab"
905 ? ("Tab" as const)
906 : event.key === "ArrowDown"
907 ? ("ArrowDown" as const)
908 : event.key === "ArrowUp"
909 ? ("ArrowUp" as const)
910 : event.key === "Escape"
911 ? ("Escape" as const)
912 : null;
913 if (!key) return false;
914 const handled = handler(key, event);
915 if (handled) {
916 event.preventDefault();
917 event.stopPropagation();
918 }
919 return handled;
920 },
921 handleTextInput: (view, from, to, text) => {
922 if (text.length !== 1) return false;
923 const closer = SURROUND_CLOSE[text];
924 if (!closer || from === to) return false;
925 // Never wrap chips or other atoms, and never wrap styled text: the
926 // default replace keeps marks intact, wrapping would drop them.
927 let touchesSpecial = false;
928 view.state.doc.nodesBetween(from, to, (node) => {
929 if (
930 (node.isAtom && node.isInline && !node.isText) ||
931 (node.isText && node.marks.length > 0)
932 ) {
933 touchesSpecial = true;
934 return false;
935 }
936 return true;
937 });
938 if (touchesSpecial) return false;
939 const map = serializeEditorDoc(view.state.doc);
940 const startMd = flatToMarkdown(map, pmToFlat(map, from));
941 const endMd = flatToMarkdown(map, pmToFlat(map, to));
942 if (selectionTouchesMentionBoundary(map.value, startMd, endMd)) return false;
943 const tr = view.state.tr.insertText(closer, to).insertText(text, from);
944 tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));
945 view.dispatch(tr);
946 return true;
947 },
948 handlePaste: (view, event) => {
949 const clipboardData = event.clipboardData;
950 if (!clipboardData || clipboardData.files.length > 0) return false;
951 const pastedText = clipboardData.getData("text/plain");
952 if (!pastedText) return false;
953 event.preventDefault();
954 const importFragment = importFragmentRef.current;
955 let text = importFragment
956 ? importPastedComposerText(clipboardData, importFragment)
957 : pastedText;
958 // Complete chips at paste boundaries just as autocomplete does.
959 const tokens = collectComposerPromptInlineTokens(`${text}\n`);
960 const lastToken = tokens.at(-1);
961 if (
962 (lastToken?.type === "mention" || lastToken?.type === "skill") &&
963 lastToken.end === text.length
964 ) {
965 text += " ";
966 }
967 if (
968 (tokens[0]?.type === "mention" || tokens[0]?.type === "skill") &&
969 tokens[0].start === 0
970 ) {
971 const map = serializeEditorDoc(view.state.doc);
972 const offset = flatToMarkdown(map, pmToFlat(map, view.state.selection.from));
973 if (offset > 0 && !/\s/.test(map.value[offset - 1]!)) text = ` ${text}`;
974 }
975 const editorInstance = editorHolder.current;
976 if (editorInstance) {
977 insertMarkdownParagraphs(text, skillLabelFor, { styling: richText }, (content) => {
978 editorInstance.commands.insertContent(content);
979 });
980 scrollTiptapCaretIntoView(editorInstance);
981 }
982 return true;
983 },
984 },
985 onUpdate: ({ editor: updated }) => {
986 handleEditorChange(updated);
987 },
988 onSelectionUpdate: ({ editor: updated }) => {
989 handleEditorChange(updated);
990 },
991 },
992 [],
993 );
994​
995 useEffect(() => {
996 editor?.setEditable(!disabled);
997 }, [disabled, editor]);
998​
999 useEffect(() => {
1000 editorHolder.current = editor;
1001 }, [editor]);
1002​
1003 // Tiptap forwards option changes to the view from a passive effect, so a
1004 // class change here would reach the ProseMirror element one tick after
1005 // React commits. The chat composer measures its resting and expanded
1006 // geometry in layout effects that run first, and it clamps the prompt
1007 // through `className`, so the attributes are pushed to the view here for
1008 // those measurements to see the layout they are about to reserve for.
1009 useLayoutEffect(() => {
1010 if (!editor?.isInitialized) return;
1011 editor.view.setProps({ attributes: editorAttributes });
1012 }, [editor, editorAttributes]);
1013​
1014 const readSnapshot = useCallback(() => {
1015 const snapshot = snapshotRef.current;
1016 if (!editor) return snapshot;
1017 const map = serializeEditorDoc(editor.state.doc);
1018 const { from, to } = editor.state.selection;
1019 const fromFlat = pmToFlat(map, from);
1020 const next: typeof snapshot = {
1021 value: map.value,
1022 cursor: clampCollapsedComposerCursor(map.value, flatToCollapsed(map, fromFlat)),
1023 expandedCursor: Math.max(0, Math.min(map.value.length, flatToMarkdown(map, fromFlat))),
1024 contextIds: map.contextIds,
1025 };
1026 const toFlat = pmToFlat(map, to);
1027 selectionRangeRef.current = {
1028 start: Math.min(next.expandedCursor, flatToMarkdown(map, toFlat)),
1029 end: Math.max(next.expandedCursor, flatToMarkdown(map, toFlat)),
1030 };
1031 snapshotRef.current = next;
1032 return next;
1033 }, [editor]);
1034​
1035 // Controlled value/cursor from the store (history recall, chip insertion…).
1036 useLayoutEffect(() => {
1037 if (!editor) return;
1038 const initialSelection = !hasAppliedControlledSelectionRef.current;
1039 hasAppliedControlledSelectionRef.current = true;
1040 const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
1041 const previousSnapshot = snapshotRef.current;
1042 if (
1043 !initialSelection &&
1044 previousSnapshot.value === value &&
1045 previousSnapshot.cursor === normalizedCursor
1046 ) {
1047 return;
1049 const normalizedExpandedCursor = expandCollapsedComposerCursor(value, normalizedCursor);
1050 snapshotRef.current = {
1051 value,
1052 cursor: normalizedCursor,
1053 expandedCursor: normalizedExpandedCursor,
1054 contextIds: collectInlineContextIds(value),
1055 };
1056 selectionRangeRef.current = {
1057 start: normalizedExpandedCursor,
1058 end: normalizedExpandedCursor,
1059 };
1060 setIsEmpty(value.length === 0);
1061 const rootElement = editor.view.dom;
1062 const isFocused = Boolean(rootElement && document.activeElement === rootElement);
1063 if (!initialSelection && previousSnapshot.value === value && !isFocused) return;
1064​
1065 isApplyingControlledUpdateRef.current = true;
1066 const pendingCitation =
1067 citationRequestRef.current?.value === value ? citationRequestRef.current : null;
1068 if (previousSnapshot.value !== value) {
1069 editor.commands.setContent(buildDocJson(value, skillLabelFor, { styling: richText }), {
1070 emitUpdate: false,
1071 });
1073 const map = serializeEditorDoc(editor.state.doc);
1074 const flat = collapsedToFlat(map, normalizedCursor);
1075 editor.commands.setTextSelection(flatToPm(map, flat));
1076 if (isFocused) scrollTiptapCaretIntoView(editor);
1077 if (pendingCitation) {
1078 citationRequestRef.current = null;
1079 const target = map.runs.find(
1080 (run) =>
1081 run.kind === "token" &&
1082 run.nodeName === "composer-citation" &&
1083 run.mdStart === pendingCitation.citationStart,
1084 );
1085 if (target) {
1086 const node = editor.state.doc.nodeAt(target.pmPos);
1087 const citeKey = (node?.attrs as { citeKey?: string } | undefined)?.citeKey;
1088 if (citeKey) {
1089 setOpenCitation({
1090 key: citeKey,
1091 sourceAnchor: pendingCitation.sourceAnchor,
1092 removeOnCancel: true,
1093 });
1097 queueMicrotask(() => {
1098 isApplyingControlledUpdateRef.current = false;
1099 });
1100 }, [cursor, editor, richText, skillLabelFor, value]);
1101​
1102 const focusAt = useCallback(
1103 (nextCursor: number) => {
1104 if (!editor) return;
1105 editor.view.dom.focus({ preventScroll: true });
1106 // A newer prompt is waiting to be applied (a chip was just inserted
1107 // through the store). Reporting the editor's stale text now would
1108 // overwrite that prompt; the pending rewrite places the caret instead.
1109 if (snapshotRef.current.value !== latestValueRef.current) return;
1110 const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
1111 const map = serializeEditorDoc(editor.state.doc);
1112 const flat = collapsedToFlat(map, boundedCursor);
1113 editor.commands.setTextSelection(flatToPm(map, flat));
1114 scrollTiptapCaretIntoView(editor);
1115 if (boundedCursor === snapshotRef.current.cursor) return;
1116 snapshotRef.current = {
1117 value: snapshotRef.current.value,
1118 cursor: boundedCursor,
1119 expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
1120 contextIds: snapshotRef.current.contextIds,
1121 };
1122 selectionRangeRef.current = {
1123 start: snapshotRef.current.expandedCursor,
1124 end: snapshotRef.current.expandedCursor,
1125 };
1126 onChangeRef.current(
1127 snapshotRef.current.value,
1128 boundedCursor,
1129 snapshotRef.current.expandedCursor,
1130 false,
1131 snapshotRef.current.contextIds,
1132 );
1133 },
1134 [editor],
1135 );
1136​
1137 useImperativeHandle(
1138 editorRef,
1139 () => ({
1140 focus: () => {
1141 focusAt(snapshotRef.current.cursor);
1142 },
1143 focusAt,
1144 focusAtEnd: () => {
1145 focusAt(
1146 collapseExpandedComposerCursor(
1147 snapshotRef.current.value,
1148 snapshotRef.current.value.length,
1149 ),
1150 );
1151 },
1152 readSelectionRange: () => {
1153 readSnapshot();
1154 return selectionRangeRef.current;
1155 },
1156 requestCitationComment: (request) => {
1157 citationRequestRef.current = request;
1158 if (!editor) return;
1159 const map = serializeEditorDoc(editor.state.doc);
1160 if (map.value !== request.value) return;
1161 const target = map.runs.find(
1162 (run) =>
1163 run.kind === "token" &&
1164 run.nodeName === "composer-citation" &&
1165 run.mdStart === request.citationStart,
1166 );
1167 if (!target) return;
1168 const node = editor.state.doc.nodeAt(target.pmPos);
1169 const citeKey = (node?.attrs as { citeKey?: string } | undefined)?.citeKey;
1170 if (citeKey) {
1171 citationRequestRef.current = null;
1172 setOpenCitation({
1173 key: citeKey,
1174 sourceAnchor: request.sourceAnchor,
1175 removeOnCancel: true,
1176 });
1178 },
1179 readSnapshot,
1180 isCaretOnVisualEdge: (edge) => {
1181 const snapshot = readSnapshot();
1182 if (snapshot.value.length === 0) return true;
1183 const beforeCaret = snapshot.value.slice(0, snapshot.expandedCursor);
1184 const afterCaret = snapshot.value.slice(snapshot.expandedCursor);
1185 if (edge === "start" ? beforeCaret.includes("\n") : afterCaret.includes("\n")) {
1186 return false;
1188 const rootElement = editor?.view.dom;
1189 const selection = window.getSelection();
1190 if (
1191 !rootElement ||
1192 !selection ||
1193 !selection.isCollapsed ||
1194 selection.rangeCount === 0 ||
1195 !selection.anchorNode ||
1196 !rootElement.contains(selection.anchorNode)
1197 ) {
1198 return false;
1200 const caretRect = caretLineRect(selection.getRangeAt(0), edge);
1201 if (!caretRect) return false;
1202 const edgeElement =
1203 edge === "start" ? rootElement.firstElementChild : rootElement.lastElementChild;
1204 const edgeRect = (edgeElement ?? rootElement).getBoundingClientRect();
1205 const threshold = caretRect.height / 2;
1206 return edge === "start"
1207 ? caretRect.top - edgeRect.top < threshold
1208 : edgeRect.bottom - caretRect.bottom < threshold;
1209 },
1210 }),
1211 [editor, focusAt, readSnapshot],
1212 );
1213​
1214 const handleCopyCut = useCallback(
1215 (event: React.ClipboardEvent, cut: boolean) => {
1216 const build = buildFragmentRef.current;
1217 if (!editor || (cut && !editor.isEditable)) return;
1218 const clipboardData = event.clipboardData;
1219 const { from, to } = editor.state.selection;
1220 if (from === to) return;
1221 const { doc, schema } = editor.state;
1222 const slice = doc.slice(from, to);
1223 const first = slice.content.firstChild;
1224 const content = first?.isInline
1225 ? schema.nodes.paragraph!.create(null, slice.content)
1226 : first?.type.name === "taskItem"
1227 ? schema.nodes.taskList!.create(null, slice.content)
1228 : slice.content;
1229 const text = serializeEditorDoc(doc.type.create(null, content)).value;
1230 const contextIds = Array.from(new Set(collectInlineContextIds(text)));
1231 const fragment = contextIds.length > 0 ? build?.(contextIds) : null;
1232 event.preventDefault();
1233 clipboardData.setData("text/plain", text);
1234 if (fragment) {
1235 clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
1236 clipboardData.setData("text/html", encodeComposerContextClipboardHtml(text, fragment));
1238 if (cut) {
1239 editor.chain().focus().deleteSelection().run();
1241 },
1242 [editor],
1243 );
1244​
1245 return (
1246 <RichComposerSkillsContext value={skills}>
1247 <ComposerContextRecordsContext value={contextRecords}>
1248 <ComposerCitationCommentContext value={citationCommentActions}>
1249 <div
1250 className={cn(
1251 "relative [font-family:var(--font-composer,var(--font-sans))] [font-size:var(--font-size-prompt,0.875rem)] [@media(max-width:39.999rem)_and_(pointer:coarse)]:[font-size:max(var(--font-size-prompt,1rem),16px)]",
1252 containerClassName,
1253 )}
1255 <EditorContent
1256 editor={editor}
1257 onKeyDown={(event) => {
1258 if (
1259 event.key === "Control" ||
1260 event.key === "Meta" ||
1261 event.key === "Alt" ||
1262 event.key === "Shift"
1263 ) {
1264 onPageScrollRelease?.();
1266 if (event.key !== "PageUp" && event.key !== "PageDown") return;
1267 const target = event.currentTarget.querySelector(
1268 '[data-testid="composer-editor"]',
1269 ) as HTMLElement | null;
1270 if (!target) return;
1271 const pageScrollKey = getTimelinePageScrollKey({
1272 altKey: event.altKey,
1273 clientHeight: target.clientHeight,
1274 ctrlKey: event.ctrlKey,
1275 defaultPrevented: event.defaultPrevented,
1276 isComposing: event.nativeEvent.isComposing,
1277 key: event.key,
1278 keyCode: event.keyCode,
1279 metaKey: event.metaKey,
1280 scrollHeight: target.scrollHeight,
1281 scrollTop: target.scrollTop,
1282 shiftKey: event.shiftKey,
1283 });
1284 if (!pageScrollKey) {
1285 onPageScrollRelease?.();
1286 return;
1288 if (!onPageScrollKeyDown) return;
1289 event.preventDefault();
1290 onPageScrollKeyDown(pageScrollKey);
1291 }}
1292 onKeyUp={(event) => onPageScrollKeyUp?.(event.key)}
1293 onBlur={onPageScrollRelease}
1294 onPasteCapture={onPaste}
1295 onCopyCapture={(event) => handleCopyCut(event, false)}
1296 onCutCapture={(event) => handleCopyCut(event, true)}
1297 />
1298 {isEmpty && contextRecords.size === 0 && placeholder ? (
1299 <div
1300 className={cn(
1301 "pointer-events-none absolute inset-0 leading-relaxed text-placeholder/75",
1302 placeholderClassName,
1303 )}
1305 {placeholder}
1306 </div>
1307 ) : null}
1308 </div>
1309 </ComposerCitationCommentContext>
1310 </ComposerContextRecordsContext>
1311 </RichComposerSkillsContext>
1312 );
1314​
1315/**
1316 * Insert pasted markdown at the selection, rebuilding inline tokens as chips
1317 * and styled spans as marks.
1319 * Newlines always become paragraph splits — never trailing hard breaks, which
1320 * render no visible line — so pasted text lands exactly as typed.
1321 */
1322function insertMarkdownParagraphs(
1323 value: string,
1324 skillLabelFor: (name: string) => SkillMeta,
1325 options: { styling: boolean },
1326 insertContent: (content: JSONContent[] | JSONContent) => void,
1327): void {
1328 const blocks = buildTiptapContent(value, skillLabelFor, options);
1329 if (blocks.length === 1 && blocks[0]?.type === "paragraph") {
1330 const inline = (blocks[0]?.content ?? []) as JSONContent[];
1331 if (inline.length === 0) return;
1332 insertContent(inline);
1333 return;
1335 insertContent(blocks as JSONContent[]);
1337​
1338/**
1339 * Follow a programmatically placed caret: native scrolling only happens for
1340 * real input, so controlled rewrites, pastes, and focus restores scroll the
1341 * composer to the caret explicitly.
1342 */
1343function scrollTiptapCaretIntoView(editor: TiptapEditor): void {
1344 editor.view.dispatch(editor.state.tr.scrollIntoView());
1346​
1347/**
1348 * Client rect of the caret's visual line, so prompt history keeps claiming
1349 * ArrowUp/Down only at the first and last soft-wrapped lines.
1350 */
1351function caretLineRect(range: Range, edge: "start" | "end"): DOMRect | null {
1352 const collapsedRects = Array.from(range.getClientRects()).filter((rect) => rect.height > 0);
1353 const collapsedRect = edge === "start" ? collapsedRects.at(-1) : collapsedRects[0];
1354 if (collapsedRect) return collapsedRect;
1355​
1356 const container = range.startContainer;
1357 // TEXT_NODE without importing the DOM lib's Node (shadowed by Tiptap's).
1358 if (container.nodeType === 3) {
1359 const textNode = container as Text;
1360 if (textNode.data.length === 0) return null;
1361 const probeStart = Math.max(
1362 0,
1363 Math.min(
1364 edge === "start" ? range.startOffset : range.startOffset - 1,
1365 textNode.data.length - 1,
1366 ),
1367 );
1368 const probeRange = document.createRange();
1369 probeRange.setStart(textNode, probeStart);
1370 probeRange.setEnd(textNode, probeStart + 1);
1371 const probeRect = Array.from(probeRange.getClientRects()).find((rect) => rect.height > 0);
1372 if (probeRect) return probeRect;
1373 const boundingRect = probeRange.getBoundingClientRect();
1374 return boundingRect.height > 0 ? boundingRect : null;
1376​
1377 if (!(container instanceof HTMLElement)) return null;
1378 const neighbour =
1379 container.childNodes[Math.max(0, range.startOffset - 1)] ??
1380 container.childNodes[range.startOffset];
1381 if (neighbour instanceof HTMLElement) {
1382 const neighbourRect = neighbour.getBoundingClientRect();
1383 if (neighbourRect.height > 0) return neighbourRect;
1384 } else if (neighbour instanceof Text && neighbour.data.length > 0) {
1385 const isBeforeCaret = neighbour === container.childNodes[range.startOffset - 1];
1386 const probeStart = isBeforeCaret ? neighbour.data.length - 1 : 0;
1387 const probeRange = document.createRange();
1388 probeRange.setStart(neighbour, probeStart);
1389 probeRange.setEnd(neighbour, probeStart + 1);
1390 const probeRect = Array.from(probeRange.getClientRects()).find((rect) => rect.height > 0);
1391 if (probeRect) return probeRect;
1393 const containerRect = container.getBoundingClientRect();
1394 return containerRect.height > 0 ? containerRect : null;