Add workspace links, restore tabs, and update project guides
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 720, height: 640 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
const output = ".audit/backlinks";
|
||||
await mkdir(output, { recursive: true });
|
||||
|
||||
await page.route("**/__backlinks__", route => route.fulfill({ contentType: "text/html", body: `<!doctype html><html><head><meta charset="UTF-8"><title>Backlinks check</title></head><body>
|
||||
<aside id="fixture" style="width:320px;height:500px;display:flex;flex-direction:column;background:var(--rs-bg-elevated);margin:24px"></aside>
|
||||
<script type="module">
|
||||
import '/src/app.css';
|
||||
import {mount,unmount} from '/node_modules/.vite/deps/svelte.js';
|
||||
import Backlinks from '/src/lib/layout/Backlinks.svelte';
|
||||
import {applyAppearance} from '/src/lib/theme/appearance.ts';
|
||||
let component;
|
||||
window.renderBacklinks = async ({mode='dark',width=320,entries=[],busy=false,error=null}={}) => {
|
||||
if(component) await unmount(component);
|
||||
applyAppearance({theme:'default',mode});
|
||||
document.querySelector('#fixture').style.width=width+'px';
|
||||
component=mount(Backlinks,{target:document.querySelector('#fixture'),props:{entries,busy,error,onOpen:entry=>window.openedBacklink=entry,onRebuild:()=>window.rebuildCount=(window.rebuildCount||0)+1}});
|
||||
};
|
||||
await window.renderBacklinks();
|
||||
window.backlinksReady=true;
|
||||
</script></body></html>` }));
|
||||
|
||||
const entries = Array.from({ length: 28 }, (_, index) => ({
|
||||
sourcePath: `research/long-folder-name/project-${index + 1}/source-note-with-a-long-readable-title.md`,
|
||||
line: index + 3, from: index * 100, to: index * 100 + 10,
|
||||
text: "This source note links to [[Target|the selected note]]. Its visible excerpt can wrap within the panel.",
|
||||
kind: "wiki", target: "Target",
|
||||
}));
|
||||
const measurements = [];
|
||||
try {
|
||||
await page.goto(`${process.env.SMOKE_URL || "http://127.0.0.1:1420"}/__backlinks__`);
|
||||
await page.waitForFunction(() => window.backlinksReady);
|
||||
const panel = page.getByRole("region", { name: "Backlinks", exact: true });
|
||||
await panel.getByText("No other notes link to this file.").waitFor();
|
||||
await page.screenshot({ path: `${output}/empty-dark.png` });
|
||||
for (const mode of ["light", "dark"]) {
|
||||
for (const width of [320, 180]) {
|
||||
await page.evaluate(args => window.renderBacklinks(args), { mode, width, entries });
|
||||
const toggle = panel.getByRole("button", { name: "Backlinks 28", exact: true });
|
||||
await toggle.focus();
|
||||
await page.keyboard.press("Enter");
|
||||
assert.equal(await toggle.getAttribute("aria-expanded"), "false");
|
||||
assert.equal(await panel.locator(".source").first().isVisible(), false);
|
||||
await page.keyboard.press("Space");
|
||||
assert.equal(await toggle.getAttribute("aria-expanded"), "true");
|
||||
await page.keyboard.press("Tab");
|
||||
await page.keyboard.press("Enter");
|
||||
assert.ok(await page.evaluate(() => window.rebuildCount > 0));
|
||||
await page.keyboard.press("Tab");
|
||||
await page.keyboard.press("Enter");
|
||||
assert.equal(await page.evaluate(() => window.openedBacklink.sourcePath), entries[0].sourcePath);
|
||||
const metrics = await panel.evaluate(node => {
|
||||
const source = node.querySelector(".source"), title = node.querySelector(".source-title"), content = node.querySelector(".content");
|
||||
const style = getComputedStyle(source);
|
||||
const color = value => value.match(/[\d.]+/g).slice(0, 3).map(Number);
|
||||
const luminance = rgb => rgb.map(value => value / 255).map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [.2126,.7152,.0722][index], 0);
|
||||
const contrast = (a,b) => { const l1=luminance(color(a)),l2=luminance(color(b));return (Math.max(l1,l2)+.05)/(Math.min(l1,l2)+.05); };
|
||||
const background = getComputedStyle(document.querySelector("#fixture")).backgroundColor;
|
||||
return { text: style.color, accent: getComputedStyle(title).color, background,
|
||||
textContrast: contrast(style.color,background), linkContrast:contrast(getComputedStyle(title).color,background),
|
||||
width:node.clientWidth,scrollWidth:node.scrollWidth,scrollable:content.scrollHeight>content.clientHeight,
|
||||
focusStyle:style.outlineStyle,focusColor:style.outlineColor,opacity:style.opacity };
|
||||
});
|
||||
assert.ok(metrics.textContrast >= 4.5, `Text contrast: ${mode} ${width}`);
|
||||
assert.ok(metrics.linkContrast >= 4.5, `Link contrast: ${mode} ${width}`);
|
||||
assert.ok(metrics.scrollWidth <= metrics.width, "The panel must not scroll horizontally");
|
||||
assert.ok(metrics.scrollable, "Long lists must scroll inside the panel");
|
||||
assert.equal(metrics.focusStyle, "solid");
|
||||
assert.equal(metrics.opacity, "1");
|
||||
measurements.push({ mode, width, ...metrics });
|
||||
await page.screenshot({ path: `${output}/${mode}-${width}-focus.png` });
|
||||
}
|
||||
}
|
||||
await page.evaluate(() => window.renderBacklinks({ busy:true, error:"Could not read one note. Rebuild the index to try again." }));
|
||||
assert.equal(await panel.getByRole("button", { name:"Rebuild note index", exact:true }).isDisabled(), true);
|
||||
await panel.getByText("Reading workspace links…").waitFor();
|
||||
await page.screenshot({ path:`${output}/busy-error-dark.png` });
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile(`${output}/measurements.json`, JSON.stringify(measurements,null,2));
|
||||
console.log("Backlinks smoke passed: themes, narrow panels, long lists, keyboard, empty, busy, error, and contrast.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,29 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { documentSessionKey, parseDocumentSession, restoreDocumentSession } from "../src/lib/workspace/documentSession.ts";
|
||||
|
||||
test("document sessions isolate workspaces and discard unsafe or duplicate paths", () => {
|
||||
assert.notEqual(documentSessionKey("C:\\one"), documentSessionKey("C:\\two"));
|
||||
assert.equal(parseDocumentSession("invalid"), null);
|
||||
assert.equal(parseDocumentSession('{"version":2,"documents":[]}'), null);
|
||||
assert.deepEqual(parseDocumentSession(JSON.stringify({ version: 1, activePath: "b.md", documents: [
|
||||
{ path: "b.md", pinned: true, contents: "unsaved" }, { path: "a.md" }, { path: "b.md" },
|
||||
{ path: "../outside.md" }, { path: "C:\\outside.md" }, { path: "empty:test" }, null,
|
||||
] })), { version: 1, activePath: "b.md", documents: [{ path: "b.md", pinned: true }, { path: "a.md", pinned: false }] });
|
||||
});
|
||||
|
||||
test("restoration keeps order and active tab when a missing file fails", async () => {
|
||||
const opened: string[] = [];
|
||||
const session = parseDocumentSession(JSON.stringify({ version: 1, activePath: "c.md",
|
||||
documents: ["b.md", "missing.md", "c.md", "a.md"].map(path => ({ path })) }))!;
|
||||
const active = await restoreDocumentSession(session, async item => {
|
||||
if (item.path === "missing.md") throw new Error("Not found");
|
||||
opened.push(item.path);
|
||||
});
|
||||
assert.deepEqual(opened, ["b.md", "c.md", "a.md"]);
|
||||
assert.equal(active, "c.md");
|
||||
assert.equal(await restoreDocumentSession({ ...session, activePath: "missing.md" }, async item => {
|
||||
if (item.path === "missing.md") throw new Error("Not found");
|
||||
}), "b.md");
|
||||
assert.equal(await restoreDocumentSession(session, async () => { throw new Error("Unavailable"); }), null);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear();
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tab-menu-workspace";
|
||||
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
|
||||
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
window.tabMenuTest.calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
|
||||
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
|
||||
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
|
||||
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
|
||||
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
|
||||
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
|
||||
|
||||
const output = '.audit/editor-preview-links';
|
||||
await mkdir(output, { recursive: true });
|
||||
const installation = '# Installation\n\nOutside the list.\n\n1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.\n2. Save both files to Downloads and open Terminal in that folder.\n3. Verify the download, then install the package:\n\n ```bash\n sha256sum --check SHA256SUMS\n sudo apt install ./RuneStone_0.1.42_amd64.deb\n ```\n\n Stop if verification fails.\n4. Open RuneStone from your applications menu.\n5. Open a workspace outside the application folder.\n\nAfter the list.\n';
|
||||
async function resetFile(text) {
|
||||
await page.locator('.cm-content').evaluate(async (node, text) => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
const view = EditorView.findFromDOM(node);
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
|
||||
}, text);
|
||||
}
|
||||
try {
|
||||
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.locator('[data-tree-rel="a.md"]').click();
|
||||
await page.locator('.cm-content').waitFor();
|
||||
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
|
||||
if (width < 1000) {
|
||||
await page.getByRole('button', { name:'Files', exact:true }).click();
|
||||
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
|
||||
}
|
||||
await resetFile(installation);
|
||||
const preview = page.locator('.writer-preview').filter({ has: page.locator('ol') });
|
||||
await preview.waitFor();
|
||||
if (theme === 'dark' && width === 1440) {
|
||||
await preview.evaluate(element => { element.style.whiteSpace = 'pre-wrap'; });
|
||||
const gap = await preview.locator('li').first().evaluate(item => item.querySelector('p').getBoundingClientRect().top - item.getBoundingClientRect().top);
|
||||
assert.ok(gap > 15, 'Inherited editor whitespace reproduces the reported blank line');
|
||||
await page.screenshot({ path:`${output}/ordered-list-before-dark-1440.png` });
|
||||
await preview.evaluate(element => { element.style.removeProperty('white-space'); });
|
||||
}
|
||||
const metrics = await preview.evaluate(element => {
|
||||
const item = element.querySelector('li'), paragraph = item.querySelector('p');
|
||||
return { whiteSpace: getComputedStyle(element).whiteSpace, itemTop: item.getBoundingClientRect().top, paragraphTop: paragraph.getBoundingClientRect().top, firstHeight: item.getBoundingClientRect().height, lineHeight: parseFloat(getComputedStyle(paragraph).lineHeight) };
|
||||
});
|
||||
assert.equal(metrics.whiteSpace, 'normal');
|
||||
assert.ok(Math.abs(metrics.paragraphTop - metrics.itemTop) < 2, 'Number and first paragraph share one line');
|
||||
assert.ok(metrics.firstHeight < metrics.lineHeight * 3, 'Short list item has no blank formatting lines');
|
||||
assert.equal(await preview.locator('li').count(), 5);
|
||||
assert.match(await preview.locator('code').last().innerText(), /sha256sum --check SHA256SUMS\n/);
|
||||
await page.screenshot({ path:`${output}/ordered-list-${theme}-${width}.png` });
|
||||
const fixture = '# Links\n\nOutside.\n\n| Task | Link |\n| --- | --- |\n| Plugin setup | [Plugin installation](<docs/plugins.md#install-a-plugin>) |\n| Wiki | [[docs/plugins.md\\|Plugin guide]] |\n';
|
||||
await resetFile(fixture);
|
||||
await page.evaluate(() => window.tabMenuTest.files.set('docs/plugins.md', '# Plugins\n\n## Install a plugin\n\nLocal plugin instructions.\n'));
|
||||
const localLink = page.locator('.writer-table a').filter({ hasText:'Plugin installation' });
|
||||
await localLink.click({ modifiers:[width === 620 ? 'Meta' : 'Control'] });
|
||||
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
|
||||
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
|
||||
assert.equal(page.url(), process.env.SMOKE_URL || 'http://127.0.0.1:1420/');
|
||||
assert.equal(browser.contexts().flatMap(context => context.pages()).length, 1, 'Local link cannot open a browser tab');
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.calls.filter(call => /open_url|open_path/.test(call.command)).length), 0);
|
||||
await page.screenshot({ path:`${output}/local-link-tab-${theme}-${width}.png` });
|
||||
await page.getByRole('tab', { name:'a.md', exact:true }).click();
|
||||
const wiki = page.locator('.writer-table a').filter({ hasText:'Plugin guide' });
|
||||
await wiki.click({ modifiers:['Control'] });
|
||||
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
|
||||
assert.equal(await page.getByRole('tab', { name:'plugins.md', exact:true }).count(), 1, 'Duplicate link focuses its existing document');
|
||||
await page.getByRole('tab', { name:'a.md', exact:true }).click();
|
||||
await page.locator('.writer-table a').filter({ hasText:'Plugin installation' }).click();
|
||||
const source = page.locator('.is-source-editing .writer-cell-editor');
|
||||
await source.waitFor();
|
||||
await page.screenshot({ path:`${output}/source-link-${theme}-${width}.png` });
|
||||
await source.locator('.writer-link-target').click({ modifiers:['Control'] });
|
||||
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
|
||||
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: nested fenced-code list spacing, preserved code newlines, rendered/table-source/wiki local links open document tabs, duplicate target focus, both themes, narrow and wide windows. Native WebView acceptance remains open.');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path:`${output}/failure.png` });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { documentHeadings, headingLinkLine, linkFragment } from "../src/lib/workspace/headingLinks.ts";
|
||||
|
||||
test("section links decode fragments without changing the file path", () => {
|
||||
assert.equal(linkFragment("notes/a%23b.md#Caf%C3%A9%20setup"), "Café setup");
|
||||
assert.equal(linkFragment("#literal%"), "literal%");
|
||||
assert.equal(linkFragment("a.md"), null);
|
||||
assert.equal(headingLinkLine("# Title", ""), 1);
|
||||
});
|
||||
|
||||
test("headings use rendered text, Unicode, and unique slugs", () => {
|
||||
const source = "# **Windows** setup!\n\n## Café `setup`\n\n## Windows setup!\n\n## Windows setup-1\n\n## Windows setup!\n";
|
||||
assert.deepEqual(documentHeadings(source).map(({ slug }) => slug),
|
||||
["windows-setup", "café-setup", "windows-setup-1", "windows-setup-1-1", "windows-setup-2"]);
|
||||
assert.equal(headingLinkLine(source, "windows-setup-2"), 9);
|
||||
assert.equal(headingLinkLine(source, "Café setup"), 3);
|
||||
assert.equal(headingLinkLine(source, "missing"), null);
|
||||
});
|
||||
|
||||
test("section lines exclude properties and code, and include Setext headings", () => {
|
||||
const source = "---\r\ntitle: Test\r\n---\r\n\r\n```md\r\n# Fake\r\n```\r\n\r\nInstall\r\n=======\r\n\r\n## Real ###\r\n";
|
||||
assert.deepEqual(documentHeadings(source), [
|
||||
{ text: "Install", slug: "install", line: 9 },
|
||||
{ text: "Real", slug: "real", line: 12 },
|
||||
]);
|
||||
assert.equal(headingLinkLine(source, "fake"), null);
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { WorkspaceNoteIndex, type NoteIndexIO } from "../src/lib/workspace/noteIndex.ts";
|
||||
|
||||
function workspace(files: Map<string, string>): NoteIndexIO {
|
||||
return {
|
||||
async list(folder) {
|
||||
const prefix = folder ? `${folder}/` : "";
|
||||
const entries = new Map<string, { rel_path: string; kind: "file" | "folder" }>();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix)) continue;
|
||||
const suffix = path.slice(prefix.length), separator = suffix.indexOf("/");
|
||||
const rel_path = separator < 0 ? path : prefix + suffix.slice(0, separator);
|
||||
entries.set(rel_path, { rel_path, kind: separator < 0 ? "file" : "folder" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async read(path) {
|
||||
if (!files.has(path)) throw new Error("File missing");
|
||||
return files.get(path)!;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("wiki names resolve anywhere and duplicate names require a path", async () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
await index.rebuild(workspace(new Map([
|
||||
["deep/source.md", "[[Elsewhere]]\n[[Root]]"], ["unrelated/nested/Elsewhere.md", ""], ["Root.md", ""],
|
||||
])));
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "resolved", path: "unrelated/nested/Elsewhere.md" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Root#Heading", "wiki"), { status: "resolved", path: "Root.md" });
|
||||
index.update("deep/Elsewhere.md", "");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "ambiguous", candidates: ["deep/Elsewhere.md", "unrelated/nested/Elsewhere.md"] });
|
||||
assert.equal(index.backlinks("deep/Elsewhere.md").length, 0);
|
||||
assert.deepEqual(index.resolve("deep/source.md", "./Elsewhere", "wiki"), { status: "resolved", path: "deep/Elsewhere.md" });
|
||||
index.update("documents/Other.mdown", "[[Root]]");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Other", "wiki"), { status: "resolved", path: "documents/Other.mdown" });
|
||||
assert.equal(index.backlinks("Root.md").length, 2);
|
||||
index.update("documents/Version 1.2.md", "");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Version 1.2", "wiki"), { status: "resolved", path: "documents/Version 1.2.md" });
|
||||
});
|
||||
|
||||
test("explicit relative links do not fall back and cannot escape the workspace", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
for (const path of ["source.md", "deep/source.md", "Target.md", "deep/folder/Target.md", "folder/Target.md", "deep/Name with spaces.md"]) index.update(path, "");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "./Target", "wiki"), { status: "missing" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "./Target.md", "md"), { status: "missing" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "../Target", "wiki"), { status: "resolved", path: "Target.md" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "/Target", "wiki"), { status: "resolved", path: "Target.md" });
|
||||
assert.equal(index.resolve("deep/source.md", "folder/Target", "wiki").status, "ambiguous");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Name%20with%20spaces.md#part", "md"), { status: "resolved", path: "deep/Name with spaces.md" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "..\\Target.md", "md"), { status: "resolved", path: "Target.md" });
|
||||
assert.equal(index.resolve("deep/source.md", "../../Target", "wiki").status, "missing");
|
||||
assert.equal(index.resolve("source.md", "../Target", "wiki").status, "missing");
|
||||
assert.equal(index.resolve("source.md", "https://example.test", "md").status, "external");
|
||||
assert.equal(index.resolve("source.md", "//example.test/Target", "md").status, "external");
|
||||
});
|
||||
|
||||
test("backlinks index wiki aliases, inline and reference Markdown links with source lines", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
index.update("Target.md", "");
|
||||
index.update("source.md", [
|
||||
"[[Target|Alias]]", "[Target](Target.md#Section)", "[Named][id]", "[id][]", "[id]", "", "[id]: Target.md", "",
|
||||
"`[[Target]]`", "", "![[Target]]", "\\[[Target]]", "<!-- [[Target]] -->", "```md", "[[Target]]", "```",
|
||||
].join("\n"));
|
||||
assert.deepEqual(index.backlinks("Target.md").map(link => [link.sourcePath, link.line, link.kind]), [
|
||||
["source.md", 1, "wiki"], ["source.md", 2, "md"], ["source.md", 3, "md"], ["source.md", 4, "md"], ["source.md", 5, "md"],
|
||||
]);
|
||||
index.update("Target.md", "[Local section](#Heading)");
|
||||
assert.equal(index.backlinks("Target.md").length, 5);
|
||||
});
|
||||
|
||||
test("backlinks follow edits, create, file and folder moves, rename, and deletion", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
index.update("folder/source.md", "[[Target]]\n[Target](../Target.md)");
|
||||
assert.deepEqual(index.backlinks("Target.md"), []);
|
||||
index.update("Target.md", "");
|
||||
assert.equal(index.backlinks("Target.md").length, 2);
|
||||
index.update("folder/source.md", "[[Target]]");
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
index.rename("folder", "other/deep");
|
||||
assert.equal(index.backlinks("Target.md")[0].sourcePath, "other/deep/source.md");
|
||||
index.rename("Target.md", "notes/Target.md");
|
||||
assert.equal(index.backlinks("notes/Target.md").length, 1);
|
||||
index.rename("notes/Target.md", "notes/Renamed.md");
|
||||
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
|
||||
index.update("other/deep/source.md", "[[Renamed]]");
|
||||
assert.equal(index.backlinks("notes/Renamed.md").length, 1);
|
||||
index.remove("other");
|
||||
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
|
||||
index.remove("notes/Renamed.md");
|
||||
assert.equal(index.resolve("", "Renamed", "wiki").status, "missing");
|
||||
});
|
||||
|
||||
test("moving a relative-link source changes its target without rewriting Markdown", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
index.update("Target.md", "");
|
||||
index.update("folder/Target.md", "");
|
||||
index.update("source.md", "[Target](./Target.md)");
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
index.rename("source.md", "folder/source.md");
|
||||
assert.equal(index.backlinks("Target.md").length, 0);
|
||||
assert.equal(index.backlinks("folder/Target.md").length, 1);
|
||||
});
|
||||
|
||||
test("rebuild replaces deleted paths and uses live drafts", async () => {
|
||||
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
|
||||
const index = new WorkspaceNoteIndex();
|
||||
await index.rebuild(workspace(files));
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
files.delete("source.md");
|
||||
files.set("elsewhere/source.md", "Old content");
|
||||
const result = await index.rebuild(workspace(files), new Map([["elsewhere/source.md", "[[Target]]"]]));
|
||||
assert.equal(result.committed, true);
|
||||
assert.equal(result.indexed, 2);
|
||||
assert.deepEqual(result.errors, []);
|
||||
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["elsewhere/source.md"]);
|
||||
index.clear();
|
||||
assert.equal(index.size, 0);
|
||||
await index.rebuild(workspace(files));
|
||||
assert.equal(index.size, 2);
|
||||
});
|
||||
|
||||
test("updates during a rebuild survive its disk snapshot", async () => {
|
||||
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
|
||||
const io = workspace(files);
|
||||
let release!: () => void;
|
||||
const barrier = new Promise<void>(resolve => release = resolve);
|
||||
const index = new WorkspaceNoteIndex();
|
||||
const rebuild = index.rebuild({ ...io, read: async path => { await barrier; return io.read(path); } });
|
||||
await Promise.resolve();
|
||||
index.update("source.md", "No link");
|
||||
index.update("new.md", "[[Target]]");
|
||||
index.rename("new.md", "moved.md");
|
||||
release();
|
||||
await rebuild;
|
||||
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["moved.md"]);
|
||||
});
|
||||
|
||||
test("workspace clear and a newer rebuild reject stale async results", async () => {
|
||||
let release!: () => void;
|
||||
const barrier = new Promise<void>(resolve => release = resolve);
|
||||
const index = new WorkspaceNoteIndex();
|
||||
const slow = index.rebuild({ list: async () => { await barrier; return [{ rel_path: "old.md", kind: "file" }]; }, read: async () => "" });
|
||||
index.clear();
|
||||
await index.rebuild(workspace(new Map([["new.md", ""]])));
|
||||
release();
|
||||
assert.equal((await slow).committed, false);
|
||||
assert.equal(index.resolve("", "old", "wiki").status, "missing");
|
||||
assert.deepEqual(index.resolve("", "new", "wiki"), { status: "resolved", path: "new.md" });
|
||||
});
|
||||
|
||||
test("read and list failures report incomplete coverage and remain rebuildable", async () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
const io = workspace(new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["blocked/note.md", ""]]));
|
||||
const result = await index.rebuild({
|
||||
list: async folder => { if (folder === "blocked") throw new Error("Folder unavailable"); return io.list(folder); },
|
||||
read: async path => { if (path === "source.md") throw new Error("File unavailable"); return io.read(path); },
|
||||
});
|
||||
assert.deepEqual(result.errors.map(error => [error.path, error.operation]), [["blocked", "list"], ["source.md", "read"]]);
|
||||
assert.equal(index.backlinks("Target.md").length, 0);
|
||||
await index.rebuild(io);
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tree-actions-test";
|
||||
const files = new Map([
|
||||
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
|
||||
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
|
||||
]);
|
||||
const calls = [];
|
||||
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence,
|
||||
unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tree-actions-test", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length);
|
||||
const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_delete") {
|
||||
if (args.rel === state.fail) throw new Error("Access denied");
|
||||
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_copy") {
|
||||
const to = args.rel + "-copy";
|
||||
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
|
||||
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
|
||||
}
|
||||
if (command === "workspace_rename") {
|
||||
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
|
||||
for (const [path, text] of [...files]) if (contains(args.from, path)) {
|
||||
files.delete(path);
|
||||
files.set(args.to + path.slice(args.from.length), text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
|
||||
if (command === "workspace_reveal") return;
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:dialog|message") return state.answer;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
window.__TEST__ = state;
|
||||
});
|
||||
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
|
||||
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
|
||||
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
|
||||
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
async function reset() {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await row("notes").waitFor();
|
||||
}
|
||||
async function action(path, name) {
|
||||
await row(path).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name, exact: true }).click();
|
||||
await settle();
|
||||
}
|
||||
async function selectFiles() {
|
||||
await row("a.md").click();
|
||||
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
|
||||
await settle();
|
||||
await row("b.md").click({ modifiers: ["Control"] });
|
||||
await settle();
|
||||
}
|
||||
async function drag(sourcePath, targetPath, place = "inside") {
|
||||
const source = await row(sourcePath).boundingBox();
|
||||
const target = await row(targetPath).boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
}
|
||||
try {
|
||||
await reset();
|
||||
for (const [theme, width] of [['dark',1440],['light',620]]) {
|
||||
await page.setViewportSize({width,height:850});
|
||||
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = 'default'; },theme);
|
||||
await row('a.md').click();
|
||||
await row('a.md').focus();
|
||||
await page.keyboard.press('F2');
|
||||
const input=row('a.md').locator('input');
|
||||
await input.waitFor();
|
||||
assert.deepEqual(await input.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
|
||||
await page.screenshot({path:'.audit/rename-selection-'+theme+'.png'});
|
||||
await input.press('Escape');
|
||||
await row('notes').click();
|
||||
await row('notes').focus();
|
||||
await page.keyboard.press('F2');
|
||||
const folder=row('notes').locator('input');
|
||||
await folder.waitFor();
|
||||
assert.deepEqual(await folder.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,5,'notes']);
|
||||
await folder.press('Escape');
|
||||
await page.getByRole('tab',{name:'a.md',exact:true}).click();
|
||||
await page.getByRole('tab',{name:'a.md',exact:true}).click({button:'right'});
|
||||
await page.getByRole('menuitem',{name:'Rename…',exact:true}).click();
|
||||
const dialogInput=page.locator('#text-request');
|
||||
await dialogInput.waitFor();
|
||||
assert.deepEqual(await dialogInput.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
|
||||
await dialogInput.press('Escape');
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('Rename selection passed: file, folder, editor dialog, dark/wide and light/narrow.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,175 @@
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.clear();
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tab-menu-workspace";
|
||||
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
|
||||
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
window.tabMenuTest.calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
|
||||
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
|
||||
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
|
||||
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
|
||||
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
|
||||
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
|
||||
|
||||
|
||||
const output = '.audit/section-links';
|
||||
await mkdir(output, { recursive: true });
|
||||
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420/';
|
||||
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
|
||||
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
|
||||
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
|
||||
async function choose(group, value) {
|
||||
const control = page.getByRole('group', { name: group, exact: true });
|
||||
await control.hover();
|
||||
await control.locator(`[data-value="${value}"]`).click();
|
||||
}
|
||||
async function writerJump(label, line) {
|
||||
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
|
||||
await link.click({ modifiers: ['Control'] });
|
||||
await page.waitForFunction(async expected => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
const node = document.querySelector('.cm-content');
|
||||
const view = node ? EditorView.findFromDOM(node) : null;
|
||||
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
|
||||
}, line);
|
||||
}
|
||||
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
|
||||
async function top() {
|
||||
await page.locator('.cm-content').evaluate(async node => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
const view = EditorView.findFromDOM(node);
|
||||
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
|
||||
view.scrollDOM.scrollTop = 0;
|
||||
});
|
||||
}
|
||||
async function readerJump(label, text) {
|
||||
await page.locator('.reading a').filter({ hasText:label }).click();
|
||||
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
|
||||
await heading.waitFor();
|
||||
await page.waitForFunction(text => {
|
||||
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
|
||||
if (!heading) return false;
|
||||
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
|
||||
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
|
||||
}, text);
|
||||
}
|
||||
try {
|
||||
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
|
||||
await page.setViewportSize({ width, height:1000 });
|
||||
await page.goto(url);
|
||||
await page.evaluate(({ source, other }) => {
|
||||
window.tabMenuTest.files.set('a.md', source);
|
||||
window.tabMenuTest.files.set('other.md', other);
|
||||
}, { source, other });
|
||||
await page.locator('[data-tree-rel="a.md"]').click();
|
||||
await page.locator('.cm-content').waitFor();
|
||||
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
|
||||
if (width < 1000) {
|
||||
await page.getByRole('button', { name:'Files', exact:true }).click();
|
||||
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
|
||||
}
|
||||
await writerJump('Windows setup', await jumpLine('## Windows installer'));
|
||||
await top();
|
||||
await writerJump('Windows setup', await jumpLine('## Windows installer'));
|
||||
await top();
|
||||
await writerJump('macOS setup', await jumpLine('## macOS installer'));
|
||||
await top();
|
||||
await writerJump('Linux setup', await jumpLine('## Linux'));
|
||||
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
|
||||
await top();
|
||||
await page.locator('.writer-link').filter({ hasText:'Missing section' }).click({ modifiers:['Control'] });
|
||||
await page.getByText('Could not open #no-such-section', { exact:true }).waitFor();
|
||||
await top();
|
||||
await page.locator('.writer-link').filter({ hasText:'Other document' }).click({ modifiers:['Control'] });
|
||||
await page.getByRole('tab', { name:'other.md', exact:true }).waitFor();
|
||||
await page.waitForFunction(async () => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
const node = document.querySelector('.cm-content');
|
||||
const view = node ? EditorView.findFromDOM(node) : null;
|
||||
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
|
||||
});
|
||||
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
|
||||
await page.getByRole('tab', { name:'a.md', exact:true }).click();
|
||||
await top();
|
||||
await choose('Document view', 'read');
|
||||
await readerJump('Windows setup', 'Windows installer');
|
||||
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
|
||||
await choose('Document view', 'split');
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('Windows setup', 'Windows installer');
|
||||
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
|
||||
await choose('Document view', 'edit');
|
||||
await choose('Editor layout', 'Ide');
|
||||
await page.locator('.monaco-editor').waitFor();
|
||||
await choose('Document view', 'read');
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
|
||||
await choose('Document view', 'edit');
|
||||
await page.waitForFunction(() => {
|
||||
const node = document.querySelector('.monaco-editor .view-lines');
|
||||
return node?.textContent.includes('Linux');
|
||||
});
|
||||
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
|
||||
assert.equal(page.url(), url);
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), source);
|
||||
}
|
||||
|
||||
await page.goto(url);
|
||||
const folded = 'Start.\n\n[Jump to nested](#nested)\n\n[[#Nested|Wiki section]]\n\n# Parent\n\n' + filler + '\n## Nested\n\nDestination text.\n';
|
||||
await page.evaluate(text => window.tabMenuTest.files.set('a.md', text), folded);
|
||||
await page.locator('[data-tree-rel="a.md"]').click();
|
||||
await page.locator('.cm-content').waitFor();
|
||||
await page.getByRole('button', { name:'Collapse Parent', exact:true }).click();
|
||||
await writerJump('Jump to nested', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
|
||||
await top();
|
||||
await writerJump('Wiki section', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
|
||||
await choose('Document view', 'read');
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
|
||||
await page.getByRole('button', { name:'Collapse Parent', exact:true }).last().click();
|
||||
await readerJump('Jump to nested', 'Nested');
|
||||
await page.screenshot({ path:`${output}/folded-section-revealed.png` });
|
||||
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Section links passed: three reported headings, cross-file encoded duplicate, four views, both themes, wide/narrow.');
|
||||
} finally { await browser.close(); }
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
|
||||
const pluginCode = `export function activate(api) {
|
||||
let state = "Board state";
|
||||
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
|
||||
saveTabState: () => state, restoreTabState: value => { state = value; },
|
||||
mount(container) {
|
||||
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
|
||||
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
|
||||
return () => input.remove();
|
||||
}
|
||||
});
|
||||
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
|
||||
identify: (path, source) => source === "board document" ? { id: path } : null,
|
||||
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const params = new URLSearchParams(location.search);
|
||||
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
|
||||
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
|
||||
files.set("saved.board", "board document");
|
||||
if (params.has("missing")) files.delete("a.md");
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
|
||||
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
|
||||
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugin:dialog|message") return window.lifecycle.answer;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
|
||||
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, { pluginCode });
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const dragSources = new Map();
|
||||
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
|
||||
async function create(query = "") {
|
||||
const page = await context.newPage(); page.setDefaultTimeout(15000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
|
||||
}
|
||||
async function open(page, name) {
|
||||
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
|
||||
}
|
||||
async function openBoard(page) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
}
|
||||
async function pin(page, name) {
|
||||
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
}
|
||||
async function start(page, name) {
|
||||
const data = await tab(page, name).evaluate(node => {
|
||||
assertDraggable(node);
|
||||
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
|
||||
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
dragSources.set(data, { page, name });
|
||||
return data;
|
||||
}
|
||||
async function drop(page, data) {
|
||||
await bar(page).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer(); transfer.setData("application/x-runestone-tab", data);
|
||||
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
|
||||
node.dispatchEvent(new DragEvent("dragover", options)); node.dispatchEvent(new DragEvent("drop", options));
|
||||
}, data);
|
||||
const source = dragSources.get(data);
|
||||
if (source) {
|
||||
await tab(source.page, source.name).evaluateAll(nodes => nodes[0]?.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
}
|
||||
}
|
||||
async function screenshots(page, prefix) {
|
||||
await mkdir("output/tab-lifecycle", { recursive: true });
|
||||
for (const mode of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-${mode}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 700, height: 700 });
|
||||
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
}
|
||||
try {
|
||||
const page = await create();
|
||||
for (const name of ["a.md", "b.md", "c.md"]) await open(page, name);
|
||||
await tab(page, "c.md").focus(); await page.keyboard.press("Alt+Shift+ArrowLeft"); await page.keyboard.press("Alt+Shift+ArrowLeft");
|
||||
await pin(page, "b.md"); await tab(page, "b.md").click();
|
||||
await page.evaluate(() => window.lifecycle.close());
|
||||
const session = await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`)));
|
||||
assert.deepEqual(session.documents.map(item => item.path), ["c.md", "a.md", "b.md"]);
|
||||
assert.equal(session.activePath, "b.md"); assert.equal(session.documents[2].pinned, true);
|
||||
assert.ok(!JSON.stringify(session).includes("Saved text"));
|
||||
await page.goto(url + "?missing"); await tab(page, "b.md").waitFor();
|
||||
assert.deepEqual(await bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["c.md", "b.md"]);
|
||||
assert.equal(await tab(page, "b.md").getAttribute("aria-selected"), "true");
|
||||
await tab(page, "b.md").click({ button: "right" }); await page.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await page.keyboard.press("Escape");
|
||||
await screenshots(page, "restored-documents");
|
||||
await page.locator(".cm-content").fill("Unsaved draft");
|
||||
await page.evaluate(() => window.lifecycle.close());
|
||||
assert.deepEqual(await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`))), session);
|
||||
await page.evaluate(() => { window.lifecycle.answer = "Ok"; return window.lifecycle.close(); });
|
||||
page.on("dialog", dialog => dialog.accept());
|
||||
await page.reload(); await tab(page, "b.md").waitFor();
|
||||
assert.match(await page.locator(".cm-content").innerText(), /Saved text/);
|
||||
await open(page, "saved.board"); await page.getByText("Saved board document", { exact: true }).waitFor();
|
||||
await page.evaluate(() => window.lifecycle.close()); await page.reload();
|
||||
await tab(page, "saved").waitFor(); await page.getByText("Saved board document", { exact: true }).waitFor();
|
||||
const source = await create("?plugins"), target = await create("?plugins"), other = await create("?other"), disabled = await create("?plugins&disabled");
|
||||
assert.equal(await tab(other, "New tab").count(), 1);
|
||||
await openBoard(source); await source.getByRole("textbox", { name: "Board state" }).fill("Transferred board state"); await pin(source, "Board");
|
||||
let data = await start(source, "Board"); assert.ok(JSON.parse(data).tabTransfer);
|
||||
await drop(other, data); await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
|
||||
await drop(disabled, data); await disabled.getByText("Enable this tab's plugin before moving it to this window.").waitFor();
|
||||
assert.equal(await tab(source, "Board").count(), 1);
|
||||
await drop(target, data); await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
|
||||
await tab(target, "Board").click({ button: "right" }); await target.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await target.keyboard.press("Escape");
|
||||
await screenshots(target, "joined-plugin");
|
||||
data = await start(target, "Board"); await drop(source, data); await tab(target, "Board").waitFor({ state: "detached" });
|
||||
await openBoard(target); await target.getByRole("textbox", { name: "Board state" }).fill("Destination state");
|
||||
data = await start(source, "Board"); await drop(target, data);
|
||||
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Destination state"); assert.equal(await tab(source, "Board").count(), 1);
|
||||
await tab(source, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
await tab(source, "Board").click({ button: "right" }); await source.getByRole("menuitem", { name: "Open in new window", exact: true }).click();
|
||||
const token = await source.evaluate(() => window.lifecycle.transfer); assert.ok(token);
|
||||
const detached = await create(`?plugins&tabTransfer=${token}`); await detached.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
await tab(source, "Board").waitFor({ state: "detached" });
|
||||
data = await start(detached, "Board"); await drop(source, data); await tab(detached, "Board").waitFor({ state: "detached" });
|
||||
assert.equal(await source.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: normal-close restore, order, active tab, pins, missing files, workspace isolation, canceled close, disk-only restore, plugin documents, plugin join, duplicate protection, disabled plugin, and tear-out return");
|
||||
} catch (reason) {
|
||||
for (const page of context.pages()) console.error(page.url(), (await page.locator("body").innerText()).slice(-1000));
|
||||
throw reason;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,183 @@
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
|
||||
const pluginCode = `export function activate(api) {
|
||||
let state = "Board state";
|
||||
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
|
||||
saveTabState: () => state, restoreTabState: value => { state = value; },
|
||||
mount(container) {
|
||||
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
|
||||
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
|
||||
return () => input.remove();
|
||||
}
|
||||
});
|
||||
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
|
||||
identify: (path, source) => source === "board document" ? { id: path } : null,
|
||||
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const params = new URLSearchParams(location.search);
|
||||
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
|
||||
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
|
||||
files.set("saved.board", "board document");
|
||||
if (params.has("missing")) files.delete("a.md");
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
|
||||
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
|
||||
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugin:dialog|message") return window.lifecycle.answer;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
|
||||
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, { pluginCode });
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
|
||||
async function create(query = "") {
|
||||
const page = await context.newPage(); page.setDefaultTimeout(15000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
|
||||
}
|
||||
async function open(page, name) {
|
||||
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
|
||||
}
|
||||
async function openBoard(page) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
}
|
||||
async function pin(page, name) {
|
||||
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
}
|
||||
async function start(page, name) {
|
||||
const data = await tab(page, name).evaluate(node => {
|
||||
assertDraggable(node);
|
||||
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
|
||||
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
return data;
|
||||
}
|
||||
async function screenshots(page, prefix) {
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const mode of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-${mode}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 700, height: 700 });
|
||||
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
}
|
||||
const order = page => bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
|
||||
async function eventAt(page, data, point, type = "dragover", mime = "application/x-runestone-tab") {
|
||||
return page.evaluate(({ data, point, type, mime }) => {
|
||||
const transfer = new DataTransfer(); transfer.setData(mime, data);
|
||||
const node = document.elementFromPoint(point.x, point.y) || document.body;
|
||||
const event = new DragEvent(type, { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
|
||||
node.dispatchEvent(event);
|
||||
return event.defaultPrevented;
|
||||
}, { data, point, type, mime });
|
||||
}
|
||||
async function receive(page, data, point) {
|
||||
assert.equal(await eventAt(page, data, point), true);
|
||||
assert.equal(await eventAt(page, data, point, "drop"), true);
|
||||
}
|
||||
async function point(page, kind) {
|
||||
return page.locator(".header").evaluate((header, kind) => {
|
||||
const bounds = header.getBoundingClientRect();
|
||||
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
|
||||
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect();
|
||||
const first = header.querySelector('.tab').getBoundingClientRect();
|
||||
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
|
||||
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
|
||||
if (kind === "precise") return { x: bar.left + 2, y: bar.top + bar.height / 2 };
|
||||
if (kind === "controls") { const controls = header.querySelector('.window-controls').getBoundingClientRect(); return { x: controls.left + 10, y: controls.top + controls.height / 2 }; }
|
||||
if (kind === "blank") return { x: plus.right + 16, y: bounds.top + bounds.height / 2 };
|
||||
return { x: plus.left + plus.width / 2, y: plus.top + plus.height / 2 };
|
||||
}, kind);
|
||||
}
|
||||
try {
|
||||
const source = await create("?plugins"), target = await create("?plugins");
|
||||
await open(target, "b.md");
|
||||
await open(source, "a.md"); await pin(source, "a.md");
|
||||
await source.locator(".cm-content").fill("Unsaved ribbon transfer");
|
||||
let data = await start(source, "a.md •");
|
||||
const broad = await point(target, "blank");
|
||||
assert.equal(await eventAt(target, data, broad), true, "Blank titlebar space accepts transferred tabs");
|
||||
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), true);
|
||||
assert.equal(await eventAt(target, data, await point(target, "outside")), false, "The document body stays outside the drop target");
|
||||
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), false);
|
||||
assert.equal(await eventAt(target, data, await point(target, "controls")), false, "Window controls stay outside the drop target");
|
||||
assert.equal(await eventAt(target, data, broad, "dragover", "text/plain"), false, "Ordinary file and text drags retain their behavior");
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await target.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await eventAt(target, data, broad);
|
||||
await target.screenshot({ path: `output/tab-ribbon-drop/${mode}-blank-receiving.png` });
|
||||
}
|
||||
await receive(target, data, broad);
|
||||
await tab(target, "a.md •").waitFor(); await tab(source, "a.md •").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["b.md", "a.md •"]);
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved ribbon transfer/);
|
||||
assert.ok(await tab(target, "a.md •").getAttribute("aria-describedby"));
|
||||
await open(source, "c.md"); data = await start(source, "c.md");
|
||||
await receive(target, data, await point(target, "precise"));
|
||||
await tab(target, "c.md").waitFor(); await tab(source, "c.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •"]);
|
||||
await openBoard(source); await pin(source, "Board"); await source.getByRole("textbox", { name: "Board state" }).fill("Plugin ribbon state");
|
||||
data = await start(source, "Board");
|
||||
await target.setViewportSize({ width: 700, height: 700 });
|
||||
const nearby = await point(target, "near");
|
||||
await eventAt(target, data, nearby);
|
||||
await bar(target).and(target.locator('.receiving')).waitFor();
|
||||
await target.screenshot({ path: "output/tab-ribbon-drop/narrow-near-receiving.png" });
|
||||
await receive(target, data, nearby);
|
||||
await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •", "Board"]);
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Plugin ribbon state");
|
||||
assert.ok(await tab(target, "Board").getAttribute("aria-describedby"));
|
||||
await screenshots(target, "ribbon-plugin-pinned");
|
||||
data = await start(target, "Board");
|
||||
assert.equal(await eventAt(target, data, await point(target, "near")), false, "Same-window reordering stays precise");
|
||||
await receive(target, data, await point(target, "precise"));
|
||||
assert.deepEqual(await order(target), ["Board", "c.md", "b.md", "a.md •"]);
|
||||
await tab(target, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: broad titlebar and nearby ribbon drops, exact tab ordering, rejection outside the ribbon and over window controls, ordinary drag isolation, pinned unsaved documents, narrow plugin transfers, and source acknowledgement");
|
||||
} catch (error) {
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `output/tab-ribbon-drop/failure-${index}.png` });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["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"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_rename") {
|
||||
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
|
||||
if (!files.has(args.from)) throw new Error("File is missing");
|
||||
if (files.has(args.to)) throw new Error("A file with that name already exists");
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return window.__TEST__.answer ?? "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem('runestone.settings',JSON.stringify({autosaveEnabled:false}));
|
||||
const {files}=window.__TEST__; files.clear();
|
||||
files.set('projects/source.md','# Source\n\n[[Target]]\n');
|
||||
files.set('archive/deep/Target.md','# Target\n');
|
||||
files.set('other.md','# Other\n\n[Target](archive/deep/Target.md)\n');
|
||||
});
|
||||
async function openNote(name) {
|
||||
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.getByRole('textbox',{name:'Writing editor',exact:true}).waitFor();
|
||||
}
|
||||
const backlink=path=>page.getByRole('button',{name:'Open '+path+', line 3',exact:true});
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL||'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace',{exact:true}).waitFor();
|
||||
await openNote('projects/source.md');
|
||||
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
|
||||
await page.getByRole('tab',{name:'Target.md',exact:true}).waitFor();
|
||||
await backlink('projects/source.md').waitFor();
|
||||
await backlink('other.md').waitFor();
|
||||
assert.equal(await page.getByRole('tab',{name:'source.md',exact:true}).count(),1);
|
||||
await page.screenshot({path:'.audit/workspace-links-dark.png'});
|
||||
await backlink('projects/source.md').click();
|
||||
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='projects/source.md');
|
||||
const writer=page.getByRole('textbox',{name:'Writing editor',exact:true});
|
||||
await writer.focus(); await page.keyboard.press('Control+Home'); await page.keyboard.press('Control+a'); await page.keyboard.type('# Source\n\nNo links now.');
|
||||
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
|
||||
await page.waitForFunction(()=>!document.querySelector('button[aria-label="Open projects/source.md, line 3"]'));
|
||||
await backlink('other.md').waitFor();
|
||||
await page.evaluate(()=>{
|
||||
window.__TEST__.files.set('duplicates/Target.md','# Another target');
|
||||
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['duplicates/Target.md']});
|
||||
});
|
||||
await page.waitForTimeout(350);
|
||||
await openNote('other.md');
|
||||
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
|
||||
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
|
||||
await page.evaluate(()=>{
|
||||
window.__TEST__.files.set('wiki.md','# Wiki\n\n[[Target]]\n');
|
||||
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['wiki.md']});
|
||||
});
|
||||
await openNote('wiki.md');
|
||||
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
|
||||
await page.locator('.status').filter({hasText:'More than one note matches Target'}).waitFor();
|
||||
assert.equal(await page.locator('.breadcrumb').textContent(),'wiki.md');
|
||||
await page.evaluate(()=>{
|
||||
window.__TEST__.files.delete('duplicates/Target.md');
|
||||
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'remove',paths:['duplicates/Target.md']});
|
||||
});
|
||||
await page.waitForTimeout(350);
|
||||
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
|
||||
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
|
||||
await backlink('wiki.md').waitFor();
|
||||
await page.evaluate(()=>{
|
||||
const {files,emit,root}=window.__TEST__;
|
||||
files.set('moved/wiki.md',files.get('wiki.md')); files.delete('wiki.md');
|
||||
emit('workspace-event',{root,kind:'rename',paths:['wiki.md','moved/wiki.md']});
|
||||
});
|
||||
await backlink('moved/wiki.md').waitFor();
|
||||
assert.equal(await backlink('wiki.md').count(),0);
|
||||
await page.evaluate(()=>{window.__TEST__.answer='Ok';});
|
||||
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).click();
|
||||
await page.keyboard.press('Control+w');
|
||||
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).waitFor({state:'detached'});
|
||||
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
|
||||
await backlink('projects/source.md').waitFor();
|
||||
await page.setViewportSize({width:620,height:850});
|
||||
await page.evaluate(()=>{document.documentElement.dataset.theme='light';});
|
||||
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
|
||||
await page.screenshot({path:'.audit/workspace-links-narrow.png'});
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('Workspace link integration passed: workspace wiki resolution, new tabs, backlinks navigation, live edits, discarded drafts, creation, move, deletion and duplicate guard.');
|
||||
}finally{await browser.close();}
|
||||
|
||||
Reference in New Issue
Block a user