Skip to content

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

:sparkles: Support editing embedded mind maps https://github.com/siyuan-note/siyuan/issues/20658

Daniel9d5626a84a5e
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
index 61aa834d5d..e331914540 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
@@ -2005,7 +2005,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "Use Lock view in the mind map toolbar to prevent editing, zooming and panning. Swiping or using the mouse wheel over the map then scrolls the document. Use Unlock view to resume interaction. The lock state is saved with the block."
+ "Data": "Use Lock view in the mind map toolbar to prevent editing, zooming and panning. Swiping or using the mouse wheel over the map then scrolls the document. Use Unlock view to resume interaction. The lock state is saved with the block. When directly embedding a complete mind map block or a document containing it, unlock the map to edit its nodes and styles. Changes update the source block and other embedded copies. Read-only and history previews remain non-editable."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
index 59fa18bcfa..aef436d104 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
@@ -2008,7 +2008,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "点击思维导图工具栏中的“锁定视图”后,禁止编辑、缩放和平移,在导图上滑动或滚动鼠标滚轮将滚动文档。点击“解锁视图”可恢复操作。锁定状态随块保存。"
+ "Data": "点击思维导图工具栏中的“锁定视图”后,禁止编辑、缩放和平移,在导图上滑动或滚动鼠标滚轮将滚动文档。点击“解锁视图”可恢复操作。锁定状态随块保存。直接嵌入完整思维导图块或包含它的文档时,解锁后可编辑节点和样式,修改会同步到源块及其他嵌入位置;只读和历史预览中仍不能编辑。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
index 18117ccdd7..45af58e6d0 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
@@ -2006,7 +2006,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "點擊思維導圖工具列中的「鎖定視圖」後,禁止編輯、縮放和平移,在導圖上滑動或滾動滑鼠滾輪將捲動文件。點擊「解鎖視圖」可恢復操作。鎖定狀態隨區塊儲存。"
+ "Data": "點擊思維導圖工具列中的「鎖定視圖」後,禁止編輯、縮放和平移,在導圖上滑動或滾動滑鼠滾輪將捲動文件。點擊「解鎖視圖」可恢復操作。鎖定狀態隨區塊儲存。直接嵌入完整心智圖區塊或包含它的文件時,解鎖後可編輯節點和樣式,修改會同步至來源區塊及其他嵌入位置;唯讀和歷史預覽中仍不能編輯。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
index 109e3da927..64c92907e0 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
@@ -2134,7 +2134,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "マインドマップのツールバーで「表示をロック」を押すと、編集、拡大・縮小、移動が無効になります。マップ上でのスワイプやマウスホイール操作は文書をスクロールします。「表示のロックを解除」で操作を再開できます。ロック状態はブロックとともに保存されます。"
+ "Data": "マインドマップのツールバーで「表示をロック」を押すと、編集、拡大・縮小、移動が無効になります。マップ上でのスワイプやマウスホイール操作は文書をスクロールします。「表示のロックを解除」で操作を再開できます。ロック状態はブロックとともに保存されます。マインドマップブロック全体、またはそれを含む文書を直接埋め込んだ場合、ロックを解除するとノードやスタイルを編集できます。変更は元のブロックと他の埋め込み先にも反映されます。読み取り専用や履歴のプレビューでは編集できません。"
}
]
},
diff --git a/app/src/protyle/render/listMindmap/connectorMenu.test.ts b/app/src/protyle/render/listMindmap/connectorMenu.test.ts
index 675da9c06b..a9ca4adcf0 100644
--- a/app/src/protyle/render/listMindmap/connectorMenu.test.ts
+++ b/app/src/protyle/render/listMindmap/connectorMenu.test.ts
@@ -29,7 +29,8 @@ test("desktop and mobile connector menus persist one undoable change and preserv
for (const mobile of [false, true]) {
let data = {version: 2, nodes: {child: {lineColor: "red"}}, relations: [] as unknown[], extension: "keep"};
const original = JSON.stringify(data);
- const list = {isConnected: true, dataset: {nodeId: "map"}, get outerHTML() { return JSON.stringify(data); }};
+ const list = {isConnected: true, dataset: {nodeId: "map"}, closest: (): null => null,
+ get outerHTML() { return JSON.stringify(data); }};
const transactions: {before: string, after: string}[] = [];
let editable = true;
let item: IMenu;
diff --git a/app/src/protyle/render/listMindmap/conversion.test.ts b/app/src/protyle/render/listMindmap/conversion.test.ts
index 96699078c8..8ea1eb9e90 100644
--- a/app/src/protyle/render/listMindmap/conversion.test.ts
+++ b/app/src/protyle/render/listMindmap/conversion.test.ts
@@ -12,6 +12,7 @@ const setup = () => {
const calls: string[] = [];
const root = {};
let embedded = false;
+ let allowChildOperation = false;
const owner = {block: {rootID: "doc"}, notebookId: "box", disabled: false, lite: false, fragment: false,
options: {action: [] as string[]}, wysiwyg: {element: root, flushPendingInput: async () => { calls.push("flush"); }}};
const attributes = new Map([["data-node-id", "map"], ["data-type", "NodeMindmap"]]);
@@ -25,6 +26,7 @@ const setup = () => {
const pending = new Promise((done, fail) => { resolve = done; reject = fail; });
const dependencies = {
Constants: {CB_GET_HISTORY: "history"}, normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,
+ getEmbedChildOperationContext: () => allowChildOperation ? {resultElement: {dataset: {rootId: "source-doc"}}} : undefined,
isProtyleListItemFragment: (protyle: typeof owner) => protyle.fragment,
fetchSyncPost: (url: string, data: unknown) => {
assert.equal(url, "/api/block/getBlockDOM");
@@ -43,7 +45,7 @@ const setup = () => {
const prepare = new Function(...Object.keys(dependencies), source + "; return prepareListMindmapConversion;")(
...Object.values(dependencies));
return {owner, list, calls, attributes, fullAttributes, prepare, resolve, reject,
- embed: () => { embedded = true; }};
+ embed: (allow = false) => { embedded = true; allowChildOperation = allow; }};
};
const flush = async () => { for (let index = 0; index < 6; index++) { await Promise.resolve(); } };
@@ -80,6 +82,20 @@ test("an editable list-item fragment keeps its local full content without a serv
assert.deepEqual(state.calls, ["flush", "wait"]);
});
+test("editable embedded roots complete their source even inside a local list-item fragment", async () => {
+ for (const lite of [false, true]) {
+ const state = setup();
+ state.embed(true);
+ state.owner.lite = lite;
+ state.owner.fragment = lite;
+ const promise = state.prepare(state.owner, state.list);
+ await flush();
+ assert.deepEqual(state.calls, ["flush", "wait", "fetch"]);
+ state.resolve({code: 0, data: {dom: "full"}});
+ assert.deepEqual(await promise, {outerHTML: "completed"});
+ }
+});
+
test("late source reads cannot overwrite edits or a changed document", async () => {
for (const mode of ["content", "document", "notebook", "readonly", "history", "embed", "editor", "removed", "type", "id"]) {
const state = setup();
diff --git a/app/src/protyle/render/listMindmap/conversion.ts b/app/src/protyle/render/listMindmap/conversion.ts
index 34fab26adc..71d25347b6 100644
--- a/app/src/protyle/render/listMindmap/conversion.ts
+++ b/app/src/protyle/render/listMindmap/conversion.ts
@@ -5,6 +5,7 @@ import {waitForPendingTransactions} from "../../util/transactionQueue";
import {completeTabsListSource} from "../../wysiwyg/tabsList";
import {isProtyleListItemFragment} from "../../runtimeCapabilities";
import {cleanListMindmapHTML} from "./model";
+import {getEmbedChildOperationContext} from "../../wysiwyg/getBlock";
// 标题转换会改动列表层级,先补齐源块,并在异步读取后复核编辑器和正文。
export const prepareListMindmapConversion = async (owner: IProtyle, list: Element): Promise<Element | undefined> => {
@@ -16,7 +17,8 @@ export const prepareListMindmapConversion = async (owner: IProtyle, list: Elemen
(!owner.lite || isProtyleListItemFragment(owner)) &&
owner.block.rootID === rootID && owner.notebookId === notebookId &&
!owner.options.action.includes(Constants.CB_GET_HISTORY) &&
- !list.closest(".protyle-wysiwyg__embed") &&
+ (!list.closest(".protyle-wysiwyg__embed") ||
+ !!getEmbedChildOperationContext(list)?.resultElement.dataset.rootId) &&
list.closest(".protyle-wysiwyg") === owner.wysiwyg.element &&
list.getAttribute("data-node-id") === id && list.getAttribute("data-type") === type;
if (!isCurrent()) {
@@ -29,7 +31,7 @@ export const prepareListMindmapConversion = async (owner: IProtyle, list: Elemen
}
const before = cleanListMindmapHTML(list.outerHTML);
const template = list.ownerDocument.createElement("template");
- if (owner.lite) {
+ if (owner.lite && !list.closest(".protyle-wysiwyg__embed")) {
// 列表项片段持有完整的本地正文,尚未提交的内容不能被内核快照替换。
template.innerHTML = before;
return template.content.firstElementChild;
diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.ts
index f0b763eb13..c74b26dffc 100644
--- a/app/src/protyle/render/listMindmap/editor.test.ts
+++ b/app/src/protyle/render/listMindmap/editor.test.ts
@@ -40,11 +40,16 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
block.textContent = text;
return block.outerHTML;
};
- const create = (initialBlockHTML = textHTML("Initial"), replaceFirstParagraph?: string, branchType = "NodeList") => {
+ const create = (initialBlockHTML = textHTML("Initial"), replaceFirstParagraph?: string,
+ branchType = "NodeList", embedded = false) => {
let transactionOwner: (operations: Array<{action: string; id: string; parentID?: string;
previousID?: string; nextID?: string}>) => unknown;
const container = document.createElement("section");
container.dataset.type = branchType;
+ const rootID = embedded ? "source-document" : "document";
+ if (embedded) {
+ container.classList.add("protyle-wysiwyg__embed");
+ }
const element = document.createElement("div");
element.dataset.type = `${branchType}Item`;
element.dataset.nodeId = "item";
@@ -138,7 +143,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
_complete: unknown, options: {source: string}) => {
check.equal(target, protyle);
check.equal(options.source, "paste");
- check.equal(target.block.rootID, "document");
+ check.equal(target.block.rootID, rootID);
check.equal(target.toolbar.range, undefined);
state.uploads.push(files);
},
@@ -181,6 +186,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
const owner = {app: {}, notebookId: "notebook", block: {rootID: "document"}};
const editor = open({
owner,
+ rootID,
node: {element}, host, replaceFirstParagraph,
canEdit: () => element.isConnected,
onResize: noop,
@@ -199,7 +205,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
},
});
check.ok(editor);
- check.equal(protyle.block.rootID, "document");
+ check.equal(protyle.block.rootID, rootID);
const type = async (value: string) => {
wysiwyg.innerHTML = textHTML(value);
await settle();
@@ -432,7 +438,8 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
await conflictingTabs.remove();
// 数据库和嵌入结果在编辑期间重新渲染,不会挡住普通文字保存或覆盖新的独立块状态。
- for (const type of ["NodeAttributeView", "NodeBlockQueryEmbed"]) {
+ for (const [type, embedded] of ["NodeAttributeView", "NodeBlockQueryEmbed"].flatMap(type =>
+ [false, true].map(embedded => [type, embedded] as const))) {
const special = document.createElement("div");
special.dataset.type = type;
special.dataset.nodeId = "special";
@@ -442,7 +449,7 @@ const browserCases = async (sourceCode: string, css: string, cleanupSource: stri
special.dataset.content = "select * from blocks";
}
special.textContent = "Old projection";
- const current = create(textHTML("Initial") + special.outerHTML);
+ const current = create(textHTML("Initial") + special.outerHTML, undefined, "NodeList", embedded);
current.element.lastElementChild.setAttribute("updated", "20260923120000");
current.element.lastElementChild.textContent = "Latest projection";
current.wysiwyg.lastElementChild.setAttribute("data-render", "true");
diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.ts
index 8337620ceb..9264914c78 100644
--- a/app/src/protyle/render/listMindmap/editor.ts
+++ b/app/src/protyle/render/listMindmap/editor.ts
@@ -25,6 +25,7 @@ import {getUndoFocusContext, restoreFocusContext} from "../../util/selection";
interface ListMindmapEditorOptions {
owner: IProtyle;
+ rootID?: string;
node: ListMindmapNode;
host: HTMLElement;
canEdit: () => boolean;
@@ -74,7 +75,8 @@ const retainIndependentBlocks = (html: string, node: ListMindmapNode) => {
child.getAttribute("data-type") !== nestedBranchType(node)).forEach(child => {
const blocks = [child, ...Array.from(child.querySelectorAll(independentBlockSelector))];
blocks.forEach(block => {
- if (block.matches(independentBlockSelector) && !block.closest(".protyle-wysiwyg__embed")) {
+ if (block.matches(independentBlockSelector) &&
+ block.closest(".protyle-wysiwyg__embed") === node.element.closest(".protyle-wysiwyg__embed")) {
current.set(block.getAttribute("data-node-id"), block);
}
});
@@ -104,6 +106,7 @@ const matchesCustomizedEditorShortcut = (event: KeyboardEvent) => {
// 编辑器挂载到节点内容区,预览与编辑沿用同一尺寸和排版。
export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
const {owner, node, host} = options;
+ const rootID = options.rootID || owner.block.rootID;
const initialBlockHTML = nodeContent(node);
if (!options.canEdit() || !node.element?.isConnected) {
return;
@@ -172,7 +175,7 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
lute: owner.lute, lockedOptions: {toolbar, hint},
},
afterSetContent: (protyle, element) => {
- protyle.block.rootID = owner.block.rootID;
+ protyle.block.rootID = rootID;
protyle.block.parentID = node.id;
protyle.path = owner.path;
setCustomBlockRootReady(element, true);
@@ -198,7 +201,7 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
saveTimer = window.setTimeout((): void => { void commit(); }, 350);
},
});
- fragment.protyle.block.rootID = owner.block.rootID;
+ fragment.protyle.block.rootID = rootID;
const overlays = [fragment.hintElement, fragment.protyle.toolbar.element, fragment.protyle.toolbar.subElement];
const overlayRoot = host.closest(".mindmap-view") || document.body;
// 菜单使用未缩放的容器定位,同时保持在原生全屏元素内可见。
diff --git a/app/src/protyle/render/listMindmap/focus.test.ts b/app/src/protyle/render/listMindmap/focus.test.ts
index fafb27293a..d343aed16a 100644
--- a/app/src/protyle/render/listMindmap/focus.test.ts
+++ b/app/src/protyle/render/listMindmap/focus.test.ts
@@ -49,6 +49,38 @@ test("new mind map nodes become selected before editing", async () => {
assert.deepEqual(steps, ["focus:new", "edit:new"]);
});
+test("embedded history uses the source document and transaction owner without depending on the selection", async () => {
+ for (const lite of [false, true]) {
+ const submitted: unknown[] = [];
+ const mainOwner = {lite: false};
+ const owner = {lite, block: {rootID: "host-document"}, wysiwyg: {element: {isConnected: true}},
+ undo: {undo: assert.fail, redo: assert.fail}};
+ const embed = {dataset: {rootId: "source-document"}};
+ const list = {dataset: {nodeId: "map"}, isConnected: true, outerHTML: "snapshot", closest: () => embed};
+ const context: any = {canEdit: () => true, roots: new WeakMap(), cleanListMindmapHTML: (html: string) => html,
+ hasMindmapFocusOverlay: () => false,
+ getProtyleTransactionOwner: (_owner: unknown, operations: {id: string}[]) => {
+ assert.equal(operations[0].id, "map");
+ return mainOwner;
+ },
+ requestUndo: (target: unknown, rootID: string) => submitted.push([target, rootID, "undo"]),
+ requestRedo: (target: unknown, rootID: string) => submitted.push([target, rootID, "redo"]),
+ fetchSyncPost: async (_url: string, data: {id: string}) => {
+ assert.equal(data.id, "map");
+ return {code: 0, data: {dom: "canonical history snapshot"}};
+ },
+ };
+ runInNewContext(compiled, context);
+ const target = Object.assign(new context.Controller(), {owner, list,
+ model: {nodes: new Map(), root: {id: "map"}}, view: {getSelectedId: () => "map"},
+ replay: (html: string) => { assert.equal(html, "canonical history snapshot"); return true; }});
+ await target.undo(false);
+ await target.undo(true);
+ assert.deepEqual(submitted, [[lite ? mainOwner : owner, "source-document", "undo"],
+ [lite ? mainOwner : owner, "source-document", "redo"]]);
+ }
+});
+
test("undo from a node editor restores that node or its previous sibling", async () => {
const root = {id: "root", children: [{id: "existing"}, {id: "new"}]};
const nodes = new Map<string, {id: string, parentId?: string, children?: {id: string}[]}>([
@@ -68,7 +100,7 @@ test("undo from a node editor restores that node or its previous sibling", async
runInNewContext(compiled, context);
const target = new context.Controller();
Object.assign(target, {
- owner, list: {dataset: {nodeId: "map"}, isConnected: true, outerHTML: "map"}, model: {nodes, root},
+ owner, list: {dataset: {nodeId: "map"}, isConnected: true, outerHTML: "map", closest: (): null => null}, model: {nodes, root},
view: {getSelectedId: () => "root", focusNode: (id: string) => selected.push(id)},
});
roots.set(owner, {restoreFocus: (_listID: string, ids: string[]) => target.focusNode(ids)});
@@ -83,7 +115,7 @@ test("undo from a node editor restores that node or its previous sibling", async
test("text history records the edited node even when selection changes before its save", async () => {
const nodes = new Map([["root", {id: "root", children: [{id: "child"}]}],
["child", {id: "child", parentId: "root", children: []}]]);
- const list = {isConnected: true, dataset: {nodeId: "map"}, outerHTML: "before"};
+ const list = {isConnected: true, dataset: {nodeId: "map"}, outerHTML: "before", closest: (): null => null};
const operations: {undo: Record<string, string>, redo: Record<string, string>}[] = [];
const context: any = {
canEdit: () => true, readListMindmap: () => ({nodes, root: nodes.get("root")}),
@@ -126,7 +158,8 @@ test("mind map transaction focus survives insertion, deletion and repeated undo/
});
return {nodes, root: nodes.get("root")};
};
- const list = {isConnected: true, dataset: {nodeId: "map"}, get outerHTML() { return JSON.stringify(state); }};
+ const list = {isConnected: true, dataset: {nodeId: "map"}, closest: (): null => null,
+ get outerHTML() { return JSON.stringify(state); }};
const roots = new WeakMap();
const root = {focusRevision: 0, restoreFocus: (_listID: string, ids: string[]) => {
root.focusRevision++;
@@ -215,7 +248,7 @@ test("empty or canceled history restores the current text selection unless a new
hasMindmapFocusOverlay: () => false};
runInNewContext(compiled, context);
const target = Object.assign(new context.Controller(), {
- owner, list: {dataset: {nodeId: "map"}, outerHTML: "same", isConnected: true}, model: {root: node, nodes},
+ owner, list: {dataset: {nodeId: "map"}, outerHTML: "same", isConnected: true, closest: (): null => null}, model: {root: node, nodes},
view: {getSelectedId: () => "item", focusNode: () => {}, getContentHost: () => ({isConnected: true})},
edit: async (...args: unknown[]) => opened.push(args[4]),
});
@@ -246,7 +279,7 @@ test("history reopening does not invalidate its own guard and stale editor clean
}};
runInNewContext(compiled, context);
const target = Object.assign(new context.Controller(), {
- owner, editRequest: 0, list: {}, model: {nodes: new Map([["item", {id: "item"}]])},
+ owner, editRequest: 0, list: {closest: (): null => null}, model: {nodes: new Map([["item", {id: "item"}]])},
view: {setEditing: () => {}, update: () => {}},
});
const saved = {undoFocusId: "body", undoFocusStart: "1", undoFocusEnd: "1"};
diff --git a/app/src/protyle/render/listMindmap/fold.test.ts b/app/src/protyle/render/listMindmap/fold.test.ts
index 3e7df8b87e..5a90a54c8f 100644
--- a/app/src/protyle/render/listMindmap/fold.test.ts
+++ b/app/src/protyle/render/listMindmap/fold.test.ts
@@ -141,7 +141,8 @@ test("batch folding saves a single undo snapshot and reads the source after fini
};
collect(root);
const snapshot = () => JSON.stringify([...nodes].map(([id, current]) => [id, current.collapsed]));
- const list = {isConnected: true, dataset: {nodeId: "map-fold"}, get outerHTML() { return snapshot(); }};
+ const list = {isConnected: true, dataset: {nodeId: "map-fold"}, closest: (): null => null,
+ get outerHTML() { return snapshot(); }};
const transactions: {before: string, after: string}[] = [];
let allowed = true;
const context: any = {
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index 859c258034..0f58b9dc39 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -47,7 +47,7 @@ import {getListMindmapFoldStates, getListMindmapSiblingFoldStates} from "./fold"
import {isMobile} from "../../../util/functions";
import {addListMindmapSummaryRanges, getListMindmapSiblingIDs, getListMindmapSummaryParentID, getListMindmapSummaryRange,
getListMindmapSummarySnapshot} from "./summary";
-import {isProtyleListItemFragment} from "../../runtimeCapabilities";
+import {getProtyleTransactionOwner, isProtyleListItemFragment} from "../../runtimeCapabilities";
import {isFoldedRenderContent} from "../foldedContent";
import {disposeCustomBlocksInElement} from "../../../plugin/customBlockRender";
import {processRender} from "../../util/processCode";
@@ -56,6 +56,8 @@ import {avRender} from "../av/render";
import {blockRender} from "../blockRender";
import {getListMindmapConnectorMenuItem} from "./connectorMenu";
import {getDefaultListMindmapConnectorStyle, setDefaultListMindmapConnectorStyle} from "./preferences";
+import {getEmbedChildOperationContext} from "../../wysiwyg/getBlock";
+import {requestRedo, requestUndo} from "../../undo/globalUndo";
const roots = new WeakMap<IProtyle, {refresh: () => void, mountNew: (list: HTMLElement) => void,
restoreFocus: (listID: string, candidateIDs: string[], selection?: Record<string, string>, source?: HTMLElement) => void, focusRevision: number,
@@ -79,7 +81,8 @@ const canToggleView = (owner: IProtyle, list: HTMLElement) => !owner.disabled &&
list.closest(".protyle-wysiwyg") === owner.wysiwyg.element;
const canEdit = (owner: IProtyle, list: HTMLElement) => canToggleView(owner, list) &&
- !list.closest(".protyle-wysiwyg__embed");
+ (!list.closest(".protyle-wysiwyg__embed") ||
+ !!getEmbedChildOperationContext(list)?.resultElement.dataset.rootId);
export const toggleListMindmap = async (owner: IProtyle, list: HTMLElement) => {
if (!["NodeList", "NodeMindmap"].includes(list.dataset.type) || !canToggleView(owner, list)) {
@@ -643,6 +646,19 @@ class ListMindmapController {
const siblings = selected?.parentId ? model.nodes.get(selected.parentId)?.children || [] : [];
const index = siblings.findIndex(node => node.id === selectedID);
const previous = getListMindmapSiblingIDs(model);
+ const focusContext = (id: string, source: ListMindmapModel): Record<string, string> => {
+ const embed = this.list.closest(".protyle-wysiwyg__embed");
+ if (!embed) {
+ return {};
+ }
+ const element = source.nodes.get(id)?.element || this.list;
+ const index = Array.from(this.owner.wysiwyg.element.querySelectorAll(`[data-node-id="${id}"]`))
+ .indexOf(element);
+ const query = embed.closest<HTMLElement>('[data-type="NodeBlockQueryEmbed"]');
+ return {...(index >= 0 ? {undoFocusIndex: String(index)} : {}),
+ ...(query?.dataset.nodeId ? {undoFocusEmbedId: query.dataset.nodeId} : {})};
+ };
+ const undoFocus = focusContext(selectedID, model);
if (change() === false) {
return false;
}
@@ -655,10 +671,12 @@ class ListMindmapController {
updateTransaction(this.owner, this.list, before, {
undoFocusId: selectedID, undoFocusStart: "0", undoFocusEnd: "0",
mindmapSnapshotId: this.list.dataset.nodeId,
+ ...undoFocus,
...(selection?.undo ? {undoFocusMindmapSelection: JSON.stringify(selection.undo)} : {}),
}, {doOperations: [], undoOperations: [], context: {
undoFocusId: nextID, undoFocusStart: "0", undoFocusEnd: "0",
mindmapSnapshotId: this.list.dataset.nodeId,
+ ...focusContext(nextID, next),
...(selection?.redo ? {undoFocusMindmapSelection: JSON.stringify(selection.redo)} : {}),
}});
}
@@ -718,6 +736,7 @@ class ListMindmapController {
this.view.setEditing(id);
const editor = openListMindmapEditor({
owner: this.owner, node, host, replaceFirstParagraph, selection,
+ rootID: this.list.closest<HTMLElement>(".protyle-wysiwyg__embed")?.dataset.rootId,
canEdit: () => !this.disposed && this.list.isConnected && canEdit(this.owner, this.list),
onSave: (html, undo, redo) => this.change(() => replaceListMindmapContent(this.list, id, html), true, id, {undo, redo}),
onResize: () => this.view.refreshLayout(),
@@ -775,7 +794,25 @@ class ListMindmapController {
this.view.focusNode(editingID);
}
const focusRevision = root?.focusRevision;
- if (redo) {
+ const sourceRootID = this.list.closest<HTMLElement>(".protyle-wysiwyg__embed")?.dataset.rootId;
+ if (sourceRootID) {
+ // 全屏视图和节点片段的选区不在嵌入源块内,撤销始终使用源文档和实际提交事务的编辑器。
+ const owner = this.owner.lite && getProtyleTransactionOwner(this.owner,
+ [{action: "update", id: this.list.dataset.nodeId, data: before}]) || this.owner;
+ if (!owner.lite) {
+ await (redo ? requestRedo(owner, sourceRootID) : requestUndo(owner, sourceRootID));
+ if (this.owner.lite && this.list.isConnected && !this.disposed) {
+ // 全屏中的片段不在外层编辑器内,按源块补齐撤销结果,并保留等待期间的新修改。
+ const snapshot = cleanListMindmapHTML(this.list.outerHTML);
+ const response = await fetchSyncPost("/api/block/getBlockDOM",
+ {id: this.list.dataset.nodeId, notebook: this.owner.notebookId});
+ if (response.code === 0 && canEdit(this.owner, this.list) && !this.disposed &&
+ cleanListMindmapHTML(this.list.outerHTML) === snapshot) {
+ this.replay(response.data.dom);
+ }
+ }
+ }
+ } else if (redo) {
await this.owner.undo.redo(this.owner);
} else {
await this.owner.undo.undo(this.owner);
@@ -895,14 +932,20 @@ class ListMindmapController {
// 补齐折叠隐藏的正文后才允许改动列表,避免以局部视图覆盖完整块树。
const completeList = async (owner: IProtyle, list: HTMLElement) => {
+ const rootID = owner.block.rootID;
+ const notebookId = owner.notebookId;
+ const id = list.dataset.nodeId;
+ const type = list.dataset.type;
+ const isCurrent = () => canEdit(owner, list) && owner.block.rootID === rootID &&
+ owner.notebookId === notebookId && list.dataset.nodeId === id && list.dataset.type === type;
await owner.wysiwyg.flushPendingInput();
await waitForPendingTransactions(owner);
- if (!list.isConnected) {
+ if (!isCurrent()) {
return "failed";
}
const before = cleanListMindmapHTML(list.outerHTML);
- const response = await fetchSyncPost("/api/block/getBlockDOM", {id: list.dataset.nodeId, notebook: owner.notebookId});
- if (response.code !== 0 || !list.isConnected) {
+ const response = await fetchSyncPost("/api/block/getBlockDOM", {id, notebook: notebookId});
+ if (response.code !== 0 || !isCurrent()) {
return "failed";
}
if (cleanListMindmapHTML(list.outerHTML) !== before) {
@@ -929,6 +972,10 @@ export const initListMindmaps = (owner: IProtyle) => {
const placeholders = new Map<HTMLElement, HTMLElement>();
const failed = new WeakSet<HTMLElement>();
const newlyCreated = new WeakSet<HTMLElement>();
+ const completeSources = new WeakSet<HTMLElement>();
+ const needsCompleteSource = (list: HTMLElement) =>
+ (!owner.lite || !!list.closest(".protyle-wysiwyg__embed")) && canEdit(owner, list) &&
+ !newlyCreated.has(list) && !completeSources.has(list);
let pendingFocus: {list: HTMLElement, candidateIDs: string[], selection?: Record<string, string>, guard?: () => boolean};
let frame = 0;
let disposed = false;
@@ -969,7 +1016,7 @@ export const initListMindmaps = (owner: IProtyle) => {
}
const lists = new Set(getListMindmapElements(root));
instances.forEach((instance, list) => {
- if (!lists.has(list)) {
+ if (!lists.has(list) || needsCompleteSource(list)) {
instance.destroy();
instances.delete(list);
} else if (!isFoldedRenderContent(list, true)) {
@@ -983,6 +1030,7 @@ export const initListMindmaps = (owner: IProtyle) => {
}
}
});
+ prepare();
lists.forEach(list => {
if (instances.has(list) || loading.has(list) || failed.has(list) || isFoldedRenderContent(list, true)) {
return;
@@ -1008,11 +1056,12 @@ export const initListMindmaps = (owner: IProtyle) => {
list.removeAttribute("data-mindmap-view-rendered");
}
};
- if (!owner.lite && canEdit(owner, list) && !newlyCreated.has(list)) {
+ if (needsCompleteSource(list)) {
loading.add(list);
let retry = false;
void completeList(owner, list).then(complete => {
if (complete === "complete") {
+ completeSources.add(list);
mount();
} else if (complete === "changed") {
retry = true;
@@ -1031,6 +1080,9 @@ export const initListMindmaps = (owner: IProtyle) => {
}
});
} else {
+ if (newlyCreated.has(list)) {
+ completeSources.add(list);
+ }
newlyCreated.delete(list);
mount();
}
diff --git a/app/src/protyle/render/listMindmap/loading.test.ts b/app/src/protyle/render/listMindmap/loading.test.ts
index e19d1506fa..c6d5679af4 100644
--- a/app/src/protyle/render/listMindmap/loading.test.ts
+++ b/app/src/protyle/render/listMindmap/loading.test.ts
@@ -31,7 +31,7 @@ const browserCases = async (source: string, css: string, constructorSource: stri
getListMindmapElements: (root: Element) => Array.from(root.querySelectorAll('[data-type="NodeMindmap"]')),
isFoldedRenderContent: (element: Element) => !!element.closest('[fold="1"]'),
syncListMindmapHeight: syncHeight,
- canEdit: () => true,
+ canEdit: (owner: {disabled?: boolean}) => !owner.disabled,
isProtyleListItemFragment: (owner: {fragment?: boolean}) => owner.fragment === true,
completeList: () => {
requests++;
@@ -134,6 +134,28 @@ const browserCases = async (source: string, css: string, constructorSource: stri
root.remove();
}
check.deepEqual(errors, []);
+ for (const lite of [false, true]) {
+ const root = document.createElement("div");
+ root.className = "protyle-wysiwyg";
+ root.innerHTML = '<div class="protyle-wysiwyg__embed"><div data-type="NodeMindmap" data-node-id="embedded">' +
+ "<div>Partial source</div></div></div>";
+ document.body.append(root);
+ const owner = {lite, fragment: lite, disabled: true, wysiwyg: {element: root}};
+ const previousRequests = requests;
+ init(owner);
+ await frame();
+ check.equal(requests, previousRequests, "read-only embeds do not load editable source");
+ owner.disabled = false;
+ roots.get(owner).refresh();
+ await frame();
+ check.equal(requests, previousRequests + 1, "permission changes must hydrate before enabling editing");
+ resolveLoad("complete");
+ await flush();
+ await frame();
+ check.equal(requests, previousRequests + 1, "completed source is reused by later refreshes");
+ roots.get(owner).destroy();
+ root.remove();
+ }
const remounted = document.createElement("div");
remounted.innerHTML = '<div data-node-id="source">Preserved source</div>' +
'<div class="mindmap-view" aria-busy="true">Stale loading</div><div class="mindmap-view">Stale rendered</div>';
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index b922456e23..2e8b40d6d5 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -213,7 +213,7 @@ test("layout rejects cyclic or invalid trees and supports deep nesting without r
});
const browserCases = async (sourceCode: string, css: string, taskSource: string, taskCSS: string, dragSource: string,
- inputSource: string) => {
+ inputSource: string, controllerSource: string) => {
const check = require("node:assert/strict");
const api = new Function("mathRender", "Constants", "highlightRender", sourceCode + "; return {readListMindmap, moveListMindmapNode, addListMindmapNode, " +
"deleteListMindmapNode, replaceListMindmapContent, cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource, remapListMindmapIDs, writeListMindmapMetadata, retagMindmapBranch, " +
@@ -221,7 +221,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
"addListMindmapSummaryRanges, getListMindmapSummarySnapshot, " +
"normalizeLegacyMindmapCodes, replaceLegacyMindmapHTML, spinListMindmapDOM, focusListMindmap, " +
"initializeListMindmapConnectorStyle, LIST_MINDMAP_DEFAULT_CONNECTOR_STYLE_KEY, " +
- "tabsRender, destroyTabsRender, getTabTask, getListMindmapTabItem, convertTabsList, ListMindmapView, registerListMindmapView, resolveVisibleListMindmapBlock, getListMindmapElements, registerListMindmapRoot, restoreListMindmapFocus};")(
+ "tabsRender, destroyTabsRender, getTabTask, getListMindmapTabItem, convertTabsList, completeTabsListSource, ListMindmapView, registerListMindmapView, resolveVisibleListMindmapBlock, getListMindmapElements, registerListMindmapRoot, restoreListMindmapFocus};")(
async (element: Element) => {
const formulas = element.querySelectorAll('[data-subtype="math"]:not([data-render="true"])');
await Promise.resolve();
@@ -235,6 +235,98 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
const lute = Lute.New();
lute.SetKramdownIAL(true);
lute.SetProtyleWYSIWYG(true);
+ window.siyuan = {languages: new Proxy({}, {get: (_target, key) => String(key)}),
+ config: {editor: {}, keymap: {editor: {general: {}, list: {}}}}, storage: {}} as unknown as typeof window.siyuan;
+ for (const mobile of [false, true]) {
+ const root = document.createElement("div");
+ root.className = "protyle-wysiwyg";
+ root.innerHTML = lute.Md2BlockDOM("- Original\n - Folded child\n");
+ const original = root.firstElementChild as HTMLElement;
+ api.retagMindmapBranch(original, true);
+ original.firstElementChild.setAttribute("fold", "1");
+ const full = original.outerHTML;
+ const copies = ["first", "second"].map(id => {
+ const query = document.createElement("div");
+ query.dataset.type = "NodeBlockQueryEmbed";
+ query.dataset.nodeId = id;
+ query.innerHTML = '<div class="protyle-wysiwyg__embed" data-allow-child-operation="true" ' +
+ 'data-root-id="source-document">' + full + "</div>";
+ const result = query.firstElementChild as HTMLElement;
+ result.dataset.id = original.dataset.nodeId;
+ root.append(query);
+ return result.firstElementChild as HTMLElement;
+ });
+ document.body.append(root);
+ const owner = {block: {rootID: "host-document"}, notebookId: "box", lute, options: {action: [] as string[], render: {}},
+ wysiwyg: {element: root, flushPendingInput: async () => {}},
+ toolbar: {isMultiSelectMode: () => false}};
+ const operations: {doOperations: IOperation[], undoOperations: IOperation[]}[] = [];
+ const controllers: any[] = [];
+ const historyRoots: string[] = [];
+ const dependencies = {...api,
+ Constants: {CB_GET_HISTORY: "history", ATTRIBUTE_EDITING: "data-editing",
+ CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap", CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data"},
+ isProtyleListItemFragment: () => false, isHiddenTabContent: () => false,
+ isMobile: () => mobile, waitForPendingTransactions: async () => {},
+ fetchSyncPost: async () => ({code: 0, data: {dom: full}}),
+ normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,
+ cleanHeadingNumberHTML: (html: string) => html, cleanTableCellRichHTML: (html: string) => html,
+ cleanBlockSelectionModeHTML: (html: string) => html,
+ syncListMindmapHeight: () => {}, bindListMindmapResize: () => ({refresh() {}, destroy() {}}),
+ showMessage: () => check.fail("Embedded edit failed"), globalClickHideMenu: () => {},
+ hideAllElements: () => {}, hideElements: () => {}, suspendBlockPopover: () => () => {},
+ getInlineStylesCache: () => ({}), getVisibleOrderedStyleKeys: (): string[] => [],
+ openListMindmapEditor: (options: any) => { editorOptions = options; return {finish: async () => true, destroy() {}}; },
+ genListItemElement: () => {
+ const holder = document.createElement("div");
+ holder.innerHTML = lute.Md2BlockDOM("- Added\n");
+ return holder.firstElementChild.firstElementChild;
+ },
+ processRender: () => {}, highlightRender: () => {}, avRender: () => {}, blockRender: () => {},
+ disposeCustomBlocksInElement: () => {},
+ transaction: (_owner: unknown, forward: IOperation[], backward: IOperation[]) => {
+ operations.push({doOperations: forward, undoOperations: backward});
+ const operation = forward[0];
+ check.equal(operation.id, original.dataset.nodeId);
+ root.firstElementChild.outerHTML = operation.data as string;
+ controllers.slice(1).forEach(controller => check.equal(controller.replay(operation.data), true));
+ },
+ requestUndo: async (_owner: unknown, rootID: string) => {
+ historyRoots.push(rootID);
+ controllers.forEach(controller => check.equal(controller.replay(operations.at(-1).undoOperations[0].data), true));
+ },
+ requestRedo: async (_owner: unknown, rootID: string) => {
+ historyRoots.push(rootID);
+ controllers.forEach(controller => check.equal(controller.replay(operations.at(-1).doOperations[0].data), true));
+ },
+ };
+ let editorOptions: any;
+ const embedded = new Function(...Object.keys(dependencies), controllerSource +
+ "; return {ListMindmapController, completeList, canEdit};")(...Object.values(dependencies));
+ copies[0].querySelector('[data-type="NodeMindmap"]').remove();
+ check.equal(await embedded.completeList(owner, copies[0]), "complete");
+ check.match(copies[0].textContent, /Folded child/);
+ copies.forEach(copy => controllers.push(new embedded.ListMindmapController(owner, copy)));
+ const target = controllers[0];
+ const itemID = copies[0].firstElementChild.getAttribute("data-node-id");
+ await target.view.options.onNodeStyle(itemID, {backgroundColor: "#ff0000"});
+ check.equal(api.readListMindmap(copies[1]).metadata.nodes[itemID].backgroundColor, "#ff0000");
+ check.equal(operations[0].undoOperations[0].context.undoFocusEmbedId, "first");
+ check.equal(operations[0].undoOperations[0].context.undoFocusIndex, "1");
+ check.match(operations[0].doOperations[0].data as string, /Folded child/);
+ await target.view.options.onAdd(itemID, "child");
+ check.equal(editorOptions.rootID, "source-document");
+ check.match(copies[1].textContent, /Added/);
+ await target.finish();
+ target.activeEditor = undefined;
+ await target.undo(false);
+ check.doesNotMatch(copies[0].textContent, /Added/);
+ await target.undo(true);
+ check.match(copies[0].textContent, /Added/);
+ check.deepEqual(historyRoots, ["source-document", "source-document"]);
+ controllers.forEach(controller => controller.destroy());
+ root.remove();
+ }
const holder = document.createElement("div");
const reset = (markdown: string) => {
holder.innerHTML = lute.Md2BlockDOM(markdown);
@@ -4295,6 +4387,15 @@ test("list mindmap mutations preserve block data in the real DOM and Lute", {
require("sass").compile(path.resolve(__dirname, "../../../assets/scss/component/_typography.scss")).css;
const indexSource = typescript.createSourceFile("index.ts", readFileSync(path.join(__dirname, "index.ts"), "utf8"),
typescript.ScriptTarget.Latest, true);
+ const transactionSource = typescript.createSourceFile("transaction.ts",
+ readFileSync(path.join(__dirname, "../../wysiwyg/transaction.ts"), "utf8"), typescript.ScriptTarget.Latest, true);
+ const updateTransaction = transactionSource.statements.find(statement => typescript.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(transactionSource) === "updateTransaction"));
+ const controllerSource = compile(path.join(__dirname, "../../util/hasClosest.ts")) +
+ compile(path.join(__dirname, "../../wysiwyg/getBlock.ts")) + compile(path.join(__dirname, "index.ts")) +
+ typescript.transpileModule(updateTransaction.getText(transactionSource).replace(/^export /, ""), {
+ compilerOptions: {target: typescript.ScriptTarget.ES2021},
+ }).outputText;
const controller = indexSource.statements.find(typescript.isClassDeclaration);
const taskMethods = controller.members.filter(member => ["setTask", "setTabTask", "queueTask", "change"]
.includes(member.name?.getText(indexSource)));
@@ -4361,7 +4462,7 @@ app.whenReady().then(async () => {
await win.loadURL("data:text/html,<html><body></body></html>");
await win.webContents.executeJavaScript(require("node:fs").readFileSync(${JSON.stringify(lutePath)}, "utf8"));
const result = await win.webContents.executeJavaScript(${JSON.stringify(
- `const __name = value => value; (${browserSource})(${JSON.stringify(source)}, ${JSON.stringify(css)}, ${JSON.stringify(taskSource)}, ${JSON.stringify(taskCSS)}, ${JSON.stringify(dragSource)}, ${JSON.stringify(inputSource)})`)});
+ `const __name = value => value; (${browserSource})(${JSON.stringify(source)}, ${JSON.stringify(css)}, ${JSON.stringify(taskSource)}, ${JSON.stringify(taskCSS)}, ${JSON.stringify(dragSource)}, ${JSON.stringify(inputSource)}, ${JSON.stringify(controllerSource)})`)});
console.log(result);
win.destroy();
app.exit(0);
diff --git a/app/src/protyle/render/listMindmap/relation.test.ts b/app/src/protyle/render/listMindmap/relation.test.ts
index 78ae3d8756..0225acd2cb 100644
--- a/app/src/protyle/render/listMindmap/relation.test.ts
+++ b/app/src/protyle/render/listMindmap/relation.test.ts
@@ -30,7 +30,8 @@ test("manual route save and reset use one transaction and reject stale relation
const original = JSON.stringify(data);
const transactions: {before: string, after: string}[] = [];
const messages: string[] = [];
- const list = {isConnected: true, dataset: {nodeId: "map-relations"}, get outerHTML() { return JSON.stringify(data); }};
+ const list = {isConnected: true, dataset: {nodeId: "map-relations"}, closest: (): null => null,
+ get outerHTML() { return JSON.stringify(data); }};
const context: any = {
canEdit: () => true,
getListMindmapSiblingIDs: () => new Map(),
diff --git a/app/src/protyle/render/listMindmap/resizeTransaction.test.ts b/app/src/protyle/render/listMindmap/resizeTransaction.test.ts
index 4470b3b2ca..eb85d23dc6 100644
--- a/app/src/protyle/render/listMindmap/resizeTransaction.test.ts
+++ b/app/src/protyle/render/listMindmap/resizeTransaction.test.ts
@@ -26,7 +26,8 @@ test("resizing uses one source update with both dimensions and retains the exact
}
globalThis.Controller = Controller;`, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
let title = "Before editing";
- const list = {isConnected: true, dataset: {nodeId: "map-resize"}, parentElement: {classList: {contains: () => false}},
+ const list = {isConnected: true, dataset: {nodeId: "map-resize"}, closest: (): null => null,
+ parentElement: {classList: {contains: () => false}},
style: {width: "50%", height: "40vh", flex: ""},
get outerHTML() { return JSON.stringify({style: this.style, title}); }};
const transactions: {before: string, after: string}[] = [];
diff --git a/app/src/protyle/render/listMindmap/toggle.test.ts b/app/src/protyle/render/listMindmap/toggle.test.ts
index 2382c8e06a..24cd2436b0 100644
--- a/app/src/protyle/render/listMindmap/toggle.test.ts
+++ b/app/src/protyle/render/listMindmap/toggle.test.ts
@@ -19,6 +19,8 @@ const compiled = transpileModule(declarations.map(item => item.getText(source).r
const setup = (embedded = true) => {
const root = {};
const embed = {};
+ let allowChildOperation = false;
+ const resultElement = {dataset: {rootId: "source-document"}};
const owner = {disabled: false, lite: false, options: {action: [] as string[]}, wysiwyg: {element: root}};
const attribute = "custom-sy-list-mindmap";
const attrs = new Map([[attribute, "1"]]);
@@ -49,6 +51,7 @@ const setup = (embedded = true) => {
getListConversionType,
roots: new WeakMap(), hideElements: () => {}, readListMindmap: () => {},
getDefaultListMindmapConnectorStyle: () => "rounded",
+ getEmbedChildOperationContext: () => allowChildOperation ? {resultElement} : undefined,
initializeListMindmapConnectorStyle: (element: unknown, style: string) => {
assert.equal(element, list);
if (!attrs.has("custom-sy-list-mindmap-data")) {
@@ -75,9 +78,32 @@ const setup = (embedded = true) => {
},
};
runInNewContext(compiled, context);
- return {owner, list, attrs, attribute, operations, updates, replaced, context, api: context.api};
+ return {owner, list, attrs, attribute, operations, updates, replaced, context, api: context.api,
+ allowChildren: () => { allowChildOperation = true; }, resultElement};
};
+test("embedded mind maps follow container permissions and require their source document", () => {
+ const state = setup();
+ assert.equal(state.api.canEdit(state.owner, state.list), false);
+ state.allowChildren();
+ assert.equal(state.api.canEdit(state.owner, state.list), true);
+ for (const mode of ["readonly", "history", "lite", "removed", "root"]) {
+ const blocked = setup();
+ blocked.allowChildren();
+ if (mode === "readonly") { blocked.owner.disabled = true; }
+ if (mode === "history") { blocked.owner.options.action.push("history"); }
+ if (mode === "lite") { blocked.owner.lite = true; }
+ if (mode === "removed") { blocked.list.isConnected = false; }
+ if (mode === "root") { blocked.resultElement.dataset.rootId = ""; }
+ assert.equal(blocked.api.canEdit(blocked.owner, blocked.list), false, mode);
+ }
+ const fragment = setup();
+ fragment.allowChildren();
+ fragment.owner.lite = true;
+ registerProtyleRuntimeCapabilities(fragment.owner as unknown as IProtyle, {listItemFragment: true});
+ assert.equal(fragment.api.canEdit(fragment.owner, fragment.list), true);
+});
+
test("a regular list becomes a dedicated mind map block", () => {
const {owner, list, attrs, attribute, operations, updates, api} = setup();
attrs.delete(attribute);