Skip to content

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

:sparkles: Support rich content editing in mind map nodes https://github.com/siyuan-note/siyuan/issues/18831

Vanessa1190b41ae1af
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index 1994205973..a10aa109fb 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -649,7 +649,7 @@ export const popTextCell = (protyle: IProtyle, cellElements: HTMLElement[], type
if (!options?.keepMenuOpen) {
window.siyuan.menus.menu.remove();
}
- document.body.insertAdjacentHTML("beforeend", `<div class="av__mask" style="z-index: ${++window.siyuan.zIndex}">
+ document.body.insertAdjacentHTML("beforeend", `<div class="av__mask" data-av-block-id="${escapeAttr(blockElement.dataset.nodeId)}" style="z-index: ${++window.siyuan.zIndex}">
${html}
</div>`);
const avMaskElement = document.querySelector(".av__mask");
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index f9eecd2aa2..2016f9a1df 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -226,7 +226,7 @@ export const openMenuPanel = (options: {
}
}
- document.body.insertAdjacentHTML("beforeend", `<div class="av__panel" style="z-index: ${++window.siyuan.zIndex};">
+ document.body.insertAdjacentHTML("beforeend", `<div class="av__panel" data-av-block-id="${escapeAttr(blockID)}" style="z-index: ${++window.siyuan.zIndex};">
<div class="b3-dialog__scrim" data-type="close"></div>
<div class="b3-menu${options.type === "filters" ? " av__filter-panel" : ""}${options.type === "relation" ? " av__relation-panel" : ""}" ${options.keepMenuOpen ? "data-menu=\"true\"" : ""} ${["select", "date", "asset", "relation", "rollup"].includes(options.type) ? `style="${["select", "asset", "relation"].includes(options.type) ? "max-height: calc(100vh - 32px);display: flex;flex-direction: column;" : ""}min-width: 200px;${options.type === "relation" ? `width: 760px;max-width: ${isMobile() ? "90vw" : "calc(100vw - 32px)"};` : isMobile() ? "max-width: 90vw;" : "max-width: 50vw;"}"` : ""}>${html}</div>
</div>`);
diff --git a/app/src/protyle/render/av/richTextEditor.ts b/app/src/protyle/render/av/richTextEditor.ts
index 30fe74558c..4d818d0abb 100644
--- a/app/src/protyle/render/av/richTextEditor.ts
+++ b/app/src/protyle/render/av/richTextEditor.ts
@@ -103,6 +103,7 @@ export const openAVRichTextEditor = (options: AVRichTextEditorOptions) => {
const mobile = isMobile();
const maskElement = document.createElement("div");
maskElement.className = "av__mask av__richtext-mask";
+ maskElement.dataset.avBlockId = options.nodeElement.dataset.nodeId;
maskElement.style.zIndex = (++window.siyuan.zIndex).toString();
maskElement.innerHTML = `<div class="av__richtext-editor" role="dialog">
<div class="av__richtext-host"></div>
diff --git a/app/src/protyle/render/listMindmap/editor.test.ts b/app/src/protyle/render/listMindmap/editor.test.ts
index 4dcc881a09..7f1ebb6c60 100644
--- a/app/src/protyle/render/listMindmap/editor.test.ts
+++ b/app/src/protyle/render/listMindmap/editor.test.ts
@@ -36,12 +36,14 @@ const browserCases = async (sourceCode: string, css: string) => {
block.textContent = text;
return block.outerHTML;
};
- const create = () => {
+ const create = (initialBlockHTML = textHTML("Initial")) => {
+ let transactionOwner: (operations: Array<{action: string; id: string; parentID?: string;
+ previousID?: string; nextID?: string}>) => unknown;
const container = document.createElement("section");
const element = document.createElement("div");
element.dataset.type = "NodeListItem";
element.dataset.nodeId = "item";
- element.innerHTML = textHTML("Initial");
+ element.innerHTML = initialBlockHTML;
const host = document.createElement("div");
host.style.display = "inline-block";
host.style.width = "120px";
@@ -66,7 +68,7 @@ const browserCases = async (sourceCode: string, css: string) => {
const protyle = {
block: {rootID: ""},
undo: {clear: noop},
- wysiwyg: {flushPendingInput: async () => {
+ wysiwyg: {lastHTMLs: {} as Record<string, string>, flushPendingInput: async () => {
state.flushed++;
await state.flush();
}},
@@ -87,7 +89,9 @@ const browserCases = async (sourceCode: string, css: string) => {
initialBlockHTML: string;
onChange: () => void;
afterSetContent: (owner: unknown, element: HTMLElement) => void;
+ runtimeCapabilities: {getTransactionOwner: typeof transactionOwner};
}) => {
+ transactionOwner = options.runtimeCapabilities.getTransactionOwner;
target.style.width = "";
wysiwyg.innerHTML = options.initialBlockHTML;
target.append(wysiwyg);
@@ -110,19 +114,18 @@ const browserCases = async (sourceCode: string, css: string) => {
getDefaultToolbar: (): unknown[] => [],
hideElements: noop,
matchHotKey: () => false,
- TABLE_CELL_SLASH_IDS: new Set<string>(),
- configureAVRichTextLute: noop,
- getAVRichTextLute: () => ({}),
- getAVRichTextUnsupportedPasteBlocks: (): string[] => [],
- sanitizeAVRichTextBlockDOM: (html: string) => html,
+ processRender: noop,
+ setCustomBlockRootReady: noop,
+ avRender: noop,
+ blockRender: noop,
highlightRender: noop,
- mathRender: noop,
cleanListMindmapHTML: (html: string) => html,
};
const open = new Function(...Object.keys(dependencies), sourceCode + "; return openListMindmapEditor;")(
...Object.values(dependencies));
+ const owner = {app: {}, notebookId: "notebook", block: {rootID: "document"}};
const editor = open({
- owner: {app: {}, notebookId: "notebook", block: {rootID: "document"}},
+ owner,
node: {element}, host,
canEdit: () => element.isConnected,
onResize: noop,
@@ -149,15 +152,129 @@ const browserCases = async (sourceCode: string, css: string) => {
await until(() => state.destroyed === 1);
container.remove();
};
- return {container, element, host, wysiwyg, state, editor, type, remove};
+ return {container, element, host, wysiwyg, protyle, state, editor, type, remove,
+ owner, transactionOwner: (operations: Parameters<typeof transactionOwner>[0]) => transactionOwner(operations)};
};
window.siyuan = {
languages: {listMindmapStale: "Content changed", listMindmapUnsupported: "Unsupported"},
config: {keymap: {editor: {general: {undo: "undo", redo: "redo"}}}},
} as unknown as typeof window.siyuan;
+ // 特殊块与普通文字共存时仍可进入编辑,修改文字不会改变特殊块的源码和属性。
+ for (const type of ["NodeThematicBreak", "NodeTable", "NodeAttributeView", "NodeBlockQueryEmbed",
+ "NodeCustomBlock", "NodeHTMLBlock", "NodeIFrame", "NodeWidget", "NodeVideo", "NodeAudio",
+ "NodeCallout", "NodeSuperBlock", "NodeTabs"]) {
+ const special = document.createElement("div");
+ special.dataset.type = type;
+ special.dataset.nodeId = "special";
+ special.dataset.content = "Raw source & attributes";
+ special.setAttribute("custom-preserve", "Original value");
+ special.textContent = "Preserved content";
+ const current = create(textHTML("Initial") + special.outerHTML);
+ current.wysiwyg.firstElementChild.textContent = "Edited text";
+ await settle();
+ check.equal(await current.editor.finish(), true, type);
+ check.equal(current.element.firstElementChild.textContent, "Edited text", type);
+ check.equal(current.element.lastElementChild.outerHTML, special.outerHTML, type);
+ check.equal(current.state.messages.length, 0, type);
+ await current.remove();
+ }
+
+ // 数据库和嵌入结果在编辑期间重新渲染,不会挡住普通文字保存或覆盖新的独立块状态。
+ for (const type of ["NodeAttributeView", "NodeBlockQueryEmbed"]) {
+ const special = document.createElement("div");
+ special.dataset.type = type;
+ special.dataset.nodeId = "special";
+ if (type === "NodeAttributeView") {
+ special.dataset.avId = "database";
+ } else {
+ special.dataset.content = "select * from blocks";
+ }
+ special.textContent = "Old projection";
+ const current = create(textHTML("Initial") + special.outerHTML);
+ current.element.lastElementChild.setAttribute("updated", "20260923120000");
+ current.element.lastElementChild.textContent = "Latest projection";
+ current.wysiwyg.lastElementChild.setAttribute("data-render", "true");
+ current.wysiwyg.lastElementChild.textContent = "Editor projection";
+ await settle();
+ current.wysiwyg.firstElementChild.textContent = "Edited text";
+ await settle();
+ check.equal(await current.editor.finish(), true, type);
+ check.equal(current.element.firstElementChild.textContent, "Edited text", type);
+ check.equal(current.element.lastElementChild.textContent, "Latest projection", type);
+ check.equal(current.state.messages.length, 0, type);
+ await current.remove();
+ }
+
+ // 嵌套在超级块中的数据库要沿用最新属性,避免保存相邻文字时写回旧视图配置。
+ let nested = create(textHTML("Initial") +
+ '<div data-type="NodeSuperBlock" data-node-id="container"><div data-type="NodeAttributeView" ' +
+ 'data-node-id="nested-database" data-av-id="database" custom-sy-av-view="old">Old projection</div></div>');
+ nested.element.querySelector('[data-node-id="nested-database"]').setAttribute("custom-sy-av-view", "new");
+ nested.wysiwyg.firstElementChild.textContent = "Edited text";
+ await settle();
+ check.equal(await nested.editor.finish(), true);
+ check.equal(nested.element.querySelector('[data-node-id="nested-database"]').getAttribute("custom-sy-av-view"), "new");
+ await nested.remove();
+
+ // 嵌入源块的拆分和删除与文字更新使用同一外层事务,普通节点正文仍留在片段中保存。
+ nested = create(textHTML("Initial") +
+ '<div data-type="NodeBlockQueryEmbed" data-node-id="embed" data-content="query"><div ' +
+ 'class="protyle-wysiwyg__embed" data-id="source"><div data-type="NodeParagraph" ' +
+ 'data-node-id="source">Source</div></div></div>');
+ await settle();
+ const result = nested.wysiwyg.querySelector(".protyle-wysiwyg__embed");
+ result.insertAdjacentHTML("beforeend", '<div data-type="NodeParagraph" data-node-id="new-source">New</div>');
+ check.equal(nested.transactionOwner([{action: "update", id: "source"},
+ {action: "insert", id: "new-source", previousID: "source"}]), nested.owner);
+ result.querySelector('[data-node-id="new-source"]').remove();
+ check.equal(nested.transactionOwner([{action: "delete", id: "new-source"}]), nested.owner);
+ check.equal(nested.transactionOwner([{action: "insert", id: "first-source", parentID: "source"}]), nested.owner);
+ check.equal(nested.transactionOwner([{action: "update", id: "paragraph"}]), undefined);
+ await nested.remove();
+
+ // 数据库浮层属于当前节点时保留编辑会话,其他位置的点击仍正常结束编辑。
+ for (const overlayClass of ["av__panel", "av__mask av__richtext-mask"]) {
+ const current = create(textHTML("Initial") +
+ '<div data-type="NodeAttributeView" data-node-id="database" data-av-id="view"></div>');
+ const overlay = document.createElement("div");
+ overlay.className = overlayClass;
+ overlay.dataset.avBlockId = "database";
+ document.body.append(overlay);
+ overlay.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));
+ await settle();
+ check.equal(current.state.destroyed, 0, overlayClass);
+ overlay.dataset.avBlockId = "other-database";
+ overlay.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true}));
+ await until(() => current.state.destroyed === 1);
+ overlay.remove();
+ await current.remove();
+ }
+
+ // 查询源码本身发生外部修改时仍视为冲突,避免旧编辑会话覆盖新查询。
+ let current = create(textHTML("Initial") +
+ '<div data-type="NodeBlockQueryEmbed" data-node-id="special" data-content="old query"></div>');
+ current.wysiwyg.firstElementChild.textContent = "Local text";
+ current.element.lastElementChild.setAttribute("data-content", "new query");
+ check.equal(await current.editor.finish(), false);
+ check.equal(current.state.saves.length, 0);
+ await current.remove();
+
+ // 浏览器将输入事件派发给编辑器根节点时,也要为嵌入源块保存有效的撤销快照。
+ current = create(textHTML("Initial") +
+ '<div data-type="NodeBlockQueryEmbed" data-node-id="special" data-content="query"><div class="protyle-wysiwyg__embed"><div data-node-id="source" data-type="NodeParagraph"><div contenteditable="true">Source</div></div></div></div>');
+ const sourceBlock = current.wysiwyg.querySelector<HTMLElement>('[data-node-id="source"]');
+ const range = document.createRange();
+ range.selectNodeContents(sourceBlock.firstElementChild);
+ range.collapse(false);
+ getSelection().removeAllRanges();
+ getSelection().addRange(range);
+ current.wysiwyg.dispatchEvent(new InputEvent("beforeinput", {bubbles: true, inputType: "insertText", data: " edited"}));
+ check.equal(current.protyle.wysiwyg.lastHTMLs.source, sourceBlock.outerHTML);
+ await current.remove();
+
// 关闭前等待输入转换完成,保存转换后的最终内容后再销毁编辑器。
- let current = create();
+ current = create();
check.equal(current.host.offsetWidth, 120, "mounting the editor preserves the preview width");
await current.type("Pending");
const flushGate = gate();
diff --git a/app/src/protyle/render/listMindmap/editor.ts b/app/src/protyle/render/listMindmap/editor.ts
index 05b34e8d47..fa621ce644 100644
--- a/app/src/protyle/render/listMindmap/editor.ts
+++ b/app/src/protyle/render/listMindmap/editor.ts
@@ -1,4 +1,5 @@
import {showMessage} from "../../../dialog/message";
+import {setCustomBlockRootReady} from "../../../plugin/customBlockRender";
import {escapeHtml} from "../../../util/escape";
import {isMobile} from "../../../util/functions";
import {hintRef, hintSlash} from "../../hint/extend";
@@ -9,12 +10,10 @@ import {setMobileToolbarUndo} from "../../lite/mobileToolbar";
import {getDefaultToolbar} from "../../toolbar/defaults";
import {hideElements} from "../../ui/hideElements";
import {matchHotKey} from "../../util/hotKey";
-import {TABLE_CELL_SLASH_IDS} from "../../util/tableCellRichMenu";
-import {
- configureAVRichTextLute, getAVRichTextLute, getAVRichTextUnsupportedPasteBlocks, sanitizeAVRichTextBlockDOM,
-} from "../av/richText";
+import {processRender} from "../../util/processCode";
+import {avRender} from "../av/render";
+import {blockRender} from "../blockRender";
import {highlightRender} from "../highlightRender";
-import {mathRender} from "../mathRender";
import {cleanListMindmapHTML} from "./model";
import type {ListMindmapNode} from "./model";
@@ -33,6 +32,49 @@ const nodeContent = (node: ListMindmapNode) => Array.from(node.element?.children
child.hasAttribute("data-node-id") && child.getAttribute("data-type") !== "NodeList")
.map(child => cleanListMindmapHTML(child.outerHTML)).join("");
+const independentBlockSelector = '[data-type="NodeAttributeView"], [data-type="NodeBlockQueryEmbed"]';
+
+const comparableContent = (html: string) => {
+ const template = document.createElement("template");
+ template.innerHTML = cleanListMindmapHTML(html);
+ template.content.querySelectorAll<HTMLElement>(independentBlockSelector).forEach(block => {
+ if (block.dataset.type === "NodeAttributeView") {
+ const identity = document.createElement("div");
+ identity.dataset.type = block.dataset.type;
+ identity.dataset.nodeId = block.dataset.nodeId;
+ identity.dataset.avId = block.dataset.avId;
+ block.replaceWith(identity);
+ } else {
+ block.removeAttribute("updated");
+ block.removeAttribute("data-render");
+ block.replaceChildren();
+ }
+ });
+ return template.innerHTML;
+};
+
+const retainIndependentBlocks = (html: string, node: ListMindmapNode) => {
+ const template = document.createElement("template");
+ template.innerHTML = html;
+ const current = new Map<string, Element>();
+ Array.from(node.element.children).filter(child => child.hasAttribute("data-node-id") &&
+ child.getAttribute("data-type") !== "NodeList").forEach(child => {
+ const blocks = [child, ...Array.from(child.querySelectorAll(independentBlockSelector))];
+ blocks.forEach(block => {
+ if (block.matches(independentBlockSelector) && !block.closest(".protyle-wysiwyg__embed")) {
+ current.set(block.getAttribute("data-node-id"), block);
+ }
+ });
+ });
+ template.content.querySelectorAll<HTMLElement>(independentBlockSelector).forEach(block => {
+ const latest = current.get(block.dataset.nodeId);
+ if (latest && comparableContent(block.outerHTML) === comparableContent(latest.outerHTML)) {
+ block.replaceWith(latest.cloneNode(true));
+ }
+ });
+ return template.innerHTML;
+};
+
// 编辑器只在双击时挂载到节点内容区,预览与编辑沿用同一尺寸和排版。
export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
const {owner, node, host} = options;
@@ -40,10 +82,6 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
if (!options.canEdit() || !node.element?.isConnected) {
return;
}
- if (getAVRichTextUnsupportedPasteBlocks(initialBlockHTML, true).length) {
- showMessage(window.siyuan.languages.listMindmapUnsupported);
- return;
- }
hideElements(["gutter", "toolbar", "hint"], owner);
let finished = false;
let closing = false;
@@ -54,40 +92,67 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
let pendingSave: Promise<boolean> | undefined;
let pendingFinish: Promise<boolean> | undefined;
let saveTimer: number;
- let source = initialBlockHTML;
+ let source = comparableContent(initialBlockHTML);
let recoveryShown = false;
const events = new AbortController();
const toolbar = getDefaultToolbar(isMobile()).filter(item =>
typeof item === "string" ? item !== "ai" : item.name !== "ai");
const slash = registerBuiltinSlashHint((key: string, protyle: IProtyle, hintSource: THintSource) =>
- hintSlash(key, protyle, hintSource).filter(item => TABLE_CELL_SLASH_IDS.has(item.id) &&
- !["list", "orderedList", "check"].includes(item.id)));
+ hintSlash(key, protyle, hintSource).filter(item => !["list", "orderedList", "check"].includes(item.id)));
const hint: IProtyleOptions["hint"] = {
extend: [{key: "((", hint: hintRef}, {key: "【【", hint: hintRef}, {key: "((", hint: hintRef},
{key: "[[", hint: hintRef}, {key: "/", hint: slash}, {key: "、", hint: slash}],
};
const originalMinWidth = host.style.minWidth;
+ const embedSourceIDs = new Set<string>();
+ const rememberEmbedSourceIDs = () => {
+ host.querySelectorAll<HTMLElement>(".protyle-wysiwyg__embed").forEach(result => {
+ if (result.dataset.id) {
+ embedSourceIDs.add(result.dataset.id);
+ }
+ result.querySelectorAll<HTMLElement>("[data-node-id]").forEach(block => {
+ embedSourceIDs.add(block.dataset.nodeId);
+ });
+ });
+ };
+ const embedSourceObserver = new MutationObserver(rememberEmbedSourceIDs);
+ embedSourceObserver.observe(host, {childList: true, subtree: true});
// 保留未缩放的亚像素宽度,避免取整后响应式容器挤压文字,导致换行和整棵树重排。
host.style.minWidth = getComputedStyle(host).width;
host.replaceChildren();
host.classList.add("list-mindmap__editor");
- host.dataset.protyleLiteRender = "safe";
host.contentEditable = "false";
const fragment = mountProtyleLiteFragment(host, {
app: owner.app,
initialBlockHTML,
protyleOptions: {notebookId: owner.notebookId, toolbar, hint},
runtimeCapabilities: {
- upload: false, websocket: false, pluginExtensions: false, customBlockRender: false,
+ upload: false, websocket: false, pluginExtensions: false,
listItemFragment: true,
- lute: getAVRichTextLute(), lockedOptions: {toolbar, hint},
- sanitizeBlockDOM: html => sanitizeAVRichTextBlockDOM(html, true),
- getUnsupportedPasteBlocks: html => getAVRichTextUnsupportedPasteBlocks(html, true),
- restoreLuteMarkdownSyntax: configureAVRichTextLute,
+ getTransactionOwner: operations => {
+ const avIDs = new Set(Array.from(host.querySelectorAll<HTMLElement>(
+ '[data-type="NodeAttributeView"][data-av-id]')).map(element => element.dataset.avId));
+ if (operations.some(operation => operation.action.includes("AttrView") &&
+ avIDs.has("avID" in operation && typeof operation.avID === "string" ? operation.avID : operation.id))) {
+ return owner;
+ }
+ rememberEmbedSourceIDs();
+ return operations.length > 0 && operations.every(operation =>
+ embedSourceIDs.has(operation.id) || operation.action === "insert" &&
+ [operation.parentID, operation.previousID, operation.nextID].some(id => embedSourceIDs.has(id))) ?
+ owner : undefined;
+ },
+ lute: owner.lute, lockedOptions: {toolbar, hint},
},
afterSetContent: (protyle, element) => {
+ protyle.block.rootID = owner.block.rootID;
+ protyle.block.parentID = node.id;
+ protyle.path = owner.path;
+ setCustomBlockRootReady(element, true);
+ processRender(element);
highlightRender(element);
- mathRender(element);
+ blockRender(protyle, element, undefined, options.onResize);
+ void avRender(element, owner);
protyle.undo.clear();
},
onChange: () => {
@@ -109,7 +174,7 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
const overlayRoot = host.closest(".list-mindmap") || document.body;
// 菜单使用未缩放的容器定位,同时保持在原生全屏元素内可见。
overlays.forEach(element => overlayRoot.appendChild(element));
- let lastHTML = cleanListMindmapHTML(fragment.getBlockHTML());
+ let lastHTML = comparableContent(fragment.getBlockHTML());
const recover = () => {
if (recoveryShown) {
return;
@@ -147,22 +212,23 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
return false;
}
const html = cleanListMindmapHTML(fragment.getBlockHTML());
- if (html === lastHTML) {
+ const version = comparableContent(html);
+ if (version === lastHTML) {
changed = false;
return true;
}
- if (!options.canEdit() || !node.element.isConnected || nodeContent(node) !== source) {
+ if (!options.canEdit() || !node.element.isConnected || comparableContent(nodeContent(node)) !== source) {
recover();
return false;
}
saving = true;
try {
- if (!await options.onSave(html)) {
+ if (!await options.onSave(retainIndependentBlocks(html, node))) {
return false;
}
- source = nodeContent(node);
- lastHTML = html;
- changed = cleanListMindmapHTML(fragment.getBlockHTML()) !== html;
+ source = comparableContent(nodeContent(node));
+ lastHTML = version;
+ changed = comparableContent(fragment.getBlockHTML()) !== version;
if (changed && !finishSession) {
saveTimer = window.setTimeout((): void => { void commit(); }, 350);
}
@@ -175,19 +241,19 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
if (finished) {
return;
}
- const html = cleanListMindmapHTML(fragment.getBlockHTML());
+ const html = comparableContent(fragment.getBlockHTML());
if (html !== lastHTML) {
recover();
}
finished = true;
clearTimeout(saveTimer);
events.abort();
+ embedSourceObserver.disconnect();
observer.disconnect();
fragment.destroy();
overlays.forEach(element => element.remove());
host.classList.remove("list-mindmap__editor");
host.style.minWidth = originalMinWidth;
- delete host.dataset.protyleLiteRender;
options.onFinish();
};
const destroy = () => {
@@ -223,17 +289,35 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
if (!await commit(true)) {
return false;
}
- } while (cleanListMindmapHTML(fragment.getBlockHTML()) !== lastHTML);
+ } while (comparableContent(fragment.getBlockHTML()) !== lastHTML);
cleanup();
return true;
};
const undo = async (redo: boolean) => {
+ const selection = getSelection();
+ const anchor = selection.anchorNode instanceof Element ? selection.anchorNode : selection.anchorNode?.parentElement;
+ if (anchor && host.contains(anchor) && anchor.closest(".protyle-wysiwyg__embed, .av")) {
+ if (redo) {
+ owner.undo.redo(owner);
+ } else {
+ owner.undo.undo(owner);
+ }
+ return;
+ }
if (await finish()) {
options.onUndo(redo);
}
};
setMobileToolbarUndo(fragment.protyle, owner, undo);
const signal = events.signal;
+ host.addEventListener("beforeinput", event => {
+ const anchor = getSelection()?.anchorNode;
+ const element = anchor instanceof Element ? anchor : anchor?.parentElement;
+ const block = element?.closest<HTMLElement>(".protyle-wysiwyg__embed [data-node-id]");
+ if (block?.dataset.nodeId && (event.inputType.startsWith("insert") || event.inputType.startsWith("delete"))) {
+ fragment.protyle.wysiwyg.lastHTMLs[block.dataset.nodeId] = block.outerHTML;
+ }
+ }, {capture: true, signal});
bindLiteCodeActions(host, fragment.protyle, {
signal,
canEdit: () => !finished && !closing && options.canEdit(),
@@ -282,9 +366,21 @@ export const openListMindmapEditor = (options: ListMindmapEditorOptions) => {
finish();
}
}), {capture: true, signal});
- const belongs = (target: Node) => host.contains(target) || fragment.hintElement.contains(target) ||
- fragment.protyle.toolbar.element.contains(target) || fragment.protyle.toolbar.subElement.contains(target) ||
- !!(target instanceof Element && target.closest("#keyboardToolbar, #commonMenu, .b3-dialog"));
+ const belongs = (target: Node) => {
+ if (host.contains(target) || fragment.hintElement.contains(target) ||
+ fragment.protyle.toolbar.element.contains(target) || fragment.protyle.toolbar.subElement.contains(target)) {
+ return true;
+ }
+ if (!(target instanceof Element)) {
+ return false;
+ }
+ const avOverlay = target.closest<HTMLElement>(".av__panel, .av__mask");
+ if (avOverlay?.dataset.avBlockId && host.querySelector(
+ `[data-type="NodeAttributeView"][data-node-id="${avOverlay.dataset.avBlockId}"]`)) {
+ return true;
+ }
+ return !!target.closest("#keyboardToolbar, #commonMenu, .b3-dialog");
+ };
document.addEventListener("pointerdown", event => {
if (!belongs(event.target as Node)) {
finish();
diff --git a/app/src/protyle/render/listMindmap/model.test.ts b/app/src/protyle/render/listMindmap/model.test.ts
index fe4fd949d9..06b2798d0e 100644
--- a/app/src/protyle/render/listMindmap/model.test.ts
+++ b/app/src/protyle/render/listMindmap/model.test.ts
@@ -155,7 +155,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
const inputTransactions: {forward: IOperation[], backward: IOperation[]}[] = [];
const inputAPI = new Function("Constants", "dayjs", "transaction", "hideElements", "mathRender", "highlightRender",
"normalizeInlineFontFamilyStyle", "getBlockquoteContext", "revealTabsForTarget",
- "updateTransaction", "isMac", "isOnlyMeta", "isNotCtrl", inputSource +
+ "updateTransaction", "isMac", "isOnlyMeta", "isNotCtrl", "isMobile", inputSource +
"; return {input, configureListItemInput, listShortcut, ListHint};")(
{ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing", KEYCODELIST: {76: "L", 74: "J"}}, () => ({format: () => "20260922120000"}),
(_protyle: IProtyle, forward: IOperation[], backward: IOperation[]) => inputTransactions.push({forward, backward}),
@@ -164,7 +164,7 @@ const browserCases = async (sourceCode: string, css: string, taskSource: string,
inputTransactions.push({forward: [{action: "update", id: block.dataset.nodeId, data: block.outerHTML}],
backward: [{action: "update", id: block.dataset.nodeId, data: before}]});
}, () => false, (event: KeyboardEvent) => event.ctrlKey && !event.metaKey,
- (event: KeyboardEvent) => !event.ctrlKey && !event.metaKey);
+ (event: KeyboardEvent) => !event.ctrlKey && !event.metaKey, () => false);
window.siyuan = {config: {editor: {markdown: {}}, keymap: {editor: {insert: {
list: {custom: "⌘J"}, "ordered-list": {custom: "⇧⌘J"}, check: {custom: "⌘L"}, quote: {custom: ""},
}}}}, storage: {}} as unknown as typeof window.siyuan;
diff --git a/app/src/protyle/render/listMindmap/preview.test.ts b/app/src/protyle/render/listMindmap/preview.test.ts
index 8cb3e81830..ce61297062 100644
--- a/app/src/protyle/render/listMindmap/preview.test.ts
+++ b/app/src/protyle/render/listMindmap/preview.test.ts
@@ -22,7 +22,6 @@ const extract = (file: string, names: string[]) => {
const cases = async (source: string) => {
const check = require("node:assert/strict");
const requests: {url: string, data: Record<string, string>}[] = [];
- const messages: string[] = [];
const chartRefreshes: Element[] = [];
const dependencies = {
fetchPost: (url: string, data: Record<string, string>) => requests.push({url, data}),
@@ -30,15 +29,12 @@ const cases = async (source: string) => {
genRenderFrame: () => {},
isEncryptedBox: () => false,
hasClosestByClassName: (element: HTMLElement, name: string) => element.closest(`.${name}`),
- showMessage: (message: string) => messages.push(message),
- cleanListMindmapHTML: (html: string) => html,
chartRender: (element: Element) => chartRefreshes.push(element),
- mountProtyleLiteFragment: () => check.fail("Unsupported content was passed to the editor sanitizer"),
};
const api = new Function(...Object.keys(dependencies), source + "; return {customBlockRender, " +
"registerCustomBlockRoot, setCustomBlockRootReady, unregisterCustomBlockRoot, activateCustomBlockPlugin, " +
"deactivateCustomBlockPlugin, htmlRender, blockRender, avRender, getAVElements, getCell, getTableNode, " +
- "TablePreviewControl, refreshChartTheme, getAVRichTextUnsupportedPasteBlocks, openListMindmapEditor};")(...Object.values(dependencies));
+ "TablePreviewControl, refreshChartTheme, getAVRichTextUnsupportedPasteBlocks};")(...Object.values(dependencies));
const root = document.createElement("div");
root.className = "protyle-wysiwyg";
document.body.append(root);
@@ -152,20 +148,16 @@ const cases = async (source: string) => {
controls.renderPinnedTableFrames();
check.equal(controls.pinnedTableActions.size, 0);
- // 复杂块在编辑入口处保留原文,不进入会丢弃不支持内容的富文本净化流程。
+ // 脑图预览保留复杂块,数据库和表格单元格仍按原有规则拒绝这些块。
const types = ["NodeTable", "NodeAttributeView", "NodeBlockQueryEmbed", "NodeCustomBlock", "NodeHTMLBlock",
"NodeIFrame", "NodeWidget", "NodeVideo", "NodeAudio", "NodeCallout", "NodeSuperBlock", "NodeTabs"];
for (const type of types) {
const item = block("NodeListItem");
item.innerHTML = `<div data-node-id="special" data-type="${type}" data-content="raw source">Keep content</div>`;
- const host = document.createElement("div");
const original = item.outerHTML;
check.ok(api.getAVRichTextUnsupportedPasteBlocks(item.innerHTML, true).length, type);
- check.equal(api.openListMindmapEditor({node: {element: item}, host, canEdit: () => true}), undefined);
check.equal(item.outerHTML, original, type);
- check.equal(host.childElementCount, 0);
}
- check.equal(messages.length, types.length);
check.deepEqual(api.getAVRichTextUnsupportedPasteBlocks('<div data-type="NodeParagraph"><img src="asset.png"></div>', true), []);
for (const type of ["NodeParagraph", "NodeBlockquote", "NodeMathBlock"]) {
check.deepEqual(api.getAVRichTextUnsupportedPasteBlocks(`<div data-type="${type}">Content</div>`, true), []);
@@ -196,8 +188,7 @@ test("special block previews cannot acquire document writes or lose unsupported
extract("../../util/tableControl.ts", ["getCell", "getTableNode"]) +
compile(`class TablePreviewControl {${methods.map(method => method.getText(tableSource)).join("\n")}}`) +
extract("../av/richText.ts", ["ALLOWED_BLOCK_TYPES", "isSupportedAVRichTextBlock", "getAVRichTextUnsupportedPasteBlocks"]) +
- extract("../av/richTextValue.ts", ["EXECUTABLE_CODE_LANGUAGES", "isAVRichTextExecutableCodeLanguage"]) +
- extract("editor.ts", ["nodeContent", "openListMindmapEditor"]);
+ extract("../av/richTextValue.ts", ["EXECUTABLE_CODE_LANGUAGES", "isAVRichTextExecutableCodeLanguage"]);
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-mindmap-preview-"));
const script = path.join(temporary, "run.cjs");
writeFileSync(script, `const {app, BrowserWindow} = require("electron");
diff --git a/app/src/protyle/runtimeCapabilities.ts b/app/src/protyle/runtimeCapabilities.ts
index f7ef828ddf..b8312131bf 100644
--- a/app/src/protyle/runtimeCapabilities.ts
+++ b/app/src/protyle/runtimeCapabilities.ts
@@ -9,6 +9,7 @@ export interface ProtyleRuntimeCapabilities {
customBlockRender?: boolean;
// 片段内容作为列表项正文编辑,首段沿用列表输入规则。
listItemFragment?: boolean;
+ getTransactionOwner?: (operations: IOperation[]) => IProtyle | undefined;
sanitizeBlockDOM?: (blockDOM: string) => string;
getUnsupportedPasteBlocks?: (blockDOM: string) => string[];
richHTMLPaste?: boolean;
@@ -42,6 +43,9 @@ export const isProtyleCustomBlockRenderEnabled = (protyle: IProtyle) =>
export const isProtyleListItemFragment = (protyle: IProtyle) =>
protyleRuntimeCapabilities.get(protyle)?.listItemFragment === true;
+export const getProtyleTransactionOwner = (protyle: IProtyle, operations: IOperation[]) =>
+ protyleRuntimeCapabilities.get(protyle)?.getTransactionOwner?.(operations);
+
export const isProtyleListItemFirstParagraph = (protyle: IProtyle, blockElement: HTMLElement) =>
isProtyleListItemFragment(protyle) && blockElement === protyle.wysiwyg.element.firstElementChild &&
blockElement.dataset.type === "NodeParagraph";
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 986261aa92..a356ad534b 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -76,6 +76,7 @@ import {
import {isEmptyParagraph} from "./emptyTextBlock";
import {cleanTableCellRichHTML, retainTableCellRichMetadata} from "../util/tableCellRich";
import {cleanListMindmapHTML, convertListMindmapToList} from "../render/listMindmap/model";
+import {getProtyleTransactionOwner} from "../runtimeCapabilities";
import {completeTabsListSource, convertTabsList, isTabsListConversion} from "./tabsList";
import {waitForPendingTransactions} from "../util/transactionQueue";
import {
@@ -2359,6 +2360,11 @@ export const transaction = (protyle: IProtyle, doOperations: IOperation[], undoO
templateDocTreePlanID?: string,
trackedRangeInsertion?: ITrackedRangeInsertion,
}) => {
+ const owner = protyle?.lite && getProtyleTransactionOwner(protyle, doOperations);
+ if (owner && !owner.lite && owner !== protyle) {
+ transaction(owner, doOperations, undoOperations, options);
+ return;
+ }
if (protyle) {
const prepared = prepareViewFoldTransaction(protyle, doOperations, undoOperations);
doOperations = prepared.doOperations;