An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Hide document actions in database-bound block previews
Danielf5ac4e01f2ca
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scssindex 2fbc816d99..f984a92d1a 100644--- a/app/src/assets/scss/protyle/_protyle.scss+++ b/app/src/assets/scss/protyle/_protyle.scss@@ -846,6 +846,10 @@opacity: 0;}+ &--hide-actions &__action {+ display: none;+ }+&__icon {height: 80px;width: 80px;diff --git a/app/src/editor/databaseRowSwitch.test.ts b/app/src/editor/databaseRowSwitch.test.tsindex 5f2ff09543..2063592706 100644--- a/app/src/editor/databaseRowSwitch.test.ts+++ b/app/src/editor/databaseRowSwitch.test.ts@@ -17,6 +17,7 @@ const createPreview = async (mobile: boolean) => {let hidden = false;let hiddenOnClose = false;const openedBlocks: string[] = [];+ const backgroundUpdates: string[] = [];let openBound: () => void;let failBound: () => void;let attributesReady: () => void;@@ -74,6 +75,9 @@ const createPreview = async (mobile: boolean) => {mountedRow = row.itemID;}},"../protyle/ui/padding": {getEditorHorizontalPadding: () => ({left: 0, right: 0})},+ "../../header/backgroundActions": {updateBackgroundActions: (protyle: {element: {dataset: {databaseRowId: string}}}) => {+ backgroundUpdates.push(protyle.element.dataset.databaseRowId);+ }},"../../../dialog": {Dialog: class {public element = root;constructor(options: {destroyCallback: () => void}) { destroy = options.destroyCallback; dialogs.push(this); }@@ -165,7 +169,7 @@ const createPreview = async (mobile: boolean) => {return {data, title, root, content, requests, complete, refresh: () => refresh(),navigate: (next: IDatabaseRowOpenData) => navigate(next), destroy: () => destroy(),body: () => body, closed: () => closed, savedRow: () => model?.data.itemID,- mountedRow: () => mountedRow, hiddenOnClose: () => hiddenOnClose, openedBlocks,+ mountedRow: () => mountedRow, hiddenOnClose: () => hiddenOnClose, openedBlocks, backgroundUpdates,openBound: () => openBound(), failBound: () => failBound(), attributesReady: () => attributesReady()};};@@ -210,6 +214,7 @@ test("mobile detached-to-bound navigation keeps the preview until the target attconst switching = preview.navigate({...preview.data, itemID: "bound", isDetached: false, boundBlockID: "block"});assert.equal(preview.closed(), 0);preview.openBound();+ assert.deepEqual(preview.backgroundUpdates, ["block"], "mobile row opening updates actions after assigning its bound block");assert.equal(preview.closed(), 0);preview.attributesReady();assert.equal(await switching, true);diff --git a/app/src/protyle/header/backgroundActions.test.ts b/app/src/protyle/header/backgroundActions.test.tsnew file mode 100644index 0000000000..fa49bbd5f8--- /dev/null+++ b/app/src/protyle/header/backgroundActions.test.ts@@ -0,0 +1,120 @@+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 {ScriptTarget, transpileModule} from "typescript";+import {compile} from "sass";++const browserCases = async (source: string, css: string) => {+ const check: typeof assert = require("node:assert/strict");+ let mobile = false;+ const update = new Function("isMobile", source + "\nreturn updateBackgroundActions;")(() => mobile);+ const style = document.createElement("style");+ style.textContent = css + ".protyle-background__action {transition: none}";+ document.head.append(style);+ document.body.innerHTML = `<div class="protyle"><div class="protyle-top">+ <div class="protyle-background protyle-background--enable"><div class="protyle-background__action">+ <button>Add tag</button><button>Add icon</button><button>Add cover</button>+ </div></div><div class="protyle-db-attr">Database tabs and fields</div>+ </div></div>`;+ const element = document.querySelector<HTMLElement>(".protyle");+ const background = document.querySelector<HTMLElement>(".protyle-background");+ const actions = document.querySelector<HTMLElement>(".protyle-background__action");+ const panel = document.querySelector<HTMLElement>(".protyle-db-attr");+ const protyle = {element, background: {element: background}, block: {id: "document", rootID: "document", showAll: false}};+ const hover = (enabled: boolean) => require("electron").ipcRenderer.invoke("header-hover", enabled);+ const visible = () => getComputedStyle(actions).display !== "none";+ for (mobile of [false, true]) {+ await hover(false);+ delete element.dataset.databaseRowId;+ protyle.block = {id: "document", rootID: "document", showAll: false};+ update(protyle);+ check.equal(visible(), true);+ check.equal(getComputedStyle(actions).opacity, mobile ? "0.86" : "0", "ordinary document behavior is preserved");+ await hover(true);+ check.equal(getComputedStyle(actions).opacity, "0.86", "desktop document actions remain available on hover");+ element.dataset.databaseRowId = "bound";+ protyle.block = {id: "bound", rootID: "document", showAll: true};+ update(protyle);+ check.equal(visible(), false, "database-bound blocks hide document actions even while the header is hovered");+ check.notEqual(getComputedStyle(panel).display, "none", "database tabs and fields remain available");+ background.classList.remove("protyle-background--enable");+ update(protyle);+ background.classList.add("protyle-background--enable");+ update(protyle);+ check.equal(visible(), false, "unlocking a bound block does not reveal document actions");+ await hover(false);+ element.dataset.databaseRowId = "document";+ protyle.block = {id: "document", rootID: "document", showAll: true};+ update(protyle);+ check.equal(visible(), true, "document rows retain document actions after switching or restoring a tab");+ check.equal(getComputedStyle(actions).opacity, mobile ? "0.86" : "0");+ background.classList.remove("protyle-background--enable");+ update(protyle);+ check.equal(visible(), false, "readonly documents hide actions on both platforms");+ background.classList.add("protyle-background--enable");+ element.dataset.databaseRowId = "bound";+ protyle.block = {id: "bound", rootID: "document", showAll: true};+ update(protyle);+ protyle.block = {id: "document", rootID: "document", showAll: false};+ update(protyle);+ check.equal(visible(), true, "exiting block focus restores document actions");+ check.equal(getComputedStyle(actions).opacity, mobile ? "0.86" : "0");+ protyle.block = {id: "other-block", rootID: "document", showAll: true};+ update(protyle);+ check.equal(visible(), true, "ordinary block navigation does not inherit another row's hidden state");+ delete element.dataset.databaseRowId;+ protyle.block.id = "bound";+ update(protyle);+ check.equal(visible(), true, "ordinary focused blocks retain their existing behavior");+ }+ update({});+ return "Background action cases passed";+};++test("database row header actions follow the opened object on desktop and mobile", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const source = transpileModule(readFileSync(path.join(__dirname, "backgroundActions.ts"), "utf8")+ .replace(/^import .*;\r?\n/gm, "").replace(/^export /gm, ""),+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const css = compile("src/assets/scss/protyle/_protyle.scss").css;+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-background-actions-test-"));+ const script = path.join(temporary, "run.cjs");+ const code = "const __name = value => value; (" + browserCases.toString() + ")(" + JSON.stringify(source) + "," + JSON.stringify(css) + ")";+ writeFileSync(script, `const {app, BrowserWindow, ipcMain} = require("electron");+app.setPath("userData", ${JSON.stringify(path.join(temporary, "profile"))});+app.commandLine.appendSwitch("disable-gpu");+app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ try {+ await win.loadURL("data:text/html,<html><body></body></html>");+ win.webContents.debugger.attach("1.3");+ await win.webContents.debugger.sendCommand("DOM.enable");+ await win.webContents.debugger.sendCommand("CSS.enable");+ ipcMain.handle("header-hover", async (_event, enabled) => {+ const {root} = await win.webContents.debugger.sendCommand("DOM.getDocument");+ const {nodeId} = await win.webContents.debugger.sendCommand("DOM.querySelector", {nodeId: root.nodeId, selector: ".protyle-top"});+ await win.webContents.debugger.sendCommand("CSS.forcePseudoState", {nodeId, forcedPseudoClasses: enabled ? ["hover"] : []});+ });+ console.log(await win.webContents.executeJavaScript(${JSON.stringify(code)}));+ win.destroy(); app.exit(0);+ } catch (error) { console.error(error); win.destroy(); 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, /Background action cases passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-background-actions-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/protyle/header/backgroundActions.ts b/app/src/protyle/header/backgroundActions.tsnew file mode 100644index 0000000000..e201690c37--- /dev/null+++ b/app/src/protyle/header/backgroundActions.ts@@ -0,0 +1,15 @@+import {isMobile} from "../../util/functions";++export const updateBackgroundActions = (protyle: IProtyle) => {+ const element = protyle.background?.element;+ if (!element) {+ return;+ }+ const isDatabaseRow = Boolean(protyle.element.dataset.databaseRowId && protyle.block.showAll &&+ protyle.element.dataset.databaseRowId === protyle.block.id);+ const isDocument = protyle.block.id === protyle.block.rootID;+ element.classList.toggle("protyle-background--hide-actions", isDatabaseRow && !isDocument);+ if (isMobile()) {+ element.classList.toggle("protyle-background--mobileshow", !protyle.block.showAll || (isDatabaseRow && isDocument));+ }+};diff --git a/app/src/protyle/render/av/attributePanel.ts b/app/src/protyle/render/av/attributePanel.tsindex f685115e19..62082c857f 100644--- a/app/src/protyle/render/av/attributePanel.ts+++ b/app/src/protyle/render/av/attributePanel.ts@@ -94,7 +94,7 @@ export class AVAttributePanel {return;}this.activeAvID = (target.closest('[data-type="av-tab"]') as HTMLElement).dataset.id || "";- this.updateTabs();+ this.updateTabSelection();event.preventDefault();event.stopPropagation();} else if (target.closest('[data-type="toggle"]')) {@@ -348,17 +348,20 @@ export class AVAttributePanel {} else {tabsElement?.remove();}+ this.updateTabSelection(databaseElements);+ }++ private updateTabSelection(databaseElements = Array.from(this.bodyElement.querySelectorAll<HTMLElement>(":scope > [data-av-id]"))) {+ const useTabs = window.siyuan.config.editor.databaseAttrUseTabs;if (databaseElements.length > 0 && !databaseElements.some(item => item.dataset.avId === this.activeAvID)) {this.activeAvID = databaseElements[0]?.dataset.avId || "";}databaseElements.forEach(item => {item.classList.toggle("fn__none", useTabs && databaseElements.length > 1 && item.dataset.avId !== this.activeAvID);});- if (tabsElement) {- tabsElement.querySelectorAll("[data-type=\"av-tab\"]").forEach(item => {- item.classList.toggle("item--focus", item.getAttribute("data-id") === this.activeAvID);- });- }+ this.bodyElement.querySelectorAll(':scope > .protyle-db-attr__tabs [data-type="av-tab"]').forEach(item => {+ item.classList.toggle("item--focus", item.getAttribute("data-id") === this.activeAvID);+ });}private bindTabDrag(tabsElement: HTMLElement) {diff --git a/app/src/protyle/render/av/attributePanelVisibility.test.ts b/app/src/protyle/render/av/attributePanelVisibility.test.tsindex d3544f24a4..784c42d3f6 100644--- a/app/src/protyle/render/av/attributePanelVisibility.test.ts+++ b/app/src/protyle/render/av/attributePanelVisibility.test.ts@@ -18,7 +18,8 @@ const browserCases = async (source: string, css: string, columnSource: string, balwaysShow: "Always show", hideWhenEmpty: "Hide when empty", alwaysHide: "Always hide",_attrView: {dateCalendar: "Calendar", solarCalendar: "Gregorian", lunarCalendar: "Chinese lunar"},}}});- const Panel = new Function("cancelHeightAnimation", source + "\nreturn AVAttributePanel;")(() => {});+ const Panel = new Function("cancelHeightAnimation", "escapeHtmlTextAndAttr", source + "\nreturn AVAttributePanel;")(+ () => {}, (value: string) => value);const style = document.createElement("style");style.textContent = css + ".fn__none {display:none} .av__row {display:flex}";document.head.append(style);@@ -104,6 +105,34 @@ const browserCases = async (source: string, css: string, columnSource: string, bcheck.equal(pending.length, 1, "subsequent refreshes request fresh attributes");pending.shift()();boundPanel.element.remove();+ config.editor.databaseAttrUseTabs = true;+ const tabPanel = new Panel({disabled: false});+ tabPanel.element.dataset.rendered = "true";+ const tabBody = tabPanel.element.querySelector(".protyle-db-attr__body") as HTMLElement;+ tabBody.innerHTML = ["first", "second"].map(id => `<div data-av-id="${id}">+ <div class="custom-attr__avheader"><div class="block__logo"><span>${id}</span></div></div>+ </div>`).join("");+ document.body.append(tabPanel.element);+ tabPanel.updateDisplayConfig();+ const tabButtons = Array.from(tabBody.querySelectorAll<HTMLButtonElement>('[data-type="av-tab"]'));+ const tabChanges = new MutationObserver(() => {});+ tabChanges.observe(tabBody.querySelector(".protyle-db-attr__tabs"), {childList: true, subtree: true});+ for (const pointerType of ["mouse", "touch"]) {+ for (const index of [1, 0, 1]) {+ tabButtons[index].focus();+ tabButtons[index].querySelector("span").dispatchEvent(new PointerEvent("click", {bubbles: true, pointerType}));+ check.equal(document.activeElement, tabButtons[index], "switching databases preserves keyboard focus");+ check.equal(tabChanges.takeRecords().length, 0, "switching databases keeps hovered tab nodes connected");+ tabButtons.forEach((button, buttonIndex) => {+ check.equal(button.classList.contains("item--focus"), buttonIndex === index);+ check.equal(tabBody.querySelector(`[data-av-id="${button.dataset.id}"]`).classList.contains("fn__none"),+ buttonIndex !== index);+ });+ }+ }+ tabChanges.disconnect();+ tabPanel.element.remove();+ config.editor.databaseAttrUseTabs = false;const transactions: unknown[][] = [];const escape = (value: string) => value || "";let mobile = false;diff --git a/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts b/app/src/protyle/render/av/databaseRowPreviewNavigation.test.tsindex 3bc095f628..b97352ade6 100644--- a/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts+++ b/app/src/protyle/render/av/databaseRowPreviewNavigation.test.ts@@ -92,6 +92,9 @@ test("row navigation replaces only its original desktop preview across bound and"../../../dialog/message": {showMessage() {}},"../../../layout/util": {saveLayout() {}},"./rowReadonly": {inheritDatabaseRowReadonly() {}},+ "../../header/backgroundActions": {updateBackgroundActions: (protyle: {element: {dataset: {databaseRowId: string}}}) => {+ assert.ok(protyle.element.dataset.databaseRowId, "desktop row opening updates actions after assigning its bound block");+ }},"./databaseRowNavigation": {getDatabaseRowNavigation: (): undefined => undefined,mountDatabaseRowNavigation: (root: object, _data: unknown, open: (data: IDatabaseRowOpenData) => Promise<boolean>) => callbacks.set(root, open),diff --git a/app/src/protyle/render/av/openDatabaseRow.ts b/app/src/protyle/render/av/openDatabaseRow.tsindex c042903140..afe3792a0c 100644--- a/app/src/protyle/render/av/openDatabaseRow.ts+++ b/app/src/protyle/render/av/openDatabaseRow.ts@@ -21,6 +21,7 @@ import {focusDatabasePrimary} from "./primaryFocus";import {preserveAVBindingRange} from "./binding";import {inheritDatabaseRowReadonly} from "./rowReadonly";import {getDatabaseRowNavigation, IDatabaseRowNavigation, mountDatabaseRowNavigation} from "./databaseRowNavigation";+import {updateBackgroundActions} from "../../header/backgroundActions";export interface IDatabaseRowOpenData {avID: string;@@ -191,6 +192,7 @@ export const showDatabaseRowPreview = (model: Editor, data: IDatabaseRowOpenData};inheritDatabaseRowReadonly(editorProtyle, source);editorProtyle.element.dataset.databaseRowId = data.boundBlockID || "";+ updateBackgroundActions(editorProtyle);mountDesktopDatabaseRowNavigation(model, data, source);editorProtyle.databaseAttributePanel?.expand(data.avID);editorProtyle.contentElement.scrollTop = 0;@@ -374,6 +376,7 @@ export const openDatabaseRowByData = async (protyle: Pick<IProtyle, "app">, dataundefined, undefined, (editorProtyle) => {inheritDatabaseRowReadonly(editorProtyle, protyle);editorProtyle.element.dataset.databaseRowId = data.boundBlockID;+ updateBackgroundActions(editorProtyle);mountDatabaseRowNavigation(editorProtyle.element, data, next => openDatabaseRowByData(protyle, next),editorProtyle.breadcrumb?.element.parentElement);editorProtyle.databaseAttributePanel?.expand(data.avID);diff --git a/app/src/protyle/util/onGet.ts b/app/src/protyle/util/onGet.tsindex 21f6cb9967..ae6401cb03 100644--- a/app/src/protyle/util/onGet.ts+++ b/app/src/protyle/util/onGet.ts@@ -44,6 +44,7 @@ import {forEachPluginSubscriber} from "../../plugin/EventBusCore";import {disposeCustomBlocksInElement, setCustomBlockRootReady} from "../../plugin/customBlockRender";import {invalidateTrackedRanges, invalidateTrackedRangesInElement} from "./trackedRange";import {areProtylePluginExtensionsEnabled} from "../runtimeCapabilities";+import {updateBackgroundActions} from "../header/backgroundActions";import {recordRestoredSpellcheckFocus} from "./spellcheckFocus";import {applyPublishFoldStates} from "./viewFold";/// #if MOBILE@@ -483,14 +484,7 @@ const setHTML = (options: {return;}- /// #if MOBILE- if (protyle.background) {- protyle.background.element.classList.toggle(- "protyle-background--mobileshow",- !options.action.includes(Constants.CB_GET_ALL)- );- }- /// #endif+ updateBackgroundActions(protyle);if (protyle.options.render.breadcrumb) {protyle.breadcrumb.toggleExit(!options.action.includes(Constants.CB_GET_ALL));diff --git a/app/src/protyle/util/onGetMobileTopBar.test.ts b/app/src/protyle/util/onGetMobileTopBar.test.tsindex cb63582a55..e9bb759aa3 100644--- a/app/src/protyle/util/onGetMobileTopBar.test.ts+++ b/app/src/protyle/util/onGetMobileTopBar.test.ts@@ -24,6 +24,7 @@ const sources = {layout: compile(sliceSource("../../mobile/util/mobileTopBar.ts", "const MOBILE_TOP_BAR_ELEMENT_IDS = ")),editor: compile(sliceSource("../../mobile/util/setEmpty.ts", "export const setEditor = ")),render: compile(sliceSource("onGet.ts", "export const onGet = ", "export const disabledForeverProtyle = ")),+ backgroundActions: compile(sliceSource("../header/backgroundActions.ts", "export const updateBackgroundActions = ")),loading: compile(sliceSource("../ui/initUI.ts", "export const addLoading = ", "export const setPadding = ")),navigation: compile(sliceSource("../render/av/databaseRowNavigation.ts", "export const clearDatabaseRowNavigation = ", "export const mountDatabaseRowNavigation = ")),completion: compile(sliceSource("../../mobile/editor.ts", " let completed = false;", " if (!isValid()) {")),@@ -55,6 +56,7 @@ const browserCases = (code: typeof sources) => {Constants.TIMEOUT_LOAD = 300;const protyle = {element: editorElement,+ background: {element: document.createElement("div")},contentElement,options: {render: {title: true, breadcrumb: true}, defIds: [] as string[]},block: {rootID: "previous"},@@ -65,6 +67,7 @@ const browserCases = (code: typeof sources) => {breadcrumb: {element: breadcrumbElement.firstElementChild, toggleExit: noop, render: noop},scroll: {element: scrollElement, invalidateDynamicLoad: noop},};+ protyle.background.element.className = "protyle-background protyle-background--hide-actions";const dependencies: Record<string, unknown> = {document, DOMParser, Constants,window: {screen: {orientation: {type: mode === "landscape" ? "landscape-primary" : "portrait-primary"}},@@ -87,7 +90,7 @@ const browserCases = (code: typeof sources) => {dependencies[name] = noop;}const runtime = new Function(...Object.keys(dependencies), code.orientation + code.layout + code.editor + code.loading +- code.render + code.navigation + code.completion + "\nreturn {onGet, addLoading, complete, fail, updateMobileTopBarLayout};")(+ code.backgroundActions + code.render + code.navigation + code.completion + "\nreturn {onGet, addLoading, complete, fail, updateMobileTopBarLayout};")(...Object.values(dependencies));if (mode !== "desktop") {runtime.updateMobileTopBarLayout();@@ -109,6 +112,9 @@ const browserCases = (code: typeof sources) => {timers.forEach(callback => callback());check.equal(renderError, undefined, `${mode}: document rendering completes without a title lookup error`);check.equal(opened, 1, `${mode}: navigation settles successfully`);+ check.equal(protyle.background.element.classList.contains("protyle-background--hide-actions"), false,+ `${mode}: ordinary document navigation clears hidden database row actions`);+ check.equal(protyle.background.element.classList.contains("protyle-background--mobileshow"), mode !== "desktop");check.equal(failed, 0);check.equal(wysiwygElement.textContent, "Next document");check.equal(editorElement.getAttribute("data-loading"), "finished");