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

composer-code-block.test.ts

319 lines11.4 KB

1import { describe, expect, it } from "vite-plus/test";
2import { Editor, getSchema, Node } from "@tiptap/core";
3import { newlineInCode } from "@tiptap/pm/commands";
4import { history, undo } from "@tiptap/pm/history";
5import { EditorState, TextSelection, type Transaction } from "@tiptap/pm/state";
6import type { EditorView } from "@tiptap/pm/view";
7​
8import {
9 indentCodeBlock,
10 convertCodeFenceOnEnter,
11 exitCodeBlockOnClosingFence,
12 exitCodeBlockOnTrailingBlankLines,
13 indentedNewlineInCodeBlock,
14} from "./composer-code-block";
15import StarterKit from "@tiptap/starter-kit";
16​
17import {
18 ComposerCodeBlockExtension,
19 ComposerListExtensions,
20 serializeEditorDoc,
21} from "./composer-rich-text-doc";
22import {
23 COMPOSER_UNDO_GROUP_DELAY,
24 type ComposerChangeKind,
25 groupUndoByChangeKind,
26} from "./composer-undo-grouping";
27​
28const extensions = [
29 StarterKit.configure({ codeBlock: false, trailingNode: false }),
30 ComposerCodeBlockExtension,
31 ...ComposerListExtensions,
32 Node.create({
33 name: "composer-mention",
34 group: "inline",
35 inline: true,
36 atom: true,
37 addAttributes: () => ({ path: { default: "" }, source: { default: "" } }),
38 }),
39];
40​
41function codeEditor(code: string, at?: { from: number; to?: number }) {
42 const editor = new Editor({
43 extensions,
44 content: {
45 type: "doc",
46 content: [{ type: "codeBlock", content: [{ type: "text", text: code }] }],
47 },
48 });
49 const start = 1;
50 const from = start + (at?.from ?? code.length);
51 const to = start + (at?.to ?? at?.from ?? code.length);
52 editor.view.dispatch(
53 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from, to)),
54 );
55 return editor;
57​
58const textOf = (editor: Editor) => editor.state.doc.textContent;
59​
60describe("indentedNewlineInCodeBlock", () => {
61 it("carries the current indentation onto the new line", () => {
62 const editor = codeEditor("function f() {\n body()");
63 const handled = indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
64 expect(handled).toBe(true);
65 expect(textOf(editor)).toBe("function f() {\n body()\n ");
66 });
67​
68 it("indents from the line the caret is on, not the last line", () => {
69 const editor = codeEditor(" deep()\nflush()", { from: 10 });
70 indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
71 expect(textOf(editor)).toBe(" deep()\n \nflush()");
72 });
73});
74​
75function pressEnter(editor: Editor) {
76 const dispatch = (tr: Parameters<typeof editor.view.dispatch>[0]) => editor.view.dispatch(tr);
77 return (
78 exitCodeBlockOnTrailingBlankLines(editor.view) ||
79 indentedNewlineInCodeBlock(editor.state, dispatch) ||
80 newlineInCode(editor.state, dispatch)
81 );
83​
84describe("exitCodeBlockOnTrailingBlankLines", () => {
85 it("leaves the block once two blank lines end it", () => {
86 const editor = codeEditor("flush()");
87 pressEnter(editor);
88 pressEnter(editor);
89 expect(editor.state.doc.childCount).toBe(1);
90 pressEnter(editor);
91 expect(editor.state.doc.firstChild?.textContent).toBe("flush()");
92 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
93 });
94​
95 it("closes an unclosed fence on the way out", () => {
96 const editor = codeEditor("flush()");
97 editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "close", ""));
98 pressEnter(editor);
99 pressEnter(editor);
100 pressEnter(editor);
101 expect(editor.state.doc.firstChild?.attrs.close).toBe("\n```");
102 });
103​
104 it.each([
105 ["a closed", "\n```"],
106 ["an open", ""],
107 ])("reverses exiting a code block with %s fence in a single undo", (_, close) => {
108 const schema = getSchema(extensions);
109 let previous: ComposerChangeKind | null = null;
110 let state = EditorState.create({
111 schema,
112 doc: schema.node("doc", null, [schema.node("codeBlock", { close }, [schema.text("a\n\n")])]),
113 plugins: [history({ newGroupDelay: COMPOSER_UNDO_GROUP_DELAY })],
114 });
115 const dispatch = (tr: Transaction) => {
116 previous = groupUndoByChangeKind(tr, previous);
117 state = state.apply(tr);
118 };
119 dispatch(state.tr.setSelection(TextSelection.atEnd(state.doc)));
120 const view = {
121 get state() {
122 return state;
123 },
124 dispatch,
125 } as EditorView;
126​
127 const before = state;
128​
129 expect(exitCodeBlockOnTrailingBlankLines(view)).toBe(true);
130 expect(state.doc.childCount).toBe(2);
131 undo(state, dispatch);
132 expect(state.doc.eq(before.doc)).toBe(true);
133 expect(state.selection.eq(before.selection)).toBe(true);
134 });
135});
136​
137describe("exitCodeBlockOnClosingFence", () => {
138 const exit = (editor: Editor) =>
139 exitCodeBlockOnClosingFence(editor.state, (tr) => editor.view.dispatch(tr));
140​
141 it("ends the block at a typed closing fence and starts a line after it", () => {
142 const editor = codeEditor("const a = 1\n```");
143 editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "language", "ts"));
144 expect(exit(editor)).toBe(true);
145 editor.view.dispatch(editor.state.tr.insertText("explain this"));
146 expect(serializeEditorDoc(editor.state.doc).value).toBe(
147 "```ts\nconst a = 1\n```\nexplain this",
148 );
149 });
150​
151 it("moves the lines after the fence out of the block", () => {
152 const editor = codeEditor("a\n```\nb", { from: "a\n```".length });
153 expect(exit(editor)).toBe(true);
154 expect(serializeEditorDoc(editor.state.doc).value).toBe("```\na\n```\n\nb");
155 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
156 expect(editor.state.selection.$from.parent.textContent).toBe("");
157 });
158​
159 it.each([
160 ["a line that cannot close the fence", "a\n``", undefined],
161 ["a caret before the end of the line", "a\n```", { from: "a\n``".length }],
162 ])("ignores %s", (_, code, at) => {
163 expect(exit(codeEditor(code, at))).toBe(false);
164 });
165});
166​
167describe("indentCodeBlock", () => {
168 it("indents every line a selection touches", () => {
169 const editor = codeEditor("one\ntwo\nthree", { from: 1, to: 9 });
170 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
171 expect(textOf(editor)).toBe(" one\n two\n three");
172 });
173​
174 it("leaves the line a selection ends at the start of", () => {
175 const editor = codeEditor("one\ntwo", { from: 0, to: 4 });
176 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
177 expect(textOf(editor)).toBe(" one\ntwo");
178 });
179​
180 it("outdents every line a selection touches", () => {
181 const editor = codeEditor(" one\n two", { from: 2, to: 9 });
182 indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr));
183 expect(textOf(editor)).toBe("one\ntwo");
184 });
185​
186 it.each([
187 ["one\ntwo", " one\n two", 5],
188 ["\none\ntwo", "\n one\n two", 1],
189 ])("keeps the selection across the shifted lines in %s", (code, expected, from) => {
190 const editor = codeEditor(code, { from: 0, to: code.length });
191 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
192 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
193 expect(textOf(editor)).toBe(expected);
194 expect(editor.state.selection.from).toBe(from);
195 });
196​
197 it("reports handled when outdenting can go no further, so Tab never escapes the editor", () => {
198 const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
199 expect(indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr))).toBe(true);
200 expect(textOf(editor)).toBe("one\ntwo");
201 });
202​
203 it.each([
204 [" a\n b", 2, 5, "out", "a\nb", 0, 2],
205 [" a\n b", 5, 2, "out", "a\nb", 2, 0],
206 ["one\ntwo", 7, 0, "in", " one\n two", 11, 2],
207 ] as const)(
208 "maps selection endpoints when shifting %j from %i to %i %s",
209 (code, anchor, head, direction, expected, nextAnchor, nextHead) => {
210 const editor = codeEditor(code, { from: anchor, to: head });
211 indentCodeBlock(editor.state, direction, (tr) => editor.view.dispatch(tr));
212 expect(textOf(editor)).toBe(expected);
213 expect(editor.state.selection.anchor - 1).toBe(nextAnchor);
214 expect(editor.state.selection.head - 1).toBe(nextHead);
215 },
216 );
217});
218​
219describe("selections across two identical fences", () => {
220 function twoBlockEditor() {
221 const block = { type: "codeBlock", content: [{ type: "text", text: " a" }] };
222 const editor = new Editor({ extensions, content: { type: "doc", content: [block, block] } });
223 editor.view.dispatch(
224 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2, 7)),
225 );
226 return editor;
227 }
228​
229 it("leaves Tab and Enter alone rather than editing through the boundary", () => {
230 const editor = twoBlockEditor();
231 const before = editor.getJSON();
232 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
233 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
234 expect(editor.getJSON()).toEqual(before);
235 });
236});
237​
238describe("convertCodeFenceOnEnter", () => {
239 function paragraphEditor(text: string) {
240 const editor = new Editor({
241 extensions,
242 content: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] },
243 });
244 editor.view.dispatch(
245 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1 + text.length)),
246 );
247 return editor;
248 }
249​
250 it.each([
251 ["```", "```", ""],
252 ["```ts", "```", "ts"],
253 ["~~~py", "~~~", "py"],
254 ["````", "````", ""],
255 ["```ts title=example", "```", "ts title=example"],
256 ["``` js", "```", " js"],
257 ])("turns %s into a code block", (text, fence, language) => {
258 const editor = paragraphEditor(text);
259 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
260 const block = editor.state.doc.firstChild!;
261 expect(block.type.name).toBe("codeBlock");
262 expect(block.attrs).toMatchObject({ fence, language, close: `\n${fence}` });
263 expect(block.textContent).toBe("");
264 expect(editor.state.selection.from).toBe(1);
265 });
266​
267 it.each(["``", "text ```", "```a`b"])("leaves %s alone", (text) => {
268 const editor = paragraphEditor(text);
269 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
270 });
271​
272 it("refuses to open a fence inside a list item", () => {
273 const text = "```ts";
274 const editor = new Editor({
275 extensions,
276 content: {
277 type: "doc",
278 content: [
279 {
280 type: "bulletList",
281 content: [
282 {
283 type: "listItem",
284 content: [{ type: "paragraph", content: [{ type: "text", text }] }],
285 },
286 ],
287 },
288 ],
289 },
290 });
291 editor.view.dispatch(
292 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3 + text.length)),
293 );
294 const before = editor.getJSON();
295 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
296 expect(editor.getJSON()).toEqual(before);
297 });
298​
299 it("keeps a chip's source in the info string", () => {
300 const editor = new Editor({
301 extensions,
302 content: {
303 type: "doc",
304 content: [
305 {
306 type: "paragraph",
307 content: [
308 { type: "text", text: "```ts " },
309 { type: "composer-mention", attrs: { path: "a.md", source: "@a.md" } },
310 ],
311 },
312 ],
313 },
314 });
315 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
316 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
317 expect(editor.state.doc.firstChild?.attrs.language).toBe("ts @a.md");
318 });
319});