Skip to content

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

:recycle: Use native frontend HTML escaping https://github.com/siyuan-note/siyuan/issues/20037

Danield91ad295a531
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.ts
index 774717f4f2..c0d7ba9033 100644
--- a/app/src/asset/anno.ts
+++ b/app/src/asset/anno.ts
@@ -9,7 +9,7 @@ import {Dialog} from "../dialog";
import {showMessage} from "../dialog/message";
import {isMobile} from "../util/functions";
import {confirmDialog} from "../dialog/confirmDialog";
-import {escapeAttr, escapeHtml} from "../util/escape";
+import {escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../util/escape";
import {filesize} from "filesize";
import md5 from "blueimp-md5";
import {getRectImageName, hideRectResizeHandles, moveRectBounds, resizeRectBounds} from "./rectAnnotationResize";
@@ -725,7 +725,7 @@ const getHightlightCoordsByRange = (pdf: any, color: string) => {
}
});
// eslint-disable-next-line no-control-regex
- const content = Lute.EscapeHTMLStr(rangeContents.textContent.replace(/[\x00]|\n/g, ""));
+ const content = escapeHtmlTextAndAttr(rangeContents.textContent.replace(/[\x00]|\n/g, ""));
const startPage = pdf.pdfViewer.getPageView(startIndex);
const startPageRect = startPage.canvas.getClientRects()[0];
const startViewport = startPage.viewport;
diff --git a/app/src/asset/index.ts b/app/src/asset/index.ts
index 2f4fdf92df..e80ce70ad0 100644
--- a/app/src/asset/index.ts
+++ b/app/src/asset/index.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../util/escape";
import {Model} from "../layout/Model";
import {Tab} from "../layout/Tab";
import {Constants} from "../constants";
@@ -110,7 +111,7 @@ export class Asset extends Model {
}
const type = this.path.substr(this.path.lastIndexOf(".")).toLowerCase().split("?")[0];
// 对资源路径进行 HTML 转义后再拼入 src 属性,避免路径中包含 " 等字符导致属性逃逸引发 XSS
- const src = Lute.EscapeHTMLStr(this.path.startsWith("file") ? this.path : document.getElementById("baseURL").getAttribute("href") + "/" + this.path);
+ const src = escapeHtmlTextAndAttr(this.path.startsWith("file") ? this.path : document.getElementById("baseURL").getAttribute("href") + "/" + this.path);
if (Constants.SIYUAN_ASSETS_IMAGE.includes(type)) {
this.element.innerHTML = `<div class="asset"><img src="${src}"></div>`;
} else if (Constants.SIYUAN_ASSETS_AUDIO.includes(type)) {
diff --git a/app/src/block/popover.ts b/app/src/block/popover.ts
index 0eff8bb8da..a70ecc0fb2 100644
--- a/app/src/block/popover.ts
+++ b/app/src/block/popover.ts
@@ -12,7 +12,7 @@ import {
shouldMeasureAVCellContentOverflow,
} from "../protyle/render/av/cellOverflow";
import {isTouchDevice} from "../util/functions";
-import {escapeAriaLabel, escapeHtml, escapeLessThans} from "../util/escape";
+import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../util/escape";
import {isListItemActionElement} from "../protyle/wysiwyg/listContext";
import {getImageTooltip} from "../protyle/render/imageTooltip";
/// #if !MOBILE
@@ -151,7 +151,7 @@ export const initBlockPopover = (app: App) => {
} else {
if (aElement.firstElementChild?.getAttribute("data-type") === "url") {
if (aElement.firstElementChild.textContent.indexOf("...") > -1) {
- tip = Lute.EscapeHTMLStr(aElement.firstElementChild.getAttribute("data-href"));
+ tip = escapeHtmlTextAndAttr(aElement.firstElementChild.getAttribute("data-href"));
tooltipClass = "href";
}
}
@@ -162,7 +162,7 @@ export const initBlockPopover = (app: App) => {
!hasClosestByClassName(event.target, "block__icon")) {
aElement.style.overflow = "auto";
if (hasAVCellContentOverflow(aElement, richTextElement)) {
- tip = Lute.EscapeHTMLStr(getCellText(aElement));
+ tip = escapeHtmlTextAndAttr(getCellText(aElement));
}
aElement.style.overflow = "";
}
@@ -189,7 +189,7 @@ export const initBlockPopover = (app: App) => {
const textElement = cellElement?.querySelector(".b3-menu__label, .av__celltext") as HTMLElement;
if (cellElement && (cellElement.clientWidth + 0.5 < cellElement.scrollWidth ||
(textElement && textElement.clientWidth + 0.5 < textElement.scrollWidth))) {
- tip = Lute.EscapeHTMLStr(cellElement.querySelector(".b3-menu__label")?.textContent ||
+ tip = escapeHtmlTextAndAttr(cellElement.querySelector(".b3-menu__label")?.textContent ||
getCellText(cellElement));
tooltipTarget = cellElement;
tooltipPositionOverride = "north";
diff --git a/app/src/config/render/render.ts b/app/src/config/render/render.ts
index 74ca9deaae..55e9252d32 100644
--- a/app/src/config/render/render.ts
+++ b/app/src/config/render/render.ts
@@ -9,7 +9,7 @@ import {
type StackRight,
type SwitchQueryItem
} from "./parts";
-import {escapeHTMLStr, escapeAttr} from "../../util/escape";
+import {escapeHtmlTextAndAttr, escapeAttr} from "../../util/escape";
import {buildRangeValues} from "../setting/domIO";
import {genConfigItemMainHtml, genConfigItemName, genSwitchRow} from "./fragments";
@@ -69,15 +69,15 @@ const genTextBlockFieldHtml = (
spellcheck = window.siyuan.config.editor.spellcheck,
): string => {
if (mode === "textarea") {
- return `<textarea class="b3-text-field fn__block" id="${id}" spellcheck="${spellcheck}">${escapeHTMLStr(value)}</textarea>`;
+ return `<textarea class="b3-text-field fn__block" id="${id}" spellcheck="${spellcheck}">${escapeHtmlTextAndAttr(value)}</textarea>`;
}
if (mode === "input-password") {
return `<div class="b3-form__icona fn__block">
- <input id="${id}" type="password" spellcheck="false" class="b3-text-field b3-form__icona-input" value="${escapeHTMLStr(value)}">
+ <input id="${id}" type="password" spellcheck="false" class="b3-text-field b3-form__icona-input" value="${escapeHtmlTextAndAttr(value)}">
<svg class="b3-form__icona-icon" data-action="togglePassword" style="user-select: none;"><use xlink:href="#iconEye"></use></svg>
</div>`;
}
- return `<input class="b3-text-field fn__block" id="${id}" type="text" spellcheck="${spellcheck}" value="${escapeHTMLStr(value)}"/>`;
+ return `<input class="b3-text-field fn__block" id="${id}" type="text" spellcheck="${spellcheck}" value="${escapeHtmlTextAndAttr(value)}"/>`;
};
const genSwitchQueryItemHtml = (item: SwitchQueryItem): string => {
@@ -133,9 +133,9 @@ export const genTextPairHtml = (
`<div class="fn__flex b3-label config-item">
${genConfigItemMainHtml(title, desc)}
<span class="fn__space"></span>
- <input class="b3-text-field fn__flex-center fn__size96" id="${left.id}" value="${escapeHTMLStr(left.readConfig() as string)}">
+ <input class="b3-text-field fn__flex-center fn__size96" id="${left.id}" value="${escapeHtmlTextAndAttr(left.readConfig() as string)}">
<span class="fn__space"></span>
- <input class="b3-text-field fn__flex-center fn__size96" id="${right.id}" value="${escapeHTMLStr(right.readConfig() as string)}">
+ <input class="b3-text-field fn__flex-center fn__size96" id="${right.id}" value="${escapeHtmlTextAndAttr(right.readConfig() as string)}">
</div>`;
const genStackRight = (r: StackRight): string => {
@@ -230,7 +230,7 @@ const renderControlParts = (parts: RowPart[]): string => {
return `<div class="fn__flex b3-label config-item">
${genConfigItemMainHtml(title, desc ?? "")}
<span class="fn__space"></span>
- <input class="b3-text-field fn__flex-center fn__size200" id="${control.id}"${control.spellcheck === undefined ? "" : ` spellcheck="${control.spellcheck}"`} value="${escapeHTMLStr(control.readConfig() as string)}"/>
+ <input class="b3-text-field fn__flex-center fn__size200" id="${control.id}"${control.spellcheck === undefined ? "" : ` spellcheck="${control.spellcheck}"`} value="${escapeHtmlTextAndAttr(control.readConfig() as string)}"/>
</div>`;
case "textBlock": {
return `<div class="b3-label config-item">
diff --git a/app/src/config/tabs/accessRuntime.ts b/app/src/config/tabs/accessRuntime.ts
index a79ab513bb..87abb80656 100644
--- a/app/src/config/tabs/accessRuntime.ts
+++ b/app/src/config/tabs/accessRuntime.ts
@@ -1,4 +1,4 @@
-import {escapeHTMLStr} from "../../util/escape";
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import {fetchPost} from "../../util/fetch";
import {isMobile} from "../../util/functions";
@@ -94,14 +94,14 @@ export const renderPublishAuthAccounts = () => {
: '<span data-action="remove" class="block__icon block__icon--show"><svg><use xlink:href="#iconTrashcan"></use></svg></span>';
const listItemHtml = window.siyuan.config.publish.auth.accounts.map((account, index) => `
<li class="b3-label b3-label--inner fn__flex" data-index="${index}">
- <input class="b3-text-field fn__block" data-name="username" value="${escapeHTMLStr(account.username)}" placeholder="${window.siyuan.languages.userName}">
+ <input class="b3-text-field fn__block" data-name="username" value="${escapeHtmlTextAndAttr(account.username)}" placeholder="${window.siyuan.languages.userName}">
<span class="fn__space"></span>
<div class="b3-form__icona fn__block">
- <input class="b3-text-field fn__block b3-form__icona-input" type="password" data-name="password" value="${escapeHTMLStr(account.password)}" placeholder="${window.siyuan.languages.password}">
+ <input class="b3-text-field fn__block b3-form__icona-input" type="password" data-name="password" value="${escapeHtmlTextAndAttr(account.password)}" placeholder="${window.siyuan.languages.password}">
<svg class="b3-form__icona-icon" data-action="togglePassword"><use xlink:href="#iconEye"></use></svg>
</div>
<span class="fn__space"></span>
- <input class="b3-text-field fn__block" data-name="memo" value="${escapeHTMLStr(account.memo)}" placeholder="${window.siyuan.languages.memo}">
+ <input class="b3-text-field fn__block" data-name="memo" value="${escapeHtmlTextAndAttr(account.memo)}" placeholder="${window.siyuan.languages.memo}">
<span class="fn__space"></span>
${removeButtonHtml}
</li>`).join("");
@@ -117,7 +117,7 @@ export const sendAccessSetting = (controlId: string, value: unknown) => {
window.siyuan.config.api.token = token;
const tokenTipEl = accessTabElement?.querySelector(`#${CSS.escape("api.token")}`)?.closest(".config-item")?.querySelector(".b3-label__text");
if (tokenTipEl) {
- tokenTipEl.innerHTML = window.siyuan.languages.about14.replace("${token}", escapeHTMLStr(token));
+ tokenTipEl.innerHTML = window.siyuan.languages.about14.replace("${token}", escapeHtmlTextAndAttr(token));
}
});
break;
diff --git a/app/src/config/tabs/accessTab.ts b/app/src/config/tabs/accessTab.ts
index 5c60c3a056..5d55da54cb 100644
--- a/app/src/config/tabs/accessTab.ts
+++ b/app/src/config/tabs/accessTab.ts
@@ -1,4 +1,4 @@
-import {escapeHTMLStr} from "../../util/escape";
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import type {SettingTabBuilder} from "../setting/builder";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import {ContractFormData} from "../../util/contractFormData";
@@ -102,7 +102,7 @@ const mountOIDCButton = (root: HTMLElement) => {
}
root.querySelector("#oidcConfig")?.addEventListener("click", () => {
const config = window.siyuan.config.oidc;
- const escape = (value: string) => escapeHTMLStr(value);
+ const escape = (value: string) => escapeHtmlTextAndAttr(value);
let destroyOIDCDialog: () => void = () => undefined;
const dialog = new Dialog({
title: window.siyuan.languages.oidcLogin,
diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.ts
index c67d77c4e7..813f5a578b 100644
--- a/app/src/config/tabs/ai/aiProviderUi.ts
+++ b/app/src/config/tabs/ai/aiProviderUi.ts
@@ -1,4 +1,4 @@
-import {escapeHTMLStr} from "../../../util/escape";
+import {escapeHtmlTextAndAttr} from "../../../util/escape";
import type {AIModelTestData} from "../../../types/api";
import {bindPasswordIconaToggle, genConfigItemMainHtml} from "../../render/fragments";
import {confirmDialog} from "../../../dialog/confirmDialog";
@@ -33,7 +33,7 @@ export interface IGroupedModelPicker {
const PROVIDER_CATEGORIES = ["official", "aggregator", "local", "custom"] as const;
-const escapeHTML = (value: string) => escapeHTMLStr(value ?? "");
+const escapeHTML = (value: string) => escapeHtmlTextAndAttr(value ?? "");
const cloneProvider = (provider: Config.IProvider): Config.IProvider =>
JSON.parse(JSON.stringify(provider)) as Config.IProvider;
diff --git a/app/src/config/tabs/ai/aiUi.ts b/app/src/config/tabs/ai/aiUi.ts
index 4c128eba1a..d36d7c9d55 100644
--- a/app/src/config/tabs/ai/aiUi.ts
+++ b/app/src/config/tabs/ai/aiUi.ts
@@ -4,7 +4,7 @@ import {showMessage} from "../../../dialog/message";
import {Constants} from "../../../constants";
import {isMobile} from "../../../util/functions";
import {fetchPost} from "../../../util/fetch";
-import {escapeHTMLStr, escapeHtml} from "../../../util/escape";
+import {escapeHtmlTextAndAttr, escapeHtml} from "../../../util/escape";
import {aiConfigApi} from "./aiRuntime";
import {openByMobile} from "../../../editor/openLink";
import {canOpenExternalURL} from "../../../util/hostCapabilities";
@@ -361,7 +361,7 @@ export const getModelPickerKeywords = (group: ModelPickerGroup): string[] => {
const showDeleteConfirm = (title: string, onConfirm: () => void) => {
confirmDialog(
window.siyuan.languages.deleteOpConfirm,
- window.siyuan.languages.confirmDeleteTip.replace("${x}", escapeHTMLStr(title)),
+ window.siyuan.languages.confirmDeleteTip.replace("${x}", escapeHtmlTextAndAttr(title)),
onConfirm,
undefined,
true,
@@ -423,7 +423,7 @@ const mountAddMcpServerButton = (root: HTMLElement, block: HTMLElement) => {
groupTitle.insertAdjacentHTML("beforeend", `<span class="fn__flex-1"></span>
<button class="b3-button b3-button--outline fn__flex-center fn__size200" data-type="addAiMcpServer">
<svg class="b3-button__icon"><use xlink:href="#iconAdd"></use></svg>
- <span>${escapeHTMLStr(window.siyuan.languages.addAiMcpServer)}</span>
+ <span>${escapeHtmlTextAndAttr(window.siyuan.languages.addAiMcpServer)}</span>
</button>`);
(groupTitle.lastElementChild as HTMLButtonElement).addEventListener("click", (event) => {
openMcpServerDialog(root, null);
@@ -643,14 +643,14 @@ const renderMcpServerList = (root: HTMLElement) => {
return;
}
const serversHtml = servers.map((server) => {
- return `<div class="b3-list-item b3-list-item--narrow${hideActionClass}" data-type="aiMcpServer" data-mcp-server-id="${escapeHTMLStr(server.id)}" data-mcp-server-name="${escapeHTMLStr(server.name)}">
- <span class="mcp-status-dot b3-tooltips b3-tooltips__n" data-mcp-status-id="${escapeHTMLStr(server.id)}" aria-label="${server.enabled ? window.siyuan.languages.mcpStatusConnecting : window.siyuan.languages.mcpStatusDisabled}" style="display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex-shrink:0;margin-right:4px;"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background-color:${server.enabled ? "#d97706" : "var(--b3-theme-on-surface-light)"};"></span></span>
- <span class="b3-list-item__text">${escapeHTMLStr(server.name)}</span>
- <span class="ft__on-surface fn__flex-center" data-mcp-tools-count="${escapeHTMLStr(server.id)}" style="font-size:12px;margin-right:8px;"></span>
- <span data-type="authorizeAiMcpServer" data-mcp-authorize-id="${escapeHTMLStr(server.id)}" class="fn__none b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.mcpAuthorize}">
+ return `<div class="b3-list-item b3-list-item--narrow${hideActionClass}" data-type="aiMcpServer" data-mcp-server-id="${escapeHtmlTextAndAttr(server.id)}" data-mcp-server-name="${escapeHtmlTextAndAttr(server.name)}">
+ <span class="mcp-status-dot b3-tooltips b3-tooltips__n" data-mcp-status-id="${escapeHtmlTextAndAttr(server.id)}" aria-label="${server.enabled ? window.siyuan.languages.mcpStatusConnecting : window.siyuan.languages.mcpStatusDisabled}" style="display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex-shrink:0;margin-right:4px;"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background-color:${server.enabled ? "#d97706" : "var(--b3-theme-on-surface-light)"};"></span></span>
+ <span class="b3-list-item__text">${escapeHtmlTextAndAttr(server.name)}</span>
+ <span class="ft__on-surface fn__flex-center" data-mcp-tools-count="${escapeHtmlTextAndAttr(server.id)}" style="font-size:12px;margin-right:8px;"></span>
+ <span data-type="authorizeAiMcpServer" data-mcp-authorize-id="${escapeHtmlTextAndAttr(server.id)}" class="fn__none b3-list-item__action b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.mcpAuthorize}">
<svg><use xlink:href="#iconKey"></use></svg>
</span>
- <span data-type="disconnectAiMcpOAuth" data-mcp-disconnect-oauth-id="${escapeHTMLStr(server.id)}" class="fn__none b3-list-item__action b3-list-item__action--warning b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.mcpDisconnectAuthorization}">
+ <span data-type="disconnectAiMcpOAuth" data-mcp-disconnect-oauth-id="${escapeHtmlTextAndAttr(server.id)}" class="fn__none b3-list-item__action b3-list-item__action--warning b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.mcpDisconnectAuthorization}">
<svg><use xlink:href="#iconLinkOff"></use></svg>
</span>
<span data-type="deleteAiMcpServer" class="b3-list-item__action b3-list-item__action--warning b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.delete}">
@@ -703,11 +703,11 @@ const renderEnvironmentVariableOptions = (availableNames: string[], selectedName
? `<span class="b3-list-item__meta">${window.siyuan.languages.aiMcpEnvSensitive}</span>`
: "")
: `<span class="b3-list-item__meta">${window.siyuan.languages.aiMcpEnvUnavailable}</span>`;
- return `<label class="b3-list-item b3-list-item--narrow" data-mcp-env-option="${escapeHTMLStr(name)}">
- <span class="b3-list-item__text">${escapeHTMLStr(name)}</span>
+ return `<label class="b3-list-item b3-list-item--narrow" data-mcp-env-option="${escapeHtmlTextAndAttr(name)}">
+ <span class="b3-list-item__text">${escapeHtmlTextAndAttr(name)}</span>
${status}
<span class="fn__space--small"></span>
- <input class="b3-switch" type="checkbox" aria-label="${escapeHTMLStr(name)}" data-mcp-inherit-env="${escapeHTMLStr(name)}"${selected.has(key) ? " checked" : ""}>
+ <input class="b3-switch" type="checkbox" aria-label="${escapeHtmlTextAndAttr(name)}" data-mcp-inherit-env="${escapeHtmlTextAndAttr(name)}"${selected.has(key) ? " checked" : ""}>
</label>`;
}).join("");
};
@@ -731,9 +731,9 @@ const parseStringRecord = (value: string, invalidMessage: string): Record<string
const renderMcpEnvironmentRow = (name = "", value = "") => `<div data-mcp-env-row>
<div class="fn__flex">
- <input class="b3-text-field fn__flex-1" data-mcp-env-name type="text" spellcheck="false" placeholder="NAME" value="${escapeHTMLStr(name)}">
+ <input class="b3-text-field fn__flex-1" data-mcp-env-name type="text" spellcheck="false" placeholder="NAME" value="${escapeHtmlTextAndAttr(name)}">
<span class="fn__space"></span>
- <input class="b3-text-field fn__flex-1" data-mcp-env-value type="text" spellcheck="false" placeholder="{{secrets.NAME}}" value="${escapeHTMLStr(value)}">
+ <input class="b3-text-field fn__flex-1" data-mcp-env-value type="text" spellcheck="false" placeholder="{{secrets.NAME}}" value="${escapeHtmlTextAndAttr(value)}">
<span class="fn__space--small"></span>
<button class="block__icon block__icon--show block__icon--warning" data-type="deleteMcpEnvironmentVariable" type="button" aria-label="${window.siyuan.languages.delete}">
<svg><use xlink:href="#iconTrashcan"></use></svg>
@@ -807,7 +807,7 @@ const openMcpServerDialogWithEnvironment = (root: HTMLElement, serverName: strin
<div class="config-name">${window.siyuan.languages.aiMcpServerName}</div>
<div class="b3-label__text">${window.siyuan.languages.aiMcpServerNameTip}</div>
<div class="fn__hr"></div>
- <input class="b3-text-field fn__block" id="aiMcpServerName" type="text" spellcheck="false" value="${escapeHTMLStr(initialServer.name)}"/>
+ <input class="b3-text-field fn__block" id="aiMcpServerName" type="text" spellcheck="false" value="${escapeHtmlTextAndAttr(initialServer.name)}"/>
</div>
<div class="b3-label b3-label--inner">
<div class="config-name">${window.siyuan.languages.connectionType}</div>
@@ -821,13 +821,13 @@ const openMcpServerDialogWithEnvironment = (root: HTMLElement, serverName: strin
<div class="config-name">${window.siyuan.languages.command}</div>
<div class="b3-label__text">${window.siyuan.languages.aiMcpCommandTip}</div>
<div class="fn__hr"></div>
- <input class="b3-text-field fn__block" id="aiMcpServerCommand" type="text" spellcheck="false" value="${escapeHTMLStr(initialServer.command)}"/>
+ <input class="b3-text-field fn__block" id="aiMcpServerCommand" type="text" spellcheck="false" value="${escapeHtmlTextAndAttr(initialServer.command)}"/>
</div>
<div class="b3-label b3-label--inner${mcpTypeHidden("stdio")}" data-mcp-type="stdio">
<div class="config-name">${window.siyuan.languages.args}</div>
<div class="b3-label__text">${window.siyuan.languages.aiMcpArgsTip}</div>
<div class="fn__hr"></div>
- <textarea spellcheck="false" class="b3-text-field fn__block" id="aiMcpServerArgs" rows="4" style="resize: vertical;">${escapeHTMLStr(argsText)}</textarea>
+ <textarea spellcheck="false" class="b3-text-field fn__block" id="aiMcpServerArgs" rows="4" style="resize: vertical;">${escapeHtmlTextAndAttr(argsText)}</textarea>
</div>
<div class="b3-label b3-label--inner${mcpTypeHidden("stdio")}" data-mcp-type="stdio">
<div class="config-name">${window.siyuan.languages.aiMcpInheritEnv}</div>
@@ -855,13 +855,13 @@ const openMcpServerDialogWithEnvironment = (root: HTMLElement, serverName: strin
<div class="config-name">URL</div>
<div class="b3-label__text">${window.siyuan.languages.aiMcpUrlTip}</div>
<div class="fn__hr"></div>
- <input class="b3-text-field fn__block" id="aiMcpServerUrl" type="text" spellcheck="false" value="${escapeHTMLStr(initialServer.url)}"/>
+ <input class="b3-text-field fn__block" id="aiMcpServerUrl" type="text" spellcheck="false" value="${escapeHtmlTextAndAttr(initialServer.url)}"/>
</div>
<div class="b3-label b3-label--inner${mcpTypeHidden("http")}" data-mcp-type="http">
<div class="config-name">${window.siyuan.languages.aiMcpHttpHeaders}</div>
<div class="b3-label__text">${window.siyuan.languages.fillJsonObject}</div>
<div class="fn__hr"></div>
- <textarea spellcheck="false" class="b3-text-field fn__block" id="aiMcpServerHeaders" rows="3" style="resize: vertical;" placeholder='{"Authorization":"Bearer ..."}'>${escapeHTMLStr(headersText)}</textarea>
+ <textarea spellcheck="false" class="b3-text-field fn__block" id="aiMcpServerHeaders" rows="3" style="resize: vertical;" placeholder='{"Authorization":"Bearer ..."}'>${escapeHtmlTextAndAttr(headersText)}</textarea>
</div>
<div class="b3-label b3-label--inner fn__flex${mcpTypeHidden("http")}" data-mcp-type="http">
<div class="fn__flex-1">
diff --git a/app/src/config/tabs/ai/mcpOAuthUi.ts b/app/src/config/tabs/ai/mcpOAuthUi.ts
index 7c6e1191f9..0e43aff3c4 100644
--- a/app/src/config/tabs/ai/mcpOAuthUi.ts
+++ b/app/src/config/tabs/ai/mcpOAuthUi.ts
@@ -1,4 +1,4 @@
-import {escapeHTMLStr} from "../../../util/escape";
+import {escapeHtmlTextAndAttr} from "../../../util/escape";
import {fetchSyncPost} from "../../../util/fetch";
import {showMessage} from "../../../dialog/message";
@@ -10,7 +10,7 @@ export const mountMcpOAuth = (root: HTMLElement) => {
return;
}
const lang = window.siyuan.languages;
- const escape = escapeHTMLStr;
+ const escape = escapeHtmlTextAndAttr;
const input = (field: string, label: string, value = "", readonly = false) =>
`<label class="fn__block">${escape(label)}<input class="b3-text-field fn__block" data-field="${field}" value="${escape(value)}" ${readonly ? "readonly" : ""} spellcheck="false"></label><div class="fn__hr"></div>`;
diff --git a/app/src/config/tabs/appTab.ts b/app/src/config/tabs/appTab.ts
index 0f98f7029a..bfaba73e86 100644
--- a/app/src/config/tabs/appTab.ts
+++ b/app/src/config/tabs/appTab.ts
@@ -22,7 +22,7 @@ import {Dialog} from "../../dialog";
import {openInputDialog} from "../../dialog/inputDialog";
import {isInMobileApp} from "../../protyle/util/compatibility";
import {pathPosix} from "../../util/pathName";
-import {escapeHTMLStr, escapeAttr, escapeHtml} from "../../util/escape";
+import {escapeHtmlTextAndAttr, escapeAttr, escapeHtml} from "../../util/escape";
/// #endif
/// #if !BROWSER
import {afterExport} from "../../protyle/export/util";
@@ -365,9 +365,9 @@ const genNetworkProxyHtml = (): string => {
<option value="http" ${proxy.scheme === "http" ? "selected" : ""}>HTTP</option>
</select>
<span class="fn__space"></span>
- <input spellcheck="false" id="networkProxyHost" placeholder="user:pass@IP" class="b3-text-field fn__flex-1" value="${escapeHTMLStr(proxy.host)}"/>
+ <input spellcheck="false" id="networkProxyHost" placeholder="user:pass@IP" class="b3-text-field fn__flex-1" value="${escapeHtmlTextAndAttr(proxy.host)}"/>
<span class="fn__space"></span>
- <input id="networkProxyPort" placeholder="Port" class="b3-text-field fn__flex-1" value="${escapeHTMLStr(proxy.port)}" type="number"/>
+ <input id="networkProxyPort" placeholder="Port" class="b3-text-field fn__flex-1" value="${escapeHtmlTextAndAttr(proxy.port)}" type="number"/>
<span class="fn__space"></span>
<button id="networkProxyConfirm" class="b3-button fn__size200 b3-button--outline">${window.siyuan.languages.confirm}</button>
</div>
diff --git a/app/src/config/tabs/exportTab.ts b/app/src/config/tabs/exportTab.ts
index 90a9ff3614..3ead0bb51e 100644
--- a/app/src/config/tabs/exportTab.ts
+++ b/app/src/config/tabs/exportTab.ts
@@ -1,4 +1,4 @@
-import {escapeHTMLStr} from "../../util/escape";
+import {escapeHtmlTextAndAttr} from "../../util/escape";
/// #if !BROWSER
import {ipcRenderer} from "electron";
import {useShell} from "../../util/pathName";
@@ -149,7 +149,7 @@ const registerExportPandocGroup = (tab: SettingTabBuilder) => {
afterMount: mountExportPandocStack,
}, (stack) => {
const pandocBinLabel = window.siyuan.config.export.pandocBin ?
- escapeHTMLStr(window.siyuan.config.export.pandocBin) : `${window.siyuan.languages.builtIn} Pandoc`;
+ escapeHtmlTextAndAttr(window.siyuan.config.export.pandocBin) : `${window.siyuan.languages.builtIn} Pandoc`;
stack.title(`${window.siyuan.languages.export19}<span class="fn__space"></span><a href="javascript:void(0)" id="pandocBinPathDisplay" style="word-break: break-all">${pandocBinLabel}</a>`);
stack.button({
id: "pandocBinReset",
diff --git a/app/src/config/tabs/secretsVariablesUi.ts b/app/src/config/tabs/secretsVariablesUi.ts
index c16c781412..d91993a3ab 100644
--- a/app/src/config/tabs/secretsVariablesUi.ts
+++ b/app/src/config/tabs/secretsVariablesUi.ts
@@ -1,4 +1,4 @@
-import {escapeHTMLStr} from "../../util/escape";
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import {bindPasswordIconaToggle} from "../render/fragments";
import {Dialog} from "../../dialog";
import {confirmDialog} from "../../dialog/confirmDialog";
@@ -228,8 +228,8 @@ const renderNamedItemList = (options: RenderNamedItemListOptions) => {
return;
}
const html = items.map((item) => {
- return `<div class="b3-list-item b3-list-item--narrow${hideActionClass}" ${dataAttr}="${escapeHTMLStr(item.name)}">
- <span class="b3-list-item__text">${escapeHTMLStr(item.name)}</span>
+ return `<div class="b3-list-item b3-list-item--narrow${hideActionClass}" ${dataAttr}="${escapeHtmlTextAndAttr(item.name)}">
+ <span class="b3-list-item__text">${escapeHtmlTextAndAttr(item.name)}</span>
<span data-type="${deleteType}" class="b3-list-item__action b3-list-item__action--warning b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.delete}">
<svg><use xlink:href="#iconTrashcan"></use></svg>
</span>
@@ -273,12 +273,12 @@ const openItemDialog = (options: OpenItemDialogOptions) => {
const valueInputHtml = isSecret
? `<div class="b3-form__icona fn__block">
- <input id="itemValue" type="password" class="b3-text-field b3-form__icona-input" spellcheck="false" value="${escapeHTMLStr(initial.value)}">
+ <input id="itemValue" type="password" class="b3-text-field b3-form__icona-input" spellcheck="false" value="${escapeHtmlTextAndAttr(initial.value)}">
<svg class="b3-form__icona-icon" data-action="togglePassword" style="user-select: none;">
<use xlink:href="#iconEye"></use>
</svg>
</div>`
- : `<input class="b3-text-field fn__block" id="itemValue" type="text" spellcheck="false" value="${escapeHTMLStr(initial.value)}"/>`;
+ : `<input class="b3-text-field fn__block" id="itemValue" type="text" spellcheck="false" value="${escapeHtmlTextAndAttr(initial.value)}"/>`;
const initialHosts: string[] = isSecret ? (initial.allowedHosts ?? []) : [];
const hostsInputHtml = isSecret
@@ -286,7 +286,7 @@ const openItemDialog = (options: OpenItemDialogOptions) => {
<div class="config-name">${window.siyuan.languages.secretAllowedHosts}</div>
<div class="b3-label__text">${window.siyuan.languages.secretAllowedHostsTip}</div>
<div class="fn__hr"></div>
- <input class="b3-text-field fn__block" id="itemAllowedHosts" type="text" spellcheck="false" value="${escapeHTMLStr(initialHosts.join(", "))}"/>
+ <input class="b3-text-field fn__block" id="itemAllowedHosts" type="text" spellcheck="false" value="${escapeHtmlTextAndAttr(initialHosts.join(", "))}"/>
</div>`
: "";
@@ -298,7 +298,7 @@ const openItemDialog = (options: OpenItemDialogOptions) => {
<div class="config-name">${isSecret ? window.siyuan.languages.secretName : window.siyuan.languages.variableName}</div>
<div class="b3-label__text">${isSecret ? window.siyuan.languages.secretNameTip : window.siyuan.languages.variableNameTip}</div>
<div class="fn__hr"></div>
- <input class="b3-text-field fn__block" id="itemName" type="text" spellcheck="false" value="${escapeHTMLStr(initial.name)}"/>
+ <input class="b3-text-field fn__block" id="itemName" type="text" spellcheck="false" value="${escapeHtmlTextAndAttr(initial.name)}"/>
</div>
${hostsInputHtml}
<div class="b3-label b3-label--inner">
@@ -356,7 +356,7 @@ const openItemDialog = (options: OpenItemDialogOptions) => {
const showDeleteConfirm = (title: string, onConfirm: () => void) => {
confirmDialog(
window.siyuan.languages.deleteOpConfirm,
- window.siyuan.languages.confirmDeleteTip.replace("${x}", escapeHTMLStr(title)),
+ window.siyuan.languages.confirmDeleteTip.replace("${x}", escapeHtmlTextAndAttr(title)),
onConfirm,
undefined,
true,
diff --git a/app/src/editor/deleteFile.ts b/app/src/editor/deleteFile.ts
index c11818d086..2643aba895 100644
--- a/app/src/editor/deleteFile.ts
+++ b/app/src/editor/deleteFile.ts
@@ -3,7 +3,7 @@ import {fetchPost, fetchSyncPost} from "../util/fetch";
import {getDisplayName, getNotebookName, isEncryptedBox} from "../util/pathName";
import {confirmDialog} from "../dialog/confirmDialog";
import {hasTopClosestByTag} from "../protyle/util/hasClosest";
-import {escapeHtml} from "../util/escape";
+import {escapeHtml, escapeHtmlTextAndAttr} from "../util/escape";
import {Constants} from "../constants";
import {checkBlockRef, getBlockRefWarningHTML} from "../util/checkBlockRef";
import {getDocTreeDeleteTargets} from "../menus/navigationSelection";
@@ -99,7 +99,7 @@ export const deleteFiles = async (liElements: Element[]) => {
if (hasRef === undefined) {
return;
}
- let tip = `${window.siyuan.languages.confirmDeleteTip.replace("${x}", Lute.EscapeHTMLStr(getNotebookName(itemNotebookId)))}
+ let tip = `${window.siyuan.languages.confirmDeleteTip.replace("${x}", escapeHtmlTextAndAttr(getNotebookName(itemNotebookId)))}
<div class="fn__hr"></div>
<div class="ft__smaller ft__on-surface">${window.siyuan.languages.rollbackTip.replace("${x}", window.siyuan.config.editor.historyRetentionDays)}</div>`;
if (hasRef) {
diff --git a/app/src/layout/dock/Files.ts b/app/src/layout/dock/Files.ts
index 70303c8b37..9043541bd7 100644
--- a/app/src/layout/dock/Files.ts
+++ b/app/src/layout/dock/Files.ts
@@ -1,4 +1,4 @@
-import {escapeAriaLabel, escapeHtml, escapeLessThans} from "../../util/escape";
+import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../util/escape";
import {Tab} from "../Tab";
import {Model} from "../Model";
import {getInstanceById, setPanelFocus} from "../util";
@@ -2147,7 +2147,7 @@ data-type="navigation-root" data-path="/" data-count="${item.subFileCount || 0}"
iconExpands && item.subFileCount === 0 && !editingPublishAccess ? " file-tree__item--icon-open" : ""}${
window.siyuan.config.fileTree.parentDocClickExpand && item.subFileCount > 0 ? " file-tree__item--title-expand" : ""}`;
const defaultIcon = item.subFileCount === 0 ? "file" : "folder";
- return `<li data-node-id="${item.id}" data-name="${Lute.EscapeHTMLStr(item.name)}" draggable="true" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}"
+ return `<li data-node-id="${item.id}" data-name="${escapeHtmlTextAndAttr(item.name)}" draggable="true" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}"
data-type="navigation-file"
style="--file-toggle-width:${paddingLeft + 18}px;--file-action-offset:${paddingLeft + 20}px"
class="b3-list-item b3-list-item--hide-action${actionClasses}" data-path="${item.path}"${getFileTreeDefaultIconAttr(item.icon, defaultIcon)}>
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index 38227c4c65..8fc1a9604c 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../util/escape";
import type {FileTreeGetDocRequestInput} from "../types/api";
import {
hasClosestBlock,
@@ -262,7 +263,7 @@ export const fileAnnotationRefMenu = (protyle: IProtyle, refElement: HTMLElement
anchorElement.value = refElement.textContent;
const inputEvent = () => {
if (anchorElement.value) {
- refElement.innerHTML = Lute.EscapeHTMLStr(anchorElement.value);
+ refElement.innerHTML = escapeHtmlTextAndAttr(anchorElement.value);
} else {
refElement.innerHTML = "*";
}
@@ -396,7 +397,7 @@ export const refMenu = (protyle: IProtyle, element: HTMLElement) => {
inputElement.addEventListener("input", () => {
if (inputElement.value) {
// 不能使用 textContent,否则 < 会变为 &lt;
- element.innerHTML = Lute.EscapeHTMLStr(inputElement.value).trim() || refBlockId;
+ element.innerHTML = escapeHtmlTextAndAttr(inputElement.value).trim() || refBlockId;
} else {
fetchPost("/api/block/getRefText", {id: refBlockId}, (response) => {
element.innerHTML = sanitizeKernelHTML(response.data);
@@ -1684,16 +1685,16 @@ style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" class="b3-text-fiel
if (anchor.length > Constants.SIZE_LINK_TEXT_MAX) {
anchor = anchor.substring(0, Constants.SIZE_LINK_TEXT_MAX) + "...";
}
- linkElement.innerHTML = Lute.EscapeHTMLStr(anchor);
+ linkElement.innerHTML = escapeHtmlTextAndAttr(anchor);
}
inputElements[1].value = anchor;
inputElements[1].addEventListener("compositionend", () => {
- linkElement.innerHTML = Lute.EscapeHTMLStr(inputElements[1].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "").trim() || "*");
+ linkElement.innerHTML = escapeHtmlTextAndAttr(inputElements[1].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "").trim() || "*");
});
inputElements[1].addEventListener("input", (event: KeyboardEvent) => {
if (!event.isComposing) {
// https://github.com/siyuan-note/siyuan/issues/4511
- linkElement.innerHTML = Lute.EscapeHTMLStr(inputElements[1].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "").trim()) || "*";
+ linkElement.innerHTML = escapeHtmlTextAndAttr(inputElements[1].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "").trim()) || "*";
}
});
inputElements[1].addEventListener("keydown", (event) => {
@@ -1898,12 +1899,12 @@ style="margin:4px 0;width: ${isMobile() ? "100%" : "360px"}" class="b3-text-fiel
}
window.siyuan.menus.menu.removeCB = () => {
if (inputElements[2].value) {
- linkElement.setAttribute("data-title", Lute.EscapeHTMLStr(inputElements[2].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "")));
+ linkElement.setAttribute("data-title", escapeHtmlTextAndAttr(inputElements[2].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "")));
} else {
linkElement.removeAttribute("data-title");
}
if (linkElement.getAttribute("data-type").indexOf("a") > -1) {
- linkElement.setAttribute("data-href", Lute.EscapeHTMLStr(inputElements[0].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "")));
+ linkElement.setAttribute("data-href", escapeHtmlTextAndAttr(inputElements[0].value.replace(/\n|\r\n|\r|\u2028|\u2029/g, "")));
} else {
linkElement.removeAttribute("data-href");
}
diff --git a/app/src/mobile/dock/MobileFiles.ts b/app/src/mobile/dock/MobileFiles.ts
index 5c54d2bdca..6c069188d4 100644
--- a/app/src/mobile/dock/MobileFiles.ts
+++ b/app/src/mobile/dock/MobileFiles.ts
@@ -1,5 +1,5 @@
import {hasClosestByClassName, hasClosestByTag, hasTopClosestByTag} from "../../protyle/util/hasClosest";
-import {escapeHtml} from "../../util/escape";
+import {escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";
import {getTreeItemTailHTML} from "../../util/treeItemTail";
import {Model} from "../../layout/Model";
import {Constants} from "../../constants";
@@ -1710,7 +1710,7 @@ export class MobileFiles extends Model {
<span data-type="new" class="b3-list-item__action b3-tooltips b3-tooltips__nw${window.siyuan.config.readonly ? " fn__none" : ""}" aria-label="${window.siyuan.languages.newSubDoc}">
<svg><use xlink:href="#iconAdd"></use></svg>
</span>`;
- return `<li data-node-id="${item.id}" data-name="${Lute.EscapeHTMLStr(item.name)}" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}" data-type="navigation-file"
+ return `<li data-node-id="${item.id}" data-name="${escapeHtmlTextAndAttr(item.name)}" data-count="${item.subFileCount}" ${FILE_TREE_CHILDREN_SORT_MODE}="${item.childrenSortMode ?? ""}" data-type="navigation-file"
class="b3-list-item" data-path="${item.path}" style="--file-toggle-width:${paddingLeft + 20}px"${getFileTreeDefaultIconAttr(item.icon, defaultIcon)}>
<span style="padding-left: ${paddingLeft}px" class="b3-list-item__toggle${item.subFileCount === 0 ? " fn__hidden" : ""}">
<svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
diff --git a/app/src/mobile/pdf.ts b/app/src/mobile/pdf.ts
index 9e99d7cfbc..00ee51815b 100644
--- a/app/src/mobile/pdf.ts
+++ b/app/src/mobile/pdf.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../util/escape";
import {Constants} from "../constants";
import {getPdfViewerHTML} from "../asset/pdf/viewerTemplate";
import {showMessage} from "../dialog/message";
@@ -142,7 +143,7 @@ export const openMobilePDF = (path: string, pdfParams?: number | string) => {
let modelElement: HTMLElement | undefined;
let isDestroyed = false;
const abortController = new AbortController();
- const title = Lute.EscapeHTMLStr(getDisplayName(getAssetPathWithoutQuery(path)));
+ const title = escapeHtmlTextAndAttr(getDisplayName(getAssetPathWithoutQuery(path)));
openModel({
title,
diff --git a/app/src/protyle/header/Title.ts b/app/src/protyle/header/Title.ts
index 05f8816099..a7089005b4 100644
--- a/app/src/protyle/header/Title.ts
+++ b/app/src/protyle/header/Title.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import type {BlockQueryRequestInput} from "../../types/api";
import {
focusByOffset,
@@ -409,21 +410,21 @@ export class Title {
}
let nodeAttrHTML = "";
if (response.data.ial.bookmark) {
- nodeAttrHTML += `<div class="protyle-attr--bookmark">${Lute.EscapeHTMLStr(response.data.ial.bookmark)}</div>`;
+ nodeAttrHTML += `<div class="protyle-attr--bookmark">${escapeHtmlTextAndAttr(response.data.ial.bookmark)}</div>`;
}
if (response.data.ial.name) {
- nodeAttrHTML += `<div class="protyle-attr--name"><svg><use xlink:href="#iconN"></use></svg>${Lute.EscapeHTMLStr(response.data.ial.name)}</div>`;
+ nodeAttrHTML += `<div class="protyle-attr--name"><svg><use xlink:href="#iconN"></use></svg>${escapeHtmlTextAndAttr(response.data.ial.name)}</div>`;
}
if (response.data.ial.alias) {
- nodeAttrHTML += `<div class="protyle-attr--alias"><svg><use xlink:href="#iconA"></use></svg>${Lute.EscapeHTMLStr(response.data.ial.alias)}</div>`;
+ nodeAttrHTML += `<div class="protyle-attr--alias"><svg><use xlink:href="#iconA"></use></svg>${escapeHtmlTextAndAttr(response.data.ial.alias)}</div>`;
}
if (response.data.ial.memo) {
- nodeAttrHTML += `<div class="protyle-attr--memo ariaLabel" aria-label="${Lute.EscapeHTMLStr(response.data.ial.memo)}" data-position="north"><svg><use xlink:href="#iconM"></use></svg></div>`;
+ nodeAttrHTML += `<div class="protyle-attr--memo ariaLabel" aria-label="${escapeHtmlTextAndAttr(response.data.ial.memo)}" data-position="north"><svg><use xlink:href="#iconM"></use></svg></div>`;
}
if (response.data.ial["custom-avs"]) {
let avTitle = "";
response.data.attrViews.forEach((item: { id: string, name: string }) => {
- avTitle += `<span data-av-id="${item.id}" data-popover-url="/api/av/getMirrorDatabaseBlocks" class="popover__block">${Lute.EscapeHTMLStr(item.name)}</span>&nbsp;`;
+ avTitle += `<span data-av-id="${item.id}" data-popover-url="/api/av/getMirrorDatabaseBlocks" class="popover__block">${escapeHtmlTextAndAttr(item.name)}</span>&nbsp;`;
});
if (avTitle) {
avTitle = avTitle.substring(0, avTitle.length - 6);
diff --git a/app/src/protyle/header/openDocTagMenu.ts b/app/src/protyle/header/openDocTagMenu.ts
index aee7e5f185..46f15109a6 100644
--- a/app/src/protyle/header/openDocTagMenu.ts
+++ b/app/src/protyle/header/openDocTagMenu.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import {MenuItem} from "../../menus/Menu";
import {Constants} from "../../constants";
import {genTagList, renameTag} from "../../util/noRelyPCFunction";
@@ -22,7 +23,7 @@ interface IOpenDocTagMenuOptions {
}
const copyTag = async (protyle: IProtyle, tag: string) => {
- const canonicalHTML = buildSemanticInlineHTML("tag", Lute.EscapeHTMLStr(tag));
+ const canonicalHTML = buildSemanticInlineHTML("tag", escapeHtmlTextAndAttr(tag));
const textSiyuan = transformSemanticInlineHTML(canonicalHTML, "legacy");
const textHTML = `<!--data-siyuan='${encodeBase64(textSiyuan)}'-->${removeZWJ(protyle.lute.BlockDOM2HTML(textSiyuan))}`;
try {
diff --git a/app/src/protyle/render/av/attributePanel.ts b/app/src/protyle/render/av/attributePanel.ts
index 031ee1adc3..ea6a7032db 100644
--- a/app/src/protyle/render/av/attributePanel.ts
+++ b/app/src/protyle/render/av/attributePanel.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../../util/escape";
import {renderAVAttribute} from "./blockAttr";
import {
cancelHeightAnimation,
@@ -307,7 +308,7 @@ export class AVAttributePanel {
}
tabsElement.innerHTML = databaseElements.map(item => {
const title = item.querySelector(".custom-attr__avheader .block__logo span")?.textContent || window.siyuan.languages.database;
- return `<button type="button" draggable="${!this.protyle.disabled}" class="item${item.dataset.avId === this.activeAvID ? " item--focus" : ""}" data-type="av-tab" data-id="${item.dataset.avId}"><span class="item__text">${Lute.EscapeHTMLStr(title)}</span></button>`;
+ return `<button type="button" draggable="${!this.protyle.disabled}" class="item${item.dataset.avId === this.activeAvID ? " item--focus" : ""}" data-type="av-tab" data-id="${item.dataset.avId}"><span class="item__text">${escapeHtmlTextAndAttr(title)}</span></button>`;
}).join("");
this.bindTabDrag(tabsElement);
} else {
diff --git a/app/src/protyle/render/av/attributeValue.ts b/app/src/protyle/render/av/attributeValue.ts
index a3d5806eb0..3813477ec7 100644
--- a/app/src/protyle/render/av/attributeValue.ts
+++ b/app/src/protyle/render/av/attributeValue.ts
@@ -1,4 +1,4 @@
-import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
+import {escapeAriaLabel, escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../../../util/escape";
import {unicode2Emoji} from "../../../emoji";
import {renderAVBlockIcon} from "./blockIcon";
import {getCompressURL} from "../../../util/image";
@@ -29,7 +29,7 @@ export const genAVRelationHTML = (item: IAVCellValue, rowID: string, showIcon =
}
const useTemplate = hasAVRenderTemplateResult(item);
const content = useTemplate ? getAVTemplateHTML(item.renderedContent || "") :
- Lute.EscapeHTMLStr(item.block.content || window.siyuan.languages.untitled);
+ escapeHtmlTextAndAttr(item.block.content || window.siyuan.languages.untitled);
const templateClass = useTemplate ? " av__celltext--template" : "";
const storedValue = escapeAttr(encodeURIComponent(JSON.stringify(cloneAVCellValueSnapshot(item))));
const attributes = `data-row-id="${escapeAttr(rowID)}" data-relation-value="${storedValue}" class="av__cell--relation"`;
diff --git a/app/src/protyle/render/av/blockIcon.test.ts b/app/src/protyle/render/av/blockIcon.test.ts
index 53bcd9f84b..f85082b0d3 100644
--- a/app/src/protyle/render/av/blockIcon.test.ts
+++ b/app/src/protyle/render/av/blockIcon.test.ts
@@ -78,7 +78,6 @@ const createHarness = (layout: TAVView = "table", detached = true, icon?: string
window: {siyuan}, document: {querySelectorAll: (): HTMLElement[] => [], createElement: () => ({
matches: () => false, querySelector: (): HTMLElement => null, querySelectorAll: (): HTMLElement[] => [], textContent: "",
})},
- Lute: {EscapeHTMLStr: escape.escapeHtml},
});
mocks[`./${name}`] = module.exports;
return module.exports;
diff --git a/app/src/protyle/render/av/cell.ts b/app/src/protyle/render/av/cell.ts
index d91a39e309..79ec7ca443 100644
--- a/app/src/protyle/render/av/cell.ts
+++ b/app/src/protyle/render/av/cell.ts
@@ -16,7 +16,7 @@ import {Constants} from "../../../constants";
import {hintRef} from "../../hint/extend";
import {getAssetExtension, getAssetName} from "../../../util/pathName";
import {mergeAddOption} from "./select";
-import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
+import {escapeAriaLabel, escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../../../util/escape";
import {electronUndo} from "../../undo";
import {formatDateDisplay, formatDateValue, parseDateValue} from "./dateFormat";
import {getFieldIdByCellElement} from "./row";
@@ -171,7 +171,7 @@ const openAVRelationIcon = async (protyle: IProtyle, target: HTMLElement, relati
};
const renderCellURL = (urlContent: string) => {
- return `<span class="av__celltext av__celltext--url" data-type="url" data-href="${escapeAttr(urlContent)}">${Lute.EscapeHTMLStr(urlContent)}</span>`;
+ return `<span class="av__celltext av__celltext--url" data-type="url" data-href="${escapeAttr(urlContent)}">${escapeHtmlTextAndAttr(urlContent)}</span>`;
};
const getStoredCellValueByElement = (cellElement: HTMLElement) => {
@@ -1379,18 +1379,18 @@ export const renderCell = (cellValue: IAVCellValue, rowIndex = 0, showIcon = tru
const storedValue = cloneAVCellValueSnapshot(cellValue);
text = `<div class="av__celltext av__celltext--rich b3-typography" data-protyle-lite-render="safe" data-cell-value="${escapeAttr(encodeURIComponent(JSON.stringify(storedValue)))}">${getAVRichTextPreviewHTML(source.content)}</div>`;
} else {
- text = `<span class="av__celltext">${cellValue ? Lute.EscapeHTMLStr(cellValue.text.content || "") : ""}</span>`;
+ text = `<span class="av__celltext">${cellValue ? escapeHtmlTextAndAttr(cellValue.text.content || "") : ""}</span>`;
}
} else if (["email", "phone"].includes(cellValue.type)) {
- text = `<span class="av__celltext av__celltext--url" data-type="${cellValue.type}">${cellValue ? Lute.EscapeHTMLStr(cellValue[cellValue.type as "email"].content || "") : ""}</span>`;
+ text = `<span class="av__celltext av__celltext--url" data-type="${cellValue.type}">${cellValue ? escapeHtmlTextAndAttr(cellValue[cellValue.type as "email"].content || "") : ""}</span>`;
} else if ("url" === cellValue.type) {
text = renderCellURL(cellValue?.url?.content || "");
} else if (cellValue.type === "block") {
// 不可使用换行 https://github.com/siyuan-note/siyuan/issues/11365
if (cellValue?.isDetached) {
- text = `${renderAVBlockIcon(cellValue, showIcon)}<span class="av__celltext">${Lute.EscapeHTMLStr(cellValue.block.content || "")}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span class="av__celltext">${escapeHtmlTextAndAttr(cellValue.block.content || "")}</span>`;
} else {
- text = `${renderAVBlockIcon(cellValue, showIcon)}<span data-type="block-ref" data-id="${cellValue.block.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(cellValue.block.content)}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span data-type="block-ref" data-id="${cellValue.block.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${escapeHtmlTextAndAttr(cellValue.block.content)}</span>`;
}
text = `<span class="av__cellprimary">${text}</span>`;
const bindLabel = cellValue?.isDetached ? window.siyuan.languages.bind : window.siyuan.languages.rebind;
@@ -1518,11 +1518,11 @@ export const getAVSelectedCellData = (blockElement: HTMLElement) => {
const renderRollup = (cellValue: IAVCellValue, showIcon: boolean) => {
let text = "";
if (["text"].includes(cellValue.type)) {
- text = cellValue ? Lute.EscapeHTMLStr(cellValue[cellValue.type as "text"].content || "") : "";
+ text = cellValue ? escapeHtmlTextAndAttr(cellValue[cellValue.type as "text"].content || "") : "";
} else if (["email", "phone"].includes(cellValue.type)) {
const emailContent = cellValue ? cellValue[cellValue.type as "email"].content : "";
if (emailContent) {
- text = `<span class="av__celltext av__celltext--url" data-type="${cellValue.type}">${Lute.EscapeHTMLStr(emailContent)}</span>`;
+ text = `<span class="av__celltext av__celltext--url" data-type="${cellValue.type}">${escapeHtmlTextAndAttr(emailContent)}</span>`;
}
} else if ("url" === cellValue.type) {
const urlContent = cellValue?.url?.content || "";
@@ -1531,9 +1531,9 @@ const renderRollup = (cellValue: IAVCellValue, showIcon: boolean) => {
}
} else if (cellValue.type === "block") {
if (cellValue?.isDetached) {
- text = `${renderAVBlockIcon(cellValue, showIcon)}<span class="av__celltext">${Lute.EscapeHTMLStr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span class="av__celltext">${escapeHtmlTextAndAttr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
} else {
- text = `${renderAVBlockIcon(cellValue, showIcon)}<span data-type="block-ref" data-id="${cellValue.block?.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${Lute.EscapeHTMLStr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
+ text = `${renderAVBlockIcon(cellValue, showIcon)}<span data-type="block-ref" data-id="${cellValue.block?.id}" data-subtype="${getAVBlockRefSubtype(cellValue)}" class="av__celltext av__celltext--ref">${escapeHtmlTextAndAttr(cellValue.block?.content || window.siyuan.languages.untitled)}</span>`;
}
} else if (cellValue.type === "number") {
text = cellValue?.number.formattedContent || cellValue?.number.content.toString() || "";
diff --git a/app/src/protyle/render/av/gallery/render.ts b/app/src/protyle/render/av/gallery/render.ts
index e8bc165af7..3409ad34de 100644
--- a/app/src/protyle/render/av/gallery/render.ts
+++ b/app/src/protyle/render/av/gallery/render.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../../../util/escape";
import {isTableLikeView} from "../viewType";
import {isAVRenderData} from "../renderData";
import {hasClosestBlock, hasClosestByClassName} from "../../../util/hasClosest";
@@ -96,7 +97,7 @@ const renderGroupGallery = (options: ITableOptions) => {
options.data.view.groups.forEach((group: IAVGallery) => {
if (group.groupHidden === 0) {
avBodyHTML += `${getGroupTitleHTML(group, group.cardCount)}
-<div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${Lute.EscapeHTMLStr(group.groupValue.text?.content || "")}"${options.resetData.virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body${group.groupFolded ? " fn__none" : ""}">${getGalleryHTML(group, options.blockElement, options.resetData.virtualData[group.id])}</div>`;
+<div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${options.resetData.virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body${group.groupFolded ? " fn__none" : ""}">${getGalleryHTML(group, options.blockElement, options.resetData.virtualData[group.id])}</div>`;
}
});
if (options.renderAll) {
diff --git a/app/src/protyle/render/av/kanban/render.ts b/app/src/protyle/render/av/kanban/render.ts
index bc519e7e29..d88d075076 100644
--- a/app/src/protyle/render/av/kanban/render.ts
+++ b/app/src/protyle/render/av/kanban/render.ts
@@ -8,7 +8,7 @@ import {Constants} from "../../../../constants";
import {avRender, genTabHeaderHTML} from "../render";
import {replaceAVContainer} from "../container";
import {afterRenderGallery, renderGallery} from "../gallery/render";
-import {escapeAttr, escapeHtml} from "../../../../util/escape";
+import {escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../../../../util/escape";
import {getRowHTML} from "../row";
import {getAVSelectedItemPoints, getBodyVirtualData} from "../virtualScroll";
import {
@@ -235,7 +235,7 @@ export const renderKanban = async (options: {
}
bodyHTML += `<div class="av__kanban-group${group.cardSize === 0 ? " av__kanban-group--small" : (group.cardSize === 2 ? " av__kanban-group--big" : "")}" data-group-id="${group.id}" data-previous-group-id="${view.groups[groupIndex - 1]?.id || ""}" data-group-config="${groupConfig}"${selectBg}>
${getKanbanTitleHTML(group, group.cardCount, groupDraggable)}
- <div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${Lute.EscapeHTMLStr(group.groupValue.text?.content || "")}"${virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body">${getKanbanHTML(group, options.blockElement, virtualData[group.id])}</div>
+ <div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${virtualData[group.id]?.locate ? ' data-av-locate-window="true"' : ""} class="av__body">${getKanbanHTML(group, options.blockElement, virtualData[group.id])}</div>
</div>`;
}
});
diff --git a/app/src/protyle/render/av/relation.ts b/app/src/protyle/render/av/relation.ts
index ffbc4ed1e7..0d526bbc10 100644
--- a/app/src/protyle/render/av/relation.ts
+++ b/app/src/protyle/render/av/relation.ts
@@ -3,7 +3,7 @@ import {Menu} from "../../../plugin/Menu";
import {hasClosestByAttribute, hasClosestByClassName, hasTopClosestByClassName} from "../../util/hasClosest";
import {UDLRHint, upDownHint} from "../../../util/upDownHint";
import {fetchPost} from "../../../util/fetch";
-import {escapeAttr, escapeHtml, escapeLessThans} from "../../../util/escape";
+import {escapeAttr, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../../../util/escape";
import {transaction} from "../../wysiwyg/transaction";
import {genCellValueByElement, getCellValueText, renderCell, updateCellsValue} from "./cell";
import {updateAttrViewCellAnimation} from "./action";
@@ -449,7 +449,7 @@ style="grid-template-columns:${gridTemplate}">
const isDetached = primaryValue.isDetached;
const useRenderedContent = hasAVRenderTemplateResult(primaryValue, column.renderTemplate);
const content = useRenderedContent ? getAVTemplateHTML(primaryValue.renderedContent || "") :
- Lute.EscapeHTMLStr(primaryValue.block?.content || window.siyuan.languages.untitled);
+ escapeHtmlTextAndAttr(primaryValue.block?.content || window.siyuan.languages.untitled);
html += `<span data-relation-column="${escapeAttr(column.id)}" class="av__relation-table-cell av__relation-table-primary" data-row-id="${escapeAttr(row.id)}"
data-value-id="${escapeAttr(primaryCell.id || "")}"
style="${primaryCell.bgColor ? `background-color:${primaryCell.bgColor};` : ""}${primaryCell.color ? `color:${primaryCell.color};` : ""}">
@@ -489,7 +489,7 @@ const genRelationFooterHTML = (menuElement: HTMLElement, keyword: string, hasCan
data-id="${escapeAttr(refElement?.getAttribute("data-id") || "")}">${escapeHtml(refElement?.textContent || "")}</span>`;
return `<button class="b3-menu__item av__relation-table-footer" data-type="setRelationCell" data-relation-type="create">
<span class="b3-menu__label fn__ellipsis">${window.siyuan.languages.newRowInRelation.replace("${x}", databaseName).
- replace("${y}", Lute.EscapeHTMLStr(keyword))}</span>
+ replace("${y}", escapeHtmlTextAndAttr(keyword))}</span>
</button>`;
}
if (!hasCandidates && !hasMore) {
@@ -999,7 +999,7 @@ const genCreatedRelationRowHTML = (menuElement: HTMLElement, rowID: string, cont
let cellsHTML = `<span data-relation-column="${escapeAttr(columns?.[0]?.dataset.relationColumn || "")}" class="av__relation-table-cell av__relation-table-primary" data-row-id="${rowID}">
<svg class="b3-menu__icon fn__grab"><use xlink:href="#iconDrag"></use></svg>
<span class="av__relation-row-icon">${getAVBlockIconHTML({isDetached: true})}</span>
- <span class="b3-menu__label fn__ellipsis" data-id="">${Lute.EscapeHTMLStr(content)}</span>
+ <span class="b3-menu__label fn__ellipsis" data-id="">${escapeHtmlTextAndAttr(content)}</span>
</span>`;
for (let i = 1; i < (columns?.length || 1); i++) {
cellsHTML += `<span data-relation-column="${escapeAttr(columns[i].dataset.relationColumn)}" class="av__relation-table-cell${columns[i].classList.contains("fn__none") ? " fn__none" : ""}"></span>`;
diff --git a/app/src/protyle/render/av/render.ts b/app/src/protyle/render/av/render.ts
index 7f8f6e13d1..91b16469d7 100644
--- a/app/src/protyle/render/av/render.ts
+++ b/app/src/protyle/render/av/render.ts
@@ -14,7 +14,7 @@ import {hasClosestBlock, hasClosestByClassName} from "../../util/hasClosest";
import {getRowHTML, stickyRow, updateAVSelectionStatus, updateHeader} from "./row";
import {getCalcValue} from "./calc";
import {renderAVAttribute} from "./blockAttr";
-import {escapeAriaLabel, escapeAttr, escapeHtml} from "../../../util/escape";
+import {escapeAriaLabel, escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../../../util/escape";
import {isInMobileApp} from "../../util/compatibility";
import {isMobile} from "../../../util/functions";
import {renderGallery} from "./gallery/render";
@@ -196,7 +196,7 @@ export const genTabHeaderHTML = (data: IAV, showSearch: boolean, editable: boole
<div class="fn__space"></div>
${editingState.newItemHTML}
</div>
- <div contenteditable="${editingState.contenteditable}" spellcheck="${window.siyuan.config.editor.spellcheck.toString()}" class="av__title${viewData.hideAttrViewName ? " fn__none" : ""}" data-title="${Lute.EscapeHTMLStr(data.name || "")}" data-tip="${window.siyuan.languages._kernel[267]}">${Lute.EscapeHTMLStr(data.name || "")}</div>
+ <div contenteditable="${editingState.contenteditable}" spellcheck="${window.siyuan.config.editor.spellcheck.toString()}" class="av__title${viewData.hideAttrViewName ? " fn__none" : ""}" data-title="${escapeHtmlTextAndAttr(data.name || "")}" data-tip="${window.siyuan.languages._kernel[267]}">${escapeHtmlTextAndAttr(data.name || "")}</div>
</div>`;
};
@@ -341,7 +341,7 @@ const renderGroupTable = (options: ITableOptions) => {
const virtualData = plan.virtualData[group.id];
const renderBody = !group.groupFolded || virtualData?.locate;
avBodyHTML += `${getGroupTitleHTML(group, group.rowCount)}
-<div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${Lute.EscapeHTMLStr(group.groupValue.text?.content || "")}"${virtualData?.locate ? ' data-av-locate-window="true"' : ""} style="float: left" class="av__body${group.groupFolded ? " fn__none" : ""}">${renderBody ? getTableHTMLs(group, options.blockElement, virtualData, true) : ""}</div>`;
+<div data-group-id="${group.id}" data-page-size="${group.pageSize}" data-dtype="${group.groupKey.type}" data-content="${escapeHtmlTextAndAttr(group.groupValue.text?.content || "")}"${virtualData?.locate ? ' data-av-locate-window="true"' : ""} style="float: left" class="av__body${group.groupFolded ? " fn__none" : ""}">${renderBody ? getTableHTMLs(group, options.blockElement, virtualData, true) : ""}</div>`;
}
});
if (options.renderAll) {
diff --git a/app/src/protyle/render/av/row.ts b/app/src/protyle/render/av/row.ts
index 7b8b23fa2d..4c03a3a5a0 100644
--- a/app/src/protyle/render/av/row.ts
+++ b/app/src/protyle/render/av/row.ts
@@ -21,7 +21,7 @@ import {clearSelect} from "../../util/clear";
import {isCustomAttr} from "./blockAttr";
import {getColIconByType, getColNameByType} from "./col";
import {unicode2Emoji} from "../../../emoji";
-import {escapeAriaLabel, escapeAttr} from "../../../util/escape";
+import {escapeAriaLabel, escapeAttr, escapeHtmlTextAndAttr} from "../../../util/escape";
import {getCompressURL} from "../../../util/image";
import {
getAVSelectStat,
@@ -115,7 +115,7 @@ ${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.ro
if (galleryData.displayFieldName) {
html += `<div class="av__gallery-field av__gallery-field--name${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-name">
- ${galleryData.fields[fieldsIndex].icon ? unicode2Emoji(galleryData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(galleryData.fields[fieldsIndex].type)}"></use></svg>`}${Lute.EscapeHTMLStr(galleryData.fields[fieldsIndex].name)}
+ ${galleryData.fields[fieldsIndex].icon ? unicode2Emoji(galleryData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(galleryData.fields[fieldsIndex].type)}"></use></svg>`}${escapeHtmlTextAndAttr(galleryData.fields[fieldsIndex].name)}
${galleryData.fields[fieldsIndex].desc ? `<svg aria-label="${escapeAriaLabel(galleryData.fields[fieldsIndex].desc)}" data-position="north" class="ariaLabel"><use xlink:href="#iconInfo"></use></svg>` : ""}
</div>
${cellHTML}
@@ -123,7 +123,7 @@ ${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.ro
} else {
html += `<div class="av__gallery-field${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-tip">
- ${galleryData.fields[fieldsIndex].icon ? unicode2Emoji(galleryData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(galleryData.fields[fieldsIndex].type)}"></use></svg>`}${window.siyuan.languages.edit} ${Lute.EscapeHTMLStr(galleryData.fields[fieldsIndex].name)}
+ ${galleryData.fields[fieldsIndex].icon ? unicode2Emoji(galleryData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(galleryData.fields[fieldsIndex].type)}"></use></svg>`}${window.siyuan.languages.edit} ${escapeHtmlTextAndAttr(galleryData.fields[fieldsIndex].name)}
</div>
${cellHTML}
</div>`;
@@ -184,7 +184,7 @@ ${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.ro
if (kanbanData.displayFieldName) {
html += `<div class="av__gallery-field av__gallery-field--name${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-name">
- ${kanbanData.fields[fieldsIndex].icon ? unicode2Emoji(kanbanData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(kanbanData.fields[fieldsIndex].type)}"></use></svg>`}${Lute.EscapeHTMLStr(kanbanData.fields[fieldsIndex].name)}
+ ${kanbanData.fields[fieldsIndex].icon ? unicode2Emoji(kanbanData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(kanbanData.fields[fieldsIndex].type)}"></use></svg>`}${escapeHtmlTextAndAttr(kanbanData.fields[fieldsIndex].name)}
${kanbanData.fields[fieldsIndex].desc ? `<svg aria-label="${escapeAriaLabel(kanbanData.fields[fieldsIndex].desc)}" data-position="north" class="ariaLabel"><use xlink:href="#iconInfo"></use></svg>` : ""}
</div>
${cellHTML}
@@ -192,7 +192,7 @@ ${cell.color ? `color:${cell.color};` : ""}">${renderCell(cell.value, options.ro
} else {
html += `<div class="av__gallery-field${fullRowClass}" data-empty="${isEmpty}">
<div class="av__gallery-tip">
- ${kanbanData.fields[fieldsIndex].icon ? unicode2Emoji(kanbanData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(kanbanData.fields[fieldsIndex].type)}"></use></svg>`}${window.siyuan.languages.edit} ${Lute.EscapeHTMLStr(kanbanData.fields[fieldsIndex].name)}
+ ${kanbanData.fields[fieldsIndex].icon ? unicode2Emoji(kanbanData.fields[fieldsIndex].icon, "av__gallery-fieldicon", true) : `<svg><use xlink:href="#${getColIconByType(kanbanData.fields[fieldsIndex].type)}"></use></svg>`}${window.siyuan.languages.edit} ${escapeHtmlTextAndAttr(kanbanData.fields[fieldsIndex].name)}
</div>
${cellHTML}
</div>`;
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 62f14b88b2..6fa1acb56e 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -70,7 +70,7 @@ import {mathRender} from "../render/mathRender";
import {linkMenu} from "../../menus/protyle";
import {addScript} from "../util/addScript";
import {paste, pasteAsPlainText, pasteEscaped} from "../util/paste";
-import {escapeAttr, escapeHtml} from "../../util/escape";
+import {escapeAttr, escapeHtml, escapeHtmlTextAndAttr} from "../../util/escape";
import {resizeSide} from "../../history/resizeSide";
import {activeBlur, updateMobilePluginToolbar} from "../../mobile/util/keyboardToolbar";
import {FormatPainter} from "./FormatPainter";
@@ -1758,7 +1758,7 @@ export class Toolbar {
}
});
} else {
- renderElement.setAttribute("data-content", Lute.EscapeHTMLStr(textElement.value));
+ renderElement.setAttribute("data-content", escapeHtmlTextAndAttr(textElement.value));
renderElement.removeAttribute("data-render");
}
if (!types.includes("NodeBlockQueryEmbed") || !types.includes("NodeHTMLBlock") || !isInlineMemo) {
@@ -1849,7 +1849,7 @@ export class Toolbar {
} else if (types.includes("inline-math") && !noChange) {
// 行内数学公式不允许换行 https://github.com/siyuan-note/siyuan/issues/2187
if (textElement.value) {
- renderElement.setAttribute("data-content", Lute.EscapeHTMLStr(textElement.value));
+ renderElement.setAttribute("data-content", escapeHtmlTextAndAttr(textElement.value));
renderElement.removeAttribute("data-render");
processRender(renderElement);
} else {
@@ -1858,7 +1858,7 @@ export class Toolbar {
renderElement.outerHTML = "<wbr>";
}
} else if (!noChange) {
- renderElement.setAttribute("data-content", Lute.EscapeHTMLStr(textElement.value));
+ renderElement.setAttribute("data-content", escapeHtmlTextAndAttr(textElement.value));
renderElement.removeAttribute("data-render");
if (types.includes("NodeBlockQueryEmbed")) {
blockRender(protyle, renderElement);
diff --git a/app/src/protyle/util/table.ts b/app/src/protyle/util/table.ts
index 424130834f..bca136c793 100644
--- a/app/src/protyle/util/table.ts
+++ b/app/src/protyle/util/table.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import {openInputDialog} from "../../dialog/inputDialog";
import {updateTransaction} from "../wysiwyg/transaction";
import {
@@ -787,13 +788,13 @@ export const updateTableTitle = (protyle: IProtyle, nodeElement: Element) => {
const title = value.trim();
const location = (dialog.element.querySelector("select") as HTMLSelectElement).value;
if (title) {
- const html = `<caption contenteditable="false" ${location === "bottom" ? 'style="caption-side: bottom;"' : ""}>${Lute.EscapeHTMLStr(title)}</caption>`;
+ const html = `<caption contenteditable="false" ${location === "bottom" ? 'style="caption-side: bottom;"' : ""}>${escapeHtmlTextAndAttr(title)}</caption>`;
if (captionElement) {
captionElement.outerHTML = html;
} else {
nodeElement.querySelector("table").insertAdjacentHTML("afterbegin", html);
}
- nodeElement.setAttribute("caption", Lute.EscapeHTMLStr(html));
+ nodeElement.setAttribute("caption", escapeHtmlTextAndAttr(html));
} else {
if (captionElement) {
captionElement.remove();
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index b31b0603f9..bcad55bce3 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import {fetchPost, fetchSyncPost} from "../../util/fetch";
import * as dayjs from "dayjs";
import {restoreInlineElementBoundaryHTML} from "../util/inlineElementBoundary";
@@ -1041,7 +1042,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
let avHTML = "";
Object.keys(data.new).forEach(key => {
attrsResult[key] = data.new[key];
- const escapeHTML = Lute.EscapeHTMLStr(data.new[key]);
+ const escapeHTML = escapeHtmlTextAndAttr(data.new[key]);
if (key === "bookmark") {
bookmarkHTML = `<div class="protyle-attr--bookmark">${escapeHTML}</div>`;
} else if (key === "name") {
diff --git a/app/src/protyle/wysiwyg/turnIntoCode.ts b/app/src/protyle/wysiwyg/turnIntoCode.ts
index 9878f6795f..ff4778dcd3 100644
--- a/app/src/protyle/wysiwyg/turnIntoCode.ts
+++ b/app/src/protyle/wysiwyg/turnIntoCode.ts
@@ -1,3 +1,4 @@
+import {escapeHtmlTextAndAttr} from "../../util/escape";
import {Constants} from "../../constants";
import {highlightRender} from "../render/highlightRender";
import {isEmptyParagraph} from "./emptyTextBlock";
@@ -15,7 +16,7 @@ export const turnParagraphIntoCode = (protyle: IProtyle, nodeElement: HTMLElemen
}
const html = nodeElement.outerHTML;
editElement.innerHTML = "```" + window.siyuan.storage[Constants.LOCAL_CODELANG] + "\n" +
- Lute.EscapeHTMLStr(editElement.textContent) + "<wbr>\n```";
+ escapeHtmlTextAndAttr(editElement.textContent) + "<wbr>\n```";
nodeElement.insertAdjacentHTML("afterend", protyle.lute.SpinBlockDOM(nodeElement.outerHTML));
const newNodeElement = nodeElement.nextElementSibling;
nodeElement.remove();
diff --git a/app/src/util/Tree.test.ts b/app/src/util/Tree.test.ts
index 1374040267..23a4c1a423 100644
--- a/app/src/util/Tree.test.ts
+++ b/app/src/util/Tree.test.ts
@@ -51,7 +51,6 @@ const fakeElement = () => ({
// 大纲条目会调用全局 Lute 生成 aria-label,这里提供最小替身
(globalThis as any).Lute = {
BlockDOM2Content: (value: string) => value,
- EscapeHTMLStr: (value: string) => value,
};
type TreeInstance = { createTopLevelItem: (item: IBlockTree) => unknown };
diff --git a/app/src/util/escape.test.ts b/app/src/util/escape.test.ts
index 87058a3ab3..34bfff67c5 100644
--- a/app/src/util/escape.test.ts
+++ b/app/src/util/escape.test.ts
@@ -1,15 +1,29 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {escapeHTMLStr, escapeSearchHighlight, stripSearchMark} from "./escape";
+import {escapeHtmlTextAndAttr, escapeSearchHighlight, stripSearchMark} from "./escape";
describe("escape HTML strings", () => {
it("matches the bundled Lute engine for text and double-quoted attributes", () => {
require("../../stage/protyle/js/lute/lute.min.js");
for (const value of ["", "plain text", "&<>\"'", "&amp; &#39; &quot;", "</textarea><img src=\"x\">",
"中文、日本語、😀\n\t'quoted'"]) {
- assert.equal(escapeHTMLStr(value), Lute.EscapeHTMLStr(value));
+ assert.equal(escapeHtmlTextAndAttr(value), Lute.EscapeHTMLStr(value));
}
- assert.equal(escapeHTMLStr("&<>\"'"), "&amp;&lt;&gt;&quot;'");
+ assert.equal(escapeHtmlTextAndAttr("&<>\"'"), "&amp;&lt;&gt;&quot;'");
+ });
+
+ it("preserves Lute string conversion for non-string values", () => {
+ require("../../stage/protyle/js/lute/lute.min.js");
+ for (const value of [undefined, null, 0, 123, NaN, false, true, ["<&", 1],
+ {toString: () => '<"&>'}]) {
+ assert.equal(escapeHtmlTextAndAttr(value), Reflect.apply(Lute.EscapeHTMLStr, Lute, [value]));
+ }
+ });
+
+ it("preserves lone surrogates while escaping HTML characters", () => {
+ assert.equal(escapeHtmlTextAndAttr("\ud800&<\udc00>\"'"), "\ud800&amp;&lt;\udc00&gt;&quot;'");
+ assert.equal(escapeHtmlTextAndAttr("\ud800"), "\ud800");
+ assert.equal(escapeHtmlTextAndAttr("\udc00"), "\udc00");
});
});
diff --git a/app/src/util/escape.ts b/app/src/util/escape.ts
index b5cf1c10d0..5bd9728cf3 100644
--- a/app/src/util/escape.ts
+++ b/app/src/util/escape.ts
@@ -1,6 +1,6 @@
// 转义 HTML 文本和双引号属性值,保持 Lute.EscapeHTMLStr 的字符替换规则。
-export const escapeHTMLStr = (html: string) => {
- return html.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
+export const escapeHtmlTextAndAttr = (html: unknown) => {
+ return String(html).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
};
export const escapeHtml = (html: string) => {
diff --git a/app/src/util/pathName.ts b/app/src/util/pathName.ts
index c8a5f35026..ab3b576c7f 100644
--- a/app/src/util/pathName.ts
+++ b/app/src/util/pathName.ts
@@ -1,7 +1,7 @@
import * as path from "path";
import {fetchPost} from "./fetch";
import {Dialog} from "../dialog";
-import {escapeAriaLabel, escapeHtml} from "./escape";
+import {escapeAriaLabel, escapeHtml, escapeHtmlTextAndAttr} from "./escape";
import {isMobile} from "./functions";
import {focusByRange} from "../protyle/util/selection";
import {Constants} from "../constants";
@@ -160,7 +160,7 @@ export const getDocDisplayName = (name: string, titleEmpty?: boolean, escape?: b
}
const displayName = getDisplayName(name, true, true);
if (escape) {
- return Lute.EscapeHTMLStr(displayName);
+ return escapeHtmlTextAndAttr(displayName);
}
return displayName;
};
diff --git a/app/tests/avAttributeNavigation.test.js b/app/tests/avAttributeNavigation.test.js
index ece9673c7f..dfd9d36098 100644
--- a/app/tests/avAttributeNavigation.test.js
+++ b/app/tests/avAttributeNavigation.test.js
@@ -13,14 +13,13 @@ const runCases = (sources) => {
let tables;
const escape = value => String(value).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
- window.Lute = {EscapeHTMLStr: escape};
window.DOMPurify = {sanitize: value => value};
window.siyuan = {config: {editor: {}}, languages: {database: "Database", empty: "Empty", untitled: "Untitled"}};
const dependencies = {
"../../../util/fetch": {fetchPost: (url, _data, callback) => callback({
data: url.endsWith("getAttributeViewKeys") ? tables : {total: 0},
})},
- "../../../util/escape": {escapeAttr: escape, escapeHtml: escape, escapeAriaLabel: escape},
+ "../../../util/escape": {escapeAttr: escape, escapeHtml: escape, escapeAriaLabel: escape, escapeHtmlTextAndAttr: escape},
"../../../emoji/fileTreeIcon": {getFileTreeIconHTML: () => "<svg></svg>"},
"../../../util/hostCapabilities": {getHostCapabilities: () => ({remoteKernel: true})},
"../../../util/functions": {isTouchDevice: () => mobile},
diff --git a/app/tests/avRelationTemplate.test.js b/app/tests/avRelationTemplate.test.js
index 02d0698740..8489f49c45 100644
--- a/app/tests/avRelationTemplate.test.js
+++ b/app/tests/avRelationTemplate.test.js
@@ -7,7 +7,6 @@ const runCases = sources => {
const assert = require("node:assert/strict");
const escape = text => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
- window.Lute = {EscapeHTMLStr: escape};
window.siyuan = {languages: {untitled: "Untitled"}, config: {editor: {allowHTMLBLockScript: false}}};
const sanitized = [];
window.DOMPurify = {sanitize: content => {
@@ -28,7 +27,7 @@ const runCases = sources => {
"./col": {getColIconByType: () => "iconText"},
"../../../emoji": {unicode2Emoji: () => ""},
"../../util/compatibility": {setStorageVal: () => {}},
- "../../../util/escape": {escapeAttr: escape, escapeHtml: escape},
+ "../../../util/escape": {escapeAttr: escape, escapeHtml: escape, escapeHtmlTextAndAttr: escape},
"../../../emoji/fileTreeIcon": {getFileTreeIconHTML: () => ""},
"../../../util/hostCapabilities": {getHostCapabilities: () => ({remoteKernel: true})},
};