Open History to see the last commit
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 it("falls back to a single space or tab", () => {
56 expect(outdentLine(" odd")).toBe("odd");
57 expect(outdentLine("\ttabbed")).toBe("tabbed");
58 });
59
60 it("bottoms out instead of eating code", () => {
61 expect(outdentLine("flush()")).toBe("flush()");
62 });
63});
64
65describe("indentLines", () => {
66 it("indents every line it is given", () => {
67 expect(indentLines(["a", "b"], "in")).toEqual([
68 `${CODE_BLOCK_INDENT}a`,
69 `${CODE_BLOCK_INDENT}b`,
70 ]);
71 });
72
73 it("leaves blank lines alone", () => {
74 expect(indentLines(["a", "", "b"], "in")).toEqual([
75 `${CODE_BLOCK_INDENT}a`,
76 "",
77 `${CODE_BLOCK_INDENT}b`,
78 ]);
79 });
80
81 it("outdents every line it is given", () => {
82 expect(indentLines([" a", " b", "c"], "out")).toEqual([" a", "b", "c"]);
83 });
84});
85
86function codeEditor(code: string, at?: { from: number; to?: number }) {
87 const editor = new Editor({
88 extensions,
89 content: {
90 type: "doc",
91 content: [{ type: "codeBlock", content: [{ type: "text", text: code }] }],
92 },
93 });
94 const start = 1;
95 const from = start + (at?.from ?? code.length);
96 const to = start + (at?.to ?? at?.from ?? code.length);
97 editor.view.dispatch(
98 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, from, to)),
99 );
100 return editor;
101}
102
103const textOf = (editor: Editor) => editor.state.doc.textContent;
104
105describe("indentedNewlineInCodeBlock", () => {
106 it("carries the current indentation onto the new line", () => {
107 const editor = codeEditor("function f() {\n body()");
108 const handled = indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
109 expect(handled).toBe(true);
110 expect(textOf(editor)).toBe("function f() {\n body()\n ");
111 });
112
113 it("declines an unindented line", () => {
114 const editor = codeEditor("flush()");
115 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
116 expect(textOf(editor)).toBe("flush()");
117 });
118
119 it("indents from the line the caret is on, not the last line", () => {
120 const editor = codeEditor(" deep()\nflush()", { from: 10 });
121 indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
122 expect(textOf(editor)).toBe(" deep()\n \nflush()");
123 });
124
125 it("replaces the selected text rather than keeping it", () => {
126 const editor = codeEditor(" keep()DROP", { from: 8, to: 12 });
127 indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr));
128 expect(textOf(editor)).toBe(" keep()\n ");
129 });
130
131 it("does nothing outside a code block", () => {
132 const editor = new Editor({
133 extensions,
134 content: {
135 type: "doc",
136 content: [{ type: "paragraph", content: [{ type: "text", text: " hi" }] }],
137 },
138 });
139 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
140 });
141});
142
143function pressEnter(editor: Editor) {
144 const dispatch = (tr: Parameters<typeof editor.view.dispatch>[0]) => editor.view.dispatch(tr);
145 return (
146 exitCodeBlockOnTrailingBlankLines(editor.view) ||
147 indentedNewlineInCodeBlock(editor.state, dispatch) ||
148 newlineInCode(editor.state, dispatch)
149 );
150}
151
152describe("exitCodeBlockOnTrailingBlankLines", () => {
153 it("leaves the block once two blank lines end it", () => {
154 const editor = codeEditor("flush()");
155 pressEnter(editor);
156 pressEnter(editor);
157 expect(editor.state.doc.childCount).toBe(1);
158 pressEnter(editor);
159 expect(editor.state.doc.firstChild?.textContent).toBe("flush()");
160 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
161 });
162
163 it("counts lines holding only carried indentation as blank", () => {
164 const editor = codeEditor(" nested()");
165 pressEnter(editor);
166 pressEnter(editor);
167 expect(editor.state.doc.childCount).toBe(1);
168 pressEnter(editor);
169 expect(editor.state.doc.firstChild?.textContent).toBe(" nested()");
170 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
171 });
172
173 it("closes an unclosed fence on the way out", () => {
174 const editor = codeEditor("flush()");
175 editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "close", ""));
176 pressEnter(editor);
177 pressEnter(editor);
178 pressEnter(editor);
179 expect(editor.state.doc.firstChild?.attrs.close).toBe("\n```");
180 });
181
182 it("stays in the block when the caret is not at its end", () => {
183 const editor = codeEditor("a\n\n\nb", { from: 3 });
184 expect(exitCodeBlockOnTrailingBlankLines(editor.view)).toBe(false);
185 });
186});
187
188describe("exitCodeBlockOnClosingFence", () => {
189 const exit = (editor: Editor) =>
190 exitCodeBlockOnClosingFence(editor.state, (tr) => editor.view.dispatch(tr));
191
192 it("ends the block at a typed closing fence and starts a line after it", () => {
193 const editor = codeEditor("const a = 1\n```");
194 editor.view.dispatch(editor.state.tr.setNodeAttribute(0, "language", "ts"));
195 expect(exit(editor)).toBe(true);
196 editor.view.dispatch(editor.state.tr.insertText("explain this"));
197 expect(serializeEditorDoc(editor.state.doc).value).toBe(
198 "```ts\nconst a = 1\n```\nexplain this",
199 );
200 });
201
202 it("moves the lines after the fence out of the block", () => {
203 const editor = codeEditor("a\n```\nb", { from: "a\n```".length });
204 expect(exit(editor)).toBe(true);
205 expect(serializeEditorDoc(editor.state.doc).value).toBe("```\na\n```\n\nb");
206 expect(editor.state.selection.$from.parent.type.name).toBe("paragraph");
207 expect(editor.state.selection.$from.parent.textContent).toBe("");
208 });
209
210 it.each([
211 ["a line that cannot close the fence", "a\n``", undefined],
212 ["a caret before the end of the line", "a\n```", { from: "a\n``".length }],
213 ])("ignores %s", (_, code, at) => {
214 expect(exit(codeEditor(code, at))).toBe(false);
215 });
216});
217
218describe("indentCodeBlock", () => {
219 it("inserts an indent at a collapsed caret", () => {
220 const editor = codeEditor("ab", { from: 1 });
221 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(true);
222 expect(textOf(editor)).toBe(`a${CODE_BLOCK_INDENT}b`);
223 });
224
225 it("indents every line a selection touches", () => {
226 const editor = codeEditor("one\ntwo\nthree", { from: 1, to: 9 });
227 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
228 expect(textOf(editor)).toBe(" one\n two\n three");
229 });
230
231 it("leaves the line a selection ends at the start of", () => {
232 const editor = codeEditor("one\ntwo", { from: 0, to: 4 });
233 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
234 expect(textOf(editor)).toBe(" one\ntwo");
235 });
236
237 it("outdents every line a selection touches", () => {
238 const editor = codeEditor(" one\n two", { from: 2, to: 9 });
239 indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr));
240 expect(textOf(editor)).toBe("one\ntwo");
241 });
242
243 it("keeps the selection across the shifted lines", () => {
244 const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
245 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
246 indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr));
247 expect(textOf(editor)).toBe(" one\n two");
248 });
249
250 it("reports handled when outdenting can go no further, so Tab never escapes the editor", () => {
251 const editor = codeEditor("one\ntwo", { from: 0, to: 7 });
252 expect(indentCodeBlock(editor.state, "out", (tr) => editor.view.dispatch(tr))).toBe(true);
253 expect(textOf(editor)).toBe("one\ntwo");
254 });
255
256 it("does nothing outside a code block", () => {
257 const editor = new Editor({
258 extensions,
259 content: {
260 type: "doc",
261 content: [{ type: "paragraph", content: [{ type: "text", text: "hi" }] }],
262 },
263 });
264 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
265 });
266});
267
268describe("selections across two identical fences", () => {
269 function twoBlockEditor() {
270 const block = { type: "codeBlock", content: [{ type: "text", text: " a" }] };
271 const editor = new Editor({ extensions, content: { type: "doc", content: [block, block] } });
272 editor.view.dispatch(
273 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 2, 7)),
274 );
275 return editor;
276 }
277
278 it("leaves Tab and Enter alone rather than editing through the boundary", () => {
279 const editor = twoBlockEditor();
280 const before = editor.getJSON();
281 expect(indentCodeBlock(editor.state, "in", (tr) => editor.view.dispatch(tr))).toBe(false);
282 expect(indentedNewlineInCodeBlock(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
283 expect(editor.getJSON()).toEqual(before);
284 });
285});
286
287describe("convertCodeFenceOnEnter", () => {
288 function paragraphEditor(text: string) {
289 const editor = new Editor({
290 extensions,
291 content: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] },
292 });
293 editor.view.dispatch(
294 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1 + text.length)),
295 );
296 return editor;
297 }
298
299 it.each([
300 ["```", "```", ""],
301 ["```ts", "```", "ts"],
302 ["~~~py", "~~~", "py"],
303 ["````", "````", ""],
304 ["```ts title=example", "```", "ts title=example"],
305 ["``` js", "```", " js"],
306 ])("turns %s into a code block", (text, fence, language) => {
307 const editor = paragraphEditor(text);
308 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
309 const block = editor.state.doc.firstChild!;
310 expect(block.type.name).toBe("codeBlock");
311 expect(block.attrs).toMatchObject({ fence, language, close: `\n${fence}` });
312 expect(block.textContent).toBe("");
313 expect(editor.state.selection.from).toBe(1);
314 });
315
316 it.each(["``", "text ```", "```a`b"])("leaves %s alone", (text) => {
317 const editor = paragraphEditor(text);
318 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
319 });
320
321 it("refuses to open a fence inside a list item", () => {
322 const text = "```ts";
323 const editor = new Editor({
324 extensions,
325 content: {
326 type: "doc",
327 content: [
328 {
329 type: "bulletList",
330 content: [
331 {
332 type: "listItem",
333 content: [{ type: "paragraph", content: [{ type: "text", text }] }],
334 },
335 ],
336 },
337 ],
338 },
339 });
340 editor.view.dispatch(
341 editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3 + text.length)),
342 );
343 const before = editor.getJSON();
344 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
345 expect(editor.getJSON()).toEqual(before);
346 });
347
348 it("keeps a chip's source in the info string", () => {
349 const editor = new Editor({
350 extensions,
351 content: {
352 type: "doc",
353 content: [
354 {
355 type: "paragraph",
356 content: [
357 { type: "text", text: "```ts " },
358 { type: "composer-mention", attrs: { path: "a.md", source: "@a.md" } },
359 ],
360 },
361 ],
362 },
363 });
364 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc)));
365 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(true);
366 expect(editor.state.doc.firstChild?.attrs.language).toBe("ts @a.md");
367 });
368
369 it("ignores a fence with the caret before its end", () => {
370 const editor = paragraphEditor("```ts");
371 editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 3)));
372 expect(convertCodeFenceOnEnter(editor.state, (tr) => editor.view.dispatch(tr))).toBe(false);
373 });
374});