An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Prevent font preview flicker in font menus https://github.com/siyuan-note/siyuan/issues/19226
Daniel1e0ee6139556
diff --git a/app/src/config/tabs/appearanceTab.ts b/app/src/config/tabs/appearanceTab.tsindex 4857b75490..97f5613c35 100644--- a/app/src/config/tabs/appearanceTab.ts+++ b/app/src/config/tabs/appearanceTab.ts@@ -38,6 +38,7 @@ import {} from "../../util/customFont";import {showMessage} from "../../dialog/message";import {IFontItem, loadSystemFonts} from "../../util/systemFont";+import {observeFontPreview} from "../../util/fontPreview";import {shouldShowBootAppearanceSetting,type IBootAppearanceListItem,@@ -344,10 +345,10 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesCon// 在异步加载前阻止冒泡,避免同一次点击关闭字体菜单。event.stopPropagation();let closed = false;- let fontPreviewObserver: IntersectionObserver;+ let cleanupFontPreview: () => void;const fontMenu = new Menu(`appearanceFontFamily-${configKey}`, () => {closed = true;- fontPreviewObserver?.disconnect();+ cleanupFontPreview?.();refreshOpenMenu = undefined;});if (fontMenu.isOpen) {@@ -416,36 +417,14 @@ const mountAppearanceFontFamily = (root: HTMLElement, configKey: FontFamiliesConfilterFontList();};refreshFontMenu();- if ("IntersectionObserver" in window) {- fontPreviewObserver = new IntersectionObserver((entries) => {- entries.forEach((entry) => {- const itemElement = entry.target as HTMLElement;- const labelElement = itemElement.querySelector<HTMLElement>(".b3-menu__label");- if (!entry.isIntersecting || !labelElement?.dataset.family) {- labelElement?.style.removeProperty("font-family");- labelElement?.style.removeProperty("font-weight");- return;- }- const customFont = itemElement.dataset.id ? customFontsByID.get(itemElement.dataset.id) : undefined;- if (customFont) {- registerCustomFont(customFont);- }- labelElement.style.fontFamily = labelElement.dataset.family;- labelElement.style.fontWeight = labelElement.dataset.weight;- });- }, {- root: listElement,- });- listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach((item) => {- fontPreviewObserver.observe(item);- });- } else {- listElement.querySelectorAll<HTMLElement>(".b3-menu__label").forEach((item) => {- item.style.fontFamily = item.dataset.family;- item.style.fontWeight = item.dataset.weight;- });- customFonts.forEach(registerCustomFont);- }+ cleanupFontPreview = observeFontPreview(listElement, (label, item) => {+ const customFont = item.dataset.id ? customFontsByID.get(item.dataset.id) : undefined;+ if (customFont) {+ registerCustomFont(customFont);+ }+ label.style.fontFamily = label.dataset.family;+ label.style.fontWeight = label.dataset.weight;+ });function filterFontList() {const value = inputElement.value.toLowerCase().trim();listElement.querySelector(".b3-list-item--focus")?.classList.remove("b3-list-item--focus");diff --git a/app/src/protyle/toolbar/fontFamilyMenu.ts b/app/src/protyle/toolbar/fontFamilyMenu.tsindex c298559c51..50cfb99b0b 100644--- a/app/src/protyle/toolbar/fontFamilyMenu.ts+++ b/app/src/protyle/toolbar/fontFamilyMenu.ts@@ -1,4 +1,5 @@import {Menu} from "../../plugin/Menu";+import {observeFontPreview} from "../../util/fontPreview";import {escapeAttr, escapeHtml} from "../../util/escape";import {getFontFamilyDisplayName,@@ -155,7 +156,6 @@ const genFontPickerHTML = (fonts: IFontItem[], options: IFontFamilyPickerOptionsconst bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions) => {const listElement = element.querySelector<HTMLElement>('[data-type="font-family-list"]');const inputElement = element.querySelector<HTMLInputElement>('[data-type="font-family-search"]');- let previewObserver: IntersectionObserver;let removalObserver: MutationObserver;const syncActiveDescendant = () => {const activeElement = listElement.querySelector<HTMLElement>(".b3-list-item--focus");@@ -188,7 +188,7 @@ const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions)syncActiveDescendant();};const cleanup = () => {- previewObserver?.disconnect();+ cleanupPreview?.();removalObserver?.disconnect();};const selectItem = (item: HTMLElement) => {@@ -197,23 +197,9 @@ const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions)options.onSelect(item.dataset.family || undefined);};- if ("IntersectionObserver" in window) {- previewObserver = new IntersectionObserver(entries => {- entries.forEach(entry => {- const labelElement = (entry.target as HTMLElement).querySelector<HTMLElement>(".b3-menu__label");- if (!entry.isIntersecting || !labelElement?.dataset.family) {- labelElement?.style.removeProperty("font-family");- return;- }- labelElement.style.fontFamily = getInlineFontFamilyStyle(labelElement.dataset.family);- });- }, {root: listElement});- listElement.querySelectorAll<HTMLElement>(".b3-list-item").forEach(item => previewObserver.observe(item));- } else {- listElement.querySelectorAll<HTMLElement>('.b3-menu__label[data-family]:not([data-family=""])').forEach(item => {- item.style.fontFamily = getInlineFontFamilyStyle(item.dataset.family);- });- }+ const cleanupPreview = observeFontPreview(listElement, label => {+ label.style.fontFamily = getInlineFontFamilyStyle(label.dataset.family);+ });inputElement.addEventListener("keydown", event => {options.onInteraction?.();event.stopPropagation();diff --git a/app/src/util/fontPreview.test.ts b/app/src/util/fontPreview.test.tsnew file mode 100644index 0000000000..21216f611a--- /dev/null+++ b/app/src/util/fontPreview.test.ts@@ -0,0 +1,86 @@+import * as assert from "node:assert/strict";+import test from "node:test";+import {observeFontPreview} from "./fontPreview";++test("font previews wait for loading, retain prepared fonts and stop after cleanup", async () => {+ const saved = new Map(["window", "document", "IntersectionObserver", "getComputedStyle"].map(key =>+ [key, Object.getOwnPropertyDescriptor(globalThis, key)]));+ let callback: (entries: unknown[]) => void;+ let finish: () => void;+ let reject: (error: Error) => void;+ let loads = 0;+ let applies = 0;+ let disconnected = false;+ const pending = () => new Promise<void>((resolve, fail) => {+ finish = resolve;+ reject = fail;+ });+ let loading = pending();+ const label = {+ dataset: {family: "Preview"}, textContent: "Preview",+ style: {visibility: "", fontFamily: "", fontWeight: "", removeProperty(name: string) {+ this[name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] = "";+ }},+ };+ const item = {querySelector: () => label};+ const list = {querySelectorAll: () => [item]} as unknown as HTMLElement;+ const emit = (visible: boolean) => callback([{target: item, isIntersecting: visible}]);+ const apply = () => { applies++; label.style.fontFamily = "Preview"; };+ try {+ Object.assign(globalThis, {+ window: {IntersectionObserver: true},+ document: {fonts: {load: () => { loads++; return loading; }}},+ getComputedStyle: () => ({fontWeight: "400", fontSize: "16px", fontFamily: "Preview"}),+ IntersectionObserver: class {+ constructor(cb: typeof callback, options: IntersectionObserverInit) {+ callback = cb;+ assert.equal(options.root, list);+ assert.equal(options.rootMargin, "200px 0px");+ }+ observe() {}+ unobserve() {}+ disconnect() { disconnected = true; }+ },+ });+ const cleanup = observeFontPreview(list, apply);+ assert.equal(label.style.visibility, "hidden");+ emit(false);+ assert.equal(loads, 0);+ emit(true);+ assert.equal(label.style.visibility, "hidden");+ finish();+ await loading;+ assert.equal(label.style.visibility, "");+ emit(false);+ emit(true);+ assert.equal(applies, 1);+ assert.equal(label.style.fontFamily, "Preview");+ cleanup();+ assert.equal(disconnected, true);++ loading = pending();+ const cleanupFailure = observeFontPreview(list, apply);+ emit(true);+ reject(new Error("Font unavailable"));+ await loading.catch(() => {});+ assert.equal(label.style.visibility, "");+ assert.equal(label.style.fontFamily, "");+ cleanupFailure();++ loading = pending();+ const cleanupPending = observeFontPreview(list, apply);+ emit(true);+ cleanupPending();+ finish();+ await loading;+ assert.equal(label.style.visibility, "hidden");+ } finally {+ saved.forEach((descriptor, key) => {+ if (descriptor) {+ Object.defineProperty(globalThis, key, descriptor);+ } else {+ Reflect.deleteProperty(globalThis, key);+ }+ });+ }+});diff --git a/app/src/util/fontPreview.ts b/app/src/util/fontPreview.tsnew file mode 100644index 0000000000..2a9b722b37--- /dev/null+++ b/app/src/util/fontPreview.ts@@ -0,0 +1,51 @@+export const observeFontPreview = (listElement: HTMLElement,+ applyFont: (label: HTMLElement, item: HTMLElement) => void) => {+ let closed = false;+ let observer: IntersectionObserver;+ const prepared = new WeakSet<HTMLElement>();+ const prepare = async (item: HTMLElement) => {+ const label = item.querySelector<HTMLElement>(".b3-menu__label");+ if (closed || !label?.dataset.family || prepared.has(item)) {+ return;+ }+ prepared.add(item);+ observer?.unobserve(item);+ try {+ applyFont(label, item);+ const style = getComputedStyle(label);+ await document.fonts?.load(`${style.fontWeight} ${style.fontSize} ${style.fontFamily}`, label.textContent);+ } catch (error) {+ // 字体加载失败时使用界面字体,确保名称仍可阅读和选择。+ label.style.removeProperty("font-family");+ label.style.removeProperty("font-weight");+ } finally {+ if (!closed) {+ label.style.removeProperty("visibility");+ }+ }+ };+ const items = listElement.querySelectorAll<HTMLElement>(".b3-list-item");+ // 名称在预览字体就绪后显示,离开可见区域时保留字体,避免滚动时反复切换。+ items.forEach(item => {+ const label = item.querySelector<HTMLElement>(".b3-menu__label");+ if (label?.dataset.family) {+ label.style.visibility = "hidden";+ }+ });+ if ("IntersectionObserver" in window) {+ observer = new IntersectionObserver(entries => {+ entries.forEach(entry => {+ if (entry.isIntersecting) {+ void prepare(entry.target as HTMLElement);+ }+ });+ }, {root: listElement, rootMargin: "200px 0px"});+ items.forEach(item => observer.observe(item));+ } else {+ items.forEach(item => void prepare(item));+ }+ return () => {+ closed = true;+ observer?.disconnect();+ };+};