Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composer-block-shortcuts.test.ts

425 lines16.6 KB

1import { Editor, Extension, InputRule, type Extensions } from "@tiptap/core";
2import { closeHistory, redo, undo } from "@tiptap/pm/history";
3import { splitBlock } from "@tiptap/pm/commands";
4import { TextSelection } from "@tiptap/pm/state";
5import StarterKit from "@tiptap/starter-kit";
6import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
7​
8import {
9 buildDocJson,
10 ComposerBlockExtensions,
11 ComposerCodeBlockExtension,
12 ComposerListExtensions,
13 ComposerTaskItemExtension,
14 ComposerTaskListExtension,
15 serializeEditorDoc,
16} from "./composer-rich-text-doc";
17​
18const mac = typeof navigator !== "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
19​
20function chord(spec: string) {
21 const parts = spec.split("-");
22 const key = parts.pop()!;
23 const has = (name: string) => parts.includes(name);
24 const base = key.length === 1 ? key.toUpperCase() : key;
25 return {
26 key: has("Shift") && /^\d$/.test(key) ? "!@#$%^&*("[Number(key) - 1]! : key,
27 keyCode: base.length === 1 ? base.charCodeAt(0) : 0,
28 shiftKey: has("Shift"),
29 altKey: has("Alt"),
30 metaKey: has("Mod") && mac,
31 ctrlKey: has("Mod") && !mac,
32 preventDefault() {},
33 stopPropagation() {},
34 } as unknown as KeyboardEvent;
36​
37function createEditor(value: string, extra: Extensions = []) {
38 const editor = new Editor({
39 extensions: [
40 StarterKit.configure({
41 blockquote: false,
42 bulletList: false,
43 codeBlock: false,
44 heading: false,
45 horizontalRule: false,
46 listItem: false,
47 orderedList: false,
48 trailingNode: false,
49 listKeymap: false,
50 }),
51 ComposerCodeBlockExtension,
52 ...ComposerBlockExtensions,
53 ...ComposerListExtensions,
54 ComposerTaskListExtension,
55 ComposerTaskItemExtension,
56 ...extra,
57 ],
58 content: buildDocJson(value, (name) => ({ label: name, description: null })),
59 });
60 // Headless editors need the plugins installed explicitly because there is no mounted view.
61 editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
62 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
63 onTestFinished(() => editor.destroy());
64 return editor;
66​
67function expectViewMatchesMarkdown(editor: Editor) {
68 const markdown = serializeEditorDoc(editor.state.doc).value;
69 const rebuilt = editor.schema.nodeFromJSON(
70 buildDocJson(markdown, (name) => ({ label: name, description: null })),
71 );
72 expect(editor.state.doc.toString()).toBe(rebuilt.toString());
74​
75function press(value: string, spec: string, caret?: number) {
76 const editor = createEditor(value);
77 if (caret !== undefined) {
78 editor.view.dispatch(
79 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, caret)),
80 );
81 }
82 const event = chord(spec);
83 const before = editor.state.doc;
84 const handled = editor.extensionManager.plugins.some((plugin) =>
85 plugin.props.handleKeyDown?.call(plugin, editor.view, event),
86 );
87 return {
88 handled,
89 changed: !editor.state.doc.eq(before),
90 value: serializeEditorDoc(editor.state.doc).value,
91 };
93​
94const BLOCK_CHORDS = [
95 "Mod-Shift-8",
96 "Mod-Shift-7",
97 "Mod-Shift-9",
98 "Mod-Shift-b",
99 "Mod-Alt-c",
100 "Mod-Alt-1",
101 "Mod-Alt-3",
102];
103​
104describe("Tiptap's block shortcuts", () => {
105 it.each(BLOCK_CHORDS)("leave a quote's text alone on %s", (spec) => {
106 expect(press("> keep this text", spec).value).toBe("> keep this text");
107 });
108​
109 it.each([
110 ["- p\n- a", "Tab"],
111 ["- p\n - a", "Shift-Tab"],
112 ["- [ ] p\n- [ ] a", "Tab"],
113 ["- [ ] p\n - [ ] a", "Shift-Tab"],
114 ])("leave the nesting of %j alone on %s", (value, spec) => {
115 const result = press(value, spec);
116 expect(result.changed).toBe(false);
117 expect(result.value).toBe(value);
118 });
119});
120​
121describe("modified Backspace in a list", () => {
122 it.each(["1. a\n2. ", "- a\n- ", "- [ ] a\n- [ ] "])(
123 "Mod-Backspace removes the empty last item of %j",
124 (value) => {
125 expect(press(value, "Mod-Backspace").value).toBe(value.split("\n")[0]);
126 },
127 );
128​
129 it("leaves an item with text before the caret to the browser", () => {
130 expect(press("1. a\n2. b", "Mod-Backspace").handled).toBe(false);
131 });
132​
133 it("joins a line after a numbered list into its last item, like Backspace", () => {
134 // Position 8 is the start of "b", below the list.
135 expect(press("1. a\n\nb", "Backspace", 8).value).toBe("1. ab");
136 expect(press("1. a\n\nb", "Mod-Backspace", 8).value).toBe("1. ab");
137 });
138});
139​
140describe("modified Delete in a list", () => {
141 // Position 4 is the end of the first item's text.
142 it.each([
143 ["1. a\n2. b", "1. ab"],
144 ["- a\n- b", "- ab"],
145 ["- [ ] a\n- [ ] b", "- [ ] ab"],
146 ])("Mod-Delete joins the next item of %j like Delete does", (value, joined) => {
147 expect(press(value, "Delete", 4).value).toBe(joined);
148 expect(press(value, "Mod-Delete", 4).value).toBe(joined);
149 });
150​
151 it("leaves Mod-Delete outside lists to the default, which removes a following rule", () => {
152 expect(press("a\n---\n```\nb\n```", "Mod-Delete", 2).value).toBe("a\n```\nb\n```");
153 });
154});
155​
156describe("composer list normalization", () => {
157 it("converts a dash edited on an earlier line and keeps the view equal to Markdown", () => {
158 const editor = createEditor("");
159 editor.view.dispatch(editor.state.tr.insertText("-get md"));
160 splitBlock(editor.state, editor.view.dispatch);
161 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2)));
162 editor.view.dispatch(editor.state.tr.insertText(" "));
163 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
164​
165 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
166 expect(editor.state.doc.firstChild?.firstChild?.textContent).toBe("get md");
167 expect(serializeEditorDoc(editor.state.doc).value).toBe("- get md\n");
168 expectViewMatchesMarkdown(editor);
169 });
170​
171 it.each([
172 ["- a\nb\n- c", "- "],
173 ["* a\nb", "* "],
174 ["1. a\nb", "2. "],
175 ["- [ ] a\nb", "- [ ] "],
176 ])("joins the converted line into the neighbouring list in %j", (value, marker) => {
177 const editor = createEditor(value);
178 let paragraph = 0;
179 editor.state.doc.forEach((node, pos) => {
180 if (node.type.name === "paragraph") paragraph = pos + 1;
181 });
182 editor.view.dispatch(editor.state.tr.insertText(marker, paragraph));
183 expect(editor.state.doc.childCount).toBe(1);
184 expectViewMatchesMarkdown(editor);
185 });
186​
187 it("keeps a converted line apart from a list with another marker", () => {
188 const editor = createEditor("* a\nb");
189 editor.view.dispatch(
190 editor.state.tr.insertText("- ", editor.state.doc.firstChild!.nodeSize + 1),
191 );
192 expect(editor.state.doc.childCount).toBe(2);
193 expectViewMatchesMarkdown(editor);
194 });
195​
196 it.each(["[link](url)", "[ordinary text]", "[x]text"])(
197 "converts a dash before existing bracket-prefixed text %j",
198 (text) => {
199 const editor = createEditor(text);
200 editor.view.dispatch(editor.state.tr.insertText("- ", 1));
201 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
202 expect(editor.state.doc.firstChild?.firstChild?.textContent).toBe(text);
203 expect(serializeEditorDoc(editor.state.doc).value).toBe(`- ${text}`);
204 },
205 );
206​
207 it.each(["- ", "* ", "+ ", "3) ", "4. ", "- [ ] ", "- [x] "])(
208 "converts %j inserted in front of existing text",
209 (marker) => {
210 const editor = createEditor("existing text");
211 editor.view.dispatch(editor.state.tr.insertText(marker, 1));
212 const list = editor.state.doc.firstChild!;
213 expect(list.type.name).toBe(
214 marker.includes("[") ? "taskList" : /^\d/.test(marker) ? "orderedList" : "bulletList",
215 );
216 expect(list.firstChild?.textContent).toBe("existing text");
217 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${marker}existing text`);
218 },
219 );
220​
221 it.each(["a - b", "-x", "-"])("leaves %j as a paragraph", (text) => {
222 const editor = createEditor("");
223 editor.view.dispatch(editor.state.tr.insertText(text));
224 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
225 expect(editor.state.doc.textContent).toBe(text);
226 });
227​
228 it("undoes the insertion and conversion together and can redo them", () => {
229 const editor = createEditor("existing text");
230 editor.view.dispatch(closeHistory(editor.state.tr).insertText("- ", 1));
231 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
232 expect(undo(editor.state, editor.view.dispatch)).toBe(true);
233 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
234 expect(editor.state.doc.textContent).toBe("existing text");
235 expect(redo(editor.state, editor.view.dispatch)).toBe(true);
236 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
237 });
238​
239 it("keeps the dash gesture available until a task marker is complete", () => {
240 const editor = createEditor("");
241 for (const ch of "- [x]") {
242 editor.view.dispatch(editor.state.tr.insertText(ch));
243 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
244 }
245 editor.view.dispatch(editor.state.tr.insertText(" "));
246 expect(editor.state.doc.firstChild?.type.name).toBe("taskList");
247 expect(editor.state.doc.firstChild?.firstChild?.attrs.checked).toBe(true);
248 });
249​
250 it.each(["```\ncode\n```", "- outer\n - inner", "> quoted"])(
251 "does not convert paragraphs inside %j",
252 (value) => {
253 const editor = createEditor(value);
254 let position = 0;
255 editor.state.doc.descendants((node, pos) => {
256 if (node.isText) position = pos;
257 });
258 const before: string[] = [];
259 editor.state.doc.descendants((node) => {
260 before.push(node.type.name);
261 });
262 editor.view.dispatch(editor.state.tr.insertText("- ", position));
263 const after: string[] = [];
264 editor.state.doc.descendants((node) => {
265 after.push(node.type.name);
266 });
267 expect(after).toEqual(before);
268 expect(editor.state.doc.textContent).toContain("- ");
269 },
270 );
271​
272 it("waits for a non-composition transaction before changing paragraph structure", () => {
273 const editor = createEditor("");
274 editor.view.dispatch(editor.state.tr.insertText("- text").setMeta("composition", 1));
275 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
276 editor.view.dispatch(editor.state.tr.insertText("日本語", 3, 7).setMeta("composition", 1));
277 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
278 editor.view.dispatch(editor.state.tr.insertText("確定", 3, 6).setMeta("composition", 1));
279 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
280 vi.useFakeTimers();
281 onTestFinished(() => {
282 vi.useRealTimers();
283 });
284 for (const plugin of editor.state.plugins) {
285 plugin.props.handleDOMEvents?.compositionend?.call(
286 plugin,
287 editor.view,
288 new Event("compositionend") as CompositionEvent,
289 );
290 }
291 vi.runAllTimers();
292 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
293 expect(serializeEditorDoc(editor.state.doc).value).toBe("- 確定");
294 expect(undo(editor.state, editor.view.dispatch)).toBe(true);
295 expect(editor.state.doc.textContent).toBe("");
296 expect(redo(editor.state, editor.view.dispatch)).toBe(true);
297 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
298 });
299​
300 it("does not immediately reconvert a literal marker restored by undo", () => {
301 const editor = createEditor("");
302 editor.view.dispatch(editor.state.tr.insertText("- "));
303 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
304 editor.view.dispatch(closeHistory(editor.state.tr).insertText("text"));
305 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
306 expect(undo(editor.state, editor.view.dispatch)).toBe(true);
307 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
308 expect(editor.state.doc.textContent).toBe("- ");
309 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atStart(editor.state.doc)));
310 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
311 });
312​
313 it("keeps the literal marker that Backspace restores from a list input rule", () => {
314 // Mirrors the composer's `- ` + first character rule; the test editor keeps Tiptap's `- ` rule.
315 const dashRule = Extension.create({
316 name: "dashRule",
317 addInputRules() {
318 return [
319 new InputRule({
320 find: /^- (?<carried>\S)$/,
321 handler: ({ range, match, chain }) => {
322 chain()
323 .deleteRange(range)
324 .wrapInList("bulletList")
325 .command(({ tr }) => {
326 tr.insertText(match.groups?.carried ?? "");
327 return true;
328 })
329 .run();
330 },
331 }),
332 ];
333 },
334 });
335 const editor = createEditor("", [dashRule]);
336 const type = (text: string) => {
337 const { from, to } = editor.state.selection;
338 const insert = () => editor.state.tr.insertText(text, from, to);
339 const handled = editor.state.plugins.some((plugin) =>
340 plugin.props.handleTextInput?.call(plugin, editor.view, from, to, text, insert),
341 );
342 if (!handled) editor.view.dispatch(editor.state.tr.insertText(text, from, to));
343 };
344 editor.view.dispatch(editor.state.tr.insertText("- "));
345 type("g");
346 expect(editor.state.doc.firstChild?.type.name).toBe("bulletList");
347 const backspace = chord("Backspace");
348 expect(
349 editor.state.plugins.some((plugin) =>
350 plugin.props.handleKeyDown?.call(plugin, editor.view, backspace),
351 ),
352 ).toBe(true);
353 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
354 expect(editor.state.doc.textContent).toBe("- g");
355 type("o");
356 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
357 expect(editor.state.doc.textContent).toBe("- go");
358 });
359​
360 it.each([
361 ["+ ", "bulletList"],
362 ["* ", "bulletList"],
363 ["1. ", "orderedList"],
364 ])("keeps the typed %j when Backspace follows its list shortcut", (marker, list) => {
365 const editor = createEditor("");
366 for (const char of marker) {
367 const { from, to } = editor.state.selection;
368 const insert = () => editor.state.tr.insertText(char, from, to);
369 const handled = editor.state.plugins.some((plugin) =>
370 plugin.props.handleTextInput?.call(plugin, editor.view, from, to, char, insert),
371 );
372 if (!handled) editor.view.dispatch(editor.state.tr.insertText(char, from, to));
373 }
374 expect(editor.state.doc.firstChild?.type.name).toBe(list);
375 const backspace = chord("Backspace");
376 expect(
377 editor.state.plugins.some((plugin) =>
378 plugin.props.handleKeyDown?.call(plugin, editor.view, backspace),
379 ),
380 ).toBe(true);
381 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
382 expect(editor.state.doc.textContent).toBe(marker);
383 });
384​
385 it("preserves formatting and the caret when removing the literal prefix", () => {
386 const editor = createEditor("**text**");
387 editor.view.dispatch(editor.state.tr.insert(1, editor.schema.text("- ")));
388 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
389 expect(editor.state.selection.$from.parentOffset).toBe(4);
390 expect(serializeEditorDoc(editor.state.doc).value).toBe("- **text**");
391 });
392​
393 it("does not turn an inline code marker into a list", () => {
394 const editor = createEditor("`-text`");
395 editor.view.dispatch(editor.state.tr.insertText(" ", 2));
396 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
397 expect(serializeEditorDoc(editor.state.doc).value).toBe("`- text`");
398 });
399​
400 it.each(["**- x**", "*-* x", "~~- x~~", "a\n**1.** b"])(
401 "preserves styled markers when restoring %j",
402 (value) => {
403 const editor = createEditor("");
404 editor.commands.setContent(
405 buildDocJson(value, (name) => ({ label: name, description: null })),
406 { emitUpdate: false },
407 );
408 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
409 expect(editor.state.doc.lastChild?.type.name).toBe("paragraph");
410 editor.view.dispatch(editor.state.tr.insertText("x", editor.state.doc.content.size - 1));
411 expect(editor.state.doc.lastChild?.type.name).toBe("paragraph");
412 },
413 );
414​
415 it("only normalizes changed blocks", () => {
416 const editor = createEditor("");
417 editor.view.updateState(editor.state.reconfigure({ plugins: [] }));
418 editor.view.dispatch(editor.state.tr.insertText("- untouched"));
419 splitBlock(editor.state, editor.view.dispatch);
420 editor.view.updateState(editor.state.reconfigure({ plugins: editor.extensionManager.plugins }));
421 editor.view.dispatch(editor.state.tr.insertText("changed"));
422 expect(editor.state.doc.firstChild?.type.name).toBe("paragraph");
423 expect(editor.state.doc.firstChild?.textContent).toBe("- untouched");
424 });
425});