An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Improve mind map routing and interaction and clean stale metadata https://github.com/siyuan-note/siyuan/issues/18831
Vanessa5132f81ac5e6
diff --git a/app/src/assets/scss/protyle/_list-mindmap.scss b/app/src/assets/scss/protyle/_list-mindmap.scssindex 653bfcfdb3..1f96a0fff3 100644--- a/app/src/assets/scss/protyle/_list-mindmap.scss+++ b/app/src/assets/scss/protyle/_list-mindmap.scss@@ -151,8 +151,8 @@min-width: 64px;max-width: 300px;width: max-content;- min-height: 36px;- padding: 7px 12px;+ min-height: 32px;+ padding: 4px 12px;box-sizing: border-box;border: 0;border-radius: var(--b3-border-radius);@@ -238,7 +238,8 @@}}- > .p {+ > .p,+ > .p.list-mindmap__preview-block {margin: 0;padding: 0;font-size: inherit;diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.tsindex 07f306aefc..e7ead47a24 100644--- a/app/src/protyle/render/listMindmap/editor.test.ts+++ b/app/src/protyle/render/listMindmap/editor.test.ts@@ -268,10 +268,13 @@ const browserCases = async (sourceCode: string, css: string) => {parseFloat(getComputedStyle(fixture.querySelector(".p")).fontSize), "heading keeps shared font size");for (const text of ["Test text", '<span data-type="strong">11pppppp</span>', "First<br>Second", "First\nSecond",'<span data-type="strong">1水电费ppppp</span>', '<span data-type="strong">1水电费pppppp</span>']) {- fixture.innerHTML = `<div data-node-id="list" data-type="NodeList"><div class="list-mindmap"><div class="list-mindmap__node"><div class="list-mindmap__content"><div class="p"><div class="list-mindmap__text">${text}</div></div></div></div></div></div>`;+ fixture.innerHTML = `<div data-node-id="list" data-type="NodeList"><div class="list-mindmap"><div class="list-mindmap__node"><div class="list-mindmap__content"><div class="p list-mindmap__preview-block" data-type="NodeParagraph"><div class="list-mindmap__text">${text}</div></div></div></div></div></div>`;const node = fixture.querySelector<HTMLElement>(".list-mindmap__node");const content = fixture.querySelector<HTMLElement>(".list-mindmap__content");const before = {width: node.offsetWidth, height: node.offsetHeight};+ if (text === "Test text") {+ check.equal(before.height, 32, "single-line previews do not inherit extra block spacing");+ }const preview = content.innerHTML;for (const scale of [1, 0.65, 1.5]) {fixture.style.transform = `scale(${scale})`;diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.tsindex b6bf94830d..741e08c623 100644--- a/app/src/protyle/render/listMindmap/model.test.ts+++ b/app/src/protyle/render/listMindmap/model.test.ts@@ -254,8 +254,12 @@ const browserCases = async (sourceCode: string, css: string) => {// 复制后关系线与节点样式引用新块 ID,遇到任一损坏配置时不进行部分迁移。list.setAttribute("custom-sy-list-mindmap-data", JSON.stringify({version: 1, extension: "keep",- nodes: {a: {bold: true}, b: {italic: true}},- relations: [{id: "relation", from: "a", to: "b", label: "keep"}]}));+ nodes: {a: {bold: true}, b: {italic: true}, deleted: {bold: true}},+ relations: [{id: "relation", from: "a", to: "b", label: "keep"},+ {id: "orphan", from: "a", to: "deleted", label: "remove"}]}));+ const copiedItems = list.querySelectorAll('[data-type="NodeListItem"]');+ copiedItems[0].setAttribute("data-node-id", "new-a");+ copiedItems[1].setAttribute("data-node-id", "new-b");const child = list.querySelector('[data-type="NodeList"]');child.setAttribute("custom-sy-list-mindmap-data", '{"version":2,"nodes":{},"relations":[]}');const beforeRemap = list.outerHTML;@@ -331,6 +335,24 @@ const browserCases = async (sourceCode: string, css: string) => {HTMLElement.prototype.hasPointerCapture = () => false;HTMLElement.prototype.releasePointerCapture = () => undefined;const nodeElement = (id: string) => host.querySelector<HTMLElement>(`[data-mindmap-id="${id}"]`);+ const compactNode = nodeElement(alpha);+ compactNode.style.minHeight = "0";+ compactNode.style.height = "32px";+ view.refreshLayout();+ await settle();+ check.equal(view.positions.get(alpha).height, compactNode.offsetHeight,+ "connection geometry uses the actual compact node height");+ const compactPositions = JSON.stringify([...view.positions]);+ view.setEditing(alpha);+ await settle();+ check.equal(JSON.stringify([...view.positions]), compactPositions, "entering edit mode preserves connection geometry");+ view.setEditing(undefined);+ await settle();+ check.equal(JSON.stringify([...view.positions]), compactPositions, "leaving edit mode preserves connection geometry");+ compactNode.style.minHeight = "";+ compactNode.style.height = "";+ view.refreshLayout();+ await settle();const sendPointer = (element: Element, type: string, x: number, y: number) => element.dispatchEvent(new PointerEvent(type, {bubbles: true, cancelable: true, pointerId: 1, pointerType: "mouse", button: 0, clientX: x, clientY: y,}));@@ -338,7 +360,7 @@ const browserCases = async (sourceCode: string, css: string) => {const targetRect = nodeElement(beta).getBoundingClientRect();const sourcePoint = {x: sourceRect.left + sourceRect.width / 2, y: sourceRect.top + sourceRect.height / 2};const targetPoint = {x: targetRect.left + targetRect.width / 2, y: targetRect.top + targetRect.height / 2};- check.ok(sourceRect.width >= 64 && sourceRect.height >= 36);+ check.ok(sourceRect.width >= 64 && sourceRect.height >= 32);check.equal(host.querySelector("[data-node-id]"), null);sendPointer(nodeElement(alpha), "pointerdown", sourcePoint.x, sourcePoint.y);sendPointer(viewport, "pointerup", sourcePoint.x, sourcePoint.y);@@ -671,6 +693,40 @@ const browserCases = async (sourceCode: string, css: string) => {check.equal(inspector.hidden, true);check.equal(host.querySelector(".list-mindmap__relation--selected"), null);+ const savedRelations = model.metadata.relations;+ model.metadata.relations = [+ {id: "forward", from: alpha, to: beta, label: ""},+ {id: "reverse", from: beta, to: alpha, label: ""},+ ];+ view.update(model);+ await settle();+ for (const scale of [0.5, 1, 2]) {+ view.scale = scale;+ view.draw();+ for (const id of ["forward", "reverse"]) {+ const end = view.linePaths.find((line: any) => line.id === id).end;+ const bounds = viewport.getBoundingClientRect();+ const x = bounds.left + view.offsetX + end.x * scale;+ const y = bounds.top + view.offsetY + end.y * scale;+ sendPointer(viewport, "pointermove", x, y);+ check.equal(view.hoveredLine, `relation:${id}`, "each arrow highlights its own direction");+ sendPointer(viewport, "pointerdown", x, y);+ sendPointer(viewport, "pointerup", x, y);+ check.equal(view.selectedRelation, id, "overlapping reverse relations can be selected independently");+ viewport.dispatchEvent(new MouseEvent("dblclick", {clientX: x, clientY: y, bubbles: true}));+ const input = host.querySelector<HTMLInputElement>(".list-mindmap__relation-editor");+ check.ok(input, "double-clicking either arrow edits that relation");+ input.value = id;+ input.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", bubbles: true}));+ check.deepEqual(relationChanges[relationChanges.length - 1], [id, {label: id}]);+ pressDelete();+ check.equal(relationDeletions[relationDeletions.length - 1], id);+ }+ }+ view.scale = 1;+ model.metadata.relations = savedRelations;+ view.update(model);+// 全屏使用编辑器同款窗口内布局,不调用浏览器全屏,并在退出和销毁时恢复原位置。Object.defineProperty(host, "requestFullscreen", {configurable: true, value: () => check.fail("Native fullscreen must not be requested")});hostParent.style.transform = "translateX(5px)";diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.tsindex ea99a45f0c..8c104ec367 100644--- a/app/src/protyle/render/listMindmap/model.ts+++ b/app/src/protyle/render/listMindmap/model.ts@@ -136,9 +136,14 @@ export const remapListMindmapIDs = (root: Element, ids: Map<string, string>) =>}const updates = lists.map(list => {const metadata = parseListMindmapMetadata(list.getAttribute(LIST_MINDMAP_META_ATTRIBUTE));+ const validIds = new Set(readListMindmap(list).nodes.keys());+ validIds.add(list.dataset.nodeId);const nodes: Record<string, ListMindmapNodeStyle> = Object.create(null);Object.entries(metadata.nodes).forEach(([id, style]) => {const mappedId = ids.get(id) || id;+ if (!validIds.has(mappedId)) {+ return;+ }if (Object.prototype.hasOwnProperty.call(nodes, mappedId)) {throw new Error("Duplicate copied list mindmap identity");}@@ -148,7 +153,7 @@ export const remapListMindmapIDs = (root: Element, ids: Map<string, string>) =>...relation,from: ids.get(relation.from) || relation.from,to: ids.get(relation.to) || relation.to,- }))}};+ })).filter(relation => validIds.has(relation.from) && validIds.has(relation.to))}};});updates.forEach(({list, metadata}) => list.setAttribute(LIST_MINDMAP_META_ATTRIBUTE, JSON.stringify(metadata)));cleanListMindmapDOM(root);diff --git a/app/src/protyle/render/listMindmap/routing.test.ts b/app/src/protyle/render/listMindmap/routing.test.tsindex 4a48f94f7c..d676628c0a 100644--- a/app/src/protyle/render/listMindmap/routing.test.ts+++ b/app/src/protyle/render/listMindmap/routing.test.ts@@ -19,6 +19,92 @@ const validate = (route: MindmapRoutePoint[], nodes: MindmapRouteBox[]) => {}};+const validateDirection = (route: MindmapRoutePoint[], from: MindmapRouteBox, to: MindmapRouteBox) => {+ const outward = (port: MindmapRoutePoint, next: MindmapRoutePoint, node: MindmapRouteBox) => {+ if (port.x < node.x) {+ assert.ok(next.x < port.x && next.y === port.y);+ } else if (port.x > node.x + node.width) {+ assert.ok(next.x > port.x && next.y === port.y);+ } else if (port.y < node.y) {+ assert.ok(next.y < port.y && next.x === port.x);+ } else {+ assert.ok(next.y > port.y && next.x === port.x);+ }+ };+ outward(route[0], route[1], from);+ outward(route[route.length - 1], route[route.length - 2], to);+};++test("mixed widths keep arrows facing nodes", () => {+ for (const width of [64, 130, 260]) {+ const nodes = [+ {x: 0, y: 56, width: 88, height: 32, controlY: 72},+ {x: 128, y: 0, width: 64, height: 32},+ {x: 128, y: 56, width, height: 32},+ {x: 128, y: 112, width: 64, height: 32},+ {x: 168 + width, y: 56, width: 64, height: 32},+ ];+ for (const [from, to] of [[1, 2], [1, 4], [2, 4], [2, 3]]) {+ const route = routeMindmapRelation(nodes[from], nodes[to], nodes);+ validate(route, nodes);+ validateDirection(route, nodes[from], nodes[to]);+ if (to === 3) {+ assert.equal(route.length, 2, "wide sibling connects vertically to the narrower sibling");+ }+ }+ for (const from of nodes) {+ for (const to of nodes) {+ if (from !== to) {+ const route = routeMindmapRelation(from, to, nodes);+ validate(route, nodes);+ validateDirection(route, from, to);+ assert.deepEqual(routeMindmapRelation(to, from, nodes), [...route].reverse(),+ "opposite connections share the same geometry");+ }+ }+ }+ }+});++test("routing is independent of other connections and reverse arrows retain their approach direction", () => {+ const nodes = [+ {x: 0, y: 0, width: 100, height: 40},+ {x: 260, y: 0, width: 100, height: 40},+ {x: 260, y: 100, width: 100, height: 40},+ ];+ const first = routeMindmapRelation(nodes[0], nodes[1], nodes);+ const second = routeMindmapRelation(nodes[0], nodes[2], nodes);+ const reverse = routeMindmapRelation(nodes[1], nodes[0], nodes);+ validate(second, nodes);+ validate(reverse, nodes);+ validateDirection(second, nodes[0], nodes[2]);+ validateDirection(reverse, nodes[1], nodes[0]);+ assert.deepEqual(routeMindmapRelation(nodes[0], nodes[1], nodes), first,+ "computing other connections does not change the existing route");+ assert.deepEqual(routeMindmapRelation(nodes[0], nodes[2], nodes), second,+ "routing remains independent of previously computed connections");+});++test("multiline parents connect directly to short children without tiny doglegs", () => {+ for (const height of [80, 128, 200]) {+ const nodes = [+ {x: 128, y: 0, width: 64, height: 32},+ {x: 128, y: 56, width: 160, height},+ {x: 328, y: 56 + (height - 32) / 2, width: 64, height: 32},+ {x: 128, y: 80 + height, width: 64, height: 32},+ ];+ for (const [from, to] of [[1, 2], [2, 1]]) {+ const route = routeMindmapRelation(nodes[from], nodes[to], nodes);+ validate(route, nodes);+ validateDirection(route, nodes[from], nodes[to]);+ assert.equal(route.length, 2, "different node heights share a horizontal port level");+ assert.equal(route[0].y, route[1].y);+ assert.equal(route[0].y, nodes[2].y + nodes[2].height / 2,+ "horizontal connections meet the short node at its vertical center");+ }+ }+});+test("vertically adjacent nodes connect when their clearance ports coincide", () => {const nodes = [{x: 200, y: 0, width: 64, height: 38},@@ -28,6 +114,23 @@ test("vertically adjacent nodes connect when their clearance ports coincide", ()validate(routeMindmapRelation(nodes[1], nodes[0], nodes), nodes);});+test("adjacent siblings remain connectable between a parent and a child column", () => {+ const nodes = [+ {x: 0, y: 62, width: 88, height: 38, controlY: 81},+ {x: 128, y: 0, width: 64, height: 38},+ {x: 128, y: 62, width: 64, height: 38},+ {x: 128, y: 124, width: 64, height: 38},+ {x: 232, y: 62, width: 64, height: 38},+ ];+ for (const from of nodes) {+ for (const to of nodes) {+ if (from !== to) {+ validate(routeMindmapRelation(from, to, nodes), nodes);+ }+ }+ }+});+test("connection preview routes to the exact pointer position around obstacles", () => {const from = {x: 0, y: 0, width: 100, height: 40};const obstacle = {x: 160, y: 0, width: 100, height: 80};@@ -37,6 +140,40 @@ test("connection preview routes to the exact pointer position around obstacles",assert.deepEqual(route[route.length - 1], {x: pointer.x, y: pointer.y});});+test("compact sibling connections prefer the gap instead of an outer detour", () => {+ for (const height of [32, 38, 46]) {+ const nodes = [+ {x: 0, y: height + 24, width: 88, height, controlY: height * 1.5 + 24},+ {x: 128, y: 0, width: 64, height},+ {x: 128, y: height + 24, width: 64, height},+ {x: 128, y: 2 * (height + 24), width: 64, height},+ {x: 232, y: height + 24, width: 64, height},+ ];+ for (const [from, to] of [[1, 2], [2, 1], [2, 3], [3, 2]]) {+ const route = routeMindmapRelation(nodes[from], nodes[to], nodes);+ validate(route, nodes);+ assert.equal(route.length, 2, "siblings use the direct vertical gap");+ assert.equal(route[0].x, nodes[from].x + nodes[from].width / 2);+ assert.equal(Math.abs(route[1].y - route[0].y), 18,+ "short connections leave enough space for two readable arrows and a gap");+ assert.deepEqual(routeMindmapRelation(nodes[from], nodes[to], nodes), route);+ }+ for (const [from, to] of [[2, 4], [4, 2]]) {+ const route = routeMindmapRelation(nodes[from], nodes[to], nodes);+ validate(route, nodes);+ assert.equal(route.length, 2, "aligned parent and child use the direct horizontal gap");+ assert.equal(route[0].y, route[1].y);+ }+ const diagonal = routeMindmapRelation(nodes[1], nodes[4], nodes);+ validate(diagonal, nodes);+ assert.equal(diagonal.length, 3, "cross-column connection only needs one bend");+ assert.equal(diagonal[0].y, nodes[1].y + nodes[1].height / 2,+ "side endpoints are vertically centered");+ assert.equal(diagonal[diagonal.length - 1].x, nodes[4].x + nodes[4].width / 2,+ "top endpoints are horizontally centered");+ }+});+test("relations route around intervening nodes in both directions", () => {const nodes = [{x: 300, y: 100, width: 165, height: 76},@@ -52,7 +189,7 @@ test("right-side endpoints remain close to node text while avoiding bottom contrconst to = {x: 240, y: 0, width: 120, height: 40};const route = routeMindmapRelation(from, to, [from, to]);validate(route, [from, to]);- assert.equal(route[0].x - from.x - from.width, 12);+ assert.equal(route[0].x - from.x - from.width, 3);});test("relations find side ports when vertical gaps are too narrow", () => {diff --git a/app/src/protyle/render/listMindmap/routing.ts b/app/src/protyle/render/listMindmap/routing.tsindex c075be6305..9e4a93d5c0 100644--- a/app/src/protyle/render/listMindmap/routing.ts+++ b/app/src/protyle/render/listMindmap/routing.ts@@ -1,24 +1,84 @@export interface MindmapRoutePoint {x: number; y: number;}export interface MindmapRouteBox extends MindmapRoutePoint {width: number; height: number; controlY?: number;}-// 在障碍边界构成的正交可视网格上搜索,方向纳入状态以惩罚多余转弯。+const bendCost = 24;+export const routeMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,nodes: MindmapRouteBox[], clearance = 12): MindmapRoutePoint[] => {+ // 双向连接使用同一条几何路径,避免端口同分时因搜索方向不同而出现错位。+ const order = from.x - to.x || from.y - to.y || from.width - to.width || from.height - to.height;+ if (to.width > 0 && to.height > 0 && order > 0) {+ return routeMindmapRelation(to, from, nodes, clearance).reverse();+ }+ let best: MindmapRoutePoint[] = [];+ let bestCost = Infinity;+ for (const gap of [...new Set([clearance, Math.min(clearance, 6)])]) {+ const route = findRelationRoute(from, to, nodes, gap);+ if (route.length < 2) {+ continue;+ }+ const cost = route.slice(1).reduce((total, point, index) => total ++ Math.abs(point.x - route[index].x) + Math.abs(point.y - route[index].y),+ Math.max(0, route.length - 2) * bendCost);+ if (cost < bestCost) {+ best = route;+ bestCost = cost;+ }+ // 直连已经没有绕行和转弯,无需再次搜索更靠近节点的端口。+ if (best.length === 2) {+ break;+ }+ }+ // 搜索保留避障空间,绘制端点靠近节点,避免短连接只剩两个挤在一起的箭头。+ const attach = (point: MindmapRoutePoint, node: MindmapRouteBox) => {+ if (!node.width || !node.height) {+ return;+ }+ if (point.x < node.x) {+ point.x = node.x - 3;+ } else if (point.x > node.x + node.width) {+ point.x = node.x + node.width + 3;+ } else if (point.y < node.y) {+ point.y = node.y - 3;+ } else {+ point.y = node.y + node.height + 3;+ }+ };+ if (best.length >= 2) {+ attach(best[0], from);+ attach(best[best.length - 1], to);+ }+ return best;+};++// 在障碍边界构成的正交可视网格上搜索,方向纳入状态以惩罚多余转弯。+const findRelationRoute = (from: MindmapRouteBox, to: MindmapRouteBox,+ nodes: MindmapRouteBox[], clearance: number): MindmapRoutePoint[] => {const boxes = nodes.flatMap(node => [{left: node.x - clearance, right: node.x + node.width + clearance,top: node.y - clearance, bottom: node.y + node.height + clearance},{left: node.x + node.width - 19, right: node.x + node.width + 46,- top: (node.controlY ?? node.y + node.height) - 19, bottom: (node.controlY ?? node.y + node.height) + 19},+ top: (node.controlY ?? node.y + node.height) - 15, bottom: (node.controlY ?? node.y + node.height) + 15},]);- const ports = (node: MindmapRouteBox) => [- {x: node.x + node.width / 2, y: node.y - clearance, direction: 1},- {x: node.x + node.width / 2, y: node.y + node.height + clearance, direction: 1},- {x: node.x - clearance, y: node.y + node.height / 2, direction: 0},- {x: node.x + node.width + clearance, y: node.y + Math.max(0, Math.min(node.height / 2, node.height - 22)), direction: 0},- ];- const starts = ports(from);+ const ports = (node: MindmapRouteBox, other: MindmapRouteBox) => {+ const centerX = node.x + node.width / 2;+ const otherCenterX = other.x + other.width / 2;+ const xs = [...new Set([centerX, ...(otherCenterX >= node.x + 12 &&+ otherCenterX <= node.x + node.width - 12 ? [otherCenterX] : [])])];+ const centerY = node.y + node.height / 2;+ const otherCenterY = other.y + other.height / 2;+ const ys = [...new Set([centerY, ...(otherCenterY >= node.y + 4 &&+ otherCenterY <= node.y + node.height - 4 ? [otherCenterY] : [])])];+ return [+ ...xs.flatMap(x => [{x, y: node.y - clearance, direction: 2},+ {x, y: node.y + node.height + clearance, direction: 3}]),+ ...ys.flatMap(y => [{x: node.x - clearance, y, direction: 0},+ {x: node.x + node.width + clearance, y, direction: 1}]),+ ];+ };+ const starts = ports(from, to);const goals = to.width === 0 && to.height === 0 ?- [{x: to.x, y: to.y, direction: 0}, {x: to.x, y: to.y, direction: 1}] : ports(to);+ [0, 1, 2, 3].map(direction => ({x: to.x, y: to.y, direction})) : ports(to, from);const xs = [...new Set([...boxes.flatMap(box => [box.left, box.right]), ...starts.map(p => p.x), ...goals.map(p => p.x)])].sort((a, b) => a - b);const ys = [...new Set([...boxes.flatMap(box => [box.top, box.bottom]), ...starts.map(p => p.y), ...goals.map(p => p.y)])].sort((a, b) => a - b);const point = (index: number) => ({x: xs[index % xs.length], y: ys[Math.floor(index / xs.length)]});@@ -38,7 +98,7 @@ export const routeMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,return rows.get(a.y).some(box => Math.max(a.x, b.x) > box.left && Math.min(a.x, b.x) < box.right);};const heuristic = (p: MindmapRoutePoint) => Math.min(...goals.map(goal => Math.abs(p.x - goal.x) + Math.abs(p.y - goal.y)));- const targets = new Set(goals.map(goal => indexOf(goal) * 2 + goal.direction));+ const targets = new Set(goals.map(goal => indexOf(goal) * 4 + (goal.direction ^ 1)));const distance = new Map<number, number>();const previous = new Map<number, number>();const heap: {key: number, cost: number, score: number}[] = [];@@ -79,7 +139,7 @@ export const routeMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,if (blocked(start, start)) {return;}- const key = indexOf(start) * 2 + start.direction;+ const key = indexOf(start) * 4 + start.direction;distance.set(key, 0);push({key, cost: 0, score: heuristic(start)});});@@ -88,14 +148,14 @@ export const routeMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,if (distance.get(current.key) !== current.cost) {continue;}- const index = Math.floor(current.key / 2);+ const index = Math.floor(current.key / 4);const a = point(index);// 相邻节点的避让端口可能重合,不能将尚未走过任何线段的起点作为完整路径。if (targets.has(current.key) && previous.has(current.key)) {const route: MindmapRoutePoint[] = [];let key: number | undefined = current.key;while (key !== undefined) {- route.push(point(Math.floor(key / 2)));+ route.push(point(Math.floor(key / 4)));key = previous.get(key);}route.reverse();@@ -111,13 +171,14 @@ export const routeMindmapRelation = (from: MindmapRouteBox, to: MindmapRouteBox,return;}const b = point(next);- const direction = side < 2 ? 0 : 1;+ const direction = side;// 起终点保留垂直于节点边缘的引出段,箭头始终朝向目标节点。- if ((!previous.has(current.key) && direction !== current.key % 2) || blocked(a, b)) {+ if (direction === (current.key % 4 ^ 1) ||+ (!previous.has(current.key) && direction !== current.key % 4) || blocked(a, b)) {return;}- const key = next * 2 + direction;- const cost = current.cost + Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + (direction === current.key % 2 ? 0 : 24);+ const key = next * 4 + direction;+ const cost = current.cost + Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + (direction === current.key % 4 ? 0 : bendCost);if (cost >= (distance.get(key) ?? Infinity)) {return;}diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.tsindex 3a06cfd151..84f9c7058f 100644--- a/app/src/protyle/render/listMindmap/view.ts+++ b/app/src/protyle/render/listMindmap/view.ts@@ -86,7 +86,7 @@ export class ListMindmapView {private selectedEdge?: string;private hoveredLine?: string;private finishRelationEdit?: (save: boolean) => void;- private linePaths: {id: string, relation: boolean, path: Path2D}[] = [];+ private linePaths: {id: string, relation: boolean, path: Path2D, end?: MindmapRoutePoint}[] = [];private relationRoutes = new Map<string, MindmapRoutePoint[]>();private relationFrom?: string;private relationPreview?: {x: number, y: number, targetId?: string};@@ -487,7 +487,7 @@ export class ListMindmapView {return {id,width: Math.max(64, element.offsetWidth),- height: Math.max(36, element.offsetHeight),+ height: Math.max(1, element.offsetHeight),collapsed: this.folded.get(id) ?? node.collapsed,children: node.children.map(child => makeLayoutNode(child.id)),};@@ -501,6 +501,7 @@ export class ListMindmapView {this.bounds = result;let top = 0;let left = 0;+ // 每条连接独立避让节点和按钮,已有关系线不影响路径选择。this.model.metadata.relations.forEach((relation) => {const from = this.positions.get(relation.from);const to = this.positions.get(relation.to);@@ -607,21 +608,24 @@ export class ListMindmapView {if (points.length < 2) {return;}+ const end = points[points.length - 1];+ const previous = points[points.length - 2];+ // 重合路径从同一端绘制,避免反向虚线填满正向虚线的间隙。+ const drawingPoints = (points[0].x - end.x || points[0].y - end.y) > 0 ? [...points].reverse() : points;const path = new Path2D();- path.moveTo(points[0].x, points[0].y);- for (let i = 1; i < points.length - 1; i++) {- const a = points[i - 1];- const b = points[i];- const c = points[i + 1];+ path.moveTo(drawingPoints[0].x, drawingPoints[0].y);+ for (let i = 1; i < drawingPoints.length - 1; i++) {+ const a = drawingPoints[i - 1];+ const b = drawingPoints[i];+ const c = drawingPoints[i + 1];const before = Math.hypot(b.x - a.x, b.y - a.y);const after = Math.hypot(c.x - b.x, c.y - b.y);const radius = Math.min(8, before / 2, after / 2);path.lineTo(b.x + (a.x - b.x) * radius / before, b.y + (a.y - b.y) * radius / before);path.quadraticCurveTo(b.x, b.y, b.x + (c.x - b.x) * radius / after, b.y + (c.y - b.y) * radius / after);}- const end = points[points.length - 1];- const previous = points[points.length - 2];- path.lineTo(end.x, end.y);+ const drawingEnd = drawingPoints[drawingPoints.length - 1];+ path.lineTo(drawingEnd.x, drawingEnd.y);if (!label) {return {path, end, previous, labelPoint: undefined as MindmapRoutePoint | undefined};}@@ -722,23 +726,29 @@ export class ListMindmapView {return;}const {path, end, previous, labelPoint} = route;- this.linePaths.push({id: relation.id, relation: true, path});+ this.linePaths.push({id: relation.id, relation: true, path, end});context.beginPath();context.strokeStyle = resolveColor(relation.color, primary);- context.lineWidth = (relation.width || 1.5) + (relation.id === this.selectedRelation ? 1 : 0) ++ const emphasis = (relation.id === this.selectedRelation ? 1 : 0) +(this.hoveredLine === `relation:${relation.id}` ? 1.5 / this.scale : 0);+ context.lineWidth = (relation.width || 1.5) + emphasis;element.classList.toggle("list-mindmap__relation--hover", this.hoveredLine === `relation:${relation.id}`);context.setLineDash(relation.dash === false ? [] : [5, 4]);context.stroke(path);context.setLineDash([]);context.beginPath();const direction = Math.atan2(end.y - previous.y, end.x - previous.x);- // 箭头保持最小屏幕尺寸,并沿避障路径朝向目标节点。- const arrowSize = Math.max(10 / this.scale, (relation.width || 1.5) * 3);+ // 短线上的双向箭头预留间隙,避免合并成菱形。+ const arrowSize = Math.min(Math.max(7 / this.scale, (relation.width || 1.5) * 2),+ Math.hypot(end.x - previous.x, end.y - previous.y) / 3);+ // 箭头随线条状态加宽,保持长度不变以保留双向箭头之间的间隙。+ const halfWidth = arrowSize / 2 + emphasis / 2;+ const baseX = end.x - arrowSize * Math.cos(Math.PI / 6) * Math.cos(direction);+ const baseY = end.y - arrowSize * Math.cos(Math.PI / 6) * Math.sin(direction);context.fillStyle = context.strokeStyle;- context.moveTo(end.x - arrowSize * Math.cos(direction - Math.PI / 6), end.y - arrowSize * Math.sin(direction - Math.PI / 6));+ context.moveTo(baseX - halfWidth * Math.sin(direction), baseY + halfWidth * Math.cos(direction));context.lineTo(end.x, end.y);- context.lineTo(end.x - arrowSize * Math.cos(direction + Math.PI / 6), end.y - arrowSize * Math.sin(direction + Math.PI / 6));+ context.lineTo(baseX + halfWidth * Math.sin(direction), baseY - halfWidth * Math.cos(direction));context.closePath();context.fill();if (labelPoint) {@@ -769,7 +779,7 @@ export class ListMindmapView {context.stroke(path);context.setLineDash([]);context.beginPath();- const size = Math.max(10 / this.scale, 4.5);+ const size = Math.min(Math.max(7 / this.scale, 3), Math.hypot(end.x - previous.x, end.y - previous.y) / 3);const direction = Math.atan2(end.y - previous.y, end.x - previous.x);context.fillStyle = color;context.moveTo(end.x - size * Math.cos(direction - Math.PI / 6), end.y - size * Math.sin(direction - Math.PI / 6));@@ -1036,7 +1046,23 @@ export class ListMindmapView {context.resetTransform();context.setLineDash([]);context.lineWidth = 12 / this.scale;- const line = this.linePaths.slice().reverse().find(item => context.isPointInStroke(item.path, x, y));+ const lines = this.linePaths.slice().reverse();+ // 优先命中最近的箭头,重合的双向连接可从各自的箭头单独选中。+ let arrow: typeof lines[number];+ let distance = 12 / this.scale;+ lines.forEach(item => {+ if (!item.end) {+ return;+ }+ const current = Math.hypot(item.end.x - x, item.end.y - y);+ if (current < distance) {+ distance = current;+ arrow = item;+ }+ });+ const hits = lines.filter(item => context.isPointInStroke(item.path, x, y));+ // 沿线移动或双击时保持已选关系,避免重新选中覆盖在上方的反向连接。+ const line = arrow || hits.find(item => item.relation && item.id === this.selectedRelation) || hits[0];context.restore();return line;}diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.tsindex 7f7c8cd598..720c9c10e2 100644--- a/app/src/protyle/wysiwyg/transaction.ts+++ b/app/src/protyle/wysiwyg/transaction.ts@@ -74,7 +74,7 @@ import {} from "./blockSelection";import {isEmptyParagraph} from "./emptyTextBlock";import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";-import {cleanListMindmapHTML, LIST_MINDMAP_VIEW_ATTRIBUTE} from "../render/listMindmap/model";+import {cleanListMindmapHTML, LIST_MINDMAP_META_ATTRIBUTE, LIST_MINDMAP_VIEW_ATTRIBUTE} from "../render/listMindmap/model";import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";import {waitForPendingTransactions} from "../util/transactionQueue";import {@@ -148,12 +148,20 @@ const syncBlockAttrs = (element: Element, operation: Extract<IOperation, {actionconst hasFold = Object.prototype.hasOwnProperty.call(attrs, "fold");const hasStyle = Object.prototype.hasOwnProperty.call(attrs, "style");const hasMindmapView = Object.prototype.hasOwnProperty.call(attrs, LIST_MINDMAP_VIEW_ATTRIBUTE);+ const hasMindmapMetadata = Object.prototype.hasOwnProperty.call(attrs, LIST_MINDMAP_META_ATTRIBUTE);const tabsAttrs = ["tabs-active-id", "tabs-position", "tabs-task"].filter(name => Object.prototype.hasOwnProperty.call(attrs, name));- if (!hasFold && !hasStyle && !hasMindmapView && tabsAttrs.length === 0) {+ if (!hasFold && !hasStyle && !hasMindmapView && !hasMindmapMetadata && tabsAttrs.length === 0) {return;}element.querySelectorAll(`[data-node-id="${operation.id}"]`).forEach(item => {+ if (hasMindmapMetadata) {+ if (attrs[LIST_MINDMAP_META_ATTRIBUTE]) {+ item.setAttribute(LIST_MINDMAP_META_ATTRIBUTE, attrs[LIST_MINDMAP_META_ATTRIBUTE]);+ } else {+ item.removeAttribute(LIST_MINDMAP_META_ATTRIBUTE);+ }+ }// 同步脑图视图属性,由列表监听器刷新各分屏中的视图。if (hasMindmapView) {if (attrs[LIST_MINDMAP_VIEW_ATTRIBUTE]) {diff --git a/app/src/protyle/wysiwyg/transactionAttrs.test.ts b/app/src/protyle/wysiwyg/transactionAttrs.test.tsindex 92adf12648..1cbc7bdc00 100644--- a/app/src/protyle/wysiwyg/transactionAttrs.test.ts+++ b/app/src/protyle/wysiwyg/transactionAttrs.test.ts@@ -9,7 +9,8 @@ const source = createSourceFile("transaction.ts", readFileSync("src/protyle/wysiconst declaration = source.statements.find(statement => isVariableStatement(statement) &&statement.declarationList.declarations.some(item => item.name.getText(source) === "syncBlockAttrs"));const attribute = "custom-sy-list-mindmap";-const context = {LIST_MINDMAP_VIEW_ATTRIBUTE: attribute, sync: undefined as any};+const metadataAttribute = "custom-sy-list-mindmap-data";+const context = {LIST_MINDMAP_VIEW_ATTRIBUTE: attribute, LIST_MINDMAP_META_ATTRIBUTE: metadataAttribute, sync: undefined as any};runInNewContext(transpileModule(declaration.getText(source) + "\nglobalThis.sync = syncBlockAttrs;", {compilerOptions: {target: ScriptTarget.ES2021},}).outputText, context);@@ -42,3 +43,15 @@ test("unrelated attribute transactions preserve the mind map view", () => {assert.equal(attrs.get("style"), "color: red");assert.equal(attrs.get("fold"), "1");});++test("kernel metadata cleanup and undo synchronize across editor copies", () => {+ const attrs = new Map<string, string>();+ const root = {querySelectorAll: () => [{+ setAttribute: (name: string, value: string) => attrs.set(name, value),+ removeAttribute: (name: string) => attrs.delete(name),+ }]};+ for (const value of ['{"version":1,"nodes":{},"relations":[]}', '{"version":1,"nodes":{"a":{}},"relations":[]}']) {+ context.sync(root, {action: "setAttrs", id: "list-id", data: JSON.stringify({[metadataAttribute]: value})});+ assert.equal(attrs.get(metadataAttribute), value);+ }+});diff --git a/docs/LIST-MINDMAP.md b/docs/LIST-MINDMAP.mdindex bf801e7dcd..6f9ea2b5fb 100644--- a/docs/LIST-MINDMAP.md+++ b/docs/LIST-MINDMAP.md@@ -28,10 +28,14 @@修改前补齐折叠隐藏的列表内容。结构、正文和配置修改通过已有文档事务保存,并进入文档撤销记录。复制列表时,样式所关联的节点 ID 和关系线的端点随复制后的块 ID 一起更新。+内核在文档事务完成结构修改后,按列表当前的完整节点树清理失效的样式及关系线,并将配置修改附加到同一事务的同步、撤销和重做记录中。普通列表编辑、其他窗口和通过文档事务执行的 API 删除共用此逻辑;同一事务内先删除再插入的节点及折叠后代不会被误清理。刷新脑图只读取配置,不执行清理;复制列表会过滤不属于副本的样式和关系线。未知版本及损坏配置保持原样。+节点内容编辑保留原正文块的身份和属性,以及穿插在正文之间的子列表。编辑器中新建的列表在结束该次编辑时转换为实际子节点。外部更新导致编辑目标失效时,不覆盖较新的正文,并显示尚未保存的内容供恢复。脑图 DOM、画布、全屏占位和编辑器均为派生显示内容,不写入列表事务或剪贴板的思源块数据。此功能沿用现有块存储、加密、历史和备份格式。+关系线路由使用带进出方向约束的正交网格搜索,按节点边界及目标位置选择连接点,禁止立即折返。路线代价综合长度及转弯,各条关系线独立计算,不避让已有线条;新增连接的吸附预览与落点使用相同规则。节点宽度变化时可选择与目标对齐的连接点,节点和折叠、添加按钮仍作为避让区域。+## 导出与验证思源格式的 HTML 和 PDF 预览沿用 `Protyle.mindmapRender` 加载列表脑图,资源均来自本地。Markdown、Markdown 格式的 HTML 和 Word 保留列表形式。diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 89ce77fc5c..5d012a74db 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -486,6 +486,10 @@ func performTx(tx *Transaction) (ret *TxErr) {tx.rollback()return}+ if ret = tx.normalizeListMindmapMetadata(); nil != ret {+ tx.rollback()+ return+ }tx.UndoOperations = append(tx.UndoOperations, tx.attributeViewDeletionUndo...)if cr := tx.commit(); nil != cr {diff --git a/kernel/model/transaction_list_mindmap.go b/kernel/model/transaction_list_mindmap.gonew file mode 100644index 0000000000..2709bc3cb0--- /dev/null+++ b/kernel/model/transaction_list_mindmap.go@@ -0,0 +1,192 @@+package model++import (+ "encoding/json"+ "math"+ "slices"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/cache"+)++const listMindmapMetadataAttr = "custom-sy-list-mindmap-data"++// 只校验当前版本的已知字段,未知字段随配置保留,损坏和较新版本的配置不参与清理。+func validListMindmapMetadata(data map[string]any) bool {+ if data["version"] != float64(1) {+ return false+ }+ nodes, ok := data["nodes"].(map[string]any)+ if !ok {+ return false+ }+ relations, ok := data["relations"].([]any)+ if !ok {+ return false+ }+ if title, exists := data["rootTitle"]; exists {+ if _, ok = title.(string); !ok {+ return false+ }+ }+ validFields := func(value map[string]any, strings, numbers, booleans []string) bool {+ for _, key := range strings {+ if field, exists := value[key]; exists {+ if _, ok := field.(string); !ok {+ return false+ }+ }+ }+ for _, key := range numbers {+ if field, exists := value[key]; exists {+ number, ok := field.(float64)+ if !ok || number < 0 || math.IsInf(number, 0) || math.IsNaN(number) {+ return false+ }+ }+ }+ for _, key := range booleans {+ if field, exists := value[key]; exists {+ if _, ok := field.(bool); !ok {+ return false+ }+ }+ }+ return true+ }+ for id, value := range nodes {+ style, ok := value.(map[string]any)+ if id == "" || !ok || !validFields(style,+ []string{"textColor", "backgroundColor", "borderColor", "lineColor"},+ []string{"fontSize", "borderWidth", "borderRadius", "lineWidth"}, []string{"bold", "italic", "lineDash"}) {+ return false+ }+ }+ seen := map[string]bool{}+ for _, value := range relations {+ relation, ok := value.(map[string]any)+ if !ok || !validFields(relation, []string{"label", "color"}, []string{"width"}, []string{"dash"}) {+ return false+ }+ for _, key := range []string{"id", "from", "to"} {+ if field, ok := relation[key].(string); !ok || field == "" {+ return false+ }+ }+ if _, ok := relation["label"].(string); !ok || seen[relation["id"].(string)] {+ return false+ }+ seen[relation["id"].(string)] = true+ }+ return true+}++func pruneListMindmapMetadata(list *ast.Node) (string, bool) {+ original := list.IALAttr(listMindmapMetadataAttr)+ var data map[string]any+ if json.Unmarshal([]byte(original), &data) != nil || !validListMindmapMetadata(data) {+ return original, false+ }+ // 列表根的样式在单根和虚拟根切换时仍需保留,折叠子树也属于有效节点。+ ids := map[string]bool{list.ID: true}+ pending := []*ast.Node{list}+ for len(pending) > 0 {+ current := pending[len(pending)-1]+ pending = pending[:len(pending)-1]+ for item := current.FirstChild; item != nil; item = item.Next {+ if item.Type != ast.NodeListItem {+ continue+ }+ ids[item.ID] = true+ for child := item.FirstChild; child != nil; child = child.Next {+ if child.Type == ast.NodeList {+ pending = append(pending, child)+ }+ }+ }+ }+ changed := false+ nodes := data["nodes"].(map[string]any)+ for id := range nodes {+ if !ids[id] {+ delete(nodes, id)+ changed = true+ }+ }+ relations := make([]any, 0)+ for _, value := range data["relations"].([]any) {+ relation := value.(map[string]any)+ if ids[relation["from"].(string)] && ids[relation["to"].(string)] {+ relations = append(relations, value)+ } else {+ changed = true+ }+ }+ if !changed {+ return original, false+ }+ // 使用原始 JSON 字段重组,避免扩展字段中的大整数在浮点解码后丢失精度。+ var raw map[string]json.RawMessage+ _ = json.Unmarshal([]byte(original), &raw)+ var rawNodes map[string]json.RawMessage+ _ = json.Unmarshal(raw["nodes"], &rawNodes)+ for id := range rawNodes {+ if !ids[id] {+ delete(rawNodes, id)+ }+ }+ var rawRelations []json.RawMessage+ _ = json.Unmarshal(raw["relations"], &rawRelations)+ kept := make([]json.RawMessage, 0, len(relations))+ for i, value := range data["relations"].([]any) {+ relation := value.(map[string]any)+ if ids[relation["from"].(string)] && ids[relation["to"].(string)] {+ kept = append(kept, rawRelations[i])+ }+ }+ raw["nodes"], _ = json.Marshal(rawNodes)+ raw["relations"], _ = json.Marshal(kept)+ encoded, err := json.Marshal(raw)+ return string(encoded), err == nil+}++// 在全部结构操作结束后清理,避免同一事务内先删除再插入的节点丢失配置。+func (tx *Transaction) normalizeListMindmapMetadata() (ret *TxErr) {+ if tx.isReplay {+ return nil+ }+ hasUndo := len(tx.UndoOperations) > 0+ var undo []*Operation+ for _, tree := range tx.trees {+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {+ if !entering || node.Type != ast.NodeList || node.IALAttr(listMindmapMetadataAttr) == "" {+ return ast.WalkContinue+ }+ previous := node.IALAttr(listMindmapMetadataAttr)+ next, changed := pruneListMindmapMetadata(node)+ if !changed {+ return ast.WalkContinue+ }+ attrs := map[string]string{listMindmapMetadataAttr: next}+ if _, err := setNodeAttrs0(node, attrs, tree.Box); err != nil {+ ret = &TxErr{code: TxErrCodePushMsg, msg: err.Error(), id: node.ID}+ return ast.WalkStop+ }+ cache.PutBlockIALInBox(node.ID, tree.Box, parse.IAL2Map(node.KramdownIAL))+ encoded, _ := json.Marshal(attrs)+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "setAttrs", ID: node.ID, Data: string(encoded)})+ if hasUndo {+ encoded, _ = json.Marshal(map[string]string{listMindmapMetadataAttr: previous})+ undo = append(undo, &Operation{Action: "setAttrs", ID: node.ID, Data: string(encoded)})+ }+ return ast.WalkContinue+ })+ if ret != nil {+ return+ }+ }+ slices.Reverse(undo)+ tx.UndoOperations = append(undo, tx.UndoOperations...)+ return nil+}diff --git a/kernel/model/transaction_list_mindmap_fts5_test.go b/kernel/model/transaction_list_mindmap_fts5_test.gonew file mode 100644index 0000000000..1759e00d6e--- /dev/null+++ b/kernel/model/transaction_list_mindmap_fts5_test.go@@ -0,0 +1,87 @@+//go:build fts5++package model++import (+ "encoding/json"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestListMindmapDeletionPersistsAndReplays(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ listID, itemID := addOrderedListForStructureTest(t, fixture.sourceID)+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ list := treenode.GetNodeInTree(tree, listID)+ sibling := &ast.Node{Type: ast.NodeListItem, ID: "20260918000000-sibling", ListData: &ast.ListData{Typ: 1}}+ sibling.SetIALAttr("id", sibling.ID)+ sibling.AppendChild(treenode.NewParagraph("20260918000000-content"))+ list.AppendChild(sibling)+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ original := `{"version":1,"nodes":{"` + itemID + `":{"bold":true}},"relations":[{"id":"r","from":"` + listID + `","to":"` + itemID + `","label":"test"}]}`+ attrs, _ := json.Marshal(map[string]string{listMindmapMetadataAttr: original})+ if err := PerformTxSync(&Transaction{DoOperations: []*Operation{{Action: "setAttrs", ID: listID, Data: string(attrs)}}}); err != nil {+ t.Fatal(err)+ }+ dom := GetBlockDOM(itemID)+ tx := &Transaction{+ DoOperations: []*Operation{{Action: "delete", ID: itemID}},+ UndoOperations: []*Operation{{Action: "insert", ID: itemID, ParentID: listID, Data: dom}},+ }+ if err := PerformTxSync(tx); err != nil {+ t.Fatal(err)+ }+ check := func(deleted bool) {+ t.Helper()+ cache.RemoveTreeData(fixture.sourceID)+ tree, err := LoadTreeByBlockID(fixture.sourceID)+ if err != nil {+ t.Fatal(err)+ }+ list := treenode.GetNodeInTree(tree, listID)+ if list == nil {+ t.Fatal("list disappeared")+ }+ value := list.IALAttr(listMindmapMetadataAttr)+ if deleted {+ var metadata map[string]any+ if err = json.Unmarshal([]byte(value), &metadata); err != nil {+ t.Fatal(err)+ }+ if len(metadata["nodes"].(map[string]any)) != 0 || len(metadata["relations"].([]any)) != 0 || treenode.GetNodeInTree(tree, itemID) != nil {+ t.Fatalf("deletion left node or configuration behind: %s", value)+ }+ } else if value != original || treenode.GetNodeInTree(tree, itemID) == nil {+ t.Fatalf("undo did not restore node and configuration: %s", value)+ }+ }+ check(true)+ for i, operations := range [][]*Operation{tx.UndoOperations, tx.DoOperations} {+ replay := &Transaction{DoOperations: operations}+ replay.MarkReplay()+ if err := PerformTxSync(replay); err != nil {+ t.Fatal(err)+ }+ check(i == 1)+ }+ restore := &Transaction{DoOperations: tx.UndoOperations}+ restore.MarkReplay()+ if err := PerformTxSync(restore); err != nil {+ t.Fatal(err)+ }+ if _, err := PerformBlockOperation(&Operation{Action: "delete", ID: itemID}); err != nil {+ t.Fatal(err)+ }+ check(true)+}diff --git a/kernel/model/transaction_list_mindmap_test.go b/kernel/model/transaction_list_mindmap_test.gonew file mode 100644index 0000000000..30afce3162--- /dev/null+++ b/kernel/model/transaction_list_mindmap_test.go@@ -0,0 +1,139 @@+package model++import (+ "encoding/json"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+)++func mindmapTestTree() (*parse.Tree, *ast.Node, *ast.Node) {+ tree, item := newFoldedListItemTree(1, false)+ list := item.Parent+ nested := &ast.Node{Type: ast.NodeList, ID: "nested"}+ child := &ast.Node{Type: ast.NodeListItem, ID: "child"}+ item.AppendChild(nested)+ nested.AppendChild(child)+ return tree, list, child+}++func TestPruneListMindmapMetadata(t *testing.T) {+ _, list, child := mindmapTestTree()+ original := `{"version":1,"rootTitle":"A & B","extension":9007199254740993,"nodes":{"` + list.ID ++ `":{"backgroundColor":"red"},"child":{"bold":true,"extension":9007199254740993},"deleted":{}},` ++ `"relations":[{"id":"keep","from":"` + list.ID + `","to":"child","label":"A & B"},` ++ `{"id":"remove","from":"child","to":"deleted","label":""}]}`+ list.SetIALAttr(listMindmapMetadataAttr, original)+ next, changed := pruneListMindmapMetadata(list)+ if !changed || strings.Contains(next, "deleted") || strings.Count(next, "9007199254740993") != 2 {+ t.Fatalf("unexpected metadata: %s", next)+ }+ var result map[string]json.RawMessage+ _ = json.Unmarshal([]byte(next), &result)+ var nodes map[string]json.RawMessage+ _ = json.Unmarshal(result["nodes"], &nodes)+ if len(nodes) != 2 || nodes[list.ID] == nil || nodes[child.ID] == nil {+ t.Fatalf("root or folded descendant lost: %s", result["nodes"])+ }+ list.SetIALAttr(listMindmapMetadataAttr, next)+ if again, changed := pruneListMindmapMetadata(list); changed || again != next {+ t.Fatal("normalization should be idempotent")+ }+ child.Unlink()+ if next, changed = pruneListMindmapMetadata(list); !changed || strings.Contains(next, `"child"`) {+ t.Fatalf("deleted child retained: %s", next)+ }+}++func TestPruneListMindmapExcludesListsInsideContentBlocks(t *testing.T) {+ _, list, child := mindmapTestTree()+ quote := &ast.Node{Type: ast.NodeBlockquote, ID: "quote"}+ list.FirstChild.AppendChild(quote)+ inner := &ast.Node{Type: ast.NodeList, ID: "quoted-list"}+ quote.AppendChild(inner)+ inner.AppendChild(&ast.Node{Type: ast.NodeListItem, ID: "quoted-item"})+ list.SetIALAttr(listMindmapMetadataAttr, `{"version":1,"nodes":{"child":{},"quoted-item":{}},"relations":[]}`)+ next, changed := pruneListMindmapMetadata(list)+ if !changed || strings.Contains(next, "quoted-item") || !strings.Contains(next, child.ID) {+ t.Fatalf("content block list was treated as a mind map branch: %s", next)+ }+}++func TestPruneListMindmapPreservesInvalidMetadata(t *testing.T) {+ for _, value := range []string{+ `broken`, `null`, `{"version":2,"nodes":{"deleted":{}},"relations":[]}`,+ `{"version":1,"nodes":{"deleted":{"bold":"true"}},"relations":[]}`,+ `{"version":1,"nodes":{},"relations":[{"id":"r","from":"a","to":"b"}]}`,+ `{"version":1,"nodes":{},"relations":[{"id":"r","from":"a","to":"b","label":""},{"id":"r","from":"b","to":"a","label":""}]}`,+ } {+ _, list, _ := mindmapTestTree()+ list.SetIALAttr(listMindmapMetadataAttr, value)+ if next, changed := pruneListMindmapMetadata(list); changed || next != value {+ t.Fatalf("invalid configuration changed: %s", value)+ }+ }+}++func TestNormalizeListMindmapTransactions(t *testing.T) {+ for _, withUndo := range []bool{false, true} {+ tree, list, child := mindmapTestTree()+ original := `{"version":1,"nodes":{"child":{"bold":true}},"relations":[{"id":"r","from":"` + list.ID + `","to":"child","label":""}]}`+ list.SetIALAttr(listMindmapMetadataAttr, original)+ parent := child.Parent+ child.Unlink()+ tx := &Transaction{trees: map[string]*parse.Tree{tree.ID: tree}, DoOperations: []*Operation{{Action: "delete", ID: child.ID}}}+ if withUndo {+ tx.UndoOperations = []*Operation{{Action: "insert", ID: child.ID}}+ }+ if ret := tx.normalizeListMindmapMetadata(); ret != nil {+ t.Fatal(ret)+ }+ cleaned := list.IALAttr(listMindmapMetadataAttr)+ if strings.Contains(cleaned, `"child"`) || len(tx.DoOperations) != 2 {+ t.Fatalf("delete did not clean or broadcast: %s", cleaned)+ }+ if !withUndo {+ if len(tx.UndoOperations) != 0 {+ t.Fatal("API transaction without undo gained an incomplete undo entry")+ }+ continue+ }+ if len(tx.UndoOperations) != 2 || tx.UndoOperations[0].Action != "setAttrs" {+ t.Fatal("cleanup not included in undo")+ }+ var attrs map[string]string+ _ = json.Unmarshal([]byte(tx.UndoOperations[0].Data.(string)), &attrs)+ list.SetIALAttr(listMindmapMetadataAttr, attrs[listMindmapMetadataAttr])+ parent.AppendChild(child)+ if list.IALAttr(listMindmapMetadataAttr) != original {+ t.Fatal("undo lost original styles or relations")+ }+ child.Unlink()+ _ = json.Unmarshal([]byte(tx.DoOperations[1].Data.(string)), &attrs)+ list.SetIALAttr(listMindmapMetadataAttr, attrs[listMindmapMetadataAttr])+ if list.IALAttr(listMindmapMetadataAttr) != cleaned {+ t.Fatal("redo failed to restore cleaned metadata")+ }+ }+}++func TestNormalizeListMindmapKeepsReinsertedNodesAndReplay(t *testing.T) {+ tree, list, child := mindmapTestTree()+ original := `{"version":1,"nodes":{"child":{}},"relations":[]}`+ list.SetIALAttr(listMindmapMetadataAttr, original)+ parent := child.Parent+ child.Unlink()+ parent.AppendChild(child)+ tx := &Transaction{trees: map[string]*parse.Tree{tree.ID: tree},+ DoOperations: []*Operation{{Action: "delete", ID: child.ID}, {Action: "insert", ID: child.ID}}}+ if ret := tx.normalizeListMindmapMetadata(); ret != nil || len(tx.DoOperations) != 2 || list.IALAttr(listMindmapMetadataAttr) != original {+ t.Fatal("same-transaction reinsert lost metadata")+ }+ child.Unlink()+ tx.isReplay = true+ if ret := tx.normalizeListMindmapMetadata(); ret != nil || list.IALAttr(listMindmapMetadataAttr) != original {+ t.Fatal("replay changed the recorded snapshot")+ }+}