Skip to content

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

:bug: Enable nested mindmap editing and localize tab placeholders https://github.com/siyuan-note/siyuan/issues/19945

Daniel76b614a9dbf5
diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.ts
index 0d3b9840fb..a150e40e93 100644
--- a/app/src/protyle/render/listMindmap/editor.test.ts
+++ b/app/src/protyle/render/listMindmap/editor.test.ts
@@ -65,6 +65,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
accept: true,
flush: async (): Promise<void> => undefined,
saveBarrier: undefined as Promise<void> | undefined,
+ finishNested: async (): Promise<boolean> => true,
};
const protyle = {
block: {rootID: ""},
@@ -146,6 +147,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
avRender: noop,
blockRender: noop,
highlightRender: noop,
+ finishListMindmaps: () => state.finishNested(),
cleanListMindmapHTML: new Function(cleanupSource + "; return cleanListMindmapHTML;")(),
};
const open = new Function(...Object.keys(dependencies), sourceCode + "; return openListMindmapEditor;")(
@@ -255,6 +257,29 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
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 nestedEditor = create(tabsHTML);
+ nestedEditor.state.finishNested = async () => false;
+ check.equal(await nestedEditor.editor.finish(), false);
+ check.equal(nestedEditor.state.destroyed, 0, "failed nested saves keep the outer editor open");
+ nestedEditor.state.finishNested = async () => {
+ nestedEditor.wysiwyg.querySelector('[data-node-id="paragraph"]').textContent = "Nested edit";
+ return true;
+ };
+ check.equal(await nestedEditor.editor.finish(), true);
+ check.equal(nestedEditor.element.querySelector('[data-node-id="paragraph"]').textContent, "Nested edit");
+ await nestedEditor.remove();
+
+ const nestedKeys = create(tabsHTML);
+ const nestedView = document.createElement("div");
+ nestedView.className = "mindmap-view";
+ nestedView.tabIndex = 0;
+ nestedKeys.wysiwyg.append(nestedView);
+ nestedView.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
+ nestedView.dispatchEvent(new KeyboardEvent("keydown", {key: "Enter", ctrlKey: true, bubbles: true}));
+ await settle();
+ check.equal(nestedKeys.state.finished, 0, "nested shortcuts must not finish the outer editor");
+ check.deepEqual(nestedKeys.state.additions, []);
+ await nestedKeys.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";
diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.ts
index 5ce54fc399..336eedea13 100644
--- a/app/src/protyle/render/listMindmap/editor.ts
+++ b/app/src/protyle/render/listMindmap/editor.ts
@@ -18,6 +18,7 @@ import {blockRender} from "../blockRender";
import {highlightRender} from "../highlightRender";
import {cleanListMindmapHTML} from "./model";
import type {ListMindmapNode} from "./model";
+import {finishListMindmaps} from "./index";
interface ListMindmapEditorOptions {
owner: IProtyle;
@@ -303,6 +304,10 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
finishAfterComposition = true;
return false;
}
+ // 退出外层节点前先保存内层脑图,避免清理预览时遗漏尚未提交的正文。
+ if (!await finishListMindmaps(fragment.protyle)) {
+ return false;
+ }
if (pendingSave) {
await pendingSave;
}
@@ -353,6 +358,10 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
.forEach(type => host.addEventListener(type, event => event.stopPropagation(), {signal}));
host.addEventListener("keydown", event => event.stopPropagation(), {signal});
host.addEventListener("keydown", event => {
+ if (event.target instanceof Element &&
+ fragment.wysiwyg.contains(event.target.closest(".mindmap-view"))) {
+ return;
+ }
if (event.isComposing || composing) {
return;
}
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index bb98f6c332..48ca046eae 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -39,13 +39,18 @@ import {focusListMindmap} from "./create";
import {getListMindmapFoldStates} from "./fold";
import {isMobile} from "../../../util/functions";
import {getListMindmapSiblingIDs, getListMindmapSummaryRange} from "./summary";
+import {isProtyleListItemFragment} from "../../runtimeCapabilities";
const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,
- restoreFocus: (listID: string, candidateIDs: string[]) => void, focusRevision: number, destroy: () => void}>();
+ restoreFocus: (listID: string, candidateIDs: string[]) => void, focusRevision: number,
+ finish: () => Promise<boolean>, destroy: () => void}>();
+
+export const finishListMindmaps = async (owner: IProtyle) => roots.get(owner)?.finish() ?? true;
export const mountNewListMindmap = (owner: IProtyle, list: HTMLElement) => roots.get(owner)?.mountNew(list);
-const canToggleView = (owner: IProtyle, list: HTMLElement) => !owner.disabled && !owner.lite &&
+const canToggleView = (owner: IProtyle, list: HTMLElement) => !owner.disabled &&
+ (!owner.lite || isProtyleListItemFragment(owner)) &&
list.isConnected && !!list.dataset.nodeId &&
!owner.options.action.includes(Constants.CB_GET_HISTORY) &&
list.closest(".protyle-wysiwyg") === owner.wysiwyg.element;
@@ -146,7 +151,8 @@ class ListMindmapController {
}, {capture: true});
this.host.addEventListener("keydown", event => {
if (this.view?.isLocked() || event.isComposing || (event.target instanceof Element &&
- event.target.closest("input, textarea, select, .mindmap-view__editor"))) {
+ (event.target.closest("input, textarea, select") ||
+ this.host.contains(event.target.closest(".mindmap-view__editor"))))) {
return;
}
const keys = owner.options?.action && window.siyuan.config.keymap.editor.general;
@@ -519,7 +525,7 @@ class ListMindmapController {
private async edit(id: string, host: HTMLElement, replaceFirstParagraph?: string) {
const request = ++this.editRequest;
if (!canEdit(this.owner, this.list) || (this.activeEditor && !await this.activeEditor.finish()) ||
- request !== this.editRequest || this.disposed || !host.isConnected) {
+ request !== this.editRequest || this.disposed || !host?.isConnected) {
return;
}
const node = this.model.nodes.get(id);
@@ -574,6 +580,11 @@ class ListMindmapController {
this.view.focusNode(candidateIDs.find(id => this.model.nodes.has(id)) || this.model.root.id);
}
+ public async finish() {
+ await this.taskChanges;
+ return this.activeEditor ? this.activeEditor.finish() : true;
+ }
+
public refresh() {
this.view.setReadOnly(!canEdit(this.owner, this.list));
syncListMindmapHeight(this.list, this.host);
@@ -631,7 +642,7 @@ const completeList = async (owner: IProtyle, list: HTMLElement) => {
};
export const initListMindmaps = (owner: IProtyle) => {
- if (owner.lite || roots.has(owner)) {
+ if (owner.lite && !isProtyleListItemFragment(owner) || roots.has(owner)) {
return;
}
const root = owner.wysiwyg.element;
@@ -718,7 +729,7 @@ export const initListMindmaps = (owner: IProtyle) => {
list.removeAttribute("data-mindmap-view-rendered");
}
};
- if (canEdit(owner, list) && !newlyCreated.has(list)) {
+ if (!owner.lite && canEdit(owner, list) && !newlyCreated.has(list)) {
loading.add(list);
let retry = false;
void completeList(owner, list).then(complete => {
@@ -775,14 +786,21 @@ export const initListMindmaps = (owner: IProtyle) => {
const observer = new MutationObserver(records => {
if (records.some(record => {
const element = record.target instanceof Element ? record.target : record.target.parentElement;
- return !element?.closest(".mindmap-view") && !(record.type === "attributes" &&
+ return !root.contains(element?.closest(".mindmap-view")) && !(record.type === "attributes" &&
["data-mindmap-view-rendered", Constants.ATTRIBUTE_EDITING].includes(record.attributeName));
})) {
schedule();
}
});
observer.observe(root, {childList: true, subtree: true, attributes: true, characterData: true});
- roots.set(owner, {refresh: schedule, mountNew: list => {
+ roots.set(owner, {refresh: schedule, finish: async () => {
+ for (const instance of instances.values()) {
+ if (!await instance.finish()) {
+ return false;
+ }
+ }
+ return true;
+ }, mountNew: list => {
if (root.contains(list)) {
newlyCreated.add(list);
refresh();
diff --git a/app/src/protyle/render/listMindmap/loading.test.ts b/app/src/protyle/render/listMindmap/loading.test.ts
index b7a3837b96..02d11acbce 100644
--- a/app/src/protyle/render/listMindmap/loading.test.ts
+++ b/app/src/protyle/render/listMindmap/loading.test.ts
@@ -27,6 +27,7 @@ const browserCases = async (source: string, css: string) => {
host.style.setProperty("--mindmap-view-height", list.style.height);
},
canEdit: () => true,
+ isProtyleListItemFragment: (owner: {fragment?: boolean}) => owner.fragment === true,
completeList: () => {
requests++;
return new Promise<string>(resolve => { resolveLoad = resolve; });
@@ -43,6 +44,7 @@ const browserCases = async (source: string, css: string) => {
list.insertAdjacentHTML("beforeend", '<div class="mindmap-view">Rendered</div>');
}
refresh() {}
+ async finish() { return true; }
destroy() {}
},
};
@@ -100,6 +102,23 @@ const browserCases = async (source: string, css: string) => {
root.remove();
}
check.deepEqual(errors, []);
+ for (const fragment of [false, true]) {
+ const root = document.createElement("div");
+ root.className = "protyle-wysiwyg";
+ root.innerHTML = '<div data-type="NodeMindmap" data-node-id="local"><div>Local content</div></div>';
+ document.body.append(root);
+ const owner = {lite: true, fragment, wysiwyg: {element: root}};
+ const previousRequests = requests;
+ init(owner);
+ await frame();
+ check.equal(!!root.querySelector(".mindmap-view"), fragment);
+ check.equal(requests, previousRequests, "local fragments must not reload content from the kernel");
+ if (fragment) {
+ check.equal(await roots.get(owner).finish(), true);
+ roots.get(owner).destroy();
+ }
+ root.remove();
+ }
return "Mindmap loading cases passed";
};
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index 8b867094e1..3904eb829f 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -152,7 +152,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
"deleteListMindmapNode, replaceListMindmapContent, cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource, remapListMindmapIDs, writeListMindmapMetadata, retagMindmapBranch, " +
"getListMindmapSiblingIDs, normalizeListMindmapSummaryMetadata, getListMindmapSummaryRange, " +
"normalizeLegacyMindmapCodes, replaceLegacyMindmapHTML, spinListMindmapDOM, focusListMindmap, " +
- "tabsRender, destroyTabsRender, getTabTask, getListMindmapTabItem, convertTabsList, ListMindmapView, registerListMindmapView, resolveVisibleListMindmapBlock};")(
+ "tabsRender, destroyTabsRender, getTabTask, getListMindmapTabItem, convertTabsList, ListMindmapView, registerListMindmapView, resolveVisibleListMindmapBlock, getListMindmapElements, registerListMindmapRoot, restoreListMindmapFocus};")(
async (element: Element) => {
const formulas = element.querySelectorAll('[data-subtype="math"]:not([data-render="true"])');
await Promise.resolve();
@@ -2766,6 +2766,7 @@ 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");
+ tabSource.querySelector(".tab-item-title").textContent = "";
const nestedSource = document.createElement("div");
nestedSource.innerHTML = lute.Md2BlockDOM("- Nested parent\n - Nested child\n");
const nestedList = nestedSource.firstElementChild as HTMLElement;
@@ -2780,6 +2781,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
taskChanges: Promise.resolve(), refresh: () => tabView.update(api.readListMindmap(tabList))});
let tabMenus = 0;
const tabView = new api.ListMindmapView({host: tabHost, model: api.readListMindmap(tabList), onExit: () => {},
+ labels: {tabItem: "页签项块"},
onTabTaskToggle: (id: string, itemID: string) => tabController.setTabTask(id, itemID, taskAPI.nextTaskListMarker),
onTabTaskMenu: (id: string, itemID: string, anchor: HTMLElement) => {
check.equal(id, tabNodeID);
@@ -2788,6 +2790,43 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
tabMenus++;
}});
tabController.view = tabView;
+ check.equal(tabHost.querySelector(".tabs-tab-label").textContent, "页签项块");
+ const fragmentHost = document.createElement("div");
+ fragmentHost.className = "mindmap-view";
+ const fragmentRoot = document.createElement("div");
+ fragmentRoot.className = "protyle-wysiwyg";
+ fragmentRoot.innerHTML = api.cleanListMindmapHTML(nestedList.outerHTML);
+ fragmentHost.append(fragmentRoot);
+ document.body.append(fragmentHost);
+ const fragmentList = fragmentRoot.firstElementChild as HTMLElement;
+ const localLists = api.getListMindmapElements(fragmentRoot);
+ check.equal(localLists.length, 1);
+ check.equal(localLists[0], fragmentList);
+ const previewHost = document.createElement("div");
+ previewHost.className = "mindmap-view";
+ previewHost.append(fragmentList.cloneNode(true));
+ fragmentList.append(previewHost);
+ check.equal(api.getListMindmapElements(fragmentRoot).length, 1, "preview copies are never editable source maps");
+ let restored = "";
+ const unregisterFragment = api.registerListMindmapRoot(fragmentRoot, () => {}, (id: string) => restored = id);
+ check.equal(api.restoreListMindmapFocus(fragmentRoot, fragmentList.firstElementChild), true);
+ check.equal(restored, fragmentList.dataset.nodeId);
+ fragmentHost.classList.add("mindmap-view__node--editing");
+ previewHost.replaceChildren();
+ let nestedEdited = "";
+ const editableNestedView = new api.ListMindmapView({host: previewHost, model: api.readListMindmap(fragmentList),
+ onExit: () => {}, onEdit: (id: string) => nestedEdited = id});
+ const nestedNode = previewHost.querySelector<HTMLElement>(".mindmap-view__node");
+ nestedNode.querySelector(".mindmap-view__content").dispatchEvent(new MouseEvent("dblclick", {bubbles: true}));
+ check.equal(nestedEdited, nestedNode.dataset.mindmapId, "an outer editing node must not disable inner double-clicks");
+ nestedEdited = "";
+ editableNestedView.setEditing(undefined);
+ editableNestedView.focusNode(nestedNode.dataset.mindmapId);
+ nestedNode.dispatchEvent(new KeyboardEvent("keydown", {key: "x", bubbles: true}));
+ check.equal(nestedEdited, nestedNode.dataset.mindmapId, "inner keyboard editing remains available");
+ editableNestedView.destroy();
+ unregisterFragment();
+ fragmentHost.remove();
const outerOptions = {readonly: () => false, task: () => check.fail("Outer editor claimed a preview task")};
api.tabsRender(taskParent, outerOptions);
const tabSnapshot = api.cleanListMindmapHTML(tabList.outerHTML);
diff --git a/app/src/protyle/render/listMindmap/render.ts b/app/src/protyle/render/listMindmap/render.ts
index 1f9a920f99..e9a4d58a42 100644
--- a/app/src/protyle/render/listMindmap/render.ts
+++ b/app/src/protyle/render/listMindmap/render.ts
@@ -22,7 +22,9 @@ export const registerListMindmapView = (list: HTMLElement, view: ListMindmapView
export const resolveVisibleListMindmapBlock = (source: Element): {
carrier: HTMLElement, scrollElement: HTMLElement, reveal: () => void, focus: () => void
} | null | undefined => {
- if (source.closest(".mindmap-view")) {
+ const view = source.closest(".mindmap-view");
+ const editor = source.closest(".protyle-wysiwyg");
+ if (view && (!editor || editor.contains(view))) {
return undefined;
}
const list = source.closest<HTMLElement>('[data-mindmap-view-rendered="true"]');
@@ -76,7 +78,7 @@ export const registerListMindmapRoot = (root: Element, refresh: () => void,
// 撤销回放会替换源块,节点焦点交给编辑器在脑图重新挂载后恢复。
export const restoreListMindmapFocus = (root: Element, source: Element) => {
const registered = editorRoots.get(root);
- if (!registered || source.closest(".mindmap-view")) {
+ if (!registered || root.contains(source.closest(".mindmap-view"))) {
return false;
}
const list = getListMindmapElements(root).find(item => item.contains(source));
@@ -100,8 +102,10 @@ export const getListMindmapElements = (root: Element) => {
if (root.matches(selector)) {
lists.unshift(root as HTMLElement);
}
- return lists.filter(list => !list.closest(".mindmap-view") &&
- !list.parentElement?.closest(selector));
+ return lists.filter(list => (!list.closest(".mindmap-view") ||
+ root.matches(".protyle-wysiwyg") && list.closest(".protyle-wysiwyg") === root &&
+ !root.contains(list.closest(".mindmap-view"))) &&
+ !root.contains(list.parentElement?.closest(selector)));
};
// 导出页面和只读预览共用节点布局,源列表始终保留在文档中。
diff --git a/app/src/protyle/render/listMindmap/view.ts b/app/src/protyle/render/listMindmap/view.ts
index 0323f5dc5b..8a359d80f4 100644
--- a/app/src/protyle/render/listMindmap/view.ts
+++ b/app/src/protyle/render/listMindmap/view.ts
@@ -721,6 +721,7 @@ export class ListMindmapView {
content.dataset.placeholder = this.label("listMindmapPlaceholder");
if (content.querySelector('.tabs[data-type="NodeTabs"]')) {
tabsRender(content, {
+ label: this.label("tabItem"),
readonly: () => true,
taskReadonly: () => !!this.readOnly || !this.options.onTabTaskToggle,
taskLabel: this.label("taskList"),
@@ -1801,7 +1802,8 @@ export class ListMindmapView {
private pinchStart = (event: TouchEvent) => {
if (this.locked || event.touches.length !== 2 || Array.from(event.touches).some(touch =>
!this.viewport.contains(touch.target as Node) ||
- (touch.target as Element).closest("button, input, select, textarea, audio, video, iframe, .mindmap-view__node--editing"))) {
+ ((touch.target as Element).closest("button, input, select, textarea, audio, video, iframe") ||
+ this.viewport.contains((touch.target as Element).closest(".mindmap-view__node--editing"))))) {
this.pinch = undefined;
return;
}
@@ -1851,7 +1853,8 @@ export class ListMindmapView {
this.suppressLinkClick = false;
this.suppressPanContextMenu = false;
const target = event.target as HTMLElement;
- if (![0, 2].includes(event.button) || target.closest("button, input, select, textarea, audio, video, iframe, .mindmap-view__node--editing")) {
+ if (![0, 2].includes(event.button) || target.closest("button, input, select, textarea, audio, video, iframe") ||
+ this.viewport.contains(target.closest(".mindmap-view__node--editing"))) {
return;
}
if (event.button === 0 && !this.panning && target.closest(".mindmap-view__summary")) {
@@ -2213,7 +2216,7 @@ export class ListMindmapView {
private contentClick = (event: MouseEvent) => {
const target = event.target as Element;
- if (target.closest(".mindmap-view__node--editing")) {
+ if (this.viewport.contains(target.closest(".mindmap-view__node--editing"))) {
return;
}
const link = target.closest<HTMLElement>('a[href], [data-type~="a"][data-href], [data-type~="block-ref"][data-id]');
@@ -2257,7 +2260,8 @@ export class ListMindmapView {
this.editRelationLabel(event);
return;
}
- if (target.closest("button, input, select, audio, video, iframe, .mindmap-view__node--editing")) {
+ if (target.closest("button, input, select, audio, video, iframe") ||
+ this.viewport.contains(target.closest(".mindmap-view__node--editing"))) {
return;
}
const id = target.closest<HTMLElement>(".mindmap-view__node")?.dataset.mindmapId;
@@ -2277,12 +2281,16 @@ export class ListMindmapView {
event.stopPropagation();
this.cancelPointer();
this.finishThen(() => {
+ const content = this.getContentHost(id);
+ if (!content?.isConnected || !this.model.nodes.has(id)) {
+ return;
+ }
if (this.model.nodes.get(id)?.virtual) {
this.editRootTitle(id);
return;
}
this.setEditing(id);
- this.options.onEdit?.(id, this.getContentHost(id));
+ this.options.onEdit?.(id, content);
});
};
@@ -2385,7 +2393,7 @@ export class ListMindmapView {
}
private wheel = (event: WheelEvent) => {
- if (this.locked || (event.target as HTMLElement).closest(".mindmap-view__node--editing")) {
+ if (this.locked || this.viewport.contains((event.target as HTMLElement).closest(".mindmap-view__node--editing"))) {
return;
}
if (this.pointer?.relation) {
@@ -2519,7 +2527,8 @@ export class ListMindmapView {
const target = event.target as HTMLElement;
const startingComposition = event.isComposing || event.key === "Process" || event.key === "Dead" ||
event.keyCode === 229;
- if (target.closest("input, textarea, select, audio, video, iframe, .mindmap-view__node--editing")) {
+ if (target.closest("input, textarea, select, audio, video, iframe") ||
+ this.viewport.contains(target.closest(".mindmap-view__node--editing"))) {
return;
}
if (this.pointer?.relation && event.key !== "Escape") {