An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Show loading feedback for font menus and previews https://github.com/siyuan-note/siyuan/issues/20557
Daniel764487d82853
diff --git a/app/src/protyle/toolbar/fontFamilyMenu.test.ts b/app/src/protyle/toolbar/fontFamilyMenu.test.tsindex e349774bfc..2368ac309b 100644--- a/app/src/protyle/toolbar/fontFamilyMenu.test.ts+++ b/app/src/protyle/toolbar/fontFamilyMenu.test.ts@@ -14,6 +14,8 @@ const browserCases = async (sources: Record<string, string>, toolbarSource: strilet readonly = false;let fonts = Array.from({length: 60}, (_, index) => ({family: `Font ${index}`, displayName: `Font ${index}`, weight: 400}));let pendingFonts: Promise<{fontItems: typeof fonts}>;+ let pendingPreviews: Promise<FontFace[]>;+ Object.defineProperty(document.fonts, "load", {value: () => pendingPreviews || Promise.resolve([])});const modules: Record<string, {exports: any}> = {};const externals = {"util/functions": {isMobile: () => mobile},@@ -28,7 +30,6 @@ const browserCases = async (sources: Record<string, string>, toolbarSource: stri"block/popoverLifecycle": {setPopoverMenuOpen() {}},"config/entryVisibility/runtime": {applyMenuEntryVisibility() {}},"util/availableFont": {loadAvailableFonts: () => pendingFonts || Promise.resolve({fontItems: fonts})},- "util/fontPreview": {observeFontPreview: () => () => {}},"protyle/util/selection": {},};const load = (name: string): any => {@@ -137,7 +138,20 @@ const browserCases = async (sources: Record<string, string>, toolbarSource: stri}toolbar.style.fontSize = "";util.style.width = "";+ let finishPreviews: (fonts: FontFace[]) => void;+ pendingPreviews = new Promise(resolve => { finishPreviews = resolve; });await tap(button);+ const previewLoading = menuElement.querySelector<HTMLElement>('[data-type="font-loading"]');+ const previewLabel = menuElement.querySelector<HTMLElement>('[data-family="Font 0"] .b3-menu__label');+ check.ok(!previewLoading.classList.contains("fn__none"), "font preview waiting shows a spinner beside search");+ check.equal(previewLoading.querySelector(".fn__rotate use").getAttribute("xlink:href"), "#iconRefresh");+ check.equal(previewLabel.style.visibility, "hidden");+ check.equal(menuElement.querySelector<HTMLElement>('[data-family=""] .b3-menu__label').style.visibility, "");+ finishPreviews([]);+ await settle();+ check.ok(previewLoading.classList.contains("fn__none"));+ check.equal(previewLabel.style.visibility, "");+ pendingPreviews = undefined;check.ok(menuElement.classList.contains("b3-menu--sheet"));check.equal(button.getAttribute("aria-expanded"), "true");check.equal(menuElement.querySelector('[data-action="fontFamilyBack"]'), null);@@ -180,10 +194,34 @@ const browserCases = async (sources: Record<string, string>, toolbarSource: striawait tap(button);await tap(scrim);check.ok(menuElement.classList.contains("fn__none"));+ let failPreviews: (error: Error) => void;+ pendingPreviews = new Promise((_resolve, reject) => { failPreviews = reject; });+ await tap(button);+ const failedLoading = menuElement.querySelector<HTMLElement>('[data-type="font-loading"]');+ check.ok(!failedLoading.classList.contains("fn__none"));+ failPreviews(new Error("Font unavailable"));+ await settle();+ check.ok(failedLoading.classList.contains("fn__none"), "failed previews also finish loading");+ const failedLabel = menuElement.querySelector<HTMLElement>('[data-family="Font 0"] .b3-menu__label');+ check.equal(failedLabel.style.visibility, "");+ check.equal(failedLabel.style.fontFamily, "", "font failures retain readable fallback labels");+ await tap(scrim);+ pendingPreviews = new Promise(resolve => { finishPreviews = resolve; });+ await tap(button);+ const closedLoading = menuElement.querySelector<HTMLElement>('[data-type="font-loading"]');+ check.ok(!closedLoading.classList.contains("fn__none"));+ await tap(scrim);+ const closedHTML = closedLoading.outerHTML;+ finishPreviews([]);+ await settle();+ check.equal(closedLoading.outerHTML, closedHTML, "late preview completion does not update a closed picker");+ check.ok(menuElement.classList.contains("fn__none"));+ pendingPreviews = undefined;let resolve: (value: {fontItems: typeof fonts}) => void;pendingFonts = new Promise(done => { resolve = done; });const opening = api.openFontFamilyMenu(button, {disabled: false, mixed: false, onSelect() {}});await settle();+ check.equal(menuElement.querySelector(".fn__rotate use").getAttribute("xlink:href"), "#iconRefresh", "font list requests show the spinner too");await tap(scrim);resolve({fontItems: fonts});await opening;@@ -235,10 +273,10 @@ const browserCases = async (sources: Record<string, string>, toolbarSource: strireturn "Font menu touch and layout cases passed";};-test("font menus hide action buttons while preserving gesture dismissal, search viewport and selection", {timeout: 45000}, async () => {+test("font menus show loading for list requests and previews while retaining mobile and desktop interactions", {timeout: 45000}, async () => {const names = ["menus/Menu", "menus/menuPosition", "menus/menuMouseScroll", "menus/menuGroup", "menus/sheetOpen", "menus/sheetActions","menus/menuToggle", "plugin/Menu", "util/setPosition", "protyle/util/hasClosest", "protyle/toolbar/fontFamilyMenu",- "protyle/toolbar/fontFamilyCore", "util/systemFontCore", "util/escape", "util/upDownHint"];+ "protyle/toolbar/fontFamilyCore", "util/systemFontCore", "util/fontPreview", "util/escape", "util/upDownHint"];const sources = Object.fromEntries(names.map(name => [name, transpileModule(readFileSync(path.join(__dirname, "../..", name + ".ts"), "utf8"), {compilerOptions: {target: ScriptTarget.ES2021, module: ModuleKind.CommonJS},}).outputText]));diff --git a/app/src/protyle/toolbar/fontFamilyMenu.ts b/app/src/protyle/toolbar/fontFamilyMenu.tsindex d44332bc0e..3cb17646c0 100644--- a/app/src/protyle/toolbar/fontFamilyMenu.ts+++ b/app/src/protyle/toolbar/fontFamilyMenu.ts@@ -158,6 +158,8 @@ const genFontListItemHTML = (font: IFontItem | undefined, currentFamily: stringlet pickerID = 0;+const getFontLoadingHTML = () => `<svg class="b3-menu__icon fn__rotate" role="status" aria-label="${escapeAttr(window.siyuan.languages.loading)}"><use xlink:href="#iconRefresh"></use></svg>`;+const genFontPickerHTML = (fonts: IFontItem[], options: IFontFamilyPickerOptions, mobile: boolean) => {const currentFamily = options.mixed ? null : options.family;const items = [undefined, ...fonts];@@ -166,6 +168,7 @@ const genFontPickerHTML = (fonts: IFontItem[], options: IFontFamilyPickerOptionsconst searchInput = `<input spellcheck="false" class="b3-text-field fn__flex-1" data-type="font-family-search" role="combobox" aria-expanded="true" aria-controls="${listID}" aria-label="${escapeAttr(window.siyuan.languages.fontFamily)}" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">`;return `<div class="fn__flex-column ${mobile ? "b3-menu__custom" : "b3-menu__filter"}" style="height:100%"><div class="fn__flex">+ <span class="fn__flex fn__none" data-type="font-loading">${getFontLoadingHTML()}</span>${searchInput}</div><div class="fn__hr"></div>@@ -176,6 +179,7 @@ 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"]');+ const loadingElement = element.querySelector<HTMLElement>('[data-type="font-loading"]');const syncActiveDescendant = () => {const activeElement = listElement.querySelector<HTMLElement>(".b3-list-item--focus");if (activeElement) {@@ -217,6 +221,8 @@ const bindFontPicker = (element: HTMLElement, options: IFontFamilyPickerOptions)const cleanupPreview = observeFontPreview(listElement, label => {label.style.fontFamily = getInlineFontFamilyStyle(label.dataset.family);+ }, loading => {+ loadingElement.classList.toggle("fn__none", !loading);});inputElement.addEventListener("keydown", event => {options.onInteraction?.();@@ -299,7 +305,7 @@ export const openFontFamilyMenu = async (target: HTMLElement, options: IFontFamiconst pickerElement = menu.addItem({iconHTML: "",type: "empty",- label: `<div class="b3-menu__filter">${escapeHtml(window.siyuan.languages.loading)}</div>`,+ label: `<div class="fn__flex b3-menu__filter">${getFontLoadingHTML()}${escapeHtml(window.siyuan.languages.loading)}</div>`,});const mobile = isMobile();if (mobile) {diff --git a/app/src/util/fontPreview.test.ts b/app/src/util/fontPreview.test.tsindex e634a3b571..bd94aad053 100644--- a/app/src/util/fontPreview.test.ts+++ b/app/src/util/fontPreview.test.ts@@ -2,7 +2,7 @@ import * as assert from "node:assert/strict";import test from "node:test";import {observeFontPreview} from "./fontPreview";-test("font previews load near the viewport, reveal settled labels and stop after cleanup", async () => {+test("font previews report pending loads, reveal settled labels and stop updates after cleanup", async () => {const saved = new Map(["window", "document", "IntersectionObserver", "getComputedStyle"].map(key =>[key, Object.getOwnPropertyDescriptor(globalThis, key)]));let callback: (entries: unknown[]) => void;@@ -11,6 +11,8 @@ test("font previews load near the viewport, reveal settled labels and stop afterlet loads = 0;let applies = 0;let disconnected = false;+ const changes: boolean[] = [];+ const onLoadingChange = (loading: boolean) => changes.push(loading);const pending = () => new Promise<void>((resolve, fail) => {finish = resolve;reject = fail;@@ -42,47 +44,65 @@ test("font previews load near the viewport, reveal settled labels and stop afterdisconnect() { disconnected = true; }},});- const cleanup = observeFontPreview(list, apply);+ const cleanup = observeFontPreview(list, apply, onLoadingChange);assert.equal(label.style.visibility, "hidden");emit(false);assert.equal(loads, 0);+ assert.deepEqual(changes, []);emit(true);assert.equal(loads, 1);assert.equal(applies, 1);assert.equal(label.style.visibility, "hidden");+ assert.deepEqual(changes, [true]);emit(true);assert.equal(loads, 1);finish();await loading;assert.equal(label.style.visibility, "");assert.equal(label.style.fontFamily, "Preview");+ assert.deepEqual(changes, [true, false]);cleanup();assert.equal(disconnected, true);loading = pending();- const cleanupFailure = observeFontPreview(list, apply);+ changes.length = 0;+ const cleanupFailure = observeFontPreview(list, apply, onLoadingChange);emit(true);reject(new Error("Font unavailable"));await loading.catch(() => {});assert.equal(label.style.visibility, "");assert.equal(label.style.fontFamily, "");+ assert.deepEqual(changes, [true, false]);cleanupFailure();loading = pending();- const cleanupPending = observeFontPreview(list, apply);+ changes.length = 0;+ const cleanupPending = observeFontPreview(list, apply, onLoadingChange);emit(true);cleanupPending();finish();await loading;assert.equal(label.style.visibility, "hidden");+ assert.deepEqual(changes, [true]);const previousLoads = loads;callback([{target: {querySelector: () => label}, isIntersecting: true}]);assert.equal(loads, previousLoads);+ loading = pending();+ changes.length = 0;+ const cleanupRejected = observeFontPreview(list, apply, onLoadingChange);+ emit(true);+ cleanupRejected();+ reject(new Error("Closed font unavailable"));+ await loading.catch(() => {});+ assert.equal(label.style.fontFamily, "Preview");+ assert.equal(label.style.visibility, "hidden");+ assert.deepEqual(changes, [true]);+loading = pending();Object.assign(globalThis, {window: {}});- const cleanupFallback = observeFontPreview(list, apply);- assert.equal(loads, previousLoads + 1);+ const cleanupFallback = observeFontPreview(list, apply, onLoadingChange);+ assert.equal(loads, previousLoads + 2);finish();await loading;assert.equal(label.style.visibility, "");@@ -97,3 +117,52 @@ test("font previews load near the viewport, reveal settled labels and stop after});}});++test("font preview loading remains active until every pending visible preview settles", async () => {+ const saved = new Map(["window", "document", "IntersectionObserver", "getComputedStyle"].map(key =>+ [key, Object.getOwnPropertyDescriptor(globalThis, key)]));+ let callback: (entries: unknown[]) => void;+ const completions: Array<() => void> = [];+ const promises: Promise<void>[] = [];+ const changes: boolean[] = [];+ const items = ["First", "Second", ""].map(family => ({querySelector: () => ({+ dataset: {family}, textContent: family, style: {visibility: "", removeProperty() {}},+ })}));+ const list = {querySelectorAll: () => items} as unknown as HTMLElement;+ try {+ Object.assign(globalThis, {+ window: {IntersectionObserver: true},+ document: {fonts: {load: () => {+ const promise = new Promise<void>(resolve => completions.push(resolve));+ promises.push(promise);+ return promise;+ }}},+ getComputedStyle: () => ({fontWeight: "400", fontSize: "16px", fontFamily: "Preview"}),+ IntersectionObserver: class {+ constructor(cb: typeof callback) { callback = cb; }+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ });+ const cleanup = observeFontPreview(list, () => {}, loading => changes.push(loading));+ callback(items.map(target => ({target, isIntersecting: true})));+ assert.equal(promises.length, 2, "the default option does not trigger a font preview load");+ assert.deepEqual(changes, [true]);+ completions[0]();+ await promises[0];+ assert.deepEqual(changes, [true], "one completed preview must not hide the spinner for another");+ completions[1]();+ await promises[1];+ assert.deepEqual(changes, [true, false]);+ cleanup();+ } 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.tsindex 913ccc54b5..021d60ed01 100644--- a/app/src/util/fontPreview.ts+++ b/app/src/util/fontPreview.ts@@ -1,6 +1,8 @@export const observeFontPreview = (listElement: HTMLElement,- applyFont: (label: HTMLElement, item: HTMLElement) => void) => {+ applyFont: (label: HTMLElement, item: HTMLElement) => void,+ onLoadingChange?: (loading: boolean) => void) => {let closed = false;+ let pending = 0;let observer: IntersectionObserver;const prepared = new WeakSet<HTMLElement>();const prepare = async (item: HTMLElement) => {@@ -10,17 +12,26 @@ export const observeFontPreview = (listElement: HTMLElement,}prepared.add(item);observer?.unobserve(item);+ if (pending++ === 0) {+ onLoadingChange?.(true);+ }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");+ if (!closed) {+ label.style.removeProperty("font-family");+ label.style.removeProperty("font-weight");+ }} finally {+ pending--;if (!closed) {label.style.removeProperty("visibility");+ if (pending === 0) {+ onLoadingChange?.(false);+ }}}};