Skip to content

Commit 4ff9a32

Browse files
fix(web): format inline code typed with a dead-key backtick (#27457)
Co-authored-by: maria-rcks <[email protected]>
1 parent a4b6afe commit 4ff9a32

2 files changed

Lines changed: 131 additions & 3 deletions

File tree

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

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1089,9 +1089,19 @@ describe("inline code entry", () => {
10891089
type(editor, "`");
10901090
expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]);
10911091
expect(editor.state.doc.textContent).toBe("`beforeafter`");
1092+
1093+
const local = editorFor();
1094+
type(local, "a ` ");
1095+
local.commands.insertContent({ type: nodeType });
1096+
type(local, "`local`");
1097+
expect(local.state.doc.firstChild?.lastChild?.toJSON()).toEqual({
1098+
type: "text",
1099+
marks: [{ type: "code" }],
1100+
text: "local",
1101+
});
10921102
});
10931103

1094-
it.each(["", "prefix ", "@README.md"])(
1104+
it.each(["", "prefix ", "@README.md", "a ``` "])(
10951105
"formats a filled pair after %j, leaves following text plain, and keeps the normal input rule",
10961106
(prefix) => {
10971107
const editor = editorFor();
@@ -1129,6 +1139,48 @@ describe("inline code entry", () => {
11291139
},
11301140
);
11311141

1142+
it.each([
1143+
[
1144+
"formats a pair",
1145+
"do ",
1146+
[
1147+
{ type: "text", text: "do " },
1148+
{ type: "text", marks: [{ type: "code" }], text: "xyz" },
1149+
],
1150+
],
1151+
[
1152+
"keeps a pair literal after an unmatched backtick",
1153+
"a ` ",
1154+
[{ type: "text", text: "a ` `xyz`" }],
1155+
],
1156+
])("%s whose backticks came from a dead key", (_name, prefix, content) => {
1157+
const editor = editorFor();
1158+
type(editor, prefix);
1159+
editor.view.dispatch(editor.state.tr.insertText("`").setMeta("composition", 1));
1160+
editor.view.dispatch(editor.state.tr.insertText("`").setMeta("composition", 2));
1161+
editor.commands.setTextSelection(prefix.length + 2);
1162+
type(editor, "xyz");
1163+
expect(editor.state.doc.textContent).toBe(`${prefix}\`xyz\``);
1164+
1165+
editor.commands.setTextSelection(prefix.length + 6);
1166+
expect(editor.state.doc.firstChild?.toJSON().content).toEqual(content);
1167+
});
1168+
1169+
it("does not reuse the closing backtick of a literal pair to open code", () => {
1170+
const editor = editorFor();
1171+
editor.view.dispatch(editor.state.tr.insertText("is `enabled`", 1));
1172+
type(editor, " and `");
1173+
expect(editor.state.doc.firstChild?.toJSON().content).toEqual([
1174+
{ type: "text", text: "is `enabled` and `" },
1175+
]);
1176+
1177+
type(editor, "persist`");
1178+
expect(editor.state.doc.firstChild?.toJSON().content).toEqual([
1179+
{ type: "text", text: "is `enabled` and " },
1180+
{ type: "text", marks: [{ type: "code" }], text: "persist" },
1181+
]);
1182+
});
1183+
11321184
it("keeps composition edits literal until the caret leaves the typed pair", () => {
11331185
const editor = editorFor();
11341186
type(editor, "``");

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

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
TextSelection,
3939
type Transaction,
4040
} from "@tiptap/pm/state";
41+
import { ReplaceStep } from "@tiptap/pm/transform";
4142

4243
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
4344
import { nextOrderedMarkerText } from "~/composer-list-continuation";
@@ -80,7 +81,7 @@ function codePairCaretPlugin(type: MarkType) {
8081
const to = tr.mapping.mapResult(pair.to, -1);
8182
return from.deleted || to.deleted ? [] : [{ from: from.pos, to: to.pos }];
8283
});
83-
const typed = tr.getMeta(codePairKey) as CodePair | undefined;
84+
const typed = (tr.getMeta(codePairKey) as CodePair | undefined) ?? composedCodePair(tr);
8485
return typed ? [...mapped, typed] : mapped;
8586
},
8687
},
@@ -90,7 +91,7 @@ function codePairCaretPlugin(type: MarkType) {
9091
const $from = view.state.doc.resolve(from);
9192
if (!$from.parent.isTextblock || $from.parent.type.spec.code) return false;
9293
const before = $from.nodeBefore?.text ?? "";
93-
if (/(^|[^`])`$/.test(before)) {
94+
if (closesBacktickPair($from)) {
9495
view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 }));
9596
return true;
9697
}
@@ -151,6 +152,45 @@ function codePairCaretPlugin(type: MarkType) {
151152
});
152153
}
153154

155+
/**
156+
* Whether a backtick typed at `$pos` would complete an empty `` pair. The
157+
* backtick before `$pos` only opens one when earlier backticks are all paired.
158+
*/
159+
function closesBacktickPair($pos: ResolvedPos): boolean {
160+
return (
161+
$pos.parent.isTextblock &&
162+
!$pos.parent.type.spec.code &&
163+
/(^|[^`])`$/.test($pos.nodeBefore?.text ?? "") &&
164+
literalBackticksBefore($pos) % 2 === 1
165+
);
166+
}
167+
168+
/**
169+
* Layouts where backtick is a dead key type it through composition, and the
170+
* pair handler above skips composing input. Read the pair
171+
* from the composed insert instead; dispatching mid-composition would break it.
172+
*/
173+
function composedCodePair(tr: Transaction): CodePair | undefined {
174+
if (tr.getMeta("composition") === undefined || tr.steps.length !== 1) {
175+
return undefined;
176+
}
177+
178+
const step = tr.steps[0];
179+
if (!(step instanceof ReplaceStep) || step.from !== step.to || step.slice.size !== 1) {
180+
return undefined;
181+
}
182+
183+
if (step.slice.content.firstChild?.text !== "`") {
184+
return undefined;
185+
}
186+
187+
if (!closesBacktickPair(tr.before.resolve(step.from))) {
188+
return undefined;
189+
}
190+
191+
return { from: step.from - 1, to: step.from + 1 };
192+
}
193+
154194
/**
155195
* Tiptap's code mark excludes every other mark, which rejects the `bold+code`
156196
* spans markdown like `**\`x\`**` parses into and drops the whole insert.
@@ -168,8 +208,44 @@ export const ComposerCodeExtension = Code.extend({
168208
addProseMirrorPlugins() {
169209
return [...(this.parent?.() ?? []), codePairCaretPlugin(this.type)];
170210
},
211+
// Tiptap's rule reads back from the caret, so after a literal `enabled` the
212+
// next typed backtick would reuse its closing backtick and wrap ` and ` in
213+
// code. Backticks pair left to right, so skip an opener that closes a pair.
214+
addInputRules() {
215+
return (this.parent?.() ?? []).map(
216+
(rule) =>
217+
new InputRule({
218+
find: rule.find,
219+
undoable: rule.undoable,
220+
handler: (props) => {
221+
if (literalBackticksBefore(props.state.doc.resolve(props.range.from)) % 2 === 1) {
222+
return null;
223+
}
224+
225+
return rule.handler(props);
226+
},
227+
}),
228+
);
229+
},
171230
});
172231

232+
/** Counts backticks typed as plain text before `$pos` in its textblock; code text never pairs. */
233+
function literalBackticksBefore($pos: ResolvedPos): number {
234+
let count = 0;
235+
$pos.parent.forEach((node, offset) => {
236+
if (offset >= $pos.parentOffset) return;
237+
if (!node.isText) {
238+
count = 0;
239+
return;
240+
}
241+
if (node.marks.some((mark) => mark.type.spec.code)) return;
242+
243+
const text = node.text!.slice(0, $pos.parentOffset - offset);
244+
count += [...text.matchAll(/(?<!`)`(?!`)/g)].length;
245+
});
246+
return count;
247+
}
248+
173249
// Code permits nested emphasis, so Tiptap's exclusion check cannot protect literal delimiters.
174250
function markInputRuleOutsideCode(find: RegExp, type: MarkType) {
175251
const rule = markInputRule({ find, type });

0 commit comments

Comments
 (0)