feat(canvas): fix rotation, clarify frame membership and load icons on demand

This commit is contained in:
2026-11-06 13:56:15 +08:00
parent 77d1b3ec86
commit 83021d0f6c
120 changed files with 817 additions and 100 deletions
+9 -1
View File
@@ -130,6 +130,14 @@ try {
assert.equal(response.status, 200, asset);
assert.deepEqual(Buffer.from(await response.arrayBuffer()), await readFile(new URL(asset, brandRoot)), asset);
}
const iconManifest = JSON.parse(await readFile(new URL("../src/lib/canvas-icon-assets.json", import.meta.url), "utf8"));
for (const file of Object.values(iconManifest.assets)) {
const path = iconManifest.root + "/" + file;
const response = await fetch(host + path);
assert.equal(response.status, 200, path);
assert.match(response.headers.get("cache-control"), /max-age=31536000.*immutable/);
assert.deepEqual(await response.json(), JSON.parse(await readFile(new URL("../public" + path, import.meta.url), "utf8")));
}
assert.equal((await fetch(host + "/missing-page")).status, 404);
const res = await fetch(host + "/api/foundry/auth/login", {
method: "POST",
@@ -303,7 +311,7 @@ try {
assert.equal(await logout.text(), "");
assert.match(logout.headers.get("set-cookie"), /Max-Age=0/);
console.log(
"PASS: Canvas GET/PATCH and independent versions, ETag/If-Match, 1+ MiB snapshot restore, conflict and 5 MiB limit, four ID/slug combinations, authenticated home redirect, anonymous and expired-session landing, canvas-free dashboard, 88 original brand assets, favicon metadata, avatar and profile updates, App Router pages and metadata, body validation, method and query filtering, OAuth redirects, logout, session cookie, token removal, authenticated proxy, invalid session, cross-origin rejection, path allowlist, OAuth validation",
"PASS: Canvas GET/PATCH and independent versions, ETag/If-Match, 1+ MiB snapshot restore, conflict and 5 MiB limit, four ID/slug combinations, authenticated home redirect, anonymous and expired-session landing, canvas-free dashboard, 88 original brand assets, 97 hashed icon shards with immutable caching, favicon metadata, avatar and profile updates, App Router pages and metadata, body validation, method and query filtering, OAuth redirects, logout, session cookie, token removal, authenticated proxy, invalid session, cross-origin rejection, path allowlist, OAuth validation",
);
} finally {
const exited = once(app, "exit");
+16 -1
View File
@@ -1,7 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { canvasReducer, decodeCanvas, emptyCanvas, makeCanvasNode } from "../src/lib/canvas.ts";
import { assignFrameMembership } from "../src/lib/canvas-frames.ts";
import { assignFrameMembership, frameDropFeedback } from "../src/lib/canvas-frames.ts";
function seeded() {
const frame = makeCanvasNode("frame", { x: 100, y: 100 });
@@ -11,6 +11,21 @@ function seeded() {
}
function state(document) { return { past: [], present: document, future: [] }; }
test("drop previews match actual assignment for every content type, exits and overlapping frames", () => {
const { frame } = seeded();
const smaller = makeCanvasNode("frame", { x: 120, y: 120 }); smaller.width = 300; smaller.height = 240;
for (const kind of ["text", "script", "image", "plain-text", "plain-image", "icon"]) {
const node = makeCanvasNode(kind, { x: 140, y: 140 });
const nodes = [frame, smaller, node];
let preview = frameDropFeedback(nodes, [node.id, frame.id]);
assert.equal(preview.length, 1); assert.equal(preview[0].to, smaller.id);
assert.equal(preview[0].to, assignFrameMembership(nodes, [node.id])[2].data.frameId);
node.data.frameId = smaller.id; node.position = { x: 2000, y: 2000 };
preview = frameDropFeedback(nodes, [node.id]); assert.equal(preview[0].from, smaller.id); assert.equal(preview[0].to, undefined);
assert.equal(assignFrameMembership(nodes, [node.id])[2].data.frameId, undefined);
}
});
test("only dropped content joins a frame; pre-existing overlapping content stays outside", () => {
const { frame, member, outsider, document } = seeded();
assert.equal(document.nodes[1].data.frameId, undefined);
+87
View File
@@ -0,0 +1,87 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import catalog from "../src/components/canvas/icon-catalog-data.json" with { type: "json" };
import manifest from "../src/lib/canvas-icon-assets.json" with { type: "json" };
import { iconAsset, validateIconShard } from "../src/lib/canvas-icon-loader.ts";
import { decodeCanvas, emptyCanvas, makeCanvasNode } from "../src/lib/canvas.ts";
import { createResourceLoader } from "../src/lib/resource-loader.ts";
test("all Lucide and experimental Tabler IDs map to valid local shards and survive snapshots", async () => {
assert.equal(catalog.filter((icon) => icon.source === "lucide").length, 2313);
assert.equal(catalog.filter((icon) => icon.source === "tabler").length, 24);
assert.equal(new Set(catalog.map((icon) => icon.name)).size, catalog.length);
const loaded = new Map();
for (const asset of Object.values(manifest.assets)) {
const content = await readFile(`public${manifest.root}/${asset}`, "utf8");
assert.ok(asset.includes(createHash("sha256").update(content.trimEnd()).digest("hex").slice(0, 12)));
loaded.set(`${manifest.root}/${asset}`, validateIconShard(JSON.parse(content)));
assert.ok(Buffer.byteLength(content) < 20_000, asset);
}
for (const icon of catalog) {
assert.ok(loaded.get(iconAsset(icon.name))[icon.name]);
assert.ok(icon.categories.every((category) => ["arrows", "people", "office", "media", "tech", "business", "nature", "travel", "shapes"].includes(category)));
}
for (const name of ["Star", "TablerAlien", "TablerCube3dSphere"]) {
assert.ok(catalog.some((icon) => icon.name === name));
const node = makeCanvasNode("icon", { x: 0, y: 0 }); node.data.icon = name;
assert.equal(decodeCanvas(JSON.stringify({ ...emptyCanvas(), nodes: [node] })).nodes[0].data.icon, name);
}
});
test("icon data rejects executable shapes, events and external paint references", () => {
for (const node of [["script", {}], ["path", { onload: "alert(1)" }], ["path", { fill: "url(https://example.com)" }], ["use", { href: "bad" }]]) {
assert.throws(() => validateIconShard({ Star: [node] }));
}
});
const tick = () => new Promise((resolve) => setImmediate(resolve));
test("an immediately unmounted icon does not start a network request", async () => {
let calls = 0;
const loader = createResourceLoader(async () => { calls++; return "unused"; });
const controller = new AbortController();
const pending = loader.request("unused", controller.signal);
const rejected = assert.rejects(pending, { name: "AbortError" });
controller.abort(); await rejected; await tick();
assert.equal(calls, 0); assert.equal(loader.peek("unused"), undefined);
});
test("loader bounds concurrency, deduplicates shared shards and reuses cache", async () => {
let active = 0, peak = 0, calls = 0;
const finish = [];
const loader = createResourceLoader(async (key) => {
active++; peak = Math.max(peak, active); calls++;
await new Promise((resolve) => finish.push(resolve)); active--; return key;
}, 2, 3);
const a = loader.request("a"), duplicate = loader.request("a"), b = loader.request("b"), c = loader.request("c");
await tick(); assert.equal(calls, 2);
finish.splice(0).forEach((resolve) => resolve()); await tick();
assert.equal(calls, 3); finish.splice(0).forEach((resolve) => resolve());
assert.deepEqual(await Promise.all([a, duplicate, b, c]), ["a", "a", "b", "c"]);
assert.equal(await loader.request("a"), "a"); assert.equal(calls, 3); assert.equal(peak, 2);
});
test("unused queued loads never start; a remaining subscriber keeps a shared load alive", async () => {
const seen = []; let release;
const loader = createResourceLoader(async (key) => { seen.push(key); if (key === "a") await new Promise((resolve) => release = resolve); return key; }, 1);
const first = new AbortController(), queued = new AbortController();
const a = loader.request("a", first.signal), shared = loader.request("a");
const b = loader.request("b", queued.signal);
const rejected = Promise.all([assert.rejects(a, { name: "AbortError" }), assert.rejects(b, { name: "AbortError" })]);
await tick(); first.abort(); queued.abort(); release();
await rejected; assert.equal(await shared, "a"); await tick(); assert.deepEqual(seen, ["a"]);
});
test("active aborts and failed requests can retry; least recently used cache is bounded", async () => {
let fail = true;
const loader = createResourceLoader(async (key, signal) => {
if (key === "abort") return new Promise((_, reject) => signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true }));
if (key === "fail" && fail) { fail = false; throw new Error("offline"); } return key;
}, 1, 2);
const controller = new AbortController(); const pending = loader.request("abort", controller.signal);
const rejected = assert.rejects(pending, { name: "AbortError" }); await tick(); controller.abort(); await rejected; await tick();
await assert.rejects(loader.request("fail"), /offline/); await tick(); assert.equal(await loader.request("fail"), "fail");
await loader.request("a"); await loader.request("b");
assert.equal(loader.peek("fail"), undefined); assert.equal(loader.peek("a"), "a");
});
+137
View File
@@ -0,0 +1,137 @@
// Isolated DOM regression check; no browser or dev server is used.
// npm install --prefix /tmp/canvas-ui-tools --ignore-scripts esbuild jsdom
// CANVAS_UI_TOOLS=/tmp/canvas-ui-tools node tests/canvas-ui-check.mjs
import assert from "node:assert/strict";
import { createRequire } from "node:module";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { resolve } from "node:path";
const tools = createRequire(resolve(process.env.CANVAS_UI_TOOLS || "/tmp/canvas-ui-tools", "package.json"));
const { JSDOM } = tools("jsdom");
const { build, stop } = tools("esbuild");
const dom = new JSDOM('<!doctype html><html><body><div id="app"></div></body></html>', { url: "http://localhost", pretendToBeVisual: true });
const { window } = dom;
// React's async act creates MessageChannels; track and close test-owned ports.
const NativeMessageChannel = globalThis.MessageChannel;
const channels = [];
globalThis.MessageChannel = class extends NativeMessageChannel { constructor() { super(); channels.push(this); } };
for (const key of ["window", "document", "HTMLElement", "Element", "Node", "SVGElement", "Event", "MouseEvent", "KeyboardEvent", "MutationObserver", "localStorage", "getComputedStyle"]) Object.defineProperty(globalThis, key, { value: key === "window" ? window : typeof window[key] === "function" && key === "getComputedStyle" ? window[key].bind(window) : window[key], configurable: true });
Object.defineProperty(globalThis, "navigator", { value: window.navigator, configurable: true });
globalThis.requestAnimationFrame = window.requestAnimationFrame.bind(window);
globalThis.cancelAnimationFrame = window.cancelAnimationFrame.bind(window);
window.matchMedia = () => ({ matches: false, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {} });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
globalThis.DOMMatrixReadOnly = window.DOMMatrixReadOnly = class { m22 = 1; };
class PointerEvent extends window.MouseEvent { constructor(type, init = {}) { super(type, init); this.pointerId = init.pointerId || 1; this.isPrimary = true; this.pointerType = "mouse"; } }
globalThis.PointerEvent = window.PointerEvent = PointerEvent;
const captures = new WeakMap();
window.HTMLElement.prototype.setPointerCapture = function (id) { captures.set(this, id); };
window.HTMLElement.prototype.hasPointerCapture = function (id) { return captures.get(this) === id; };
window.HTMLElement.prototype.releasePointerCapture = function () { captures.delete(this); };
const width = (element) => parseFloat(element.style.width) || (element.className?.includes?.("react-flow__node") ? 260 : 1200);
const height = (element) => parseFloat(element.style.height) || (element.getAttribute("aria-label") === "图标列表" ? 192 : element.className?.includes?.("react-flow__node") ? 200 : 800);
for (const [key, get] of [["offsetWidth", width], ["offsetHeight", height], ["clientWidth", width], ["clientHeight", height]]) Object.defineProperty(window.HTMLElement.prototype, key, { get() { return get(this); } });
window.HTMLElement.prototype.getBoundingClientRect = function () { return { x: 0, y: 0, left: 0, top: 0, width: width(this), height: height(this), right: width(this), bottom: height(this) }; };
globalThis.ResizeObserver = window.ResizeObserver = class {
constructor(callback) { this.callback = callback; }
observe(element) { this.callback([{ target: element, contentRect: element.getBoundingClientRect() }]); }
unobserve() {} disconnect() {}
};
const requests = [];
globalThis.fetch = async (url, options) => {
requests.push(String(url));
assert.ok(String(url).startsWith("/canvas-icons/"), `Unexpected network request ${url}`);
if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");
return new Response(await readFile(resolve("public", String(url).slice(1))), { headers: { "Content-Type": "application/json" } });
};
const folder = await mkdtemp(resolve(tmpdir(), "endoleap-canvas-ui-"));
try {
const outfile = resolve(folder, "fixture.cjs");
await build({
stdin: { contents: 'export { default as GraphCanvas } from "./src/components/canvas/graph-canvas"; export { IconPicker } from "./src/components/canvas/icon-picker"; export { makeCanvasNode, emptyCanvas } from "./src/lib/canvas"; export { createRoot } from "react-dom/client"; export { act, createElement } from "react";', resolveDir: process.cwd(), loader: "tsx" },
outfile, bundle: true, platform: "node", format: "cjs", jsx: "automatic", logLevel: "silent", nodePaths: [resolve("node_modules")],
loader: { ".css": "empty" },
plugins: [{ name: "dynamic-component", setup(build) {
build.onResolve({ filter: /^next\/dynamic$/ }, () => ({ path: "dynamic", namespace: "fixture" }));
build.onLoad({ filter: /.*/, namespace: "fixture" }, () => ({ contents: 'import React from "react"; export default function dynamic(loader) { const Component = React.lazy(loader); return function Dynamic(props) { return React.createElement(React.Suspense, {fallback:null}, React.createElement(Component,props)); }; }', resolveDir: process.cwd() }));
if (process.env.ROTATION_BASELINE === "1") build.onLoad({ filter: /node-style-toolbar\.tsx$/ }, async ({ path }) => ({ contents: (await readFile(path, "utf8")).replace('onClick={(event) => event.stopPropagation()}', ''), loader: "tsx" }));
} }],
});
const { GraphCanvas, IconPicker, makeCanvasNode, emptyCanvas, act, createElement: h, createRoot } = createRequire(import.meta.url)(outfile);
const root = createRoot(document.querySelector("#app"));
const tick = () => new Promise((resolve) => setTimeout(resolve, 30));
const event = async (target, type, init = {}) => { assert.ok(target, `Missing target for ${type}`); await act(async () => { const Type = type.startsWith("pointer") ? PointerEvent : type.startsWith("key") ? window.KeyboardEvent : window.MouseEvent; target.dispatchEvent(new Type(type, { bubbles: true, cancelable: true, view: window, ...init })); await tick(); }); };
const node = makeCanvasNode("text", { x: 100, y: 100 }); node.id = "text-one";
const frameNode = makeCanvasNode("frame", { x: 500, y: 100 }); frameNode.id = "frame-one"; frameNode.data.title = "分区 A";
localStorage.setItem("endoleap_canvas_v1:w:b", JSON.stringify({ ...emptyCanvas(), nodes: [node, frameNode] }));
await act(async () => { root.render(h(GraphCanvas, { board: { id: "b", workspace_id: "w", kind: "board", title: "test", version: 1 } })); await tick(); });
await event(document.querySelector('[data-id="text-one"]'), "click");
const toggle = () => document.querySelector('[aria-label="旋转模式"]');
await event(toggle(), "click");
if (process.env.ROTATION_BASELINE === "1") {
assert.equal(toggle().getAttribute("aria-pressed"), "false", "Baseline should reproduce immediate cancellation");
console.log("PASS baseline: portal click cancels rotation before the fix");
} else {
assert.equal(toggle().getAttribute("aria-pressed"), "true", "Portal click must keep rotation active");
const frame = document.querySelector('[data-id="text-one"] [style*="rotate("]');
await event(frame, "pointerdown", { clientX: 330, clientY: 200, button: 0 });
await event(frame, "pointermove", { clientX: 230, clientY: 300, buttons: 1 });
await event(frame, "pointerup", { clientX: 230, clientY: 300 });
assert.ok(frame.style.transform.includes("90deg"), frame.style.transform);
await event(window, "keydown", { key: "Escape" });
assert.equal(toggle().getAttribute("aria-pressed"), "false");
await event(document.querySelector('[aria-label="撤销"]'), "click");
assert.ok(frame.style.transform.includes("0deg"));
await event(document.querySelector('[aria-label="重做"]'), "click");
assert.ok(frame.style.transform.includes("90deg"));
assert.equal(requests.length, 0, "Closed picker and text-only board must not load icon shapes");
console.log("PASS rotation: portal click, pointer rotation, Escape, undo and redo");
const textNode = document.querySelector('.react-flow__node[data-id="text-one"]');
await event(textNode, "mousedown", { clientX: 200, clientY: 200, button: 0, buttons: 1 });
await event(window, "mousemove", { clientX: 210, clientY: 200, buttons: 1 });
await event(window, "mousemove", { clientX: 700, clientY: 200, buttons: 1 });
assert.ok(document.body.textContent.includes("松开加入"), "Dragging over a frame must preview membership");
await event(window, "mouseup", { clientX: 700, clientY: 200, button: 0 });
assert.ok(document.querySelector('[title="属于:分区 A"]'));
assert.ok(document.querySelector('[role="status"]').textContent.includes("已加入「分区 A」"));
assert.ok(document.querySelector('.react-flow__node[data-id="frame-one"]').textContent.includes("1 项"));
await event(textNode, "mousedown", { clientX: 700, clientY: 200, button: 0, buttons: 1 });
await event(window, "mousemove", { clientX: 690, clientY: 200, buttons: 1 });
await event(window, "mousemove", { clientX: 200, clientY: 200, buttons: 1 });
assert.ok(document.body.textContent.includes("松开移出"));
await event(window, "mouseup", { clientX: 200, clientY: 200, button: 0 });
assert.equal(document.querySelector('[title="属于:分区 A"]'), null);
assert.ok(document.querySelector('[role="status"]').textContent.includes("已移出「分区 A」"));
console.log("PASS frames: actual drag previews, membership badge, count and join/leave announcements");
let choice;
await act(async () => { root.render(h(IconPicker, { close() {}, choose(name) { choice = name; } })); await tick(); });
await act(async () => { await tick(); });
const grid = document.querySelector('[aria-label="图标列表"]');
assert.ok(grid.querySelectorAll("button").length <= 30);
const commonRequests = requests.length; assert.ok(commonRequests > 0 && commonRequests < 30);
const source = document.querySelector('[aria-label="图标库"]');
await act(async () => { source.value = "tabler"; source.dispatchEvent(new window.Event("change", { bubbles: true })); await tick(); });
await act(async () => { await tick(); });
assert.equal(grid.querySelectorAll("button").length, 24);
assert.equal(requests.filter((url) => url.split("/").at(-1).startsWith("tabler-")).length, 1, "Tabler shares one cached 24-icon shard");
await event(grid.querySelector('[data-icon-id="TablerAlien"]'), "click");
assert.equal(choice, "TablerAlien");
await act(async () => { source.value = "lucide"; source.dispatchEvent(new window.Event("change", { bubbles: true })); await tick(); });
await event([...document.querySelectorAll('[aria-label="图标分类"] button')].find((button) => button.textContent === "全部"), "click");
await act(async () => { grid.scrollTop = 4800; grid.dispatchEvent(new window.Event("scroll", { bubbles: true })); await tick(); });
assert.ok(grid.querySelectorAll("button").length <= 30, "Long scrolling must not accumulate DOM");
assert.ok(Number(grid.querySelector("button").dataset.index) >= 490, "Scroll should render a different window");
assert.ok(new Set(requests).size < 97, "Scrolling one window must not load the entire library");
await event([...document.querySelectorAll('[aria-label="图标分类"] button')].find((button) => button.textContent === "科技与设备"), "click");
assert.equal(grid.querySelector("button").dataset.index, "0", "Category change resets virtual window");
console.log("PASS picker: bounded DOM, on-demand data, shared Tabler load and selection");
}
await act(async () => { root.unmount(); await tick(); });
} finally {
await rm(folder, { recursive: true, force: true }); window.close(); stop();
for (const channel of channels) { channel.port1.close(); channel.port2.close(); }
globalThis.MessageChannel = NativeMessageChannel;
}