TypeScript
feat(web): block-level Markdown in the rich text composer (#14677)
Chris Deeming300f7f9d45ff
diff --git a/apps/web/package.json b/apps/web/package.jsonindex d17795f15c5..915466100bc 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -32,7 +32,12 @@"@tanstack/react-pacer": "^0.19.4","@tanstack/react-router": "^1.160.2","@tiptap/core": "^3.31.3",+ "@tiptap/extension-blockquote": "^3.31.3","@tiptap/extension-code": "^3.31.3",+ "@tiptap/extension-code-block": "^3.31.3",+ "@tiptap/extension-heading": "^3.31.3",+ "@tiptap/extension-horizontal-rule": "^3.31.3",+ "@tiptap/extension-list": "^3.31.3","@tiptap/extension-task-item": "^3.31.3","@tiptap/extension-task-list": "^3.31.3","@tiptap/pm": "^3.31.3",diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex 42a34d8b5d2..e595efdc5a0 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -989,6 +989,63 @@ function MarkdownDetails({);}+/**+ * The code block frame, shared with the composer so an editable fence and a+ * rendered one cannot drift apart: the wrapper, its header row with the+ * language title, an optional actions slot, and the body as children. The+ * composer passes Tiptap's node view wrapper as the outer element.+ */+export function MarkdownCodeBlockFrame({+ as: Wrapper = "div",+ language,+ fenceTitle,+ theme,+ wrapped = true,+ title,+ actions,+ headerProps,+ children,+}: {+ as?: React.ElementType;+ language: string;+ fenceTitle: string | null;+ theme: "light" | "dark";+ wrapped?: boolean;+ /** Replaces the language title, as the composer does with its language picker. */+ title?: React.ReactNode;+ actions?: React.ReactNode;+ headerProps?: React.HTMLAttributes<HTMLDivElement>;+ children: React.ReactNode;+}) {+ return (+ <Wrapper+ className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"+ data-language={language}+ data-wrap={wrapped ? "true" : "false"}+ >+ <div+ {...headerProps}+ className={cn(+ "chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none",+ headerProps?.className,+ )}+ >+ {title ?? (+ <span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">+ <MarkdownCodeBlockTitleContent+ fenceTitle={fenceTitle}+ language={language}+ theme={theme}+ />+ </span>+ )}+ {actions}+ </div>+ {children}+ </Wrapper>+ );+}+/*** Filename titles render icon + text; language-only titles render just the* icon (redundant next to its own name) and fall back to the language text@@ -1141,19 +1198,12 @@ function MarkdownCodeBlock({}return (- <div- className="chat-markdown-codeblock my-[0.65rem] overflow-hidden rounded-lg border border-border/70 bg-secondary leading-snug dark:border-transparent dark:bg-input/32"- data-language={language}- data-wrap={wrapped ? "true" : "false"}- >- <div className="chat-markdown-codeblock-header flex items-center justify-between gap-2 pt-1.5 pr-1.5 pb-0 pl-3 select-none">- <span className="inline-flex min-w-0 items-center gap-1.5 font-mono text-2xs">- <MarkdownCodeBlockTitleContent- fenceTitle={fenceTitle}- language={language}- theme={theme}- />- </span>+ <MarkdownCodeBlockFrame+ language={language}+ fenceTitle={fenceTitle}+ theme={theme}+ wrapped={wrapped}+ actions={<span className="flex items-center gap-0.5" role="toolbar" aria-label="Code block actions">{leadingActions}{canWrap ? (@@ -1195,9 +1245,10 @@ function MarkdownCodeBlock({) : null}{copyButton}</span>- </div>+ }+ >{children}- </div>+ </MarkdownCodeBlockFrame>);}diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsxindex bac965c0b97..6e830991ab7 100644--- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx+++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx@@ -1,11 +1,17 @@-import { Extension, Node, wrappingInputRule, type JSONContent } from "@tiptap/core";-import { TaskList } from "@tiptap/extension-task-list";+import { Extension, InputRule, Node, wrappingInputRule, type JSONContent } from "@tiptap/core";import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";import StarterKit from "@tiptap/starter-kit";import { type Node as ProseMirrorNode } from "@tiptap/pm/model";-import { splitBlockKeepMarks } from "@tiptap/pm/commands";-import { type EditorState, Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";-import { Decoration, DecorationSet } from "@tiptap/pm/view";+import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands";+import {+ type EditorState,+ NodeSelection,+ Plugin,+ PluginKey,+ TextSelection,+} from "@tiptap/pm/state";+import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";+import type { NodeType, ResolvedPos } from "@tiptap/pm/model";import type {AssistantCitation,ComposerContextClipboardFragment,@@ -45,19 +51,34 @@ import {} from "~/composer-editor-mentions";import {buildDocJson,+ ComposerBlockExtensions,+ ComposerCodeBlockExtension,+ ComposerListExtensions,buildTiptapContent,collapsedToFlat,caretTakesMarksBefore,+ convertBulletItemToTask,ComposerCodeExtension,ComposerTaskItemExtension,+ ComposerTaskListExtension,flatToCollapsed,flatToMarkdown,flatToPm,pmToFlat,serializeEditorDoc,+ serializeSelection,+ splitOrLiftListItem,stepCaretAcrossStyledEdge,type SkillMeta,} from "~/composer-rich-text-doc";+import {+ convertCodeFenceOnEnter,+ exitCodeBlockOnClosingFence,+ exitCodeBlockOnTrailingBlankLines,+ indentCodeBlock,+ indentedNewlineInCodeBlock,+ selectionInOneCodeBlock,+} from "~/composer-code-block";import {COMPOSER_UNDO_GROUP_DELAY,type ComposerChangeKind,@@ -65,6 +86,7 @@ import {markAsClipboardEdit,} from "~/composer-undo-grouping";import { collectInlineContextIds } from "~/lib/composerContextReferences";+import { resolveDiffThemeName } from "~/lib/diffRendering";import { cn, isMacPlatform } from "~/lib/utils";import { basenameOfPath } from "~/pierre-icons";import { FileTagChipContent } from "./chat/FileTagChip";@@ -82,6 +104,8 @@ import {import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";+import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView";+import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight";import { importPastedComposerText } from "./composerInlineTokenPaste";import { didComposerSelectionChangeVisibly } from "./composerSelection";import type { ComposerDraftContextRecords } from "./composerContextPresentation";@@ -491,6 +515,9 @@ function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {let range: StyledRange | null = null;let openLength = 0;for (const run of map.runs) {+ // A fence is drawn as a block, not revealed a character at a time, so its+ // delimiters never become marker widgets.+ if (run.nodeName === "codeBlock") continue;if (run.openLen > 0) {range ??= { from: run.pmPos, to: run.pmPos, markers: [] };range.markers.push({@@ -518,6 +545,162 @@ function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {return ranges;}+/**+ * A typed marker becomes a list item that remembers the marker it was typed+ * with, so the stored Markdown keeps `*` or `3)` rather than a canonical `-`.+ *+ * `- ` alone is not enough for a dash: it waits for the first character after+ * the space, which it carries into the new item. That is what lets the GFM+ * task gesture `- [ ] ` or `- [x] ` be typed whole and reach the task rule,+ * instead of being cut off by an instant bullet. A `- ` left on its own is+ * still a bullet the next time the draft is rebuilt.+ */+function listMarkerInputRule(find: RegExp, listType: "bulletList" | "orderedList"): InputRule {+ return new InputRule({+ find,+ handler: ({ state, range, match, chain }) => {+ const marker = match.groups?.marker ?? "-";+ const space = match.groups?.space ?? " ";+ const carried = match.groups?.carried ?? "";+ // Top-level paragraphs only: inside an item or a quote the new list+ // would nest under a line the stored draft writes flat.+ const $from = state.doc.resolve(range.from);+ if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;+ const command = chain()+ .deleteRange(range)+ .wrapInList(+ listType,+ listType === "orderedList" ? { start: Number.parseInt(marker, 10) || 1 } : {},+ )+ .updateAttributes("listItem", { marker, space });+ (carried ? command.insertContent(carried) : command).run();+ return undefined;+ },+ });+}++/**+ * `[ ] ` at the start of an existing bullet item turns it into a task, for+ * items that were already a list when the checkbox was wanted. New tasks are+ * typed whole, `- [ ] `, and reach the task rule directly.+ */+const bulletToTaskInputRule = new InputRule({+ find: /^\[([ xX])\] $/,+ handler: ({ state, range, match, chain }) => {+ const $from = state.doc.resolve(range.from);+ const item = $from.node(-1);+ if ($from.parent.type.name !== "paragraph" || item?.type.name !== "listItem") return null;+ // Any bullet converts; the task grammar only knows `-`, so a `*` or `+`+ // item comes back out as `- [ ]`.+ if (!["-", "*", "+"].includes((item.attrs as { marker?: string }).marker ?? "")) return null;+ const checked = (match[1] ?? " ").toLowerCase() === "x";+ chain()+ .command(({ tr }) => {+ convertBulletItemToTask(tr, range.from, range.to, checked);+ return true;+ })+ .run();+ return undefined;+ },+});++/** `- [ ] ` or `- [x] ` at a top-level paragraph, for the same reason as the list markers. */+function taskInputRule(type: NodeType): InputRule {+ const rule = wrappingInputRule({+ find: /^- \[([ xX])\] $/,+ type,+ getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),+ });+ return new InputRule({+ find: rule.find,+ handler: (props) =>+ props.state.doc.resolve(props.range.from).depth === 1 ? rule.handler(props) : null,+ });+}++function hasAncestor($pos: ResolvedPos, name: string): boolean {+ for (let depth = $pos.depth; depth > 0; depth -= 1) {+ if ($pos.node(depth).type.name === name) return true;+ }+ return false;+}++/**+ * `> ` at the start of a top-level paragraph opens a quote. Not inside a list:+ * a quote holds prose lines, and a list item is not one.+ */+const blockquoteInputRule = new InputRule({+ find: /^>(\s)$/,+ handler: ({ state, range, match, chain }) => {+ const $from = state.doc.resolve(range.from);+ if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;+ chain()+ .deleteRange(range)+ .wrapIn("blockquote", { prefix: `>${match[1] ?? " "}` })+ .run();+ return undefined;+ },+});++/**+ * `---` becomes a rule as the third dash lands; `***` and `___` need a space+ * after them so typing bold or an underscore is not interrupted, matching+ * Tiptap's own rule. Only at a top-level paragraph: the list and quote+ * serializers have no line to write a rule into. The typed characters are+ * kept as the rule's source, and `setHorizontalRule` adds a paragraph after a+ * rule at the end so the caret has somewhere to go.+ */+const horizontalRuleInputRule = new InputRule({+ find: /^(---|\*\*\*|___)\s?$/,+ handler: ({ state, range, match, chain }) => {+ const source = match[0] ?? "---";+ if (!source.startsWith("---") && !/\s$/.test(source)) return null;+ const $from = state.doc.resolve(range.from);+ if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;+ chain()+ .deleteRange(range)+ .setHorizontalRule()+ .command(({ tr }) => {+ // The rule is the block before the caret's paragraph.+ const $pos = tr.selection.$from;+ const index = $pos.index(0) - 1;+ if (index < 0) return true;+ const rulePos = $pos.posAtIndex(index, 0);+ const rule = tr.doc.nodeAt(rulePos);+ if (rule?.type.name === "horizontalRule") {+ tr.setNodeMarkup(rulePos, undefined, { ...rule.attrs, source });+ }+ return true;+ })+ .run();+ return undefined;+ },+});++/**+ * `# ` through `###### ` at a top-level paragraph make a heading. The space+ * is required, which is exactly what keeps `#1234` a pull request reference+ * with its picker rather than a heading. Not inside lists or quotes, whose+ * serializers have no line for one.+ */+const headingInputRule = new InputRule({+ find: /^(#{1,6})(\s)$/,+ handler: ({ state, range, match, chain }) => {+ const $from = state.doc.resolve(range.from);+ if ($from.parent.type.name !== "paragraph" || $from.depth !== 1) return null;+ chain()+ .deleteRange(range)+ .setNode("heading", { level: match[1]?.length ?? 1, space: match[2] ?? " " })+ .run();+ return undefined;+ },+});++/** Whether the caret sits inside a fenced code block. */+function isInCodeBlock(view: EditorView): boolean {+ return view.state.selection.$from.parent.type.spec.code === true;+}+const MarkerPluginKey = new PluginKey("composer-rich-markers");const ComposerMarkerPlugin = new Plugin({@@ -766,16 +949,16 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {expandedCursor: nextExpandedCursor,contextIds: map.contextIds,};- const cursorAdjacentToMention =+ // A fence holds no chips, so nothing in it should summon the mention or+ // command menu: `@` in code is a decorator, not a file. Suppressing the+ // trigger here also keeps the store from inserting a link the block can+ // only show as literal text, which the store would then count as a chip.+ const inCodeBlock = updated.state.selection.$from.parent.type.spec.code === true;+ const suppressTrigger =+ inCodeBlock ||isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");- onChangeRef.current(- nextValue,- nextCursor,- nextExpandedCursor,- cursorAdjacentToMention,- map.contextIds,- );+ onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, suppressTrigger, map.contextIds);}, []);const editorAttributes = useMemo(@@ -824,6 +1007,8 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {gapcursor: false,trailingNode: false,code: false,+ // The list extensions handle Backspace and Delete themselves.+ listKeymap: false,undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY },// Plain mode has no marks: typed markers stay literal characters....(richText ? {} : { bold: false, italic: false, strike: false }),@@ -837,16 +1022,78 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {...(richText? [ComposerCodeExtension,- TaskList,- ComposerTaskItemExtension.extend({+ ComposerCodeBlockExtension.extend({+ addNodeView() {+ return ReactNodeViewRenderer(ComposerCodeBlockNodeView, {+ // The header holds the language picker. Tiptap only shields+ // events aimed at the button element itself, so a click on+ // its icon or label would reach ProseMirror and move the+ // selection; keep every header event away from the editor.+ stopEvent: ({ event }) =>+ event.target instanceof Element &&+ event.target.closest(".chat-markdown-codeblock-header") !== null,+ });+ },+ // Tiptap's own ``` + space rule would open a fence inside a+ // list item or quote, where the serializer has no line for+ // it. Enter on a fence line covers the gesture at top level.addInputRules() {- return [- wrappingInputRule({- find: /^- \[([ xX])\] $/,- type: this.type,- getAttributes: (match) => ({ checked: match[1]?.toLowerCase() === "x" }),+ return [];+ },+ }),+ composerCodeBlockHighlight({+ resolveTheme: () =>+ resolveDiffThemeName(+ document.documentElement.classList.contains("dark") ? "dark" : "light",+ ),+ }),+ ...ComposerBlockExtensions.map((extension) =>+ extension.name === "blockquote"+ ? extension.extend({+ addInputRules() {+ return [blockquoteInputRule];+ },+ })+ : extension.name === "horizontalRule"+ ? extension.extend({+ addInputRules() {+ return [horizontalRuleInputRule];+ },+ })+ : extension.name === "heading"+ ? extension.extend({+ addInputRules() {+ return [headingInputRule];+ },+ })+ : extension,+ ),+ ...ComposerListExtensions.map((extension) =>+ extension.name === "listItem"+ ? extension+ : extension.extend({+ addInputRules() {+ return this.name === "bulletList"+ ? [+ listMarkerInputRule(/^(?<marker>[*+])(?<space>\s)$/, "bulletList"),+ listMarkerInputRule(+ /^(?<marker>-)(?<space>[ \t]+)(?<carried>[^\s[])$/,+ "bulletList",+ ),+ ]+ : [+ listMarkerInputRule(+ /^(?<marker>\d+[.)])(?<space>\s)$/,+ "orderedList",+ ),+ ];+ },}),- ];+ ),+ ComposerTaskListExtension,+ ComposerTaskItemExtension.extend({+ addInputRules() {+ return [taskInputRule(this.type), bulletToTaskInputRule];},}),]@@ -982,23 +1229,71 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {event.preventDefault();return true;}+ // Inside a fence Tab belongs to the code, not to the composer's+ // focus order or its autocomplete.+ if (+ event.key === "Tab" &&+ !event.metaKey &&+ !event.ctrlKey &&+ selectionInOneCodeBlock(view.state)+ ) {+ event.preventDefault();+ event.stopPropagation();+ return indentCodeBlock(view.state, event.shiftKey ? "out" : "in", (tr) =>+ view.dispatch(tr),+ );+ }+ // A fence is multi-line by definition, so Enter and Shift+Enter+ // belong to the code rather than to sending or splitting: inside a+ // block they make a line (a generic split would cut the fence in+ // two), and on a line that is only an opening fence they open the+ // block. Sending from inside a fence is still Cmd/Ctrl+Enter, which+ // falls through.+ if (+ event.key === "Enter" &&+ richText &&+ !event.metaKey &&+ !event.ctrlKey &&+ !event.isComposing+ ) {+ if (selectionInOneCodeBlock(view.state)) {+ event.preventDefault();+ event.stopPropagation();+ const dispatch = (tr: typeof view.state.tr) => view.dispatch(tr.scrollIntoView());+ return (+ exitCodeBlockOnClosingFence(view.state, dispatch) ||+ exitCodeBlockOnTrailingBlankLines(view) ||+ indentedNewlineInCodeBlock(view.state, dispatch) ||+ newlineInCode(view.state, dispatch)+ );+ }+ if (convertCodeFenceOnEnter(view.state, (tr) => view.dispatch(tr))) {+ event.preventDefault();+ event.stopPropagation();+ return true;+ }+ }const handler = onCommandKeyDownRef.current;if (event.key === "Enter") {const instance = editorHolder.current;const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);- const handled = handler?.("Enter", event, isTaskItem) ?? false;+ const isListItem = richText && (instance?.isActive("listItem") ?? false);+ const handled = handler?.("Enter", event, isTaskItem || isListItem) ?? false;if (handled) {event.preventDefault();event.stopPropagation();return true;}event.preventDefault();+ if ((isTaskItem || isListItem) && instance && splitOrLiftListItem(instance)) {+ return true;+ }if (- isTaskItem &&+ richText &&instance &&- (instance.commands.splitListItem("taskItem", { checked: false }) ||- (view.state.selection.$from.parent.content.size === 0 &&- instance.commands.liftListItem("taskItem")))+ hasAncestor(view.state.selection.$from, "blockquote") &&+ view.state.selection.$from.parent.content.size === 0 &&+ instance.commands.lift("blockquote")) {return true;}@@ -1050,6 +1345,19 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {const pastedText = clipboardData.getData("text/plain");if (!pastedText) return false;event.preventDefault();+ // A fence takes the clipboard verbatim. Running the markdown path+ // here would split the block on newlines, nest a pasted fence and+ // build chips the code block's schema cannot hold anyway.+ if (isInCodeBlock(view)) {+ const { from, to } = view.state.selection;+ view.dispatch(+ markAsClipboardEdit(+ view.state.tr.insertText(pastedText, from, to),+ "paste",+ ).scrollIntoView(),+ );+ return true;+ }const importFragment = importFragmentRef.current;let text = importFragment? importPastedComposerText(clipboardData, importFragment)@@ -1073,18 +1381,44 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {}const editorInstance = editorHolder.current;if (editorInstance) {- insertMarkdownParagraphs(text, skillLabelFor, { styling: richText }, (content) => {- // Tagged on the same transaction insertContent builds, so the- // paste is one undo step of its own.- editorInstance- .chain()- .command(({ tr }) => {- markAsClipboardEdit(tr, "paste");- return true;- })- .insertContent(content)- .run();- });+ // Inside a list item or quote, pasted block markup has nowhere to+ // go: it stays literal lines the next rebuild reads back. Inline+ // marks still apply.+ const $paste = view.state.selection.$from;+ const nested = ["listItem", "taskItem", "blockquote"].some((name) =>+ hasAncestor($paste, name),+ );+ insertMarkdownParagraphs(+ text,+ skillLabelFor,+ { styling: richText, blocks: !nested },+ (content) => {+ // Tagged on the same transaction insertContent builds, so the+ // paste is one undo step of its own.+ editorInstance+ .chain()+ .command(({ tr }) => {+ markAsClipboardEdit(tr, "paste");+ return true;+ })+ .insertContent(content)+ .command(({ tr }) => {+ // A paste ending in a rule leaves the rule selected, and+ // the next keystroke would replace it. The caret goes to+ // the line after it, which is added when there is none.+ const { selection } = tr;+ if (!(selection instanceof NodeSelection) || !selection.node.isBlock) {+ return true;+ }+ if (!tr.doc.resolve(selection.to).nodeAfter?.isTextblock) {+ tr.insert(selection.to, tr.doc.type.schema.nodes.paragraph!.create());+ }+ tr.setSelection(TextSelection.create(tr.doc, selection.to + 1));+ return true;+ })+ .run();+ },+ );scrollTiptapCaretIntoView(editorInstance);}return true;@@ -1330,15 +1664,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {const clipboardData = event.clipboardData;const { from, to } = editor.state.selection;if (from === to) return;- const { doc, schema } = editor.state;- const slice = doc.slice(from, to);- const first = slice.content.firstChild;- const content = first?.isInline- ? schema.nodes.paragraph!.create(null, slice.content)- : first?.type.name === "taskItem"- ? schema.nodes.taskList!.create(null, slice.content)- : slice.content;- const text = serializeEditorDoc(doc.type.create(null, content)).value;+ const text = serializeSelection(editor.state.doc, from, to);const contextIds = Array.from(new Set(collectInlineContextIds(text)));const fragment = contextIds.length > 0 ? build?.(contextIds) : null;event.preventDefault();@@ -1442,7 +1768,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) {function insertMarkdownParagraphs(value: string,skillLabelFor: (name: string) => SkillMeta,- options: { styling: boolean },+ options: { styling: boolean; blocks?: boolean },insertContent: (content: JSONContent[] | JSONContent) => void,): void {const blocks = buildTiptapContent(value, skillLabelFor, options);diff --git a/apps/web/src/components/chat/ComposerCodeBlockLanguagePicker.tsx b/apps/web/src/components/chat/ComposerCodeBlockLanguagePicker.tsxnew file mode 100644index 00000000000..bf200bab53d--- /dev/null+++ b/apps/web/src/components/chat/ComposerCodeBlockLanguagePicker.tsx@@ -0,0 +1,121 @@+import { CheckIcon, ChevronDownIcon } from "lucide-react";+import { useMemo, useState } from "react";++import {+ CODE_BLOCK_LANGUAGES,+ type CodeBlockLanguage,+ codeLanguageEntry,+ codeLanguageLabel,+} from "~/composer-code-languages";+import { syntheticFileNameForLanguageId } from "~/pierre-icons";++import { Button } from "../ui/button";+import {+ Combobox,+ ComboboxEmpty,+ ComboboxItem,+ ComboboxList,+ ComboboxPopup,+ ComboboxSearchInput,+ ComboboxTrigger,+} from "../ui/combobox";+import { PierreEntryIcon } from "./PierreEntryIcon";++/**+ * The language's file icon: plain text gets the text-file icon, and a+ * language the icon set does not cover gets the default file icon, so every+ * entry has one and the labels line up.+ */+function LanguageIcon(props: { language: string; theme: "light" | "dark" }) {+ const fileName = props.language ? syntheticFileNameForLanguageId(props.language) : "file.txt";+ return (+ <PierreEntryIcon pathValue={fileName} kind="file" theme={props.theme} className="size-3.5" />+ );+}++/**+ * The language control in a composer fence's header: shows what the fence+ * declares and switches it from a searchable list. A language typed on the+ * fence line that the list does not carry is offered as its own entry, so+ * the current choice is always visible and checked.+ */+export function ComposerCodeBlockLanguagePicker(props: {+ language: string;+ theme: "light" | "dark";+ disabled: boolean;+ onChange: (language: string) => void;+}) {+ const [query, setQuery] = useState("");+ const current = codeLanguageEntry(props.language)?.id ?? props.language;+ const items = useMemo<CodeBlockLanguage[]>(+ () =>+ CODE_BLOCK_LANGUAGES.some((entry) => entry.id === current)+ ? [...CODE_BLOCK_LANGUAGES]+ : [{ id: current, label: current }, ...CODE_BLOCK_LANGUAGES],+ [current],+ );+ const filteredItems = useMemo(() => {+ const needle = query.trim().toLowerCase();+ if (!needle) return items;+ return items.filter(+ (entry) => entry.label.toLowerCase().includes(needle) || entry.id.includes(needle),+ );+ }, [items, query]);+ const selected = items.find((entry) => entry.id === current) ?? null;++ return (+ // The trigger's pill pads its content by 8px (padding plus border) and the+ // button pulls a leading icon back 2px; offsetting the difference lines+ // the icon up with the code below while keeping the hover pill.+ <span className="-ml-1.5 flex min-w-0">+ <Combobox+ items={items}+ filteredItems={filteredItems}+ autoHighlight+ itemToStringLabel={(entry) => entry.label}+ isItemEqualToValue={(a, b) => a.id === b.id}+ value={selected}+ onOpenChange={(open) => {+ if (!open) setQuery("");+ }}+ onValueChange={(entry) => {+ if (entry && entry.id !== current) props.onChange(entry.id);+ }}+ >+ <ComboboxTrigger+ render={+ <Button+ type="button"+ variant="ghost-muted"+ size="xs"+ disabled={props.disabled}+ aria-label={`Code language: ${codeLanguageLabel(props.language)}`}+ />+ }+ >+ <LanguageIcon language={current} theme={props.theme} />+ <span className="max-w-40 truncate">{codeLanguageLabel(props.language)}</span>+ <ChevronDownIcon className="opacity-60" />+ </ComboboxTrigger>+ <ComboboxPopup align="start" className="w-56">+ <ComboboxSearchInput+ aria-label="Search languages"+ placeholder="Search languages"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ <ComboboxEmpty>No matching languages.</ComboboxEmpty>+ <ComboboxList>+ {(entry: CodeBlockLanguage) => (+ <ComboboxItem key={entry.id || "plain"} value={entry}>+ <LanguageIcon language={entry.id} theme={props.theme} />+ <span className="min-w-0 flex-1 truncate">{entry.label}</span>+ {entry.id === current ? <CheckIcon className="ml-auto" /> : null}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxPopup>+ </Combobox>+ </span>+ );+}diff --git a/apps/web/src/components/chat/ComposerCodeBlockNodeView.tsx b/apps/web/src/components/chat/ComposerCodeBlockNodeView.tsxnew file mode 100644index 00000000000..fcaf93af941--- /dev/null+++ b/apps/web/src/components/chat/ComposerCodeBlockNodeView.tsx@@ -0,0 +1,67 @@+import { NodeViewContent, NodeViewWrapper, type NodeViewProps } from "@tiptap/react";++import { languageOfInfoString, withInfoStringLanguage } from "~/composer-code-languages";++import { useTheme } from "../../hooks/useTheme";+import { MarkdownCodeBlockFrame } from "../ChatMarkdown";+import { ComposerCodeBlockLanguagePicker } from "./ComposerCodeBlockLanguagePicker";++/**+ * Draws a composer fence in the chat view's own code block frame, so a draft+ * looks like the message it is about to become, with the language title+ * swapped for a picker that rewrites the fence's language in place.+ *+ * The chrome stops at the language. Chat's wrap and copy buttons act on text+ * the reader cannot change; here the text is the draft, and both are already+ * a selection away.+ */+export function ComposerCodeBlockNodeView({+ node,+ editor,+ getPos,+ updateAttributes,+}: NodeViewProps) {+ const { resolvedTheme } = useTheme();+ const info = typeof node.attrs.language === "string" ? node.attrs.language : "";+ const language = languageOfInfoString(info);++ const changeLanguage = (next: string) => {+ updateAttributes({ language: withInfoStringLanguage(info, next) });+ // Back into the code, at its end, the way a picker hands focus back.+ const position = getPos();+ if (typeof position === "number") {+ editor+ .chain()+ .focus(position + 1 + node.content.size)+ .run();+ }+ };++ return (+ <MarkdownCodeBlockFrame+ as={NodeViewWrapper}+ language={language || "text"}+ fenceTitle={null}+ theme={resolvedTheme}+ headerProps={{ contentEditable: false }}+ title={+ <ComposerCodeBlockLanguagePicker+ language={language}+ theme={resolvedTheme}+ disabled={!editor.isEditable}+ onChange={changeLanguage}+ />+ }+ >+ <div className="chat-markdown-shiki">+ <pre className="max-w-full overflow-x-auto px-3 pt-1 pb-2">+ {/* A caret needs a line to sit on even before any code is typed. */}+ <NodeViewContent<"code">+ as="code"+ className="block min-h-[1lh] font-mono whitespace-pre-wrap text-inherit [overflow-wrap:anywhere]"+ />+ </pre>+ </div>+ </MarkdownCodeBlockFrame>+ );+}diff --git a/apps/web/src/components/composerCodeBlockHighlight.test.ts b/apps/web/src/components/composerCodeBlockHighlight.test.tsnew file mode 100644index 00000000000..bd765dbd7b4--- /dev/null+++ b/apps/web/src/components/composerCodeBlockHighlight.test.ts@@ -0,0 +1,152 @@+import { Editor } from "@tiptap/core";+import type { EditorView } from "@tiptap/pm/view";+import StarterKit from "@tiptap/starter-kit";+import { afterEach, describe, expect, it, vi } from "vite-plus/test";++import { ComposerCodeBlockExtension } from "~/composer-rich-text-doc";+import type { DiffThemeName } from "~/lib/diffRendering";+import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";++import {+ composerCodeBlockHighlight,+ MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH,+ shouldHighlightCodeBlock,+ tokenizeBlock,+} from "./composerCodeBlockHighlight";++vi.mock("~/lib/syntaxHighlighting", () => ({ getSyntaxHighlighterPromise: vi.fn() }));++const THEME = "github-dark" as DiffThemeName;++/**+ * Stands in for the Shiki highlighter so the offset arithmetic can be checked+ * without loading a real grammar. Splits each line into whitespace-delimited+ * tokens, which is enough shape for the flattening logic under test.+ */+function fakeHighlighter(colorFor: (content: string) => string | undefined) {+ return {+ codeToTokens(code: string) {+ return {+ tokens: code.split(/\r?\n/).map((line) =>+ line+ .split(/(\s+)/)+ .filter((part) => part.length > 0)+ .map((content) => ({ content, color: colorFor(content) })),+ ),+ };+ },+ } as unknown as Parameters<typeof tokenizeBlock>[0];+}++describe("composer code block highlighting", () => {+ it("maps token offsets to positions within the block text", () => {+ const highlighter = fakeHighlighter((content) => (content === "const" ? "#ff0000" : undefined));++ const decorations = tokenizeBlock(highlighter, "const answer = 42", "ts", THEME);++ expect(decorations).toEqual([{ from: 0, to: 5, color: "#ff0000" }]);+ });++ it("accounts for the newline between lines", () => {+ const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));++ const decorations = tokenizeBlock(highlighter, "one\ntwo", "ts", THEME);++ // "one" is 3 characters, then the newline, so "two" starts at 4.+ expect(decorations).toEqual([{ from: 4, to: 7, color: "#00ff00" }]);+ });++ it("accounts for both characters of a CRLF line break", () => {+ const highlighter = fakeHighlighter((content) => (content === "two" ? "#00ff00" : undefined));++ const decorations = tokenizeBlock(highlighter, "one\r\ntwo", "ts", THEME);++ expect(decorations).toEqual([{ from: 5, to: 8, color: "#00ff00" }]);+ });++ it("skips whitespace-only tokens so indentation is not decorated", () => {+ const highlighter = fakeHighlighter(() => "#0000ff");++ const decorations = tokenizeBlock(highlighter, " indented", "ts", THEME);++ expect(decorations).toEqual([{ from: 2, to: 10, color: "#0000ff" }]);+ });++ it("falls back to plain text when the grammar throws", () => {+ const throwing = {+ codeToTokens() {+ throw new Error("unsupported language");+ },+ } as unknown as Parameters<typeof tokenizeBlock>[0];++ expect(tokenizeBlock(throwing, "const answer = 42", "nope", THEME)).toEqual([]);+ });+});++describe("the highlighting size cap", () => {+ // Each keystroke re-tokenizes the whole fence on the main thread; past a+ // few hundred lines that stalls typing, so large fences stay plain.+ it("highlights a fence up to the cap", () => {+ expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH))).toBe(true);+ });++ it("leaves a fence past the cap plain", () => {+ expect(shouldHighlightCodeBlock("x".repeat(MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH + 1))).toBe(false);+ });+});++describe("a highlighter that fails to load", () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ /**+ * Shiki can fail to initialize at all. The blocks it could not reach stay+ * plain, the ones it could are still painted, and nothing is left rejected.+ */+ it("still repaints the blocks whose highlighter loaded", async () => {+ vi.mocked(getSyntaxHighlighterPromise).mockImplementation((language) =>+ language === "ts"+ ? Promise.resolve(fakeHighlighter(() => "#ff0000"))+ : Promise.reject(new Error("Shiki failed to initialize")),+ );+ const editor = new Editor({+ extensions: [+ StarterKit.configure({ codeBlock: false, trailingNode: false }),+ ComposerCodeBlockExtension,+ composerCodeBlockHighlight({ resolveTheme: () => THEME }),+ ],+ content: {+ type: "doc",+ content: [+ { type: "codeBlock", attrs: { language: "ts" }, content: [{ type: "text", text: "a" }] },+ { type: "codeBlock", attrs: { language: "py" }, content: [{ type: "text", text: "b" }] },+ ],+ },+ });+ // The plugin watches <html> for theme changes; the unit suite has no DOM.+ vi.stubGlobal("document", { documentElement: {} });+ vi.stubGlobal(+ "MutationObserver",+ class {+ observe() {}+ disconnect() {}+ },+ );+ // ProseMirror names each plugin after its key, though it does not type it.+ const plugin = editor.extensionManager.plugins.find((candidate) =>+ (candidate as unknown as { key: string }).key.startsWith("composerCodeBlockHighlight"),+ );+ const repainted = new Promise<void>((resolve) => {+ const view = {+ get state() {+ return editor.state;+ },+ dispatch: () => resolve(),+ } as unknown as EditorView;+ plugin?.spec.view?.(view);+ });++ await expect(repainted).resolves.toBeUndefined();+ });+});diff --git a/apps/web/src/components/composerCodeBlockHighlight.ts b/apps/web/src/components/composerCodeBlockHighlight.tsnew file mode 100644index 00000000000..68f024cb907--- /dev/null+++ b/apps/web/src/components/composerCodeBlockHighlight.ts@@ -0,0 +1,231 @@+import { Extension } from "@tiptap/core";+import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";+import { Decoration, DecorationSet } from "@tiptap/pm/view";+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";++import type { DiffThemeName } from "~/lib/diffRendering";+import { languageOfInfoString } from "~/composer-code-languages";+import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting";++interface HighlightedBlock {+ /** Guards against repainting a block whose text and language are unchanged. */+ readonly signature: string;+ readonly decorations: ReadonlyArray<{ from: number; to: number; color: string }>;+}++const composerCodeBlockHighlightKey = new PluginKey<DecorationSet>("composerCodeBlockHighlight");++/**+ * Past this many characters a fence is left plain. Any edit changes a block's+ * signature, so each keystroke re-tokenizes the whole block synchronously on+ * the main thread: a few milliseconds for a couple of hundred lines, but ~80ms+ * at a thousand, which stalls typing. 20k characters is roughly 400–500 lines+ * of ordinary code; a fence that shrinks back under it is highlighted again.+ */+export const MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH = 20_000;++export function shouldHighlightCodeBlock(code: string): boolean {+ return code.length <= MAX_HIGHLIGHTED_CODE_BLOCK_LENGTH;+}+function blockSignature(node: ProseMirrorNode, theme: DiffThemeName): string {+ // A separator that cannot occur in a language name keeps the parts distinct.+ return [theme, String(node.attrs.language ?? ""), node.textContent].join("\u0000");+}++/**+ * The composer's code blocks, which are always top-level: list items and+ * quotes cannot hold one. Scanning only the top level keeps a keystroke in a+ * long draft from walking every node in it.+ */+function collectCodeBlocks(state: EditorState): Array<{ node: ProseMirrorNode; pos: number }> {+ const blocks: Array<{ node: ProseMirrorNode; pos: number }> = [];+ state.doc.forEach((node, pos) => {+ if (node.type.name === "codeBlock") blocks.push({ node, pos });+ });+ return blocks;+}++/**+ * Highlights composer code blocks with the same Shiki instance the chat view+ * uses, painted as inline decorations so the text nodes stay editable.+ *+ * Highlighting is asynchronous and per block: a keystroke re-tokenizes only the+ * block that changed, and only after its highlighter has resolved. Blocks whose+ * text and language are unchanged reuse their previous decorations.+ */+export function composerCodeBlockHighlight(options: {+ resolveTheme: () => DiffThemeName;+}): Extension {+ return Extension.create({+ name: "composerCodeBlockHighlight",++ addProseMirrorPlugins() {+ // Every keystroke in a code block mints a new signature, so each scan+ // drops the signatures the document no longer holds. The cache is then+ // bounded by the document itself, and no block it holds is ever evicted.+ const cache = new Map<string, HighlightedBlock>();+ // The latest scan's signatures, so a tokenize that resolves after its+ // block was edited away does not put it back.+ let live = new Set<string>();++ return [+ new Plugin<DecorationSet>({+ key: composerCodeBlockHighlightKey,++ state: {+ init: () => DecorationSet.empty,+ apply(transaction, value, _oldState, newState) {+ if (!transaction.docChanged && !transaction.getMeta(composerCodeBlockHighlightKey)) {+ return value.map(transaction.mapping, transaction.doc);+ }+ return buildDecorations(newState, cache, options.resolveTheme());+ },+ },++ props: {+ decorations(state) {+ return composerCodeBlockHighlightKey.getState(state);+ },+ },++ view(view) {+ let disposed = false;+ let paintedTheme = options.resolveTheme();+ let scannedDoc: ProseMirrorNode | null = null;++ /**+ * Tokenizes any block missing from the cache, then repaints once.+ * Returning early when nothing is pending is what stops the+ * dispatch below from re-triggering this on its own update.+ */+ const refresh = () => {+ const theme = options.resolveTheme();+ const themeChanged = theme !== paintedTheme;+ paintedTheme = theme;+ // A selection change cannot alter what needs tokenizing, and+ // building a signature means concatenating every block's text.+ if (!themeChanged && view.state.doc === scannedDoc) return;+ scannedDoc = view.state.doc;+ const blocks = collectCodeBlocks(view.state);+ live = new Set(blocks.map(({ node }) => blockSignature(node, theme)));+ for (const signature of cache.keys()) {+ if (!live.has(signature)) cache.delete(signature);+ }+ const pending = blocks.filter(+ ({ node }) =>+ shouldHighlightCodeBlock(node.textContent) &&+ !cache.has(blockSignature(node, theme)),+ );+ if (pending.length === 0) {+ // A theme switch keeps every signature but changes which one+ // applies, so the painted decorations still have to be rebuilt.+ if (themeChanged) {+ view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));+ }+ return;+ }++ // Settled rather than all: a block whose highlighter fails to+ // load stays plain, and the others are still painted.+ void Promise.allSettled(+ pending.map(async ({ node }) => {+ // The stored info string keeps everything after the language+ // (`js title=x`); Shiki wants only the name.+ const language =+ languageOfInfoString(String(node.attrs.language ?? "")) || "text";+ const signature = blockSignature(node, theme);+ const highlighter = await getSyntaxHighlighterPromise(language);+ if (disposed || cache.has(signature) || !live.has(signature)) return;+ cache.set(signature, {+ signature,+ decorations: tokenizeBlock(highlighter, node.textContent, language, theme),+ });+ }),+ ).then(() => {+ if (disposed) return;+ view.dispatch(view.state.tr.setMeta(composerCodeBlockHighlightKey, true));+ });+ };++ refresh();+ // The theme lives on <html>, outside the editor, so nothing would+ // otherwise tell the view a repaint is due.+ const themeObserver = new MutationObserver(refresh);+ themeObserver.observe(document.documentElement, {+ attributeFilter: ["class"],+ });++ return {+ update: refresh,+ destroy() {+ disposed = true;+ themeObserver.disconnect();+ },+ };+ },+ }),+ ];+ },+ });+}++type Highlighter = Awaited<ReturnType<typeof getSyntaxHighlighterPromise>>;++/** Flattens Shiki's line/token structure into offsets within the block's text. */+export function tokenizeBlock(+ highlighter: Highlighter,+ code: string,+ language: string,+ theme: DiffThemeName,+): ReadonlyArray<{ from: number; to: number; color: string }> {+ let tokens;+ try {+ tokens = highlighter.codeToTokens(code, { lang: language, theme }).tokens;+ } catch {+ // An unsupported language should read as plain text, not break the editor.+ return [];+ }++ const decorations: Array<{ from: number; to: number; color: string }> = [];+ let offset = 0;+ for (const [lineIndex, line] of tokens.entries()) {+ // The separator between lines, which Shiki drops; CRLF is two characters.+ if (lineIndex > 0) offset += code.startsWith("\r\n", offset) ? 2 : 1;+ for (const token of line) {+ const length = token.content.length;+ if (token.color && token.content.trim()) {+ decorations.push({ from: offset, to: offset + length, color: token.color });+ }+ offset += length;+ }+ }+ return decorations;+}++function buildDecorations(+ state: EditorState,+ cache: Map<string, HighlightedBlock>,+ theme: DiffThemeName,+): DecorationSet {+ const decorations: Decoration[] = [];+ for (const { node, pos } of collectCodeBlocks(state)) {+ if (!shouldHighlightCodeBlock(node.textContent)) continue;+ const highlighted = cache.get(blockSignature(node, theme));+ if (!highlighted) continue;+ // Token offsets index the block's text, which lines up with document+ // positions only because `codeBlock` is `text*` with no marks — one+ // unmarked text node, so `content.size === textContent.length`. Allowing+ // marks or hard breaks in the code block would desync these silently.+ if (node.content.size !== node.textContent.length) continue;+ // +1 steps past the code block's opening token into its text.+ const start = pos + 1;+ for (const decoration of highlighted.decorations) {+ decorations.push(+ Decoration.inline(start + decoration.from, start + decoration.to, {+ style: `color:${decoration.color}`,+ }),+ );+ }+ }+ return DecorationSet.create(state.doc, decorations);+}diff --git a/apps/web/src/composer-block-shortcuts.test.ts b/apps/web/src/composer-block-shortcuts.test.tsnew file mode 100644index 00000000000..8ecd47d0e29--- /dev/null+++ b/apps/web/src/composer-block-shortcuts.test.ts@@ -0,0 +1,126 @@+import { Editor } from "@tiptap/core";+import { TextSelection } from "@tiptap/pm/state";+import StarterKit from "@tiptap/starter-kit";+import { describe, expect, it } from "vite-plus/test";++import {+ buildDocJson,+ ComposerBlockExtensions,+ ComposerCodeBlockExtension,+ ComposerListExtensions,+ ComposerTaskItemExtension,+ ComposerTaskListExtension,+ serializeEditorDoc,+} from "./composer-rich-text-doc";++// The same modifier ProseMirror's keymap reads "Mod" as.+const mac = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);++/** A key chord as the browser reports it: key, keyCode and modifiers. */+function chord(spec: string) {+ const parts = spec.split("-");+ const key = parts.pop()!;+ const has = (name: string) => parts.includes(name);+ const base = key.length === 1 ? key.toUpperCase() : key;+ return {+ key: has("Shift") && /^\d$/.test(key) ? "!@#$%^&*("[Number(key) - 1]! : key,+ keyCode: base.length === 1 ? base.charCodeAt(0) : 0,+ shiftKey: has("Shift"),+ altKey: has("Alt"),+ metaKey: has("Mod") && mac,+ ctrlKey: has("Mod") && !mac,+ preventDefault() {},+ stopPropagation() {},+ } as unknown as KeyboardEvent;+}++/**+ * Presses `spec` with the caret inside `value`, the way the composer's+ * editor would receive it, and returns the stored Markdown.+ */+function press(value: string, spec: string) {+ const editor = new Editor({+ extensions: [+ StarterKit.configure({+ blockquote: false,+ bulletList: false,+ codeBlock: false,+ heading: false,+ horizontalRule: false,+ listItem: false,+ orderedList: false,+ trailingNode: false,+ }),+ ComposerCodeBlockExtension,+ ...ComposerBlockExtensions,+ ...ComposerListExtensions,+ ComposerTaskListExtension,+ ComposerTaskItemExtension,+ ],+ content: buildDocJson(value, (name) => ({ label: name, description: null })),+ });+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));+ // What the view's `someProp("handleKeyDown")` does, without mounting one:+ // offer the key to each extension plugin in order until one handles it.+ // An unmounted editor's state does not carry them yet, so they come from+ // the extension manager.+ const event = chord(spec);+ const before = editor.state.doc;+ const handled = editor.extensionManager.plugins.some((plugin) =>+ plugin.props.handleKeyDown?.call(plugin, editor.view, event),+ );+ return {+ handled,+ changed: !editor.state.doc.eq(before),+ value: serializeEditorDoc(editor.state.doc).value,+ };+}++// Tiptap's own block shortcuts would nest a list, task list, code block or+// heading inside a quote, or restructure a list item. The serializers only+// write what the composer's grammar has, so the nested block, and the text+// in it, would vanish from the stored draft. None of these are the+// composer's shortcuts; they must do nothing.+const BLOCK_CHORDS = [+ "Mod-Shift-8",+ "Mod-Shift-7",+ "Mod-Shift-9",+ "Mod-Shift-b",+ "Mod-Alt-c",+ "Mod-Alt-1",+ "Mod-Alt-3",+];++describe("Tiptap's block shortcuts", () => {+ it.each(BLOCK_CHORDS)("leave a quote's text alone on %s", (spec) => {+ expect(press("> keep this text", spec).value).toBe("> keep this text");+ });++ it.each(BLOCK_CHORDS)("leave a list item alone on %s", (spec) => {+ expect(press("- item", spec).value).toBe("- item");+ });++ it.each(BLOCK_CHORDS)("leave a paragraph alone on %s", (spec) => {+ expect(press("plain text", spec).value).toBe("plain text");+ });++ // Guards the harness itself: a chord the composer keeps must still reach+ // the keymap, or every case above would pass without pressing anything.+ it("still delivers the composer's own keys", () => {+ expect(press("**bold**", "Mod-b").handled).toBe(true);+ });++ // Sinking or lifting an item moves it without touching its `indent`, so+ // the stored draft keeps the old nesting and the next rebuild undoes the+ // move. Nesting belongs to the composer's own Tab, which edits the source.+ it.each([+ ["- p\n- a", "Tab"],+ ["- p\n - a", "Shift-Tab"],+ ["- [ ] p\n- [ ] a", "Tab"],+ ["- [ ] p\n - [ ] a", "Shift-Tab"],+ ])("leave the nesting of %j alone on %s", (value, spec) => {+ const result = press(value, spec);+ expect(result.changed).toBe(false);+ expect(result.value).toBe(value);+ });+});diff --git a/apps/web/src/composer-code-block.test.ts b/apps/web/src/composer-code-block.test.tsnew file mode 100644index 00000000000..3a0ec2fe127--- /dev/null+++ b/apps/web/src/composer-code-block.test.ts@@ -0,0 +1,391 @@+import { describe, expect, it } from "vite-plus/test";+import { Editor, Node } from "@tiptap/core";+import { newlineInCode } from "@tiptap/pm/commands";+import { TextSelection } from "@tiptap/pm/state";++import {+ CODE_BLOCK_INDENT,+ indentCodeBlock,+ indentLines,+ convertCodeFenceOnEnter,+ exitCodeBlockOnClosingFence,+ exitCodeBlockOnTrailingBlankLines,+ indentedNewlineInCodeBlock,+ leadingWhitespace,+ outdentLine,+} from "./composer-code-block";+import StarterKit from "@tiptap/starter-kit";++import {+ ComposerCodeBlockExtension,+ ComposerListExtensions,+ serializeEditorDoc,+} from "./composer-rich-text-doc";++const extensions = [+ StarterKit.configure({ codeBlock: false, trailingNode: false }),+ ComposerCodeBlockExtension,+ ...ComposerListExtensions,+ Node.create({+ name: "composer-mention",+ group: "inline",+ inline: true,+ atom: true,+ addAttributes: () => ({ path: { default: "" }, source: { default: "" } }),+ }),+];++describe("leadingWhitespace", () => {+ it("reads the indent a new line should inherit", () => {+ expect(leadingWhitespace(" nested()")).toBe(" ");+ expect(leadingWhitespace("\tnested()")).toBe("\t");+ expect(leadingWhitespace("flush()")).toBe("");+ });++ it("stops at the first non-space so code is never treated as indent", () => {+ expect(leadingWhitespace(" a b")).toBe(" ");+ });+});++describe("outdentLine", () => {+ it("removes a full indent when there is one", () => {+ expect(outdentLine(" deep")).toBe(" deep");+ });++ /** Hand-indented lines should still outdent rather than refuse to move. */+ it("falls back to a single space or tab", () => {+ expect(outdentLine(" odd")).toBe("odd");+ expect(outdentLine("\ttabbed")).toBe("tabbed");+ });++ it("bottoms out instead of eating code", () => {+ expect(outdentLine("flush()")).toBe("flush()");+ });+});++describe("indentLines", () => {+ it("indents every line it is given", () => {+ expect(indentLines(["a", "b"], "in")).toEqual([+ `${CODE_BLOCK_INDENT}a`,+ `${CODE_BLOCK_INDENT}b`,+ ]);+ });++ /** Indenting a blank line would leave whitespace the user cannot see. */+ it("leaves blank lines alone", () => {+ expect(indentLines(["a", "", "b"], "in")).toEqual([+ `${CODE_BLOCK_INDENT}a`,+ "",+ `${CODE_BLOCK_INDENT}b`,+ ]);+ });++ it("outdents every line it is given", () => {+ expect(indentLines([" a", " b", "c"], "out")).toEqual([" a", "b", "c"]);+ });+});++/** Builds an editor holding a single fenced block, with the caret placed by offset. */+function codeEditor(code: string, at?: { from: number; to?: number }) {+ const editor = new Editor({+ extensions,+ content: {+ type: "doc",+ content: [{ type: "codeBlock", content: [{ type: "text", text: code }] }],+ },+ });+ const start = 1;+ const from = start + (at?.from ?? code.length);+ const to = start + (at?.to ?? at?.from ?? code.length);+ editor.view.dispatch(+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from, to)),+ );+ return editor;+}++const textOf = (editor: Editor) => editor.state.doc.textContent;++describe("indentedNewlineInCodeBlock", () => {+ it("carries the current indentation onto the new line", () => {+ const editor = codeEditor("function f() {\n body()");+ const handled = indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));+ expect(handled).toBe(true);+ expect(textOf(editor)).toBe("function f() {\n body()\n ");+ });++ /**+ * With no indent to carry there is nothing to add, so the default newline+ * should handle it and stay a single undo step.+ */+ it("declines an unindented line", () => {+ const editor = codeEditor("flush()");+ expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);+ expect(textOf(editor)).toBe("flush()");+ });++ it("indents from the line the caret is on, not the last line", () => {+ const editor = codeEditor(" deep()\nflush()", { from: 10 });+ indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));+ expect(textOf(editor)).toBe(" deep()\n \nflush()");+ });++ it("replaces the selected text rather than keeping it", () => {+ const editor = codeEditor(" keep()DROP", { from: 8, to: 12 });+ indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));+ expect(textOf(editor)).toBe(" keep()\n ");+ });++ it("does nothing outside a code block", () => {+ const editor = new Editor({+ extensions,+ content: {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: " hi" }] }],+ },+ });+ expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);+ });+});++/** Enter inside a fence, in the order the composer's key handler tries it. */+function pressEnter(editor: Editor) {+ const dispatch = (tr: Parameters<typeof editor.view.dispatch>[0]) => editor.view.dispatch(tr);+ return (+ exitCodeBlockOnTrailingBlankLines(editor.view) ||+ indentedNewlineInCodeBlock(editor.state, dispatch) ||+ newlineInCode(editor.state, dispatch)+ );+}++describe("exitCodeBlockOnTrailingBlankLines", () => {+ it("leaves the block once two blank lines end it", () => {+ const editor = codeEditor("flush()");+ pressEnter(editor);+ pressEnter(editor);+ expect(editor.state.doc.childCount).toBe(1);+ pressEnter(editor);+ expect(editor.state.doc.firstChild?.textContent).toBe("flush()");+ expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");+ });++ /** Enter carries indentation, so the blank lines after nested code are not empty. */+ it("counts lines holding only carried indentation as blank", () => {+ const editor = codeEditor(" nested()");+ pressEnter(editor);+ pressEnter(editor);+ expect(editor.state.doc.childCount).toBe(1);+ pressEnter(editor);+ expect(editor.state.doc.firstChild?.textContent).toBe(" nested()");+ expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");+ });++ /** An unclosed fence runs to the end of the draft, so leaving it must close it. */+ it("closes an unclosed fence on the way out", () => {+ const editor = codeEditor("flush()");+ editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "close", ""));+ pressEnter(editor);+ pressEnter(editor);+ pressEnter(editor);+ expect(editor.state.doc.firstChild?.attrs.close).toBe("\n```");+ });++ it("stays in the block when the caret is not at its end", () => {+ const editor = codeEditor("a\n\n\nb", { from: 3 });+ expect(exitCodeBlockOnTrailingBlankLines(editor.view)).toBe(false);+ });+});++describe("exitCodeBlockOnClosingFence", () => {+ const exit = (editor: Editor) =>+ exitCodeBlockOnClosingFence(editor.state, (tr) => editor.view.dispatch(tr));++ it("ends the block at a typed closing fence and starts a line after it", () => {+ const editor = codeEditor("const a = 1\n```");+ editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "language", "ts"));+ expect(exit(editor)).toBe(true);+ editor.view.dispatch(editor.state.tr.insertText("explain this"));+ expect(serializeEditorDoc(editor.state.doc).value).toBe(+ "```ts\nconst a = 1\n```\nexplain this",+ );+ });++ it("moves the lines after the fence out of the block", () => {+ const editor = codeEditor("a\n```\nb", { from: "a\n```".length });+ expect(exit(editor)).toBe(true);+ expect(serializeEditorDoc(editor.state.doc).value).toBe("```\na\n```\n\nb");+ expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");+ expect(editor.state.selection.$from.parent.textContent).toBe("");+ });++ it.each([+ ["a line that cannot close the fence", "a\n``", undefined],+ ["a caret before the end of the line", "a\n```", { from: "a\n``".length }],+ ])("ignores %s", (_, code, at) => {+ expect(exit(codeEditor(code, at))).toBe(false);+ });+});++describe("indentCodeBlock", () => {+ it("inserts an indent at a collapsed caret", () => {+ const editor = codeEditor("ab", { from: 1 });+ expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(true);+ expect(textOf(editor)).toBe(`a${CODE_BLOCK_INDENT}b`);+ });++ it("indents every line a selection touches", () => {+ const editor = codeEditor("one\ntwo\nthree", { from: 1, to: 9 });+ indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));+ expect(textOf(editor)).toBe(" one\n two\n three");+ });++ /** A selection of whole lines ends at the start of the next one, which it does not touch. */+ it("leaves the line a selection ends at the start of", () => {+ const editor = codeEditor("one\ntwo", { from: 0, to: 4 });+ indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));+ expect(textOf(editor)).toBe(" one\ntwo");+ });++ it("outdents every line a selection touches", () => {+ const editor = codeEditor(" one\n two", { from: 2, to: 9 });+ indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr));+ expect(textOf(editor)).toBe("one\ntwo");+ });++ /** Repeated Tab presses should keep working on the same block. */+ it("keeps the selection across the shifted lines", () => {+ const editor = codeEditor("one\ntwo", { from: 0, to: 7 });+ indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));+ indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));+ expect(textOf(editor)).toBe(" one\n two");+ });++ it("reports handled when outdenting can go no further, so Tab never escapes the editor", () => {+ const editor = codeEditor("one\ntwo", { from: 0, to: 7 });+ expect(indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr))).toBe(true);+ expect(textOf(editor)).toBe("one\ntwo");+ });++ it("does nothing outside a code block", () => {+ const editor = new Editor({+ extensions,+ content: {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: "hi" }] }],+ },+ });+ expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);+ });+});++describe("selections across two identical fences", () => {+ /** Two structurally equal code blocks; the selection spans from one into the other. */+ function twoBlockEditor() {+ const block = { type: "codeBlock", content: [{ type: "text", text: " a" }] };+ const editor = new Editor({ extensions, content: { type: "doc", content: [block, block] } });+ // First block: 1..4 (text " a" occupies 1..4); second block starts at 5.+ editor.view.dispatch(+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2, 7)),+ );+ return editor;+ }++ it("leaves Tab and Enter alone rather than editing through the boundary", () => {+ const editor = twoBlockEditor();+ const before = editor.getJSON();+ expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);+ expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);+ expect(editor.getJSON()).toEqual(before);+ });+});++describe("convertCodeFenceOnEnter", () => {+ /** Builds an editor holding one paragraph with the caret at its end. */+ function paragraphEditor(text: string) {+ const editor = new Editor({+ extensions,+ content: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] },+ });+ editor.view.dispatch(+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1 + text.length)),+ );+ return editor;+ }++ it.each([+ ["```", "```", ""],+ ["```ts", "```", "ts"],+ ["~~~py", "~~~", "py"],+ ["````", "````", ""],+ ["```ts title=example", "```", "ts title=example"],+ ["``` js", "```", " js"],+ ])("turns %s into a code block", (text, fence, language) => {+ const editor = paragraphEditor(text);+ expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);+ const block = editor.state.doc.firstChild!;+ expect(block.type.name).toBe("codeBlock");+ expect(block.attrs).toMatchObject({ fence, language, close: `\n${fence}` });+ expect(block.textContent).toBe("");+ // The caret belongs inside the new block, ready for the first line.+ expect(editor.state.selection.from).toBe(1);+ });++ it.each(["``", "text ```", "```a`b"])("leaves %s alone", (text) => {+ const editor = paragraphEditor(text);+ expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);+ });++ it("refuses to open a fence inside a list item", () => {+ const text = "```ts";+ const editor = new Editor({+ extensions,+ content: {+ type: "doc",+ content: [+ {+ type: "bulletList",+ content: [+ {+ type: "listItem",+ content: [{ type: "paragraph", content: [{ type: "text", text }] }],+ },+ ],+ },+ ],+ },+ });+ // Inside listItem > paragraph: position 3 is the paragraph start.+ editor.view.dispatch(+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3 + text.length)),+ );+ const before = editor.getJSON();+ expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);+ expect(editor.getJSON()).toEqual(before);+ });++ it("keeps a chip's source in the info string", () => {+ const editor = new Editor({+ extensions,+ content: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ { type: "text", text: "```ts " },+ { type: "composer-mention", attrs: { path: "a.md", source: "@a.md" } },+ ],+ },+ ],+ },+ });+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));+ expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);+ expect(editor.state.doc.firstChild?.attrs.language).toBe("ts @a.md");+ });++ it("ignores a fence with the caret before its end", () => {+ const editor = paragraphEditor("```ts");+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3)));+ expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);+ });+});diff --git a/apps/web/src/composer-code-block.ts b/apps/web/src/composer-code-block.tsnew file mode 100644index 00000000000..f4f28765f76--- /dev/null+++ b/apps/web/src/composer-code-block.ts@@ -0,0 +1,254 @@+import { exitCode } from "@tiptap/pm/commands";+import type { EditorState, Transaction } from "@tiptap/pm/state";+import { TextSelection } from "@tiptap/pm/state";+import type { EditorView } from "@tiptap/pm/view";++import { isClosingFence, parseOpeningFence, serializeSelection } from "~/composer-rich-text-doc";++/**+ * Spaces rather than a tab: the fence round-trips through Markdown on its way+ * to the agent, and a literal tab there renders at whatever width the reader+ * happens to use. Two matches how this repo indents its own source.+ */+export const CODE_BLOCK_INDENT = " ";++/** The leading run of spaces and tabs on a line, which Enter carries forward. */+export function leadingWhitespace(line: string): string {+ return /^[ \t]*/.exec(line)?.[0] ?? "";+}++/**+ * Removes one indent's worth of leading whitespace, tolerating lines that were+ * indented by hand with an odd number of spaces or with tabs. A line with no+ * leading whitespace is returned unchanged, so outdenting bottoms out quietly+ * rather than eating the first character of code.+ */+export function outdentLine(line: string): string {+ if (line.startsWith(CODE_BLOCK_INDENT)) return line.slice(CODE_BLOCK_INDENT.length);+ if (line.startsWith("\t")) return line.slice(1);+ if (line.startsWith(" ")) return line.slice(1);+ return line;+}++/** Applies Tab/Shift+Tab to every line a selection touches, whole lines at a time. */+export function indentLines(lines: ReadonlyArray<string>, direction: "in" | "out"): string[] {+ return lines.map((line) => {+ // Indenting a blank line would leave trailing whitespace behind on a line+ // the user cannot see the caret move on, so leave it be.+ if (direction === "in") return line.length === 0 ? line : `${CODE_BLOCK_INDENT}${line}`;+ return outdentLine(line);+ });+}++/** Whether every endpoint of the selection sits in the same code block. */+export function selectionInOneCodeBlock(state: EditorState): boolean {+ const { $from, $to } = state.selection;+ return $from.parent.type.spec.code === true && $from.sameParent($to);+}++/**+ * The code block containing the selection, or null when the selection is+ * outside a fence or spans out of one. Both ends must sit in the same block: a+ * selection that reaches past the fence belongs to the document, not to the+ * code.+ */+function codeBlockRange(+ state: EditorState,+): { readonly from: number; readonly to: number; readonly text: string } | null {+ const { $from, $to } = state.selection;+ const parent = $from.parent;+ if (parent.type.spec.code !== true) return null;+ // Same occurrence, not merely equal structure: two identical fences would+ // otherwise let a selection across them edit through the block boundary.+ if (!$from.sameParent($to)) return null;+ const from = $from.start();+ return { from, to: from + parent.content.size, text: parent.textContent };+}++/**+ * Enter inside a fence, carrying the current line's indentation onto the new+ * line. ProseMirror's default splits the text but starts the new line at column+ * zero, which means re-typing the indent on every line of a nested block.+ */+export function indentedNewlineInCodeBlock(+ state: EditorState,+ dispatch?: (transaction: Transaction) => void,+): boolean {+ const block = codeBlockRange(state);+ if (!block) return false;++ const { from, to } = state.selection;+ const beforeCursor = block.text.slice(0, from - block.from);+ const currentLine = beforeCursor.slice(beforeCursor.lastIndexOf("\n") + 1);+ const indent = leadingWhitespace(currentLine);++ // Nothing to carry, so let the default newline handle it and keep this path+ // out of the undo history.+ if (indent.length === 0) return false;++ if (dispatch) {+ const inserted = `\n${indent}`;+ const transaction = state.tr.insertText(inserted, from, to);+ const caret = from + inserted.length;+ transaction.setSelection(TextSelection.create(transaction.doc, caret));+ dispatch(transaction.scrollIntoView());+ }+ return true;+}++/**+ * Two blank lines at the end of a fence leave it, the way every code editor+ * does. Without this a fence at the end of the prompt is a trap: Enter only+ * ever adds another line and there is no way back to prose. A line holding+ * only the indentation Enter carried forward counts as blank, and is removed+ * with the rest.+ */+export function exitCodeBlockOnTrailingBlankLines(view: EditorView): boolean {+ const { $from, empty } = view.state.selection;+ if (!empty || $from.parent.type.spec.code !== true) return false;+ if ($from.parentOffset !== $from.parent.content.size) return false;+ const trailing = /\n[ \t]*\n[ \t]*$/.exec($from.parent.textContent);+ if (!trailing) return false;+ const transaction = view.state.tr.delete($from.pos - trailing[0].length, $from.pos);+ // An unclosed fence runs to the end of the draft; the prose after it would+ // be read back as code, so leaving it writes the closing fence.+ if (!$from.parent.attrs.close) {+ transaction.setNodeAttribute($from.before(), "close", `\n${$from.parent.attrs.fence}`);+ }+ view.dispatch(transaction);+ return exitCode(view.state, (tr) => view.dispatch(tr.scrollIntoView()));+}++/**+ * Enter at the end of a line that would close the fence, such as ```` ``` ````+ * typed under the code, ends the block there. That line becomes the closing+ * fence, and any lines after it continue as paragraphs after a new empty one,+ * which is how the stored draft reads them.+ */+export function exitCodeBlockOnClosingFence(+ state: EditorState,+ dispatch?: (transaction: Transaction) => void,+): boolean {+ const block = codeBlockRange(state);+ if (!block || !state.selection.empty) return false;+ const caret = state.selection.from - block.from;+ const lineStart = block.text.lastIndexOf("\n", caret - 1) + 1;+ const newlineAfter = block.text.indexOf("\n", caret);+ const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;+ const line = block.text.slice(lineStart, lineEnd);+ const node = state.selection.$from.parent;+ if (caret !== lineEnd || !isClosingFence(line, String(node.attrs.fence))) return false;++ if (dispatch) {+ const { schema } = state;+ const paragraph = (text: string) =>+ schema.nodes.paragraph!.create(null, text ? schema.text(text) : null);+ const code = block.text.slice(0, Math.max(0, lineStart - 1));+ const rest = newlineAfter === -1 ? [] : block.text.slice(newlineAfter + 1).split("\n");+ const closed = node.type.create(+ { ...node.attrs, close: `\n${line}` },+ code ? schema.text(code) : null,+ );+ const start = state.selection.$from.before();+ const transaction = state.tr.replaceWith(start, start + node.nodeSize, [+ closed,+ paragraph(""),+ ...rest.map(paragraph),+ ]);+ transaction.setSelection(TextSelection.create(transaction.doc, start + closed.nodeSize + 1));+ dispatch(transaction.scrollIntoView());+ }+ return true;+}++/**+ * Tab and Shift+Tab inside a fence. A collapsed cursor indents at the caret so+ * Tab works mid-line the way typing does; any selection spanning text indents+ * the whole lines it touches, which is what makes re-indenting a block possible.+ */+export function indentCodeBlock(+ state: EditorState,+ direction: "in" | "out",+ dispatch?: (transaction: Transaction) => void,+): boolean {+ const block = codeBlockRange(state);+ if (!block) return false;++ const { from, to } = state.selection;+ const startOffset = from - block.from;+ const endOffset = to - block.from;++ if (from === to && direction === "in") {+ if (dispatch) {+ const transaction = state.tr.insertText(CODE_BLOCK_INDENT, from, to);+ dispatch(transaction.scrollIntoView());+ }+ return true;+ }++ // Grow the range to whole lines so indenting is stable no matter where in the+ // first and last lines the selection happens to start and end.+ const lineStart = block.text.lastIndexOf("\n", Math.max(0, startOffset - 1)) + 1;+ // A selection ending at the start of a line does not touch that line.+ const newlineAfter = block.text.indexOf("\n", Math.max(startOffset, endOffset - 1));+ const lineEnd = newlineAfter === -1 ? block.text.length : newlineAfter;++ const originalLines = block.text.slice(lineStart, lineEnd).split("\n");+ const nextLines = indentLines(originalLines, direction);+ if (nextLines.join("\n") === originalLines.join("\n")) return true;++ if (dispatch) {+ const transaction = state.tr.insertText(+ nextLines.join("\n"),+ block.from + lineStart,+ block.from + lineEnd,+ );+ // Keep the same lines selected after the shift, so repeated Tab presses+ // keep indenting the block rather than collapsing the selection.+ // `split` always yields at least one entry, so these stand in only for the+ // compiler's benefit.+ const firstDelta = (nextLines[0]?.length ?? 0) - (originalLines[0]?.length ?? 0);+ const totalDelta = nextLines.join("\n").length - originalLines.join("\n").length;+ const nextFrom = Math.max(block.from + lineStart, from + firstDelta);+ const nextTo = Math.max(nextFrom, to + totalDelta);+ transaction.setSelection(TextSelection.create(transaction.doc, nextFrom, nextTo));+ dispatch(transaction.scrollIntoView());+ }+ return true;+}++/**+ * Enter on a line that is nothing but an opening fence turns it into a code+ * block. Tiptap's own input rules only fire on a space, so without this the+ * gesture every markdown editor has — ```` ```ts ```` then Enter — leaves the+ * fence as literal text.+ */+export function convertCodeFenceOnEnter(+ state: EditorState,+ dispatch?: (transaction: Transaction) => void,+): boolean {+ const { $from, empty } = state.selection;+ // Top-level paragraphs only: the list and quote serializers have no line+ // to write a fence into, so one created inside them would vanish.+ if (!empty || $from.parent.type.name !== "paragraph" || $from.depth !== 1) return false;+ if ($from.parentOffset !== $from.parent.content.size) return false;+ // The parser's own grammar, read from the line's stored source, so a line+ // Enter turns into a fence is exactly one the stored draft reads back as a+ // fence, info string and all, including any chip's source in it.+ const opening = parseOpeningFence(serializeSelection(state.doc, $from.start(), $from.end()));+ const codeBlock = state.schema.nodes.codeBlock;+ if (!opening || !codeBlock) return false;++ if (dispatch) {+ const blockStart = $from.before();+ const { fence, language } = opening;+ const transaction = state.tr.replaceWith(+ blockStart,+ blockStart + $from.parent.nodeSize,+ codeBlock.create({ language, fence, close: `\n${fence}` }),+ );+ transaction.setSelection(TextSelection.create(transaction.doc, blockStart + 1));+ dispatch(transaction.scrollIntoView());+ }+ return true;+}diff --git a/apps/web/src/composer-code-languages.test.ts b/apps/web/src/composer-code-languages.test.tsnew file mode 100644index 00000000000..cc29b29dfd3--- /dev/null+++ b/apps/web/src/composer-code-languages.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vite-plus/test";++import {+ CODE_BLOCK_LANGUAGES,+ codeLanguageLabel,+ languageOfInfoString,+ withInfoStringLanguage,+} from "./composer-code-languages";++describe("languageOfInfoString", () => {+ it.each([+ ["", ""],+ ["ts", "ts"],+ [" ts ", "ts"],+ ["js title=example", "js"],+ ["typescript ", "typescript"],+ ])("reads %j as %j", (info, language) => {+ expect(languageOfInfoString(info)).toBe(language);+ });+});++describe("withInfoStringLanguage", () => {+ it.each([+ ["", "ts", "ts"],+ ["js", "python", "python"],+ // Anything after the language belongs to the fence and stays put.+ ["js title=example", "ts", "ts title=example"],+ ["js {1,3}", "ts", "ts {1,3}"],+ // Plain text clears the language...+ ["js", "", ""],+ // ...but a bare `title=x` would read as the language, so it keeps `text`.+ ["js title=example", "", "text title=example"],+ // Whitespace between the fence and the language is the user's formatting.+ [" js title=x", "python", " python title=x"],+ [" js title=x", "", " text title=x"],+ [" js", "go", " go"],+ [" ", "go", " go"],+ ])("sets %j to %j as %j", (info, language, expected) => {+ expect(withInfoStringLanguage(info, language)).toBe(expected);+ });+});++describe("codeLanguageLabel", () => {+ it.each([+ ["", "Plain text"],+ ["text", "Plain text"],+ ["cpp", "C++"],+ ["ts", "TypeScript"],+ ["arduino", "arduino"],+ ])("labels %j as %j", (language, label) => {+ expect(codeLanguageLabel(language)).toBe(label);+ });++ it("lists every language once, plain text first", () => {+ const ids = CODE_BLOCK_LANGUAGES.map((language) => language.id);+ expect(ids[0]).toBe("");+ expect(new Set(ids).size).toBe(ids.length);+ });+});diff --git a/apps/web/src/composer-code-languages.ts b/apps/web/src/composer-code-languages.tsnew file mode 100644index 00000000000..1c6a68aab75--- /dev/null+++ b/apps/web/src/composer-code-languages.ts@@ -0,0 +1,97 @@+/**+ * The languages a composer fence can be switched to from its header, and how+ * a choice is written back into the fence's info string.+ *+ * Ids are the names the highlighter and the file icons both know. The list+ * is curated rather than every grammar the highlighter bundles: a picker is+ * for the common case, and any other language can still be typed on the+ * fence line, where it shows as its own entry.+ */+export const CODE_BLOCK_LANGUAGES = [+ { id: "", label: "Plain text" },+ { id: "bash", label: "Bash" },+ { id: "c", label: "C" },+ { id: "cpp", label: "C++" },+ { id: "csharp", label: "C#" },+ { id: "css", label: "CSS" },+ { id: "dart", label: "Dart" },+ { id: "diff", label: "Diff" },+ { id: "dockerfile", label: "Dockerfile" },+ { id: "elixir", label: "Elixir" },+ { id: "go", label: "Go" },+ { id: "graphql", label: "GraphQL" },+ { id: "haskell", label: "Haskell" },+ { id: "html", label: "HTML" },+ { id: "java", label: "Java" },+ { id: "javascript", label: "JavaScript" },+ { id: "json", label: "JSON" },+ { id: "jsx", label: "JSX" },+ { id: "kotlin", label: "Kotlin" },+ { id: "lua", label: "Lua" },+ { id: "markdown", label: "Markdown" },+ { id: "php", label: "PHP" },+ { id: "powershell", label: "PowerShell" },+ { id: "python", label: "Python" },+ { id: "r", label: "R" },+ { id: "ruby", label: "Ruby" },+ { id: "rust", label: "Rust" },+ { id: "scala", label: "Scala" },+ { id: "scss", label: "SCSS" },+ { id: "sql", label: "SQL" },+ { id: "svelte", label: "Svelte" },+ { id: "swift", label: "Swift" },+ { id: "toml", label: "TOML" },+ { id: "tsx", label: "TSX" },+ { id: "typescript", label: "TypeScript" },+ { id: "vue", label: "Vue" },+ { id: "xml", label: "XML" },+ { id: "yaml", label: "YAML" },+ { id: "zig", label: "Zig" },+] as const;++export type CodeBlockLanguage = { readonly id: string; readonly label: string };++/** Short names people type on the fence line, labelled like the entry they mean. */+const LANGUAGE_ALIASES: Record<string, string> = {+ cs: "csharp",+ "c++": "cpp",+ js: "javascript",+ md: "markdown",+ py: "python",+ rb: "ruby",+ rs: "rust",+ sh: "bash",+ shell: "bash",+ ts: "typescript",+ yml: "yaml",+};++/** The language is the info string's first word; the rest belongs to the fence. */+export function languageOfInfoString(info: string): string {+ return info.trim().split(/\s+/, 1)[0] ?? "";+}++/**+ * Replaces the language and keeps everything around it: the whitespace the+ * fence had before it and whatever follows it. Plain text clears it, unless+ * something follows: a bare `title=x` would read as the language, so that+ * keeps `text` in front.+ */+export function withInfoStringLanguage(info: string, language: string): string {+ const leading = /^\s*/.exec(info)![0];+ // The language is the first word, so what follows it is empty or starts+ // with whitespace.+ const rest = info.slice(leading.length + languageOfInfoString(info).length);+ if (language) return `${leading}${language}${rest}`;+ return rest.trim() ? `${leading}text${rest}` : "";+}++/** The canonical entry a language names, if the picker lists it. */+export function codeLanguageEntry(language: string): CodeBlockLanguage | null {+ const id = language === "text" ? "" : (LANGUAGE_ALIASES[language.toLowerCase()] ?? language);+ return CODE_BLOCK_LANGUAGES.find((entry) => entry.id === id.toLowerCase()) ?? null;+}++export function codeLanguageLabel(language: string): string {+ return codeLanguageEntry(language)?.label ?? language;+}diff --git a/apps/web/src/composer-list-continuation.test.ts b/apps/web/src/composer-list-continuation.test.tsindex b92514dd271..a878ed95a12 100644--- a/apps/web/src/composer-list-continuation.test.ts+++ b/apps/web/src/composer-list-continuation.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vite-plus/test";-import { listContinuationForEnter, listIndentForTab } from "./composer-list-continuation";+import {+ listContinuationForEnter,+ listIndentForTab,+ nextOrderedMarkerText,+} from "./composer-list-continuation";function applyEdit(value: string, edit: { start: number; end: number; replacement: string }) {return value.slice(0, edit.start) + edit.replacement + value.slice(edit.end);@@ -66,3 +70,16 @@ describe("composer list continuation", () => {expect(listIndentForTab("- foo", 1, 3)).toBeNull();});});++describe("nextOrderedMarkerText", () => {+ it.each([+ ["1.", "2."],+ ["1)", "2)"],+ ["09.", "10."],+ ["001)", "002)"],+ ["99.", "100."],+ ["99999999999999999999.", "99999999999999999999."],+ ])("counts %s up to %s", (marker, expected) => {+ expect(nextOrderedMarkerText(marker)).toBe(expected);+ });+});diff --git a/apps/web/src/composer-list-continuation.ts b/apps/web/src/composer-list-continuation.tsindex 952dfa54947..be617da2a26 100644--- a/apps/web/src/composer-list-continuation.ts+++ b/apps/web/src/composer-list-continuation.ts@@ -55,13 +55,24 @@ function parseListMarker(line: string): { marker: ListMarker; markerEnd: numberreturn null;}+/**+ * The ordered marker that follows `3.` or `09)`: one higher, same delimiter,+ * zero padding kept, and a number too large to count left as typed. Shared+ * with the rich editor's native split so both modes count the same way.+ */+export function nextOrderedMarkerText(marker: string): string {+ const numberText = marker.slice(0, -1);+ const delimiter = marker.slice(-1);+ const number = Number.parseInt(numberText, 10);+ const next = Number.isSafeInteger(number)+ ? String(number + 1).padStart(numberText.length, "0")+ : numberText;+ return `${next}${delimiter}`;+}+function nextMarkerText(marker: ListMarker): string {if (marker.kind === "ordered") {- const number = Number.parseInt(marker.numberText, 10);- const next = Number.isSafeInteger(number)- ? String(number + 1).padStart(marker.numberText.length, "0")- : marker.numberText;- return `${marker.indent}${next}${marker.delimiter} `;+ return `${marker.indent}${nextOrderedMarkerText(`${marker.numberText}${marker.delimiter}`)} `;}if (marker.kind === "task") {return `${marker.indent}- [ ] `;diff --git a/apps/web/src/composer-list-split.test.ts b/apps/web/src/composer-list-split.test.tsnew file mode 100644index 00000000000..0e5c4d6a395--- /dev/null+++ b/apps/web/src/composer-list-split.test.ts@@ -0,0 +1,265 @@+// @vitest-environment jsdom++import { Editor } from "@tiptap/core";+import { TaskList } from "@tiptap/extension-task-list";+import { TextSelection } from "@tiptap/pm/state";+import StarterKit from "@tiptap/starter-kit";+import { afterEach, describe, expect, it } from "vite-plus/test";++import {+ backspaceAcrossList,+ buildDocJson,+ buildTiptapContent,+ ComposerBlockExtensions,+ ComposerCodeBlockExtension,+ ComposerListExtensions,+ ComposerTaskItemExtension,+ convertBulletItemToTask,+ deleteAcrossList,+ serializeEditorDoc,+ splitOrLiftListItem,+} from "./composer-rich-text-doc";++// ProseMirror's DOM observer can flush on a timer after a test ends, which+// throws once jsdom is torn down, so every editor is destroyed after its test.+const editors: Editor[] = [];+afterEach(() => {+ for (const editor of editors.splice(0)) editor.destroy();+});++/**+ * Splits the last item of `value` the way Shift+Enter does, types `b`, and+ * returns the stored Markdown. Tiptap carries every attribute left at the+ * default `keepOnSplit: true` onto the new item and merges the overrides on+ * top, so the new item must keep the source marker, indent and spacing.+ */+function makeEditor(value: string) {+ const editor = new Editor({+ extensions: [+ StarterKit.configure({+ bulletList: false,+ orderedList: false,+ listItem: false,+ codeBlock: false,+ blockquote: false,+ heading: false,+ horizontalRule: false,+ trailingNode: false,+ listKeymap: false,+ }),+ ...ComposerListExtensions,+ TaskList,+ ComposerTaskItemExtension,+ ComposerCodeBlockExtension,+ ...ComposerBlockExtensions,+ ],+ content: buildDocJson(value, (name) => ({ label: name, description: null })),+ });+ editors.push(editor);+ return editor;+}++function splitLastItem(value: string, type: "listItem" | "taskItem", overrides: object) {+ const editor = makeEditor(value);+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));+ editor.commands.splitListItem(type, overrides);+ editor.view.dispatch(editor.state.tr.insertText("b"));+ return serializeEditorDoc(editor.state.doc).value;+}++describe("splitting a list item", () => {+ it.each([+ ["* a", { space: " " }, "* a\n* b"],+ ["+ a", { space: " " }, "+ a\n+ b"],+ ["- p\n - a", { space: " " }, "- p\n - a\n - b"],+ ["3) a", { marker: "4)", space: " " }, "3) a\n4) b"],+ ])("keeps the source marker and indent of %s", (value, overrides, expected) => {+ expect(splitLastItem(value, "listItem", overrides)).toBe(expected);+ });++ it("keeps the indent of a nested task", () => {+ expect(splitLastItem("- [ ] p\n - [ ] a", "taskItem", { checked: false })).toBe(+ "- [ ] p\n - [ ] a\n - [ ] b",+ );+ });+});++/** Puts the caret `offset` characters into the first text node holding `text`. */+function placeCaret(editor: Editor, text: string, offset = 0) {+ let caret = -1;+ editor.state.doc.descendants((node, pos) => {+ if (caret < 0 && node.isText && node.text!.includes(text)) {+ caret = pos + node.text!.indexOf(text) + offset;+ }+ });+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, caret)));+}++/** The stored draft, after checking a rebuild from it gives back the same document. */+function storedDraft(editor: Editor) {+ const stored = serializeEditorDoc(editor.state.doc).value;+ expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());+ return stored;+}++describe("Shift+Enter twice on an item", () => {+ // The second Shift+Enter lifts the new empty item one level. The stored+ // draft must write it at its new depth, so a rebuild from that draft gives+ // back the document the user is looking at.+ it.each([+ ["- a\n - x", "- a\n - x\n- b"],+ ["* a\n * x", "* a\n * x\n* b"],+ ["1. a\n 1. x", "1. a\n 1. x\n2. b"],+ ["- a\n - x\n- c", "- a\n - x\n- b\n- c"],+ ["- a\n - x\n - y", "- a\n - x\n- b\n - y"],+ ["- [ ] a\n - [ ] x", "- [ ] a\n - [ ] x\n- [ ] b"],+ ["- [x] a\n - [ ] x\n- [ ] c", "- [x] a\n - [ ] x\n- [ ] b\n- [ ] c"],+ ])("after x in %j writes %j", (value, expected) => {+ const editor = makeEditor(value);+ let caret = -1;+ editor.state.doc.descendants((node, pos) => {+ if (node.isText && node.text === "x") caret = pos + 1;+ });+ editor.view.dispatch(+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, caret)),+ );+ expect(splitOrLiftListItem(editor)).toBe(true);+ expect(splitOrLiftListItem(editor)).toBe(true);+ editor.view.dispatch(editor.state.tr.insertText("b"));+ const stored = serializeEditorDoc(editor.state.doc).value;+ expect(stored).toBe(expected);+ // Same nesting after a rebuild; spacing defaults may differ but write the same.+ expect(makeEditor(stored).state.doc.toString()).toBe(editor.state.doc.toString());+ });+});++describe("Shift+Enter in the middle of an ordered list", () => {+ it.each([+ ["1. a\n2. x\n3. c\n4. d", "1. a\n2. x\n3. b\n4. c\n5. d"],+ ["1) a\n2) x\n3) c", "1) a\n2) x\n3) b\n4) c"],+ ["1. a\n 1. x\n 2. c\n2. d", "1. a\n 1. x\n 2. b\n 3. c\n2. d"],+ ])("after x in %j writes %j", (value, expected) => {+ const editor = makeEditor(value);+ placeCaret(editor, "x", 1);+ expect(splitOrLiftListItem(editor)).toBe(true);+ editor.view.dispatch(editor.state.tr.insertText("b"));+ expect(storedDraft(editor)).toBe(expected);+ });+});++describe("Shift+Enter on an empty task under a bullet", () => {+ // There is no task list one level up to move it into, and the item cannot+ // hold a second line, so the draft stays what the editor shows.+ it.each(["- a\n - [ ] x", "- [ ] a\n - x"])("in %j keeps the draft honest", (value) => {+ const editor = makeEditor(value);+ placeCaret(editor, "x", 1);+ splitOrLiftListItem(editor);+ splitOrLiftListItem(editor);+ storedDraft(editor);+ });+});++describe("Backspace at the start of a line", () => {+ it.each([+ ["- a\n - x", "x", "- a\n- x"],+ ["- a\n - x\n - y", "x", "- a\n- x\n - y"],+ ["- [ ] a\n - [ ] x", "x", "- [ ] a\n- [ ] x"],+ ["- a\n- b\n- c", "b", "- a\nb\n- c"],+ // A task under a bullet has no task list to move into, so it joins up.+ ["- a\n - [ ] x", "x", "- ax"],+ ["- a\n - x\nb", "b", "- a\n - xb"],+ ["1. a\nb", "b", "1. ab"],+ ])("in %j at %s writes %j", (value, at, expected) => {+ const editor = makeEditor(value);+ placeCaret(editor, at);+ expect(backspaceAcrossList(editor)).toBe(true);+ expect(storedDraft(editor)).toBe(expected);+ });++ it.each([+ ["- a\n```\nl1\nl2\n```", "- a\nl1\nl2"],+ ["p\n```ts\nl1\n```", "p\nl1"],+ ])("removes the fence of %j rather than joining its code up", (value, expected) => {+ const editor = makeEditor(value);+ placeCaret(editor, "l1");+ editor.commands.keyboardShortcut("Backspace");+ expect(storedDraft(editor)).toBe(expected);+ });+});++describe("Delete at the end of a line", () => {+ it.each([+ ["- a\n- b", "- ab"],+ ["- a\n - x\n- c", "- ax\n- c"],+ ["- a\n\nb", "- a\nb"],+ ])("in %j writes %j", (value, expected) => {+ const editor = makeEditor(value);+ placeCaret(editor, "a", 1);+ expect(deleteAcrossList(editor)).toBe(true);+ expect(storedDraft(editor)).toBe(expected);+ });++ it.each(["- a\n```\nl1\n```", "a\n```\nl1\n```"])("leaves the fence in %j alone", (value) => {+ const editor = makeEditor(value);+ placeCaret(editor, "a", 1);+ editor.commands.keyboardShortcut("Delete");+ expect(storedDraft(editor)).toBe(value);+ });+});++describe("blocks that a list item or quote cannot hold", () => {+ it("puts lines pasted at the end of an item after the list", () => {+ const editor = makeEditor("- a");+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));+ const lines = buildTiptapContent("one\ntwo", (name) => ({ label: name, description: null }));+ editor.commands.insertContent(lines);+ expect(storedDraft(editor)).toBe("- a\none\ntwo");+ });++ it("will not make a task list inside a quote", () => {+ const editor = makeEditor("> q");+ placeCaret(editor, "q");+ expect(editor.commands.wrapInList("taskList")).toBe(false);+ expect(storedDraft(editor)).toBe("> q");+ });+});++describe("[ ] typed at the start of a bullet item", () => {+ // The value holds `[ ]` already; the rule fires on the space after it.+ it.each([+ ["* [ ]x", "- [ ] x"],+ ["* a\n* [ ]x\n* c", "* a\n- [ ] x\n* c"],+ ["- a\n * [ ]x", "- a\n - [ ] x"],+ ["- a\n - [ ]x\n - y", "- a\n - [ ] x\n - y"],+ ["- [ ]x\n - y", "- [ ] x\n - y"],+ ["- [ ]x", "- [ ] x"],+ ])("makes the item in %j a task where it stands", (value, expected) => {+ const editor = makeEditor(value);+ placeCaret(editor, "[ ]x");+ const from = editor.state.selection.from;+ editor.view.dispatch(+ editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from + 3)),+ );+ const { tr } = editor.state;+ convertBulletItemToTask(tr, from, from + 3, false);+ editor.view.dispatch(tr);+ expect(editor.state.selection.$from.parent.textContent).toBe("x");+ expect(editor.state.selection.$from.parentOffset).toBe(0);+ expect(storedDraft(editor)).toBe(expected);+ });+});++describe("a rule at the end of the draft", () => {+ it("keeps an empty line after it to type on", () => {+ const editor = makeEditor("a\n---");+ // Removing the line after the rule puts one straight back.+ editor.view.dispatch(+ editor.state.tr.delete(editor.state.doc.content.size - 2, editor.state.doc.content.size),+ );+ expect(editor.state.doc.lastChild?.type.name).toBe("paragraph");+ expect(storedDraft(editor)).toBe("a\n---");+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));+ editor.view.dispatch(editor.state.tr.insertText("b"));+ expect(storedDraft(editor)).toBe("a\n---\nb");+ });+});diff --git a/apps/web/src/composer-rich-text-doc.test.ts b/apps/web/src/composer-rich-text-doc.test.tsindex 44f8e6d1f6d..5b26b74cacf 100644--- a/apps/web/src/composer-rich-text-doc.test.ts+++ b/apps/web/src/composer-rich-text-doc.test.ts@@ -5,9 +5,15 @@ import { Node as ProseMirrorNode } from "@tiptap/pm/model";import { EditorState, TextSelection } from "@tiptap/pm/state";import { describe, expect, it } from "vite-plus/test";+import { collapseExpandedComposerCursor } from "./composer-logic";+import {buildDocJson,+ buildTiptapContent,caretTakesMarksBefore,+ ComposerBlockExtensions,+ ComposerCodeBlockExtension,+ ComposerListExtensions,collapsedToFlat,ComposerCodeExtension,ComposerTaskItemExtension,@@ -16,6 +22,7 @@ import {flatToPm,pmToFlat,serializeEditorDoc,+ serializeSelection,stepCaretAcrossStyledEdge,} from "./composer-rich-text-doc";@@ -64,6 +71,9 @@ const schema = getSchemaByResolvedExtensions(}),TaskList,ComposerTaskItemExtension,+ ComposerCodeBlockExtension,+ ...ComposerListExtensions,+ ...ComposerBlockExtensions,]),);@@ -344,6 +354,437 @@ describe("composer rich text document model", () => {expect(roundTripPlain(value).value).toBe(value);});+ it.each([+ "- one\n- two",+ "* star\n* star two",+ "+ plus",+ "* star\n+ plus",+ "1. first\n2. second",+ "1) paren\n2) paren",+ "3. starts at three\n4. four",+ "01. zero padded\n02. two",+ "- parent\n - child\n - sibling\n- uncle",+ "1. ordered\n - bullet child\n2. next",+ "- outer\n 1. inner ordered\n 2. more\n- outer again",+ "- wide space item",+ "-",+ "1.",+ "- \n- second",+ "- **bold** item with @README.md",+ "- [ ] task\n- bullet after",+ "- bullet\n- [x] task after",+ "para\n- item\npara",+ "\t- tab indented\n\t- again",+ " - leading indent only",+ "- item\n\n- after a blank",+ "- item one\n```ts\ncode\n```\n- item two",+ "-no space stays literal",+ "1.no space stays literal",+ "10. ten\n11. eleven",+ ])("round-trips the list %s through a real ProseMirror document", (value) => {+ expect(roundTrip(value).value).toBe(value);+ });++ it.each([+ "- one\n- two",+ "1. first\n2. second",+ "- parent\n - child",+ "* star\n+ plus",+ "-no space stays literal",+ ])("keeps the list %s literal in plain mode", (value) => {+ expect(roundTripPlain(value).value).toBe(value);+ });++ it.each(["- one\n- two", "1. a\n - b\n2. c", "- **bold** @README.md tail", "-"])(+ "maps every document offset of the list %s through collapsed coordinates and back",+ (value) => {+ const map = roundTrip(value);+ expect(map.value).toBe(value);+ for (let flat = 0; flat <= map.docLength; flat += 1) {+ expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);+ }+ },+ );++ it("clamps offsets inside a list marker to the start of the item text", () => {+ const value = "- item";+ const map = roundTrip(value);+ // The marker owns no document characters, like a checkbox.+ for (let collapsed = 0; collapsed <= "- ".length; collapsed += 1) {+ expect(collapsedToFlat(map, collapsed)).toBe(0);+ }+ expect(collapsedToFlat(map, "- it".length)).toBe(2);+ expect(flatToCollapsed(map, 0)).toBe("- ".length);+ });++ it.each([+ "> quoted",+ "> line one\n> line two",+ ">no space",+ "> two spaces",+ "> a\n>b",+ ">",+ "> **bold** and @README.md inside",+ "> - looks like a list but stays quote text",+ "> > nested stays literal inside the quote",+ "before\n> quoted\nafter",+ "> quote\n\n> another",+ "- item\n> quote after list",+ ])("round-trips the quote %s through a real ProseMirror document", (value) => {+ expect(roundTrip(value).value).toBe(value);+ });++ it.each([+ "---",+ "***",+ "___",+ "- - -",+ "* * *",+ "-----",+ "--- ",+ "text\n---\nmore",+ "- item\n---\n- item two",+ "```\n---\n```",+ "--",+ "-- -",+ "---text",+ ])("round-trips the rule %s through a real ProseMirror document", (value) => {+ expect(roundTrip(value).value).toBe(value);+ });++ it("parses rules ahead of lists and emphasis", () => {+ const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({+ label: n,+ description: null,+ }));+ expect(json.content.map((block) => block.type)).toEqual([+ "horizontalRule",+ "horizontalRule",+ "horizontalRule",+ "paragraph",+ "horizontalRule",+ "bulletList",+ ]);+ });++ it.each([+ "# Heading",+ "## Two",+ "###### Six",+ "####### seven hashes stays a paragraph",+ "# two spaces",+ "#\tTab",+ "# Trailing hashes stay literal #",+ "#1234",+ "#1234 is a pull request, not a heading",+ "# Heading with **bold** and @README.md",+ "#",+ "# ",+ "text\n# Heading\ntext",+ "# Heading\n- item\n> quote\n---",+ ])("round-trips the heading %s through a real ProseMirror document", (value) => {+ expect(roundTrip(value).value).toBe(value);+ });++ it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(+ "keeps the block %s literal in plain mode",+ (value) => {+ expect(roundTripPlain(value).value).toBe(value);+ },+ );++ it("parses the blocks it renders as the right node types", () => {+ const json = buildDocJson("# Title\n> quote\n---\n#1234 ref\n- - -", (n) => ({+ label: n,+ description: null,+ }));+ expect(json.content.map((block) => block.type)).toEqual([+ "heading",+ "blockquote",+ "horizontalRule",+ "paragraph",+ "horizontalRule",+ // The empty line a final rule keeps for the caret.+ "paragraph",+ ]);+ });++ it.each([+ ["---", "---"],+ ["a\n---", "a\n---"],+ // That line and a trailing newline are the same document; the newline goes.+ ["---\n", "---"],+ ])("gives the caret a line after the final rule of %j, written %j", (value, expected) => {+ const map = roundTrip(value);+ expect(map.value).toBe(expected);+ const json = buildDocJson(value, () => ({ label: "", description: null }));+ const doc = ProseMirrorNode.fromJSON(schema, json);+ expect(doc.resolve(flatToPm(map, map.docLength)).parent.isTextblock).toBe(true);+ });++ it("parses rules ahead of lists and emphasis", () => {+ const json = buildDocJson("- - -\n***\n___\ntext\n---\n- item", (n) => ({+ label: n,+ description: null,+ }));+ expect(json.content.map((block) => block.type)).toEqual([+ "horizontalRule",+ "horizontalRule",+ "horizontalRule",+ "paragraph",+ "horizontalRule",+ "bulletList",+ ]);+ });++ it.each([+ "# Heading",+ "## Two",+ "###### Six",+ "####### seven hashes stays a paragraph",+ "# two spaces",+ "#\tTab",+ "# Trailing hashes stay literal #",+ "#1234",+ "#1234 is a pull request, not a heading",+ "# Heading with **bold** and @README.md",+ "#",+ "# ",+ "text\n# Heading\ntext",+ "# Heading\n- item\n> quote\n---",+ ])("round-trips the heading %s through a real ProseMirror document", (value) => {+ expect(roundTrip(value).value).toBe(value);+ });++ it.each(["> quoted", "> a\n>b", "---", "- - -", "# Heading", "#1234"])(+ "keeps the block %s literal in plain mode",+ (value) => {+ expect(roundTripPlain(value).value).toBe(value);+ },+ );++ it("parses a quote as a blockquote of one paragraph per line", () => {+ const json = buildDocJson("> a\n> b\n>c", (n) => ({ label: n, description: null }));+ expect(json.content.map((block) => block.type)).toEqual(["blockquote", "blockquote"]);+ expect((json.content[0] as { content: unknown[] }).content).toHaveLength(2);+ });++ it.each([+ "> a\n> b",+ "> **q** @README.md",+ "text\n---\nmore",+ "---\ntext",+ "# Heading text",+ "## **b** @README.md",+ ])(+ "maps every document offset of the block %s through collapsed coordinates and back",+ (value) => {+ const map = roundTrip(value);+ expect(map.value).toBe(value);+ for (let flat = 0; flat <= map.docLength; flat += 1) {+ expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);+ }+ },+ );++ it("clamps offsets inside a quote or heading marker to the start of the text", () => {+ for (const [value, prefix] of [+ ["> quoted", "> "],+ ["# Heading", "# "],+ ] as const) {+ const map = roundTrip(value);+ for (let collapsed = 0; collapsed <= prefix.length; collapsed += 1) {+ expect(collapsedToFlat(map, collapsed)).toBe(0);+ }+ expect(flatToCollapsed(map, 0)).toBe(prefix.length);+ }+ });++ it.each([+ "```\ncode\n```",+ "```ts\nconst a = 1;\n```",+ "```ts\nconst a = 1;\n```\n",+ "before\n```ts\nconst a = 1;\n```\nafter",+ "```\n```",+ "```ts\nline one\nline two\nline three\n```",+ "```ts\n indented\n deeper\n```",+ "```js title=example\ncode\n```",+ "~~~py\ncode\n~~~",+ "````\n```\n````",+ "```ts\ncode without a closing fence",+ "```",+ "```ts\n**not bold** and @README.md stay literal\n```",+ "```ts\ncode\n````",+ "- [ ] task\n```ts\ncode\n```\n- [ ] after",+ " ```ts\nindented fence stays a paragraph\n ```",+ ])("round-trips the fenced block %s", (value) => {+ expect(roundTrip(value).value).toBe(value);+ });++ it.each(["```ts\nconst a = 1;\n```", "```\n```", "before\n```ts\ncode\n```\nafter"])(+ "maps every document offset of %s through collapsed coordinates and back",+ (value) => {+ const map = roundTrip(value);+ expect(map.value).toBe(value);+ for (let flat = 0; flat <= map.docLength; flat += 1) {+ expect(collapsedToFlat(map, flatToCollapsed(map, flat))).toBe(flat);+ }+ },+ );++ it("reads blocks written with CRLF line endings", () => {+ const value = "# Title\r\n> quote\r\n---\r\n```ts\r\nconst a = 1;\r\n```\r\nafter";+ const doc = buildDocJson(value, () => ({ label: "", description: null }));+ expect(doc.content.map((block) => block.type)).toEqual([+ "heading",+ "blockquote",+ "horizontalRule",+ "codeBlock",+ "paragraph",+ ]);+ expect(roundTrip(value).value).toBe(value);+ });++ it("keeps the end of the code inside the fence rather than after it", () => {+ const value = "```ts\nfunc();\n```";+ const map = roundTrip(value);+ const endOfCode = "func();".length;+ // Not the end of the string: the closing fence is a line of its own.+ expect(flatToCollapsed(map, endOfCode)).toBe("```ts\nfunc();".length);+ expect(flatToMarkdown(map, endOfCode)).toBe("```ts\nfunc();".length);+ expect(collapsedToFlat(map, flatToCollapsed(map, endOfCode))).toBe(endOfCode);+ });++ it("keeps the caret inside an empty fence", () => {+ const value = "before\n```\n```";+ const map = roundTrip(value);+ const inside = "before\n".length;+ expect(flatToCollapsed(map, inside)).toBe("before\n```".length);+ expect(collapsedToFlat(map, flatToCollapsed(map, inside))).toBe(inside);+ });++ it("still places the end of an inline mark after its markers", () => {+ // The fence rule must not leak into inline marks, whose trailing edge is+ // deliberately the position after the closing delimiter.+ const map = roundTrip("a **bold** c");+ expect(flatToMarkdown(map, 6)).toBe(10);+ });++ it("clamps offsets inside a fence to the edge of the code", () => {+ const value = "```ts\nab\n```";+ const map = roundTrip(value);+ expect(map.value).toBe(value);+ // The opening fence owns no document characters, so every offset in it+ // lands on the first character of the code.+ for (let collapsed = 0; collapsed <= "```ts\n".length; collapsed += 1) {+ expect(collapsedToFlat(map, collapsed)).toBe(0);+ }+ expect(collapsedToFlat(map, "```ts\na".length)).toBe(1);+ // Everything from the closing newline onwards clamps to the code's end.+ for (let collapsed = "```ts\nab".length; collapsed <= value.length; collapsed += 1) {+ expect(collapsedToFlat(map, collapsed)).toBe(2);+ }+ });++ it.each([+ ["```\n\n```", "```\n```"],+ ["```\n", "```"],+ ])("canonicalizes the empty fence %s", (value, expected) => {+ expect(roundTrip(value).value).toBe(expected);+ });++ it("keeps a chip in a fence info string as source and keeps later chips aligned", () => {+ const value = "```@README.md\ncode\n```\n$my-skill after";+ expect(roundTrip(value).value).toBe(value);+ const json = buildDocJson(value, (n) => ({ label: n, description: null }));+ const after = json.content[1] as {+ content: { type: string; attrs?: { skillName?: string } }[];+ };+ expect(after.content.map((n) => n.type)).toEqual(["composer-skill", "text"]);+ expect(after.content[0]?.attrs?.skillName).toBe("my-skill");+ });++ it("keeps chips in a fence's info string and body each in their own place", () => {+ const value = "``` @a.md\nsee @b.md\n```";+ expect(roundTrip(value).value).toBe(value);+ const json = buildDocJson(value, (n) => ({ label: n, description: null }));+ const code = json.content[0] as { attrs: { language: string } };+ expect(code.attrs.language).toBe(" @a.md");+ });++ it.each([+ ["listItem", { marker: "-", space: "" }, "bulletList", "- text"],+ ["listItem", { marker: "1.", space: "" }, "orderedList", "1. text"],+ ])("gives a bare %s a space once it has text", (item, attrs, list, expected) => {+ const doc = ProseMirrorNode.fromJSON(schema, {+ type: "doc",+ content: [+ {+ type: list,+ content: [+ {+ type: item,+ attrs,+ content: [{ type: "paragraph", content: [{ type: "text", text: "text" }] }],+ },+ ],+ },+ ],+ });+ expect(serializeEditorDoc(doc).value).toBe(expected);+ expect(roundTrip("-").value).toBe("-");+ });++ it("writes code holding a closing fence inside a longer fence", () => {+ const doc = ProseMirrorNode.fromJSON(schema, {+ type: "doc",+ content: [+ {+ type: "codeBlock",+ attrs: { fence: "```", close: "\n```" },+ content: [{ type: "text", text: "initial\n```\nsecret" }],+ },+ ],+ });+ const stored = serializeEditorDoc(doc).value;+ expect(stored).toBe("````\ninitial\n```\nsecret\n````");+ expect(buildDocJson(stored, () => ({ label: "", description: null })).content).toHaveLength(1);+ expect(roundTrip(stored).value).toBe(stored);+ });++ it("closes an unclosed fence that has a block after it", () => {+ const doc = ProseMirrorNode.fromJSON(schema, {+ type: "doc",+ content: [+ { type: "codeBlock", attrs: { close: "" }, content: [{ type: "text", text: "code" }] },+ { type: "paragraph", content: [{ type: "text", text: "after" }] },+ ],+ });+ expect(serializeEditorDoc(doc).value).toBe("```\ncode\n```\nafter");+ // At the end of the draft it stays unclosed, as it was written.+ expect(roundTrip("```\ncode").value).toBe("```\ncode");+ });++ it("counts a chip's source in a fence as one cursor position, as the draft store does", () => {+ const value = "```\nsee @b.md now\n```\nafter";+ const map = roundTrip(value);+ expect(map.value).toBe(value);+ for (let flat = 0; flat <= map.docLength; flat += 1) {+ expect(flatToCollapsed(map, flat)).toBe(+ collapseExpandedComposerCursor(value, flatToMarkdown(map, flat)),+ );+ }+ const afterChip = "see @b.md".length;+ expect(collapsedToFlat(map, flatToCollapsed(map, afterChip))).toBe(afterChip);+ const end = map.docLength;+ expect(collapsedToFlat(map, flatToCollapsed(map, end))).toBe(end);+ });++ it("keeps fences literal in plain mode", () => {+ const value = "```ts\nconst a = 1;\n```";+ expect(roundTripPlain(value).value).toBe(value);+ });+it("maps every document offset through collapsed coordinates and back", () => {const value = "hi **bold** @README.md bye";const map = roundTrip(value);@@ -353,6 +794,37 @@ describe("composer rich text document model", () => {}});+ // Flipping the rich text setting remounts the editor, and the caret is+ // restored from the stored collapsed cursor. That only works because the+ // coordinate means the same thing on both sides of the flip.+ it.each([+ "plain prose with no styling at all",+ "a chip @README.md counts one character in both modes",+ "$my-skill leads the line",+ "trailing newline\n",+ ])("resolves a collapsed cursor identically in both modes for %s", (value) => {+ const rich = roundTrip(value);+ const plain = roundTripPlain(value);+ expect(rich.value).toBe(value);+ expect(plain.value).toBe(value);+ for (let collapsed = 0; collapsed <= value.length; collapsed += 1) {+ expect(flatToMarkdown(rich, collapsedToFlat(rich, collapsed))).toBe(+ flatToMarkdown(plain, collapsedToFlat(plain, collapsed)),+ );+ }+ });++ it("clamps a cursor that was sitting inside a marker onto the styled text", () => {+ const value = "a **bold** c";+ const plain = roundTripPlain(value);+ const rich = roundTrip(value);+ // Between the two asterisks: a real caret position in plain mode, and no+ // position at all in rich mode, where it lands on the first styled+ // character instead. The flip moves the caret by a marker's width at most.+ expect(flatToMarkdown(plain, collapsedToFlat(plain, 3))).toBe(3);+ expect(flatToMarkdown(rich, collapsedToFlat(rich, 3))).toBe(4);+ });+it("maps markdown offsets at styled edges onto document text", () => {const value = "a **bold** c";const map = roundTrip(value);@@ -365,6 +837,63 @@ describe("composer rich text document model", () => {});});+describe("serializeSelection", () => {+ /** The stored Markdown of the selection from the start of `first` to the end of `last`. */+ function copy(value: string, first: string, last: string) {+ const doc = ProseMirrorNode.fromJSON(+ schema,+ buildDocJson(value, (name) => ({ label: name, description: null })),+ );+ let from = -1;+ let to = -1;+ doc.descendants((node, pos) => {+ if (!node.isText) return true;+ const text = node.text ?? "";+ if (from < 0 && text.includes(first)) from = pos + text.indexOf(first);+ if (text.includes(last)) to = pos + text.lastIndexOf(last) + last.length;+ return false;+ });+ return serializeSelection(doc, from, to);+ }++ it("keeps the markers of the list items it spans", () => {+ expect(copy("- one\n- two\n- three", "one", "two")).toBe("- one\n- two");+ expect(copy("3) one\n4) two", "one", "two")).toBe("3) one\n4) two");+ expect(copy("- [ ] one\n- [x] two", "one", "two")).toBe("- [ ] one\n- [x] two");+ });++ it("keeps the nesting of an item and its children", () => {+ expect(copy("- p\n - a\n - b", "p", "a")).toBe("- p\n - a");+ });++ it("keeps the prefix of the quote lines it spans", () => {+ expect(copy("> one\n> two", "one", "two")).toBe("> one\n> two");+ });++ it("copies text within one block without its marker", () => {+ expect(copy("- one two", "one", "one")).toBe("one");+ });++ it("copies across blocks as they are written", () => {+ expect(copy("intro\n- one", "intro", "one")).toBe("intro\n- one");+ });+});++describe("pasting into a list item or quote", () => {+ it("keeps inline marks but builds no blocks", () => {+ const content = buildTiptapContent(+ "**bold** text\n- item\n> quote",+ () => ({ label: "", description: null }),+ { styling: true, blocks: false },+ );+ expect(content.map((block) => block.type)).toEqual(["paragraph", "paragraph", "paragraph"]);+ const first = content[0] as { content: { text: string; marks?: { type: string }[] }[] };+ expect(first.content[0]).toMatchObject({ text: "bold", marks: [{ type: "bold" }] });+ expect(JSON.stringify(content[1])).toContain("- item");+ expect(JSON.stringify(content[2])).toContain("> quote");+ });+});+describe("caret stops at styled edges", () => {function stateAt(value: string, pmPos: number) {const doc = ProseMirrorNode.fromJSON(diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.tsindex 49a489c82ad..efdfb145dc1 100644--- a/apps/web/src/composer-rich-text-doc.ts+++ b/apps/web/src/composer-rich-text-doc.ts@@ -1,9 +1,24 @@-import { Mark, type Node as ProseMirrorNode } from "@tiptap/pm/model";-import type { EditorState, Transaction } from "@tiptap/pm/state";+import { joinBackward, joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands";+import { Fragment, Mark, type Node as ProseMirrorNode, type ResolvedPos } from "@tiptap/pm/model";import { Code } from "@tiptap/extension-code";+import { Blockquote } from "@tiptap/extension-blockquote";+import { CodeBlock } from "@tiptap/extension-code-block";+import { Heading } from "@tiptap/extension-heading";+import { HorizontalRule } from "@tiptap/extension-horizontal-rule";+import { type Command, type Editor, mergeAttributes } from "@tiptap/core";+import { BulletList, ListItem, OrderedList } from "@tiptap/extension-list";import { TaskItem } from "@tiptap/extension-task-item";+import { TaskList } from "@tiptap/extension-task-list";+import {+ type EditorState,+ Plugin,+ Selection,+ TextSelection,+ type Transaction,+} from "@tiptap/pm/state";import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";+import { nextOrderedMarkerText } from "~/composer-list-continuation";import { parseInlineMarkdown, RICH_TEXT_DELIMITERS, type RichTextMark } from "~/composer-rich-text";import { collectInlineContextIds } from "~/lib/composerContextReferences";@@ -55,12 +70,53 @@ export const ComposerCodeExtension = Code.extend({exitable: false,});+/**+ * Tiptap's block extensions each bind a chord that turns the current block+ * into their node (Mod-Shift-8 for a list, Mod-Alt-c for a fence, and so on).+ * The composer does not offer them, and they are not harmless: run inside a+ * quote they nest a block the quote serializer cannot write, and the text in+ * it drops out of the stored draft. `drop` names the chords to remove; the+ * keys the composer relies on, such as Backspace and the arrows at a block's+ * edge, stay.+ */+function withoutBlockChords<Shortcuts extends Record<string, unknown>>(+ shortcuts: Shortcuts | undefined,+ drop: readonly string[],+): Shortcuts {+ return Object.fromEntries(+ Object.entries(shortcuts ?? {}).filter(([key]) => !drop.includes(key)),+ ) as Shortcuts;+}++/**+ * What a list item may hold: its own line, then nested lists. That is all the+ * Markdown can write, so ProseMirror refuses any join, wrap or paste that+ * would put a second line or another block into an item.+ */+const LIST_ITEM_CONTENT = "paragraph list*";++/** Task lists come from `- [ ]` alone; Mod-Shift-9 would nest one in a quote. */+export const ComposerTaskListExtension = TaskList.extend({+ addKeyboardShortcuts() {+ return withoutBlockChords(this.parent?.(), ["Mod-Shift-9"]);+ },+});++/**+ * Tiptap's Tab and Shift-Tab sink and lift an item without touching its+ * `indent`, so the stored draft keeps the old nesting and the next rebuild+ * undoes the move. The composer nests through its own Tab, which edits the+ * source the way plain mode does.+ */+const LIST_NESTING_KEYS = ["Tab", "Shift-Tab"];+/*** Task list items keep their exact source indent in an attribute so nesting* round-trips byte-identically. Checkbox case (`[X]`) normalizes to `[x]` —* the same fixed-point deal as `__bold__` becoming `**bold**`.*/export const ComposerTaskItemExtension = TaskItem.extend({+ content: LIST_ITEM_CONTENT,addAttributes() {return {...this.parent?.(),@@ -69,8 +125,222 @@ export const ComposerTaskItemExtension = TaskItem.extend({contentSpace: { default: null },};},+ addKeyboardShortcuts() {+ return withoutBlockChords(this.parent?.(), LIST_NESTING_KEYS);+ },}).configure({ nested: true });+/**+ * Fenced code blocks keep their exact source delimiters so a fence round-trips+ * byte-identically: `fence` is the opening run of backticks or tildes,+ * `language` its info string, and `close` the closing newline and fence, or+ * the empty string when the fence was never closed.+ *+ * Neither delimiter owns a document character, so the caret can never land+ * inside a fence — the same deal as a checkbox marker.+ *+ * An empty block written with a blank line (```` ```\n\n``` ````) canonicalizes+ * to the blank-free form, the same fixed-point deal as `__bold__` becoming+ * `**bold**`.+ */+export const ComposerCodeBlockExtension = CodeBlock.extend({+ addAttributes() {+ return {+ ...this.parent?.(),+ language: { default: "" },+ fence: { default: "```" },+ close: { default: "\n```" },+ };+ },+ addKeyboardShortcuts() {+ return {+ ...withoutBlockChords(this.parent?.(), ["Mod-Alt-c"]),+ Backspace: () => unwrapCodeBlockAtStart(this.editor),+ };+ },+});++/**+ * Backspace at the start of a fence removes the fence and keeps its lines as+ * paragraphs, the way it removes a list marker. Joining the code onto the line+ * above instead would drop the fence from the draft and leave the rest of the+ * code as stray lines.+ */+function unwrapCodeBlockAtStart(editor: Editor): boolean {+ const { $from, empty } = editor.state.selection;+ if (!empty || $from.parent.type.name !== "codeBlock" || $from.parentOffset !== 0) return false;+ const { schema } = editor.state;+ const paragraphs = $from.parent.textContent+ .split("\n")+ .map((line) => schema.nodes.paragraph!.create(null, line ? schema.text(line) : null));+ const start = $from.before();+ const tr = editor.state.tr.replaceWith(start, $from.after(), paragraphs);+ editor.view.dispatch(tr.setSelection(TextSelection.create(tr.doc, start + 1)));+ return true;+}++/**+ * The markdown a code block node serializes to, delimiters included. `followed`+ * says another block comes after it in the draft.+ */+function codeBlockSource(+ node: ProseMirrorNode,+ followed: boolean,+): {+ open: string;+ content: string;+ close: string;+} {+ const attrs = node.attrs as Record<string, unknown>;+ let fence = typeof attrs.fence === "string" && attrs.fence ? attrs.fence : "```";+ const language = typeof attrs.language === "string" ? attrs.language : "";+ let close = typeof attrs.close === "string" ? attrs.close : "";+ const content = node.textContent;+ // Code holding a line that would close the fence, such as a pasted fence,+ // is written inside a longer one, so the agent reads all of it as code. A+ // parsed block never holds such a line, so its source stays byte-identical.+ const longest = Math.max(+ 0,+ ...content+ .split("\n")+ .filter((line) => isClosingFence(line, fence))+ .map((line) => /^[`~]+/.exec(line)![0].length),+ );+ if (longest > 0) {+ fence = fence[0]!.repeat(longest + 1);+ if (close) close = `\n${fence}`;+ }+ // An unclosed fence runs to the end of the draft, so with a block after it+ // the fence is written closed, or the next rebuild would read that block as code.+ if (!close && followed) close = `\n${fence}`;+ return { open: `${fence}${language}${content ? "\n" : ""}`, content, close };+}++/**+ * Bullet and ordered items keep their exact source marker so a list+ * round-trips byte-identically: `marker` is the literal `-`, `*`, `+`, `3.`+ * or `3)`, `space` what followed it, and `indent` the leading whitespace.+ * Numbering is not renumbered: what the user typed is what the agent gets.+ */+const ComposerListItemExtension = ListItem.extend({+ content: LIST_ITEM_CONTENT,+ addAttributes() {+ return {+ ...this.parent?.(),+ indent: { default: "" },+ marker: { default: "-" },+ space: { default: " " },+ };+ },+ addKeyboardShortcuts() {+ return {+ ...withoutBlockChords(this.parent?.(), LIST_NESTING_KEYS),+ // Task items share these: the list extensions are always loaded together.+ Backspace: () => backspaceAcrossList(this.editor),+ Delete: () => deleteAcrossList(this.editor),+ };+ },+ // The source marker rides on the item so the composer draws `3)` and a+ // nested `7.` as written, rather than the browser own numbering.+ renderHTML({ node, HTMLAttributes }) {+ return ["li", mergeAttributes(HTMLAttributes, { "data-marker": node.attrs.marker }), 0];+ },+});++export const ComposerListExtensions = [+ BulletList.extend({+ addKeyboardShortcuts() {+ return withoutBlockChords(this.parent?.(), ["Mod-Shift-8"]);+ },+ }),+ OrderedList.extend({+ addKeyboardShortcuts() {+ return withoutBlockChords(this.parent?.(), ["Mod-Shift-7"]);+ },+ }),+ ComposerListItemExtension,+];++/**+ * A quote keeps the exact `>` prefix its lines were written with, applied to+ * every line, so it round-trips byte-identically and a new line typed inside+ * it gets the same prefix. One source line is one paragraph; a line whose+ * prefix differs starts a sibling quote. Nested markers and list markers+ * inside a quote stay literal text: the composer quotes prose, not documents.+ */+const ComposerBlockquoteExtension = Blockquote.extend({+ content: "paragraph+",+ addAttributes() {+ return { ...this.parent?.(), prefix: { default: "> " } };+ },+ addKeyboardShortcuts() {+ return withoutBlockChords(this.parent?.(), ["Mod-Shift-b"]);+ },+});++/**+ * A rule keeps the exact line it was written as (`---`, `* * *`, `_____`), so+ * it round-trips byte-identically. It owns no document characters: offsets+ * inside its source clamp to the block after it.+ *+ * A rule cannot hold the caret, so a document never ends in one: an empty+ * line follows it, which the draft does not write (see `isTrailingLineAfterRule`).+ * A draft ending in `---\n` reads back the same way and so loses that newline,+ * the same fixed-point deal as `__bold__` becoming `**bold**`.+ */+const ComposerHorizontalRuleExtension = HorizontalRule.extend({+ addAttributes() {+ return { ...this.parent?.(), source: { default: "---" } };+ },+ addProseMirrorPlugins() {+ return [+ ...(this.parent?.() ?? []),+ new Plugin({+ appendTransaction: (transactions, _, state) => {+ if (!transactions.some((tr) => tr.docChanged)) return null;+ if (state.doc.lastChild?.type.name !== "horizontalRule") return null;+ return state.tr.insert(state.doc.content.size, state.schema.nodes.paragraph!.create());+ },+ }),+ ];+ },+});++/** The empty line after a rule that ends the document, which writes nothing. */+function isTrailingLineAfterRule(doc: ProseMirrorNode, index: number): boolean {+ const block = doc.child(index);+ return (+ index === doc.childCount - 1 &&+ index > 0 &&+ block.type.name === "paragraph" &&+ block.content.size === 0 &&+ doc.child(index - 1).type.name === "horizontalRule"+ );+}++/**+ * A heading keeps the exact whitespace between its `#`s and its text. The+ * `#`s must be followed by whitespace to count, which is also what keeps a+ * `#1234` pull request reference a reference: the marker owns no document+ * characters, closing `#`s stay literal text, and nothing is ever stripped.+ */+const ComposerHeadingExtension = Heading.extend({+ addAttributes() {+ return { ...this.parent?.(), space: { default: " " } };+ },+ // Its only shortcuts are the Mod-Alt-1…6 block chords.+ addKeyboardShortcuts() {+ return {};+ },+});++/** Block-level nodes beyond lists and fences, in the order the parser tries them. */+export const ComposerBlockExtensions = [+ ComposerBlockquoteExtension,+ ComposerHorizontalRuleExtension,+ ComposerHeadingExtension,+];+function randomNodeKey(): string {return `tiptap-${Math.random().toString(36).slice(2)}`;}@@ -98,10 +368,73 @@ function parseTaskPrefix(head: string): { prefix: TaskLinePrefix; markerLength:};}+/**+ * An opening fence: three or more backticks or tildes at the start of a line,+ * followed by an info string. A backtick fence cannot carry a backtick in its+ * info string, which is what keeps `` `code` `` on its own line literal.+ * Indented fences stay paragraphs — the composer is a prompt box, not a+ * CommonMark renderer, and honoring indentation would cost another attribute+ * for no case anyone writes.+ */+export function parseOpeningFence(line: string): { fence: string; language: string } | null {+ // `[^\n]` rather than `.`, here and in the block rules: a CRLF draft's lines+ // end in `\r`, which `.` refuses, and the `\r` stays in the stored text.+ const match = /^(`{3,}|~{3,})([^\n]*)$/.exec(line);+ if (!match) return null;+ const fence = match[1]!;+ const language = match[2]!;+ if (fence.startsWith("`") && language.includes("`")) return null;+ return { fence, language };+}++/** A closing fence matches the opening run's character and is at least as long. */+export function isClosingFence(line: string, fence: string): boolean {+ const match = /^(`{3,}|~{3,})[ \t]*\r?$/.exec(line);+ if (!match) return false;+ const run = match[1]!;+ return run[0] === fence[0] && run.length >= fence.length;+}++type ListLinePrefix =+ | ({ kind: "task" } & TaskLinePrefix)+ | { kind: "bullet" | "ordered"; indent: string; marker: string; space: string };++/**+ * The same grammar the literal continuation uses, so plain and rich mode agree+ * on what a list line is: a task first (it also looks like a bullet), then an+ * ordered marker, then a bullet. A marker followed by nothing is an empty item.+ */+function parseListPrefix(line: string): { prefix: ListLinePrefix; markerLength: number } | null {+ const task = parseTaskPrefix(line);+ if (task) return { prefix: { kind: "task", ...task.prefix }, markerLength: task.markerLength };+ const ordered = /^([ \t]*)(\d+[.)])((?:[ \t]+)|$)/.exec(line);+ if (ordered) {+ return {+ prefix: { kind: "ordered", indent: ordered[1]!, marker: ordered[2]!, space: ordered[3]! },+ markerLength: ordered[0].length,+ };+ }+ const bullet = /^([ \t]*)([-*+])((?:[ \t]+)|$)/.exec(line);+ if (bullet) {+ return {+ prefix: { kind: "bullet", indent: bullet[1]!, marker: bullet[2]!, space: bullet[3]! },+ markerLength: bullet[0].length,+ };+ }+ return null;+}++/** Items of one kind and marker family belong to one list; a change starts a sibling list. */+function listKey(prefix: ListLinePrefix): string {+ if (prefix.kind === "task") return "task";+ if (prefix.kind === "ordered") return `ordered:${prefix.marker.slice(-1)}`;+ return `bullet:${prefix.marker}`;+}+type InlineJson = Record<string, unknown>;interface DocLine {- task: TaskLinePrefix | null;+ list: ListLinePrefix | null;inline: InlineJson[];}@@ -143,28 +476,52 @@ function atomJsonForSegment(};}-interface PendingTaskItem extends TaskLinePrefix {+interface PendingItem {+ prefix: ListLinePrefix;content: InlineJson[];- children: PendingTaskItem[];+ /** Nested lists, in order; a parent can hold lists of different kinds. */+ children: PendingList[];}-function taskListJson(items: PendingTaskItem[]): InlineJson {- return {- type: "taskList",- content: items.map((item) => ({- type: "taskItem",- attrs: {- checked: item.checked,- indent: item.indent,- markerSpace: item.markerSpace,- contentSpace: item.contentSpace,- },- content: [- { type: "paragraph", content: item.content },- ...(item.children.length > 0 ? [taskListJson(item.children)] : []),- ],- })),- };+interface PendingList {+ key: string;+ items: PendingItem[];+}++function listJson(list: PendingList): InlineJson {+ const first = list.items[0]!.prefix;+ const items = list.items.map((item) => {+ const content = [+ { type: "paragraph", content: item.content },+ ...item.children.map((child) => listJson(child)),+ ];+ if (item.prefix.kind === "task") {+ return {+ type: "taskItem",+ attrs: {+ checked: item.prefix.checked,+ indent: item.prefix.indent,+ markerSpace: item.prefix.markerSpace,+ contentSpace: item.prefix.contentSpace,+ },+ content,+ };+ }+ return {+ type: "listItem",+ attrs: { indent: item.prefix.indent, marker: item.prefix.marker, space: item.prefix.space },+ content,+ };+ });+ if (first.kind === "task") return { type: "taskList", content: items };+ if (first.kind === "ordered") {+ return {+ type: "orderedList",+ attrs: { start: Number.parseInt(first.marker, 10) || 1 },+ content: items,+ };+ }+ return { type: "bulletList", content: items };}function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unknown> {@@ -180,9 +537,12 @@ function textJsonForSpan(text: string, marks: RichTextMark[]): Record<string, unexport function buildTiptapContent(value: string,skillLabelFor: (name: string) => SkillMeta,- options?: { styling?: boolean },+ options?: { styling?: boolean; blocks?: boolean },): Record<string, unknown>[] {const styling = options?.styling ?? true;+ // Inline marks without block structure: text pasted into a list item or+ // quote, which has no line to write a nested block into.+ const blockSyntax = styling && (options?.blocks ?? true);// Hide token source from the markdown parser, then restore the atoms with// the marks of their surrounding text. Choose a sentinel absent from input.let sentinel = "\uFFFC";@@ -190,17 +550,19 @@ export function buildTiptapContent(sentinel = String.fromCodePoint(codePoint);}const atoms: InlineJson[] = [];+ // Code fences hold no chips, so their lines put the original source back in+ // place of the sentinel rather than building an atom for it.+ const atomSources: string[] = [];const text = splitPromptIntoComposerSegments(value).map((segment) => {if (segment.type === "text") return segment.text;atoms.push(atomJsonForSegment(segment, skillLabelFor));+ atomSources.push(segment.source);return sentinel;}).join("");let atomIndex = 0;- const lines: DocLine[] = text.split("\n").map((line) => {- const parsed = styling ? parseTaskPrefix(line) : null;- const content = parsed ? line.slice(parsed.markerLength) : line;+ const buildInline = (content: string): InlineJson[] => {const spans = styling ? parseInlineMarkdown(content) : [{ text: content, marks: [] }];const inline: InlineJson[] = [];for (const span of spans) {@@ -212,61 +574,185 @@ export function buildTiptapContent(if (piece) inline.push(textJsonForSpan(piece, span.marks));});}- return { task: parsed?.prefix ?? null, inline };- });+ return inline;+ };+ const buildDocLine = (line: string): DocLine => {+ const parsed = blockSyntax ? parseListPrefix(line) : null;+ const content = parsed ? line.slice(parsed.markerLength) : line;+ return { list: parsed?.prefix ?? null, inline: buildInline(content) };+ };- // Pass 2: consecutive task lines group into (possibly nested) task lists- // by indent prefix; everything else stays a paragraph.- const blocks: Record<string, unknown>[] = [];- let stack: { indent: string; items: PendingTaskItem[] }[] = [];- const flushTasks = () => {- if (stack.length > 0) {- blocks.push(taskListJson(stack[0]!.items));- stack = [];+ // Pass 1: fenced blocks claim their lines whole; everything else becomes an+ // inline-parsed line. Fence bodies restore chip sources as literal text.+ const sourceLines = text.split("\n");+ const entries: (+ | { code: Record<string, unknown> }+ | { rule: string }+ | { heading: { level: number; space: string; inline: InlineJson[] } }+ | { quote: { prefix: string; inline: InlineJson[] } }+ | { line: DocLine }+ )[] = [];+ const restoreSources = (line: string) =>+ line.split(sentinel).reduce((joined, piece, index) => {+ if (index === 0) return piece;+ atomIndex += 1;+ return joined + atomSources[atomIndex - 1]! + piece;+ }, "");++ for (let index = 0; index < sourceLines.length; index += 1) {+ const line = sourceLines[index]!;+ const opening = blockSyntax ? parseOpeningFence(line) : null;+ if (!opening) {+ // A thematic break outranks a list: `- - -` and `* * *` are rules, and+ // `***` on its own line is a rule rather than an empty bold span.+ if (blockSyntax && /^([-*_])(?:[ \t]*\1){2,}[ \t]*\r?$/.test(line)) {+ entries.push({ rule: line });+ continue;+ }+ const heading = blockSyntax ? /^(#{1,6})([ \t]+)([^\n]*)$/.exec(line) : null;+ if (heading) {+ entries.push({+ heading: {+ level: heading[1]!.length,+ space: heading[2]!,+ inline: buildInline(heading[3]!),+ },+ });+ continue;+ }+ const quote = blockSyntax ? /^(>[ \t]*)([^\n]*)$/.exec(line) : null;+ if (quote) entries.push({ quote: { prefix: quote[1]!, inline: buildInline(quote[2]!) } });+ else entries.push({ line: buildDocLine(line) });+ continue;+ }+ // The info string went through the sentinel pass like every line, so a+ // token in it is put back as source here, in order, before the body.+ const language = restoreSources(opening.language);+ const body: string[] = [];+ let cursor = index + 1;+ let close = "";+ while (cursor < sourceLines.length) {+ const candidate = sourceLines[cursor]!;+ if (isClosingFence(candidate, opening.fence)) {+ close = `\n${candidate}`;+ break;+ }+ body.push(restoreSources(candidate));+ cursor += 1;}+ // An unclosed fence runs to the end of the prompt, which is what the user+ // is looking at while they are still typing the block.+ const closed = cursor < sourceLines.length;+ const content = body.join("\n");+ entries.push({+ code: {+ type: "codeBlock",+ attrs: { language, fence: opening.fence, close },+ ...(content ? { content: [{ type: "text", text: content }] } : {}),+ },+ });+ index = closed ? cursor : sourceLines.length;+ }++ // Pass 2: consecutive list lines group into (possibly nested) lists by+ // indent prefix; everything else stays a paragraph. Items of a different+ // kind or marker at the same indent start a sibling list, so `* a` under+ // `- b` keeps its star and a task list can follow a bullet list.+ const blocks: Record<string, unknown>[] = [];+ let rootLists: PendingList[] = [];+ let stack: { indent: string; list: PendingList; container: PendingList[] }[] = [];+ const flushLists = () => {+ for (const list of rootLists) blocks.push(listJson(list));+ rootLists = [];+ stack = [];+ };+ const openList = (container: PendingList[], key: string): PendingList => {+ const list = { key, items: [] };+ container.push(list);+ return list;+ };+ let openQuote: { prefix: string; content: InlineJson[][] } | null = null;+ const flushQuote = () => {+ if (!openQuote) return;+ blocks.push({+ type: "blockquote",+ attrs: { prefix: openQuote.prefix },+ content: openQuote.content.map((inline) => ({ type: "paragraph", content: inline })),+ });+ openQuote = null;};- for (const line of lines) {- if (!line.task) {- flushTasks();+ for (const entry of entries) {+ if ("quote" in entry) {+ flushLists();+ if (openQuote && openQuote.prefix !== entry.quote.prefix) flushQuote();+ openQuote ??= { prefix: entry.quote.prefix, content: [] };+ openQuote.content.push(entry.quote.inline);+ continue;+ }+ flushQuote();+ if ("code" in entry) {+ flushLists();+ blocks.push(entry.code);+ continue;+ }+ if ("rule" in entry) {+ flushLists();+ blocks.push({ type: "horizontalRule", attrs: { source: entry.rule } });+ continue;+ }+ if ("heading" in entry) {+ flushLists();+ blocks.push({+ type: "heading",+ attrs: { level: entry.heading.level, space: entry.heading.space },+ content: entry.heading.inline,+ });+ continue;+ }+ const line = entry.line;+ if (!line.list) {+ flushLists();blocks.push({ type: "paragraph", content: line.inline });continue;}- const item: PendingTaskItem = {- ...line.task,- content: line.inline,- children: [],- };+ const item: PendingItem = { prefix: line.list, content: line.inline, children: [] };+ const key = listKey(line.list);+ const indent = line.list.indent;for (;;) {const top = stack[stack.length - 1];if (!top) {// A leading indented item with no parent flattens but keeps indent.- stack.push({ indent: item.indent, items: [] });+ stack.push({ indent, list: openList(rootLists, key), container: rootLists });continue;}- if (top.indent === item.indent) {- top.items.push(item);+ if (top.indent === indent) {+ if (top.list.key !== key) top.list = openList(top.container, key);+ top.list.items.push(item);break;}- if (top.indent !== "" && !item.indent.startsWith(top.indent)) {+ if (top.indent !== "" && !indent.startsWith(top.indent)) {if (stack.length > 1) {stack.pop();continue;}- top.indent = item.indent;- top.items.push(item);+ top.indent = indent;+ if (top.list.key !== key) top.list = openList(top.container, key);+ top.list.items.push(item);break;}- const parent = top.items[top.items.length - 1];+ const parent = top.list.items[top.list.items.length - 1];if (!parent) {- top.items.push(item);+ top.list.items.push(item);break;}- parent.children.push(item);- stack.push({ indent: item.indent, items: parent.children });+ const list = openList(parent.children, key);+ stack.push({ indent, list, container: parent.children });+ list.items.push(item);break;}}- flushTasks();+ flushQuote();+ flushLists();return blocks;}@@ -275,7 +761,10 @@ export function buildDocJson(skillLabelFor: (name: string) => SkillMeta,options?: { styling?: boolean },) {- return { type: "doc", content: buildTiptapContent(value, skillLabelFor, options) };+ const content = buildTiptapContent(value, skillLabelFor, options);+ // The empty line the rule extension keeps after a final rule.+ if (content.at(-1)?.type === "horizontalRule") content.push({ type: "paragraph" });+ return { type: "doc", content };}export interface RichRun {@@ -495,7 +984,210 @@ function appendInlineRuns(}}-function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {+const LIST_NODE_NAMES = new Set(["taskList", "bulletList", "orderedList"]);+const LIST_ITEM_NODE_NAMES = new Set(["taskItem", "listItem"]);++/**+ * Gives the list item at the caret the indent and marker of the sibling it+ * follows, or of the one after it when it is first. Tiptap moves items between+ * lists without touching these attributes, so without this the stored draft+ * keeps an outdented item at its old depth, and the next rebuild nests it again.+ */+function alignListItemWithSiblings(tr: Transaction, itemType: string): void {+ const $pos = tr.selection.$from;+ // A lift out of the list leaves the caret in a paragraph, possibly inside+ // an item of another kind, which did not move.+ if ($pos.depth < 3 || $pos.node(-1).type.name !== itemType) return;+ const item = $pos.node(-1);+ const list = $pos.node(-2);+ const index = $pos.index(-2);+ const sibling =+ index > 0 ? list.child(index - 1) : index + 1 < list.childCount ? list.child(index + 1) : null;+ if (!sibling) return;+ const attrs: Record<string, unknown> = { ...item.attrs, indent: sibling.attrs.indent };+ if (item.type.name === "taskItem") {+ attrs.markerSpace = sibling.attrs.markerSpace;+ } else {+ const marker = typeof sibling.attrs.marker === "string" ? sibling.attrs.marker : "-";+ attrs.marker = index > 0 && /^\d+[.)]$/.test(marker) ? nextOrderedMarkerText(marker) : marker;+ }+ tr.setNodeMarkup($pos.before(-1), undefined, attrs);+ if (typeof attrs.marker === "string" && /^\d+[.)]$/.test(attrs.marker)) {+ renumberFollowingItems(tr, $pos.before(-2), index, attrs.marker);+ }+}++/**+ * Counts the items after `index` on from `marker`, so an item inserted in the+ * middle of an ordered list pushes the rest down instead of repeating a number.+ * Only marker attributes change, so positions stay valid while walking.+ */+function renumberFollowingItems(+ tr: Transaction,+ listPos: number,+ index: number,+ marker: string,+): void {+ const list = tr.doc.nodeAt(listPos);+ if (!list) return;+ let pos = listPos + 1;+ let previous = marker;+ list.forEach((child, _, childIndex) => {+ if (childIndex > index) {+ previous = nextOrderedMarkerText(previous);+ if (child.attrs.marker !== previous) {+ tr.setNodeMarkup(pos, undefined, { ...child.attrs, marker: previous });+ }+ }+ pos += child.nodeSize;+ });+}++/**+ * Shift+Enter in a list or task item: split it, or on an empty item leave one+ * level of nesting. Either way the item at the caret ends up written with the+ * indent and marker of its new siblings.+ */+export function splitOrLiftListItem(editor: Editor): boolean {+ const $from = editor.state.selection.$from;+ const itemType = listItemTypeAt($from);+ if (!itemType) return false;+ const empty = $from.parent.content.size === 0;+ // One transaction, so the split or lift and the realignment undo together.+ const move: Command = ({ commands, tr }) => {+ const moved =+ commands.splitListItem(+ itemType,+ itemType === "taskItem" ? { checked: false } : { space: " " },+ ) ||+ (empty && commands.liftListItem(itemType));+ if (moved) alignListItemWithSiblings(tr, itemType);+ return moved;+ };+ return editor.can().command(move) && editor.chain().command(move).run();+}++/**+ * Deletes `from`–`to`, the typed `[ ]` at the start of a bullet item's text,+ * and makes that item a task where it stands. A task list holds only tasks, so+ * the bullet list splits around it into sibling lists, which is also how the+ * parser reads a change of list kind. Nested items and the item's own nested+ * lists stay where they are.+ */+export function convertBulletItemToTask(+ tr: Transaction,+ from: number,+ to: number,+ checked: boolean,+): void {+ tr.delete(from, to);+ const $pos = tr.doc.resolve(from);+ const item = $pos.node(-1);+ const list = $pos.node(-2);+ const index = $pos.index(-2);+ const { schema } = tr.doc.type;+ const before: ProseMirrorNode[] = [];+ const after: ProseMirrorNode[] = [];+ list.forEach((child, _, childIndex) => {+ if (childIndex < index) before.push(child);+ else if (childIndex > index) after.push(child);+ });+ // The spacing after the bullet stays between the dash and the box, as typed.+ const markerSpace =+ typeof item.attrs.space === "string" && item.attrs.space ? item.attrs.space : " ";+ const task = schema.nodes.taskItem!.create(+ { checked, indent: item.attrs.indent, markerSpace },+ item.content,+ );+ const lists = [+ ...(before.length > 0 ? [list.copy(Fragment.from(before))] : []),+ schema.nodes.taskList!.create(null, task),+ ...(after.length > 0 ? [list.copy(Fragment.from(after))] : []),+ ];+ const listStart = $pos.before(-2);+ tr.replaceWith(listStart, listStart + list.nodeSize, lists);+ // Into the task list, its item and its paragraph.+ const caret = listStart + (before.length > 0 ? lists[0]!.nodeSize : 0) + 3;+ tr.setSelection(TextSelection.create(tr.doc, caret));+}++function listItemTypeAt($pos: ResolvedPos): "listItem" | "taskItem" | null {+ const name = $pos.depth > 1 ? $pos.node(-1).type.name : null;+ return name === "listItem" || name === "taskItem" ? name : null;+}++/**+ * Backspace at the start of an item's text leaves one level of nesting, or+ * the list itself at the top, written at its new depth. At the start of a+ * line right after a list it joins that line onto the list's last line.+ * Tiptap's list keymap, which StarterKit loads, does both by moving nodes+ * without touching their indent or marker, so the composer turns it off.+ */+export function backspaceAcrossList(editor: Editor): boolean {+ const { state } = editor;+ const { $from, empty } = state.selection;+ if (!empty || $from.parentOffset !== 0) return false;+ const itemType = listItemTypeAt($from);+ if (itemType && $from.index(-1) === 0) {+ const lift: Command = ({ commands, tr }) => {+ const moved = commands.liftListItem(itemType);+ if (moved) alignListItemWithSiblings(tr, itemType);+ return moved;+ };+ // Not `can()` first: a dry run of the lift skips the schema check, so it+ // says yes to a task under a bullet, which has no list to lift into. Its+ // text joins the line above instead.+ return editor.chain().command(lift).run() || joinBackward(state, editor.view.dispatch);+ }+ const before = $from.depth === 1 ? $from.node(0).maybeChild($from.index(0) - 1) : null;+ if (before && LIST_NODE_NAMES.has(before.type.name) && $from.parent.type.name !== "codeBlock") {+ return joinTextblockBackward(state, editor.view.dispatch);+ }+ return false;+}++/**+ * Delete at the end of a line next to list structure pulls the next line's+ * text up onto it. Tiptap's default would instead nest the next item, or a+ * whole list, under this one at its old indent. Before a fence, anywhere, it+ * does nothing: pulling the code into the line would drop the fence from the+ * draft and leave the rest of the code as stray lines.+ */+export function deleteAcrossList(editor: Editor): boolean {+ const { state } = editor;+ const { $from, empty } = state.selection;+ if (!empty || !$from.parent.isTextblock || $from.depth === 0) return false;+ if ($from.parentOffset !== $from.parent.content.size) return false;+ const next = Selection.findFrom(state.doc.resolve($from.after()), 1, true);+ if (!next) return false;+ if (next.$from.parent.type.name === "codeBlock") return $from.parent.type.name !== "codeBlock";+ if (!listItemTypeAt($from) && !listItemTypeAt(next.$from)) return false;+ return joinTextblockForward(state, editor.view.dispatch);+}++/** The literal prefix an item serializes to. Empty items keep their exact spacing. */+function listItemPrefix(item: ProseMirrorNode, empty: boolean): string {+ const attrs = item.attrs as Record<string, unknown>;+ const indent = typeof attrs.indent === "string" ? attrs.indent : "";+ if (item.type.name === "taskItem") {+ const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";+ const contentSpace =+ typeof attrs.contentSpace === "string"+ ? attrs.contentSpace || (empty ? "" : " ")+ : empty+ ? ""+ : " ";+ return `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;+ }+ const marker = typeof attrs.marker === "string" && attrs.marker ? attrs.marker : "-";+ // A bare `-` keeps its missing space only while the item is empty: once it+ // has text, `-text` would not be a list line any more.+ const space =+ typeof attrs.space === "string" ? attrs.space || (empty ? "" : " ") : empty ? "" : " ";+ return `${indent}${marker}${space}`;+}++function walkList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {let itemPos = listStart + 1;let firstItem = true;list.content.forEach((item) => {@@ -505,17 +1197,8 @@ function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulconst itemContentStart = itemPos + 1;const first = item.firstChild;const empty = first?.type.name === "paragraph" && first.content.childCount === 0;- const attrs = item.attrs as Record<string, unknown>;- const indent = typeof attrs.indent === "string" ? attrs.indent : "";- const markerSpace = typeof attrs.markerSpace === "string" ? attrs.markerSpace : " ";- const contentSpace =- typeof attrs.contentSpace === "string"- ? attrs.contentSpace || (empty ? "" : " ")- : empty- ? ""- : " ";- const prefix = `${indent}-${markerSpace}[${attrs.checked === true ? "x" : " "}]${contentSpace}`;- // The checkbox owns no document characters; every prefix offset clamps+ const prefix = listItemPrefix(item, empty);+ // The marker owns no document characters; every prefix offset clamps// to the start of the item text, exactly like style markers.acc.runs.push({kind: "prefix",@@ -537,8 +1220,8 @@ function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulitem.content.forEach((child) => {if (!firstBlock) pushBreakRun(acc);firstBlock = false;- if (child.type.name === "taskList") {- walkTaskList(child, childPos, acc);+ if (LIST_NODE_NAMES.has(child.type.name)) {+ walkList(child, childPos, acc);} else if (child.type.name === "paragraph") {appendInlineRuns(child, childPos + 1, acc);}@@ -548,6 +1231,111 @@ function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumul});}+/**+ * A fence becomes one run whose open and close lengths are the delimiters, so+ * every cursor rule that already clamps out of a style marker clamps out of a+ * fence too. `nodeName` keeps the marker decorations off it: a code block is+ * drawn as a block, not revealed a character at a time.+ *+ * The code is literal text in the editor, but the draft store still counts a+ * chip's source in it as one cursor position, as it does everywhere. So the+ * run splits at each chip source, which spans its characters in the document+ * and one position in the collapsed space.+ */+function appendCodeBlockRun(+ block: ProseMirrorNode,+ pmPos: number,+ followed: boolean,+ acc: RichAccumulator,+): void {+ const { open, content, close } = codeBlockSource(block, followed);+ const pieces = content+ ? splitPromptIntoComposerSegments(content).map((segment) =>+ segment.type === "text"+ ? { length: segment.text.length, collapsedLen: segment.text.length }+ : { length: segment.source.length, collapsedLen: 1 },+ )+ : [{ length: 0, collapsedLen: 0 }];+ let offset = 0;+ pieces.forEach((piece, index) => {+ const openLen = index === 0 ? open.length : 0;+ const closeLen = index === pieces.length - 1 ? close.length : 0;+ const collapsedLen = openLen + piece.collapsedLen + closeLen;+ const mdLen = openLen + piece.length + closeLen;+ acc.runs.push({+ kind: "text",+ flatStart: acc.flat,+ docLen: piece.length,+ collapsedLen,+ mdLen,+ openLen,+ closeLen,+ pmPos: pmPos + offset,+ mdStart: acc.md,+ collapsedStart: acc.collapsed,+ nodeName: "codeBlock",+ });+ offset += piece.length;+ acc.flat += piece.length;+ acc.collapsed += collapsedLen;+ acc.md += mdLen;+ });+ acc.value += open + content + close;+}++/** Each paragraph of a quote is one source line behind the quote's prefix. */+function walkBlockquote(quote: ProseMirrorNode, quoteStart: number, acc: RichAccumulator): void {+ const attrs = quote.attrs as Record<string, unknown>;+ const prefix = typeof attrs.prefix === "string" ? attrs.prefix : "> ";+ let childPos = quoteStart + 1;+ let firstLine = true;+ quote.content.forEach((child) => {+ if (!firstLine) pushBreakRun(acc);+ firstLine = false;+ acc.runs.push({+ kind: "prefix",+ flatStart: acc.flat,+ docLen: 0,+ collapsedLen: prefix.length,+ mdLen: prefix.length,+ openLen: 0,+ closeLen: 0,+ pmPos: childPos + 1,+ mdStart: acc.md,+ collapsedStart: acc.collapsed,+ });+ acc.value += prefix;+ acc.collapsed += prefix.length;+ acc.md += prefix.length;+ if (child.type.name === "paragraph") appendInlineRuns(child, childPos + 1, acc);+ childPos += child.nodeSize;+ });+}++/**+ * The stored Markdown of a selection, as copy and cut put it on the clipboard.+ * A slice holds only the content of the blocks the ends share, so items or+ * quote lines arrive without the list or quote that writes their markers. The+ * shared block is put back around them, and an item's list around it.+ */+export function serializeSelection(doc: ProseMirrorNode, from: number, to: number): string {+ const slice = doc.slice(from, to);+ const $from = doc.resolve(from);+ let depth = $from.sharedDepth(to);+ let content: Fragment | ProseMirrorNode = slice.content;+ if (slice.content.firstChild?.isInline) {+ content = doc.type.schema.nodes.paragraph!.create(null, slice.content);+ } else {+ while (depth > 0) {+ const shared = $from.node(depth);+ content = shared.copy(Fragment.from(content));+ if (!LIST_ITEM_NODE_NAMES.has(shared.type.name)) break;+ depth -= 1;+ }+ }+ return serializeEditorDoc(doc.type.create(null, content)).value;+}+export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {const acc: RichAccumulator = { runs: [], value: "", flat: 0, collapsed: 0, md: 0 };const blocks: ProseMirrorNode[] = [];@@ -557,9 +1345,52 @@ export function serializeEditorDoc(doc: ProseMirrorNode): RichDocMap {let pmBlockStart = 0;blocks.forEach((block, blockIndex) => {- if (blockIndex > 0) pushBreakRun(acc);- if (block.type.name === "taskList") {- walkTaskList(block, pmBlockStart, acc);+ if (blockIndex > 0 && !isTrailingLineAfterRule(doc, blockIndex)) pushBreakRun(acc);+ if (LIST_NODE_NAMES.has(block.type.name)) {+ walkList(block, pmBlockStart, acc);+ } else if (block.type.name === "codeBlock") {+ appendCodeBlockRun(block, pmBlockStart + 1, blockIndex < blocks.length - 1, acc);+ } else if (block.type.name === "blockquote") {+ walkBlockquote(block, pmBlockStart, acc);+ } else if (block.type.name === "heading") {+ const attrs = block.attrs as Record<string, unknown>;+ const level = typeof attrs.level === "number" ? attrs.level : 1;+ const space = typeof attrs.space === "string" ? attrs.space : " ";+ const prefix = `${"#".repeat(level)}${space}`;+ acc.runs.push({+ kind: "prefix",+ flatStart: acc.flat,+ docLen: 0,+ collapsedLen: prefix.length,+ mdLen: prefix.length,+ openLen: 0,+ closeLen: 0,+ pmPos: pmBlockStart + 1,+ mdStart: acc.md,+ collapsedStart: acc.collapsed,+ });+ acc.value += prefix;+ acc.collapsed += prefix.length;+ acc.md += prefix.length;+ appendInlineRuns(block, pmBlockStart + 1, acc);+ } else if (block.type.name === "horizontalRule") {+ const attrs = block.attrs as Record<string, unknown>;+ const source = typeof attrs.source === "string" && attrs.source ? attrs.source : "---";+ acc.runs.push({+ kind: "prefix",+ flatStart: acc.flat,+ docLen: 0,+ collapsedLen: source.length,+ mdLen: source.length,+ openLen: 0,+ closeLen: 0,+ pmPos: pmBlockStart + block.nodeSize,+ mdStart: acc.md,+ collapsedStart: acc.collapsed,+ });+ acc.value += source;+ acc.collapsed += source.length;+ acc.md += source.length;} else if (block.type.name === "paragraph") {appendInlineRuns(block, pmBlockStart + 1, acc);}@@ -582,12 +1413,28 @@ function lastRunEnd(map: RichDocMap, space: "collapsed" | "md"): number {: last.mdStart + last.mdLen;}+/**+ * The end of a run belongs to the next run, which is how the end of `**bold**`+ * lands after its markers. A fence is the exception: its close is a line of+ * its own, so the end of the code stays inside the block rather than jumping+ * past the closing fence. Inline marks keep their trailing position.+ */+function runOwnsOffset(run: RichRun, flatOffset: number): boolean {+ const end = run.flatStart + run.docLen;+ return flatOffset < end || (flatOffset === end && run.nodeName === "codeBlock");+}+export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {const bounded = Math.max(0, Math.min(flatOffset, map.docLength));for (const run of map.runs) {- if (bounded < run.flatStart + run.docLen) {+ if (runOwnsOffset(run, bounded)) {if (run.kind === "text" || run.kind === "token") {- return run.collapsedStart + run.openLen + (bounded - run.flatStart);+ // A chip's source in a fence spans its characters but one position.+ const within = Math.min(+ bounded - run.flatStart,+ run.collapsedLen - run.openLen - run.closeLen,+ );+ return run.collapsedStart + run.openLen + within;}return run.collapsedStart + (bounded - run.flatStart);}@@ -598,7 +1445,7 @@ export function flatToCollapsed(map: RichDocMap, flatOffset: number): number {export function flatToMarkdown(map: RichDocMap, flatOffset: number): number {const bounded = Math.max(0, Math.min(flatOffset, map.docLength));for (const run of map.runs) {- if (bounded < run.flatStart + run.docLen) {+ if (runOwnsOffset(run, bounded)) {if (run.kind === "text" || run.kind === "token") {return run.mdStart + run.openLen + (bounded - run.flatStart);}@@ -616,9 +1463,10 @@ export function collapsedToFlat(map: RichDocMap, collapsedOffset: number): numbeif (run.kind === "prefix") return run.flatStart;if (run.kind === "text" || run.kind === "token") {const within = collapsedOffset - run.collapsedStart;+ const contentLen = run.collapsedLen - run.openLen - run.closeLen;// Marker characters clamp to the styled edge: they are shown, never edited.if (within <= run.openLen) return run.flatStart;- if (within >= run.openLen + run.docLen) return run.flatStart + run.docLen;+ if (within >= run.openLen + contentLen) return run.flatStart + run.docLen;return run.flatStart + (within - run.openLen);}return run.flatStart + (collapsedOffset - run.collapsedStart);diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 46b57325a3f..d43fc36769a 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -1422,7 +1422,7 @@ html[data-theme-id] [data-chat-header] [data-slot="separator"] {/* Chat code blocks join the other code surfaces on the code tokens. Thedefault look keeps its secondary/input tints; themed palettes tint thosesurfaces with the accent, which fights syntax highlighting. */-html[data-theme-id] .chat-markdown .chat-markdown-codeblock {+html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock {background-color: var(--code-background);border-color: var(--contrast-border);color: var(--code-foreground);@@ -1433,11 +1433,11 @@ html[data-theme-id] .chat-markdown pre {color: var(--code-foreground);}-html[data-theme-id] .chat-markdown .chat-markdown-codeblock pre {+html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock pre {background-color: transparent;}-html[data-theme-id] .chat-markdown .chat-markdown-codeblock-header {+html[data-theme-id] :is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock-header {color: color-mix(in srgb, var(--code-foreground) 72%, transparent);}@@ -1685,7 +1685,7 @@ code {Inline code stays relative to its sentence so it never towers over prose;diffs and file previews take the size through --diffs-font-size. */.chat-markdown .chat-markdown-shiki .shiki,-.chat-markdown pre code {+:is(.chat-markdown, .composer-tiptap) pre code {font-size: var(--font-size-code, inherit);}@@ -1755,45 +1755,47 @@ code {.chat-markdown ol,.chat-markdown blockquote,.chat-markdown pre,-.chat-markdown .chat-markdown-table-container {+.chat-markdown .chat-markdown-table-container,+.composer-tiptap ul,+.composer-tiptap ol {margin: 0.65rem 0;}-.chat-markdown h1,-.chat-markdown h2,-.chat-markdown h3,-.chat-markdown h4,-.chat-markdown h5,-.chat-markdown h6 {+:is(.chat-markdown, .composer-tiptap) h1,+:is(.chat-markdown, .composer-tiptap) h2,+:is(.chat-markdown, .composer-tiptap) h3,+:is(.chat-markdown, .composer-tiptap) h4,+:is(.chat-markdown, .composer-tiptap) h5,+:is(.chat-markdown, .composer-tiptap) h6 {margin: 1.25rem 0 0.5rem;font-weight: 600;line-height: 1.3;color: var(--contrast-foreground);}-.chat-markdown h1 {+:is(.chat-markdown, .composer-tiptap) h1 {font-size: 1.25rem;}-.chat-markdown h2 {+:is(.chat-markdown, .composer-tiptap) h2 {font-size: 1.125rem;}-.chat-markdown h3 {+:is(.chat-markdown, .composer-tiptap) h3 {font-size: 1rem;}-.chat-markdown h4,-.chat-markdown h5,-.chat-markdown h6 {+:is(.chat-markdown, .composer-tiptap) h4,+:is(.chat-markdown, .composer-tiptap) h5,+:is(.chat-markdown, .composer-tiptap) h6 {font-size: 0.875rem;}-.chat-markdown h6 {+:is(.chat-markdown, .composer-tiptap) h6 {color: var(--contrast-muted-foreground);}-.chat-markdown ul {+:is(.chat-markdown, .composer-tiptap) ul {/* Reset for nested uls under a widened ol. --list-gutter is an inheritedcustom property, so without this a task-list under a multi-digit orderedlist would inherit the outer gutter instead of its own default. */@@ -1807,21 +1809,27 @@ code {widest marker has multiple characters so it isn't clipped by list-style-position:outside painting the marker past the padding box. Reset it here too so anested ol without its own widened marker doesn't inherit the outer one. */-.chat-markdown ol {+:is(.chat-markdown, .composer-tiptap) ol {--list-gutter: 1.25rem;padding-left: var(--list-gutter, 1.25rem);list-style-type: decimal;}-.chat-markdown ol > li::marker {+:is(.chat-markdown, .composer-tiptap) ol > li::marker {font-variant-numeric: tabular-nums;}-.chat-markdown ul ul {+/* The composer shows the marker the source has, `3)` or a nested `7.`, not the+ browser counter. Browsers without ::marker content fall back to `start`. */+.composer-tiptap ol > li[data-marker]::marker {+ content: attr(data-marker) " ";+}++:is(.chat-markdown, .composer-tiptap) ul ul {list-style-type: circle;}-.chat-markdown ul ul ul {+:is(.chat-markdown, .composer-tiptap) ul ul ul {list-style-type: square;}@@ -1870,12 +1878,30 @@ code {background-size: 4px 2px;}-.chat-markdown blockquote {+:is(.chat-markdown, .composer-tiptap) blockquote {border-left: 2px solid var(--contrast-border);padding-left: 0.8rem;color: var(--contrast-muted-foreground);}+/* A quote in the composer is text the user is still writing; muting it reads+ as disabled in an input, so the border alone carries the quote. */+.composer-tiptap blockquote {+ margin: 0.65rem 0;+ color: var(--foreground);+}++/* Preflight already draws the 1px rule, as it does in chat; only the block+ spacing needs to match. */+.composer-tiptap hr {+ margin: 0.65rem 0;+}++/* A heading at the top of a draft should not push the first line down. */+.composer-tiptap :is(h1, h2, h3, h4, h5, h6):first-child {+ margin-top: 0;+}+.chat-markdown section[data-footnotes] {margin-top: 1.25rem;border-top: 1px solid var(--contrast-border);@@ -1939,23 +1965,23 @@ code {background: color-mix(in srgb, var(--contrast-border) 78%, transparent);}-.chat-markdown .chat-markdown-codeblock-header {+:is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock-header {color: color-mix(in srgb, var(--contrast-foreground) 72%, transparent);}-.chat-markdown .chat-markdown-codeblock pre {+:is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock pre {margin: 0;border: none;border-radius: 0;background: transparent;}-.chat-markdown .chat-markdown-codeblock[data-wrap="true"] pre {+:is(.chat-markdown, .composer-tiptap) .chat-markdown-codeblock[data-wrap="true"] pre {white-space: pre-wrap;overflow-wrap: anywhere;}-.chat-markdown .chat-markdown-shiki .shiki {+:is(.chat-markdown, .composer-tiptap) .chat-markdown-shiki .shiki {background: transparent !important;}@@ -2181,7 +2207,7 @@ code {outline: none;}-.composer-tiptap code {+.composer-tiptap :not(pre) > code {font-family: var(--font-mono);font-size: 0.92em;background: color-mix(in oklab, var(--muted-foreground) 12%, transparent);diff --git a/docs/internals/composer-editors.md b/docs/internals/composer-editors.mdindex 6ed0a8c2f7b..650564f751b 100644--- a/docs/internals/composer-editors.md+++ b/docs/internals/composer-editors.md@@ -25,3 +25,18 @@ Clipboard text must come from the Markdown serializer, not DOM text: chip labelsthe source and marker decorations are not content. Structured context records accompanythat text when available. Paste completes trailing chip delimiters and adds a leadingboundary when inserting a chip directly after text.++Block nodes (fences, lists, quotes, rules, headings) keep their exact Markdown+delimiters as node attributes, so the round trip is byte-identical and offsets+inside a delimiter clamp to the block's text like task and style markers. The+serializers write only what the grammar has: a quote holds paragraphs, a list+holds paragraphs and lists. So blocks may only form at a top-level paragraph.+Input rules check this, and Tiptap's own block chords (Mod-Shift-8, Mod-Alt-c,+and so on) are removed, because nesting a block the serializer cannot write+drops its text from the stored draft. The list grammar is the plain-mode+continuation's in [composer-list-continuation](../../apps/web/src/composer-list-continuation.ts);+keep the two in step.++Enter sends, so the fence handling in `handleKeyDown` must run before the send+handler: checked afterwards, a fence never opens and a newline inside one sends+the draft.diff --git a/docs/user/composer.md b/docs/user/composer.mdindex f4c2829019a..ba8d26fd81c 100644--- a/docs/user/composer.md+++ b/docs/user/composer.md@@ -12,6 +12,23 @@ becomes an attachment when inserting it would exceed the message limit. On ahardware keyboard, use `Cmd+Shift+V` on Apple devices or `Ctrl+Shift+V` elsewhereto keep a large paste editable in the composer instead.+## Formatting++The composer writes Markdown and shows it styled as you type. Markers such as+`**` stay in the text and show beside the styled words when your cursor is on+them. Lines starting with `- `, `1. `, `- [ ] `, `> `, `# ` or `---` become lists,+task lists, quotes, headings and rules; ` ``` ` followed by Enter opens a code+block. What you typed is what the agent receives, markers and numbering+included, and `#1234` without a space still looks up a pull request.++Enter sends. In a list or quote, **Shift+Enter** continues it, and Shift+Enter+on an empty line leaves it; **Tab** nests a list item. In a code block, Enter+starts a new line at the current indentation, **Tab** and **Shift+Tab** indent+the selected lines, and a closing ` ``` ` followed by Enter, or two blank lines+at the end, leave the block. **Backspace** at the start of a code block turns it+back into plain lines. Choose the language in a code block's corner to change+it. Very large code blocks are shown without syntax highlighting.+## Attach filesAttach up to 100 files per message. Each image can be up to 10 MiB, with at mostdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fe1e71770eb..44555640186 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -687,9 +687,24 @@ importers:'@tiptap/core':specifier: ^3.31.3version: 3.31.3(@tiptap/[email protected])+ '@tiptap/extension-blockquote':+ specifier: ^3.31.3'@tiptap/extension-code':specifier: ^3.31.3version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-code-block':+ specifier: ^3.31.3+ '@tiptap/extension-heading':+ specifier: ^3.31.3+ version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-horizontal-rule':+ specifier: ^3.31.3+ '@tiptap/extension-list':+ specifier: ^3.31.3'@tiptap/extension-task-item':specifier: ^3.31.3version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))