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

ComposerPromptEditorTiptap.input.browser.test.tsx

439 lines15.8 KB

1import type { ComposerFileAttachment } from "../composerDraftStore";
2import { formatInlineContextReference } from "../lib/composerContextReferences";
3import { fileContextReference } from "../lib/composerContextRecords";
4import {
5 reconcileAttachmentContextReferences,
6 type RetainedContextPayloads,
7 useRetainedContextPayloads,
8} from "./chat/composerContextUndo";
9​
10import type { ServerProviderSkill } from "@t3tools/contracts";
11import type { Editor } from "@tiptap/core";
12import { createElement, createRef, useEffect, useState } from "react";
13import { describe, expect, it, vi } from "vite-plus/test";
14import { userEvent } from "vite-plus/test/browser";
15​
16import { act, fakeTimers, render } from "../../test/render";
17​
18import { serializeEditorDoc } from "~/composer-rich-text-doc";
19import { isMacPlatform } from "~/lib/utils";
20import {
21 ComposerPromptEditorTiptap as ComposerPromptEditor,
22 type ComposerPromptEditorHandle,
23 type ComposerPromptEditorProps,
24} from "./ComposerPromptEditorTiptap";
25​
26const babysit: ServerProviderSkill = {
27 name: "babysit",
28 path: "/skills/babysit/SKILL.md",
29 enabled: true,
30};
31​
32function Composer({
33 value,
34 richTextEnabled,
35 skills,
36 onChange,
37}: {
38 value: string;
39 richTextEnabled: boolean;
40 skills: ReadonlyArray<ServerProviderSkill>;
41 onChange?: ComposerPromptEditorProps["onChange"] | undefined;
42}) {
43 const [prompt, setPrompt] = useState({ value, cursor: value.length });
44 return (
45 <ComposerPromptEditor
46 editorRef={createRef<ComposerPromptEditorHandle>()}
47 value={prompt.value}
48 cursor={prompt.cursor}
49 richTextEnabled={richTextEnabled}
50 contextRecords={new Map()}
51 skills={skills}
52 disabled={false}
53 placeholder=""
54 onChange={(...args) => {
55 setPrompt({ value: args[0], cursor: args[1] });
56 onChange?.(...args);
57 }}
58 onPaste={() => {}}
59 />
60 );
62​
63function composer(
64 value: string,
65 richTextEnabled = true,
66 skills: ReadonlyArray<ServerProviderSkill> = [],
67 onChange?: ComposerPromptEditorProps["onChange"],
68) {
69 return (
70 <Composer value={value} richTextEnabled={richTextEnabled} skills={skills} onChange={onChange} />
71 );
73​
74function editorIn(container: HTMLElement) {
75 const element = container.querySelector<HTMLElement & { editor: Editor }>(".tiptap");
76 if (!element) throw new Error("Composer did not mount");
77 return element.editor;
79​
80async function mountEditor(...props: Parameters<typeof composer>) {
81 await using stack = new AsyncDisposableStack();
82 const screen = stack.use(await render(composer(...props)));
83 const editor = editorIn(screen.container);
84 const environment = stack.move();
85 return Object.assign(screen, {
86 [Symbol.asyncDispose]: () => environment.disposeAsync(),
87 editor,
88 /** Rerenders the same composer with new props, as a parent would. */
89 update: async (...next: Parameters<typeof composer>) => {
90 await screen.rerender(composer(...next));
91 return editorIn(screen.container);
92 },
93 });
95​
96async function replaceDomText(editor: Editor, text: string, isComposing = false) {
97 await act(async () => {
98 const node = editor.view.dom.querySelector("p")?.firstChild;
99 if (!(node instanceof Text)) throw new Error("Composition text is missing");
100 node.data = text;
101 window.getSelection()?.collapse(node, text.length);
102 if (isComposing) {
103 editor.view.dom.dispatchEvent(new CompositionEvent("compositionupdate", { data: text }));
104 }
105 editor.view.dom.dispatchEvent(
106 new InputEvent("input", {
107 inputType: isComposing ? "insertCompositionText" : "insertText",
108 data: text,
109 isComposing,
110 }),
111 );
112 });
114​
115function typeText(editor: Editor, from: number, to: number, text: string) {
116 const insert = () => editor.state.tr.insertText(text, from, to);
117 if (
118 !editor.view.someProp("handleTextInput", (handler) =>
119 handler(editor.view, from, to, text, insert),
120 )
121 ) {
122 editor.view.dispatch(insert());
123 }
125​
126function textWithMark(editor: Editor, name: string) {
127 const text: string[] = [];
128 editor.state.doc.descendants((node) => {
129 if (node.isText && node.marks.some((mark) => mark.type.name === name)) {
130 text.push(node.textContent);
131 }
132 });
133 return text;
135​
136it.each([
137 { value: "clean _build and node", code: [] },
138 { value: "clean `_build` and `node", code: ["_build"] },
139])("keeps a typed underscore literal after $value", async ({ value, code }) => {
140 await using screen = await mountEditor(value);
141 const { editor } = screen;
142 await act(async () => {
143 editor.commands.focus("end");
144 const { from, to } = editor.state.selection;
145 typeText(editor, from, to, "_");
146 });
147 expect(serializeEditorDoc(editor.state.doc).value).toBe(`${value}_`);
148 expect(textWithMark(editor, "italic")).toEqual([]);
149 expect(textWithMark(editor, "code")).toEqual(code);
150});
151​
152it("bolds with Mod+B only when text is selected", async () => {
153 await using screen = await mountEditor("ship it");
154 const { editor } = screen;
155 const modB = isMacPlatform(navigator.platform) ? "{Meta>}b{/Meta}" : "{Control>}b{/Control}";
156 await act(async () => {
157 editor.commands.focus("end");
158 });
159 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
160 await userEvent.keyboard(modB);
161 // Without the guard, Tiptap stores bold for the next typed text.
162 expect(editor.state.storedMarks).toBeNull();
163​
164 await act(async () => {
165 editor.commands.setTextSelection({ from: 1, to: 5 });
166 });
167 await userEvent.keyboard(modB);
168 await vi.waitFor(() => expect(textWithMark(editor, "bold")).toEqual(["ship"]));
169});
170​
171it.each([false, true])(
172 "composes an umlaut without wrapping the preedit text (rich text: %s)",
173 async (richTextEnabled) => {
174 // The middle dot stands in for the provisional text shown by the Compose key.
175 await using screen = await mountEditor("·", richTextEnabled);
176 const { editor } = screen;
177 await act(async () => {
178 editor.view.focus();
179 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
180 });
181 await replaceDomText(editor, '"', true);
182 expect(serializeEditorDoc(editor.state.doc).value).toBe('"');
183 await replaceDomText(editor, "ö", true);
184 await act(async () => {
185 editor.view.dom.dispatchEvent(new CompositionEvent("compositionend", { data: "ö" }));
186 });
187 expect(serializeEditorDoc(editor.state.doc).value).toBe("ö");
188 },
189);
190​
191it("lets composition replace selected text without surrounding it", async () => {
192 await using screen = await mountEditor("word");
193 const { editor } = screen;
194 await act(async () => {
195 editor.commands.setTextSelection({ from: 1, to: 5 });
196 editor.view.dom.dispatchEvent(new CompositionEvent("compositionstart"));
197 typeText(editor, 1, 5, '"');
198 });
199 expect(serializeEditorDoc(editor.state.doc).value).toBe('"');
200});
201​
202it("keeps unknown dollar names editable when restoring and pasting a draft", async () => {
203 const value = "echo $HOME $PATH $anything $notaskill $20 $20k $babysit ";
204 await using screen = await mountEditor(value, true, [babysit]);
205 const { editor } = screen;
206 expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
207 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
208 await act(async () => {
209 editor.commands.setTextSelection("echo $HO".length + 1);
210 editor.commands.insertContent("X");
211 });
212 expect(serializeEditorDoc(editor.state.doc).value).toBe(value.replace("$HOME", "$HOXME"));
213 await act(async () => {
214 editor.commands.selectAll();
215 const clipboardData = new DataTransfer();
216 clipboardData.setData("text/plain", value);
217 editor.view.dom.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
218 });
219 expect(editor.state.doc.textContent).toBe(value.replace("$babysit", ""));
220 expect(serializeEditorDoc(editor.state.doc).value).toBe(value);
221});
222​
223it("keeps the caret inside unknown dollar text across rich and plain remounts", async () => {
224 const value = "echo $HOME now";
225 await using screen = await mountEditor(value);
226 let { editor } = screen;
227 await act(async () => {
228 editor.commands.setTextSelection("echo $HO".length + 1);
229 });
230 editor = await screen.update(value, false);
231 await act(async () => {
232 editor.commands.insertContent("X");
233 });
234 expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXME now");
235 editor = await screen.update(value, true);
236 await act(async () => {
237 editor.commands.insertContent("Y");
238 });
239 expect(serializeEditorDoc(editor.state.doc).value).toBe("echo $HOXYME now");
240});
241​
242const file = {
243 type: "file",
244 id: "file-1",
245 name: "notes.txt",
246 mimeType: "text/plain",
247 sizeBytes: 5,
248 file: new File(["notes"], "notes.txt", { type: "text/plain" }),
249} satisfies ComposerFileAttachment;
250​
251describe("composer context undo lifetime", () => {
252 async function mountComposer(destinationValue = "") {
253 const initialValue = `Draft A ${formatInlineContextReference(fileContextReference(file))}`;
254 const editorRef = createRef<ComposerPromptEditorHandle>();
255 let current: { value: string; files: ComposerFileAttachment[] };
256 let retained: RetainedContextPayloads;
257​
258 function Composer({ targetKey }: { targetKey: string }) {
259 const [drafts, setDrafts] = useState<
260 Record<string, { value: string; files: ComposerFileAttachment[] }>
261 >({
262 a: { value: initialValue, files: [file] },
263 b: { value: destinationValue, files: [] },
264 });
265 const payloads = useRetainedContextPayloads(targetKey);
266 const draft = drafts[targetKey]!;
267 useEffect(() => {
268 current = draft;
269 retained = payloads;
270 });
271 const editorProps = {
272 draftKey: targetKey,
273 editorRef,
274 value: draft.value,
275 cursor: 0,
276 contextRecords: new Map(
277 draft.files.map((entry) => [
278 fileContextReference(entry).contextId,
279 { kind: "file" as const, record: entry },
280 ]),
281 ),
282 skills: [],
283 disabled: false,
284 placeholder: "",
285 onChange: (value, _cursor, _expandedCursor, _adjacent, contextIds) => {
286 const changes = reconcileAttachmentContextReferences({
287 referencedContextIds: new Set(contextIds),
288 files: draft.files,
289 images: [],
290 previewAnnotations: [],
291 retained: payloads,
292 });
293 setDrafts({
294 ...drafts,
295 [targetKey]: {
296 value,
297 files: [
298 ...draft.files.filter((entry) => !changes.filesToRemove.includes(entry.id)),
299 ...changes.filesToRestore,
300 ],
301 },
302 });
303 },
304 onPaste: () => {},
305 } satisfies ComposerPromptEditorProps;
306 return createElement(ComposerPromptEditor, editorProps);
307 }
308​
309 await using stack = new AsyncDisposableStack();
310 const screen = stack.use(await render(createElement(Composer, { targetKey: "a" })));
311 const editor = () => editorIn(screen.container);
312 const environment = stack.move();
313 return Object.assign(screen, {
314 [Symbol.asyncDispose]: () => environment.disposeAsync(),
315 initialValue,
316 show: (targetKey: string) => screen.rerender(createElement(Composer, { targetKey })),
317 editor,
318 draft: () => current,
319 retained: () => retained,
320 deleteDraft: async () => {
321 await act(async () => {
322 const currentEditor = editor();
323 currentEditor.view.dispatch(
324 currentEditor.state.tr.delete(1, currentEditor.state.doc.content.size - 1),
325 );
326 });
327 },
328 undo: async () => {
329 await act(async () => {
330 editor().commands.undo();
331 });
332 },
333 });
334 }
335​
336 it("restores a deleted chip and its file bytes on same-draft undo, then releases them on unmount", async () => {
337 await using composer = await mountComposer();
338 await composer.deleteDraft();
339 expect(composer.draft()).toEqual({ value: "", files: [] });
340 const retained = composer.retained();
341 expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
342​
343 await composer.show("a");
344 await composer.undo();
345 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(composer.initialValue);
346 expect(composer.draft()).toEqual({ value: composer.initialValue, files: [file] });
347 expect(composer.draft().files[0]?.file).toBe(file.file);
348​
349 await composer.deleteDraft();
350 await composer.unmount();
351 expect(retained.files.size).toBe(0);
352 });
353​
354 it.each(["", "Draft B"])(
355 "releases deleted payloads and prevents undo into the previous draft when switching to %j",
356 async (destinationValue) => {
357 await using composer = await mountComposer(destinationValue);
358 await composer.deleteDraft();
359 expect(composer.draft()).toEqual({ value: "", files: [] });
360 const retained = composer.retained();
361 expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file);
362​
363 await composer.show("b");
364 expect(retained.files.size).toBe(0);
365 await composer.undo();
366 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(destinationValue);
367 expect(composer.draft()).toEqual({ value: destinationValue, files: [] });
368​
369 await composer.show("a");
370 await composer.undo();
371 expect(serializeEditorDoc(composer.editor().state.doc).value).toBe("");
372 expect(composer.draft()).toEqual({ value: "", files: [] });
373 },
374 );
375});
376​
377describe("an Arabic line", () => {
378 async function focusEnd(editor: Editor) {
379 // ProseMirror rewrites the DOM caret 20ms after focus. Run that now, or it
380 // can undo the first arrow key before ProseMirror reads the native move.
381 using _timers = fakeTimers();
382 await act(async () => {
383 editor.commands.focus("end");
384 });
385 await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom));
386 vi.runOnlyPendingTimers();
387 }
388​
389 it("leaves inline code through its start with ArrowRight, which points back", async () => {
390 // Positions: اكتب at 1-5, sumBy at 6-11, الان at 12-16.
391 await using screen = await mountEditor("اكتب `sumBy` الان");
392 const { editor } = screen;
393 await focusEnd(editor);
394 const caret = () => ({
395 head: editor.state.selection.head,
396 inCode: (editor.state.storedMarks ?? editor.state.selection.$head.marks()).length > 0,
397 });
398 const visited = [caret()];
399 while (visited.at(-1)!.head > 5) {
400 const before = visited.at(-1)!;
401 await userEvent.keyboard("{ArrowRight}");
402 await vi.waitFor(() => {
403 const after = caret();
404 expect(after.head < before.head || after.inCode !== before.inCode).toBe(true);
405 });
406 visited.push(caret());
407 }
408 expect(visited.some((stop) => stop.inCode)).toBe(true);
409 });
410​
411 it("shows the backticks on either side of inline code it is editing", async () => {
412 await using screen = await mountEditor("اكتب `sumBy` الان");
413 const { editor } = screen;
414 await act(async () => {
415 editor.commands.setTextSelection("اكتب su".length + 1);
416 });
417 const code = editor.view.dom.querySelector("code")!;
418 const word = document.createRange();
419 word.selectNodeContents([...code.childNodes].find((node) => node instanceof Text)!);
420 const text = word.getBoundingClientRect();
421 const [open, close] = [...editor.view.dom.querySelectorAll(".composer-rich-marker")].map(
422 (marker) => marker.getBoundingClientRect(),
423 );
424 expect(open!.right).toBeLessThanOrEqual(text.left + 1);
425 expect(close!.left).toBeGreaterThanOrEqual(text.right - 1);
426 });
427​
428 it("starts the next line on the right", async () => {
429 await using screen = await mountEditor("اكتب الدالة");
430 const { editor } = screen;
431 await focusEnd(editor);
432 await userEvent.keyboard("{Shift>}{Enter}{/Shift}");
433 await vi.waitFor(() => expect(editor.state.doc.childCount).toBe(2));
434 const box = editor.view.dom.getBoundingClientRect();
435 expect(editor.view.coordsAtPos(editor.state.selection.head).left).toBeGreaterThan(
436 box.left + box.width / 2,
437 );
438 });
439});