252 lines
15 KiB
JavaScript
252 lines
15 KiB
JavaScript
// Image drops and pastes: unique attachments, live source, zoom, delayed writes, source mode, and undo.
|
|
import assert from "node:assert/strict";
|
|
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
|
|
|
|
await runSmoke("editor/images", async ({ page }) => {
|
|
await mockTauri(page, {
|
|
commands: test => {
|
|
const workspace = test.workspace({
|
|
root: "C:\\smoke-workspace",
|
|
files: {
|
|
"notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n",
|
|
"notes/second.md": "# Second note\n",
|
|
"src/hello.py": "print('hello')\n",
|
|
},
|
|
writeEvents: true,
|
|
});
|
|
test.files = workspace.files;
|
|
return {
|
|
...workspace,
|
|
// Saves send the last saved text. Reject a save when the file changed, as the backend does.
|
|
workspace_write: args => {
|
|
if (args.expected !== undefined && workspace.files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
|
return workspace.workspace_write(args);
|
|
},
|
|
// Image files hold base64 SVG. Tests set `delay` to hold a write until `resume()`, or `failWrite` to reject it.
|
|
workspace_write_bytes: async args => {
|
|
if (test.delay) await new Promise(resolve => { test.resume = resolve; });
|
|
if (test.failWrite) throw new Error("Image write failed");
|
|
workspace.files.set(args.rel, args.base64);
|
|
},
|
|
// The download of a copied web image. The host adds the extension of the downloaded format.
|
|
workspace_save_image_url: args => {
|
|
if (args.url.includes("offline")) throw new Error("Cannot reach the image server");
|
|
const rel = args.rel + ".gif";
|
|
workspace.files.set(rel, btoa('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'));
|
|
return rel;
|
|
},
|
|
workspace_read_data_url: ({ rel }) => {
|
|
if (!workspace.files.has(rel)) throw new Error("missing image");
|
|
return "data:image/svg+xml;base64," + workspace.files.get(rel);
|
|
},
|
|
};
|
|
},
|
|
});
|
|
const output = await outputDir("editor/images");
|
|
async function openNote(name = "welcome.md") {
|
|
await page.keyboard.press("Control+p");
|
|
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
|
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
|
await page.locator(".cm-content").waitFor();
|
|
}
|
|
async function source() {
|
|
return page.evaluate(() => window.__CM__.state.doc.toString());
|
|
}
|
|
async function save() {
|
|
await page.keyboard.press("Control+s");
|
|
await page.waitForTimeout(100);
|
|
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
|
|
}
|
|
async function drop(count = 1, selector = ".cm-content") {
|
|
await page.locator(selector).evaluate((element, count) => {
|
|
const data = new DataTransfer();
|
|
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
|
|
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
|
|
const rect = element.getBoundingClientRect();
|
|
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
|
|
}, count);
|
|
}
|
|
await page.goto(smokeUrl);
|
|
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
|
await openNote();
|
|
await page.evaluate(async () => {
|
|
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
|
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
|
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } });
|
|
});
|
|
const original = await source();
|
|
const acceptsDrag = await page.locator(".cm-content").evaluate(element => {
|
|
const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg"));
|
|
const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data });
|
|
element.dispatchEvent(event); return event.defaultPrevented;
|
|
});
|
|
assert.ok(acceptsDrag);
|
|
await drop(2);
|
|
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2);
|
|
await page.locator(".md-image-frame img").first().waitFor();
|
|
assert.equal(await page.locator(".md-image-frame img").count(), 2);
|
|
const inserted = await source();
|
|
assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor");
|
|
const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]);
|
|
assert.notEqual(paths[0], paths[1]);
|
|
assert.ok(paths.every(path => path.startsWith("../attachments/")));
|
|
assert.equal(await save(), inserted);
|
|
|
|
// Selecting and editing Markdown leaves the image visible and updates its alt text.
|
|
await page.locator(".md-image-frame").first().hover();
|
|
await page.getByRole("button", { name: "Edit image source", exact: true }).first().click();
|
|
assert.equal(await page.locator(".md-image-frame img").count(), 2);
|
|
assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0])));
|
|
await page.evaluate(() => {
|
|
const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2;
|
|
view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } });
|
|
});
|
|
await page.locator('img[alt="Edited alt"]').waitFor();
|
|
await page.screenshot({ path: `${output}/images-editing.png` });
|
|
await page.locator(".md-image-frame").first().hover();
|
|
await page.getByRole("button", { name: "Zoom in", exact: true }).first().click();
|
|
const zoom = page.getByRole("dialog", { name: "Image zoom" });
|
|
await zoom.waitFor();
|
|
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
|
|
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%");
|
|
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
|
|
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%");
|
|
await page.screenshot({ path: `${output}/images-zoom.png` });
|
|
await zoom.getByRole("button", { name: "Fit image", exact: true }).click();
|
|
await page.keyboard.press("Escape");
|
|
assert.equal(await page.getByRole("dialog").count(), 0);
|
|
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in");
|
|
|
|
// Undo the alt edit and the complete drop as separate operations.
|
|
await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click();
|
|
await page.keyboard.press("Control+z");
|
|
await page.keyboard.press("Control+z");
|
|
assert.equal(await source(), original);
|
|
await page.keyboard.press("Control+y");
|
|
assert.equal(await source(), inserted);
|
|
|
|
// Type and move the cursor during a slow import; the drop follows its original position.
|
|
await page.evaluate(() => { window.__TEST__.delay = true; });
|
|
await drop();
|
|
await page.waitForFunction(() => !!window.__TEST__.resume);
|
|
await page.evaluate(() => {
|
|
const view = window.__CM__;
|
|
view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } });
|
|
window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null;
|
|
});
|
|
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3);
|
|
assert.ok((await source()).startsWith("Typed while saving.\n\n![]"));
|
|
|
|
// Typed local image paths load without changing views, including wiki syntax.
|
|
await page.evaluate(path => {
|
|
window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]);
|
|
const view = window.__CM__;
|
|
view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } });
|
|
}, "../attachments/typed.svg");
|
|
await page.locator('img[alt="Wiki image"]').waitFor();
|
|
await save();
|
|
await page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { name: "Write", exact: true }).focus();
|
|
await page.keyboard.press("End");
|
|
await page.locator(".md-page .md-image-frame").first().hover();
|
|
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
|
|
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
|
|
await page.keyboard.press("Escape");
|
|
|
|
// Source uses the same drop flow. The batch is one undo step.
|
|
await page.getByRole("radiogroup", { name: "View" }).getByRole("radio", { name: "Read", exact: true }).focus();
|
|
await page.keyboard.press("Home");
|
|
await page.keyboard.press("Control+e");
|
|
await page.locator(".source-editor .cm-content").waitFor();
|
|
await page.evaluate(async () => {
|
|
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
|
window.__CM__ = EditorView.findFromDOM(document.querySelector(".source-editor .cm-content"));
|
|
});
|
|
const sourceBefore = await source();
|
|
await drop(2, ".source-editor .cm-content");
|
|
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 5);
|
|
await page.keyboard.press("Control+z");
|
|
assert.equal(await source(), sourceBefore);
|
|
await page.keyboard.press("Control+y");
|
|
assert.equal((await save()).match(/!\[\]/g).length, 5);
|
|
// A failed write leaves source unchanged and surfaces an error.
|
|
const beforeFailure = await source();
|
|
await page.evaluate(() => { window.__TEST__.failWrite = true; });
|
|
await drop(1, ".source-editor .cm-content");
|
|
await page.getByText("Image write failed", { exact: true }).waitFor();
|
|
assert.equal(await source(), beforeFailure);
|
|
await page.evaluate(() => { window.__TEST__.failWrite = false; });
|
|
|
|
// File drops over a rendered widget are handled by the editor's capture listener.
|
|
await page.keyboard.press("Control+e");
|
|
await page.locator(".cm-content").waitFor();
|
|
await page.evaluate(async () => {
|
|
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
|
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
|
});
|
|
await drop(1, ".md-image-frame img >> nth=0");
|
|
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6);
|
|
|
|
// Switching tabs while a write is pending cannot insert into the new document.
|
|
await page.evaluate(() => { window.__TEST__.delay = true; });
|
|
await drop();
|
|
await page.waitForFunction(() => !!window.__TEST__.resume);
|
|
await openNote("second.md");
|
|
await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); });
|
|
await page.waitForTimeout(100);
|
|
assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/"));
|
|
// Clipboard images are inserted and remain a single undo operation too.
|
|
await page.locator(".cm-content").evaluate(element => {
|
|
const data = new DataTransfer();
|
|
data.items.add(new File(['<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'], "pasted.svg", { type: "image/svg+xml" }));
|
|
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
|
|
});
|
|
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
|
|
await page.keyboard.press("Control+s");
|
|
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
|
|
// A browser copies the still first frame of a GIF. RuneStone saves the original file from the address in the HTML.
|
|
async function pasteWebImage(src) {
|
|
await page.locator(".cm-content").evaluate((element, src) => {
|
|
const data = new DataTransfer();
|
|
data.items.add(new File(["png"], "image.png", { type: "image/png" }));
|
|
data.setData("text/html", `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`);
|
|
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
|
|
}, src);
|
|
}
|
|
await page.evaluate(async () => {
|
|
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
|
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
|
});
|
|
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_write_bytes").length);
|
|
const writesBefore = await writes();
|
|
await pasteWebImage("https://media.example.com/cat.gif?size=large&v=2");
|
|
await page.waitForFunction(() => /attachments\/[\w-]+-image\.gif\)/.test(window.__CM__.state.doc.toString()));
|
|
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_save_image_url").args);
|
|
assert.equal(download.url, "https://media.example.com/cat.gif?size=large&v=2");
|
|
assert.match(download.rel, /^attachments\/[\w-]+-image$/);
|
|
assert.equal(await writes(), writesBefore);
|
|
// When the download fails, the still copy stays.
|
|
await pasteWebImage("https://offline.example.com/cat.gif");
|
|
await page.waitForFunction(() => /attachments\/[\w-]+-image\.png\)/.test(window.__CM__.state.doc.toString()));
|
|
assert.equal(await writes(), writesBefore + 1);
|
|
await page.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
|
|
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
|
|
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
|
|
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
|
|
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_save_image_url").length);
|
|
const downloadsBefore = await downloads();
|
|
await pasteWebImage("https://offline.example.com/copied.gif");
|
|
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/-image\.gif\)/g) || []).length === 2);
|
|
assert.equal(await downloads(), downloadsBefore);
|
|
assert.match(await page.evaluate(() => window.__TEST__.calls.findLast(call => call.command === "workspace_write_bytes").args.rel), /-image\.gif$/);
|
|
// An empty file from a browser drag gives a message, not a broken image.
|
|
await page.locator(".cm-content").evaluate(element => {
|
|
const data = new DataTransfer();
|
|
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
|
|
const rect = element.getBoundingClientRect();
|
|
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
|
|
});
|
|
await page.getByText("The image file is empty.", { exact: false }).waitFor();
|
|
assert.ok(!(await page.evaluate(() => window.__CM__.state.doc.toString())).includes("viprsr188"));
|
|
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode, undo, web GIF pastes, copied originals, and empty files passed.");
|
|
});
|