Skip to content

Commit e5d6504

Browse files
committed
fix(web): format text typed between existing backticks as inline code
The code input rule only matches text typed in front of the caret, so a backtick pair typed before its contents stayed literal. When the caret moves onto the closing backtick, apply the code mark and drop the pair. Co-authored-by: maco <[email protected]>
1 parent 2577baf commit e5d6504

2 files changed

Lines changed: 152 additions & 2 deletions

File tree

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
buildDocJson,
1313
buildTiptapContent,
1414
caretTakesMarksBefore,
15+
codePairCaretPlugin,
1516
ComposerBlockExtensions,
1617
ComposerCodeBlockExtension,
1718
ComposerListExtensions,
@@ -1095,3 +1096,63 @@ describe("caret stops at styled edges", () => {
10951096
expect(caretTakesMarksBefore(stateAt("plain text", 1))).toBe(false);
10961097
});
10971098
});
1099+
1100+
describe("backtick pair at the caret", () => {
1101+
function withPlugin(text: string, pos: number) {
1102+
const doc = schema.node("doc", null, [
1103+
schema.node("paragraph", null, text ? [schema.text(text)] : []),
1104+
]);
1105+
return EditorState.create({
1106+
doc,
1107+
selection: TextSelection.create(doc, pos),
1108+
plugins: [codePairCaretPlugin(schema.marks.code!)],
1109+
});
1110+
}
1111+
1112+
it("formats text typed between backticks once the caret leaves the pair", () => {
1113+
let state = withPlugin("", 1);
1114+
const type = (ch: string) => {
1115+
state = state.apply(state.tr.insertText(ch));
1116+
};
1117+
type("`");
1118+
type("`");
1119+
state = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 2)));
1120+
for (const ch of "not working") type(ch);
1121+
expect(state.doc.textContent).toBe("`not working`");
1122+
state = state.apply(
1123+
state.tr.setSelection(TextSelection.create(state.doc, 1 + state.doc.textContent.length)),
1124+
);
1125+
expect(state.doc.textContent).toBe("not working");
1126+
expect(serializeEditorDoc(state.doc).value).toBe("`not working`");
1127+
state = state.apply(state.tr.insertText("x"));
1128+
expect(serializeEditorDoc(state.doc).value).toBe("`not working`x");
1129+
});
1130+
1131+
it("leaves a pasted backtick pair literal", () => {
1132+
const state = withPlugin("", 1);
1133+
const pasted = state.apply(state.tr.insertText("`not working`").setMeta("uiEvent", "paste"));
1134+
expect(pasted.doc.textContent).toBe("`not working`");
1135+
const before = pasted.apply(pasted.tr.setSelection(TextSelection.create(pasted.doc, 1)));
1136+
const moved = before.apply(
1137+
before.tr.setSelection(TextSelection.create(before.doc, 1 + before.doc.textContent.length)),
1138+
);
1139+
expect(moved.doc.textContent).toBe("`not working`");
1140+
expect(moved.doc.child(0).firstChild?.marks).toEqual([]);
1141+
});
1142+
1143+
it("does not format doubled backticks", () => {
1144+
const text = "``not working``";
1145+
const state = withPlugin(text, 1);
1146+
const moved = state.apply(
1147+
state.tr.setSelection(TextSelection.create(state.doc, 1 + text.length)),
1148+
);
1149+
expect(moved.doc.textContent).toBe(text);
1150+
});
1151+
1152+
it("does not code the prefix when the caret sits between two closing backticks", () => {
1153+
const text = "`a``";
1154+
const state = withPlugin(text, 1);
1155+
const moved = state.apply(state.tr.setSelection(TextSelection.create(state.doc, 4)));
1156+
expect(moved.doc.textContent).toBe(text);
1157+
});
1158+
});

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

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { joinBackward, joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands";
2-
import { Fragment, Mark, type Node as ProseMirrorNode, type ResolvedPos } from "@tiptap/pm/model";
3-
import { Code } from "@tiptap/extension-code";
2+
import {
3+
Fragment,
4+
Mark,
5+
type MarkType,
6+
type Node as ProseMirrorNode,
7+
type ResolvedPos,
8+
} from "@tiptap/pm/model";
9+
import { Code, inputRegexMatch } from "@tiptap/extension-code";
410
import { Blockquote } from "@tiptap/extension-blockquote";
511
import { CodeBlock } from "@tiptap/extension-code-block";
612
import { Heading } from "@tiptap/extension-heading";
@@ -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,15 +47,97 @@ const TIPTAP_TO_MARK: Record<string, RichTextMark> = {
4047
code: "code",
4148
};
4249

50+
type PastedRange = { from: number; to: number };
51+
52+
const pastedPairKey = new PluginKey<PastedRange[]>("pastedBacktickPair");
53+
54+
/** Paste insertions that contain a backtick, mapped by each later transaction. */
55+
function pastedRanges(tr: Transaction, previous: readonly PastedRange[]): PastedRange[] {
56+
const ranges = previous.flatMap((range) => {
57+
const from = tr.mapping.map(range.from, 1);
58+
const to = tr.mapping.map(range.to, -1);
59+
return from < to ? [{ from, to }] : [];
60+
});
61+
if (tr.getMeta("paste") !== true && tr.getMeta("uiEvent") !== "paste") return ranges;
62+
tr.steps.forEach((step, index) => {
63+
const after = tr.mapping.slice(index + 1);
64+
step.getMap().forEach((_from, _to, start, end) => {
65+
if (start >= end) return;
66+
const from = after.map(start, 1);
67+
const to = after.map(end, -1);
68+
if (from < to && tr.doc.textBetween(from, to).includes("`")) ranges.push({ from, to });
69+
});
70+
});
71+
return ranges;
72+
}
73+
74+
/**
75+
* Formats a finished backtick pair when the caret moves onto its closing
76+
* backtick. The code input rule only sees text typed in front of the caret,
77+
* so a pair typed before its contents stays literal until the caret leaves it.
78+
* A pair inserted by a paste stays literal through that later move.
79+
*/
80+
export function codePairCaretPlugin(type: MarkType): Plugin {
81+
return new Plugin({
82+
key: pastedPairKey,
83+
state: {
84+
init: (): PastedRange[] => [],
85+
apply: (tr, ranges) => pastedRanges(tr, ranges),
86+
},
87+
appendTransaction(transactions, oldState, state) {
88+
if (!state.selection.empty || oldState.selection.from === state.selection.from) return null;
89+
if (transactions.some((tr) => tr.docChanged)) return null;
90+
const $from = state.selection.$from;
91+
if (!$from.parent.isTextblock || $from.parent.type.spec.code) return null;
92+
let textOnly = true;
93+
$from.parent.forEach((node) => {
94+
if (!node.isText) textOnly = false;
95+
});
96+
if (!textOnly) return null;
97+
// The match is end-anchored, so a backtick after the caret is invisible
98+
// to it. At the end of the text there is no next character to read.
99+
if (
100+
$from.parentOffset < $from.parent.content.size &&
101+
$from.parent.textBetween($from.parentOffset, $from.parentOffset + 1) === "`"
102+
) {
103+
return null;
104+
}
105+
const before = $from.parent.textBetween(0, $from.parentOffset);
106+
const found = inputRegexMatch(before);
107+
const content = found?.replaceWith;
108+
if (!found || content === undefined) return null;
109+
const from = $from.start() + found.index;
110+
const to = from + found.text.length;
111+
const pasted = pastedPairKey.getState(state);
112+
if (pasted?.some((range) => range.from < to && from < range.to)) return null;
113+
let marked = false;
114+
state.doc.nodesBetween(from, to, (node) => {
115+
if (node.isText && node.marks.length > 0) marked = true;
116+
});
117+
if (marked) return null;
118+
const tr = state.tr.delete(to - 1, to).delete(from, from + 1);
119+
tr.addMark(from, from + content.length, type.create());
120+
tr.setSelection(TextSelection.create(tr.doc, from + content.length));
121+
tr.removeStoredMark(type);
122+
return tr;
123+
},
124+
});
125+
}
126+
43127
/**
44128
* Tiptap's code mark excludes every other mark, which rejects the `bold+code`
45129
* spans markdown like `**\`x\`**` parses into and drops the whole insert.
130+
* `codePairCaretPlugin` covers a pair typed around its contents, which the
131+
* stock input rule never sees.
46132
*/
47133
export const ComposerCodeExtension = Code.extend({
48134
excludes: "code",
49135
// ArrowRight leaves code through the caret stops at styled edges, so the
50136
// stock exit (inserting a space at the end of a line) is not needed.
51137
exitable: false,
138+
addProseMirrorPlugins() {
139+
return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];
140+
},
52141
});
53142

54143
/**

0 commit comments

Comments
 (0)