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: Complete pinned document tooltip details
Daniele5f9e7fa9c17
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.tsindex 035b402728..97496a8ce4 100644--- a/app/src/layout/dock/Files.ts+++ b/app/src/layout/dock/Files.ts@@ -1,5 +1,6 @@import {config as configApi} from "../../config/util/configApi";import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../util/escape";+import {genFileTreeDocAriaLabel} from "../../util/fileTreeTooltip";import {Tab} from "../Tab";import {Model} from "../Model";import {getInstanceById, setPanelFocus} from "../util";@@ -1322,7 +1323,7 @@ export class Files extends Model {);if (liElement) {if (liElement.getAttribute("data-type") === "navigation-file") {- liElement.querySelector(".b3-list-item__text.ariaLabel")?.setAttribute("aria-label", this.genDocAriaLabel(data.data, escapeLessThans));+ liElement.querySelector(".b3-list-item__text.ariaLabel")?.setAttribute("aria-label", genFileTreeDocAriaLabel(data.data, escapeLessThans));}this.updateSubFileCount(liElement as HTMLElement, subFileCount);}@@ -2149,16 +2150,12 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"setStorageVal(Constants.LOCAL_FILESPATHS, filesPaths);}- private genDocAriaLabel(item: IFile, escapeMethod: (text: string) => string) {- return `${escapeMethod(getDocDisplayName(item.name, item.titleEmpty))} <small class='ft__on-surface'>${item.hSize}</small>${item.bookmark ? "<br>" + window.siyuan.languages.bookmark + " " + escapeMethod(item.bookmark) : ""}${item.name1 ? "<br>" + window.siyuan.languages.name + " " + escapeMethod(item.name1) : ""}${item.alias ? "<br>" + window.siyuan.languages.alias + " " + escapeMethod(item.alias) : ""}${item.memo ? "<br>" + window.siyuan.languages.memo + " " + escapeMethod(item.memo) : ""}${item.subFileCount !== 0 ? window.siyuan.languages.includeSubFile.replace("x", item.subFileCount) : ""}<br>${window.siyuan.languages.modifiedAt} ${item.hMtime}<br>${window.siyuan.languages.createdAt} ${item.hCtime}`;- }-private genFileHTML(item: IFile) {let countHTML = "";if (item.count && item.count > 0) {countHTML = `<span class="popover__block counter b3-tooltips b3-tooltips__nw" aria-label="${window.siyuan.languages.ref}">${item.count}</span>`;}- const ariaLabel = this.genDocAriaLabel(item, escapeAriaLabel);+ const ariaLabel = genFileTreeDocAriaLabel(item, escapeAriaLabel);const paddingLeft = (item.path.split("/").length - 1) * 18;const editingPublishAccess = this.element.classList.contains("file-tree__publish-access--active");const iconExpands = window.siyuan.config.fileTree.docIconClickMode === 1;diff --git a/app/src/layout/dock/PinnedDocs.test.ts b/app/src/layout/dock/PinnedDocs.test.tsindex 6b21305962..e559a2e122 100644--- a/app/src/layout/dock/PinnedDocs.test.ts+++ b/app/src/layout/dock/PinnedDocs.test.ts@@ -1,13 +1,13 @@import * as assert from "node:assert/strict";import test from "node:test";import {readFileSync} from "node:fs";-import {join} from "node:path";+import {join, posix} from "node:path";import {runInNewContext} from "node:vm";import * as ts from "typescript";import {getPinnedDropPosition} from "../../util/pinnedDocsDrop";import {ParentDocClick} from "./parentDocClick";import {setTimeout as delay} from "node:timers/promises";-import {escapeAriaLabel, escapeHtml} from "../../util/escape";+import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../util/escape";interface IPanelHarness {parentDocClick: ParentDocClick;@@ -17,7 +17,7 @@ interface IPanelHarness {clearSelection(): void;updateDocActions(): void;refresh(dirtyChildren?: Set<string>): Promise<void>;- onFileTreeMessage(data: {cmd: string, data?: {id: string}}): void;+ onFileTreeMessage(data: {cmd: string, data?: {id?: string, rootID?: string} & Partial<IFile>}): void;collapse(): void;expanded: Set<string>;list: unknown;@@ -47,7 +47,7 @@ const loadPanel = (fetchCode = 0) => {const hitTest = {target: null as unknown};const storage = new Map<string, string>();const docs: {id: string, notebook: string, name: string}[] = [];- const childData = {effectiveSortMode: 6, files: [] as {id: string, name: string, icon?: string}[]};+ const childData = {effectiveSortMode: 6, files: [] as ({id: string, name: string} & Partial<IFile>)[]};const config = {readonly: false, fileTree: {docIconClickMode: 0, parentDocTitleClickMode: 0}};const calls: {kind: string, args: unknown[]}[] = [];const timers: (() => void)[] = [];@@ -66,6 +66,19 @@ const loadPanel = (fetchCode = 0) => {return {code: kind === "http" ? fetchCode : 0, data: args[0] === "/api/filetree/listDocsByPath" ? childData : docs};};const exports: {PinnedDocs?: {prototype: object}} = {};+ const pathName = {};+ const tooltip = {};+ const escape = {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr};+ for (const [file, target] of [["pathName", pathName], ["fileTreeTooltip", tooltip]] as const) {+ runInNewContext(ts.transpileModule(readFileSync(join(__dirname, `../../util/${file}.ts`), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText, {exports: target, window: {siyuan: runtime}, require: (name: string) => {+ if (name === "path") { return {posix}; }+ if (name.endsWith("/escape")) { return escape; }+ if (name.endsWith("/pathName")) { return pathName; }+ return {};+ }});+ }const menuToggle = {};runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "../../menus/menuToggle.ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},@@ -96,7 +109,8 @@ const loadPanel = (fetchCode = 0) => {if (name.endsWith("/dragover")) { return {dragOverScroll: () => {}}; }if (name.endsWith("/compatibility")) { return {isOnlyMeta: (event: MouseEvent) => Boolean(event.ctrlKey)}; }if (name.endsWith("/fileTreeIcon")) { return {getFileTreeIconHTML: () => ""}; }- if (name.endsWith("/escape")) { return {escapeAriaLabel, escapeHtml}; }+ if (name.endsWith("/escape")) { return escape; }+ if (name.endsWith("/fileTreeTooltip")) { return tooltip; }if (name.endsWith("/emoji")) { return {openEmojiPanel: record("icon")}; }if (name.endsWith("/navigation")) {return {initFileMenu: (...args: unknown[]) => {@@ -683,12 +697,34 @@ test("pinned area follows list contents on initial load, pin, unpin and sync", aassert.ok(calls.every(call => call.kind === "http" && call.args[0] === "/api/filetree/getPinnedDocs"));});+test("document info updates every available pinned copy without scheduling another tree refresh", () => {+ const {panel, calls, runtime} = loadPanel();+ Object.assign(runtime.languages, {bookmark: "Bookmark", name: "Name", alias: "Alias", memo: "Memo",+ includeSubFile: " (x children)", modifiedAt: "Modified", createdAt: "Created"});+ const rows = ["document", "document", "other", "document"].map((nodeId, index) => ({+ dataset: {nodeId, unavailable: String(index === 3)},+ label: "unchanged",+ querySelector() { return {setAttribute: (_name: string, value: string) => { this.label = value; }}; },+ }));+ panel.list = {querySelectorAll: () => rows};+ const info = {rootID: "document", name: 'A "title" <tag>', hSize: "2 KB", hMtime: "updated", hCtime: "created",+ bookmark: "bookmark <text>", name1: "named", alias: "alias", memo: "memo", subFileCount: 2};+ panel.onFileTreeMessage({cmd: "reloadDocInfo", data: info});+ const expected = 'A "title" <tag> <small class=\'ft__on-surface\'>2 KB</small><br>Bookmark bookmark <text>' ++ "<br>Name named<br>Alias alias<br>Memo memo (2 children)<br>Modified updated<br>Created created";+ assert.equal(rows[0].label, expected);+ assert.equal(rows[1].label, expected);+ assert.equal(rows[2].label, "unchanged");+ assert.equal(rows[3].label, "unchanged");+ assert.equal(calls.length, 0);+});+test("rename refresh is not repeated by delayed document info or notebook info pushes", () => {const {panel} = loadPanel();const updates: (string | undefined)[] = [];panel.scheduleRefresh = id => updates.push(id);panel.onFileTreeMessage({cmd: "rename", data: {id: "document"}});- panel.onFileTreeMessage({cmd: "reloadDocInfo"});+ panel.onFileTreeMessage({cmd: "reloadDocInfo", data: {rootID: "document"}});panel.onFileTreeMessage({cmd: "reloadNotebookInfo"});panel.onFileTreeMessage({cmd: "reloadFiletree"});assert.deepEqual(updates, ["document"]);@@ -718,6 +754,11 @@ test("unchanged child lists preserve DOM while title, icon and order changes rebchildData.files.reverse();await panel.loadChildren(row, children, 1);assert.equal(rebuilds, 4);+ for (const field of ["hSize", "hMtime", "hCtime", "name1", "alias", "memo", "bookmark"] as const) {+ childData.files[0][field] = "updated " + field;+ await panel.loadChildren(row, children, 1);+ }+ assert.equal(rebuilds, 11);});test("unchanged roots still refresh the affected expanded child list without replacing root rows", async () => {diff --git a/app/src/layout/dock/PinnedDocs.tooltip.test.ts b/app/src/layout/dock/PinnedDocs.tooltip.test.tsnew file mode 100644index 0000000000..2e6290d05f--- /dev/null+++ b/app/src/layout/dock/PinnedDocs.tooltip.test.ts@@ -0,0 +1,122 @@+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 * as ts from "typescript";++const browserCases = async (sources: Record<string, string>) => {+ const check: typeof assert = require("node:assert/strict");+ document.body.innerHTML = "<style>.fn__none{display:none}li{width:200px;height:28px}#tooltip{position:fixed}</style>" ++ '<ul id="pinned"></ul><ul id="ordinary"></ul><div id="tooltip" class="fn__none"></div>';+ window.siyuan = {config: {readonly: false, fileTree: {docIconClickMode: 1}}, notebooks: [], languages: {+ bookmark: "Bookmark", name: "Name", alias: "Alias", memo: "Memo", includeSubFile: " (x children)",+ modifiedAt: "Modified", createdAt: "Created", closeNotebook: "Closed notebook", _kernel: {16: "Untitled"},+ }} as unknown as typeof window.siyuan;+ window.DOMPurify = {sanitize: (value: string) => value} as typeof window.DOMPurify;+ let mobile = false;+ const modules: Record<string, Record<string, unknown>> = {};+ const load = (name: string) => {+ const exports: Record<string, unknown> = {};+ new Function("exports", "require", sources[name])(exports, (id: string) => {+ const key = id.split("/").pop();+ if (key === "path") { return require("node:path"); }+ return modules[key] || {isInIOS: () => false, isMobile: () => mobile,+ emitToPlugins: () => {}, forEachPluginSubscriber: () => {}, getFileTreeIconHTML: () => ""};+ });+ modules[name] = exports;+ return exports;+ };+ load("escape");+ const names = load("pathName") as typeof import("../../util/pathName");+ const helper = load("fileTreeTooltip");+ const input = load("hoverInput") as typeof import("../../util/hoverInput");+ const tooltip = load("tooltip") as typeof import("../../dialog/tooltip");+ const Pinned = load("PinnedDocs") as unknown as {PinnedDocs: {prototype: object}};+ const panel = Object.create(Pinned.PinnedDocs.prototype);+ panel.expanded = new Set();+ const regular: {render?: (item: unknown) => string} = {};+ const dependencies = {...modules.escape, ...helper, getDocDisplayName: names.getDocDisplayName,+ FILE_TREE_CHILDREN_SORT_MODE: "data-children-sort-mode", getFileTreeDefaultIconAttr: () => "",+ getFileTreeIconHTML: () => "", getPublishAccessOptionByLevel: () => ({iconHTML: ""})};+ new Function("exports", ...Object.keys(dependencies), sources.regular)(regular, ...Object.values(dependencies));+ const pinned = document.getElementById("pinned");+ const ordinary = document.getElementById("ordinary");+ const tip = document.getElementById("tooltip");+ tooltip.initTooltips();+ const doc = {id: "doc", notebook: "box", name: 'Title "quotes" <tag> & text', path: "/doc.sy", subFileCount: 2,+ hSize: "2 KB", hMtime: "2026-10-17 11:00:00", hCtime: "2026-09-01 10:00:00",+ bookmark: 'Mark "quoted"', name1: "Named <tag>", alias: "Alias & text", memo: "Memo <img src=x>"};+ for (const depth of [0, 1]) {+ pinned.replaceChildren();+ await panel.appendDoc(pinned, doc, "doc", depth, 0);+ ordinary.innerHTML = regular.render.call({element: ordinary}, doc);+ const title = pinned.querySelector(".b3-list-item__text");+ check.equal(title.getAttribute("aria-label"), ordinary.querySelector(".b3-list-item__text").getAttribute("aria-label"));+ title.dispatchEvent(new PointerEvent("pointerover", {bubbles: true, pointerType: "mouse"}));+ title.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));+ await new Promise(resolve => setTimeout(resolve, 260));+ check.equal(tip.classList.contains("fn__none"), false);+ for (const value of [doc.name, doc.hSize, doc.hMtime, doc.hCtime, doc.bookmark, doc.name1, doc.alias, doc.memo, "2 children"]) {+ check.ok(tip.textContent.includes(value), `missing tooltip detail: ${value}`);+ }+ check.equal(tip.querySelector("img, tag"), null, "metadata remains plain text");+ tooltip.hideTooltip();+ }+ pinned.replaceChildren();+ await panel.appendDoc(pinned, {...doc, unavailable: true}, "doc", 0, 0);+ const closed = pinned.querySelector(".b3-list-item__text");+ closed.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));+ check.equal(tip.textContent, doc.name + " (Closed notebook)");+ tooltip.hideTooltip();+ closed.dispatchEvent(new PointerEvent("pointerdown", {bubbles: true, pointerType: "touch"}));+ closed.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));+ check.equal(input.isTouchHoverInput(), true);+ check.equal(tip.classList.contains("fn__none"), true);+ mobile = true;+ closed.dispatchEvent(new PointerEvent("pointerover", {bubbles: true, pointerType: "mouse"}));+ closed.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));+ check.equal(tip.classList.contains("fn__none"), true);+ return "Pinned tooltip details passed";+};++test("pinned roots and children show the same complete escaped tooltip as ordinary documents", {+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,+ timeout: 30000,+}, async () => {+ const sources: Record<string, string> = {};+ const compile = (source: string) => ts.transpileModule(source, {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},+ }).outputText;+ for (const file of ["util/escape", "util/pathName", "util/fileTreeTooltip", "util/hoverInput", "dialog/tooltip", "layout/dock/PinnedDocs"]) {+ sources[file.split("/").pop()] = compile(readFileSync(`src/${file}.ts`, "utf8"));+ }+ const source = ts.createSourceFile("Files.ts", readFileSync("src/layout/dock/Files.ts", "utf8"), ts.ScriptTarget.Latest, true);+ const declaration = source.statements.find(ts.isClassDeclaration);+ const method = declaration.members.find(member => member.name?.getText(source) === "genFileHTML") as ts.MethodDeclaration;+ sources.regular = compile(`exports.render = function(item) ${method.body.getText(source)};`);+ const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-pinned-tooltip-test-"));+ const script = path.join(temporary, "run.cjs");+ writeFileSync(script, `const {app,BrowserWindow}=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,width:800,height:600,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("const __name = value => value; (" ++ browserCases.toString() + ")(" + JSON.stringify(sources) + ")")}));win.destroy();app.exit(0);+}catch(e){console.error(e);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, /Pinned tooltip details passed/);+ } finally {+ if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&+ path.basename(temporary).startsWith("siyuan-pinned-tooltip-test-")) {+ rmSync(temporary, {recursive: true, force: true});+ }+ }+});diff --git a/app/src/layout/dock/PinnedDocs.ts b/app/src/layout/dock/PinnedDocs.tsindex 581a255070..b9e449051d 100644--- a/app/src/layout/dock/PinnedDocs.ts+++ b/app/src/layout/dock/PinnedDocs.ts@@ -5,7 +5,8 @@ import {pinnedDocIDs, updatePinnedDocs} from "../../util/pinnedDocs";import {getPinnedDropPosition} from "../../util/pinnedDocsDrop";import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";import {openEmojiPanel} from "../../emoji";-import {escapeAriaLabel, escapeHtml} from "../../util/escape";+import {escapeAriaLabel, escapeHtml, escapeLessThans} from "../../util/escape";+import {genFileTreeDocAriaLabel, type IFileTreeDocTooltip} from "../../util/fileTreeTooltip";import {initFileMenu} from "../../menus/navigation";import {toggleMenu} from "../../menus/menuToggle";import {globalClickHideMenu} from "../../menus/menuClick";@@ -20,7 +21,7 @@ import {setFileTreeVisibility} from "./fileTreeAnimation";import {ParentDocClick} from "./parentDocClick";import {hideDragTip, setDragTipGhost, showDragTip} from "../../protyle/util/dragTip";-interface IPinnedDoc {+interface IPinnedDoc extends IFileTreeDocTooltip {id: string;notebook: string;name: string;@@ -53,6 +54,14 @@ export class PinnedDocs {public onFileTreeMessage(data: IWebSocketData) {switch (data.cmd) {+ case "reloadDocInfo":+ this.list.querySelectorAll<HTMLElement>("[data-pin-row]").forEach(row => {+ if (row.dataset.nodeId === data.data.rootID && row.dataset.unavailable !== "true") {+ row.querySelector(".b3-list-item__text")?.setAttribute("aria-label",+ genFileTreeDocAriaLabel(data.data, escapeLessThans));+ }+ });+ break;case "pinnedDocsChanged":this.scheduleRefresh("");break;@@ -326,8 +335,10 @@ export class PinnedDocs {if (doc.subFileCount) { row.setAttribute("aria-expanded", "false"); }// 桌面端点击会修改图标时给出提示,移动端保留无障碍标签const iconLabel = this.getDocIconLabel(doc.subFileCount);+ const ariaLabel = doc.unavailable || !doc.hSize ? escapeAriaLabel(doc.name) ++ (doc.unavailable ? ` (${window.siyuan.languages.closeNotebook})` : "") : genFileTreeDocAriaLabel(doc, escapeAriaLabel);if (!doc.icon) { row.dataset.defaultIcon = doc.subFileCount ? "folder" : "file"; }- row.innerHTML = `<span data-pin-toggle="true" style="padding-left:${paddingLeft}px" class="b3-list-item__toggle b3-list-item__toggle--hl${doc.subFileCount ? "" : " fn__hidden"}"><svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg></span><span class="b3-list-item__icon${iconLabel ? " ariaLabel" : ""}" data-position="8east"${iconLabel ? ` aria-label="${iconLabel}"` : ""}>${getFileTreeIconHTML(doc.icon, doc.subFileCount ? "folder" : "file")}</span><span class="b3-list-item__text ariaLabel" data-delay="200" data-position="parentE" aria-label="${escapeAriaLabel(doc.name)}${doc.unavailable ? ` (${window.siyuan.languages.closeNotebook})` : ""}">${escapeHtml(doc.name)}${doc.unavailable ? ` (${window.siyuan.languages.closeNotebook})` : ""}</span><span data-pin-more="true" data-menu="true" class="b3-list-item__action" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span>`;+ row.innerHTML = `<span data-pin-toggle="true" style="padding-left:${paddingLeft}px" class="b3-list-item__toggle b3-list-item__toggle--hl${doc.subFileCount ? "" : " fn__hidden"}"><svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg></span><span class="b3-list-item__icon${iconLabel ? " ariaLabel" : ""}" data-position="8east"${iconLabel ? ` aria-label="${iconLabel}"` : ""}>${getFileTreeIconHTML(doc.icon, doc.subFileCount ? "folder" : "file")}</span><span class="b3-list-item__text ariaLabel" data-delay="200" data-position="parentE" aria-label="${ariaLabel}">${escapeHtml(doc.name)}${doc.unavailable ? ` (${window.siyuan.languages.closeNotebook})` : ""}</span><span data-pin-more="true" data-menu="true" class="b3-list-item__action" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></span>`;if (!doc.unavailable && !window.siyuan.config.readonly) {const add = document.createElement("span");add.className = "b3-list-item__action";@@ -374,7 +385,9 @@ export class PinnedDocs {}const snapshot = JSON.stringify({sort: response.data.effectiveSortMode, files: response.data.files.map((doc: IFile) => ({id: doc.id, name: doc.name, path: doc.path, icon: doc.icon, subFileCount: doc.subFileCount,- childrenSortMode: doc.childrenSortMode,+ childrenSortMode: doc.childrenSortMode, titleEmpty: doc.titleEmpty,+ hSize: doc.hSize, hMtime: doc.hMtime, hCtime: doc.hCtime,+ name1: doc.name1, alias: doc.alias, memo: doc.memo, bookmark: doc.bookmark,}))});if (children.dataset.pinSnapshot === snapshot) {if (refreshDescendants) {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 14a079ce39..4d5739c1b6 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1582,7 +1582,7 @@ export type PerformTransactionsRequestInput = { "app"?: string; "reqId": number;export type Petal = { "css": string; "disabledInPublish": boolean; "disallowInstall": boolean; "displayName": string; "enabled": boolean; "i18n": { [key: string]: JSONValue } | null; "incompatible": boolean; "js": string; "kernel": KernelPetal; "name": string; "settingsWindow"?: boolean; "userDisabledInPublish": boolean; "version": string; };-export type PinnedDoc = { "childrenSortMode": number | null; "icon": string; "id": string; "name": string; "notebook": string; "path": string; "subFileCount": number; "unavailable": boolean; };+export type PinnedDoc = { "alias": string; "bookmark": string; "childrenSortMode": number | null; "hCtime": string; "hMtime": string; "hSize": string; "icon": string; "id": string; "memo": string; "name": string; "name1": string; "notebook": string; "path": string; "subFileCount": number; "unavailable": boolean; };export type PluginPublishInfo = { "fields": Array<string>; "granted": boolean; "resources": Array<string>; };@@ -5113,6 +5113,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 按置顶顺序返回普通文档及与文档树一致的大小、属性和时间信息。+ * 关闭笔记本的条目标记 unavailable,详细信息为空;加密笔记本不返回置顶条目。+ */"/api/filetree/getPinnedDocs": {request: EmptyRequestInput;response: { "code": 0; "data": Array<PinnedDoc>; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/app/src/util/fileTreeTooltip.ts b/app/src/util/fileTreeTooltip.tsnew file mode 100644index 0000000000..c5782a4d26--- /dev/null+++ b/app/src/util/fileTreeTooltip.ts@@ -0,0 +1,8 @@+import {getDocDisplayName} from "./pathName";++export type IFileTreeDocTooltip = Pick<IFile, "name" | "titleEmpty" | "hSize" | "bookmark" | "name1" | "alias" |+ "memo" | "subFileCount" | "hMtime" | "hCtime">;++export const genFileTreeDocAriaLabel = (item: IFileTreeDocTooltip, escapeMethod: (text: string) => string) => {+ return `${escapeMethod(getDocDisplayName(item.name, item.titleEmpty))} <small class='ft__on-surface'>${item.hSize}</small>${item.bookmark ? "<br>" + window.siyuan.languages.bookmark + " " + escapeMethod(item.bookmark) : ""}${item.name1 ? "<br>" + window.siyuan.languages.name + " " + escapeMethod(item.name1) : ""}${item.alias ? "<br>" + window.siyuan.languages.alias + " " + escapeMethod(item.alias) : ""}${item.memo ? "<br>" + window.siyuan.languages.memo + " " + escapeMethod(item.memo) : ""}${item.subFileCount !== 0 ? window.siyuan.languages.includeSubFile.replace("x", item.subFileCount) : ""}<br>${window.siyuan.languages.modifiedAt} ${item.hMtime}<br>${window.siyuan.languages.createdAt} ${item.hCtime}`;+};diff --git a/kernel/api/pinned_docs.go b/kernel/api/pinned_docs.goindex dc68b1d0f8..96f03188a2 100644--- a/kernel/api/pinned_docs.go+++ b/kernel/api/pinned_docs.go@@ -14,6 +14,8 @@ var getPinnedDocs = contractHandler(apicontract.GetPinnedDocs, func(c *gin.Conteret := []apicontract.PinnedDoc{}for _, doc := range docs {ret = append(ret, apicontract.PinnedDoc{ID: doc.ID, Notebook: doc.Notebook, Name: doc.Name, Path: doc.Path,+ HSize: doc.HSize, HMtime: doc.HMtime, HCtime: doc.HCtime,+ Name1: doc.Name1, Alias: doc.Alias, Memo: doc.Memo, Bookmark: doc.Bookmark,Icon: doc.Icon, SubFileCount: doc.SubFileCount, Unavailable: doc.Unavailable, ChildrenSortMode: doc.ChildrenSortMode})}return apicontract.Success(ret)diff --git a/kernel/api/pinned_docs_test.go b/kernel/api/pinned_docs_test.goindex 232dc18783..d718409bfb 100644--- a/kernel/api/pinned_docs_test.go+++ b/kernel/api/pinned_docs_test.go@@ -1,12 +1,20 @@package apiimport (+ "encoding/json""net/http""net/http/httptest"+ "path/filepath""strings""testing""github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -33,3 +41,82 @@ func TestAPIContractPinnedDocs(t *testing.T) {}}}++func TestAPIContractPinnedDocsMetadata(t *testing.T) {+ previousConf, previousData, previousBlockTree := model.Conf, util.DataDir, util.BlockTreeDBPath+ root := t.TempDir()+ util.DataDir, util.BlockTreeDBPath = filepath.Join(root, "data"), filepath.Join(root, "blocktree.db")+ model.Conf = model.NewAppConf()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ model.Conf.Lang = "pinned-api-test"+ previousTimeLang, hadTimeLang := util.TimeLangs[model.Conf.Lang]+ util.TimeLangs[model.Conf.Lang] = map[string]any{}+ for _, key := range []string{"albl", "blbl", "now", "1s", "xs", "1m", "xm", "1h", "xh", "1d", "xd", "1w", "xw", "1M", "xM", "1y", "2y", "xy", "max"} {+ util.TimeLangs[model.Conf.Lang][key] = "time"+ }+ t.Cleanup(func() {+ treenode.CloseDatabase()+ if hadTimeLang {+ util.TimeLangs[model.Conf.Lang] = previousTimeLang+ } else {+ delete(util.TimeLangs, model.Conf.Lang)+ }+ model.Conf, util.DataDir, util.BlockTreeDBPath = previousConf, previousData, previousBlockTree+ if previousBlockTree != "" {+ treenode.InitBlockTree(false)+ }+ })+ treenode.InitBlockTree(true)+ box := &model.Box{ID: "20261017000000-pinapi1"}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Pinned", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ tree := treenode.NewTree(box.ID, "/20261017000001-pinapi1.sy", "/Pinned", "Pinned")+ attrs := map[string]string{"name": "Named", "alias": "Alias", "memo": "Memo <text>", "bookmark": "Bookmark"}+ for key, value := range attrs {+ tree.Root.SetIALAttr(key, value)+ }+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ t.Cleanup(func() { cache.RemoveTreeData(tree.ID); cache.RemoveDocIAL(tree.Path) })+ if err := model.UpdatePinnedDocs([]string{tree.ID}, "pin", "", false); err != nil {+ t.Fatal(err)+ }+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.POST("/api/filetree/getPinnedDocs", getPinnedDocs)+ for _, closed := range []bool{false, true} {+ boxConf.Closed = closed+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ response := httptest.NewRecorder()+ engine.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/api/filetree/getPinnedDocs", nil))+ requireAPIContract(t, http.MethodPost, "/api/filetree/getPinnedDocs", response)+ var body struct {+ Code int `json:"code"`+ Data []apicontract.PinnedDoc `json:"data"`+ }+ if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.Code != 0 || len(body.Data) != 1 {+ t.Fatalf("unexpected response: %s, %v", response.Body.String(), err)+ }+ doc := body.Data[0]+ if doc.Unavailable != closed {+ t.Fatalf("incorrect availability: %+v", doc)+ }+ for _, detail := range []string{doc.HSize, doc.HMtime, doc.HCtime, doc.Name1, doc.Alias, doc.Memo, doc.Bookmark} {+ if (detail == "") != closed {+ t.Fatalf("incorrect detail for closed=%v: %+v", closed, doc)+ }+ }+ if !closed && (doc.Name1 != attrs["name"] || doc.Alias != attrs["alias"] || doc.Memo != attrs["memo"] || doc.Bookmark != attrs["bookmark"]) {+ t.Fatalf("metadata was lost in response: %+v", doc)+ }+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 8f514f8a03..6d06df94f6 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -152,6 +152,8 @@ var ()var (+ // GetPinnedDocs 按置顶顺序返回普通文档及与文档树一致的大小、属性和时间信息。+ // 关闭笔记本的条目标记 unavailable,详细信息为空;加密笔记本不返回置顶条目。GetPinnedDocs = define[EmptyRequest, []PinnedDoc]("getPinnedDocs", "/api/filetree/getPinnedDocs", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{NonNullable: true}, "POST")UpdatePinnedDocs = define[UpdatePinnedDocsRequest, Null]("updatePinnedDocs", "/api/filetree/updatePinnedDocs", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST"))diff --git a/kernel/apicontract/pinned_docs.go b/kernel/apicontract/pinned_docs.goindex a21efb99d4..e3a2acb8cc 100644--- a/kernel/apicontract/pinned_docs.go+++ b/kernel/apicontract/pinned_docs.go@@ -6,6 +6,13 @@ type PinnedDoc struct {Name string `json:"name"`Path string `json:"path"`Icon string `json:"icon"`+ HSize string `json:"hSize"`+ HMtime string `json:"hMtime"`+ HCtime string `json:"hCtime"`+ Name1 string `json:"name1"`+ Alias string `json:"alias"`+ Memo string `json:"memo"`+ Bookmark string `json:"bookmark"`SubFileCount int `json:"subFileCount"`Unavailable bool `json:"unavailable"`ChildrenSortMode *int `json:"childrenSortMode"`diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex bbc3e1ceee..1eb88268bc 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -35149,6 +35149,12 @@"PinnedDoc": {"type": "object","properties": {+ "alias": {+ "type": "string"+ },+ "bookmark": {+ "type": "string"+ },"childrenSortMode": {"anyOf": [{@@ -35159,15 +35165,30 @@}]},+ "hCtime": {+ "type": "string"+ },+ "hMtime": {+ "type": "string"+ },+ "hSize": {+ "type": "string"+ },"icon": {"type": "string"},"id": {"type": "string"},+ "memo": {+ "type": "string"+ },"name": {"type": "string"},+ "name1": {+ "type": "string"+ },"notebook": {"type": "string"},@@ -35182,10 +35203,17 @@}},"required": [+ "alias",+ "bookmark","childrenSortMode",+ "hCtime",+ "hMtime",+ "hSize","icon","id",+ "memo","name",+ "name1","notebook","path","subFileCount",diff --git a/kernel/model/pinned_docs.go b/kernel/model/pinned_docs.goindex 7e656f5d27..6d4546e5c0 100644--- a/kernel/model/pinned_docs.go+++ b/kernel/model/pinned_docs.go@@ -28,6 +28,8 @@ type pinnedDocsStorage struct {type PinnedDoc struct {ID, Notebook, Name, Path, Icon string+ HSize, HMtime, HCtime string+ Name1, Alias, Memo, Bookmark stringSubFileCount intUnavailable boolChildrenSortMode *int@@ -137,6 +139,8 @@ func GetPinnedDocs() (ret []PinnedDoc, err error) {return nil, fmt.Errorf("cannot read pinned document [%s]", ref.ID)}doc.Name, doc.Path, doc.Icon = file.Name, file.Path, file.Icon+ doc.HSize, doc.HMtime, doc.HCtime = file.HSize, file.HMtime, file.HCtime+ doc.Name1, doc.Alias, doc.Memo, doc.Bookmark = file.Name1, file.Alias, file.Memo, file.Bookmarkdoc.ChildrenSortMode = file.ChildrenSortModeif file.TitleEmpty {doc.Name = Conf.Language(16)diff --git a/kernel/model/pinned_docs_test.go b/kernel/model/pinned_docs_test.goindex 9d13c2ff5f..824c240ed8 100644--- a/kernel/model/pinned_docs_test.go+++ b/kernel/model/pinned_docs_test.go@@ -103,6 +103,61 @@ func TestPinnedDocsValidateAndMaintainReferences(t *testing.T) {}}+func TestPinnedDocsTooltipMetadata(t *testing.T) {+ f := setupFileOperationTest(t)+ for _, id := range []string{f.sourceID, f.box.ID} {+ tree := treenode.NewTree(f.box.ID, "/"+id+".sy", "/Tooltip", "Tooltip")+ t.Cleanup(func() { cache.RemoveTreeData(id); cache.RemoveDocIAL(tree.Path) })+ writeTree := func() {+ t.Helper()+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.UpsertBlockTree(tree)+ cache.RemoveDocIAL(tree.Path)+ }+ writeTree()+ if err := UpdatePinnedDocs([]string{id}, "pin", "", false); err != nil {+ t.Fatal(err)+ }+ for _, suffix := range []string{"before", "after", ""} {+ attrs := map[string]string{"name": suffix, "alias": suffix, "memo": suffix, "bookmark": suffix}+ for key, value := range attrs {+ tree.Root.SetIALAttr(key, value)+ }+ tree.Root.SetIALAttr("updated", "20261017010203")+ writeTree()+ docs, err := GetPinnedDocs()+ if err != nil {+ t.Fatal(err)+ }+ var doc *PinnedDoc+ for i := range docs {+ if docs[i].ID == id {+ doc = &docs[i]+ }+ }+ if doc == nil || doc.HSize == "" || doc.HMtime == "" || doc.HCtime == "" ||+ doc.Name1 != suffix || doc.Alias != suffix || doc.Memo != suffix || doc.Bookmark != suffix {+ t.Fatalf("incomplete pinned metadata for %s: %+v", id, doc)+ }+ if id == f.sourceID {+ files, _, err := ListDocTree(f.box.ID, "/", util.SortModeNameASC, false, false, 100)+ if err != nil {+ t.Fatal(err)+ }+ for _, file := range files {+ if file.ID == id && !reflect.DeepEqual(+ []string{doc.HSize, doc.HMtime, doc.HCtime, doc.Name1, doc.Alias, doc.Memo, doc.Bookmark},+ []string{file.HSize, file.HMtime, file.HCtime, file.Name1, file.Alias, file.Memo, file.Bookmark}) {+ t.Fatalf("pinned metadata differs from source tree: %+v, %+v", doc, file)+ }+ }+ }+ }+ }+}+func TestPinnedDocsClosedAndEncryptedNotebook(t *testing.T) {f := setupFileOperationTest(t)originalLangs := util.Langs@@ -121,6 +176,10 @@ func TestPinnedDocsClosedAndEncryptedNotebook(t *testing.T) {if err != nil || len(docs) != 1 || !docs[0].Unavailable {t.Fatalf("closed notebook lost pin: %+v, %v", docs, err)}+ if docs[0].HSize != "" || docs[0].HMtime != "" || docs[0].HCtime != "" ||+ docs[0].Name1 != "" || docs[0].Alias != "" || docs[0].Memo != "" || docs[0].Bookmark != "" {+ t.Fatalf("closed notebook exposed detailed metadata: %+v", docs[0])+ }boxConf.Encrypted = trueforgetRuntimeNormalBox(f.box.ID)if err := f.box.SaveConf(boxConf); err != nil {