Skip to content

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

:zap: Improve emoji picker virtualization and lifecycle https://github.com/siyuan-note/siyuan/issues/13563

Danielcb930b8b8c7c
diff --git a/app/src/assets/scss/business/_emojis.scss b/app/src/assets/scss/business/_emojis.scss
index 1a8f9f396d..dbd59bf1c5 100644
--- a/app/src/assets/scss/business/_emojis.scss
+++ b/app/src/assets/scss/business/_emojis.scss
@@ -227,8 +227,8 @@
flex-wrap: wrap;
}
- &__load {
- height: 1px;
+ &__chunk {
+ overflow: hidden;
}
&__types {
diff --git a/app/src/emoji/index.ts b/app/src/emoji/index.ts
index 2df53f6535..ac8b86ac79 100644
--- a/app/src/emoji/index.ts
+++ b/app/src/emoji/index.ts
@@ -25,10 +25,10 @@ import {showMessage} from "../dialog/message";
import {escapeAttr, escapeHtml} from "../util/escape";
import {
collectEmojiMatches,
- getCustomEmojiBatch,
+ getActiveEmojiCategory,
getEmojiItemMap,
+ getEmojiVirtualChunks,
groupCustomEmojiItems,
- TCustomEmojiGroup,
} from "./panel";
export const getRandomEmoji = () => {
@@ -188,22 +188,39 @@ export const genEmojiCategoryButtons = (hideCustom = false) => {
export class EmojiPanelController {
private categoryID = "";
- private customGroups: TCustomEmojiGroup[] = [];
- private customOffset = 0;
- private customObserver?: IntersectionObserver;
private imageObserver?: IntersectionObserver;
+ private virtualObserver?: IntersectionObserver;
+ private selectionObserver?: IntersectionObserver;
private resizeObserver: ResizeObserver;
+ private active = true;
+ private pageMode: "common" | "custom" | "search" | "" = "";
private searchMode = false;
private scrollFrame = 0;
- private categoryOffsets: {id: string, top: number, element: HTMLElement}[] = [];
+ private virtualTimer = 0;
+ private virtualKey = 0;
+ private columnCount = 10;
+ private selectedUnicode = "";
+ private categoryOffsets: {id: string, top: number}[] = [];
+ private virtualItems = new Map<string, IEmojiItem[]>();
+ private virtualQueue = new Map<HTMLElement, boolean>();
+ private visibleChunks = new Set<HTMLElement>();
+ private itemHTMLCache = new WeakMap<IEmojiItem, string>();
constructor(private panelElement: HTMLElement, private typeElement: HTMLElement, private options: TEmojiPanelOptions) {
this.panelElement.addEventListener("scroll", this.handleScroll, {passive: true});
this.resizeObserver = new ResizeObserver(() => {
- if (!this.searchMode && this.categoryID !== "custom") {
- this.updateBuiltInPlaceholders();
+ if (!this.active || this.pageMode === "search" || this.panelElement.clientWidth === 0) {
+ return;
+ }
+ const columnCount = this.getColumnCount();
+ if (columnCount !== this.columnCount) {
+ if (this.pageMode === "custom") {
+ this.renderCustomPage();
+ } else {
+ this.renderCommonPage(this.categoryID);
+ }
+ } else if (this.pageMode === "common") {
this.updateCategoryOffsets();
- this.updateVirtualCategories();
}
});
this.resizeObserver.observe(this.panelElement);
@@ -216,7 +233,7 @@ export class EmojiPanelController {
public renderInitial() {
const recentHTML = getRecentEmojiButtons("", this.options);
const firstBuiltIn = window.siyuan.emojis.find((category) => category.id !== "custom");
- this.renderCategory(recentHTML ? "recent" : firstBuiltIn?.id || "recent");
+ this.renderCommonPage(recentHTML ? "recent" : firstBuiltIn?.id || "recent", recentHTML);
}
public renderCategory(categoryID: string) {
@@ -226,35 +243,26 @@ export class EmojiPanelController {
return;
}
+ if (category?.id === "custom") {
+ if (!this.searchMode && this.pageMode === "custom") {
+ this.panelElement.scrollTop = 0;
+ this.ensureCurrentSelection();
+ return;
+ }
+ this.renderCustomPage();
+ return;
+ }
+
if (category?.id !== "custom") {
const targetElement = this.getCategoryElement(categoryID);
- if (!this.searchMode && targetElement) {
+ if (!this.searchMode && this.pageMode === "common" && targetElement) {
this.categoryID = categoryID;
this.updateCurrentType();
this.scrollToCategory(targetElement);
return;
}
this.renderCommonPage(categoryID);
- 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 (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();
- }
- this.observeImages(this.panelElement);
- this.selectFirst();
}
public renderSearch(key: string, max?: number) {
@@ -267,6 +275,8 @@ export class EmojiPanelController {
return;
}
this.disconnectObservers();
+ this.resetVirtualState();
+ this.pageMode = "search";
this.searchMode = true;
this.panelElement.innerHTML = genEmojiSearchHTML(key, max, this.options);
this.panelElement.scrollTop = 0;
@@ -275,71 +285,76 @@ export class EmojiPanelController {
this.selectFirst();
}
- public loadMoreCustomEmojis() {
- if (this.searchMode || this.categoryID !== "custom" || this.customGroups.length === 0) {
+ public loadMoreEmojis(direction: "previous" | "next" = "next") {
+ if (this.searchMode || (this.pageMode !== "common" && this.pageMode !== "custom")) {
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);
+ const chunks = Array.from(this.panelElement.querySelectorAll<HTMLElement>(".emojis__chunk"));
+ const currentChunk = this.panelElement.querySelector(".emojis__item--current")?.closest<HTMLElement>(".emojis__chunk");
+ const currentIndex = currentChunk ? chunks.indexOf(currentChunk) : -1;
+ const adjacentChunk = direction === "previous" ? chunks[currentIndex - 1] : chunks[currentIndex + 1];
+ if (!adjacentChunk || adjacentChunk.childElementCount > 0) {
+ return false;
+ }
+ this.renderVirtualChunk(adjacentChunk);
+ return true;
+ }
+
+ public moveSelection(key: string) {
+ const nextElement = moveEmojiSelection(
+ this.panelElement,
+ key,
+ (direction) => this.loadMoreEmojis(direction),
+ );
+ if (nextElement) {
+ this.selectedUnicode = nextElement.dataset.unicode || "";
}
- return batch.groups.length > 0;
+ return nextElement;
}
public deactivate() {
+ this.active = false;
this.disconnectObservers();
+ this.resizeObserver.disconnect();
}
public activate() {
+ this.active = true;
+ this.resizeObserver.observe(this.panelElement);
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);
+ if (this.pageMode === "common") {
+ this.updateCategoryOffsets();
}
+ if (this.pageMode === "common" || this.pageMode === "custom") {
+ this.observeVirtualChunks();
+ }
+ this.ensureCurrentSelection();
}
public destroy() {
- this.disconnectObservers();
- this.resizeObserver.disconnect();
+ this.deactivate();
+ this.resetVirtualState();
this.panelElement.removeEventListener("scroll", this.handleScroll);
if (this.scrollFrame) {
cancelAnimationFrame(this.scrollFrame);
}
}
- private renderCommonPage(categoryID: string) {
+ public getCurrentElement() {
+ return this.ensureCurrentSelection();
+ }
+
+ private renderCommonPage(categoryID: string, recentHTML = getRecentEmojiButtons("", this.options)) {
this.disconnectObservers();
+ this.resetVirtualState();
+ this.pageMode = "common";
+ this.searchMode = false;
+ this.columnCount = this.getColumnCount();
const sections: string[] = [];
- const recentHTML = getRecentEmojiButtons("", this.options);
if (recentHTML) {
sections.push(genEmojiSection(window.siyuan.languages.recentEmoji, recentHTML, undefined, "recent"));
}
@@ -347,27 +362,69 @@ export class EmojiPanelController {
if (item.id === "custom") {
return;
}
- sections.push(genEmojiSection(getEmojiTitle(index), "", undefined, item.id));
+ sections.push(this.genVirtualSection(getEmojiTitle(index), item.items, undefined, item.id));
});
this.panelElement.innerHTML = sections.join("") ||
`<div class="emojis__section"><div class="emojis__title">${window.siyuan.languages.emptyContent}</div></div>`;
this.panelElement.scrollTop = 0;
- this.updateBuiltInPlaceholders();
this.updateCategoryOffsets();
this.categoryID = this.getCategoryElement(categoryID)?.dataset.category ||
this.panelElement.querySelector<HTMLElement>(".emojis__section[data-category]")?.dataset.category || "recent";
- this.searchMode = false;
this.typeElement.classList.remove("fn__none");
this.updateCurrentType();
this.observeImages(this.panelElement);
const targetElement = this.getCategoryElement(this.categoryID);
if (targetElement) {
- this.loadBuiltInCategory(targetElement);
this.scrollToCategory(targetElement);
- this.updateVirtualCategories();
} else {
this.selectFirst();
}
+ const firstVirtualChunk = this.panelElement.querySelector<HTMLElement>(".emojis__chunk");
+ if (firstVirtualChunk) {
+ this.renderVirtualChunk(firstVirtualChunk);
+ if (!this.panelElement.querySelector(".emojis__item--current")) {
+ this.selectElement(firstVirtualChunk.querySelector(".emojis__item"));
+ }
+ }
+ this.observeVirtualChunks();
+ }
+
+ private renderCustomPage() {
+ this.disconnectObservers();
+ this.resetVirtualState();
+ this.pageMode = "custom";
+ this.searchMode = false;
+ this.categoryID = "custom";
+ this.columnCount = this.getColumnCount();
+ const category = window.siyuan.emojis.find((item) => item.id === "custom");
+ if (!category || category.items.length === 0) {
+ this.panelElement.innerHTML = `<div class="emojis__section"><div class="emojis__title">${window.siyuan.languages.setEmojiTip}</div></div>`;
+ } else {
+ this.panelElement.innerHTML = groupCustomEmojiItems(category.items)
+ .map((group) => this.genVirtualSection(group.name, group.items, group.name)).join("");
+ }
+ this.panelElement.scrollTop = 0;
+ this.typeElement.classList.remove("fn__none");
+ this.updateCurrentType();
+ const firstChunk = this.panelElement.querySelector<HTMLElement>(".emojis__chunk");
+ if (firstChunk) {
+ this.renderVirtualChunk(firstChunk);
+ this.selectElement(firstChunk.querySelector(".emojis__item"));
+ }
+ this.observeVirtualChunks();
+ }
+
+ private genVirtualSection(title: string, items: IEmojiItem[], groupName?: string, categoryID?: string) {
+ const groupAttribute = typeof groupName === "string" ? ` data-group="${escapeAttr(escapeHtml(groupName))}"` : "";
+ const categoryAttribute = categoryID ? ` data-category="${escapeAttr(categoryID)}"` : "";
+ const titleHTML = title ? `<div class="emojis__title">${escapeHtml(title)}</div>` : "";
+ const chunksHTML = getEmojiVirtualChunks(items, this.columnCount).map((chunk) => {
+ const key = (++this.virtualKey).toString();
+ this.virtualItems.set(key, chunk);
+ const height = Math.ceil(chunk.length / this.columnCount) * 34;
+ return `<div class="emojis__content emojis__chunk" data-virtual-key="${key}" style="height:${height}px"></div>`;
+ }).join("");
+ return `<div class="emojis__section"${groupAttribute}${categoryAttribute}>${titleHTML}<div class="emojis__chunks">${chunksHTML}</div></div>`;
}
private getCategoryElement(categoryID: string) {
@@ -376,9 +433,11 @@ export class EmojiPanelController {
}
private scrollToCategory(targetElement: HTMLElement) {
- this.loadBuiltInCategory(targetElement);
- this.panelElement.querySelector(".emojis__item--current")?.classList.remove("emojis__item--current");
- targetElement.querySelector(".emojis__item")?.classList.add("emojis__item--current");
+ const firstChunk = targetElement.querySelector<HTMLElement>(".emojis__chunk");
+ if (firstChunk) {
+ this.renderVirtualChunk(firstChunk);
+ }
+ this.selectElement(targetElement.querySelector(".emojis__item"));
const categoryOffset = this.categoryOffsets.find((item) => item.id === targetElement.dataset.category);
if (categoryOffset) {
this.panelElement.scrollTop = categoryOffset.top;
@@ -391,62 +450,183 @@ export class EmojiPanelController {
.map((item) => ({
id: item.dataset.category || "",
top: item.getBoundingClientRect().top - panelTop + this.panelElement.scrollTop,
- element: item,
}));
}
- private updateBuiltInPlaceholders() {
- this.panelElement.querySelectorAll<HTMLElement>(".emojis__section[data-category]").forEach((sectionElement) => {
- const category = window.siyuan.emojis.find((item) => item.id === sectionElement.dataset.category && item.id !== "custom");
- const contentElement = sectionElement.querySelector<HTMLElement>(".emojis__content");
- if (!category || !contentElement || contentElement.clientWidth === 0) {
- return;
- }
- const columnCount = Math.max(1, Math.floor(contentElement.clientWidth / 34));
- contentElement.style.height = `${Math.ceil(category.items.length / columnCount) * 34}px`;
- });
+ private getColumnCount() {
+ if (this.panelElement.clientWidth === 0) {
+ return this.columnCount;
+ }
+ return Math.max(1, Math.floor(Math.max(34, this.panelElement.clientWidth - 12) / 34));
}
- private loadBuiltInCategory(sectionElement: HTMLElement) {
- const category = window.siyuan.emojis.find((item) => item.id === sectionElement.dataset.category && item.id !== "custom");
- const contentElement = sectionElement.querySelector<HTMLElement>(".emojis__content");
- if (!category || !contentElement || contentElement.childElementCount > 0) {
+ private observeVirtualChunks() {
+ this.virtualObserver?.disconnect();
+ this.selectionObserver?.disconnect();
+ this.visibleChunks.clear();
+ const chunks = this.panelElement.querySelectorAll<HTMLElement>(".emojis__chunk");
+ if (chunks.length === 0) {
+ this.virtualObserver = undefined;
+ this.selectionObserver = undefined;
return;
}
- contentElement.innerHTML = category.items
- .map((item) => genEmojiButton(item.unicode, getEmojiDesc(item), true)).join("");
- this.observeImages(contentElement);
+ this.virtualObserver = new IntersectionObserver((entries) => {
+ entries.forEach((entry) => {
+ this.queueVirtualChunk(entry.target as HTMLElement, entry.isIntersecting);
+ });
+ }, {root: this.panelElement, rootMargin: "200% 0px"});
+ chunks.forEach((item) => this.virtualObserver.observe(item));
+ this.selectionObserver = new IntersectionObserver((entries) => {
+ entries.forEach((entry) => {
+ const element = entry.target as HTMLElement;
+ if (entry.isIntersecting) {
+ this.visibleChunks.add(element);
+ this.queueVirtualChunk(element, true);
+ } else {
+ this.visibleChunks.delete(element);
+ }
+ });
+ this.syncVisibleSelection();
+ }, {root: this.panelElement});
+ chunks.forEach((item) => this.selectionObserver.observe(item));
}
- private unloadBuiltInCategory(sectionElement: HTMLElement) {
- const category = window.siyuan.emojis.find((item) => item.id === sectionElement.dataset.category && item.id !== "custom");
- const contentElement = sectionElement.querySelector<HTMLElement>(".emojis__content");
- if (!category || !contentElement || contentElement.childElementCount === 0) {
+ private queueVirtualChunk(element: HTMLElement, render: boolean) {
+ if (!render && element.childElementCount === 0) {
+ this.virtualQueue.delete(element);
return;
}
- contentElement.querySelectorAll("img[data-src]").forEach((item) => this.imageObserver?.unobserve(item));
- contentElement.innerHTML = "";
+ this.virtualQueue.set(element, render);
+ if (!this.virtualTimer) {
+ this.virtualTimer = window.setTimeout(() => this.flushVirtualQueue());
+ }
}
- private updateVirtualCategories() {
- const viewportHeight = this.panelElement.clientHeight;
- if (viewportHeight === 0 || this.categoryOffsets.length === 0) {
+ private flushVirtualQueue() {
+ this.virtualTimer = 0;
+ const queuedItems = Array.from(this.virtualQueue.entries());
+ const nextItem = queuedItems.find((item) => item[1]) || queuedItems[0];
+ if (!nextItem) {
return;
}
- const renderStart = Math.max(0, this.panelElement.scrollTop - viewportHeight);
- const renderEnd = this.panelElement.scrollTop + viewportHeight * 2;
- this.categoryOffsets.forEach((item, index) => {
- const category = window.siyuan.emojis.find((emoji) => emoji.id === item.id && emoji.id !== "custom");
- if (!category) {
- return;
- }
- const sectionEnd = this.categoryOffsets[index + 1]?.top ?? this.panelElement.scrollHeight;
- if (item.top <= renderEnd && sectionEnd >= renderStart) {
- this.loadBuiltInCategory(item.element);
+ const [element, render] = nextItem;
+ this.virtualQueue.delete(element);
+ if (element.isConnected && this.panelElement.contains(element)) {
+ if (render) {
+ this.renderVirtualChunk(element);
} else {
- this.unloadBuiltInCategory(item.element);
+ this.unloadVirtualChunk(element);
}
- });
+ }
+ if (this.virtualQueue.size > 0) {
+ this.virtualTimer = window.setTimeout(() => this.flushVirtualQueue());
+ }
+ }
+
+ private renderVirtualChunk(element: HTMLElement) {
+ if (element.childElementCount > 0) {
+ return;
+ }
+ const items = this.virtualItems.get(element.dataset.virtualKey);
+ if (!items) {
+ return;
+ }
+ element.innerHTML = items.map((item) => {
+ let html = this.itemHTMLCache.get(item);
+ if (!html) {
+ html = genEmojiButton(item.unicode, getEmojiDesc(item), true);
+ this.itemHTMLCache.set(item, html);
+ }
+ return html;
+ }).join("");
+ this.observeImages(element);
+ this.restoreVirtualSelection(element);
+ }
+
+ private unloadVirtualChunk(element: HTMLElement) {
+ const currentElement = element.querySelector<HTMLElement>(".emojis__item--current");
+ if (currentElement) {
+ this.selectedUnicode = currentElement.dataset.unicode || "";
+ }
+ element.querySelectorAll("img[data-src]").forEach((item) => this.imageObserver?.unobserve(item));
+ element.innerHTML = "";
+ if (currentElement) {
+ this.ensureCurrentSelection();
+ }
+ }
+
+ private restoreVirtualSelection(element: HTMLElement) {
+ if (!this.visibleChunks.has(element)) {
+ return;
+ }
+ const currentElement = this.panelElement.querySelector<HTMLElement>(".emojis__item--current");
+ const currentChunk = currentElement?.closest<HTMLElement>(".emojis__chunk");
+ const currentCategoryID = currentElement?.closest<HTMLElement>(".emojis__section")?.dataset.category;
+ if (currentElement && ((currentChunk && this.visibleChunks.has(currentChunk)) ||
+ (!currentChunk && this.pageMode === "common" && currentCategoryID === this.categoryID))) {
+ return;
+ }
+ const selectedElement = Array.from(element.querySelectorAll<HTMLElement>(".emojis__item"))
+ .find((item) => item.dataset.unicode === this.selectedUnicode);
+ if (selectedElement) {
+ this.selectElement(selectedElement);
+ return;
+ }
+ this.selectElement(element.querySelector(".emojis__item"));
+ }
+
+ private ensureCurrentSelection() {
+ const currentElement = this.panelElement.querySelector<HTMLElement>(".emojis__item--current");
+ const currentChunk = currentElement?.closest<HTMLElement>(".emojis__chunk");
+ const currentCategoryID = currentElement?.closest<HTMLElement>(".emojis__section")?.dataset.category;
+ if (currentElement && ((currentChunk && this.visibleChunks.has(currentChunk)) ||
+ (!currentChunk && (this.pageMode !== "common" || currentCategoryID === this.categoryID)))) {
+ return currentElement;
+ }
+ const visibleChunk = Array.from(this.visibleChunks).find((item) => item.childElementCount > 0);
+ const categoryElement = this.pageMode === "common" ? this.getCategoryElement(this.categoryID) : undefined;
+ const nextElement = visibleChunk?.querySelector<HTMLElement>(".emojis__item") ||
+ categoryElement?.querySelector<HTMLElement>(".emojis__item") ||
+ this.panelElement.querySelector<HTMLElement>(".emojis__item");
+ this.selectElement(nextElement);
+ return nextElement;
+ }
+
+ private syncVisibleSelection() {
+ const currentElement = this.panelElement.querySelector<HTMLElement>(".emojis__item--current");
+ const currentChunk = currentElement?.closest<HTMLElement>(".emojis__chunk");
+ if (currentChunk && this.visibleChunks.has(currentChunk)) {
+ return;
+ }
+ if (currentElement && !currentChunk && this.pageMode === "common" &&
+ currentElement.closest<HTMLElement>(".emojis__section")?.dataset.category === this.categoryID) {
+ return;
+ }
+ const categoryElement = this.pageMode === "common" ? this.getCategoryElement(this.categoryID) : undefined;
+ const visibleChunk = Array.from(this.visibleChunks).find((item) =>
+ item.childElementCount > 0 && (!categoryElement || categoryElement.contains(item))
+ ) || Array.from(this.visibleChunks).find((item) => item.childElementCount > 0);
+ if (visibleChunk) {
+ this.selectElement(visibleChunk.querySelector(".emojis__item"));
+ }
+ }
+
+ private selectElement(element?: HTMLElement | null) {
+ if (!element) {
+ return;
+ }
+ this.panelElement.querySelector(".emojis__item--current")?.classList.remove("emojis__item--current");
+ element.classList.add("emojis__item--current");
+ this.selectedUnicode = element.dataset.unicode || "";
+ }
+
+ private resetVirtualState() {
+ this.categoryOffsets = [];
+ this.virtualItems.clear();
+ this.virtualQueue.clear();
+ this.visibleChunks.clear();
+ this.virtualKey = 0;
+ this.selectedUnicode = "";
}
private handleScroll = () => {
@@ -458,27 +638,21 @@ export class EmojiPanelController {
if (this.categoryOffsets.length === 0) {
return;
}
- let currentCategory = this.categoryOffsets[0];
- this.categoryOffsets.some((item) => {
- if (item.top > this.panelElement.scrollTop + 1) {
- return true;
- }
- currentCategory = item;
- return false;
- });
- if (this.panelElement.scrollTop + this.panelElement.clientHeight >= this.panelElement.scrollHeight - 1) {
- currentCategory = this.categoryOffsets[this.categoryOffsets.length - 1];
- }
- if (currentCategory.id !== this.categoryID) {
- this.categoryID = currentCategory.id;
+ const categoryID = getActiveEmojiCategory(
+ this.categoryOffsets,
+ this.panelElement.scrollTop,
+ this.panelElement.scrollTop + this.panelElement.clientHeight >= this.panelElement.scrollHeight - 1,
+ );
+ if (categoryID && categoryID !== this.categoryID) {
+ this.categoryID = categoryID;
this.updateCurrentType();
+ this.syncVisibleSelection();
}
- this.updateVirtualCategories();
});
};
private selectFirst() {
- this.panelElement.querySelector(".emojis__item")?.classList.add("emojis__item--current");
+ this.selectElement(this.panelElement.querySelector(".emojis__item"));
}
private updateCurrentType() {
@@ -508,24 +682,42 @@ export class EmojiPanelController {
}
private disconnectObservers() {
- this.customObserver?.disconnect();
- this.customObserver = undefined;
+ this.virtualObserver?.disconnect();
+ this.virtualObserver = undefined;
+ this.selectionObserver?.disconnect();
+ this.selectionObserver = undefined;
this.imageObserver?.disconnect();
this.imageObserver = undefined;
+ if (this.virtualTimer) {
+ clearTimeout(this.virtualTimer);
+ this.virtualTimer = 0;
+ }
+ this.virtualQueue.clear();
+ this.visibleChunks.clear();
}
}
-export const moveEmojiSelection = (panelElement: HTMLElement, key: string, loadMore?: () => boolean) => {
+export const moveEmojiSelection = (
+ panelElement: HTMLElement,
+ key: string,
+ loadMore?: (direction: "previous" | "next") => 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;
}
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?.()) {
+ const columnCount = Math.max(1, Math.floor(currentElement.parentElement.clientWidth / 34));
+ const currentChunk = currentElement.closest<HTMLElement>(".emojis__chunk");
+ const chunkItems = currentChunk ? Array.from(currentChunk.querySelectorAll<HTMLElement>(".emojis__item")) : items;
+ const chunkIndex = chunkItems.indexOf(currentElement);
+ const direction = (key === "ArrowLeft" && chunkIndex === 0) ||
+ (key === "ArrowUp" && chunkIndex < columnCount) ? "previous" :
+ (key === "ArrowRight" && chunkIndex === chunkItems.length - 1) ||
+ (key === "ArrowDown" && chunkIndex + columnCount >= chunkItems.length) ? "next" : undefined;
+ if (direction) {
+ if (loadMore?.(direction)) {
items = Array.from(panelElement.querySelectorAll<HTMLElement>(".emojis__item"));
currentIndex = items.indexOf(currentElement);
}
@@ -1034,7 +1226,7 @@ export const openEmojiPanel = (
if (event.key.indexOf("Arrow") === -1 && event.key !== "Enter") {
return;
}
- const currentElement: HTMLElement = dialog.element.querySelector(".emojis__item--current");
+ const currentElement = emojiPanelController.getCurrentElement();
if (!currentElement) {
return;
}
@@ -1044,7 +1236,7 @@ export const openEmojiPanel = (
event.stopPropagation();
return;
}
- moveEmojiSelection(emojisContentElement, event.key, () => emojiPanelController.loadMoreCustomEmojis());
+ emojiPanelController.moveSelection(event.key);
event.preventDefault();
event.stopPropagation();
});
diff --git a/app/src/emoji/panel.test.ts b/app/src/emoji/panel.test.ts
index 942c561334..03dc7b347e 100644
--- a/app/src/emoji/panel.test.ts
+++ b/app/src/emoji/panel.test.ts
@@ -1,6 +1,12 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
-import {collectEmojiMatches, getCustomEmojiBatch, getEmojiItemMap, groupCustomEmojiItems} from "./panel";
+import {
+ collectEmojiMatches,
+ getActiveEmojiCategory,
+ getEmojiItemMap,
+ getEmojiVirtualChunks,
+ groupCustomEmojiItems,
+} from "./panel";
const createEmoji = (unicode: string) => ({
unicode,
@@ -28,24 +34,24 @@ describe("groupCustomEmojiItems", () => {
});
});
-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"),
- ]);
+describe("getEmojiVirtualChunks", () => {
+ it("splits items at complete row boundaries", () => {
+ const items = Array.from({length: 15}, (_, index) => createEmoji(index.toString()));
+ const chunks = getEmojiVirtualChunks(items, 3, 2);
+ assert.deepEqual(chunks.map((chunk) => chunk.length), [6, 6, 3]);
+ });
+});
- 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);
+describe("getActiveEmojiCategory", () => {
+ const offsets = [{id: "recent", top: 0}, {id: "people", top: 100}, {id: "nature", top: 500}];
- 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);
+ it("selects the section at the sticky boundary", () => {
+ assert.equal(getActiveEmojiCategory(offsets, 98), "recent");
+ assert.equal(getActiveEmojiCategory(offsets, 99), "people");
+ });
+
+ it("selects the last section at the scroll boundary", () => {
+ assert.equal(getActiveEmojiCategory(offsets, 200, true), "nature");
});
});
@@ -70,9 +76,23 @@ describe("emoji filtering", () => {
assert.deepEqual(result.builtInItems.map((item) => item.unicode), ["1f600"]);
});
+ it("stops matching after reaching the requested maximum", () => {
+ let matchCount = 0;
+ collectEmojiMatches(categories, () => {
+ matchCount++;
+ return true;
+ }, 2);
+ assert.equal(matchCount, 2);
+ });
+
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);
});
+
+ it("reuses emoji indexes for an unchanged configuration", () => {
+ assert.equal(getEmojiItemMap(categories), getEmojiItemMap(categories));
+ assert.equal(getEmojiItemMap(categories, true), getEmojiItemMap(categories, true));
+ });
});
diff --git a/app/src/emoji/panel.ts b/app/src/emoji/panel.ts
index cb2e15555a..226aa3ae69 100644
--- a/app/src/emoji/panel.ts
+++ b/app/src/emoji/panel.ts
@@ -1,25 +1,32 @@
-export const CUSTOM_EMOJI_BATCH_SIZE = 128;
+export const EMOJI_VIRTUAL_CHUNK_ROWS = 8;
export type TCustomEmojiGroup = {
name: string;
items: IEmojiItem[];
};
-export type TCustomEmojiBatch = {
- groups: TCustomEmojiGroup[];
- nextOffset: number;
- hasMore: boolean;
-};
+const emojiItemMapCache = new WeakMap<IEmoji[], {
+ all: Map<string, IEmojiItem>;
+ builtIn: Map<string, IEmojiItem>;
+}>();
export const getEmojiItemMap = (categories: IEmoji[], hideCustom = false) => {
- const emojiMap = new Map<string, IEmojiItem>();
+ const cached = emojiItemMapCache.get(categories);
+ if (cached) {
+ return hideCustom ? cached.builtIn : cached.all;
+ }
+ const all = new Map<string, IEmojiItem>();
+ const builtIn = new Map<string, IEmojiItem>();
categories.forEach((category) => {
- if (hideCustom && category.id === "custom") {
- return;
- }
- category.items.forEach((item) => emojiMap.set(item.unicode, item));
+ category.items.forEach((item) => {
+ all.set(item.unicode, item);
+ if (category.id !== "custom") {
+ builtIn.set(item.unicode, item);
+ }
+ });
});
- return emojiMap;
+ emojiItemMapCache.set(categories, {all, builtIn});
+ return hideCustom ? builtIn : all;
};
export const collectEmojiMatches = (
@@ -31,13 +38,17 @@ export const collectEmojiMatches = (
const customItems: IEmojiItem[] = [];
const builtInItems: IEmojiItem[] = [];
let matchedCount = 0;
- categories.forEach((category) => {
+ outer:
+ for (const category of categories) {
if (hideCustom && category.id === "custom") {
- return;
+ continue;
}
- category.items.forEach((item) => {
- if ((typeof max === "number" && matchedCount >= max) || !matcher(item)) {
- return;
+ for (const item of category.items) {
+ if (typeof max === "number" && matchedCount >= max) {
+ break outer;
+ }
+ if (!matcher(item)) {
+ continue;
}
if (category.id === "custom") {
customItems.push(item);
@@ -45,8 +56,8 @@ export const collectEmojiMatches = (
builtInItems.push(item);
}
matchedCount++;
- });
- });
+ }
+ }
return {customItems, builtInItems};
};
@@ -79,36 +90,36 @@ export const groupCustomEmojiItems = (items: IEmojiItem[]) => {
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;
+export const getEmojiVirtualChunks = (
+ items: IEmojiItem[],
+ columnCount: number,
+ rowCount = EMOJI_VIRTUAL_CHUNK_ROWS,
+) => {
+ const chunks: IEmojiItem[][] = [];
+ const chunkSize = Math.max(1, columnCount) * Math.max(1, rowCount);
+ for (let offset = 0; offset < items.length; offset += chunkSize) {
+ chunks.push(items.slice(offset, offset + chunkSize));
+ }
+ return chunks;
+};
- 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;
+export const getActiveEmojiCategory = (
+ offsets: {id: string, top: number}[],
+ scrollTop: number,
+ isBottom = false,
+) => {
+ if (offsets.length === 0) {
+ return "";
+ }
+ if (isBottom) {
+ return offsets[offsets.length - 1].id;
+ }
+ let currentID = offsets[0].id;
+ for (const item of offsets) {
+ if (item.top > scrollTop + 1) {
+ break;
}
- skipped += group.items.length;
- });
-
- return {
- groups: batchGroups,
- nextOffset,
- hasMore: nextOffset < total,
- };
+ currentID = item.id;
+ }
+ return currentID;
};
diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.ts
index 482e09929b..44f96b67b5 100644
--- a/app/src/protyle/hint/index.ts
+++ b/app/src/protyle/hint/index.ts
@@ -38,7 +38,6 @@ import {
addEmoji,
EmojiPanelController,
genEmojiCategoryButtons,
- moveEmojiSelection,
unicode2Emoji,
} from "../../emoji";
import {blockRender} from "../render/blockRender";
@@ -141,6 +140,14 @@ export class Hint {
});
}
+ public deactivateEmojiPanel() {
+ this.emojiPanel?.deactivate();
+ }
+
+ public destroy() {
+ this.destroyEmojiPanel();
+ }
+
public prepareCreateTarget(protyle: IProtyle, type: TCreateTargetType) {
const notebookId = protyle.notebookId || "";
const path = protyle.path || "";
@@ -284,6 +291,7 @@ export class Hint {
}
public genLoading(protyle: IProtyle) {
+ this.destroyEmojiPanel();
if (this.element.classList.contains("fn__none")) {
this.element.innerHTML = '<div class="fn__loading" style="height: 128px;position: initial"><img width="64px" src="/stage/loading-pure.svg"></div>';
this.element.classList.remove("fn__none");
@@ -347,6 +355,7 @@ export class Hint {
public genHTML(data: IHintData[], protyle: IProtyle, hide = false, source: THintSource) {
this.source = source;
+ this.destroyEmojiPanel();
if (data.length === 0) {
if (!this.element.querySelector(".fn__loading") || hide) {
this.element.classList.add("fn__none");
@@ -488,8 +497,8 @@ ${genHintItemHTML(item)}
const targetElement = hasClosestBlock(protyle.toolbar.range?.startContainer);
const targetID = targetElement ? targetElement.getAttribute("data-node-id") : protyle.block.rootID;
let panelElement = this.element.querySelector(".emojis__panel") as HTMLElement;
- if (!panelElement) {
- this.emojiPanel?.destroy();
+ if (!panelElement || !this.emojiPanel) {
+ this.destroyEmojiPanel();
// 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"></div>
@@ -506,6 +515,7 @@ ${genHintItemHTML(item)}
}
this.emojiBrowseMode = value === "";
this.emojiPanel.renderSearch(value, 256);
+ this.emojiPanel.activate();
const firstEmojiElement = this.element.querySelector(".emojis__item");
if (firstEmojiElement) {
this.element.classList.remove("fn__none");
@@ -516,6 +526,12 @@ ${genHintItemHTML(item)}
}
}
+ private destroyEmojiPanel() {
+ this.emojiPanel?.destroy();
+ this.emojiPanel = undefined;
+ this.emojiBrowseMode = false;
+ }
+
public fill(value: string, protyle: IProtyle, updateRange = true, refIsS = false) {
hideElements(["hint", "toolbar"], protyle);
if (updateRange && this.source !== "av") {
@@ -1051,7 +1067,7 @@ ${genHintItemHTML(item)}
}
if (event.key === "Enter") {
if (isEmojiPanel) {
- const currentElement = this.element.querySelector(".emojis__item--current");
+ const currentElement = this.emojiPanel?.getCurrentElement();
if (!currentElement) {
return false;
}
@@ -1083,14 +1099,10 @@ ${genHintItemHTML(item)}
return true;
}
if (isEmojiPanel) {
- if (!this.element.querySelector(".emojis__item--current")) {
+ if (!this.emojiPanel?.getCurrentElement()) {
return false;
}
- moveEmojiSelection(
- this.element.querySelector(".emojis__panel") as HTMLElement,
- event.key,
- () => this.emojiPanel?.loadMoreCustomEmojis() || false,
- );
+ this.emojiPanel.moveSelection(event.key);
event.preventDefault();
event.stopPropagation();
return true;
diff --git a/app/src/protyle/ui/hideElements.ts b/app/src/protyle/ui/hideElements.ts
index 7be934b9f9..2ace482022 100644
--- a/app/src/protyle/ui/hideElements.ts
+++ b/app/src/protyle/ui/hideElements.ts
@@ -15,6 +15,7 @@ export const hideElements = (panels: string[], protyle?: IProtyle, focusHide = f
}
if (panels.includes("hint")) {
clearTimeout(protyle.hint.timeId);
+ protyle.hint.deactivateEmojiPanel();
protyle.hint.element.classList.add("fn__none");
}
if (protyle.gutter && panels.includes("gutter")) {
diff --git a/app/src/protyle/util/destroy.ts b/app/src/protyle/util/destroy.ts
index b45785dfdd..1652844b22 100644
--- a/app/src/protyle/util/destroy.ts
+++ b/app/src/protyle/util/destroy.ts
@@ -6,6 +6,7 @@ export const destroy = (protyle: IProtyle) => {
return;
}
hideElements(["util"], protyle);
+ protyle.hint?.destroy();
protyle.preview?.destroy();
if (isSupportCSSHL()) {
protyle.highlight.markHL.clear();