Skip to content

Commit 7259e4f

Browse files
fix(web): format text typed between existing backticks as inline code (pingdotgg#17435)
Co-authored-by: macodev00 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent fa68107 commit 7259e4f

2 files changed

Lines changed: 197 additions & 3 deletions

File tree

‎apps/web/src/composer-rich-text-doc.test.ts‎

Lines changed: 121 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";
1+
import { Editor, getSchemaByResolvedExtensions, Node, resolveExtensions } from "@tiptap/core";
22
import StarterKit from "@tiptap/starter-kit";
33
import { TaskList } from "@tiptap/extension-task-list";
44
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
55
import { EditorState, TextSelection } from "@tiptap/pm/state";
66
import { splitBlockKeepMarks } from "@tiptap/pm/commands";
7-
import { describe, expect, it } from "vite-plus/test";
7+
import { describe, expect, it, onTestFinished } from "vite-plus/test";
88

99
import { collapseExpandedComposerCursor, pastedPathQueryLength } from "./composer-logic";
1010

@@ -1156,3 +1156,122 @@ describe("caret stops at styled edges", () => {
11561156
expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);
11571157
});
11581158
});
1159+
1160+
describe("inline code entry", () => {
1161+
function editorFor(block = "paragraph", mark?: string) {
1162+
const editor = new Editor({
1163+
element: null,
1164+
extensions: [
1165+
StarterKit.configure({ code: false, codeBlock: false, trailingNode: false }),
1166+
ComposerCodeExtension,
1167+
ComposerCodeBlockExtension,
1168+
stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }),
1169+
],
1170+
content: { type: "doc", content: [{ type: block }] },
1171+
});
1172+
// Unmounted editors need the same plugins that Tiptap installs on mount.
1173+
editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
1174+
if (mark) editor.commands.setMark(mark);
1175+
onTestFinished(() => editor.destroy());
1176+
return editor;
1177+
}
1178+
1179+
function type(editor: Editor, text: string) {
1180+
for (const ch of text) {
1181+
const { from, to } = editor.state.selection;
1182+
const insert = () => editor.state.tr.insertText(ch, from, to);
1183+
const handled = editor.state.plugins.some((plugin) =>
1184+
plugin.props.handleTextInput?.call(plugin, editor.view, from, to, ch, insert),
1185+
);
1186+
if (!handled) editor.view.dispatch(insert());
1187+
}
1188+
}
1189+
1190+
it.each(["", "prefix ", "@README.md"])(
1191+
"formats a filled pair after %j, leaves following text plain, and keeps the normal input rule",
1192+
(prefix) => {
1193+
const editor = editorFor();
1194+
if (prefix === "@README.md") {
1195+
editor.commands.insertContent({
1196+
type: "composer-mention",
1197+
attrs: { path: "README.md", source: prefix },
1198+
});
1199+
} else {
1200+
type(editor, prefix);
1201+
}
1202+
const offset = editor.state.selection.from - 1;
1203+
type(editor, "``");
1204+
editor.commands.setTextSelection(offset + 2);
1205+
type(editor, "hello world");
1206+
expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);
1207+
expect(editor.state.doc.firstChild?.lastChild?.marks).toEqual([]);
1208+
1209+
editor.commands.setTextSelection(offset + 14);
1210+
expect(editor.state.doc.textContent).toBe(
1211+
`${prefix === "@README.md" ? "" : prefix}hello world`,
1212+
);
1213+
expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`hello world\``);
1214+
type(editor, " next `typed`");
1215+
expect(serializeEditorDoc(editor.state.doc).value).toBe(
1216+
`${prefix}\`hello world\` next \`typed\``,
1217+
);
1218+
const formatted = editor.state.doc.toJSON();
1219+
let undos = 0;
1220+
while (editor.commands.undo()) undos += 1;
1221+
expect(undos).toBeGreaterThan(0);
1222+
expect(serializeEditorDoc(editor.state.doc).value).toBe("");
1223+
for (let i = 0; i < undos; i += 1) expect(editor.commands.redo()).toBe(true);
1224+
expect(editor.state.doc.toJSON()).toEqual(formatted);
1225+
},
1226+
);
1227+
1228+
it("keeps composition edits literal until the caret leaves the typed pair", () => {
1229+
const editor = editorFor();
1230+
type(editor, "``");
1231+
editor.commands.setTextSelection(2);
1232+
editor.view.dispatch(editor.state.tr.insertText("世").setMeta("composition", 1));
1233+
editor.view.dispatch(editor.state.tr.insertText("世界", 2, 3).setMeta("composition", 1));
1234+
expect(editor.state.doc.textContent).toBe("`世界`");
1235+
expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]);
1236+
editor.commands.setTextSelection(5);
1237+
expect(editor.state.doc.textContent).toBe("世界");
1238+
expect(serializeEditorDoc(editor.state.doc).value).toBe("`世界`");
1239+
});
1240+
1241+
it.each(["paste", "setContent"])("keeps a %s pair literal after moving through it", (source) => {
1242+
const editor = editorFor();
1243+
const literal = "`literal`";
1244+
if (source === "paste") {
1245+
editor.view.dispatch(editor.state.tr.insertText(literal).setMeta("uiEvent", "paste"));
1246+
} else {
1247+
type(editor, "``");
1248+
editor.commands.setContent({
1249+
type: "doc",
1250+
content: [{ type: "paragraph", content: [{ type: "text", text: literal }] }],
1251+
});
1252+
}
1253+
const before = editor.state.doc.toJSON();
1254+
editor.commands.setTextSelection(2);
1255+
editor.commands.setTextSelection(literal.length + 1);
1256+
expect(editor.state.doc.toJSON()).toEqual(before);
1257+
});
1258+
1259+
it.each([
1260+
{ name: "doubled delimiters", delimiters: "````", caret: 3 },
1261+
{ name: "doubled closing delimiters", delimiters: "```", caret: 2 },
1262+
{ name: "bold text", delimiters: "``", caret: 2, mark: "bold" },
1263+
{ name: "existing inline code", delimiters: "``", caret: 2, mark: "code" },
1264+
{ name: "a code block", delimiters: "``", caret: 2, block: "codeBlock" },
1265+
])("leaves $name unchanged on caret movement", ({ delimiters, caret, mark, block }) => {
1266+
const editor = editorFor(block, mark);
1267+
type(editor, delimiters);
1268+
editor.commands.setTextSelection(caret);
1269+
type(editor, "literal");
1270+
const before = editor.state.doc.toJSON();
1271+
// Visit both the gap between closing ticks and the end of the pair.
1272+
editor.commands.setTextSelection(caret + "literal".length + 1);
1273+
expect(editor.state.doc.toJSON()).toEqual(before);
1274+
editor.commands.setTextSelection(editor.state.doc.content.size - 1);
1275+
expect(editor.state.doc.toJSON()).toEqual(before);
1276+
});
1277+
});

‎apps/web/src/composer-rich-text-doc.ts‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { joinBackward, joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands";
2-
import { Fragment, Mark, type Node as ProseMirrorNode, type ResolvedPos } from "@tiptap/pm/model";
2+
import {
3+
Fragment,
4+
Mark,
5+
type MarkType,
6+
type Node as ProseMirrorNode,
7+
type ResolvedPos,
8+
} from "@tiptap/pm/model";
39
import { Code } from "@tiptap/extension-code";
410
import { Blockquote } from "@tiptap/extension-blockquote";
511
import { CodeBlock } from "@tiptap/extension-code-block";
@@ -12,6 +18,7 @@ import { TaskList } from "@tiptap/extension-task-list";
1218
import {
1319
type EditorState,
1420
Plugin,
21+
PluginKey,
1522
Selection,
1623
TextSelection,
1724
type Transaction,
@@ -40,6 +47,71 @@ const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
4047
code: "code",
4148
};
4249

50+
type CodePair = { from: number; to: number };
51+
52+
const codePairKey = new PluginKey<CodePair[]>("typedBacktickPairs");
53+
54+
// Input rules only see text before the caret, so filling an already typed
55+
// pair needs a separate exit handler. Only typed pairs opt into that handler.
56+
function codePairCaretPlugin(type: MarkType) {
57+
return new Plugin<CodePair[]>({
58+
key: codePairKey,
59+
state: {
60+
init: () => [],
61+
apply(tr, pairs) {
62+
const mapped = pairs.flatMap((pair) => {
63+
const from = tr.mapping.mapResult(pair.from, 1);
64+
const to = tr.mapping.mapResult(pair.to, -1);
65+
return from.deleted || to.deleted ? [] : [{ from: from.pos, to: to.pos }];
66+
});
67+
const typed = tr.getMeta(codePairKey) as CodePair | undefined;
68+
return typed ? [...mapped, typed] : mapped;
69+
},
70+
},
71+
props: {
72+
handleTextInput(view, from, to, text, insert) {
73+
if (view.composing || from !== to || text !== "`") return false;
74+
const $from = view.state.doc.resolve(from);
75+
if (
76+
!$from.parent.isTextblock ||
77+
$from.parent.type.spec.code ||
78+
!/(^|[^`])`$/.test($from.nodeBefore?.text ?? "")
79+
) {
80+
return false;
81+
}
82+
view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 }));
83+
return true;
84+
},
85+
},
86+
appendTransaction(transactions, oldState, state) {
87+
if (!state.selection.empty || oldState.selection.from === state.selection.from) return null;
88+
if (transactions.some((tr) => tr.docChanged)) return null;
89+
const pair = codePairKey.getState(state)?.find(({ to }) => to === state.selection.from);
90+
if (!pair) return null;
91+
const $start = state.doc.resolve(pair.from);
92+
const $end = state.selection.$from;
93+
if (!$start.sameParent($end) || $start.parent.type.spec.code) return null;
94+
if (
95+
$start.nodeBefore?.text?.endsWith("`") ||
96+
$end.nodeAfter?.text?.startsWith("`") ||
97+
!/^`[^`]+`$/.test(state.doc.textBetween(pair.from, pair.to))
98+
) {
99+
return null;
100+
}
101+
let plain = true;
102+
state.doc.nodesBetween(pair.from, pair.to, (node) => {
103+
if (node.isInline && (!node.isText || node.marks.length > 0)) plain = false;
104+
});
105+
if (!plain) return null;
106+
const tr = state.tr.delete(pair.to - 1, pair.to).delete(pair.from, pair.from + 1);
107+
tr.addMark(pair.from, pair.to - 2, type.create());
108+
tr.setSelection(TextSelection.create(tr.doc, pair.to - 2));
109+
tr.removeStoredMark(type);
110+
return tr;
111+
},
112+
});
113+
}
114+
43115
/**
44116
* Tiptap's code mark excludes every other mark, which rejects the `bold+code`
45117
* spans markdown like `**\`x\`**` parses into and drops the whole insert.
@@ -49,6 +121,9 @@ export const ComposerCodeExtension = Code.extend({
49121
// ArrowRight leaves code through the caret stops at styled edges, so the
50122
// stock exit (inserting a space at the end of a line) is not needed.
51123
exitable: false,
124+
addProseMirrorPlugins() {
125+
return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];
126+
},
52127
});
53128

54129
/**

0 commit comments

Comments
 (0)