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

composer-code-block.test.ts

391 lines14.2 KB

1import { describe, expect, it } from "vite-plus/test";
2import { Editor, Node } from "@tiptap/core";
3import { newlineInCode } from "@tiptap/pm/commands";
4import { TextSelection } from "@tiptap/pm/state";
5​
6import {
7 CODE_BLOCK_INDENT,
8 indentCodeBlock,
9 indentLines,
10 convertCodeFenceOnEnter,
11 exitCodeBlockOnClosingFence,
12 exitCodeBlockOnTrailingBlankLines,
13 indentedNewlineInCodeBlock,
14 leadingWhitespace,
15 outdentLine,
16} from "./composer-code-block";
17import StarterKit from "@tiptap/starter-kit";
18​
19import {
20 ComposerCodeBlockExtension,
21 ComposerListExtensions,
22 serializeEditorDoc,
23} from "./composer-rich-text-doc";
24​
25const extensions = [
26 StarterKit.configure({ codeBlock: false, trailingNode: false }),
27 ComposerCodeBlockExtension,
28 ...ComposerListExtensions,
29 Node.create({
30 name: "composer-mention",
31 group: "inline",
32 inline: true,
33 atom: true,
34 addAttributes: () => ({ path: { default: "" }, source: { default: "" } }),
35 }),
36];
37​
38describe("leadingWhitespace", () => {
39 it("reads the indent a new line should inherit", () => {
40 expect(leadingWhitespace(" nested()")).toBe(" ");
41 expect(leadingWhitespace("\tnested()")).toBe("\t");
42 expect(leadingWhitespace("flush()")).toBe("");
43 });
44​
45 it("stops at the first non-space so code is never treated as indent", () => {
46 expect(leadingWhitespace(" a b")).toBe(" ");
47 });
48});
49​
50describe("outdentLine", () => {
51 it("removes a full indent when there is one", () => {
52 expect(outdentLine(" deep")).toBe(" deep");
53 });
54​
55 /** Hand-indented lines should still outdent rather than refuse to move. */
56 it("falls back to a single space or tab", () => {
57 expect(outdentLine(" odd")).toBe("odd");
58 expect(outdentLine("\ttabbed")).toBe("tabbed");
59 });
60​
61 it("bottoms out instead of eating code", () => {
62 expect(outdentLine("flush()")).toBe("flush()");
63 });
64});
65​
66describe("indentLines", () => {
67 it("indents every line it is given", () => {
68 expect(indentLines(["a", "b"], "in")).toEqual([
69 `${CODE_BLOCK_INDENT}a`,
70 `${CODE_BLOCK_INDENT}b`,
71 ]);
72 });
73​
74 /** Indenting a blank line would leave whitespace the user cannot see. */
75 it("leaves blank lines alone", () => {
76 expect(indentLines(["a", "", "b"], "in")).toEqual([
77 `${CODE_BLOCK_INDENT}a`,
78 "",
79 `${CODE_BLOCK_INDENT}b`,
80 ]);
81 });
82​
83 it("outdents every line it is given", () => {
84 expect(indentLines([" a", " b", "c"], "out")).toEqual([" a", "b", "c"]);
85 });
86});
87​
88/** Builds an editor holding a single fenced block, with the caret placed by offset. */
89function codeEditor(code: string, at?: { from: number; to?: number }) {
90 const editor = new Editor({
91 extensions,
92 content: {
93 type: "doc",
94 content: [{ type: "codeBlock", content: [{ type: "text", text: code }] }],
95 },
96 });
97 const start = 1;
98 const from = start + (at?.from ?? code.length);
99 const to = start + (at?.to ?? at?.from ?? code.length);
100 editor.view.dispatch(
101 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from, to)),
102 );
103 return editor;
105​
106const textOf = (editor: Editor) => editor.state.doc.textContent;
107​
108describe("indentedNewlineInCodeBlock", () => {
109 it("carries the current indentation onto the new line", () => {
110 const editor = codeEditor("function f() {\n body()");
111 const handled = indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
112 expect(handled).toBe(true);
113 expect(textOf(editor)).toBe("function f() {\n body()\n ");
114 });
115​
116 /**
117 * With no indent to carry there is nothing to add, so the default newline
118 * should handle it and stay a single undo step.
119 */
120 it("declines an unindented line", () => {
121 const editor = codeEditor("flush()");
122 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
123 expect(textOf(editor)).toBe("flush()");
124 });
125​
126 it("indents from the line the caret is on, not the last line", () => {
127 const editor = codeEditor(" deep()\nflush()", { from: 10 });
128 indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
129 expect(textOf(editor)).toBe(" deep()\n \nflush()");
130 });
131​
132 it("replaces the selected text rather than keeping it", () => {
133 const editor = codeEditor(" keep()DROP", { from: 8, to: 12 });
134 indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
135 expect(textOf(editor)).toBe(" keep()\n ");
136 });
137​
138 it("does nothing outside a code block", () => {
139 const editor = new Editor({
140 extensions,
141 content: {
142 type: "doc",
143 content: [{ type: "paragraph", content: [{ type: "text", text: " hi" }] }],
144 },
145 });
146 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
147 });
148});
149​
150/** Enter inside a fence, in the order the composer's key handler tries it. */
151function pressEnter(editor: Editor) {
152 const dispatch = (tr: Parameters<typeof editor.view.dispatch>[0]) => editor.view.dispatch(tr);
153 return (
154 exitCodeBlockOnTrailingBlankLines(editor.view) ||
155 indentedNewlineInCodeBlock(editor.state, dispatch) ||
156 newlineInCode(editor.state, dispatch)
157 );
159​
160describe("exitCodeBlockOnTrailingBlankLines", () => {
161 it("leaves the block once two blank lines end it", () => {
162 const editor = codeEditor("flush()");
163 pressEnter(editor);
164 pressEnter(editor);
165 expect(editor.state.doc.childCount).toBe(1);
166 pressEnter(editor);
167 expect(editor.state.doc.firstChild?.textContent).toBe("flush()");
168 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
169 });
170​
171 /** Enter carries indentation, so the blank lines after nested code are not empty. */
172 it("counts lines holding only carried indentation as blank", () => {
173 const editor = codeEditor(" nested()");
174 pressEnter(editor);
175 pressEnter(editor);
176 expect(editor.state.doc.childCount).toBe(1);
177 pressEnter(editor);
178 expect(editor.state.doc.firstChild?.textContent).toBe(" nested()");
179 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
180 });
181​
182 /** An unclosed fence runs to the end of the draft, so leaving it must close it. */
183 it("closes an unclosed fence on the way out", () => {
184 const editor = codeEditor("flush()");
185 editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "close", ""));
186 pressEnter(editor);
187 pressEnter(editor);
188 pressEnter(editor);
189 expect(editor.state.doc.firstChild?.attrs.close).toBe("\n```");
190 });
191​
192 it("stays in the block when the caret is not at its end", () => {
193 const editor = codeEditor("a\n\n\nb", { from: 3 });
194 expect(exitCodeBlockOnTrailingBlankLines(editor.view)).toBe(false);
195 });
196});
197​
198describe("exitCodeBlockOnClosingFence", () => {
199 const exit = (editor: Editor) =>
200 exitCodeBlockOnClosingFence(editor.state, (tr) => editor.view.dispatch(tr));
201​
202 it("ends the block at a typed closing fence and starts a line after it", () => {
203 const editor = codeEditor("const a = 1\n```");
204 editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "language", "ts"));
205 expect(exit(editor)).toBe(true);
206 editor.view.dispatch(editor.state.tr.insertText("explain this"));
207 expect(serializeEditorDoc(editor.state.doc).value).toBe(
208 "```ts\nconst a = 1\n```\nexplain this",
209 );
210 });
211​
212 it("moves the lines after the fence out of the block", () => {
213 const editor = codeEditor("a\n```\nb", { from: "a\n```".length });
214 expect(exit(editor)).toBe(true);
215 expect(serializeEditorDoc(editor.state.doc).value).toBe("```\na\n```\n\nb");
216 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
217 expect(editor.state.selection.$from.parent.textContent).toBe("");
218 });
219​
220 it.each([
221 ["a line that cannot close the fence", "a\n``", undefined],
222 ["a caret before the end of the line", "a\n```", { from: "a\n``".length }],
223 ])("ignores %s", (_, code, at) => {
224 expect(exit(codeEditor(code, at))).toBe(false);
225 });
226});
227​
228describe("indentCodeBlock", () => {
229 it("inserts an indent at a collapsed caret", () => {
230 const editor = codeEditor("ab", { from: 1 });
231 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(true);
232 expect(textOf(editor)).toBe(`a${CODE_BLOCK_INDENT}b`);
233 });
234​
235 it("indents every line a selection touches", () => {
236 const editor = codeEditor("one\ntwo\nthree", { from: 1, to: 9 });
237 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
238 expect(textOf(editor)).toBe(" one\n two\n three");
239 });
240​
241 /** A selection of whole lines ends at the start of the next one, which it does not touch. */
242 it("leaves the line a selection ends at the start of", () => {
243 const editor = codeEditor("one\ntwo", { from: 0, to: 4 });
244 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
245 expect(textOf(editor)).toBe(" one\ntwo");
246 });
247​
248 it("outdents every line a selection touches", () => {
249 const editor = codeEditor(" one\n two", { from: 2, to: 9 });
250 indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr));
251 expect(textOf(editor)).toBe("one\ntwo");
252 });
253​
254 /** Repeated Tab presses should keep working on the same block. */
255 it("keeps the selection across the shifted lines", () => {
256 const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
257 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
258 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
259 expect(textOf(editor)).toBe(" one\n two");
260 });
261​
262 it("reports handled when outdenting can go no further, so Tab never escapes the editor", () => {
263 const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
264 expect(indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr))).toBe(true);
265 expect(textOf(editor)).toBe("one\ntwo");
266 });
267​
268 it("does nothing outside a code block", () => {
269 const editor = new Editor({
270 extensions,
271 content: {
272 type: "doc",
273 content: [{ type: "paragraph", content: [{ type: "text", text: "hi" }] }],
274 },
275 });
276 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
277 });
278});
279​
280describe("selections across two identical fences", () => {
281 /** Two structurally equal code blocks; the selection spans from one into the other. */
282 function twoBlockEditor() {
283 const block = { type: "codeBlock", content: [{ type: "text", text: " a" }] };
284 const editor = new Editor({ extensions, content: { type: "doc", content: [block, block] } });
285 // First block: 1..4 (text " a" occupies 1..4); second block starts at 5.
286 editor.view.dispatch(
287 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2, 7)),
288 );
289 return editor;
290 }
291​
292 it("leaves Tab and Enter alone rather than editing through the boundary", () => {
293 const editor = twoBlockEditor();
294 const before = editor.getJSON();
295 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
296 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
297 expect(editor.getJSON()).toEqual(before);
298 });
299});
300​
301describe("convertCodeFenceOnEnter", () => {
302 /** Builds an editor holding one paragraph with the caret at its end. */
303 function paragraphEditor(text: string) {
304 const editor = new Editor({
305 extensions,
306 content: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] },
307 });
308 editor.view.dispatch(
309 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1 + text.length)),
310 );
311 return editor;
312 }
313​
314 it.each([
315 ["```", "```", ""],
316 ["```ts", "```", "ts"],
317 ["~~~py", "~~~", "py"],
318 ["````", "````", ""],
319 ["```ts title=example", "```", "ts title=example"],
320 ["``` js", "```", " js"],
321 ])("turns %s into a code block", (text, fence, language) => {
322 const editor = paragraphEditor(text);
323 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
324 const block = editor.state.doc.firstChild!;
325 expect(block.type.name).toBe("codeBlock");
326 expect(block.attrs).toMatchObject({ fence, language, close: `\n${fence}` });
327 expect(block.textContent).toBe("");
328 // The caret belongs inside the new block, ready for the first line.
329 expect(editor.state.selection.from).toBe(1);
330 });
331​
332 it.each(["``", "text ```", "```a`b"])("leaves %s alone", (text) => {
333 const editor = paragraphEditor(text);
334 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
335 });
336​
337 it("refuses to open a fence inside a list item", () => {
338 const text = "```ts";
339 const editor = new Editor({
340 extensions,
341 content: {
342 type: "doc",
343 content: [
344 {
345 type: "bulletList",
346 content: [
347 {
348 type: "listItem",
349 content: [{ type: "paragraph", content: [{ type: "text", text }] }],
350 },
351 ],
352 },
353 ],
354 },
355 });
356 // Inside listItem > paragraph: position 3 is the paragraph start.
357 editor.view.dispatch(
358 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3 + text.length)),
359 );
360 const before = editor.getJSON();
361 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
362 expect(editor.getJSON()).toEqual(before);
363 });
364​
365 it("keeps a chip's source in the info string", () => {
366 const editor = new Editor({
367 extensions,
368 content: {
369 type: "doc",
370 content: [
371 {
372 type: "paragraph",
373 content: [
374 { type: "text", text: "```ts " },
375 { type: "composer-mention", attrs: { path: "a.md", source: "@a.md" } },
376 ],
377 },
378 ],
379 },
380 });
381 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
382 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
383 expect(editor.state.doc.firstChild?.attrs.language).toBe("ts @a.md");
384 });
385​
386 it("ignores a fence with the caret before its end", () => {
387 const editor = paragraphEditor("```ts");
388 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3)));
389 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
390 });
391});