Skip to content

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

:bug: Render document tooltip entities consistently https://github.com/siyuan-note/siyuan/issues/20844

Daniel86a0001f0990
diff --git a/app/src/dialog/tooltipTitles.test.ts b/app/src/dialog/tooltipTitles.test.ts
index 5ad3131e11..462e5a97e7 100644
--- a/app/src/dialog/tooltipTitles.test.ts
+++ b/app/src/dialog/tooltipTitles.test.ts
@@ -7,7 +7,7 @@ import {test} from "node:test";
import {promisify} from "node:util";
import * as ts from "typescript";
-const browserCases = (sources: Record<string, string>) => {
+const browserCases = async (sources: Record<string, string>) => {
const check: typeof assert = require("node:assert/strict");
document.body.innerHTML = "<style>#carrier{width:200px}span{display:inline-block;min-height:20px}</style>" +
'<div id="carrier"></div><div id="tooltip" class="fn__none"></div>';
@@ -27,7 +27,11 @@ const browserCases = (sources: Record<string, string>) => {
getArticle() {}, fetchPost: (_url: string, _data: unknown, callback: (value: unknown) => void) => callback({
data: {pageCount: 1, blocks: [{id: "doc", rootID: "doc", type: "d", hPath, content: "", ial: {}}]},
})};
- }, {BlockDOM2Content: (value: string) => value});
+ }, {BlockDOM2Content: (value: string) => {
+ const content = document.createElement("div");
+ content.innerHTML = value;
+ return content.textContent;
+ }});
modules[name] = exports;
return exports;
};
@@ -37,18 +41,24 @@ const browserCases = (sources: Record<string, string>) => {
const treeModule = load("Tree") as unknown as {Tree: {prototype: object}};
const tree = Object.create(treeModule.Tree.prototype);
tree.titleTooltipPosition = "parentE";
- const search = load("search") as {render: (config: {hPath: string}) => string};
+ const search = load("search") as {render: (config: {hPath: string}) => string, results: (title: string) => string[]};
+ load("config");
+ const searchPath = load("path") as typeof import("../search/path");
const unRef = load("unRef") as typeof import("../search/unRef");
const carrier = document.getElementById("carrier");
const tip = document.getElementById("tooltip");
tooltip.initTooltips();
- for (const title of ["A%2FB", "A%3Ctag%3E.sy", "100%25/Incomplete%2"]) {
- hPath = title;
+ const escape = modules.escape as typeof import("../util/escape");
+ for (const title of ["A%2FB", "A%3Ctag%3E.sy", "100%25/Incomplete%2", "A&copy;B", "A&amp;B",
+ "A&lt;tag&gt;", 'A<tag> & "quotes"', "A&#47;B", "A&#x2f;B"]) {
+ // hPath is derived from escaped IAL attributes; outline content is BlockDOM.
+ hPath = escape.escapeHtmlTextAndAttr(title);
const fragments = [
tree.genHTML([{id: "doc", type: "backlink", depth: 0, name: title, hPath}]),
- tree.genHTML([{id: "doc", type: "outline", depth: 0, name: title}]),
- tree.genBlockHTML([{id: "doc", depth: 0, content: title}], true, "outline"),
+ tree.genHTML([{id: "doc", type: "outline", depth: 0, name: hPath}]),
+ tree.genBlockHTML([{id: "doc", depth: 0, content: hPath}], true, "outline"),
search.render({hPath}),
+ ...search.results(hPath),
];
carrier.innerHTML = '<div id="searchUnRefResult"></div><div id="searchUnRefList"></div>' +
'<div data-type="unRefPrevious"></div><div data-type="unRefNext"></div><div class="fn__loading"></div>';
@@ -58,15 +68,21 @@ const browserCases = (sources: Record<string, string>) => {
carrier.innerHTML = fragment;
const target = carrier.querySelector(".ariaLabel");
check.equal(target.getAttribute("data-tooltip-encoding"), "none");
- check.equal(target.getAttribute("aria-label"), title);
+ check.equal(target.getAttribute("aria-label"), escape.escapeHtmlTextAndAttr(title));
target.dispatchEvent(new PointerEvent("pointerover", {bubbles: true, pointerType: "mouse"}));
target.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
check.equal(tip.textContent, title, fragment);
check.equal(tip.querySelector("tag"), null);
+ if (target.id === "searchPathInput") {
+ await searchPath.refreshCurrentSearchPath({element: carrier, config: {idPath: ["doc"]} as Config.IUILayoutTabSearchConfig,
+ resolveHPath: async () => hPath});
+ target.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ check.equal(tip.textContent, title, "refreshed search path matches the initial tooltip");
+ }
}
mobile = true;
carrier.innerHTML = tree.genHTML([{id: "doc", type: "backlink", depth: 0, name: title, hPath}]);
- check.equal(carrier.querySelector(".ariaLabel").getAttribute("aria-label"), title);
+ check.equal(carrier.querySelector(".ariaLabel").getAttribute("aria-label"), escape.escapeHtmlTextAndAttr(title));
mobile = false;
}
carrier.innerHTML = '<span class="ariaLabel" aria-label="A%2FB">Legacy encoded tooltip</span>';
@@ -75,7 +91,7 @@ const browserCases = (sources: Record<string, string>) => {
return "Title tooltip cases passed";
};
-test("document and heading tooltips preserve percent escapes across trees and search", {
+test("document and heading tooltips preserve percent escapes and entities across trees and search", {
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
timeout: 30000,
}, async () => {
@@ -83,14 +99,19 @@ test("document and heading tooltips preserve percent escapes across trees and se
const compile = (source: string) => ts.transpileModule(source, {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
}).outputText;
- for (const file of ["util/escape", "util/hoverInput", "dialog/tooltip", "util/Tree", "search/unRef"]) {
+ for (const file of ["util/escape", "util/hoverInput", "dialog/tooltip", "util/Tree", "search/unRef", "search/config", "search/path"]) {
sources[file.split("/").pop()] = compile(readFileSync(`src/${file}.ts`, "utf8"));
}
const searchSource = readFileSync("src/search/util.ts", "utf8");
const start = searchSource.indexOf('<span id="searchPathInput"');
const end = searchSource.indexOf("</span>", start) + "</span>".length;
- sources.search = compile('const {escapeAriaLabel, escapeHtml} = require("escape"); exports.render = config => `' +
- searchSource.slice(start, end) + "`;");
+ const resultTemplates = [...searchSource.matchAll(
+ /<span class="b3-list-item__(?:text|meta)[^\n]*aria-label="\$\{escapeHtmlTextAndAttr\(title\)}"[^\n]*<\/span>/g,
+ )];
+ assert.equal(resultTemplates.length, 2);
+ sources.search = compile('const {escapeHtml, escapeHtmlTextAndAttr} = require("escape"); exports.render = config => `' +
+ searchSource.slice(start, end) + "`; exports.results = title => [" +
+ resultTemplates.map(match => "`" + match[0] + "`").join(",") + "];");
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-title-tooltip-test-"));
const script = path.join(temporary, "run.cjs");
writeFileSync(script, `const {app,BrowserWindow}=require("electron");
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index d1b647de19..d2d66f0e6a 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -1,5 +1,5 @@
import {config as configApi} from "../../config/util/configApi";
-import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../util/escape";
+import {escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";
import {genFileTreeDocAriaLabel} from "../../util/fileTreeTooltip";
import {Tab} from "../Tab";
import {Model} from "../Model";
@@ -1323,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", genFileTreeDocAriaLabel(data.data, escapeLessThans));
+ liElement.querySelector(".b3-list-item__text.ariaLabel")?.setAttribute("aria-label", genFileTreeDocAriaLabel(data.data));
}
this.updateSubFileCount(liElement as HTMLElement, subFileCount);
}
@@ -2155,7 +2155,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
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 = genFileTreeDocAriaLabel(item, escapeAriaLabel);
+ const ariaLabel = genFileTreeDocAriaLabel(item, true);
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.ts
index e559a2e122..9e173dd665 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, posix} from "node:path";
+import {join} 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, escapeLessThans, escapeHtmlTextAndAttr} from "../../util/escape";
+import {escapeHtml, escapeHtmlTextAndAttr, escapeTooltipTextAttr} from "../../util/escape";
interface IPanelHarness {
parentDocClick: ParentDocClick;
@@ -66,19 +66,14 @@ 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 escape = {escapeHtml, escapeHtmlTextAndAttr, escapeTooltipTextAttr};
+ runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "../../util/fileTreeTooltip.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText, {exports: tooltip, window: {siyuan: runtime}, require: (name: string) => {
+ if (name.endsWith("/escape")) { return escape; }
+ return {};
+ }});
const menuToggle = {};
runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "../../menus/menuToggle.ts"), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
@@ -707,10 +702,10 @@ test("document info updates every available pinned copy without scheduling anoth
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",
+ const info = {rootID: "document", name: 'A "title" <tag> &copy;', 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" &lt;tag> <small class=\'ft__on-surface\'>2 KB</small><br>Bookmark bookmark &lt;text>' +
+ const expected = "A &quot;title&quot; &lt;tag&gt; &amp;copy; <small class='ft__on-surface'>2 KB</small><br>Bookmark bookmark &lt;text&gt;" +
"<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);
diff --git a/app/src/layout/dock/PinnedDocs.tooltip.test.ts b/app/src/layout/dock/PinnedDocs.tooltip.test.ts
index 8406fd9b65..22998aac7d 100644
--- a/app/src/layout/dock/PinnedDocs.tooltip.test.ts
+++ b/app/src/layout/dock/PinnedDocs.tooltip.test.ts
@@ -37,26 +37,30 @@ const browserCases = async (sources: Record<string, string>) => {
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 regular: {render?: (item: unknown) => string, renderExpanded?: (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 expanded = document.createElement("ul");
+ document.body.append(expanded);
const tip = document.getElementById("tooltip");
tooltip.initTooltips();
- const doc = {id: "doc", notebook: "box", name: 'A//%2F/%3Ctag%3E/Title "quotes" <tag> & text.sy', path: "/doc.sy", subFileCount: 2,
+ const doc = {id: "doc", notebook: "box", name: 'A//%2F/%3Ctag%3E/Title "quotes" <tag> & text &amp; &copy; &lt;tag&gt;.sy', 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);
+ expanded.innerHTML = regular.renderExpanded(doc);
const title = pinned.querySelector(".b3-list-item__text");
check.equal(title.textContent, doc.name);
check.equal(ordinary.querySelector(".b3-list-item__text").textContent, doc.name);
check.equal(title.getAttribute("aria-label"), ordinary.querySelector(".b3-list-item__text").getAttribute("aria-label"));
+ check.equal(title.getAttribute("aria-label"), expanded.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));
@@ -65,6 +69,11 @@ const browserCases = async (sources: Record<string, string>) => {
check.ok(tip.textContent.includes(value), `missing tooltip detail: ${value}`);
}
check.equal(tip.querySelector("img, tag"), null, "metadata remains plain text");
+ expanded.querySelector(".b3-list-item__text").dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ check.ok(tip.textContent.includes(doc.name), "expanded documents preserve the same title");
+ title.setAttribute("aria-label", (helper as typeof import("../../util/fileTreeTooltip")).genFileTreeDocAriaLabel(doc));
+ title.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ check.ok(tip.textContent.includes(doc.name), "dynamic tooltip updates preserve literal entities");
tooltip.hideTooltip();
}
pinned.replaceChildren();
@@ -98,7 +107,11 @@ test("pinned roots and children show the same complete escaped tooltip as ordina
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 pathNameSource = readFileSync("src/util/pathName.ts", "utf8");
+ const start = pathNameSource.indexOf('<span class="b3-list-item__text ariaLabel" data-position="parentE" data-tooltip-encoding');
+ const end = pathNameSource.indexOf("</span>", start) + "</span>".length;
+ sources.regular = compile(`exports.render = function(item) ${method.body.getText(source)};` +
+ "exports.renderExpanded = item => `" + pathNameSource.slice(start, end) + "`;");
const temporary = mkdtempSync(path.join(tmpdir(), "siyuan-pinned-tooltip-test-"));
const script = path.join(temporary, "run.cjs");
writeFileSync(script, `const {app,BrowserWindow}=require("electron");
diff --git a/app/src/layout/dock/PinnedDocs.ts b/app/src/layout/dock/PinnedDocs.ts
index 779225708f..be0545128d 100644
--- a/app/src/layout/dock/PinnedDocs.ts
+++ b/app/src/layout/dock/PinnedDocs.ts
@@ -5,7 +5,7 @@ import {pinnedDocIDs, updatePinnedDocs} from "../../util/pinnedDocs";
import {getPinnedDropPosition} from "../../util/pinnedDocsDrop";
import {getFileTreeIconHTML} from "../../emoji/fileTreeIcon";
import {openEmojiPanel} from "../../emoji";
-import {escapeAriaLabel, escapeHtml, escapeLessThans} from "../../util/escape";
+import {escapeTooltipTextAttr, escapeHtml} from "../../util/escape";
import {genFileTreeDocAriaLabel, type IFileTreeDocTooltip} from "../../util/fileTreeTooltip";
import {initFileMenu} from "../../menus/navigation";
import {toggleMenu} from "../../menus/menuToggle";
@@ -58,7 +58,7 @@ export class PinnedDocs {
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));
+ genFileTreeDocAriaLabel(data.data));
}
});
break;
@@ -335,8 +335,8 @@ 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);
+ const ariaLabel = doc.unavailable || !doc.hSize ? escapeTooltipTextAttr(doc.name +
+ (doc.unavailable ? ` (${window.siyuan.languages.closeNotebook})` : "")) : genFileTreeDocAriaLabel(doc, true);
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" data-tooltip-encoding="none" 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) {
diff --git a/app/src/search/path.ts b/app/src/search/path.ts
index a53e45036a..2fd5e09de1 100644
--- a/app/src/search/path.ts
+++ b/app/src/search/path.ts
@@ -52,8 +52,8 @@ const renderSearchPath = (element: Element, hPath: string) => {
const pathElement = element.querySelector("#searchPathInput");
if (pathElement) {
pathElement.innerHTML = `${escapeHtml(hPath)}<svg class="search__rmpath"><use xlink:href="#iconCloseRound"></use></svg>`;
- // Tooltip 会将 aria-label 作为 HTML 渲染,动态赋值时需要保留一层实体转义。
- pathElement.setAttribute("aria-label", escapeHtml(hPath));
+ // hPath 已包含标题属性的实体转义,setAttribute 不再经过 HTML 属性解析。
+ pathElement.setAttribute("aria-label", hPath);
}
};
diff --git a/app/src/search/unRef.ts b/app/src/search/unRef.ts
index c5ac020584..216410e005 100644
--- a/app/src/search/unRef.ts
+++ b/app/src/search/unRef.ts
@@ -4,7 +4,7 @@ import {fetchPost} from "../util/fetch";
import {setStorageVal} from "../protyle/util/compatibility";
import {getArticle} from "./util";
import {getAttr} from "./attrs";
-import {escapeAriaLabel, escapeLessThans} from "../util/escape";
+import {escapeHtmlTextAndAttr, escapeLessThans} from "../util/escape";
import {getIconByType} from "../editor/getIcon";
import {unicode2Emoji} from "../emoji";
import {getDisplayName, getNotebookName} from "../util/pathName";
@@ -108,13 +108,16 @@ export const getUnRefList = (element: Element, edit: Protyle, page = 1) => {
}
let resultHTML = "";
response.data.blocks.forEach((item: IBlock, index: number) => {
- const title = getNotebookName(item.box) + getDisplayName(item.hPath, false);
+ const notebookName = getNotebookName(item.box);
+ const hPath = getDisplayName(item.hPath, false);
+ const title = notebookName + hPath;
+ const tooltip = escapeHtmlTextAndAttr(notebookName) + hPath;
resultHTML += `<div data-type="search-item" class="b3-list-item${index === 0 ? " b3-list-item--focus" : ""}" data-node-id="${item.id}" data-root-id="${item.rootID}">
<svg class="b3-list-item__graphic"><use xlink:href="#${getIconByType(item.type)}"></use></svg>
${unicode2Emoji(item.ial.icon, "b3-list-item__graphic", true)}
<span class="b3-list-item__text">${item.content}</span>
${getAttr(item)}
-<span class="b3-list-item__meta b3-list-item__meta--ellipsis ariaLabel" data-tooltip-encoding="none" aria-label="${escapeAriaLabel(title)}">${escapeLessThans(title)}</span>
+<span class="b3-list-item__meta b3-list-item__meta--ellipsis ariaLabel" data-tooltip-encoding="none" aria-label="${escapeHtmlTextAndAttr(tooltip)}">${escapeLessThans(title)}</span>
</div>`;
});
if (response.data.blocks.length > 0) {
diff --git a/app/src/search/util.ts b/app/src/search/util.ts
index 2c9bd833d8..4202d8ae7f 100644
--- a/app/src/search/util.ts
+++ b/app/src/search/util.ts
@@ -9,7 +9,7 @@ import {getAllModels} from "../layout/getAll";
import * as path from "path";
/// #endif
import {Constants} from "../constants";
-import {escapeAriaLabel, escapeHtml} from "../util/escape";
+import {escapeHtml, escapeHtmlTextAndAttr} from "../util/escape";
import {fetchPost, fetchSyncPost} from "../util/fetch";
import {openFile, openFileById} from "../editor/util";
import {showMessage} from "../dialog/message";
@@ -157,7 +157,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele
<span id="searchResult" class="fn__flex-shrink ft__selectnone"></span>
<span class="fn__space"></span>
<span class="fn__flex-1${closeCB ? " resize__move" : ""}" style="min-height: 100%"></span>
- <span id="searchPathInput" data-position="9south" data-tooltip-encoding="none" class="search__path ft__on-surface fn__flex-center ft__smaller fn__ellipsis ariaLabel" aria-label="${escapeAriaLabel(escapeHtml(escapeHtml(config.hPath)))}">
+ <span id="searchPathInput" data-position="9south" data-tooltip-encoding="none" class="search__path ft__on-surface fn__flex-center ft__smaller fn__ellipsis ariaLabel" aria-label="${escapeHtmlTextAndAttr(config.hPath)}">
${escapeHtml(config.hPath)}
<svg class="search__rmpath${config.hPath ? "" : " fn__none"}"><use xlink:href="#iconCloseRound"></use></svg>
</span>
@@ -549,7 +549,7 @@ export const genSearch = (app: App, config: Config.IUILayoutTabSearchConfig, ele
config.hPath = hPathList.join(" ");
config.page = 1;
searchPathInputElement.innerHTML = `${escapeHtml(config.hPath)}<svg class="search__rmpath"><use xlink:href="#iconCloseRound"></use></svg>`;
- searchPathInputElement.setAttribute("aria-label", escapeHtml(config.hPath));
+ searchPathInputElement.setAttribute("aria-label", config.hPath);
const includeElement = element.querySelector("#searchInclude");
includeElement.firstElementChild.classList.add("ft__primary");
if (enableIncludeChild) {
@@ -1174,7 +1174,7 @@ export const updateConfig = (element: Element, item: Config.IUILayoutTabSearchCo
const searchPathInputElement = element.querySelector("#searchPathInput");
if (runtimeConfig.hPath) {
searchPathInputElement.innerHTML = `${escapeHtml(runtimeConfig.hPath)}<svg class="search__rmpath"><use xlink:href="#iconCloseRound"></use></svg>`;
- searchPathInputElement.setAttribute("aria-label", escapeHtml(runtimeConfig.hPath));
+ searchPathInputElement.setAttribute("aria-label", runtimeConfig.hPath);
} else {
searchPathInputElement.innerHTML = "";
searchPathInputElement.setAttribute("aria-label", "");
@@ -1648,7 +1648,7 @@ const onSearch = (data: IBlock[], edit: Protyle, element: Element, config: Confi
<svg class="b3-list-item__arrow b3-list-item__arrow--open"><use xlink:href="#iconRight"></use></svg>
</span>
${getFileTreeIconHTML(getNotebookIcon(item.box), "notebook", "b3-list-item__graphic", true)}
-<span class="b3-list-item__text ariaLabel" style="color: var(--b3-theme-on-surface)" aria-label="${escapeAriaLabel(escapeHtml(title))}">${title}</span>
+<span class="b3-list-item__text ariaLabel" style="color: var(--b3-theme-on-surface)" data-tooltip-encoding="none" aria-label="${escapeHtmlTextAndAttr(title)}">${title}</span>
</div><div>`;
item.children.forEach((childItem) => {
if (focusId) {
@@ -1690,7 +1690,7 @@ ${unicode2Emoji(item.ial.icon, "b3-list-item__graphic", true)}
<span class="b3-list-item__text${item.type === "NodeAttributeView" ? " search__av-content" : ""}">${item.content}</span>
${getAttr(item)}
${item.tag ? `<span class="b3-list-item__meta b3-list-item__meta--ellipsis">${item.tag.replace(/#/g, "")}</span>` : ""}
-<span class="b3-list-item__meta b3-list-item__meta--ellipsis ariaLabel" aria-label="${escapeAriaLabel(escapeHtml(title))}">${title}</span>
+<span class="b3-list-item__meta b3-list-item__meta--ellipsis ariaLabel" data-tooltip-encoding="none" aria-label="${escapeHtmlTextAndAttr(title)}">${title}</span>
${countHTML}
</div>`;
}
diff --git a/app/src/util/Tree.ts b/app/src/util/Tree.ts
index a84370f175..78da629e41 100644
--- a/app/src/util/Tree.ts
+++ b/app/src/util/Tree.ts
@@ -2,7 +2,7 @@ import {getIconByType} from "../editor/getIcon";
import {isMobile} from "./functions";
import {mathRender} from "../protyle/render/mathRender";
import {getFileTreeIconHTML} from "../emoji/fileTreeIcon";
-import {escapeAriaLabel, escapeAttr, escapeHtml} from "./escape";
+import {escapeHtmlTextAndAttr, escapeTooltipTextAttr, escapeAttr, escapeHtml} from "./escape";
import {hasClosestByTag} from "../protyle/util/hasClosest";
import {headingNumberNeedsLeadingTrim, headingNumberNeedsSpacing} from "../protyle/util/headingNumberCore";
import {getTreeItemTailHTML} from "./treeItemTail";
@@ -95,10 +95,10 @@ export class Tree {
} else if (item.type === "tag") {
iconHTML = '<svg class="b3-list-item__graphic"><use xlink:href="#iconTag"></use></svg>';
} else if (item.type === "backlink") {
- titleTip = ` data-tooltip-encoding="none" aria-label="${escapeAriaLabel(item.hPath)}"`;
+ titleTip = ` data-tooltip-encoding="none" aria-label="${escapeHtmlTextAndAttr(item.hPath || "")}"`;
iconHTML = `<svg class="b3-list-item__graphic popover__block" data-id="${item.id}"><use xlink:href="#${getIconByType(item.nodeType, item.subType)}"></use></svg>`;
} else if (item.type === "outline") {
- titleTip = ` data-tooltip-encoding="none" aria-label="${escapeAriaLabel(Lute.BlockDOM2Content(item.name))}"`;
+ titleTip = ` data-tooltip-encoding="none" aria-label="${escapeTooltipTextAttr(Lute.BlockDOM2Content(item.name))}"`;
iconHTML = `<svg class="b3-list-item__graphic popover__block" data-id="${item.id}" style="height: ${isM ? 16 : 22}px;width: 16px;"><use xlink:href="#${getIconByType(item.nodeType, item.subType)}"></use></svg>`;
}
let countHTML = "";
@@ -191,7 +191,7 @@ data-def-path="${item.defPath}">
</span>
${iconHTML}
${numberHTML}
- <span class="b3-list-item__text ariaLabel" data-position="${this.titleTooltipPosition}" ${type === "outline" ? ' data-tooltip-encoding="none" aria-label="' + escapeAriaLabel(Lute.BlockDOM2Content(item.content)) + '"' : ""}>${item.content}</span>
+ <span class="b3-list-item__text ariaLabel" data-position="${this.titleTooltipPosition}" ${type === "outline" ? ' data-tooltip-encoding="none" aria-label="' + escapeTooltipTextAttr(Lute.BlockDOM2Content(item.content)) + '"' : ""}>${item.content}</span>
${getTreeItemTailHTML(countHTML, this.blockExtHTML || "", isM)}
</li>`;
if (item.children && item.children.length > 0) {
diff --git a/app/src/util/escape.ts b/app/src/util/escape.ts
index 5bd9728cf3..3a74fd104e 100644
--- a/app/src/util/escape.ts
+++ b/app/src/util/escape.ts
@@ -3,6 +3,10 @@ export const escapeHtmlTextAndAttr = (html: unknown) => {
return String(html).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
};
+// 纯文本写入 HTML 模板中的提示属性,需分别保护属性解析及提示框的 innerHTML 解析。
+// 已转义的 hPath 只需 escapeHtmlTextAndAttr;setAttribute 接受的提示 HTML 不再转义属性层。
+export const escapeTooltipTextAttr = (text: string) => escapeHtmlTextAndAttr(escapeHtmlTextAndAttr(text));
+
export const escapeHtml = (html: string) => {
if (!html) {
return html;
diff --git a/app/src/util/fileTreeTooltip.ts b/app/src/util/fileTreeTooltip.ts
index c5782a4d26..61a3a8e677 100644
--- a/app/src/util/fileTreeTooltip.ts
+++ b/app/src/util/fileTreeTooltip.ts
@@ -1,8 +1,12 @@
-import {getDocDisplayName} from "./pathName";
+import {escapeHtmlTextAndAttr} from "./escape";
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}`;
+// 返回提示 HTML;用于 HTML 模板的属性时,额外转义整个属性,动态 setAttribute 则直接使用。
+export const genFileTreeDocAriaLabel = (item: IFileTreeDocTooltip, htmlAttribute = false) => {
+ const escapeMethod = escapeHtmlTextAndAttr;
+ const name = item.titleEmpty ? window.siyuan.languages._kernel[16] : item.name;
+ const label = `${escapeMethod(name)} <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}`;
+ return htmlAttribute ? escapeHtmlTextAndAttr(label) : label;
};
diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.ts
index 9f77edb9ad..6493638e5f 100644
--- a/app/src/util/pathName.ts
+++ b/app/src/util/pathName.ts
@@ -3,6 +3,7 @@ import * as path from "path";
import {fetchPost} from "./fetch";
import {Dialog} from "../dialog";
import {escapeAriaLabel, escapeHtml, escapeHtmlTextAndAttr} from "./escape";
+import {genFileTreeDocAriaLabel} from "./fileTreeTooltip";
import {isMobile} from "./functions";
import {focusByRange} from "../protyle/util/selectionOffsets";
import {Constants} from "../constants";
@@ -789,7 +790,7 @@ const getLeaf = (liElement: HTMLElement, flashcard: boolean) => {
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
</span>
${getFileTreeIconHTML(item.icon, defaultIcon, "b3-list-item__graphic", true)}
- <span class="b3-list-item__text ariaLabel" data-position="parentE" data-tooltip-encoding="none" aria-label="${getDocDisplayName(item.name, item.titleEmpty, true)} <small class='ft__on-surface'>${item.hSize}</small>${item.bookmark ? "<br>" + window.siyuan.languages.bookmark + " " + escapeAriaLabel(item.bookmark) : ""}${item.name1 ? "<br>" + window.siyuan.languages.name + " " + escapeAriaLabel(item.name1) : ""}${item.alias ? "<br>" + window.siyuan.languages.alias + " " + escapeAriaLabel(item.alias) : ""}${item.memo ? "<br>" + window.siyuan.languages.memo + " " + escapeAriaLabel(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}">${getDocDisplayName(item.name, item.titleEmpty, true)}</span>
+ <span class="b3-list-item__text ariaLabel" data-position="parentE" data-tooltip-encoding="none" aria-label="${genFileTreeDocAriaLabel(item, true)}">${getDocDisplayName(item.name, item.titleEmpty, true)}</span>
${countHTML}
</li>`;
});