Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Preserve tabbed mindmap edits and nested previews https://github.com/siyuan-note/siyuan/issues/19945

Daniel5941276f722a
diff --git a/app/src/assets/scss/protyle/_mindmap-view.scss b/app/src/assets/scss/protyle/_mindmap-view.scss
index e8aee7c837..c44a2434af 100644
--- a/app/src/assets/scss/protyle/_mindmap-view.scss
+++ b/app/src/assets/scss/protyle/_mindmap-view.scss
@@ -40,6 +40,16 @@
line-height: 1.5;
outline: none;
+ &--nested {
+ width: 260px;
+ --mindmap-view-height: 260px;
+ pointer-events: none;
+
+ > .mindmap-view__toolbar {
+ display: none;
+ }
+ }
+
&__preview-block.protyle-wysiwyg--hl {
position: relative;
}
diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.ts
index 6f0d937337..0d3b9840fb 100644
--- a/app/src/protyle/render/listMindmap/editor.test.ts
+++ b/app/src/protyle/render/listMindmap/editor.test.ts
@@ -7,7 +7,7 @@ import test from "node:test";
import {promisify} from "node:util";
import {ScriptTarget, transpileModule} from "typescript";
-const browserCases = async (sourceCode: string, css: string) => {
+const browserCases = async (sourceCode: string, css: string, cleanupSource: string) => {
const check = require("node:assert/strict");
const noop = (): void => undefined;
const settle = async () => {
@@ -146,7 +146,7 @@ const browserCases = async (sourceCode: string, css: string) => {
avRender: noop,
blockRender: noop,
highlightRender: noop,
- cleanListMindmapHTML: (html: string) => html,
+ cleanListMindmapHTML: new Function(cleanupSource + "; return cleanListMindmapHTML;")(),
};
const open = new Function(...Object.keys(dependencies), sourceCode + "; return openListMindmapEditor;")(
...Object.values(dependencies));
@@ -239,6 +239,30 @@ const browserCases = async (sourceCode: string, css: string) => {
await current.remove();
}
+ // 页签重新渲染和切换编辑状态不会伪造正文冲突,隐藏页签的内容仍参与冲突检测。
+ const tabsHTML = '<div data-type="NodeTabs" data-node-id="tabs" class="tabs" tabs-position="top">' +
+ '<div data-type="NodeTabItem" data-node-id="tab" class="tab-item"><div class="tab-item-info">Title</div>' +
+ '<div class="tab-item-content">' + textHTML("Body") + "</div></div></div>";
+ const tabsEditor = create(tabsHTML);
+ tabsEditor.element.firstElementChild.insertAdjacentHTML("afterbegin", '<div class="tabs-header">Navigation</div>');
+ tabsEditor.element.querySelector(".tab-item-content").setAttribute("id", "siyuan-tabs-1-panel-0");
+ tabsEditor.wysiwyg.querySelector(".tab-item-content").setAttribute("id", "siyuan-tabs-2-panel-0");
+ tabsEditor.wysiwyg.querySelector(".tab-item").setAttribute("data-tabs-editing", "true");
+ tabsEditor.wysiwyg.querySelector('[data-node-id="paragraph"]').textContent = "Edited body";
+ await settle();
+ check.equal(await tabsEditor.editor.finish(), true);
+ check.equal(tabsEditor.state.messages.length, 0);
+ check.equal(tabsEditor.element.querySelector('[data-node-id="paragraph"]').textContent, "Edited body");
+ check.equal(tabsEditor.element.querySelector(".tabs").getAttribute("tabs-position"), "top");
+ await tabsEditor.remove();
+ const conflictingTabs = create(tabsHTML);
+ conflictingTabs.element.querySelector('[data-node-id="paragraph"]').textContent = "External change";
+ conflictingTabs.wysiwyg.querySelector('[data-node-id="paragraph"]').textContent = "Local change";
+ await settle();
+ check.equal(await conflictingTabs.editor.finish(), false);
+ check.equal(conflictingTabs.state.saves.length, 0);
+ await conflictingTabs.remove();
+
// 数据库和嵌入结果在编辑期间重新渲染,不会挡住普通文字保存或覆盖新的独立块状态。
for (const type of ["NodeAttributeView", "NodeBlockQueryEmbed"]) {
const special = document.createElement("div");
@@ -623,6 +647,10 @@ test("list mindmap editor flushes pending input and preserves text across finish
const css = require("sass").compile(path.resolve(__dirname, "../../../assets/scss/base.scss"), {
logger: require("sass").Logger.silent,
}).css;
+ const modelSource = readFileSync(path.join(__dirname, "model.ts"), "utf8");
+ const cleanupSource = transpileModule(modelSource.slice(modelSource.indexOf("const cleanListMindmapDOM ="),
+ modelSource.indexOf("// 转换前将思维导图块还原为列表结构"))
+ .replace(/^export /gm, ""), {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
const code = `const {app, BrowserWindow, ipcMain} = require("electron");
app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});
app.commandLine.appendSwitch("disable-gpu");
@@ -634,7 +662,7 @@ app.whenReady().then(async () => {
try {
await win.loadURL("data:text/html,<html><body></body></html>");
const result = await win.webContents.executeJavaScript(${JSON.stringify(
- `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(css)})`)});
+ `const __name = value => value; (${browserCases.toString()})(${JSON.stringify(source)}, ${JSON.stringify(css)}, ${JSON.stringify(cleanupSource)})`)});
console.log(result);
win.destroy();
app.exit(0);
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index 05327e964a..8b867094e1 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -2766,6 +2766,11 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
tabContent.innerHTML = lute.Md2BlockDOM("::: tabs\n@tab First\n\nOne\n@tab Second\n\nTwo\n:::\n{: tabs-task=\"true\"}\n");
tabNode.querySelector(".p").replaceWith(tabContent.firstElementChild);
const tabSource = tabNode.querySelector<HTMLElement>(".tabs");
+ const nestedSource = document.createElement("div");
+ nestedSource.innerHTML = lute.Md2BlockDOM("- Nested parent\n - Nested child\n");
+ const nestedList = nestedSource.firstElementChild as HTMLElement;
+ api.retagMindmapBranch(nestedList, true);
+ tabSource.querySelectorAll(".tab-item-content")[1].append(nestedList);
const sourceActiveTab = tabSource.getAttribute("tabs-active-id");
const tabItemIDs = Array.from(tabSource.querySelectorAll<HTMLElement>(":scope > .tab-item"))
.map(item => item.dataset.nodeId);
@@ -2785,9 +2790,29 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
tabController.view = tabView;
const outerOptions = {readonly: () => false, task: () => check.fail("Outer editor claimed a preview task")};
api.tabsRender(taskParent, outerOptions);
+ const tabSnapshot = api.cleanListMindmapHTML(tabList.outerHTML);
+ api.destroyTabsRender(taskParent);
+ api.tabsRender(taskParent, outerOptions);
+ check.equal(api.cleanListMindmapHTML(tabList.outerHTML), tabSnapshot,
+ "recreating tab navigation must not change the mindmap content snapshot");
+ const savedTabs = document.createElement("div");
+ savedTabs.innerHTML = tabSnapshot;
+ check.equal(savedTabs.querySelector(".tabs-header, .tabs-divider, [data-tabs-hidden]"), null);
+ check.equal(savedTabs.querySelectorAll(".tab-item").length, 2, "hidden tab content is retained");
+ check.equal(savedTabs.querySelector(".tabs").getAttribute("tabs-task"), "true");
+ check.equal(lute.BlockDOM2StdMd(savedTabs.querySelector(".tabs").outerHTML), lute.BlockDOM2StdMd(tabSource.outerHTML));
const previewTask = (index = 1) => tabHost.querySelectorAll<HTMLElement>(".tabs-task")[index];
const previewTab = (index = 1) => tabHost.querySelectorAll<HTMLElement>(".tabs-tab")[index];
previewTab().click();
+ const nestedPreview = () => tabHost.querySelector<HTMLElement>(".mindmap-view--nested");
+ check.ok(nestedPreview());
+ check.equal(nestedPreview().querySelectorAll(".mindmap-view__node").length, 2);
+ check.equal(nestedPreview().getAttribute("role"), "img");
+ check.ok(nestedPreview().getAttribute("aria-label").includes("Nested child"));
+ check.ok(Array.from(nestedPreview().children).every((child: HTMLElement) => child.inert),
+ "nested previews leave editing to their owner node");
+ check.ok(nestedPreview().textContent.includes("Nested child"));
+ const previousNestedView = (tabView as any).nestedViews.get(tabNodeID)[0];
operations.length = 0;
previewTask().click();
await tabController.taskChanges;
@@ -2795,6 +2820,8 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
check.equal(operations[0].id, tabList.dataset.nodeId);
check.equal(api.getTabTask(api.getListMindmapTabItem(tabList, tabNodeID, tabItemIDs[1])), "X");
check.equal(previewTask().getAttribute("data-task"), "X");
+ check.equal(previousNestedView.destroyed, true, "refresh disposes the nested view and its observers");
+ check.ok(nestedPreview());
check.equal(previewTab().getAttribute("aria-selected"), "true", "saving a task preserves the visible preview tab");
check.equal(tabHost.querySelector(".tabs-control"), null, "preview only exposes supported writes");
check.equal(tabHost.querySelector("[data-node-id]"), null);
@@ -2838,7 +2865,16 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
removedTab.remove();
await tabController.setTabTask(tabNodeID, tabItemIDs[1], () => "X");
check.equal(operations.length, savedCount, "removed tab IDs never produce an update");
+ const lastNestedView = (tabView as any).nestedViews.get(tabNodeID)[0];
+ tabView.setEditing(tabNodeID);
+ check.equal(lastNestedView.destroyed, true, "entering the fragment editor disposes its nested previews");
+ tabView.setEditing(undefined);
+ tabSource.append(removedTab);
+ tabView.update(api.readListMindmap(tabList));
+ const finalNestedViews = Array.from((tabView as any).nestedViews.values()).flat();
+ check.equal(finalNestedViews.length, 1);
tabView.destroy();
+ check.ok(finalNestedViews.every((view: any) => view.destroyed));
api.destroyTabsRender(taskParent);
taskParent.remove();
diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.ts
index 6b05dab8b3..04ae9adc34 100644
--- a/app/src/protyle/render/listMindmap/model.ts
+++ b/app/src/protyle/render/listMindmap/model.ts
@@ -290,6 +290,19 @@ export const readListMindmap = (list: HTMLElement): ListMindmapModel => {
const cleanListMindmapDOM = (root: Element | DocumentFragment) => {
root.querySelectorAll(".mindmap-view, .list-mindmap").forEach(element => element.remove());
+ // 页签导航和面板标识由渲染器生成,不参与正文比较或脑图节点事务。
+ root.querySelectorAll(".tabs-header, .tabs-divider, .tabs-attributes").forEach(element => element.remove());
+ root.querySelectorAll('[data-type="NodeTabs"], [data-type="NodeTabItem"]').forEach(element => {
+ ["data-tabs-ready", "data-tabs-orientation", "data-tabs-hidden", "data-tabs-editing", "data-tabs-attributes"]
+ .forEach(name => element.removeAttribute(name));
+ });
+ root.querySelectorAll(".tab-item-content").forEach(element => {
+ ["id", "role", "aria-labelledby", "tabindex"].forEach(name => element.removeAttribute(name));
+ });
+ root.querySelectorAll(".tab-item-info").forEach(element => {
+ element.classList.remove("tabs-title-editor");
+ element.removeAttribute("style");
+ });
const elements = Array.from(root.querySelectorAll("[data-mindmap-view-rendered], [data-mindmap-view-editing]"));
if (root.nodeType === 1) {
elements.push(root as Element);
@@ -309,7 +322,7 @@ const cleanListMindmapDOM = (root: Element | DocumentFragment) => {
};
export const cleanListMindmapHTML = (html: string): string => {
- if (!html.includes("mindmap-view") && !html.includes("list-mindmap")) {
+ if (!html.includes("mindmap-view") && !html.includes("list-mindmap") && !html.includes("NodeTabs")) {
return html;
}
const template = document.createElement("template");
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index bdc906b769..0323f5dc5b 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -5,6 +5,7 @@ import {
ListMindmapNodeStyle,
ListMindmapPosition,
ListMindmapRelation,
+ readListMindmap,
} from "./model";
import {routeMindmapRelation, routeManualMindmapRelation, adjustMindmapRoute,
MindmapRoutePoint, MindmapManualRoute} from "./routing";
@@ -109,6 +110,7 @@ export class ListMindmapView {
private readonly zoomLabel: HTMLSpanElement;
private readonly zoomSlider = createElement("input", "b3-slider");
private readonly nodeElements = new Map<string, HTMLDivElement>();
+ private readonly nestedViews = new Map<string, ListMindmapView[]>();
private readonly previewID = `mindmap-view-${Lute.NewNodeID()}-`;
private readonly relationElements = new Map<string, HTMLButtonElement>();
private readonly summaryElements = new Map<string, HTMLDivElement>();
@@ -576,7 +578,7 @@ export class ListMindmapView {
}
this.nodeElements.forEach((element, id) => {
if (!model.nodes.has(id)) {
- destroyTabsRender(this.getContentHost(id));
+ this.destroyContentViews(id);
this.resizeObserver.unobserve(element);
element.remove();
this.nodeElements.delete(id);
@@ -631,14 +633,14 @@ export class ListMindmapView {
content.querySelectorAll<HTMLElement>('.tab-item[data-tabs-hidden="false"]').forEach(item => {
activeTabs.set(item.parentElement.id, item.id);
});
- destroyTabsRender(content);
+ this.destroyContentViews(id);
content.replaceChildren();
const sourceTabIDs = new Map<string, string>();
if (node.virtual) {
content.textContent = this.model.metadata.rootTitle || "";
} else {
node.contentBlocks.forEach((block) => {
- const clone = block.cloneNode(true) as HTMLElement;
+ let clone = block.cloneNode(true) as HTMLElement;
const sourceCanvases = block.querySelectorAll("canvas");
clone.querySelectorAll("canvas").forEach((canvas, index) => {
const source = sourceCanvases[index];
@@ -647,6 +649,22 @@ export class ListMindmapView {
}
});
const previewTabIDs = new Map<string, string>();
+ // 嵌套脑图使用独立模型生成静态预览,双击仍由外层节点打开正文编辑。
+ const nested: {host: HTMLElement, model: ListMindmapModel}[] = [];
+ const selector = '[data-type="NodeMindmap"], [data-type="NodeList"][custom-sy-list-mindmap="1"]';
+ const nestedLists = Array.from(clone.querySelectorAll<HTMLElement>(selector));
+ if (clone.matches(selector)) {
+ nestedLists.unshift(clone);
+ }
+ nestedLists.filter(list => !list.parentElement?.closest(selector)).forEach(list => {
+ const host = createElement("div", "mindmap-view--nested");
+ nested.push({host, model: readListMindmap(list)});
+ if (list === clone) {
+ clone = host;
+ } else {
+ list.replaceWith(host);
+ }
+ });
clone.querySelectorAll(".protyle-attr, .protyle-action, .protyle-action__table, .protyle-icons, .mindmap-view")
.forEach(item => item.remove());
[clone, ...Array.from(clone.querySelectorAll<HTMLElement>("*"))].forEach((item) => {
@@ -679,6 +697,20 @@ export class ListMindmapView {
}
});
content.append(clone);
+ nested.forEach(({host, model}) => {
+ const view = new ListMindmapView({host, model, readOnly: true,
+ printLayout: this.options.printLayout, labels: this.options.labels,
+ cdn: this.options.cdn, onExit: () => {}});
+ host.setAttribute("role", "img");
+ host.setAttribute("aria-label", Array.from(model.nodes.values()).map(node =>
+ node.virtual ? model.metadata.rootTitle || "" :
+ node.contentBlocks.map(block => block.textContent).join("\n")).join("\n") || this.label("mindmap"));
+ Array.from(host.children).forEach((child: HTMLElement) => child.inert = true);
+ host.tabIndex = -1;
+ const views = this.nestedViews.get(id) || [];
+ views.push(view);
+ this.nestedViews.set(id, views);
+ });
});
}
const hasBlankLines = node.contentBlocks.length > 1 || content.textContent.includes("\n") ||
@@ -739,6 +771,12 @@ export class ListMindmapView {
return this.nodeElements.get(id)?.querySelector<HTMLElement>(".mindmap-view__content");
}
+ private destroyContentViews(id: string) {
+ this.nestedViews.get(id)?.forEach(view => view.destroy());
+ this.nestedViews.delete(id);
+ destroyTabsRender(this.getContentHost(id));
+ }
+
public getBlockById(id: string) {
return this.nodeElements.get(id) ||
this.options.host.querySelector<HTMLElement>(`[data-mindmap-source-id="${id}"]`);
@@ -795,7 +833,7 @@ export class ListMindmapView {
}
this.editingId = id;
if (id) {
- destroyTabsRender(this.getContentHost(id));
+ this.destroyContentViews(id);
this.selectNode(id);
this.nodeElements.get(id)?.classList.add("mindmap-view__node--editing");
}
@@ -2812,7 +2850,7 @@ export class ListMindmapView {
this.resizeObserver.disconnect();
this.disposers.forEach(dispose => dispose());
this.exitFullscreen();
- this.nodeElements.forEach((_element, id) => destroyTabsRender(this.getContentHost(id)));
+ this.nodeElements.forEach((_element, id) => this.destroyContentViews(id));
this.nodeElements.clear();
this.relationElements.clear();
this.summaryElements.clear();