An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support configurable embed block toolbars https://github.com/siyuan-note/siyuan/issues/19794
Daniela9d2c5644322
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scssindex 420ef7e280..e2f67f3ddb 100644--- a/app/src/assets/scss/protyle/_wysiwyg.scss+++ b/app/src/assets/scss/protyle/_wysiwyg.scss@@ -556,6 +556,11 @@ $block-rtl-selector: ".protyle-block--rtl" !default;max-width: 100%;padding: 2px 4px;+ & > .protyle-icons[data-entry-hidden="true"],+ & > .protyle-wysiwyg__embed > .protyle-icons[data-entry-hidden="true"] {+ display: none;+ }+/* 选中块的高亮覆盖 border */&.protyle-wysiwyg--select::after,&.protyle-wysiwyg--select-mode::after,diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex b5473df696..dc4e12c3ae 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -103,7 +103,7 @@ test("document tree duplication follows single-document duplication in the confitest("embedded heading levels follow display modes and expose all levels in Simple", () => {const path = "gutter.single.blockEmbed";assert.deepEqual(getEntryCatalogChildren(path).map(entry => entry.key), [- "refresh", "update", "separator_breadcrumb", "embedBlockBreadcrumb", "embedBlockBreadcrumbParentPath",+ "refresh", "update", "refPopover", "separator_breadcrumb", "embedBlockBreadcrumb", "embedBlockBreadcrumbParentPath","headingEmbedMode", "embedHeadingLevel",]);const levelPath = `${path}.embedHeadingLevel`;@@ -127,6 +127,20 @@ test("embedded heading levels follow display modes and expose all levels in Simp});});+test("embed toolbars and popover menus remain visible by default and have independent configuration", () => {+ const toolbar = getEntryCatalogNode("editor.blockEmbed.toolbar");+ assert.equal(toolbar.type, "entry");+ assert.equal(toolbar.simple, true);+ assert.equal(toolbar.sortable, false);+ assert.equal(getEntryParentPath("editor.blockEmbed.toolbar"), "editor.blockEmbed");+ assert.equal(getEntryCatalogDefaultVisibility("editor.blockEmbed.toolbar"), true);+ assert.equal(getEntryCatalogCustomDefaultVisibility("editor.blockEmbed.toolbar"), true);+ const popover = getEntryCatalogNode("gutter.single.blockEmbed.refPopover");+ assert.equal(popover.type, "entry");+ assert.equal(popover.simple, true);+ assert.equal(getEntryParentPath("gutter.single.blockEmbed.refPopover"), "gutter.single.blockEmbed");+});+const slashMenuBuiltinOrder = ["template","widget",diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 2b7da4e2ee..213262d565 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -450,6 +450,7 @@ const gutterSingle = () => [node("blockEmbed", lang("blockEmbed"), true, [node("refresh", lang("refresh")),node("update", lang("update")),+ node("refPopover", lang("refPopover")),separator("separator_breadcrumb"),...["embedBlockBreadcrumb", "embedBlockBreadcrumbParentPath"].map(key => node(key, lang(key), true, [node("enable", lang("enable")),@@ -902,6 +903,12 @@ export const entryCatalog: IEntryCatalogSection[] = [],},toolbarCatalogSection,+ {+ key: "editor.blockEmbed",+ label: location(lang("editor"), lang("blockEmbed")),+ sortable: false,+ children: [node("toolbar", lang("entryToolbar"), true, undefined, false)],+ },{key: "editor.image",label: location(lang("editor"), lang("image")),diff --git a/app/src/config/entryVisibility/mobileSlash.test.ts b/app/src/config/entryVisibility/mobileSlash.test.tsindex b705ca0881..3bfa0bb488 100644--- a/app/src/config/entryVisibility/mobileSlash.test.ts+++ b/app/src/config/entryVisibility/mobileSlash.test.ts@@ -50,6 +50,16 @@ test("slash visibility shares profile settings and only platform defaults differassert.equal(api.isEntryVisible("editor.image.ocrText"), visible);}delete custom.entries["editor.image.ocrText"];+ for (const active of ["simple", "full", "custom"]) {+ config.active = active;+ assert.equal(api.isEntryVisible("editor.blockEmbed.toolbar"), true);+ }+ config.active = "custom";+ for (const visible of [false, true]) {+ custom.entries["editor.blockEmbed.toolbar"] = visible;+ assert.equal(api.isEntryVisible("editor.blockEmbed.toolbar"), visible);+ }+ delete custom.entries["editor.blockEmbed.toolbar"];assert.equal(catalog.getEntryCatalogDefaultVisibility(root), !mobile);assert.equal(catalog.getEntryCatalogCustomDefaultVisibility(root), !mobile);for (const active of ["simple", "full", "custom"]) {diff --git a/app/src/config/entryVisibility/mobileUi.test.ts b/app/src/config/entryVisibility/mobileUi.test.tsindex 663b920f5a..193322d7e1 100644--- a/app/src/config/entryVisibility/mobileUi.test.ts+++ b/app/src/config/entryVisibility/mobileUi.test.ts@@ -182,7 +182,21 @@ const browserCases = async (sources: Record<string, string>, languages: Record<sselect.dispatchEvent(new Event("change", {bubbles: true}));check(view.querySelector("[data-entry-path='editor.image.ocrText']"), "Mobile exposes image OCR visibility");check(view.querySelector("[data-entry-path='editor.image.copyAsPNG']"), "Mobile exposes image copy visibility");- check(select.options.length === 3, "Mobile must offer toolbar, slash, and image categories");+ check(select.options.length === 4, "Mobile must offer toolbar, embed, slash, and image categories");+ select.value = "editor.blockEmbed";+ select.dispatchEvent(new Event("change", {bubbles: true}));+ const embedToolbar = view.querySelector<HTMLInputElement>("[data-entry-path='editor.blockEmbed.toolbar']");+ check(embedToolbar?.checked, "Mobile exposes the default-visible embed toolbar");+ const saved = JSON.stringify(config());+ const readonly = embedToolbar.hasAttribute("data-entry-readonly");+ embedToolbar.click();+ check(view.querySelector<HTMLInputElement>("[data-entry-path='editor.blockEmbed.toolbar']").checked === readonly,+ "Custom profiles can hide embed toolbars while built-in profiles remain read-only");+ check(JSON.stringify(config()) === saved,+ "Draft toolbar changes do not mutate saved profiles");+ if (!readonly) {+ view.querySelector<HTMLInputElement>("[data-entry-path='editor.blockEmbed.toolbar']").click();+ }select.value = "editor.slash";select.dispatchEvent(new Event("change", {bubbles: true}));};diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.tsindex 3ffe857acc..395fd6dbc2 100644--- a/app/src/config/entryVisibility/order.test.ts+++ b/app/src/config/entryVisibility/order.test.ts@@ -182,7 +182,7 @@ test("missing table and image actions merge into saved orders while preserving p{path: "inline.text.more", added: ["cancelMerged"]},{path: "inline.image", added: ["openBy"]},{path: "gutter.single.copy", added: ["copyMirror"]},- {path: "gutter.single.blockEmbed", added: ["embedHeadingLevel", "embedBlockBreadcrumbParentPath"]},+ {path: "gutter.single.blockEmbed", added: ["refPopover", "embedHeadingLevel", "embedBlockBreadcrumbParentPath"]},{path: "gutter.single.blockEmbed.embedBlockBreadcrumb", added: ["enable", "disable", "default"]},{path: "gutter.single.blockEmbed.embedBlockBreadcrumbParentPath", added: ["enable", "disable", "default"]},].forEach(({path, added}) => {diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.tsindex 9c87ff9592..b2f55654c8 100644--- a/app/src/config/entryVisibility/runtime.ts+++ b/app/src/config/entryVisibility/runtime.ts@@ -72,7 +72,8 @@ export const isEntryVisible = (path: string): boolean => {/// #if MOBILEif (!path.startsWith(`${TOOLBAR_ENTRY_ROOT_PATH}.`) &&path !== SLASH_MENU_ROOT_PATH && !path.startsWith(`${SLASH_MENU_ROOT_PATH}.`) &&- path !== "editor.image" && !path.startsWith("editor.image.")) {+ path !== "editor.image" && !path.startsWith("editor.image.") &&+ path !== "editor.blockEmbed" && !path.startsWith("editor.blockEmbed.")) {return true;}/// #endifdiff --git a/app/src/config/entryVisibility/ui.test.ts b/app/src/config/entryVisibility/ui.test.tsindex 8533a6eff2..67f056af0e 100644--- a/app/src/config/entryVisibility/ui.test.ts+++ b/app/src/config/entryVisibility/ui.test.ts@@ -36,7 +36,7 @@ test("entry settings show exit only on native tablets without changing the persiassert.equal(hasExit(exports.catalog()), true);mobile = true;const catalog = exports.catalog();- assert.deepEqual(Array.from(catalog, item => item.key), [TOOLBAR_ENTRY_ROOT_PATH, "editor.image", "editor.slash"]);+ assert.deepEqual(Array.from(catalog, item => item.key), [TOOLBAR_ENTRY_ROOT_PATH, "editor.blockEmbed", "editor.image", "editor.slash"]);assert.equal(catalog.find(item => item.key === "editor.slash"), entryCatalog.find(item => item.key === "editor.slash"));assert.deepEqual(Array.from(catalog[0].children, item => item.key), MOBILE_TOOLBAR_CONTEXT_KEYS);for (const name of ["undo", "indent", "heading1", "table", "template"]) {diff --git a/app/src/config/entryVisibility/ui.ts b/app/src/config/entryVisibility/ui.tsindex 1f384b8f96..eed3575ed7 100644--- a/app/src/config/entryVisibility/ui.ts+++ b/app/src/config/entryVisibility/ui.ts@@ -68,7 +68,8 @@ import {} from "./dockOrder";const getVisibleEntryCatalog = () => isMobile() ? entryCatalog.filter(item =>- item.key === TOOLBAR_ENTRY_ROOT_PATH || item.key === "editor.slash" || item.key === "editor.image")+ item.key === TOOLBAR_ENTRY_ROOT_PATH || item.key === "editor.slash" || item.key === "editor.image" ||+ item.key === "editor.blockEmbed").map(item => item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, sortable: false,children: item.children.filter(child => MOBILE_TOOLBAR_CONTEXT_KEYS.includes(child.key))} : item) : entryCatalog.map(item =>item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, children: item.children.filter(child => !child.key.startsWith("mobile-"))} :diff --git a/app/src/protyle/gutter/embedOpenMenu.test.ts b/app/src/protyle/gutter/embedOpenMenu.test.tsnew file mode 100644index 0000000000..5698f45d34--- /dev/null+++ b/app/src/protyle/gutter/embedOpenMenu.test.ts@@ -0,0 +1,91 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {createSourceFile, isIfStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";+import {escapeHtml} from "../../util/escape";++const {parse} = require("ifdef-loader/preprocessor");++for (const mobile of [false, true]) {+ test(`embed popover menus preserve result targets in the ${mobile ? "mobile" : "desktop"} build`, () => {+ const panels: Array<{targetElement: HTMLElement; refDefs: Array<{refID: string}>}> = [];+ const opens: unknown[][] = [];+ const constants = {CB_GET_HL: 1, CB_GET_CONTEXT: 2, CB_GET_ROOTSCROLL: 3};+ const owner = {app: {}} as IProtyle;+ const api = {} as typeof import("./embedOpenMenu");+ const dependencies = {+ Constants: constants, escapeHtml,+ BlockPanel: class {constructor(options: typeof panels[number]) { panels.push(options); }},+ openMobileFileById: (...args: unknown[]) => opens.push(args),+ };+ const window = {siyuan: {languages: {refPopover: "Open in popover"}, blockPanels: [] as unknown[]}};+ runInNewContext(transpileModule(parse(readFileSync("src/protyle/gutter/embedOpenMenu.ts", "utf8"),+ {MOBILE: mobile, BROWSER: true}, false, true), {compilerOptions: {module: ModuleKind.CommonJS}}).outputText,+ {exports: api, window, require: () => dependencies});+ const result = (id: string, text: string) => ({dataset: {id}, querySelector: () => ({textContent: text})}) as unknown as HTMLElement;+ const first = result("first", "<script> & first");+ const second = result("second", "Second");+ let results: HTMLElement[] = [];+ const embed = {querySelectorAll: () => results} as unknown as Element;+ assert.equal(api.embedOpenMenu(owner, embed).disabled, true);+ api.openEmbedBlock(owner, first, "");+ assert.equal(opens.length + panels.length, 0);+ results = [first];+ const single = api.embedOpenMenu(owner, embed);+ assert.equal(single.id, "refPopover");+ assert.equal(single.disabled, false);+ assert.equal(single.submenu, undefined);+ single.click(undefined, undefined);+ results = [first, second];+ const menu = api.embedOpenMenu(owner, embed);+ assert.equal(menu.click, undefined);+ assert.deepEqual(Array.from(menu.submenu, item => item.id), ["first", "second"]);+ assert.equal(menu.submenu[0].label, "<script> & first");+ menu.submenu[1].click(undefined, undefined);+ if (mobile) {+ assert.equal(panels.length, 0);+ assert.deepEqual(Array.from(opens, args => [args[0], args[1], Array.from(args[2] as number[]), args[3]]), [+ [owner.app, "first", [1, 2, 3], "start"], [owner.app, "second", [1, 2, 3], "start"],+ ]);+ } else {+ assert.equal(opens.length, 0);+ assert.deepEqual(panels.map(panel => panel.targetElement), [first, second]);+ assert.deepEqual(panels.map(panel => panel.refDefs[0].refID), ["first", "second"]);+ }+ });+}++test("the shared block menu exposes popovers in editable and read-only embeds", () => {+ const source = createSourceFile("index.ts", readFileSync("src/protyle/gutter/index.ts", "utf8"), ScriptTarget.Latest, true);+ let branch = "";+ const visit = (node: import("typescript").Node) => {+ if (isIfStatement(node) && node.expression.getText(source) === 'type === "NodeBlockQueryEmbed"') {+ branch = node.thenStatement.getText(source);+ }+ node.forEachChild(visit);+ };+ visit(source);+ assert.ok(branch);+ const owner = {disabled: false};+ const embed = {getAttribute: () => ""};+ const items: IMenu[] = [];+ const window = {siyuan: {languages: {}, menus: {menu: {append: (item: IMenu) => items.push(item)}}}};+ const dependencies = {window,+ MenuItem: class {public element: IMenu; constructor(item: IMenu) { this.element = item; }},+ embedOpenMenu: () => ({id: "refPopover"}), embedBreadcrumbMenu: (): IMenu[] => [],+ isHeadingEmbed: () => false, getEmbedHeadingLevel: () => 0,+ };+ const render = new Function("protyle", "nodeElement", ...Object.keys(dependencies),+ transpileModule(branch, {compilerOptions: {target: ScriptTarget.ES2021}}).outputText);+ for (const readonly of [false, true]) {+ owner.disabled = readonly;+ items.length = 0;+ render(owner, embed, ...Object.values(dependencies));+ const children = items.find(item => item.id === "blockEmbed").submenu;+ assert.ok(children.some(item => item.id === "refPopover"));+ assert.equal(children.some(item => item.id === "update"), !readonly);+ assert.deepEqual(children.slice(0, readonly ? 1 : 3).map(item => item.id),+ readonly ? ["refPopover"] : ["refresh", "update", "refPopover"]);+ }+});diff --git a/app/src/protyle/gutter/embedOpenMenu.ts b/app/src/protyle/gutter/embedOpenMenu.tsnew file mode 100644index 0000000000..0b411187fd--- /dev/null+++ b/app/src/protyle/gutter/embedOpenMenu.ts@@ -0,0 +1,49 @@+import {Constants} from "../../constants";+import {escapeHtml} from "../../util/escape";+/// #if MOBILE+import {openMobileFileById} from "../../mobile/editor";+/// #endif+/// #if !MOBILE+import {BlockPanel} from "../../block/Panel";+/// #endif++export const openEmbedBlock = (protyle: IProtyle, target: HTMLElement, id: string) => {+ if (!id) {+ return;+ }+ /// #if MOBILE+ openMobileFileById(protyle.app, id, [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL], "start");+ /// #else+ window.siyuan.blockPanels.push(new BlockPanel({+ app: protyle.app,+ isBacklink: false,+ targetElement: target,+ refDefs: [{refID: id}],+ }));+ /// #endif+};++export const embedOpenMenu = (protyle: IProtyle, embed: Element): IMenu => {+ const results = Array.from(embed.querySelectorAll<HTMLElement>(":scope > .protyle-wysiwyg__embed[data-id]"))+ .filter(result => result.dataset.id);+ const openResult = (result: HTMLElement): IMenu => ({+ id: result.dataset.id,+ icon: "iconPictureInPicture",+ label: escapeHtml(result.querySelector(`[data-node-id="${result.dataset.id}"]`)?.textContent.trim().slice(0, 80) ||+ result.dataset.id),+ click: () => openEmbedBlock(protyle, result, result.dataset.id),+ });+ return {+ id: "refPopover",+ icon: "iconPictureInPicture",+ label: window.siyuan.languages.refPopover,+ disabled: results.length === 0,+ ...(results.length > 1 ? {submenu: results.map(openResult)} : {+ click: () => {+ if (results[0]) {+ openEmbedBlock(protyle, results[0], results[0].dataset.id);+ }+ },+ }),+ };+};diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.tsindex 3e48701159..2e256f7715 100644--- a/app/src/protyle/gutter/index.ts+++ b/app/src/protyle/gutter/index.ts@@ -47,6 +47,7 @@ import {isGutterTouchDragging, markGutterForFoldRestore} from "../ui/gutterVisibimport {highlightRender} from "../render/highlightRender";import {blockRender} from "../render/blockRender";import {embedBreadcrumbMenu} from "./embedBreadcrumbMenu";+import {embedOpenMenu} from "./embedOpenMenu";import {toggleListMindmap} from "../render/listMindmap";import {getBlockHeightTarget, setBlockHeight} from "./height";import {orderGutterTurnIntoItems} from "./turnIntoMenu";@@ -2499,14 +2500,14 @@ export class Gutter {protyle.toolbar.showRender(protyle, nodeElement);}}).element);- } else if (type === "NodeBlockQueryEmbed" && !protyle.disabled) {+ } else if (type === "NodeBlockQueryEmbed") {window.siyuan.menus.menu.append(new MenuItem({id: "separator_blockEmbed", type: "separator"}).element);window.siyuan.menus.menu.append(new MenuItem({id: "blockEmbed",type: "submenu",icon: "iconSQL",label: window.siyuan.languages.blockEmbed,- submenu: [{+ submenu: protyle.disabled ? [embedOpenMenu(protyle, nodeElement)] : [{id: "refresh",icon: "iconRefresh",label: `${window.siyuan.languages.refresh} SQL`,@@ -2521,7 +2522,7 @@ export class Gutter {click() {protyle.toolbar.showRender(protyle, nodeElement);}- }, {+ }, embedOpenMenu(protyle, nodeElement), {id: "separator_breadcrumb",type: "separator"}, ...embedBreadcrumbMenu(protyle, nodeElement), {diff --git a/app/src/protyle/render/blockRender.ts b/app/src/protyle/render/blockRender.tsindex 32bb594a93..a9e21b3475 100644--- a/app/src/protyle/render/blockRender.ts+++ b/app/src/protyle/render/blockRender.ts@@ -14,6 +14,7 @@ import {isDirectHeadingEmbed} from "./embedHeading";import {isFoldedRenderContent} from "./foldedContent";import {getEmbedBreadcrumbPaths, resolveEmbedBreadcrumbPreference} from "./embedBreadcrumb";import {Constants} from "../../constants";+import {renderEmbedToolbarVisibility} from "../wysiwyg/embedToolbarVisibility";/*** 渲染嵌入块@@ -151,6 +152,7 @@ ${popover}${breadcrumbHTML}${blocksItem.block.content}}processRender(item);+ renderEmbedToolbarVisibility(item);highlightRender(item);avRender(item, protyle);if (protyle.disabled) {diff --git a/app/src/protyle/render/embedBreadcrumb.test.ts b/app/src/protyle/render/embedBreadcrumb.test.tsindex 41407a600d..cea01cc4b2 100644--- a/app/src/protyle/render/embedBreadcrumb.test.ts+++ b/app/src/protyle/render/embedBreadcrumb.test.ts@@ -52,7 +52,7 @@ test("SQL and JS embed rendering use global preferences and per-result document...constants, getEmbedBreadcrumbPaths, resolveEmbedBreadcrumbPreference,genBreadcrumb: (items: IBreadcrumb[]) => { breadcrumbs.push(items.map(item => item.name)); return "breadcrumbs"; },normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,- improveBreadcrumbAppearance: noop, processRender: noop, highlightRender: noop, avRender: noop,+ improveBreadcrumbAppearance: noop, processRender: noop, renderEmbedToolbarVisibility: noop, highlightRender: noop, avRender: noop,hasClosestByAttribute: () => false, isDirectHeadingEmbed: () => false, isFoldedRenderContent: () => false,isEncryptedBox: () => false, genRenderFrame: noop, getHostCapabilities: () => ({}),fetchPost: (_url: string, data: typeof requests[number], callback: (data: unknown) => void) => {diff --git a/app/src/protyle/render/util.ts b/app/src/protyle/render/util.tsindex e6ac96bc96..22d5ebb31e 100644--- a/app/src/protyle/render/util.ts+++ b/app/src/protyle/render/util.ts@@ -1,6 +1,7 @@import {isInEmbedBlock} from "../util/hasClosest";import {Constants} from "../../constants";import {addStyle} from "../util/addStyle";+import {renderEmbedToolbarVisibility} from "../wysiwyg/embedToolbarVisibility";export const genIconHTML = (element?: false | HTMLElement, actions = ["edit", "more"]) => {let enable = true;@@ -39,6 +40,7 @@ export const genRenderFrame = (renderElement: Element) => {<span aria-label="${window.siyuan.languages.refPopover}" data-position="4north" data-action="openFloat" class="ariaLabel protyle-icon"><svg><use xlink:href="#iconPictureInPicture"></use></svg></span><span aria-label="${window.siyuan.languages.more}" data-position="4north" class="ariaLabel protyle-icon protyle-action__menu protyle-icon--last"><svg><use xlink:href="#iconMore"></use></svg></span></div><div class="protyle-cursor">${Constants.ZWSP}</div>`);+ renderEmbedToolbarVisibility(renderElement);} else if (type === "NodeMathBlock" || renderElement.getAttribute("data-subtype") === "math") {renderElement.firstElementChild.innerHTML = `<span></span><span class="protyle-cursor">${Constants.ZWSP}</span>`;}diff --git a/app/src/protyle/wysiwyg/embedToolbarVisibility.test.ts b/app/src/protyle/wysiwyg/embedToolbarVisibility.test.tsnew file mode 100644index 0000000000..145daee8c9--- /dev/null+++ b/app/src/protyle/wysiwyg/embedToolbarVisibility.test.ts@@ -0,0 +1,160 @@+import * as assert from "node:assert/strict";+import {execFile} from "node:child_process";+import {mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import * as path from "node:path";+import {test} from "node:test";+import {promisify} from "node:util";+import {compileString} from "sass";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const browserCases = async (sources: Record<string, string>, css: string, luteSource: string) => {+ const check: typeof assert = require("node:assert/strict");+ new Function(luteSource)();+ const lute = Lute.New();+ lute.SetProtyleWYSIWYG(true);+ const style = document.createElement("style");+ style.textContent = css + ".protyle-wysiwyg {width: 600px; font-size: 16px;}";+ document.head.appendChild(style);+ const noop = () => {};+ let visible = true;+ const deps: Record<string, unknown> = {+ isEntryVisible: (key: string) => { check.equal(key, "editor.blockEmbed.toolbar"); return visible; },+ Constants: {ZWSP: "\u200b"},+ isInEmbedBlock: (element: Element) => element.parentElement.closest('[data-type="NodeBlockQueryEmbed"]'),+ getHostCapabilities: () => ({}), isFoldedRenderContent: () => false,+ isEncryptedBox: () => false, normalizeHTMLAssetIFrameBlockDOM: (html: string) => html,+ resolveEmbedBreadcrumbPreference: () => false, isDirectHeadingEmbed: () => false,+ improveBreadcrumbAppearance: noop, processRender: noop, highlightRender: noop, avRender: noop,+ hasClosestByAttribute: () => false,+ fetchPost: (_url: string, _data: unknown, callback: (data: unknown) => void) => callback({data: {blocks: [+ {block: {id: "20261026000000-aaaaaaa", content: '<div data-node-id="20261026000000-aaaaaaa" data-type="NodeParagraph"><div contenteditable="true">Editable first result</div></div>'}, blockPaths: []},+ {block: {id: "20261026000000-bbbbbbb", content: '<div data-node-id="20261026000000-bbbbbbb" data-type="NodeParagraph"><div contenteditable="true">Second result</div></div>'}, blockPaths: []},+ ]}}),+ };+ const load = (name: string) => {+ const exports = {};+ new Function("exports", "require", sources[name])(exports, () => deps);+ Object.assign(deps, exports);+ return exports;+ };+ const api = load("visibility") as typeof import("./embedToolbarVisibility");+ const frame = load("frame") as typeof import("../render/util");+ const render = load("render") as typeof import("../render/blockRender");+ window.siyuan = {languages: {}, config: {editor: {}, system: {safeMode: false}}} as unknown as typeof window.siyuan;+ const root = document.createElement("div");+ root.className = "protyle-wysiwyg";+ root.contentEditable = "true";+ document.body.appendChild(root);+ const create = () => {+ const embed = document.createElement("div");+ embed.className = "render-node";+ embed.dataset.nodeId = "20261026000000-ccccccc";+ embed.dataset.type = "NodeBlockQueryEmbed";+ embed.dataset.content = "select * from blocks";+ root.appendChild(embed);+ return embed;+ };+ const embed = create();+ const protyle = {block: {rootID: "host"}} as IProtyle;+ const dispose = api.bindEmbedToolbarVisibility(root);+ render.blockRender(protyle, embed);+ const icons = () => Array.from(embed.querySelectorAll<HTMLElement>(":scope > .protyle-icons, :scope > .protyle-wysiwyg__embed > .protyle-icons"));+ check.equal(icons().length, 2);+ check.ok(icons().every(icon => getComputedStyle(icon).display !== "none"));+ const before = lute.BlockDOM2Md(embed.outerHTML);+ visible = false;+ window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));+ check.ok(icons().every(icon => getComputedStyle(icon).display === "none"));+ check.equal(lute.BlockDOM2Md(embed.outerHTML), before, "visibility settings do not change persisted block content");+ const text = embed.querySelector<HTMLElement>('[contenteditable="true"]');+ const rect = text.getBoundingClientRect();+ check.ok(text.contains(document.elementFromPoint(rect.right - 8, rect.top + 8)), "hidden controls leave text clickable");+ // A query refresh and both SQL/JS async result paths must honor the current profile.+ for (const content of ["select * from blocks", "//!js\nreturn ['result'];"]) {+ embed.dataset.content = content;+ embed.removeAttribute("data-render");+ render.blockRender(protyle, embed);+ await new Promise(resolve => setTimeout(resolve, 0));+ check.equal(icons().length, 2);+ check.ok(icons().every(icon => getComputedStyle(icon).display === "none"));+ }+ const other = document.createElement("div");+ other.innerHTML = '<div class="protyle-icons">Image or code controls</div>';+ root.appendChild(other);+ const nested = create();+ embed.querySelector(".protyle-wysiwyg__embed").appendChild(nested);+ frame.genRenderFrame(nested);+ visible = true;+ window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));+ check.ok(icons().every(icon => getComputedStyle(icon).display !== "none"));+ check.equal(getComputedStyle(nested.querySelector(".protyle-icons")).display, "none", "nested query controls retain their original hidden state");+ check.equal(other.firstElementChild.hasAttribute("data-entry-hidden"), false);+ const newEmbed = create();+ visible = false;+ frame.genRenderFrame(newEmbed);+ check.equal(getComputedStyle(newEmbed.querySelector(".protyle-icons")).display, "none", "new embeds start hidden without another settings event");+ visible = true;+ window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));+ // Preserve the existing caret proximity behavior independently of the profile toggle.+ const toolbar = embed.querySelector<HTMLElement>(":scope > .protyle-icons");+ const editable = embed.querySelector<HTMLElement>('[contenteditable="true"]');+ editable.textContent = "Edit here";+ const toolbarRect = toolbar.getBoundingClientRect();+ editable.style.position = "relative";+ editable.style.left = (toolbarRect.left - editable.getBoundingClientRect().left) + "px";+ root.focus();+ check.ok(root.contains(document.activeElement), "the editor owns focus for caret proximity checks");+ const range = document.createRange();+ range.setStart(editable.firstChild, 0);+ range.collapse(true);+ getSelection().removeAllRanges();+ getSelection().addRange(range);+ document.dispatchEvent(new Event("selectionchange"));+ check.equal(toolbar.classList.contains("protyle-icons--editing-obscured"), true,+ `caret ${JSON.stringify(range.getBoundingClientRect())} must hide toolbar ${JSON.stringify(toolbar.getBoundingClientRect())}`);+ check.equal(getComputedStyle(toolbar).pointerEvents, "none");+ dispose();+ check.equal(toolbar.classList.contains("protyle-icons--editing-obscured"), false);+ visible = false;+ window.dispatchEvent(new CustomEvent("siyuan-entry-visibility"));+ check.equal(toolbar.hasAttribute("data-entry-hidden"), false, "destroyed editors release the profile listener");+ root.remove();+ return "Embed toolbar cases passed";+};++test("embed toolbar profiles update existing, refreshed, and new controls without changing content", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const sources = Object.fromEntries(Object.entries({visibility: "wysiwyg/embedToolbarVisibility", frame: "render/util", render: "render/blockRender"})+ .map(([key, file]) => [key, transpileModule(readFileSync(`src/protyle/${file}.ts`, "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText]));+ const css = compileString('@use "protyle/protyle"; @use "component/typography"; .fn__none {display: none !important;}',+ {loadPaths: ["src/assets/scss"], logger: {warn() {}, debug() {}}}).css;+ const code = "const __name = value => value; (" + browserCases.toString() + ")(" + [sources, css,+ readFileSync("stage/protyle/js/lute/lute.min.js", "utf8")].map(value => JSON.stringify(value)).join(",") + ")";+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-embed-toolbar-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app, BrowserWindow} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code)}));+ app.exit(0);+ } catch (error) {console.error(error); app.exit(1);}+});`, "utf8");+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const result = await promisify(execFile)(require("electron") as unknown as string, [script], {env, windowsHide: true, timeout: 25000});+ assert.match(result.stdout, /Embed toolbar cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) && path.basename(temporary).startsWith("siyuan-embed-toolbar-")) {+ rmSync(temporary, {recursive: true, force: true, maxRetries: 20, retryDelay: 100});+ }+ }+});diff --git a/app/src/protyle/wysiwyg/embedToolbarVisibility.ts b/app/src/protyle/wysiwyg/embedToolbarVisibility.tsindex a00dcfd8c8..333ca11d59 100644--- a/app/src/protyle/wysiwyg/embedToolbarVisibility.ts+++ b/app/src/protyle/wysiwyg/embedToolbarVisibility.ts@@ -1,7 +1,27 @@+import {isEntryVisible} from "../../config/entryVisibility/runtime";+const EMBED_SELECTOR = '[data-type="NodeBlockQueryEmbed"]';const HIDDEN_CLASS = "protyle-icons--editing-obscured";const PROXIMITY = 12;+export const renderEmbedToolbarVisibility = (root: Element) => {+ const visible = window.siyuan.isPublish || isEntryVisible("editor.blockEmbed.toolbar");+ const embeds = Array.from(root.querySelectorAll(EMBED_SELECTOR));+ if (root.matches(EMBED_SELECTOR)) {+ embeds.unshift(root);+ }+ embeds.forEach(embed => {+ embed.querySelectorAll(":scope > .protyle-icons, :scope > .protyle-wysiwyg__embed > .protyle-icons")+ .forEach(toolbar => {+ if (visible) {+ toolbar.removeAttribute("data-entry-hidden");+ } else {+ toolbar.setAttribute("data-entry-hidden", "true");+ }+ });+ });+};+const getToolbar = (element: Element | null): HTMLElement | null => {const embed = element?.closest(EMBED_SELECTOR);return embed?.querySelector<HTMLElement>(":scope > .protyle-icons") || null;@@ -15,6 +35,8 @@ const isNearToolbar = (rect: DOMRect, toolbar: HTMLElement): boolean => {export const bindEmbedToolbarVisibility = (root: HTMLElement): (() => void) => {let caretToolbar: HTMLElement | null = null;+ const onEntryVisibility = () => renderEmbedToolbarVisibility(root);+ onEntryVisibility();const onSelectionChange = () => {const previous = caretToolbar;@@ -47,9 +69,11 @@ export const bindEmbedToolbarVisibility = (root: HTMLElement): (() => void) => {document.addEventListener("selectionchange", onSelectionChange);root.addEventListener("focusout", onFocusOut);+ window.addEventListener("siyuan-entry-visibility", onEntryVisibility);return () => {document.removeEventListener("selectionchange", onSelectionChange);root.removeEventListener("focusout", onFocusOut);+ window.removeEventListener("siyuan-entry-visibility", onEntryVisibility);caretToolbar?.classList.remove(HIDDEN_CLASS);};};diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.tsindex 3faf43ad4a..e76cf3f2ce 100644--- a/app/src/protyle/wysiwyg/index.ts+++ b/app/src/protyle/wysiwyg/index.ts@@ -4,6 +4,7 @@ import {recordReplacementUndo} from "./replacementInput";import {expandAndroidWordSelection, isAndroidWordSelectionPending} from "../../mobile/util/wordSelection";import {bindBoundedBlockDragSelect} from "./boundedBlockDragSelect";import {bindEmbedToolbarVisibility} from "./embedToolbarVisibility";+import {openEmbedBlock} from "../gutter/embedOpenMenu";import {bindSpellcheckFocus} from "../util/spellcheckFocus";import {isTableLikeView} from "../render/av/viewType";import {visibleTabsSelectionHTML} from "../render/tabsVisibility";@@ -199,7 +200,6 @@ import {reloadProtyle} from "../util/reload";import {nbsp2space, removeZWJ} from "../util/normalizeText";import {setFold, toggleListFold} from "../util/blockFold";import {bindHeadingFoldIndicators} from "../util/headingFoldIndicator";-import {BlockPanel} from "../../block/Panel";import {isEncryptedBox, parseSiYuanUriInfo} from "../../util/pathName";import {processSiYuanUri} from "../../util/uri";import {enhanceRichClipboard, prepareExternalClipboardHTML, prepareRichClipboardHTML} from "../util/richClipboard";@@ -5292,16 +5292,7 @@ export class WYSIWYG {const openFloatElement = hasClosestByAttribute(event.target, "data-action", "openFloat");if (openFloatElement) {const id = openFloatElement.getAttribute("data-id");- /// #if MOBILE- openMobileFileById(protyle.app, id, [Constants.CB_GET_HL, Constants.CB_GET_CONTEXT, Constants.CB_GET_ROOTSCROLL], "start");- /// #else- window.siyuan.blockPanels.push(new BlockPanel({- app: protyle.app,- isBacklink: false,- targetElement: openFloatElement,- refDefs: [{refID: id}]- }));- /// #endif+ openEmbedBlock(protyle, openFloatElement, id);event.stopPropagation();event.preventDefault();return;