TypeScript
fix(web): format text typed between existing backticks as inline code (#17435)
maco7259e4f594ca
diff --git a/apps/web/src/composer-rich-text-doc.test.ts b/apps/web/src/composer-rich-text-doc.test.tsindex d60590cbbb0..0a0ae5d732f 100644--- a/apps/web/src/composer-rich-text-doc.test.ts+++ b/apps/web/src/composer-rich-text-doc.test.ts@@ -1,10 +1,10 @@-import { getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";+import { Editor, getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";import StarterKit from "@tiptap/starter-kit";import { TaskList } from "@tiptap/extension-task-list";import { Node as ProseMirrorNode } from "@tiptap/pm/model";import { EditorState, TextSelection } from "@tiptap/pm/state";import { splitBlockKeepMarks } from "@tiptap/pm/commands";-import { describe, expect, it } from "vite-plus/test";+import { describe, expect, it, onTestFinished } from "vite-plus/test";import { collapseExpandedComposerCursor, pastedPathQueryLength } from "./composer-logic";@@ -1156,3 +1156,122 @@ describe("caret stops at styled edges", () => {expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);});});++describe("inline code entry", () => {+ function editorFor(block = "paragraph", mark?: string) {+ const editor = new Editor({+ element: null,+ extensions: [+ StarterKit.configure({ code: false, codeBlock: false, trailingNode: false }),+ ComposerCodeExtension,+ ComposerCodeBlockExtension,+ stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),+ ],+ content: { type: "doc", content: [{ type: block }] },+ });+ // Unmounted editors need the same plugins that Tiptap installs on mount.+ editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));+ if (mark) editor.commands.setMark(mark);+ onTestFinished(() => editor.destroy());+ return editor;+ }++ function type(editor: Editor, text: string) {+ for (const ch of text) {+ const { from, to } = editor.state.selection;+ const insert = () => editor.state.tr.insertText(ch, from, to);+ const handled = editor.state.plugins.some((plugin) =>+ plugin.props.handleTextInput?.call(plugin, editor.view, from, to, ch, insert),+ );+ if (!handled) editor.view.dispatch(insert());+ }+ }++ it.each(["", "prefix ", "@README.md"])(+ "formats a filled pair after %j, leaves following text plain, and keeps the normal input rule",+ (prefix) => {+ const editor = editorFor();+ if (prefix === "@README.md") {+ editor.commands.insertContent({+ type: "composer-mention",+ attrs: { path: "README.md", source: prefix },+ });+ } else {+ type(editor, prefix);+ }+ const offset = editor.state.selection.from - 1;+ type(editor, "``");+ editor.commands.setTextSelection(offset + 2);+ type(editor, "hello world");+ expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);+ expect(editor.state.doc.firstChild?.lastChild?.marks).toEqual([]);++ editor.commands.setTextSelection(offset + 14);+ expect(editor.state.doc.textContent).toBe(+ `${prefix === "@README.md" ? "" : prefix}hello world`,+ );+ expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);+ type(editor, " next `typed`");+ expect(serializeEditorDoc(editor.state.doc).value).toBe(+ `${prefix}\`hello world\` next \`typed\``,+ );+ const formatted = editor.state.doc.toJSON();+ let undos = 0;+ while (editor.commands.undo()) undos += 1;+ expect(undos).toBeGreaterThan(0);+ expect(serializeEditorDoc(editor.state.doc).value).toBe("");+ for (let i = 0; i < undos; i += 1) expect(editor.commands.redo()).toBe(true);+ expect(editor.state.doc.toJSON()).toEqual(formatted);+ },+ );++ it("keeps composition edits literal until the caret leaves the typed pair", () => {+ const editor = editorFor();+ type(editor, "``");+ editor.commands.setTextSelection(2);+ editor.view.dispatch(editor.state.tr.insertText("世").setMeta("composition", 1));+ editor.view.dispatch(editor.state.tr.insertText("世界", 2, 3).setMeta("composition", 1));+ expect(editor.state.doc.textContent).toBe("`世界`");+ expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]);+ editor.commands.setTextSelection(5);+ expect(editor.state.doc.textContent).toBe("世界");+ expect(serializeEditorDoc(editor.state.doc).value).toBe("`世界`");+ });++ it.each(["paste", "setContent"])("keeps a %s pair literal after moving through it", (source) => {+ const editor = editorFor();+ const literal = "`literal`";+ if (source === "paste") {+ editor.view.dispatch(editor.state.tr.insertText(literal).setMeta("uiEvent", "paste"));+ } else {+ type(editor, "``");+ editor.commands.setContent({+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: literal }] }],+ });+ }+ const before = editor.state.doc.toJSON();+ editor.commands.setTextSelection(2);+ editor.commands.setTextSelection(literal.length + 1);+ expect(editor.state.doc.toJSON()).toEqual(before);+ });++ it.each([+ { name: "doubled delimiters", delimiters: "````", caret: 3 },+ { name: "doubled closing delimiters", delimiters: "```", caret: 2 },+ { name: "bold text", delimiters: "``", caret: 2, mark: "bold" },+ { name: "existing inline code", delimiters: "``", caret: 2, mark: "code" },+ { name: "a code block", delimiters: "``", caret: 2, block: "codeBlock" },+ ])("leaves $name unchanged on caret movement", ({ delimiters, caret, mark, block }) => {+ const editor = editorFor(block, mark);+ type(editor, delimiters);+ editor.commands.setTextSelection(caret);+ type(editor, "literal");+ const before = editor.state.doc.toJSON();+ // Visit both the gap between closing ticks and the end of the pair.+ editor.commands.setTextSelection(caret + "literal".length + 1);+ expect(editor.state.doc.toJSON()).toEqual(before);+ editor.commands.setTextSelection(editor.state.doc.content.size - 1);+ expect(editor.state.doc.toJSON()).toEqual(before);+ });+});diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.tsindex 4c365c3afcd..2c71de4a150 100644--- a/apps/web/src/composer-rich-text-doc.ts+++ b/apps/web/src/composer-rich-text-doc.ts@@ -1,5 +1,11 @@import { joinBackward, joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands";-import { Fragment, Mark, type Node as ProseMirrorNode, type ResolvedPos } from "@tiptap/pm/model";+import {+ Fragment,+ Mark,+ type MarkType,+ 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";@@ -12,6 +18,7 @@ import { TaskList } from "@tiptap/extension-task-list";import {type EditorState,Plugin,+ PluginKey,Selection,TextSelection,type Transaction,@@ -40,6 +47,71 @@ const TIPTAP_TO_MARK: Record<string, RichTextMark> = {code: "code",};+type CodePair = { from: number; to: number };++const codePairKey = new PluginKey<CodePair[]>("typedBacktickPairs");++// Input rules only see text before the caret, so filling an already typed+// pair needs a separate exit handler. Only typed pairs opt into that handler.+function codePairCaretPlugin(type: MarkType) {+ return new Plugin<CodePair[]>({+ key: codePairKey,+ state: {+ init: () => [],+ apply(tr, pairs) {+ const mapped = pairs.flatMap((pair) => {+ const from = tr.mapping.mapResult(pair.from, 1);+ const to = tr.mapping.mapResult(pair.to, -1);+ return from.deleted || to.deleted ? [] : [{ from: from.pos, to: to.pos }];+ });+ const typed = tr.getMeta(codePairKey) as CodePair | undefined;+ return typed ? [...mapped, typed] : mapped;+ },+ },+ props: {+ handleTextInput(view, from, to, text, insert) {+ if (view.composing || from !== to || text !== "`") return false;+ const $from = view.state.doc.resolve(from);+ if (+ !$from.parent.isTextblock ||+ $from.parent.type.spec.code ||+ !/(^|[^`])`$/.test($from.nodeBefore?.text ?? "")+ ) {+ return false;+ }+ view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 }));+ return true;+ },+ },+ appendTransaction(transactions, oldState, state) {+ if (!state.selection.empty || oldState.selection.from === state.selection.from) return null;+ if (transactions.some((tr) => tr.docChanged)) return null;+ const pair = codePairKey.getState(state)?.find(({ to }) => to === state.selection.from);+ if (!pair) return null;+ const $start = state.doc.resolve(pair.from);+ const $end = state.selection.$from;+ if (!$start.sameParent($end) || $start.parent.type.spec.code) return null;+ if (+ $start.nodeBefore?.text?.endsWith("`") ||+ $end.nodeAfter?.text?.startsWith("`") ||+ !/^`[^`]+`$/.test(state.doc.textBetween(pair.from, pair.to))+ ) {+ return null;+ }+ let plain = true;+ state.doc.nodesBetween(pair.from, pair.to, (node) => {+ if (node.isInline && (!node.isText || node.marks.length > 0)) plain = false;+ });+ if (!plain) return null;+ const tr = state.tr.delete(pair.to - 1, pair.to).delete(pair.from, pair.from + 1);+ tr.addMark(pair.from, pair.to - 2, type.create());+ tr.setSelection(TextSelection.create(tr.doc, pair.to - 2));+ tr.removeStoredMark(type);+ return tr;+ },+ });+}+/*** Tiptap's code mark excludes every other mark, which rejects the `bold+code`* spans markdown like `**\`x\`**` parses into and drops the whole insert.@@ -49,6 +121,9 @@ export const ComposerCodeExtension = Code.extend({// ArrowRight leaves code through the caret stops at styled edges, so the// stock exit (inserting a space at the end of a line) is not needed.exitable: false,+ addProseMirrorPlugins() {+ return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];+ },});/**