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