An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve emoji picker organization and loading performance https://github.com/siyuan-note/siyuan/issues/13563
Danielc0b49825f71a
diff --git a/app/src/assets/scss/business/_emojis.scss b/app/src/assets/scss/business/_emojis.scssindex f4c35bc9d3..caa82dc2a4 100644--- a/app/src/assets/scss/business/_emojis.scss+++ b/app/src/assets/scss/business/_emojis.scss@@ -75,10 +75,18 @@}&__title {+ position: sticky;+ z-index: 1;+ top: 0;color: var(--b3-theme-on-surface);+ background-color: var(--b3-theme-background);padding: 8px 4px 4px 4px;}+ &__section {+ position: relative;+ }+&__panel {flex: 1;overflow: auto;@@ -215,6 +223,10 @@flex-wrap: wrap;}+ &__load {+ height: 1px;+ }+&__type {cursor: pointer;flex: 1;@@ -231,6 +243,7 @@font-family: var(--b3-font-family-emoji);font-variant-emoji: emoji;+ &--current,&:hover {background-color: var(--b3-theme-surface-lighter);}diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.tsindex 01641615c7..58af2ba3e1 100644--- a/app/src/emoji/index.ts+++ b/app/src/emoji/index.ts@@ -23,6 +23,13 @@ import {} from "./iconValue";import {showMessage} from "../dialog/message";import {escapeAttr, escapeHtml} from "../util/escape";+import {+ collectEmojiMatches,+ getCustomEmojiBatch,+ getEmojiItemMap,+ groupCustomEmojiItems,+ TCustomEmojiGroup,+} from "./panel";export const getRandomEmoji = () => {const emojis = window.siyuan.emojis[getRandom(0, window.siyuan.emojis.length - 1)];@@ -68,41 +75,6 @@ const genEmojiButton = (unicode: string, label: string, lazy = false) => {${unicode2Emoji(unicode, "", false, lazy)}</button>`;};-export const lazyLoadEmoji = (element: HTMLElement) => {- const emojiIntersectionObserver = new IntersectionObserver((entries) => {- entries.forEach((entrie: IntersectionObserverEntry & { target: HTMLImageElement }) => {- const index = entrie.target.getAttribute("data-index");- if ((typeof entrie.isIntersecting === "undefined" ? entrie.intersectionRatio !== 0 : entrie.isIntersecting) && index) {- let html = "";- window.siyuan.emojis[parseInt(index)].items.forEach(emoji => {- html += genEmojiButton(emoji.unicode, getEmojiDesc(emoji));- });- entrie.target.innerHTML = html;- entrie.target.removeAttribute("data-index");- entrie.target.style.minHeight = "";- }- });- });- element.querySelectorAll(".emojis__content").forEach((panelElement) => {- emojiIntersectionObserver.observe(panelElement);- });-};--export const lazyLoadEmojiImg = (element: Element) => {- const emojiIntersectionObserver = new IntersectionObserver((entries) => {- entries.forEach((entrie: IntersectionObserverEntry & { target: HTMLImageElement }) => {- const src = entrie.target.getAttribute("data-src");- if ((typeof entrie.isIntersecting === "undefined" ? entrie.intersectionRatio !== 0 : entrie.isIntersecting) && src) {- entrie.target.src = src;- entrie.target.removeAttribute("data-src");- }- });- });- element.querySelectorAll("img").forEach((panelElement) => {- emojiIntersectionObserver.observe(panelElement);- });-};-const isEmojiMatched = (emoji: IEmojiItem, key: string) => {const lowerKey = key.toLowerCase();return unicode2Emoji(emoji.unicode) === key ||@@ -112,73 +84,33 @@ const isEmojiMatched = (emoji: IEmojiItem, key: string) => {emoji.description_ja_jp.toLowerCase().includes(lowerKey);};-export const filterEmoji = (key = "", max?: number, hideCustom = false, options?: {+type TEmojiPanelOptions = {targetID?: string,hideDynamic?: boolean,-}) => {- let html = "";- const recentEmojiMap = new Map<string, IEmojiItem>();- if (key) {- html = `<div class="emojis__title">${window.siyuan.languages.emoji}</div><div class="emojis__content">`;- }- let maxCount = 0;- let keyHTML = "";- const customStore: IEmojiItem[] = [];- window.siyuan.emojis.forEach((category, index) => {- if (hideCustom && category.id === "custom") {- return;- }- if (!key) {- html += `<div class="emojis__title" data-type="${index + 1}">${getEmojiTitle(index)}</div><div style="min-height:${index === 0 ? "30px" : "300px"}" class="emojis__content"${index > 1 ? ' data-index="' + index + '"' : ""}>`;- }- if (category.items.length === 0 && index === 0 && !key) {- html += `<div style="margin-left: 4px">${window.siyuan.languages.setEmojiTip}</div>`;- }+ hideCustom?: boolean,+};- category.items.forEach(emoji => {- recentEmojiMap.set(emoji.unicode, emoji);- if (key) {- if (max && maxCount > max) {- return;- }- if (isEmojiMatched(emoji, key)) {- if (category.id === "custom") {- customStore.push(emoji);- } else {- keyHTML += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);- }- maxCount++;- }- } else if (index < 2) {- html += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);- }- });- if (!key) {- html += "</div>";- }- });- if (key) {- customStore.sort((a, b) => {- const aKeywords = a.keywords.split("/");- const bKeywords = b.keywords.split("/");- if (aKeywords[aKeywords.length - 1].toLowerCase().indexOf(key.toLowerCase()) < bKeywords[bKeywords.length - 1].toLowerCase().indexOf(key.toLowerCase())) {- return -1;- }- return 0;- }).sort((a, b) => {- const aKeywords = a.keywords.split("/");- const bKeywords = b.keywords.split("/");- if (aKeywords[aKeywords.length - 1].toLowerCase().indexOf(key.toLowerCase()) === bKeywords[bKeywords.length - 1].toLowerCase().indexOf(key.toLowerCase()) && aKeywords[aKeywords.length - 1].length < bKeywords[bKeywords.length - 1].length) {- return -1;- }- return 0;- }).forEach(item => {- html += genEmojiButton(item.unicode, getEmojiDesc(item), true);- });- html = html + keyHTML + "</div>";- }+const emojiCategoryIcons: Record<string, string> = {+ custom: "1f527",+ people: "1f60d",+ nature: "1f433",+ food: "1f96a",+ activity: "1f3a8",+ travel: "1f3dd-fe0f",+ objects: "1f52e",+ symbols: "267e-fe0f",+ flags: "1f6a9",+};- let recentItemsHTML = "";+const genEmojiSection = (title: string, content: string, groupName?: string) => {+ const groupAttribute = typeof groupName === "string" ? ` data-group="${escapeAttr(escapeHtml(groupName))}"` : "";+ const titleHTML = title ? `<div class="emojis__title">${escapeHtml(title)}</div>` : "";+ return `<div class="emojis__section"${groupAttribute}>${titleHTML}<div class="emojis__content">${content}</div></div>`;+};++const getRecentEmojiButtons = (key: string, options: TEmojiPanelOptions) => {+ const recentEmojiMap = getEmojiItemMap(window.siyuan.emojis, options.hideCustom);+ let html = "";const renderedRecentValues = new Set<string>();window.siyuan.config.editor.emoji.forEach((value) => {const recentValue = normalizeRecentIconValue(value);@@ -189,7 +121,7 @@ export const filterEmoji = (key = "", max?: number, hideCustom = false, options?const emoji = recentEmojiMap.get(recentValue);if (emoji) {if (!key || isEmojiMatched(emoji, key)) {- recentItemsHTML += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);+ html += genEmojiButton(emoji.unicode, getEmojiDesc(emoji), true);}return;}@@ -203,15 +135,263 @@ export const filterEmoji = (key = "", max?: number, hideCustom = false, options?}const displayValue = bindDynamicIconTarget(recentValue, options?.targetID);const label = kind === "dynamic" ? window.siyuan.languages.dynamicIcon : recentValue;- recentItemsHTML += genEmojiButton(displayValue, label, true);+ html += 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>` : "";+ return html;+};++const genEmojiSearchHTML = (key: string, max: number | undefined, options: TEmojiPanelOptions) => {+ const {customItems, builtInItems} = collectEmojiMatches(+ window.siyuan.emojis,+ (item) => isEmojiMatched(item, key),+ max,+ options.hideCustom,+ );+ customItems.sort((a, b) => {+ const lowerKey = key.toLowerCase();+ const aName = a.keywords.split("/").pop().toLowerCase();+ const bName = b.keywords.split("/").pop().toLowerCase();+ const positionDiff = aName.indexOf(lowerKey) - bName.indexOf(lowerKey);+ return positionDiff || aName.length - bName.length;+ });+ const resultHTML = [...customItems, ...builtInItems]+ .map((item) => genEmojiButton(item.unicode, getEmojiDesc(item), true)).join("");+ const recentHTML = getRecentEmojiButtons(key, options);+ if (!recentHTML && !resultHTML) {+ return `<div class="emojis__section"><div class="emojis__title">${window.siyuan.languages.emptyContent}</div></div>`;+ }+ return (recentHTML ? genEmojiSection(window.siyuan.languages.recentEmoji, recentHTML) : "") ++ (resultHTML ? genEmojiSection(window.siyuan.languages.emoji, resultHTML) : "");+};++export const genEmojiCategoryButtons = (hideCustom = false) => {+ const categories = [{+ id: "recent",+ unicode: "2b50",+ title: window.siyuan.languages.recentEmoji,+ }];+ window.siyuan.emojis.forEach((category, index) => {+ if (hideCustom && category.id === "custom") {+ return;+ }+ categories.push({+ id: category.id,+ unicode: emojiCategoryIcons[category.id] || "2753",+ title: getEmojiTitle(index),+ });+ });+ return categories.map((category) =>+ `<button data-type="${escapeAttr(category.id)}" class="emojis__type ariaLabel" aria-label="${escapeAttr(escapeHtml(category.title))}">${unicode2Emoji(category.unicode)}</button>`+ ).join("");+};++export class EmojiPanelController {+ private categoryID = "";+ private customGroups: TCustomEmojiGroup[] = [];+ private customOffset = 0;+ private customObserver?: IntersectionObserver;+ private imageObserver?: IntersectionObserver;+ private searchMode = false;++ constructor(private panelElement: HTMLElement, private typeElement: HTMLElement, private options: TEmojiPanelOptions) {+ }++ public setOptions(options: TEmojiPanelOptions) {+ this.options = options;+ }++ public renderInitial() {+ const recentHTML = getRecentEmojiButtons("", this.options);+ const firstBuiltIn = window.siyuan.emojis.find((category) => category.id !== "custom");+ this.renderCategory(recentHTML ? "recent" : firstBuiltIn?.id || "recent");+ }++ public renderCategory(categoryID: string) {+ const category = window.siyuan.emojis.find((item) => item.id === categoryID);+ if (categoryID !== "recent" && (!category || (this.options.hideCustom && category.id === "custom"))) {+ this.renderInitial();+ return;+ }+ this.disconnectObservers();+ this.panelElement.innerHTML = "";+ this.panelElement.scrollTop = 0;+ this.categoryID = categoryID;+ this.searchMode = false;+ this.typeElement.classList.remove("fn__none");+ this.updateCurrentType();++ if (categoryID === "recent") {+ const html = getRecentEmojiButtons("", this.options);+ this.panelElement.innerHTML = html ? genEmojiSection(window.siyuan.languages.recentEmoji, html) :+ `<div class="emojis__section"><div class="emojis__title">${window.siyuan.languages.emptyContent}</div></div>`;+ } else if (category.id === "custom") {+ if (category.items.length === 0) {+ this.panelElement.innerHTML = `<div class="emojis__section"><div class="emojis__title">${window.siyuan.languages.setEmojiTip}</div></div>`;+ } else {+ this.customGroups = groupCustomEmojiItems(category.items);+ this.customOffset = 0;+ this.loadMoreCustomEmojis();+ }+ } else {+ const html = category.items.map((item) => genEmojiButton(item.unicode, getEmojiDesc(item), true)).join("");+ this.panelElement.innerHTML = genEmojiSection(getEmojiTitle(window.siyuan.emojis.indexOf(category)), html);+ }+ this.observeImages(this.panelElement);+ this.selectFirst();+ }++ public renderSearch(key: string, max?: number) {+ if (!key) {+ if (this.categoryID) {+ this.renderCategory(this.categoryID);+ } else {+ this.renderInitial();+ }+ return;+ }+ this.disconnectObservers();+ this.searchMode = true;+ this.panelElement.innerHTML = genEmojiSearchHTML(key, max, this.options);+ this.panelElement.scrollTop = 0;+ this.typeElement.classList.add("fn__none");+ this.observeImages(this.panelElement);+ this.selectFirst();+ }++ public loadMoreCustomEmojis() {+ if (this.searchMode || this.categoryID !== "custom" || this.customGroups.length === 0) {+ return false;+ }+ this.customObserver?.disconnect();+ this.panelElement.querySelector(".emojis__load")?.remove();+ const batch = getCustomEmojiBatch(this.customGroups, this.customOffset);+ batch.groups.forEach((group) => {+ const itemsHTML = group.items.map((item) => genEmojiButton(item.unicode, getEmojiDesc(item), true)).join("");+ const lastSection = this.panelElement.querySelector(".emojis__section:last-of-type") as HTMLElement;+ if (lastSection?.dataset.group === group.name) {+ lastSection.querySelector(".emojis__content").insertAdjacentHTML("beforeend", itemsHTML);+ } else {+ this.panelElement.insertAdjacentHTML("beforeend", genEmojiSection(group.name, itemsHTML, group.name));+ }+ });+ this.customOffset = batch.nextOffset;+ this.observeImages(this.panelElement);+ if (batch.hasMore) {+ this.panelElement.insertAdjacentHTML("beforeend", '<div class="emojis__load"></div>');+ const loadElement = this.panelElement.lastElementChild;+ this.customObserver = new IntersectionObserver((entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ this.loadMoreCustomEmojis();+ }+ }, {root: this.panelElement, rootMargin: "128px"});+ this.customObserver.observe(loadElement);+ }+ return batch.groups.length > 0;+ }++ public deactivate() {+ this.disconnectObservers();+ }++ public activate() {+ if (!this.categoryID || this.panelElement.childElementCount === 0) {+ this.renderInitial();+ return;+ }+ this.observeImages(this.panelElement);+ const loadElement = this.panelElement.querySelector(".emojis__load");+ if (loadElement) {+ this.customObserver = new IntersectionObserver((entries) => {+ if (entries.some((entry) => entry.isIntersecting)) {+ this.loadMoreCustomEmojis();+ }+ }, {root: this.panelElement, rootMargin: "128px"});+ this.customObserver.observe(loadElement);+ }+ }++ public destroy() {+ this.disconnectObservers();+ }- if (recentHTML + html === "") {- return `<div class="emojis__title">${window.siyuan.languages.emptyContent}</div>`;+ private selectFirst() {+ this.panelElement.querySelector(".emojis__item")?.classList.add("emojis__item--current");+ }++ private updateCurrentType() {+ this.typeElement.querySelectorAll(".emojis__type").forEach((item: HTMLElement) => {+ item.classList.toggle("emojis__type--current", item.dataset.type === this.categoryID);+ });+ }++ private observeImages(element: Element) {+ if (!this.imageObserver) {+ this.imageObserver = new IntersectionObserver((entries) => {+ entries.forEach((entry) => {+ if (!entry.isIntersecting) {+ return;+ }+ const imageElement = entry.target as HTMLImageElement;+ const src = imageElement.dataset.src;+ if (src) {+ imageElement.src = src;+ imageElement.removeAttribute("data-src");+ }+ this.imageObserver?.unobserve(imageElement);+ });+ }, {root: this.panelElement, rootMargin: "64px"});+ }+ element.querySelectorAll("img[data-src]").forEach((item) => this.imageObserver.observe(item));+ }++ private disconnectObservers() {+ this.customObserver?.disconnect();+ this.customObserver = undefined;+ this.imageObserver?.disconnect();+ this.imageObserver = undefined;+ }+}++export const moveEmojiSelection = (panelElement: HTMLElement, key: string, loadMore?: () => boolean) => {+ let items = Array.from(panelElement.querySelectorAll<HTMLElement>(".emojis__item"));+ const currentElement = panelElement.querySelector<HTMLElement>(".emojis__item--current") || items[0];+ if (!currentElement || !key.startsWith("Arrow")) {+ return;}- return recentHTML + html;+ let currentIndex = items.indexOf(currentElement);+ const columnCount = Math.max(1, Math.floor(panelElement.clientWidth / 34));+ if ((key === "ArrowRight" && currentIndex === items.length - 1) ||+ (key === "ArrowDown" && currentIndex + columnCount >= items.length)) {+ if (loadMore?.()) {+ items = Array.from(panelElement.querySelectorAll<HTMLElement>(".emojis__item"));+ currentIndex = items.indexOf(currentElement);+ }+ }+ let nextIndex = currentIndex;+ if (key === "ArrowLeft") {+ nextIndex--;+ } else if (key === "ArrowRight") {+ nextIndex++;+ } else if (key === "ArrowUp") {+ nextIndex -= columnCount;+ } else if (key === "ArrowDown") {+ nextIndex += columnCount;+ }+ nextIndex = Math.max(0, Math.min(items.length - 1, nextIndex));+ const nextElement = items[nextIndex];+ if (nextElement === currentElement) {+ return currentElement;+ }+ currentElement.classList.remove("emojis__item--current");+ nextElement.classList.add("emojis__item--current");+ const panelRect = panelElement.getBoundingClientRect();+ const itemRect = nextElement.getBoundingClientRect();+ if (itemRect.top < panelRect.top + 32) {+ panelElement.scrollTop -= panelRect.top + 32 - itemRect.top;+ } else if (itemRect.bottom > panelRect.bottom) {+ panelElement.scrollTop += itemRect.bottom - panelRect.bottom;+ }+ return nextElement;};export const addEmoji = (unicode: string) => {@@ -246,19 +426,6 @@ const genWeekdayOptions = (lang: string, weekdayType: string) => {<option value="4" ${weekdayType === "4" ? " selected" : ""}>${dynamicWeekdayLang[4][currentLang]}</option>`;};-const renderEmojiContent = (previousIndex: string, previousContentElement: Element) => {- if (!previousIndex) {- return;- }- let html = "";- window.siyuan.emojis[parseInt(previousIndex)].items.forEach(emoji => {- html += `<button data-unicode="${escapeAttr(emoji.unicode)}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(emoji)}">${unicode2Emoji(emoji.unicode)}</button>`;- });- previousContentElement.innerHTML = html;- previousContentElement.removeAttribute("data-index");- previousContentElement.removeAttribute("style");-};-export const openEmojiPanel = (id: string,type: "doc" | "notebook" | "av",@@ -307,6 +474,7 @@ export const openEmojiPanel = ();let pastedCustomIconFile: File | undefined;let pastedCustomIconObjectURL = "";+ const emojiPanelState: {controller?: EmojiPanelController} = {};const clearPastedCustomIcon = () => {pastedCustomIconFile = undefined;if (pastedCustomIconObjectURL) {@@ -321,7 +489,10 @@ export const openEmojiPanel = (hideCloseIcon: true,width: isMobile() ? "80vw" : "368px",height: "50vh",- destroyCallback: clearPastedCustomIcon,+ destroyCallback: () => {+ clearPastedCustomIcon();+ emojiPanelState.controller?.destroy();+ },content: `<div class="emojis"><div class="emojis__tabheader"><div data-type="tab-emoji" class="ariaLabel block__icon block__icon--show" aria-label="${window.siyuan.languages.emoji}"><svg><use xlink:href="#iconEmoji"></use></svg></div>@@ -345,29 +516,8 @@ 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, {- targetID,- hideDynamic: options?.dynamic,- })}</div>- <div class="fn__flex">- ${[- ["2b50", window.siyuan.languages.recentEmoji],- ["1f527", getEmojiTitle(0)],- ["1f60d", getEmojiTitle(1)],- ["1f433", getEmojiTitle(2)],- ["1f96a", getEmojiTitle(3)],- ["1f3a8", getEmojiTitle(4)],- ["1f3dd-fe0f", getEmojiTitle(5)],- ["1f52e", getEmojiTitle(6)],- ["267e-fe0f", getEmojiTitle(7)],- ["1f6a9", getEmojiTitle(8)],- ].map(([unicode, title], index) => {- if (options?.custom && index === 1) {- return "";- }- return `<div data-type="${index}" class="emojis__type ariaLabel" aria-label="${title}">${unicode2Emoji(unicode)}</div>`;- }).join("")}- </div>+ <div class="emojis__panel"></div>+ <div class="fn__flex">${genEmojiCategoryButtons(options?.custom)}</div></div><div class="fn__none" data-type="tab-dynamic"><div class="fn__flex emoji__dynamic-color">@@ -503,7 +653,6 @@ export const openEmojiPanel = (dialog.element.querySelector(`.emojis__tabheader [data-type="tab-${currentTab}"]`).classList.add("block__icon--active");dialog.element.querySelector(`.emojis__tabbody [data-type="tab-${currentTab}"]`).classList.remove("fn__none");setPosition(dialog.element.querySelector(".b3-dialog__container"), position.x, position.y, position.h, position.w);- dialog.element.querySelector(".emojis__item").classList.add("emojis__item--current");const networkIconInputElement = dialog.element.querySelector('[data-type="network-icon-url"]') as HTMLTextAreaElement;const customIconFileElement = dialog.element.querySelector('[data-type="custom-icon-file"]') as HTMLInputElement;const customIconNameElement = dialog.element.querySelector('[data-type="custom-icon-name"]') as HTMLInputElement;@@ -696,43 +845,24 @@ export const openEmojiPanel = (});renderNetworkIconPreview();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, {+ const emojisContentElement = dialog.element.querySelector(".emojis__panel") as HTMLElement;+ const emojiPanelController = new EmojiPanelController(+ emojisContentElement,+ emojisContentElement.nextElementSibling as HTMLElement,+ {targetID,hideDynamic: options?.dynamic,- });- if (emojiSearchInputElement.value) {- emojisContentElement.nextElementSibling.classList.add("fn__none");- } else {- emojisContentElement.nextElementSibling.classList.remove("fn__none");- }- emojisContentElement.scrollTop = 0;- dialog.element.querySelector(".emojis__item")?.classList.add("emojis__item--current");- if (emojiSearchInputElement.value === "") {- lazyLoadEmoji(dialog.element);- }- lazyLoadEmojiImg(dialog.element);- });+ hideCustom: options?.custom,+ },+ );+ emojiPanelState.controller = emojiPanelController;+ const renderEmojiSearch = () => emojiPanelController.renderSearch(emojiSearchInputElement.value);+ emojiSearchInputElement.addEventListener("compositionend", renderEmojiSearch);emojiSearchInputElement.addEventListener("input", (event: InputEvent) => {if (event.isComposing) {return;}- emojisContentElement.innerHTML = filterEmoji(emojiSearchInputElement.value, null, options?.custom, {- targetID,- hideDynamic: options?.dynamic,- });- if (emojiSearchInputElement.value) {- emojisContentElement.nextElementSibling.classList.add("fn__none");- } else {- emojisContentElement.nextElementSibling.classList.remove("fn__none");- }- emojisContentElement.scrollTop = 0;- dialog.element.querySelector(".emojis__item")?.classList.add("emojis__item--current");- if (emojiSearchInputElement.value === "") {- lazyLoadEmoji(dialog.element);- }- lazyLoadEmojiImg(dialog.element);+ renderEmojiSearch();});emojiSearchInputElement.addEventListener("keydown", (event: KeyboardEvent) => {if (event.isComposing) {@@ -746,129 +876,29 @@ export const openEmojiPanel = (return;}if (event.key === "Enter") {- const unicode = currentElement.getAttribute("data-unicode");- if (type === "notebook") {- fetchPost("/api/notebook/setNotebookIcon", {- notebook: id,- icon: unicode- }, () => {- dialog.destroy();- updateFileTreeEmoji(unicode, id, "iconNewNoteBook");- });- } else if (type === "doc") {- fetchPost("/api/attr/setBlockAttrs", {- id,- attrs: {"icon": unicode}- }, () => {- dialog.destroy();- updateFileTreeEmoji(unicode, id);- updateOutlineEmoji(unicode, id);- });- }- if (callback) {- callback(unicode);- }- addEmoji(unicode);+ applyLinkIcon(currentElement.getAttribute("data-unicode"));event.preventDefault();event.stopPropagation();return;}- let newCurrentElement: HTMLElement;- if (event.key === "ArrowLeft") {- if (currentElement.previousElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.previousElementSibling as HTMLElement;- event.preventDefault();- event.stopPropagation();- } else if (currentElement.parentElement.previousElementSibling?.previousElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.parentElement.previousElementSibling.previousElementSibling.lastElementChild as HTMLElement;- event.preventDefault();- event.stopPropagation();- }- } else if (event.key === "ArrowRight") {- if (currentElement.nextElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.nextElementSibling as HTMLElement;- event.preventDefault();- event.stopPropagation();- } else if (currentElement.parentElement.nextElementSibling?.nextElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.parentElement.nextElementSibling.nextElementSibling.firstElementChild as HTMLElement;- event.preventDefault();- event.stopPropagation();- }- } else if (event.key === "ArrowDown") {- if (!currentElement.nextElementSibling) {- const nextContentElement = currentElement.parentElement.nextElementSibling?.nextElementSibling;- if (nextContentElement) {- newCurrentElement = nextContentElement.firstElementChild as HTMLElement;- currentElement.classList.remove("emojis__item--current");- }- } else {- currentElement.classList.remove("emojis__item--current");- let counter = Math.floor(currentElement.parentElement.clientWidth / (currentElement.clientWidth + 2));- newCurrentElement = currentElement;- while (newCurrentElement.nextElementSibling && counter > 0) {- newCurrentElement = newCurrentElement.nextElementSibling as HTMLElement;- counter--;- }- }- event.preventDefault();- event.stopPropagation();- } else if (event.key === "ArrowUp") {- if (!currentElement.previousElementSibling) {- const prevContentElement = currentElement.parentElement.previousElementSibling?.previousElementSibling;- if (prevContentElement) {- newCurrentElement = prevContentElement.lastElementChild as HTMLElement;- currentElement.classList.remove("emojis__item--current");- }- } else {- currentElement.classList.remove("emojis__item--current");- let counter = Math.floor(currentElement.parentElement.clientWidth / (currentElement.clientWidth + 2));- newCurrentElement = currentElement;- while (newCurrentElement.previousElementSibling && counter > 0) {- newCurrentElement = newCurrentElement.previousElementSibling as HTMLElement;- counter--;- }- }- event.preventDefault();- event.stopPropagation();- }- if (newCurrentElement) {- newCurrentElement.classList.add("emojis__item--current");- const inputHeight = emojiSearchInputElement.clientHeight + 6;- if (newCurrentElement.offsetTop - inputHeight < emojisContentElement.scrollTop) {- emojisContentElement.scrollTop = newCurrentElement.offsetTop - inputHeight - 6;- } else if (newCurrentElement.offsetTop - inputHeight - emojisContentElement.clientHeight + newCurrentElement.clientHeight > emojisContentElement.scrollTop) {- emojisContentElement.scrollTop = newCurrentElement.offsetTop - inputHeight - emojisContentElement.clientHeight + newCurrentElement.clientHeight;- }- }+ moveEmojiSelection(emojisContentElement, event.key, () => emojiPanelController.loadMoreCustomEmojis());+ event.preventDefault();+ event.stopPropagation();});+ if (currentTab === "emoji") {+ emojiPanelController.activate();+ }if (!isMobile() && currentTab === "emoji") {emojiSearchInputElement.focus();} else if (!isMobile() && currentTab === "link") {linkIconElement.focus();}- lazyLoadEmoji(dialog.element);- lazyLoadEmojiImg(dialog.element);// 不能使用 getEventName 否则 https://github.com/siyuan-note/siyuan/issues/5472dialog.element.addEventListener("click", (event) => {let target = event.target as HTMLElement;while (target && target !== dialog.element) {if (target.classList.contains("emojis__type")) {- const titleElement = emojisContentElement.querySelector(`[data-type="${target.getAttribute("data-type")}"]`) as HTMLElement;- if (titleElement) {- const index = titleElement.nextElementSibling.getAttribute("data-index");- if (index) {- renderEmojiContent(titleElement.previousElementSibling?.getAttribute("data-index"), titleElement.previousElementSibling);- renderEmojiContent(index, titleElement.nextElementSibling);- }- emojisContentElement.scrollTo({- top: titleElement.offsetTop - 77,- // behavior: "smooth" 不能使用,否则无法定位- });- }+ emojiPanelController.renderCategory(target.dataset.type);break;} else if (target.getAttribute("data-action") === "select-custom-icon") {customIconFileElement.value = "";@@ -973,6 +1003,14 @@ export const openEmojiPanel = (});window.siyuan.storage[Constants.LOCAL_EMOJIS].currentTab = target.dataset.type.replace("tab-", "");setStorageVal(Constants.LOCAL_EMOJIS, window.siyuan.storage[Constants.LOCAL_EMOJIS]);+ if (target.dataset.type === "tab-emoji") {+ emojiPanelController.activate();+ if (!isMobile()) {+ emojiSearchInputElement.focus();+ }+ } else {+ emojiPanelController.deactivate();+ }if (target.dataset.type === "tab-link" && !isMobile()) {linkIconElement.focus();}diff --git a/app/src/emoji/panel.test.ts b/app/src/emoji/panel.test.tsnew file mode 100644index 0000000000..942c561334--- /dev/null+++ b/app/src/emoji/panel.test.ts@@ -0,0 +1,78 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {collectEmojiMatches, getCustomEmojiBatch, getEmojiItemMap, groupCustomEmojiItems} from "./panel";++const createEmoji = (unicode: string) => ({+ unicode,+ description: unicode,+ description_zh_cn: unicode,+ description_ja_jp: unicode,+ keywords: unicode,+});++describe("groupCustomEmojiItems", () => {+ it("places root items before groups and uses the first folder as the group name", () => {+ const groups = groupCustomEmojiItems([+ createEmoji("animals/cat.png"),+ createEmoji("root.png"),+ createEmoji("animals/mammals/dog.png"),+ createEmoji("games/icon.png"),+ ]);++ assert.deepEqual(groups.map((group) => group.name), ["", "animals", "games"]);+ assert.deepEqual(groups[0].items.map((item) => item.unicode), ["root.png"]);+ assert.deepEqual(groups[1].items.map((item) => item.unicode), [+ "animals/cat.png",+ "animals/mammals/dog.png",+ ]);+ });+});++describe("getCustomEmojiBatch", () => {+ it("continues a group without duplicating its heading across batches", () => {+ const groups = groupCustomEmojiItems([+ createEmoji("root.png"),+ createEmoji("animals/cat.png"),+ createEmoji("animals/dog.png"),+ createEmoji("games/icon.png"),+ ]);++ const first = getCustomEmojiBatch(groups, 0, 2);+ assert.deepEqual(first.groups.map((group) => [group.name, group.items.length]), [["", 1], ["animals", 1]]);+ assert.equal(first.nextOffset, 2);+ assert.equal(first.hasMore, true);++ const second = getCustomEmojiBatch(groups, first.nextOffset, 2);+ assert.deepEqual(second.groups.map((group) => [group.name, group.items.length]), [["animals", 1], ["games", 1]]);+ assert.equal(second.nextOffset, 4);+ assert.equal(second.hasMore, false);+ });+});++describe("emoji filtering", () => {+ const categories: IEmoji[] = [{+ id: "custom",+ title: "Custom",+ title_zh_cn: "自定义",+ title_ja_jp: "カスタム",+ items: [createEmoji("custom-a.png"), createEmoji("custom-b.png")],+ }, {+ id: "people",+ title: "People",+ title_zh_cn: "人物",+ title_ja_jp: "人々",+ items: [createEmoji("1f600"), createEmoji("1f601")],+ }];++ it("limits search results without exceeding the requested maximum", () => {+ const result = collectEmojiMatches(categories, () => true, 3);+ assert.equal(result.customItems.length + result.builtInItems.length, 3);+ assert.deepEqual(result.builtInItems.map((item) => item.unicode), ["1f600"]);+ });++ it("excludes custom items from recent lookup when custom icons are hidden", () => {+ const emojiMap = getEmojiItemMap(categories, true);+ assert.equal(emojiMap.has("custom-a.png"), false);+ assert.equal(emojiMap.has("1f600"), true);+ });+});diff --git a/app/src/emoji/panel.ts b/app/src/emoji/panel.tsnew file mode 100644index 0000000000..cb2e15555a--- /dev/null+++ b/app/src/emoji/panel.ts@@ -0,0 +1,114 @@+export const CUSTOM_EMOJI_BATCH_SIZE = 128;++export type TCustomEmojiGroup = {+ name: string;+ items: IEmojiItem[];+};++export type TCustomEmojiBatch = {+ groups: TCustomEmojiGroup[];+ nextOffset: number;+ hasMore: boolean;+};++export const getEmojiItemMap = (categories: IEmoji[], hideCustom = false) => {+ const emojiMap = new Map<string, IEmojiItem>();+ categories.forEach((category) => {+ if (hideCustom && category.id === "custom") {+ return;+ }+ category.items.forEach((item) => emojiMap.set(item.unicode, item));+ });+ return emojiMap;+};++export const collectEmojiMatches = (+ categories: IEmoji[],+ matcher: (item: IEmojiItem) => boolean,+ max?: number,+ hideCustom = false,+) => {+ const customItems: IEmojiItem[] = [];+ const builtInItems: IEmojiItem[] = [];+ let matchedCount = 0;+ categories.forEach((category) => {+ if (hideCustom && category.id === "custom") {+ return;+ }+ category.items.forEach((item) => {+ if ((typeof max === "number" && matchedCount >= max) || !matcher(item)) {+ return;+ }+ if (category.id === "custom") {+ customItems.push(item);+ } else {+ builtInItems.push(item);+ }+ matchedCount++;+ });+ });+ return {customItems, builtInItems};+};++const getCustomEmojiGroupName = (unicode: string) => {+ const separatorIndex = unicode.indexOf("/");+ return separatorIndex > -1 ? unicode.substring(0, separatorIndex) : "";+};++export const groupCustomEmojiItems = (items: IEmojiItem[]) => {+ const rootItems: IEmojiItem[] = [];+ const folderGroups = new Map<string, IEmojiItem[]>();+ items.forEach((item) => {+ const groupName = getCustomEmojiGroupName(item.unicode);+ if (!groupName) {+ rootItems.push(item);+ return;+ }+ const groupItems = folderGroups.get(groupName) || [];+ groupItems.push(item);+ folderGroups.set(groupName, groupItems);+ });++ const groups: TCustomEmojiGroup[] = [];+ if (rootItems.length > 0) {+ groups.push({name: "", items: rootItems});+ }+ folderGroups.forEach((groupItems, name) => {+ groups.push({name, items: groupItems});+ });+ return groups;+};++export const getCustomEmojiBatch = (+ groups: TCustomEmojiGroup[],+ offset: number,+ limit = CUSTOM_EMOJI_BATCH_SIZE,+): TCustomEmojiBatch => {+ const batchGroups: TCustomEmojiGroup[] = [];+ let skipped = 0;+ let remaining = limit;+ let nextOffset = offset;+ let total = 0;++ groups.forEach((group) => {+ total += group.items.length;+ if (remaining === 0 || skipped + group.items.length <= offset) {+ skipped += group.items.length;+ return;+ }+ const groupOffset = Math.max(0, offset - skipped);+ const items = group.items.slice(groupOffset, groupOffset + remaining);+ if (items.length > 0) {+ batchGroups.push({name: group.name, items});+ remaining -= items.length;+ nextOffset += items.length;+ }+ skipped += group.items.length;+ });++ return {+ groups: batchGroups,+ nextOffset,+ hasMore: nextOffset < total,+ };+};diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex 571edb0347..79dce0dce7 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -1,5 +1,4 @@import {Constants} from "../../constants";-import {escapeAttr} from "../../util/escape";import {hasClosestBlock,hasClosestByAttribute,@@ -37,12 +36,10 @@ import {fetchPost} from "../../util/fetch";import {getDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";import {addEmoji,- filterEmoji,- getEmojiDesc,- getEmojiTitle,- lazyLoadEmoji,- lazyLoadEmojiImg,- unicode2Emoji+ EmojiPanelController,+ genEmojiCategoryButtons,+ moveEmojiSelection,+ unicode2Emoji,} from "../../emoji";import {blockRender} from "../render/blockRender";import {uploadFiles} from "../upload";@@ -95,6 +92,8 @@ export class Hint {private createTargetSessionID = 0;private createTargetRenderID = 0;private createTargetSession?: TCreateTargetSession;+ private emojiPanel?: EmojiPanelController;+ private emojiBrowseMode = false;constructor(protyle: IProtyle) {this.element = document.createElement("div");@@ -113,33 +112,15 @@ export class Hint {event.stopPropagation(); // https://github.com/siyuan-note/siyuan/issues/3710return;}- const emojisContentElement = this.element.querySelector(".emojis__panel");const typeElement = hasClosestByClassName(eventTarget, "emojis__type");if (typeElement) {- const titleElement = emojisContentElement.querySelector(`[data-type="${typeElement.getAttribute("data-type")}"]`) as HTMLElement;- if (titleElement) {- const index = titleElement.nextElementSibling.getAttribute("data-index");- if (index) {- let html = "";- window.siyuan.emojis[parseInt(index)].items.forEach(emoji => {- html += `<button data-unicode="${escapeAttr(emoji.unicode)}" class="emojis__item ariaLabel" aria-label="${getEmojiDesc(emoji)}">-${unicode2Emoji(emoji.unicode)}</button>`;- });- titleElement.nextElementSibling.innerHTML = html;- titleElement.nextElementSibling.removeAttribute("data-index");- }-- emojisContentElement.scrollTo({- top: titleElement.offsetTop,- // behavior: "smooth" 不能使用,否则无法定位- });- }+ this.emojiPanel?.renderCategory(typeElement.dataset.type);return;}const emojiElement = hasClosestByClassName(eventTarget, "emojis__item");if (emojiElement) {const unicode = emojiElement.getAttribute("data-unicode");- if (this.element.querySelectorAll(".emojis__title").length > 2) {+ if (this.emojiBrowseMode) {// /emoji 后会自动添加冒号,导致 range 无法计算,因此不依赖 this.fillconst range = getSelection().getRangeAt(0);if (range.endContainer.nodeType !== 3) {@@ -151,7 +132,9 @@ ${unicode2Emoji(emoji.unicode)}</button>`;addEmoji(unicode);insertHTML(protyle.lute.SpinBlockDOM(genEmojiInsertHTML(unicode)), protyle, false, true);this.element.classList.add("fn__none");+ this.emojiPanel?.deactivate();} else {+ this.emojiPanel?.deactivate();this.fill(unicode, protyle);}}@@ -504,46 +487,30 @@ ${genHintItemHTML(item)}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, false, {targetID});- if (value) {- panelElement.nextElementSibling.classList.add("fn__none");- } else {- panelElement.nextElementSibling.classList.remove("fn__none");- }- lazyLoadEmojiImg(panelElement);- } else {+ let panelElement = this.element.querySelector(".emojis__panel") as HTMLElement;+ if (!panelElement) {+ this.emojiPanel?.destroy();// 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, false, {targetID})}</div>-<div class="fn__flex${value ? " fn__none" : ""}">- ${[- ["2b50", window.siyuan.languages.recentEmoji],- ["1f527", getEmojiTitle(0)],- ["1f60d", getEmojiTitle(1)],- ["1f433", getEmojiTitle(2)],- ["1f96a", getEmojiTitle(3)],- ["1f3a8", getEmojiTitle(4)],- ["1f3dd-fe0f", getEmojiTitle(5)],- ["1f52e", getEmojiTitle(6)],- ["267e-fe0f", getEmojiTitle(7)],- ["1f6a9", getEmojiTitle(8)],- ].map(([unicode, title], index) =>- `<button data-type="${index}" class="emojis__type ariaLabel" aria-label="${title}">${unicode2Emoji(unicode)}</button>`- ).join("")}-</div>+<div class="emojis__panel"></div>+<div class="fn__flex">${genEmojiCategoryButtons()}</div></div>`;- lazyLoadEmoji(this.element);- lazyLoadEmojiImg(this.element);+ panelElement = this.element.querySelector(".emojis__panel") as HTMLElement;+ this.emojiPanel = new EmojiPanelController(+ panelElement,+ panelElement.nextElementSibling as HTMLElement,+ {targetID},+ );+ } else {+ this.emojiPanel.setOptions({targetID});}+ this.emojiBrowseMode = value === "";+ this.emojiPanel.renderSearch(value, 256);const firstEmojiElement = this.element.querySelector(".emojis__item");if (firstEmojiElement) {- firstEmojiElement.classList.add("emojis__item--current");this.element.classList.remove("fn__none");const textareaPosition = getSelectionPosition(protyle.wysiwyg.element);setPosition(this.element, textareaPosition.left, textareaPosition.top + 26, 30);- this.element.querySelector(".emojis__panel").scrollTop = 0;} else {this.element.classList.add("fn__none");}@@ -1089,7 +1056,7 @@ ${genHintItemHTML(item)}return false;}const unicode = currentElement.getAttribute("data-unicode");- if (this.element.querySelectorAll(".emojis__title").length > 2) {+ if (this.emojiBrowseMode) {// /emoji 后会自动添加冒号,导致 range 无法计算,因此不依赖 this.fillconst range = getSelection().getRangeAt(0);if (range.endContainer.nodeType !== 3) {@@ -1098,7 +1065,9 @@ ${genHintItemHTML(item)}addEmoji(unicode);insertHTML(protyle.lute.SpinBlockDOM(genEmojiInsertHTML(unicode)), protyle);this.element.classList.add("fn__none");+ this.emojiPanel?.deactivate();} else {+ this.emojiPanel?.deactivate();this.fill(unicode, protyle);}} else {@@ -1114,76 +1083,14 @@ ${genHintItemHTML(item)}return true;}if (isEmojiPanel) {- const currentElement: HTMLElement = this.element.querySelector(".emojis__item--current");- if (!currentElement) {+ if (!this.element.querySelector(".emojis__item--current")) {return false;}- let newCurrentElement: HTMLElement;- if (event.key === "ArrowLeft") {- if (currentElement.previousElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.previousElementSibling as HTMLElement;- } else if (currentElement.parentElement.previousElementSibling?.previousElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.parentElement.previousElementSibling.previousElementSibling.lastElementChild as HTMLElement;- }- } else if (event.key === "ArrowRight") {- if (currentElement.nextElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.nextElementSibling as HTMLElement;- } else if (currentElement.parentElement.nextElementSibling?.nextElementSibling) {- currentElement.classList.remove("emojis__item--current");- newCurrentElement = currentElement.parentElement.nextElementSibling.nextElementSibling.firstElementChild as HTMLElement;- }- } else if (event.key === "ArrowDown") {- if (!currentElement.nextElementSibling) {- const nextContentElement = currentElement.parentElement.nextElementSibling?.nextElementSibling;- if (nextContentElement) {- newCurrentElement = nextContentElement.firstElementChild as HTMLElement;- currentElement.classList.remove("emojis__item--current");- }- } else {- currentElement.classList.remove("emojis__item--current");- let counter = Math.floor(currentElement.parentElement.clientWidth / (currentElement.clientWidth + 2));- newCurrentElement = currentElement;- while (newCurrentElement.nextElementSibling && counter > 0) {- newCurrentElement = newCurrentElement.nextElementSibling as HTMLElement;- counter--;- }- }- event.preventDefault();- event.stopPropagation();- } else if (event.key === "ArrowUp") {- if (!currentElement.previousElementSibling) {- const prevContentElement = currentElement.parentElement.previousElementSibling?.previousElementSibling;- if (prevContentElement) {- newCurrentElement = prevContentElement.lastElementChild as HTMLElement;- currentElement.classList.remove("emojis__item--current");- }- } else {- currentElement.classList.remove("emojis__item--current");- let counter = Math.floor(currentElement.parentElement.clientWidth / (currentElement.clientWidth + 2));- newCurrentElement = currentElement;- while (newCurrentElement.previousElementSibling && counter > 0) {- newCurrentElement = newCurrentElement.previousElementSibling as HTMLElement;- counter--;- }- }- event.preventDefault();- event.stopPropagation();- }- if (newCurrentElement) {- newCurrentElement.classList.add("emojis__item--current");- const emojisContentElement = this.element.querySelector(".emojis__panel");- if (newCurrentElement.offsetTop - 8 < emojisContentElement.scrollTop) {- emojisContentElement.scrollTop = newCurrentElement.offsetTop - 8;- } else {- const topHeight = emojisContentElement.nextElementSibling.classList.contains("fn__none") ? 8 : 36;- if (newCurrentElement.offsetTop + topHeight - this.element.clientHeight + newCurrentElement.clientHeight > emojisContentElement.scrollTop) {- emojisContentElement.scrollTop = newCurrentElement.offsetTop + topHeight - this.element.clientHeight + newCurrentElement.clientHeight;- }- }- }+ moveEmojiSelection(+ this.element.querySelector(".emojis__panel") as HTMLElement,+ event.key,+ () => this.emojiPanel?.loadMoreCustomEmojis() || false,+ );event.preventDefault();event.stopPropagation();return true;