Skip to content

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

:bug: Preserve mind map root titles when converting to lists https://github.com/siyuan-note/siyuan/issues/20004

Danielc287b0291247
diff --git a/app/src/protyle/render/listMindmap/conversion.test.ts b/app/src/protyle/render/listMindmap/conversion.test.ts
new file mode 100644
index 0000000000..96699078c8
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/conversion.test.ts
@@ -0,0 +1,121 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import * as path from "node:path";
+import test from "node:test";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const source = transpileModule(readFileSync(path.join(__dirname, "conversion.ts"), "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+const setup = () => {
+ const calls: string[] = [];
+ const root = {};
+ let embedded = 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"]]);
+ const fullAttributes = new Map(attributes);
+ const full = {getAttribute: (name: string) => fullAttributes.get(name)};
+ const list = {isConnected: true, outerHTML: "visible", getAttribute: (name: string) => attributes.get(name),
+ closest: (selector: string) => selector === ".protyle-wysiwyg" ? root : embedded ? {} : null,
+ ownerDocument: {createElement: () => ({content: {firstElementChild: full}, innerHTML: ""})}};
+ let resolve: (response: any) => void;
+ let reject: (error: Error) => void;
+ const pending = new Promise((done, fail) => { resolve = done; reject = fail; });
+ const dependencies = {
+ Constants: {CB_GET_HISTORY: "history"}, normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,
+ isProtyleListItemFragment: (protyle: typeof owner) => protyle.fragment,
+ fetchSyncPost: (url: string, data: unknown) => {
+ assert.equal(url, "/api/block/getBlockDOM");
+ assert.deepEqual(data, {id: "map", notebook: "box"});
+ calls.push("fetch");
+ return pending;
+ },
+ waitForPendingTransactions: async () => { calls.push("wait"); },
+ completeTabsListSource: (visible: unknown, complete: unknown) => {
+ assert.equal(visible, list);
+ assert.equal(complete, full);
+ calls.push("complete");
+ return {outerHTML: "completed"};
+ }, cleanListMindmapHTML: (html: string) => html,
+ };
+ 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; }};
+};
+const flush = async () => { for (let index = 0; index < 6; index++) { await Promise.resolve(); } };
+
+test("root conversion completes folded source after pending input and transactions", async () => {
+ const state = setup();
+ 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"});
+ assert.equal(state.list.outerHTML, "visible", "preparing the full source never mutates live content");
+});
+
+test("inaccessible source never submits a root conversion read", async () => {
+ for (const mode of ["removed", "id", "readonly", "history", "embed", "editor", "lite"]) {
+ const state = setup();
+ if (mode === "removed") { state.list.isConnected = false; }
+ if (mode === "id") { state.attributes.delete("data-node-id"); }
+ if (mode === "readonly") { state.owner.disabled = true; }
+ if (mode === "history") { state.owner.options.action.push("history"); }
+ if (mode === "embed") { state.embed(); }
+ if (mode === "editor") { state.owner.wysiwyg.element = {}; }
+ if (mode === "lite") { state.owner.lite = true; }
+ assert.equal(await state.prepare(state.owner, state.list), undefined, mode);
+ assert.deepEqual(state.calls, [], mode);
+ }
+});
+
+test("an editable list-item fragment keeps its local full content without a server read", async () => {
+ const state = setup();
+ state.owner.lite = true;
+ state.owner.fragment = true;
+ assert.ok(await state.prepare(state.owner, state.list));
+ assert.deepEqual(state.calls, ["flush", "wait"]);
+});
+
+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();
+ const promise = state.prepare(state.owner, state.list);
+ await flush();
+ if (mode === "content") { state.list.outerHTML = "edited"; }
+ if (mode === "document") { state.owner.block.rootID = "other"; }
+ if (mode === "notebook") { state.owner.notebookId = "other"; }
+ if (mode === "readonly") { state.owner.disabled = true; }
+ if (mode === "history") { state.owner.options.action.push("history"); }
+ if (mode === "embed") { state.embed(); }
+ if (mode === "editor") { state.owner.wysiwyg.element = {}; }
+ if (mode === "removed") { state.list.isConnected = false; }
+ if (mode === "type") { state.attributes.set("data-type", "NodeList"); }
+ if (mode === "id") { state.attributes.set("data-node-id", "other"); }
+ state.resolve({code: 0, data: {dom: "full"}});
+ assert.equal(await promise, undefined, mode);
+ assert.equal(state.calls.includes("complete"), false, mode);
+ }
+});
+
+test("failed or mismatched full source reads do not produce conversion content", async () => {
+ for (const mode of ["error", "id", "type"]) {
+ const state = setup();
+ const promise = state.prepare(state.owner, state.list);
+ await flush();
+ if (mode === "id") { state.fullAttributes.set("data-node-id", "other"); }
+ if (mode === "type") { state.fullAttributes.set("data-type", "NodeList"); }
+ state.resolve({code: mode === "error" ? 1 : 0, data: {dom: "full"}});
+ assert.equal(await promise, undefined, mode);
+ assert.equal(state.calls.includes("complete"), false, mode);
+ }
+ const state = setup();
+ const promise = state.prepare(state.owner, state.list);
+ await flush();
+ state.reject(new Error("unavailable"));
+ await assert.rejects(promise, /unavailable/);
+ assert.equal(state.list.outerHTML, "visible");
+});
diff --git a/app/src/protyle/render/listMindmap/conversion.ts b/app/src/protyle/render/listMindmap/conversion.ts
new file mode 100644
index 0000000000..34fab26adc
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/conversion.ts
@@ -0,0 +1,47 @@
+import {Constants} from "../../../constants";
+import {normalizeHTMLAssetIFrameBlockDOM} from "../../../asset/html";
+import {fetchSyncPost} from "../../../util/fetch";
+import {waitForPendingTransactions} from "../../util/transactionQueue";
+import {completeTabsListSource} from "../../wysiwyg/tabsList";
+import {isProtyleListItemFragment} from "../../runtimeCapabilities";
+import {cleanListMindmapHTML} from "./model";
+
+// 标题转换会改动列表层级,先补齐源块,并在异步读取后复核编辑器和正文。
+export const prepareListMindmapConversion = async (owner: IProtyle, list: Element): Promise<Element | undefined> => {
+ const rootID = owner.block.rootID;
+ const notebookId = owner.notebookId;
+ const id = list.getAttribute("data-node-id");
+ const type = list.getAttribute("data-type");
+ const isCurrent = () => list.isConnected && !!id && !owner.disabled &&
+ (!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") === owner.wysiwyg.element &&
+ list.getAttribute("data-node-id") === id && list.getAttribute("data-type") === type;
+ if (!isCurrent()) {
+ return;
+ }
+ await owner.wysiwyg.flushPendingInput();
+ await waitForPendingTransactions(owner);
+ if (!isCurrent()) {
+ return;
+ }
+ const before = cleanListMindmapHTML(list.outerHTML);
+ const template = list.ownerDocument.createElement("template");
+ if (owner.lite) {
+ // 列表项片段持有完整的本地正文,尚未提交的内容不能被内核快照替换。
+ template.innerHTML = before;
+ return template.content.firstElementChild;
+ }
+ const response = await fetchSyncPost("/api/block/getBlockDOM", {id, notebook: notebookId});
+ if (response.code !== 0 || !isCurrent() || cleanListMindmapHTML(list.outerHTML) !== before) {
+ return;
+ }
+ template.innerHTML = normalizeHTMLAssetIFrameBlockDOM(response.data?.dom || "");
+ const full = template.content.firstElementChild;
+ if (full?.getAttribute("data-node-id") !== id || full.getAttribute("data-type") !== type) {
+ return;
+ }
+ return completeTabsListSource(list, full);
+};
diff --git a/app/src/protyle/render/listMindmap/index.ts b/app/src/protyle/render/listMindmap/index.ts
index 6a130f826e..4f07ddbef9 100644
--- a/app/src/protyle/render/listMindmap/index.ts
+++ b/app/src/protyle/render/listMindmap/index.ts
@@ -29,7 +29,9 @@ import {
addListMindmapNode, cleanListMindmapHTML, deleteListMindmapNode,
moveListMindmapNode, readListMindmap, replaceListMindmapContent,
writeListMindmapMetadata, getListMindmapTabItem, retagMindmapBranch, normalizeListMindmapSummaryMetadata,
+ convertListMindmapToList, hasListMindmapRootTitle,
} from "./model";
+import {prepareListMindmapConversion} from "./conversion";
import type {ListMindmapMetadata, ListMindmapModel} from "./model";
import {getListMindmapElements, registerListMindmapRoot, registerListMindmapView} from "./render";
import {syncListMindmapHeight} from "./height";
@@ -59,10 +61,30 @@ const canToggleView = (owner: IProtyle, list: HTMLElement) => !owner.disabled &&
const canEdit = (owner: IProtyle, list: HTMLElement) => canToggleView(owner, list) &&
!list.closest(".protyle-wysiwyg__embed");
-export const toggleListMindmap = (owner: IProtyle, list: HTMLElement) => {
+export const toggleListMindmap = async (owner: IProtyle, list: HTMLElement) => {
if (!["NodeList", "NodeMindmap"].includes(list.dataset.type) || !canToggleView(owner, list)) {
return;
}
+ const exiting = list.dataset.type === "NodeMindmap" || list.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) === "1";
+ if (exiting && canEdit(owner, list) && hasListMindmapRootTitle(list)) {
+ const source = await prepareListMindmapConversion(owner, list);
+ if (!source || !canEdit(owner, list)) {
+ return;
+ }
+ const type = {o: "UL2OL", t: "UL2TL", u: "OL2UL"}[source.getAttribute("data-subtype")] || "OL2UL";
+ const html = convertListMindmapToList(source, type, owner.lute);
+ const template = list.ownerDocument.createElement("template");
+ template.innerHTML = html;
+ const converted = template.content.firstElementChild;
+ const before = cleanListMindmapHTML(source.outerHTML);
+ Array.from(list.attributes).forEach(attr => list.removeAttribute(attr.name));
+ Array.from(converted.attributes).forEach(attr => list.setAttribute(attr.name, attr.value));
+ list.replaceChildren(...Array.from(converted.childNodes));
+ hideElements(["gutter", "toolbar", "hint"], owner);
+ updateTransaction(owner, list, before);
+ roots.get(owner)?.refresh();
+ return;
+ }
if (list.dataset.type === "NodeMindmap" || list.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) == null) {
const before = cleanListMindmapHTML(list.outerHTML);
const toMindmap = list.dataset.type === "NodeList";
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index f0b7f8c3ad..9c6c7570aa 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -676,7 +676,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
const sourceList = source.firstElementChild;
sourceList.setAttribute("custom-sy-list-mindmap", "1");
sourceList.setAttribute("data-mindmap-view-rendered", "true");
- const metadata = JSON.stringify({version: 1, nodes: {}, relations: [], rootTitle: "Example"});
+ const metadata = JSON.stringify({version: 1, nodes: {}, relations: [], rootTitle: ""});
sourceList.setAttribute("custom-sy-list-mindmap-data", metadata);
sourceList.classList.add("protyle-wysiwyg--select");
sourceList.querySelector('[contenteditable="true"]').insertAdjacentHTML("afterbegin", "<wbr>");
@@ -702,7 +702,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
typedSource.innerHTML = lute.Md2BlockDOM("* Alpha\n * Nested\n* Beta\n");
const typedList = typedSource.firstElementChild as HTMLElement;
const typedIDs = ids(typedList);
- const typedMetadata = JSON.stringify({version: 1, nodes: {}, relations: [], rootTitle: "Example"});
+ const typedMetadata = JSON.stringify({version: 1, nodes: {}, relations: [], rootTitle: ""});
typedList.setAttribute("custom-sy-list-mindmap-data", typedMetadata);
api.retagMindmapBranch(typedList, true);
typedList.classList.add("protyle-wysiwyg--select");
diff --git a/app/src/protyle/render/listMindmap/model.ts b/app/src/protyle/render/listMindmap/model.ts
index 04ae9adc34..47b9c0924d 100644
--- a/app/src/protyle/render/listMindmap/model.ts
+++ b/app/src/protyle/render/listMindmap/model.ts
@@ -343,22 +343,81 @@ export const listMindmapConversionSource = (element: Element): Element => {
return source;
};
+export const hasListMindmapRootTitle = (element: Element) =>
+ !!parseListMindmapMetadata(element.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP_DATA)).rootTitle?.trim();
+
+// 将有标题的虚拟根转为真实父项,已有块及其身份保持不变。
+export const materializeListMindmapRoot = (list: HTMLElement, lute: Lute): boolean => {
+ const model = readListMindmap(list);
+ const title = model.metadata.rootTitle;
+ if (!model.root.virtual || !title?.trim()) {
+ return false;
+ }
+ const marker = list.dataset.subtype === "o" ? "1." : list.dataset.subtype === "t" ? "* [ ]" : "*";
+ const template = list.ownerDocument.createElement("template");
+ template.innerHTML = lute.Md2BlockDOM(`${marker} x\n`);
+ const nested = template.content.firstElementChild as HTMLElement;
+ const item = directItems(nested)[0];
+ const titleElement = list.ownerDocument.createElement("span");
+ titleElement.setAttribute("data-type", "text");
+ titleElement.textContent = title;
+ item.querySelector<HTMLElement>('[data-type="NodeParagraph"] > [contenteditable]').replaceChildren(titleElement);
+ item.remove();
+ const children = directItems(list);
+ if (children.length) {
+ const attr = nested.querySelector(":scope > .protyle-attr");
+ children.forEach(child => nested.insertBefore(child, attr));
+ item.insertBefore(nested, item.querySelector(":scope > .protyle-attr"));
+ }
+ list.insertBefore(item, list.querySelector(":scope > .protyle-attr"));
+ const rootID = model.root.id;
+ const itemID = item.dataset.nodeId;
+ const metadata = model.metadata;
+ delete metadata.rootTitle;
+ if (Object.prototype.hasOwnProperty.call(metadata.nodes, rootID)) {
+ metadata.nodes[itemID] = metadata.nodes[rootID];
+ delete metadata.nodes[rootID];
+ }
+ metadata.relations.forEach(relation => {
+ if (relation.from === rootID) {
+ relation.from = itemID;
+ }
+ if (relation.to === rootID) {
+ relation.to = itemID;
+ }
+ });
+ metadata.summaries?.forEach(summary => {
+ if (summary.parentId === rootID) {
+ summary.parentId = itemID;
+ }
+ });
+ writeListMindmapMetadata(list, metadata);
+ return true;
+};
+
+export const isListMindmapListConversion = (element: Element, type: string) =>
+ (element.getAttribute("data-type") === "NodeMindmap" ||
+ element.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) === "1") &&
+ ["OL2UL", "UL2OL", "UL2TL", "OL2TL", "TL2UL", "TL2OL"].includes(type);
+
// 转换列表类型时退出脑图显示,保留节点、连接元数据及原 DOM 供撤销使用。
export const convertListMindmapToList = (element: Element, type: string, lute: Lute): string | undefined => {
- if (element.getAttribute("data-type") !== "NodeMindmap" &&
- element.getAttribute(Constants.CUSTOM_SY_LIST_MINDMAP) !== "1" ||
- !["OL2UL", "UL2OL", "UL2TL", "OL2TL", "TL2UL", "TL2OL"].includes(type)) {
+ if (!isListMindmapListConversion(element, type)) {
return;
}
const source = listMindmapConversionSource(element);
const from = {o: "OL", t: "TL", u: "UL"}[source.getAttribute("data-subtype")] || "UL";
const to = type.split("2")[1];
- if (from === to) {
- // 同类型转换也规范化块 DOM,清除脑图遗留的块选中状态并保留正文光标。
- return lute.SpinBlockDOM(source.outerHTML);
- }
+ // 同类型转换也规范化块 DOM,清除脑图遗留的块选中状态并保留正文光标。
// @ts-expect-error Lute 的类型声明未包含列表转换方法。
- return lute[`${from}2${to}`](source.outerHTML);
+ const converted = from === to ? lute.SpinBlockDOM(source.outerHTML) : lute[`${from}2${to}`](source.outerHTML);
+ if (!hasListMindmapRootTitle(source)) {
+ return converted;
+ }
+ const template = source.ownerDocument.createElement("template");
+ template.innerHTML = converted;
+ const list = template.content.firstElementChild as HTMLElement;
+ return materializeListMindmapRoot(list, lute) ? lute.SpinBlockDOM(list.outerHTML) : converted;
};
// 按每层最大宽度对齐节点,并为每个分支保留完整的垂直空间,避免富文本节点相互遮挡。
diff --git a/app/src/protyle/render/listMindmap/rootConversion.test.ts b/app/src/protyle/render/listMindmap/rootConversion.test.ts
new file mode 100644
index 0000000000..3fe6340892
--- /dev/null
+++ b/app/src/protyle/render/listMindmap/rootConversion.test.ts
@@ -0,0 +1,260 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {createRequire} from "node:module";
+import * as path from "node:path";
+import test from "node:test";
+import {createSourceFile, isVariableStatement, ScriptTarget, transpileModule} from "typescript";
+
+// 使用项目已有的 HTML 解析器承载节点操作,Lute 负责真实块 DOM 的生成和转换。
+const parse5 = createRequire(require.resolve("html-loader"))("parse5");
+class ElementFixture {
+ constructor(public node: any) {}
+ get ownerDocument() { return documentFixture; }
+ get children(): ElementFixture[] { return (this.node.childNodes || []).filter((node: any) => node.tagName).map(wrap); }
+ get childNodes(): ElementFixture[] { return (this.node.childNodes || []).map(wrap); }
+ get firstElementChild() { return this.children[0]; }
+ get parentElement() { return this.node.parentNode ? wrap(this.node.parentNode) : undefined; }
+ get attributes() { return this.node.attrs || []; }
+ get nodeType() { return this.node.tagName ? 1 : this.node.nodeName === "#comment" ? 8 : 11; }
+ get nodeValue() { return this.node.data; }
+ get dataset() { return {nodeId: this.getAttribute("data-node-id"), subtype: this.getAttribute("data-subtype"),
+ type: this.getAttribute("data-type")}; }
+ get classList() {
+ const classes = () => (this.getAttribute("class") || "").split(/\s+/);
+ return {contains: (name: string) => classes().includes(name), replace: (from: string, to: string) =>
+ this.setAttribute("class", classes().map(name => name === from ? to : name).join(" "))};
+ }
+ getAttribute(name: string): string | null { return this.attributes.find((attr: any) => attr.name === name)?.value ?? null; }
+ hasAttribute(name: string) { return this.getAttribute(name) !== null; }
+ setAttribute(name: string, value: string) {
+ this.removeAttribute(name);
+ (this.node.attrs ||= []).push({name, value});
+ }
+ removeAttribute(name: string) { this.node.attrs = this.attributes.filter((attr: any) => attr.name !== name); }
+ get outerHTML(): string { return parse5.serialize({nodeName: "#document-fragment", childNodes: [this.node]}); }
+ get innerHTML(): string { return parse5.serialize(this.node); }
+ set innerHTML(value: string) {
+ this.node.childNodes = parse5.parseFragment(value).childNodes;
+ this.node.childNodes.forEach((child: any) => { child.parentNode = this.node; });
+ }
+ get textContent(): string {
+ return this.node.nodeName === "#text" ? this.node.value : this.childNodes.map(child => child.textContent).join("");
+ }
+ set textContent(value: string) {
+ this.node.childNodes = [{nodeName: "#text", value, parentNode: this.node}];
+ }
+ remove() {
+ if (this.node.parentNode) {
+ this.node.parentNode.childNodes = this.node.parentNode.childNodes.filter((child: any) => child !== this.node);
+ this.node.parentNode = undefined;
+ }
+ }
+ insertBefore(child: ElementFixture, before: ElementFixture | null) {
+ child.remove();
+ const index = before ? this.node.childNodes.indexOf(before.node) : this.node.childNodes.length;
+ assert.ok(index >= 0);
+ this.node.childNodes.splice(index, 0, child.node);
+ child.node.parentNode = this.node;
+ }
+ replaceChildren(...children: ElementFixture[]) {
+ this.childNodes.forEach(child => child.remove());
+ children.forEach(child => this.insertBefore(child, null));
+ }
+ cloneNode() { return wrap(parse5.parseFragment(this.outerHTML)).firstElementChild; }
+ querySelector<T = ElementFixture>(selector: string): T | null { return this.querySelectorAll<T>(selector)[0] || null; }
+ querySelectorAll<T = ElementFixture>(selector: string): T[] {
+ if (selector.includes(", ")) {
+ return selector.split(", ").flatMap(part => this.querySelectorAll<T>(part));
+ }
+ const matches = (element: ElementFixture, value: string) => {
+ if (value.startsWith(".")) { return element.classList.contains(value.slice(1)); }
+ const attr = value.match(/^\[([^=\]]+)(?:="([^"]*)")?\]$/);
+ return attr ? attr[2] === undefined ? element.hasAttribute(attr[1]) :
+ element.getAttribute(attr[1]) === attr[2] : element.node.tagName === value;
+ };
+ if (selector.startsWith(":scope > ")) {
+ return this.children.filter(child => matches(child, selector.slice(9))) as T[];
+ }
+ const parts = selector.split(" > ");
+ const descendants: ElementFixture[] = [];
+ const visit = (element: ElementFixture) => element.children.forEach(child => { descendants.push(child); visit(child); });
+ visit(this);
+ return descendants.filter(child => matches(child, parts[parts.length - 1]) &&
+ (parts.length === 1 || matches(child.parentElement, parts[0]))) as T[];
+ }
+}
+const wrap = (node: any) => new ElementFixture(node);
+const documentFixture = {createTreeWalker: (root: ElementFixture) => {
+ const comments: ElementFixture[] = [];
+ const visit = (element: ElementFixture) => element.childNodes.forEach(child => {
+ if (child.nodeType === 8) { comments.push(child); }
+ visit(child);
+ });
+ visit(root);
+ let index = -1;
+ return {nextNode: () => comments[++index], get currentNode() { return comments[index]; }};
+}, createElement: (name: string) => {
+ if (name !== "template") { return wrap(parse5.parseFragment(`<${name}></${name}>`)).firstElementChild; }
+ const fragment = wrap(parse5.parseFragment(""));
+ return {content: fragment, get innerHTML() { return fragment.innerHTML; },
+ set innerHTML(value: string) { fragment.innerHTML = value; }};
+}};
+require(path.resolve("stage/protyle/js/lute/lute.min.js"));
+const lute = Lute.New();
+lute.SetKramdownIAL(true);
+lute.SetProtyleWYSIWYG(true);
+const source = readFileSync(path.join(__dirname, "model.ts"), "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, "");
+const api = new Function("Constants", "Lute", "document", "NodeFilter", transpileModule(source, {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText + "; return {convertListMindmapToList, readListMindmap, retagMindmapBranch, listMindmapConversionSource, cleanListMindmapHTML};")({
+ CUSTOM_SY_LIST_MINDMAP: "custom-sy-list-mindmap", CUSTOM_SY_LIST_MINDMAP_DATA: "custom-sy-list-mindmap-data",
+}, Lute, documentFixture, {SHOW_COMMENT: 8});
+const parse = (html: string) => wrap(parse5.parseFragment(html)).firstElementChild;
+const ids = (element: ElementFixture) => [element, ...element.querySelectorAll<ElementFixture>("[data-node-id]")]
+ .map(item => item.dataset.nodeId);
+const dataAttr = "custom-sy-list-mindmap-data";
+const tabsSource = transpileModule(readFileSync(path.join(__dirname, "../../wysiwyg/tabsList.ts"), "utf8")
+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""), {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+const completeSource = new Function(tabsSource + "; return completeTabsListSource;")();
+const transactionSource = createSourceFile("transaction.ts", readFileSync(path.join(__dirname,
+ "../../wysiwyg/transaction.ts"), "utf8"), ScriptTarget.ES2021, true);
+const updateDeclaration = transactionSource.statements.filter(isVariableStatement).find(statement =>
+ statement.declarationList.declarations.some(item => item.name.getText(transactionSource) === "updateTransaction"));
+const updateSource = transpileModule(updateDeclaration.getText(transactionSource).replace(/^export /, ""), {
+ compilerOptions: {target: ScriptTarget.ES2021},
+}).outputText;
+const getUpdateOperations = (element: ElementFixture, before: string) => {
+ let operations: {doOperations: IOperation[], undoOperations: IOperation[]};
+ const dependencies = {Constants: {ATTRIBUTE_EDITING: "data-editing"}, cleanListMindmapHTML: api.cleanListMindmapHTML,
+ cleanHeadingNumberHTML: (html: string) => html, cleanTableCellRichHTML: (html: string) => html,
+ cleanBlockSelectionModeHTML: (html: string) => html,
+ transaction: (_owner: IProtyle, doOperations: IOperation[], undoOperations: IOperation[]) => {
+ operations = {doOperations, undoOperations};
+ }};
+ new Function(...Object.keys(dependencies), updateSource + "; return updateTransaction;")(
+ ...Object.values(dependencies))({}, element, before);
+ element.removeAttribute("data-editing");
+ return operations;
+};
+
+test("titled virtual roots preserve content, identities and associations across every list type", () => {
+ for (const legacy of [false, true]) {
+ for (const marker of ["*", "3.", "* [X]"]) {
+ for (const conversion of ["OL2UL", "UL2OL", "UL2TL"]) {
+ const indent = marker === "3." ? " " : " ";
+ const original = parse(lute.Md2BlockDOM(`${marker} Alpha\n${indent}* Nested\n${marker} Beta\n`));
+ if (legacy) { original.setAttribute("custom-sy-list-mindmap", "1"); }
+ else { api.retagMindmapBranch(original, true); }
+ const children = original.children.filter(child => child.dataset.nodeId);
+ assert.equal(children.length, 2);
+ children[0].setAttribute("custom-keep", "value");
+ children[0].setAttribute("fold", "1");
+ original.setAttribute("custom-container", "keep");
+ const rootID = original.dataset.nodeId;
+ const metadata = {version: 1, rootTitle: "<Root> & **literal**", extension: "keep",
+ nodes: {[rootID]: {bold: true, extension: "keep"}, [children[0].dataset.nodeId]: {italic: true}},
+ relations: [{id: "r", from: rootID, to: children[0].dataset.nodeId, label: "link"}],
+ summaries: [{id: "s", parentId: rootID, nodeIds: children.map(child => child.dataset.nodeId), label: "both"}]};
+ original.setAttribute(dataAttr, JSON.stringify(metadata));
+ const before = original.outerHTML;
+ const oldIDs = ids(original);
+ const result = parse(api.convertListMindmapToList(original, conversion, lute));
+ const model = api.readListMindmap(result);
+ assert.equal(original.outerHTML, before, "undo source is unchanged");
+ assert.equal(result.dataset.type, "NodeList");
+ assert.equal(result.dataset.nodeId, rootID);
+ assert.equal(result.getAttribute("custom-container"), "keep");
+ assert.equal(model.root.virtual, false);
+ assert.equal(model.root.contentBlocks[0].querySelector("[contenteditable]").textContent, metadata.rootTitle);
+ assert.equal(model.root.children.length, 2);
+ assert.equal(model.root.children[0].element.getAttribute("custom-keep"), "value");
+ assert.equal(model.root.children[0].element.getAttribute("fold"), "1");
+ assert.ok(oldIDs.every(id => ids(result).includes(id)));
+ assert.equal(ids(result).length, oldIDs.length + 3);
+ assert.equal(new Set(ids(result)).size, ids(result).length);
+ assert.equal(model.metadata.rootTitle, undefined);
+ assert.equal(model.metadata.extension, "keep");
+ assert.deepEqual(model.metadata.nodes[model.root.id], metadata.nodes[rootID]);
+ assert.equal(model.metadata.relations[0].from, model.root.id);
+ assert.equal(model.metadata.relations[0].to, children[0].dataset.nodeId);
+ assert.equal(model.metadata.summaries[0].parentId, model.root.id);
+ assert.deepEqual(model.metadata.summaries[0].nodeIds, metadata.summaries[0].nodeIds);
+ if (marker === "* [X]" && conversion === "UL2TL") {
+ assert.equal(model.root.taskMarker, " ");
+ assert.equal(model.root.children[0].taskMarker, "X");
+ }
+ const operations = getUpdateOperations(result, before);
+ assert.equal(operations.doOperations.length, 1);
+ assert.equal(operations.undoOperations.length, 1);
+ assert.equal(operations.doOperations[0].id, rootID);
+ assert.equal(operations.undoOperations[0].id, rootID);
+ const undo = parse(operations.undoOperations[0].data as string);
+ assert.deepEqual(ids(undo), oldIDs);
+ assert.equal(undo.getAttribute(dataAttr), JSON.stringify(metadata));
+ assert.equal(undo.dataset.type, original.dataset.type);
+ const redo = parse(operations.doOperations[0].data as string);
+ assert.deepEqual(ids(redo), ids(result));
+ assert.equal(redo.getAttribute(dataAttr), result.getAttribute(dataAttr));
+ const savedIDs = ids(result);
+ api.retagMindmapBranch(result, true);
+ const again = parse(api.convertListMindmapToList(result, conversion, lute));
+ assert.deepEqual(ids(again), savedIDs, "round trips do not add another parent");
+ assert.equal(api.readListMindmap(again).root.children.length, 2);
+ }
+ }
+ }
+});
+
+test("empty titles and existing real roots retain their original hierarchy", () => {
+ for (const [markdown, title] of [["* One\n* Two\n", " \n"], ["* Root\n * Child\n", "Dormant title"]]) {
+ const list = parse(lute.Md2BlockDOM(markdown));
+ api.retagMindmapBranch(list, true);
+ const metadata = JSON.stringify({version: 1, rootTitle: title, nodes: {}, relations: []});
+ list.setAttribute(dataAttr, metadata);
+ const result = parse(api.convertListMindmapToList(list, "UL2OL", lute));
+ assert.deepEqual(ids(result), ids(list));
+ assert.equal(result.getAttribute(dataAttr), metadata);
+ }
+});
+
+test("shared sources for tabs and paragraph conversion do not acquire a parent", () => {
+ const list = parse(lute.Md2BlockDOM("* One\n* Two\n"));
+ api.retagMindmapBranch(list, true);
+ const metadata = JSON.stringify({version: 1, rootTitle: "Title", nodes: {}, relations: []});
+ list.setAttribute(dataAttr, metadata);
+ const result = api.listMindmapConversionSource(list);
+ assert.deepEqual(ids(result), ids(list));
+ assert.equal(result.getAttribute(dataAttr), metadata);
+ assert.equal(api.convertListMindmapToList(list, "CancelList", lute), undefined);
+});
+
+test("completing a partial folded map preserves local edits and every hidden block before conversion and undo", () => {
+ const full = parse(lute.Md2BlockDOM("* Alpha\n * Hidden\n* Beta\n"));
+ api.retagMindmapBranch(full, true);
+ full.setAttribute(dataAttr, JSON.stringify({version: 1, rootTitle: "Title", nodes: {}, relations: []}));
+ const visible = full.cloneNode();
+ const items = visible.children.filter(child => child.dataset.nodeId);
+ items[1].remove();
+ items[0].querySelector<ElementFixture>('[data-type="NodeMindmap"]').remove();
+ items[0].querySelector<ElementFixture>("[contenteditable]").textContent = "Edited";
+ items[0].setAttribute("fold", "1");
+ const before = visible.outerHTML;
+ assert.equal(api.readListMindmap(visible).root.virtual, false, "partial source alone cannot identify the virtual root");
+ const complete = completeSource(visible, full);
+ assert.equal(visible.outerHTML, before);
+ assert.deepEqual(ids(complete), ids(full));
+ const result = parse(api.convertListMindmapToList(complete, "UL2TL", lute));
+ const model = api.readListMindmap(result);
+ assert.equal(model.root.contentBlocks[0].querySelector("[contenteditable]").textContent, "Title");
+ assert.equal(model.root.children[0].contentBlocks[0].querySelector("[contenteditable]").textContent, "Edited");
+ assert.equal(model.root.children[0].children.length, 1);
+ assert.ok(ids(full).every(id => ids(result).includes(id)));
+ const operations = getUpdateOperations(result, complete.outerHTML);
+ const undo = parse(operations.undoOperations[0].data as string);
+ assert.deepEqual(ids(undo), ids(full));
+ assert.equal(undo.querySelector<ElementFixture>("[contenteditable]").textContent, "Edited");
+ assert.equal(api.readListMindmap(undo).metadata.rootTitle, "Title");
+});
diff --git a/app/src/protyle/render/listMindmap/toggle.test.ts b/app/src/protyle/render/listMindmap/toggle.test.ts
index b495e0b32e..ee3e0c6527 100644
--- a/app/src/protyle/render/listMindmap/toggle.test.ts
+++ b/app/src/protyle/render/listMindmap/toggle.test.ts
@@ -12,7 +12,7 @@ const declarations = source.statements.filter(statement => isVariableStatement(s
const compiled = transpileModule(declarations.map(item => item.getText(source).replace(/^export /, "")).join("\n") +
"\nglobalThis.api = {canEdit, toggleListMindmap};", {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;
-const setup = () => {
+const setup = (embedded = true) => {
const root = {};
const embed = {};
const owner = {disabled: false, lite: false, options: {action: [] as string[]}, wysiwyg: {element: root}};
@@ -22,17 +22,28 @@ const setup = () => {
isConnected: true,
dataset: {type: "NodeList", nodeId: "source-list"},
outerHTML: '<div data-type="NodeList"></div>',
- closest: (selector: string) => selector === ".protyle-wysiwyg" ? root : embed,
+ closest: (selector: string) => selector === ".protyle-wysiwyg" ? root : embedded ? embed : null,
+ get attributes() { return Array.from(attrs, ([name, value]) => ({name, value})); },
getAttribute: (name: string) => attrs.get(name),
- setAttribute: (name: string, value: string) => attrs.set(name, value),
+ setAttribute: (name: string, value: string) => {
+ if (name === "data-type") { list.dataset.type = value; }
+ attrs.set(name, value);
+ },
removeAttribute: (name: string) => attrs.delete(name),
+ replaceChildren: (...children: unknown[]) => { replaced.push(children); },
+ ownerDocument: {createElement: () => ({innerHTML: "", content: {firstElementChild: {
+ attributes: [{name: "data-type", value: "NodeList"}, {name: "data-node-id", value: "source-list"}],
+ childNodes: ["new parent"],
+ }}})},
};
+ const replaced: unknown[][] = [];
const operations: {doOperations: any[], undoOperations: any[]}[] = [];
const updates: string[] = [];
const context: any = {
Constants: {CB_GET_HISTORY: "history", CUSTOM_SY_LIST_MINDMAP: attribute},
isProtyleListItemFragment,
roots: new WeakMap(), hideElements: () => {}, readListMindmap: () => {},
+ hasListMindmapRootTitle: () => false,
cleanListMindmapHTML: (html: string) => html,
retagMindmapBranch: (_element: Element, toMindmap: boolean) => {
list.dataset.type = toMindmap ? "NodeMindmap" : "NodeList";
@@ -44,7 +55,7 @@ const setup = () => {
},
};
runInNewContext(compiled, context);
- return {owner, list, attrs, attribute, operations, updates, api: context.api};
+ return {owner, list, attrs, attribute, operations, updates, replaced, context, api: context.api};
};
test("a regular list becomes a dedicated mind map block", () => {
@@ -122,3 +133,50 @@ test("removed lists and blocks without IDs cannot submit view changes", () => {
assert.equal(operations.length, 0);
}
});
+
+test("leaving either mindmap format materializes a title using its current list type and full undo source", async () => {
+ for (const legacy of [false, true]) {
+ for (const [subtype, conversion] of [["u", "OL2UL"], ["o", "UL2OL"], ["t", "UL2TL"]]) {
+ const state = setup(false);
+ if (!legacy) { state.list.dataset.type = "NodeMindmap"; }
+ state.context.hasListMindmapRootTitle = () => true;
+ const full = {outerHTML: "complete source", getAttribute: () => subtype};
+ state.context.prepareListMindmapConversion = async () => full;
+ state.context.convertListMindmapToList = (source: unknown, type: string) => {
+ assert.equal(source, full);
+ assert.equal(type, conversion);
+ return "converted";
+ };
+ await state.api.toggleListMindmap(state.owner, state.list);
+ assert.equal(state.list.dataset.type, "NodeList");
+ assert.deepEqual(state.updates, ["complete source"]);
+ assert.deepEqual(state.replaced, [["new parent"]]);
+ assert.equal(state.operations.length, 0);
+ }
+ }
+});
+
+test("a failed preparation or revoked editing permission cannot change the exiting mindmap", async () => {
+ for (const disabled of [false, true]) {
+ const state = setup(false);
+ state.list.dataset.type = "NodeMindmap";
+ state.context.hasListMindmapRootTitle = () => true;
+ state.context.prepareListMindmapConversion = async () => {
+ state.owner.disabled = disabled;
+ return disabled ? {} : undefined;
+ };
+ await state.api.toggleListMindmap(state.owner, state.list);
+ assert.equal(state.list.dataset.type, "NodeMindmap");
+ assert.deepEqual(state.updates, []);
+ assert.deepEqual(state.replaced, []);
+ }
+});
+
+test("embedded read-only content exits without materializing its virtual root", async () => {
+ const state = setup();
+ state.context.hasListMindmapRootTitle = () => { throw new Error("no content conversion in embeds"); };
+ await state.api.toggleListMindmap(state.owner, state.list);
+ assert.equal(state.operations.length, 1);
+ assert.deepEqual(state.updates, []);
+ assert.deepEqual(state.replaced, []);
+});
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 58af1712fe..b31b0603f9 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -79,7 +79,11 @@ import {isEmptyParagraph} from "./emptyTextBlock";
import {getHeadingConversionElements, isListHeadingContainer} from "./headingConversion";
import {cleanTableCellRichHTML, getTableBlockHTML, retainTableCellRichMetadata} from "../util/tableCellRich";
import {cleanTableVirtualizationHTML, TABLE_VIRTUAL_ID} from "../util/tableVirtualizationDOM";
-import {cleanListMindmapHTML, convertListMindmapToList, listMindmapConversionSource} from "../render/listMindmap/model";
+import {
+ cleanListMindmapHTML, convertListMindmapToList, hasListMindmapRootTitle,
+ isListMindmapListConversion, listMindmapConversionSource,
+} from "../render/listMindmap/model";
+import {prepareListMindmapConversion} from "../render/listMindmap/conversion";
import {buildCancelListOperations} from "./cancelList";
import {buildListConversionOperations} from "./listConversion";
import {getProtyleTransactionOwner} from "../runtimeCapabilities";
@@ -2309,9 +2313,19 @@ export const turnsOneInto = async (options: {
if (["CancelBlockquote", "CancelList", "CancelCallout"].includes(options.type)) {
foldOperations = await unfoldListHeadings(options.protyle, [options.nodeElement]);
}
- let oldHTML = options.nodeElement.outerHTML;
+ const completeMindmap = isListMindmapListConversion(options.nodeElement, options.type) &&
+ hasListMindmapRootTitle(options.nodeElement);
+ const conversionSource = completeMindmap ?
+ await prepareListMindmapConversion(options.protyle, options.nodeElement) : options.nodeElement;
+ if (!conversionSource) {
+ return;
+ }
+ const mindmapSnapshot = completeMindmap ? cleanListMindmapHTML(options.nodeElement.outerHTML) : undefined;
+ const mindmapRootID = options.protyle.block.rootID;
+ const mindmapNotebookID = options.protyle.notebookId;
+ let oldHTML = conversionSource.outerHTML;
if (options.undoElement) {
- const oldElement = options.nodeElement.cloneNode(true) as HTMLElement;
+ const oldElement = conversionSource.cloneNode(true) as HTMLElement;
const undoElement = oldElement.querySelector(`[data-node-id="${options.undoElement.id}"]`);
if (undoElement) {
undoElement.outerHTML = options.undoElement.html;
@@ -2330,11 +2344,20 @@ export const turnsOneInto = async (options: {
}
previousId = response.data.previousID;
}
+ if (completeMindmap && (!options.nodeElement.isConnected || options.protyle.disabled ||
+ options.protyle.block.rootID !== mindmapRootID ||
+ options.protyle.notebookId !== mindmapNotebookID ||
+ options.protyle.options.action.includes(Constants.CB_GET_HISTORY) ||
+ options.nodeElement.closest(".protyle-wysiwyg__embed") ||
+ options.nodeElement.closest(".protyle-wysiwyg") !== options.protyle.wysiwyg.element ||
+ cleanListMindmapHTML(options.nodeElement.outerHTML) !== mindmapSnapshot)) {
+ return;
+ }
const parentId = getEmbedChildOperationParentID(options.nodeElement) ||
getParentBlock(options.nodeElement).getAttribute("data-node-id") || options.protyle.block.parentID;
let newHTML: string;
if (isTabsListConversion(options.type)) {
- let source = options.nodeElement;
+ let source = conversionSource;
if (!options.protyle.lite && source.querySelector('[fold="1"]')) {
await waitForPendingTransactions(options.protyle);
const snapshot = source.outerHTML;
@@ -2364,7 +2387,7 @@ export const turnsOneInto = async (options: {
}
newHTML = converted.outerHTML;
} else {
- const listHTML = convertListMindmapToList(options.nodeElement, options.type, options.protyle.lute);
+ const listHTML = convertListMindmapToList(conversionSource, options.type, options.protyle.lute);
const sourceHTML = options.type === "CancelList" && options.nodeElement.getAttribute("data-type") === "NodeMindmap" ?
listMindmapConversionSource(options.nodeElement).outerHTML : cleanListMindmapHTML(options.nodeElement.outerHTML);
// @ts-ignore