Skip to content

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

:sparkles: Support dynamic and network icons in recent emojis https://github.com/siyuan-note/siyuan/issues/16386

Daniel99bdcb1adafe
diff --git a/app/src/emoji/iconValue.test.ts b/app/src/emoji/iconValue.test.ts
index f12e554200..42ae608396 100644
--- a/app/src/emoji/iconValue.test.ts
+++ b/app/src/emoji/iconValue.test.ts
@@ -1,6 +1,14 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {genEmojiImageHTML, normalizeNetworkIconURL} from "./iconValue";
+import {
+ bindDynamicIconTarget,
+ genEmojiImageHTML,
+ getIconSearchText,
+ getIconValueKind,
+ normalizeNetworkIconURL,
+ normalizeRecentIconValue,
+ updateRecentIconValues,
+} from "./iconValue";
describe("normalizeNetworkIconURL", () => {
it("accepts absolute HTTP(S) links without relying on file extensions", () => {
@@ -23,6 +31,61 @@ describe("normalizeNetworkIconURL", () => {
});
});
+describe("getIconValueKind", () => {
+ it("distinguishes supported icon value formats", () => {
+ assert.equal(getIconValueKind("1f600"), "unicode");
+ assert.equal(getIconValueKind("folder/icon.png"), "custom");
+ assert.equal(getIconValueKind("api/icon/getDynamicIcon?type=8&content=A.B"), "dynamic");
+ assert.equal(getIconValueKind("https://example.com/icon.png"), "network");
+ assert.equal(getIconValueKind("javascript:alert(1)"), "invalid");
+ });
+});
+
+describe("dynamic icon recent values", () => {
+ it("removes source IDs and canonicalizes query parameters", () => {
+ assert.equal(
+ normalizeRecentIconValue("api/icon/getDynamicIcon?type=8&content=%E6%97%A5&id=source&color=%23d23f31"),
+ "api/icon/getDynamicIcon?color=%23d23f31&content=%E6%97%A5&type=8",
+ );
+ });
+
+ it("binds text dynamic icons to the current target", () => {
+ const recent = "api/icon/getDynamicIcon?content=%E6%97%A5&type=8";
+ assert.equal(
+ bindDynamicIconTarget(recent, "current"),
+ "api/icon/getDynamicIcon?content=%E6%97%A5&id=current&type=8",
+ );
+ assert.equal(
+ bindDynamicIconTarget("api/icon/getDynamicIcon?date=&type=1", "current"),
+ "api/icon/getDynamicIcon?date=&type=1",
+ );
+ });
+
+ it("provides custom text for recent icon search", () => {
+ assert.match(getIconSearchText("api/icon/getDynamicIcon?content=%E6%97%A5&type=8"), /^日 /);
+ });
+});
+
+describe("updateRecentIconValues", () => {
+ it("moves normalized values to the front without shrinking the list", () => {
+ const values = Array.from({length: 64}, (_, index) => index === 20 ?
+ "api/icon/getDynamicIcon?type=8&content=%E6%97%A5&id=source" :
+ `1f${index.toString(16).padStart(3, "0")}`);
+ const updated = updateRecentIconValues(
+ values,
+ "api/icon/getDynamicIcon?content=%E6%97%A5&id=current&type=8",
+ 64,
+ );
+ assert.equal(updated.length, 64);
+ assert.equal(updated[0], "api/icon/getDynamicIcon?content=%E6%97%A5&type=8");
+ assert.equal(updated.filter(item => item.includes("content=%E6%97%A5")).length, 1);
+ });
+
+ it("ignores unsupported icon values", () => {
+ assert.deepEqual(updateRecentIconValues(["1f600"], "javascript:alert(1)", 64), ["1f600"]);
+ });
+});
+
describe("genEmojiImageHTML", () => {
it("renders network, dynamic, and custom image icons", () => {
assert.equal(
diff --git a/app/src/emoji/iconValue.ts b/app/src/emoji/iconValue.ts
index a014a34ce1..48a5c40250 100644
--- a/app/src/emoji/iconValue.ts
+++ b/app/src/emoji/iconValue.ts
@@ -3,6 +3,8 @@ import {escapeAttr, escapeHtml} from "../util/escape";
const DYNAMIC_ICON_PREFIX = "api/icon/getDynamicIcon";
const URL_SCHEME_PATTERN = /^[a-zA-Z][a-zA-Z\d+.-]*:/;
+export type TIconValueKind = "unicode" | "custom" | "dynamic" | "network" | "invalid";
+
export const normalizeNetworkIconURL = (value: string): string | undefined => {
const icon = value.trim();
let url: URL;
@@ -17,23 +19,102 @@ export const normalizeNetworkIconURL = (value: string): string | undefined => {
return url.href;
};
+export const getIconValueKind = (value: string): TIconValueKind => {
+ if (value.startsWith(DYNAMIC_ICON_PREFIX)) {
+ return "dynamic";
+ }
+ if (normalizeNetworkIconURL(value)) {
+ return "network";
+ }
+ if (URL_SCHEME_PATTERN.test(value) || value.startsWith("//")) {
+ return "invalid";
+ }
+ if (value.includes(".")) {
+ return "custom";
+ }
+ return "unicode";
+};
+
+export const normalizeRecentIconValue = (value: string): string | undefined => {
+ const kind = getIconValueKind(value);
+ if (kind === "invalid") {
+ return;
+ }
+ if (kind === "network") {
+ return normalizeNetworkIconURL(value);
+ }
+ if (kind !== "dynamic") {
+ return value;
+ }
+
+ const [path, query = ""] = value.split("?", 2);
+ const params = new URLSearchParams(query);
+ params.delete("id");
+ params.sort();
+ const normalizedQuery = params.toString();
+ return normalizedQuery ? `${path}?${normalizedQuery}` : path;
+};
+
+export const bindDynamicIconTarget = (value: string, targetID = ""): string => {
+ if (getIconValueKind(value) !== "dynamic") {
+ return value;
+ }
+
+ const [path, query = ""] = value.split("?", 2);
+ const params = new URLSearchParams(query);
+ if (params.get("type") === "8" && targetID) {
+ params.set("id", targetID);
+ } else {
+ params.delete("id");
+ }
+ params.sort();
+ const boundQuery = params.toString();
+ return boundQuery ? `${path}?${boundQuery}` : path;
+};
+
+export const getIconSearchText = (value: string): string => {
+ if (getIconValueKind(value) !== "dynamic") {
+ return value;
+ }
+ const query = value.split("?", 2)[1] || "";
+ const params = new URLSearchParams(query);
+ return `${params.get("content") || ""} ${value}`;
+};
+
+export const updateRecentIconValues = (values: string[], value: string, max: number): string[] => {
+ const recentValue = normalizeRecentIconValue(value);
+ if (!recentValue) {
+ return values;
+ }
+
+ const result = [recentValue];
+ const seen = new Set(result);
+ for (const item of values) {
+ const normalizedItem = normalizeRecentIconValue(item);
+ if (normalizedItem && !seen.has(normalizedItem)) {
+ result.push(normalizedItem);
+ seen.add(normalizedItem);
+ }
+ if (result.length === max) {
+ break;
+ }
+ }
+ return result;
+};
+
export const genEmojiImageHTML = (value: string, className = "", lazy = false): string | undefined => {
let src: string;
let network = false;
- if (value.startsWith(DYNAMIC_ICON_PREFIX)) {
+ const kind = getIconValueKind(value);
+ if (kind === "dynamic") {
src = value;
+ } else if (kind === "network") {
+ src = normalizeNetworkIconURL(value)!;
+ network = true;
+ } else if (kind === "custom") {
+ src = `/emojis/${value}`;
} else {
- const networkURL = normalizeNetworkIconURL(value);
- if (networkURL) {
- src = networkURL;
- network = true;
- } else if (URL_SCHEME_PATTERN.test(value) || value.startsWith("//")) {
- return;
- } else if (value.includes(".")) {
- src = `/emojis/${value}`;
- } else {
- return;
- }
+ return;
}
const safeClassName = escapeAttr(escapeHtml(className));
diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.ts
index 6d3abd4ef7..f1ea124e71 100644
--- a/app/src/emoji/index.ts
+++ b/app/src/emoji/index.ts
@@ -12,8 +12,17 @@ import {setPosition} from "../util/setPosition";
import {setStorageVal} from "../protyle/util/compatibility";
import {getLuteInstance} from "../protyle/render/setLute";
import * as dayjs from "dayjs";
-import {genEmojiImageHTML, normalizeNetworkIconURL} from "./iconValue";
+import {
+ bindDynamicIconTarget,
+ genEmojiImageHTML,
+ getIconSearchText,
+ getIconValueKind,
+ normalizeNetworkIconURL,
+ normalizeRecentIconValue,
+ updateRecentIconValues,
+} from "./iconValue";
import {showMessage} from "../dialog/message";
+import {escapeAttr, escapeHtml} from "../util/escape";
export const getRandomEmoji = () => {
const emojis = window.siyuan.emojis[getRandom(0, window.siyuan.emojis.length - 1)];
@@ -51,6 +60,13 @@ export const unicode2Emoji = (unicode: string, className = "", needSpan = false,
return emoji;
};
+const genEmojiButton = (unicode: string, label: string, lazy = false) => {
+ const safeUnicode = escapeAttr(escapeHtml(unicode));
+ const safeLabel = escapeAttr(escapeHtml(label));
+ return `<button data-unicode="${safeUnicode}" class="emojis__item ariaLabel" aria-label="${safeLabel}">
+${unicode2Emoji(unicode, "", false, lazy)}</button>`;
+};
+
export const lazyLoadEmoji = (element: HTMLElement) => {
const emojiIntersectionObserver = new IntersectionObserver((entries) => {
entries.forEach((entrie: IntersectionObserverEntry & { target: HTMLImageElement }) => {
@@ -58,8 +74,7 @@ export const lazyLoadEmoji = (element: HTMLElement) => {
if ((typeof entrie.isIntersecting === "undefined" ? entrie.intersectionRatio !== 0 : entrie.isIntersecting) && index) {
let html = "";
window.siyuan.emojis[parseInt(index)].items.forEach(emoji => {
- html += `<button data-unicode="${emoji.unicode}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(emoji)}">
-${unicode2Emoji(emoji.unicode)}</button>`;
+ html += genEmojiButton(emoji.unicode, getEmojiDesc(emoji));
});
entrie.target.innerHTML = html;
entrie.target.removeAttribute("data-index");
@@ -87,9 +102,21 @@ export const lazyLoadEmojiImg = (element: Element) => {
});
};
-export const filterEmoji = (key = "", max?: number, hideCustom = false) => {
+const isEmojiMatched = (emoji: IEmojiItem, key: string) => {
+ const lowerKey = key.toLowerCase();
+ return unicode2Emoji(emoji.unicode) === key ||
+ emoji.keywords.toLowerCase().includes(lowerKey) ||
+ emoji.description.toLowerCase().includes(lowerKey) ||
+ emoji.description_zh_cn.toLowerCase().includes(lowerKey) ||
+ emoji.description_ja_jp.toLowerCase().includes(lowerKey);
+};
+
+export const filterEmoji = (key = "", max?: number, hideCustom = false, options?: {
+ targetID?: string,
+ hideDynamic?: boolean,
+}) => {
let html = "";
- const recentEmojis: IEmojiItem[] = [];
+ const recentEmojiMap = new Map<string, IEmojiItem>();
if (key) {
html = `<div class="emojis__title">${window.siyuan.languages.emoji}</div><div class="emojis__content">`;
}
@@ -108,40 +135,21 @@ export const filterEmoji = (key = "", max?: number, hideCustom = false) => {
}
category.items.forEach(emoji => {
+ recentEmojiMap.set(emoji.unicode, emoji);
if (key) {
- if (window.siyuan.config.editor.emoji.includes(emoji.unicode) &&
- (unicode2Emoji(emoji.unicode) === key ||
- emoji.keywords.toLowerCase().indexOf(key.toLowerCase()) > -1 ||
- emoji.description.toLowerCase().indexOf(key.toLowerCase()) > -1 ||
- emoji.description_zh_cn.toLowerCase().indexOf(key.toLowerCase()) > -1 ||
- emoji.description_ja_jp.toLowerCase().indexOf(key.toLowerCase()) > -1)
- ) {
- recentEmojis.push(emoji);
- }
if (max && maxCount > max) {
return;
}
- if (unicode2Emoji(emoji.unicode) === key ||
- emoji.keywords.toLowerCase().indexOf(key.toLowerCase()) > -1 ||
- emoji.description.toLowerCase().indexOf(key.toLowerCase()) > -1 ||
- emoji.description_zh_cn.toLowerCase().indexOf(key.toLowerCase()) > -1 ||
- emoji.description_ja_jp.toLowerCase().indexOf(key.toLowerCase()) > -1) {
+ if (isEmojiMatched(emoji, key)) {
if (category.id === "custom") {
customStore.push(emoji);
} else {
- keyHTML += `<button data-unicode="${emoji.unicode}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(emoji)}">
-${unicode2Emoji(emoji.unicode, undefined, false, true)}</button>`;
+ keyHTML += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);
}
maxCount++;
}
- } else {
- if (window.siyuan.config.editor.emoji.includes(emoji.unicode)) {
- recentEmojis.push(emoji);
- }
- if (index < 2) {
- html += `<button data-unicode="${emoji.unicode}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(emoji)}">
-${unicode2Emoji(emoji.unicode, undefined, false, true)}</button>`;
- }
+ } else if (index < 2) {
+ html += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);
}
});
if (!key) {
@@ -164,24 +172,40 @@ ${unicode2Emoji(emoji.unicode, undefined, false, true)}</button>`;
}
return 0;
}).forEach(item => {
- html += `<button data-unicode="${item.unicode}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(item)}">
-${unicode2Emoji(item.unicode, undefined, false, true)}</button>`;
+ html += genEmojiButton(item.unicode, getEmojiDesc(item), true);
});
html = html + keyHTML + "</div>";
}
- let recentHTML = "";
- if (recentEmojis.length > 0) {
- recentHTML = `<div class="emojis__title" data-type="0">${window.siyuan.languages.recentEmoji}</div><div class="emojis__content">`;
- window.siyuan.config.editor.emoji.forEach(emojiUnicode => {
- const emoji = recentEmojis.filter((item) => item.unicode === emojiUnicode);
- if (emoji[0]) {
- recentHTML += `<button data-unicode="${emoji[0].unicode}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(emoji[0])}">
-${unicode2Emoji(emoji[0].unicode, undefined, false, true)}
-</button>`;
+
+ let recentItemsHTML = "";
+ const renderedRecentValues = new Set<string>();
+ window.siyuan.config.editor.emoji.forEach((value) => {
+ const recentValue = normalizeRecentIconValue(value);
+ if (!recentValue || renderedRecentValues.has(recentValue)) {
+ return;
+ }
+ renderedRecentValues.add(recentValue);
+ const emoji = recentEmojiMap.get(recentValue);
+ if (emoji) {
+ if (!key || isEmojiMatched(emoji, key)) {
+ recentItemsHTML += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);
}
- });
- recentHTML += "</div>";
- }
+ return;
+ }
+
+ const kind = getIconValueKind(recentValue);
+ if ((kind !== "dynamic" && kind !== "network") || (kind === "dynamic" && options?.hideDynamic)) {
+ return;
+ }
+ if (key && !getIconSearchText(recentValue).toLowerCase().includes(key.toLowerCase())) {
+ return;
+ }
+ const displayValue = bindDynamicIconTarget(recentValue, options?.targetID);
+ const label = kind === "dynamic" ? window.siyuan.languages.dynamicIcon : recentValue;
+ recentItemsHTML += genEmojiButton(displayValue, label, true);
+ });
+ const recentHTML = recentItemsHTML ?
+ `<div class="emojis__title" data-type="0">${window.siyuan.languages.recentEmoji}</div><div class="emojis__content">${recentItemsHTML}</div>` : "";
if (recentHTML + html === "") {
return `<div class="emojis__title">${window.siyuan.languages.emptyContent}</div>`;
@@ -190,11 +214,11 @@ ${unicode2Emoji(emoji[0].unicode, undefined, false, true)}
};
export const addEmoji = (unicode: string) => {
- window.siyuan.config.editor.emoji.unshift(unicode);
- if (window.siyuan.config.editor.emoji.length > Constants.SIZE_UNDO) {
- window.siyuan.config.editor.emoji.pop();
- }
- window.siyuan.config.editor.emoji = Array.from(new Set(window.siyuan.config.editor.emoji));
+ window.siyuan.config.editor.emoji = updateRecentIconValues(
+ window.siyuan.config.editor.emoji,
+ unicode,
+ Constants.SIZE_UNDO,
+ );
fetchPost("/api/setting/setEmoji", {emoji: window.siyuan.config.editor.emoji});
};
@@ -243,7 +267,8 @@ export const openEmojiPanel = (
options?: {
dynamic?: boolean,
custom?: boolean,
- ownerElement?: HTMLElement
+ ownerElement?: HTMLElement,
+ targetID?: string,
}) => {
if (type !== "av") {
window.siyuan.menus.menu.remove();
@@ -252,6 +277,7 @@ export const openEmojiPanel = (
}
const popoverElement = options?.ownerElement?.closest<HTMLElement>(".block__popover");
+ const targetID = options?.targetID || id;
const dynamicURL = "api/icon/getDynamicIcon?";
const dynamicCurrentObj: Record<string, any> = {
color: "#d23f31",
@@ -274,6 +300,10 @@ export const openEmojiPanel = (
dynamicCurrentObj.type = dynamicCurrentUrl.get("type") || "1";
dynamicCurrentObj.content = dynamicCurrentUrl.get("content") || "SiYuan";
}
+ const dynamicTextURL = bindDynamicIconTarget(
+ `${dynamicURL}type=8&color=${encodeURIComponent(dynamicCurrentObj.color)}&content=${encodeURIComponent(dynamicCurrentObj.content)}`,
+ targetID,
+ );
const dialog = new Dialog({
disableAnimation: true,
@@ -304,7 +334,10 @@ export const openEmojiPanel = (
<span class="block__icon block__icon--show fn__flex-center ariaLabel" data-action="random" aria-label="${window.siyuan.languages.random}"><svg><use xlink:href="#iconRefresh"></use></svg></span>
<span class="fn__space"></span>
</div>
- <div class="emojis__panel">${filterEmoji("", null, options?.custom)}</div>
+ <div class="emojis__panel">${filterEmoji("", null, options?.custom, {
+ targetID,
+ hideDynamic: options?.dynamic,
+ })}</div>
<div class="fn__flex">
${[
["2b50", window.siyuan.languages.recentEmoji],
@@ -388,7 +421,7 @@ export const openEmojiPanel = (
<span class="fn__space"></span>
</div>
<div>
- <img data-type="text" class="emoji__dynamic-item${dynamicCurrentObj.type === "8" ? " emoji__dynamic-item--current" : ""}" src="${dynamicURL}type=8&color=${encodeURIComponent(dynamicCurrentObj.color)}&content=${encodeURIComponent(dynamicCurrentObj.content)}&id=${id}">
+ <img data-type="text" class="emoji__dynamic-item${dynamicCurrentObj.type === "8" ? " emoji__dynamic-item--current" : ""}" src="${escapeAttr(escapeHtml(dynamicTextURL))}">
</div>
</div>
<div class="fn__none emojis__link" data-type="tab-link">
@@ -455,6 +488,7 @@ export const openEmojiPanel = (
if (callback) {
callback(unicode);
}
+ addEmoji(unicode);
dialog.destroy();
};
networkIconInputElement.addEventListener("input", renderNetworkIconPreview);
@@ -470,7 +504,10 @@ export const openEmojiPanel = (
const emojiSearchInputElement = dialog.element.querySelector('[data-type="tab-emoji"] .b3-text-field') as HTMLInputElement;
const emojisContentElement = dialog.element.querySelector(".emojis__panel");
emojiSearchInputElement.addEventListener("compositionend", () => {
- emojisContentElement.innerHTML = filterEmoji(emojiSearchInputElement.value, null, options?.custom);
+ emojisContentElement.innerHTML = filterEmoji(emojiSearchInputElement.value, null, options?.custom, {
+ targetID,
+ hideDynamic: options?.dynamic,
+ });
if (emojiSearchInputElement.value) {
emojisContentElement.nextElementSibling.classList.add("fn__none");
} else {
@@ -487,7 +524,10 @@ export const openEmojiPanel = (
if (event.isComposing) {
return;
}
- emojisContentElement.innerHTML = filterEmoji(emojiSearchInputElement.value, null, options?.custom);
+ emojisContentElement.innerHTML = filterEmoji(emojiSearchInputElement.value, null, options?.custom, {
+ targetID,
+ hideDynamic: options?.dynamic,
+ });
if (emojiSearchInputElement.value) {
emojisContentElement.nextElementSibling.classList.add("fn__none");
} else {
diff --git a/app/src/plugin/API.ts b/app/src/plugin/API.ts
index 6537a44a18..23d3bc220e 100644
--- a/app/src/plugin/API.ts
+++ b/app/src/plugin/API.ts
@@ -326,6 +326,7 @@ const openEmoji = (options: {
dynamicIconURL?: string
hideDynamicIcon?: boolean
hideCustomIcon?: boolean
+ targetID?: string
}) => {
let dynamicImgElement: HTMLImageElement;
if (options.dynamicIconURL) {
@@ -334,7 +335,8 @@ const openEmoji = (options: {
}
openEmojiPanel("", "av", options.position, options.selectedCB, dynamicImgElement, {
dynamic: options.hideDynamicIcon,
- custom: options.hideCustomIcon
+ custom: options.hideCustomIcon,
+ targetID: options.targetID,
});
};
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 3c732a173e..097b38fa86 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -54,6 +54,15 @@ import {avRender} from "../render/av/render";
import {genIconHTML} from "../render/util";
import {updateAttrViewCellAnimation} from "../render/av/action";
import {setFold} from "../util/blockFold";
+import {getIconValueKind} from "../../emoji/iconValue";
+
+const genEmojiInsertHTML = (value: string) => {
+ const kind = getIconValueKind(value);
+ if (kind === "custom") {
+ return `:${value.split(".")[0]}: `;
+ }
+ return unicode2Emoji(value, kind === "dynamic" || kind === "network" ? "emoji" : "") + " ";
+};
export class Hint {
public timeId: number;
@@ -118,13 +127,7 @@ ${unicode2Emoji(emoji.unicode)}</button>`;
range.endContainer.textContent = "";
}
addEmoji(unicode);
- let emoji;
- if (unicode.indexOf(".") > -1) {
- emoji = `:${unicode.split(".")[0]}: `;
- } else {
- emoji = unicode2Emoji(unicode) + " ";
- }
- insertHTML(protyle.lute.SpinBlockDOM(emoji), protyle, false, true);
+ insertHTML(protyle.lute.SpinBlockDOM(genEmojiInsertHTML(unicode)), protyle, false, true);
this.element.classList.add("fn__none");
} else {
this.fill(unicode, protyle);
@@ -420,9 +423,11 @@ ${genHintItemHTML(item)}
return;
}
+ const targetElement = hasClosestBlock(protyle.toolbar.range?.startContainer);
+ const targetID = targetElement ? targetElement.getAttribute("data-node-id") : protyle.block.rootID;
const panelElement = this.element.querySelector(".emojis__panel");
if (panelElement) {
- panelElement.innerHTML = filterEmoji(value, 256);
+ panelElement.innerHTML = filterEmoji(value, 256, false, {targetID});
if (value) {
panelElement.nextElementSibling.classList.add("fn__none");
} else {
@@ -432,7 +437,7 @@ ${genHintItemHTML(item)}
} else {
// max-height:min(402px,40vh) 和 .protyle-hint 保持一致,否则 emoji 不显示底部导航
this.element.innerHTML = `<div style="padding:0;max-height:min(402px,40vh);width:366px" class="emojis">
-<div class="emojis__panel">${filterEmoji(value, 256)}</div>
+<div class="emojis__panel">${filterEmoji(value, 256, false, {targetID})}</div>
<div class="fn__flex${value ? " fn__none" : ""}">
${[
["2b50", window.siyuan.languages.recentEmoji],
@@ -642,13 +647,7 @@ ${genHintItemHTML(item)}
return;
} else if (this.splitChar === ":") {
addEmoji(value);
- let emoji;
- if (value.indexOf(".") > -1) {
- emoji = `:${value.split(".")[0]}: `;
- } else {
- emoji = unicode2Emoji(value) + " ";
- }
- insertHTML(protyle.lute.SpinBlockDOM(emoji), protyle);
+ insertHTML(protyle.lute.SpinBlockDOM(genEmojiInsertHTML(value)), protyle);
} else if (["「「", "「『", "『「", "『『", "{{"].includes(this.splitChar) || this.splitChar === "#" || this.splitChar === ":") {
if (value === "") {
const editElement = getContenteditableElement(nodeElement);
@@ -1003,13 +1002,7 @@ ${genHintItemHTML(item)}
range.endContainer.childNodes[range.endOffset - 1]?.remove();
}
addEmoji(unicode);
- let emoji;
- if (unicode.indexOf(".") > -1) {
- emoji = `:${unicode.split(".")[0]}: `;
- } else {
- emoji = unicode2Emoji(unicode) + " ";
- }
- insertHTML(protyle.lute.SpinBlockDOM(emoji), protyle);
+ insertHTML(protyle.lute.SpinBlockDOM(genEmojiInsertHTML(unicode)), protyle);
this.element.classList.add("fn__none");
} else {
this.fill(unicode, protyle);
diff --git a/app/src/protyle/render/av/col.ts b/app/src/protyle/render/av/col.ts
index 84f2a5ae57..b53035c8e7 100644
--- a/app/src/protyle/render/av/col.ts
+++ b/app/src/protyle/render/av/col.ts
@@ -856,7 +856,10 @@ export const showColMenu = (protyle: IProtyle, blockElement: Element, cellElemen
}]);
iconElement.innerHTML = unicode ? unicode2Emoji(unicode) : `<svg style="height: 14px;width: 14px"><use xlink:href="#${getColIconByType(type)}"></use></svg>`;
updateAttrViewCellAnimation(blockElement.querySelector(`.av__row--header .av__cell[data-col-id="${colId}"]`), undefined, {icon: unicode});
- }, iconElement.querySelector("img"), {ownerElement: protyle.element});
+ }, iconElement.querySelector("img"), {
+ ownerElement: protyle.element,
+ targetID: protyle.block.rootID,
+ });
event.preventDefault();
event.stopPropagation();
});
diff --git a/app/src/protyle/render/av/newItemTemplate.ts b/app/src/protyle/render/av/newItemTemplate.ts
index 8429bfbd3b..eda4d0af94 100644
--- a/app/src/protyle/render/av/newItemTemplate.ts
+++ b/app/src/protyle/render/av/newItemTemplate.ts
@@ -636,7 +636,10 @@ export const openNewItemTemplateDialog = (options: {
}, unicode => {
iconElement.dataset.value = unicode;
emojiElement.innerHTML = unicode2Emoji(unicode || window.siyuan.storage[Constants.LOCAL_IMAGES].file);
- }, emojiElement.querySelector("img"), {ownerElement: options.protyle.element});
+ }, emojiElement.querySelector("img"), {
+ ownerElement: options.protyle.element,
+ targetID: options.protyle.block.rootID,
+ });
event.preventDefault();
event.stopPropagation();
});
diff --git a/app/src/protyle/render/av/openMenuPanel.ts b/app/src/protyle/render/av/openMenuPanel.ts
index 598a7adde7..8e66676de4 100644
--- a/app/src/protyle/render/av/openMenuPanel.ts
+++ b/app/src/protyle/render/av/openMenuPanel.ts
@@ -1121,7 +1121,10 @@ export const openMenuPanel = (options: {
}]);
target.innerHTML = unicode ? unicode2Emoji(unicode) : '<svg style="width: 14px;height: 14px;"><use xlink:href="#iconTable"></use></svg>';
target.dataset.icon = unicode;
- }, target.querySelector("img"), {ownerElement: options.protyle.element});
+ }, target.querySelector("img"), {
+ ownerElement: options.protyle.element,
+ targetID: options.protyle.block.rootID,
+ });
event.preventDefault();
event.stopPropagation();
break;
@@ -1192,7 +1195,10 @@ export const openMenuPanel = (options: {
updateAttrViewCellAnimation(options.blockElement.querySelector(`.av__row--header .av__cell[data-col-id="${colId}"]`), undefined, {icon: unicode});
}
target.dataset.icon = unicode;
- }, target.querySelector("img"), {ownerElement: options.protyle.element});
+ }, target.querySelector("img"), {
+ ownerElement: options.protyle.element,
+ targetID: options.protyle.block.rootID,
+ });
event.preventDefault();
event.stopPropagation();
break;
diff --git a/app/src/protyle/wysiwyg/callout.ts b/app/src/protyle/wysiwyg/callout.ts
index 9470b1018d..e18a4b03c1 100644
--- a/app/src/protyle/wysiwyg/callout.ts
+++ b/app/src/protyle/wysiwyg/callout.ts
@@ -117,14 +117,7 @@ export const updateCalloutType = (blockElements: HTMLElement[], protyle: IProtyl
h: emojiRect.height,
w: emojiRect.width
}, (unicode) => {
- let emojiHTML;
- if (unicode.startsWith("api/icon/getDynamicIcon")) {
- emojiHTML = `<img class="callout-img" src="${unicode}"/>`;
- } else if (unicode.indexOf(".") > -1) {
- emojiHTML = `<img class="callout-img" src="/emojis/${unicode}">`;
- } else {
- emojiHTML = unicode2Emoji(unicode);
- }
+ let emojiHTML = unicode2Emoji(unicode, "callout-img");
if (unicode === "") {
if (textElements[0].value === "NOTE") {
emojiHTML = "✏️";
@@ -139,7 +132,10 @@ export const updateCalloutType = (blockElements: HTMLElement[], protyle: IProtyl
}
}
dialogCalloutIconElement.innerHTML = emojiHTML;
- }, dialogCalloutIconElement.querySelector("img"), {ownerElement: protyle.element});
+ }, dialogCalloutIconElement.querySelector("img"), {
+ ownerElement: protyle.element,
+ targetID: blockElements[0].dataset.nodeId,
+ });
});
dialog.element.querySelector(".b3-form__icona-icon").addEventListener("click", (event) => {
const menu = new Menu(Constants.MENU_CALLOUT_SELECT, () => {
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index f99d83a94c..c3b9bfa137 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -101,6 +101,8 @@ import {
} from "../render/av/cell";
import {getAVSelectedCells} from "../render/av/selectionState";
import {openEmojiPanel, unicode2Emoji} from "../../emoji";
+import {getIconValueKind} from "../../emoji/iconValue";
+import {escapeAttr, escapeHtml} from "../../util/escape";
import {openLink} from "../../editor/openLink";
import {mathRender} from "../render/mathRender";
import {editAssetItem} from "../render/av/asset";
@@ -3992,14 +3994,7 @@ export class WYSIWYG {
w: emojiRect.width
}, (unicode) => {
const oldHTML = nodeElement.outerHTML;
- let emojiHTML;
- if (unicode.startsWith("api/icon/getDynamicIcon")) {
- emojiHTML = `<img class="callout-img" src="${unicode}"/>`;
- } else if (unicode.indexOf(".") > -1) {
- emojiHTML = `<img class="callout-img" src="/emojis/${unicode}">`;
- } else {
- emojiHTML = unicode2Emoji(unicode);
- }
+ let emojiHTML = unicode2Emoji(unicode, "callout-img");
if (unicode === "") {
const subType = nodeElement.getAttribute("data-subtype");
if (subType === "NOTE") {
@@ -4017,7 +4012,10 @@ export class WYSIWYG {
calloutIconElement.innerHTML = emojiHTML;
updateTransaction(protyle, nodeElement, oldHTML);
focusBlock(nodeElement);
- }, calloutIconElement.querySelector("img"), {ownerElement: protyle.element});
+ }, calloutIconElement.querySelector("img"), {
+ ownerElement: protyle.element,
+ targetID: nodeElement.dataset.nodeId,
+ });
}
event.preventDefault();
event.stopPropagation();
@@ -4037,20 +4035,20 @@ export class WYSIWYG {
}, (unicode) => {
emojiElement.insertAdjacentHTML("afterend", "<wbr>");
const oldHTML = nodeElement.outerHTML;
- let emojiHTML;
- if (unicode.startsWith("api/icon/getDynamicIcon")) {
- emojiHTML = `<img class="emoji" src="${unicode}"/>`;
- } else if (unicode.indexOf(".") > -1) {
- const emojiList = unicode.split(".");
- emojiHTML = `<img alt="${emojiList[0]}" class="emoji" src="/emojis/${unicode}" title="${emojiList[0]}">`;
- } else {
- emojiHTML = unicode2Emoji(unicode);
+ let emojiHTML = unicode2Emoji(unicode, "emoji");
+ if (getIconValueKind(unicode) === "custom") {
+ const emojiName = escapeAttr(escapeHtml(unicode.split(".")[0]));
+ const emojiPath = escapeAttr(escapeHtml(unicode));
+ emojiHTML = `<img alt="${emojiName}" class="emoji" src="/emojis/${emojiPath}" title="${emojiName}">`;
}
emojiElement.outerHTML = emojiHTML;
hideElements(["dialog"]);
updateTransaction(protyle, nodeElement, oldHTML);
focusByWbr(nodeElement, range);
- }, emojiElement, {ownerElement: protyle.element});
+ }, emojiElement, {
+ ownerElement: protyle.element,
+ targetID: nodeElement.dataset.nodeId,
+ });
}
return;
}
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index 12766cf5e2..0a790a9ef9 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -901,13 +901,13 @@ func setEmoji(c *gin.Context) {
argEmoji := arg["emoji"].([]any)
var emoji []string
+ seen := map[string]bool{}
for _, ae := range argEmoji {
e := ae.(string)
- if strings.Contains(e, ".") {
- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- e = util.FilterUploadEmojiFileName(e)
+ if e, valid := util.FilterRecentIconValue(e); valid && !seen[e] {
+ emoji = append(emoji, e)
+ seen[e] = true
}
- emoji = append(emoji, e)
}
model.Conf.Editor.Emoji = emoji
diff --git a/kernel/model/box.go b/kernel/model/box.go
index c534230733..d02c5f8942 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -20,7 +20,6 @@ import (
"bytes"
"errors"
"fmt"
- "net/url"
"os"
"path"
"path/filepath"
@@ -945,20 +944,14 @@ func SetBoxIcon(boxID, icon string) {
}
func filterBoxIcon(icon string) string {
- networkURL := strings.TrimSpace(icon)
- if isNetworkIconURL(networkURL) {
- return networkURL
+ if filtered, valid := util.FilterIconValue(icon); valid {
+ return filtered
}
- if strings.Contains(icon, ".") {
- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- icon = util.FilterUploadEmojiFileName(icon)
- }
- return icon
+ return ""
}
func isNetworkIconURL(icon string) bool {
- u, err := url.Parse(icon)
- return nil == err && "" != u.Host && ("http" == strings.ToLower(u.Scheme) || "https" == strings.ToLower(u.Scheme))
+ return util.IsNetworkIconURL(icon)
}
func (box *Box) UpdateHistoryGenerated() {
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index 98ebf3640c..76f4283768 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -375,13 +375,15 @@ func InitConf() {
if 1 > len(Conf.Editor.Emoji) {
Conf.Editor.Emoji = []string{}
}
- for i, emoji := range Conf.Editor.Emoji {
- if strings.Contains(emoji, ".") {
- // XSS through emoji name https://github.com/siyuan-note/siyuan/issues/15034
- emoji = util.FilterUploadEmojiFileName(emoji)
- Conf.Editor.Emoji[i] = emoji
+ var filteredEmojis []string
+ seenEmojis := map[string]bool{}
+ for _, emoji := range Conf.Editor.Emoji {
+ if emoji, valid := util.FilterRecentIconValue(emoji); valid && !seenEmojis[emoji] {
+ filteredEmojis = append(filteredEmojis, emoji)
+ seenEmojis[emoji] = true
}
}
+ Conf.Editor.Emoji = filteredEmojis
if 9 > Conf.Editor.FontSize || 72 < Conf.Editor.FontSize {
Conf.Editor.FontSize = 16
}
diff --git a/kernel/util/file.go b/kernel/util/file.go
index 3f61e4a186..0593827faa 100644
--- a/kernel/util/file.go
+++ b/kernel/util/file.go
@@ -21,6 +21,7 @@ import (
"io"
"io/fs"
"mime"
+ "net/url"
"os"
"path"
"path/filepath"
@@ -216,6 +217,43 @@ func IsValidUploadFileName(name string) bool {
return name == FilterUploadFileName(name)
}
+func IsNetworkIconURL(icon string) bool {
+ u, err := url.Parse(icon)
+ return nil == err && "" != u.Host && ("http" == strings.ToLower(u.Scheme) || "https" == strings.ToLower(u.Scheme))
+}
+
+func FilterIconValue(icon string) (ret string, valid bool) {
+ ret = strings.TrimSpace(icon)
+ if strings.HasPrefix(ret, "api/icon/") || IsNetworkIconURL(ret) {
+ return ret, true
+ }
+
+ u, err := url.Parse(ret)
+ if strings.HasPrefix(ret, "//") || (nil == err && "" != u.Scheme) {
+ return "", false
+ }
+ if strings.Contains(ret, ".") {
+ ret = FilterUploadEmojiFileName(ret)
+ }
+ return ret, true
+}
+
+func FilterRecentIconValue(icon string) (ret string, valid bool) {
+ ret, valid = FilterIconValue(icon)
+ if !valid || !strings.HasPrefix(ret, "api/icon/getDynamicIcon") {
+ return
+ }
+
+ u, err := url.Parse(ret)
+ if nil != err {
+ return "", false
+ }
+ query := u.Query()
+ query.Del("id")
+ u.RawQuery = query.Encode()
+ return u.String(), true
+}
+
func FilterUploadEmojiFileName(name string) string {
if strings.HasPrefix(name, "api/icon/") {
// 忽略动态图标 https://github.com/siyuan-note/siyuan/issues/15139
diff --git a/kernel/util/icon_test.go b/kernel/util/icon_test.go
new file mode 100644
index 0000000000..d09ae2a352
--- /dev/null
+++ b/kernel/util/icon_test.go
@@ -0,0 +1,74 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package util
+
+import "testing"
+
+func TestFilterIconValuePreservesSupportedValues(t *testing.T) {
+ for _, icon := range []string{
+ "1f600",
+ "folder/icon.png",
+ "api/icon/getDynamicIcon?type=8&content=A.B",
+ "https://example.com/icon?id=1&size=2",
+ "http://127.0.0.1:8080/icon",
+ } {
+ filtered, valid := FilterIconValue(icon)
+ if !valid {
+ t.Fatalf("supported icon value was rejected [%q]", icon)
+ }
+ if filtered != icon {
+ t.Fatalf("supported icon value was changed [expected=%q, actual=%q]", icon, filtered)
+ }
+ }
+}
+
+func TestFilterIconValueRejectsUnsupportedURLs(t *testing.T) {
+ for _, icon := range []string{
+ "data:image/png;base64,AAAA",
+ "file:///tmp/icon.png",
+ "ftp://example.com/icon.png",
+ "javascript:alert(1)",
+ "//example.com/icon.png",
+ } {
+ if filtered, valid := FilterIconValue(icon); valid {
+ t.Fatalf("unsupported icon URL was accepted [input=%q, actual=%q]", icon, filtered)
+ }
+ }
+}
+
+func TestFilterIconValueSanitizesCustomEmoji(t *testing.T) {
+ icon := `" onerror="alert(1).png`
+ filtered, valid := FilterIconValue(icon)
+ if !valid {
+ t.Fatalf("custom emoji was rejected [%q]", icon)
+ }
+ if filtered == icon {
+ t.Fatalf("unsafe custom emoji filename was preserved [%q]", icon)
+ }
+}
+
+func TestFilterRecentIconValueRemovesDynamicIconID(t *testing.T) {
+ icon := "api/icon/getDynamicIcon?type=8&content=%E6%97%A5&id=source&color=%23d23f31"
+ filtered, valid := FilterRecentIconValue(icon)
+ if !valid {
+ t.Fatalf("dynamic icon was rejected [%q]", icon)
+ }
+ expected := "api/icon/getDynamicIcon?color=%23d23f31&content=%E6%97%A5&type=8"
+ if filtered != expected {
+ t.Fatalf("dynamic icon was not canonicalized [expected=%q, actual=%q]", expected, filtered)
+ }
+}