AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(fonts): show loading status and retry failed font loads
tianma-if8726df75428e
diff --git a/apps/web/src/components/FontLabel.tsx b/apps/web/src/components/FontLabel.tsxindex b0cdc96b..11d2bae7 100644--- a/apps/web/src/components/FontLabel.tsx+++ b/apps/web/src/components/FontLabel.tsx@@ -1,9 +1,15 @@import { useEffect, useRef, useState } from "react";+import { FontLoadIcon } from "./FontLoadFeedback";+import type { FontLoadStatus } from "@/lib/font-load-state";+import { useTranslation } from "react-i18next";import { FONT_CATALOG, type RemoteNoteImageFont } from "@edgeever/shared/font-catalog";import { loadCatalogFont } from "@edgeever/shared/font-loader";/** Radix mounts hidden items too; previews only request fonts for visible menu rows. */-export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enabled, visibleOnly = false, loadFont }: {+export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enabled, visibleOnly = false, loadFont, status, onStatusChange, retryKey = 0 }: {+ onStatusChange?: (status: FontLoadStatus) => void;+ status?: FontLoadStatus;+ retryKey?: number;label: string;fontId?: RemoteNoteImageFont;fontFamily?: string;@@ -12,10 +18,12 @@ export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enablvisibleOnly?: boolean;loadFont?: (text: string) => Promise<unknown>;}) => {+ const { t } = useTranslation();+ const [progress, setProgress] = useState<{ key: string; status: FontLoadStatus }>({ key: "", status: "idle" });const ref = useRef<HTMLSpanElement>(null);const [readyKey, setReadyKey] = useState("");const family = fontFamily ?? (fontId ? `"${registrationFamily ?? FONT_CATALOG[fontId].family}", sans-serif` : undefined);- const key = `${fontId ?? ""}:${family ?? ""}:${label}`;+ const key = `${fontId ?? ""}:${family ?? ""}:${label}:${retryKey}`;useEffect(() => {if (!enabled) return;let active = true;@@ -23,8 +31,9 @@ export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enablconst load = () => {if (started) return;started = true;+ setProgress({ key, status: "loading" });const pending = fontId ? loadCatalogFont(fontId, label, { family: registrationFamily }) : loadFont?.(label) ?? Promise.resolve();- void pending.then(() => { if (active) setReadyKey(key); }).catch(() => { /* Keep names readable and selectable. */ });+ void pending.then(() => { if (active) { setReadyKey(key); setProgress({ key, status: "ready" }); } }).catch(() => { if (active) setProgress({ key, status: "error" }); });};let observer: IntersectionObserver | undefined;if (visibleOnly && ref.current) {@@ -35,5 +44,13 @@ export const FontLabel = ({ label, fontId, fontFamily, registrationFamily, enabl} else load();return () => { active = false; observer?.disconnect(); };}, [enabled, visibleOnly, fontId, registrationFamily, label, key, loadFont]);- return <span ref={ref} className="text-sm leading-6" style={readyKey === key ? { fontFamily: family } : undefined}>{label}</span>;+ const ownStatus = progress.key === key ? progress.status : "idle";+ useEffect(() => { if (enabled) onStatusChange?.(ownStatus === "idle" ? "loading" : ownStatus); }, [enabled, onStatusChange, ownStatus]);+ const displayStatus = status === "error" || ownStatus === "error" ? "error"+ : status === "loading" || ownStatus === "loading" ? "loading" : status ?? ownStatus;+ return <span ref={ref} className="inline-flex items-center gap-1.5 text-sm leading-6" aria-busy={displayStatus === "loading"}>+ <span style={readyKey === key ? { fontFamily: family } : undefined}>{label}</span>+ <FontLoadIcon status={displayStatus} />+ {displayStatus === "loading" || displayStatus === "error" ? <span className="sr-only">{t(`fontLoad.${displayStatus}`)}</span> : null}+ </span>;};diff --git a/apps/web/src/components/FontLoadFeedback.tsx b/apps/web/src/components/FontLoadFeedback.tsxnew file mode 100644index 00000000..f5bda0a4--- /dev/null+++ b/apps/web/src/components/FontLoadFeedback.tsx@@ -0,0 +1,23 @@+import { Check, CircleAlert, LoaderCircle } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import type { FontLoadStatus } from "@/lib/font-load-state";++export const FontLoadIcon = ({ status }: { status: FontLoadStatus }) => {+ if (status === "loading") return <LoaderCircle aria-hidden="true" className="h-3.5 w-3.5 shrink-0 animate-spin motion-reduce:animate-none" />;+ if (status === "error") return <CircleAlert aria-hidden="true" className="h-3.5 w-3.5 shrink-0 text-red-600" />;+ return null;+};++/** Kept outside SelectTrigger/SelectItem so retry is a real keyboard-accessible button. */+export const FontLoadFeedback = ({ status, onRetry }: { status: FontLoadStatus; onRetry: () => void }) => {+ const { t } = useTranslation();+ if (status === "idle") return null;+ return <div className="flex min-h-6 items-center gap-1.5 text-xs text-slate-500">+ <span role="status" aria-live="polite" className="flex items-center gap-1.5">+ {status === "ready" ? <Check aria-hidden="true" className="h-3.5 w-3.5" /> : <FontLoadIcon status={status} />}+ {t(`fontLoad.${status}`)}+ </span>+ {status === "error" ? <Button type="button" variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={onRetry}>{t("fontLoad.retry")}</Button> : null}+ </div>;+};diff --git a/apps/web/src/components/PosterEditorPane.tsx b/apps/web/src/components/PosterEditorPane.tsxindex 44cef6a5..72a0154e 100644--- a/apps/web/src/components/PosterEditorPane.tsx+++ b/apps/web/src/components/PosterEditorPane.tsx@@ -1,6 +1,7 @@+import { createFontLoadState } from "@/lib/font-load-state";import { loadPosterFont } from "@/lib/poster-design/fonts";import { AI_ASSISTANT_LAUNCHER_POSITION } from "@/lib/ai-assistant-launcher";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { useTranslation } from "react-i18next";import {ArrowLeft,@@ -170,6 +171,7 @@ export default function PosterEditorPane({const [selectedIds, setSelectedIds] = useState<string[]>([]);const [busy, setBusy] = useState(false),[canvasReady, setCanvasReady] = useState(false),+ [fontLoadState] = useState(createFontLoadState),[canvasRevision, setCanvasRevision] = useState(0),[saving, setSaving] = useState(false),[ready, setReady] = useState(false);@@ -244,6 +246,7 @@ export default function PosterEditorPane({} | null>(null);const draftKey = `edgeever:poster-draft:${memo.id}`;const dirty = snapshot(title, document) !== saved || tagsText !== savedTags;+ const fontStatus = useSyncExternalStore(fontLoadState.subscribe, fontLoadState.getSnapshot, fontLoadState.getSnapshot);const editable = !readOnly && Boolean(initial) && ready && !busy;const selectedElements = document.elements.filter((element) =>selectedIds.includes(element.id),@@ -786,12 +789,12 @@ export default function PosterEditorPane({instance.on("text:changed", ({ target }) => {if (!(target instanceof Textbox)) return;const text = target.text;- void loadPosterFont(target.fontFamily, text).then(() => {+ void fontLoadState.run(() => loadPosterFont(target.fontFamily, text)).then(() => {if (canvas.current !== instance || target.text !== text) return;target.initDimensions();target.dirty = true;instance.requestRenderAll();- }).catch(() => { /* The current readable fallback remains until another edit or retry. */ });+ }).catch(() => { /* The font feedback exposes failure and rebuilds the canvas on retry. */ });});instance.on("object:moving", ({ target }) => {if (!target || !options.current.snap || target instanceof ActiveSelection)@@ -866,9 +869,10 @@ export default function PosterEditorPane({setCanvasReady(false);const value = current.current.document,ids = [...selected.current];- void Promise.all(- value.elements.map((element) => posterObject(element, readResource)),- )+ void fontLoadState.run(() => Promise.all(+ value.elements.filter(element => element.type === "text").map(element => loadPosterFont(element.fontFamily, element.text)),+ ))+ .then(() => cancelled ? [] : Promise.all(value.elements.map(element => posterObject(element, readResource)))).then((objects) => {if (cancelled) return;instance.discardActiveObject();@@ -914,8 +918,9 @@ export default function PosterEditorPane({});return () => {cancelled = true;+ fontLoadState.reset();};- }, [canvasRevision, readOnly, readResource]);+ }, [canvasRevision, readOnly, readResource, fontLoadState]);useEffect(() => {const instance = canvas.current;if (!instance) return;@@ -2035,6 +2040,8 @@ export default function PosterEditorPane({<div className="min-h-0 flex-1 overflow-y-auto">{rightTab === "properties" ? (<PosterInspector+ fontStatus={fontStatus}+ onRetryFont={() => { setError(null); setCanvasRevision(value => value + 1); }}elements={selectedElements}disabled={!editable}zh={zh}diff --git a/apps/web/src/components/dialogs/NoteImageFontLabel.tsx b/apps/web/src/components/dialogs/NoteImageFontLabel.tsxindex f67d267f..a47cf752 100644--- a/apps/web/src/components/dialogs/NoteImageFontLabel.tsx+++ b/apps/web/src/components/dialogs/NoteImageFontLabel.tsx@@ -1,3 +1,4 @@+import type { FontLoadStatus } from "@/lib/font-load-state";import { useCallback } from "react";import { prepareNoteImageAssets } from "@edgeever/shared/note-image-fonts";import { noteImageAssetUrls } from "@edgeever/shared/note-image-assets";@@ -5,9 +6,12 @@ import { isRemoteNoteImageFont } from "@edgeever/shared/font-catalog";import { resolveNoteImageTypography, type NoteImageFontStyle, type NoteImageTheme } from "@edgeever/shared/note-image-card";import { FontLabel } from "@/components/FontLabel";-export const NoteImageFontLabel = ({ label, fontStyle, theme, enabled, visibleOnly = false }: {+export const NoteImageFontLabel = ({ label, fontStyle, theme, enabled, visibleOnly = false, status, onStatusChange, retryKey }: {+ onStatusChange?: (status: FontLoadStatus) => void;+ status?: FontLoadStatus;+ retryKey?: number;label: string; fontStyle: NoteImageFontStyle; theme: NoteImageTheme; enabled: boolean; visibleOnly?: boolean;}) => {const loadFont = useCallback((text: string) => prepareNoteImageAssets({ theme, fontStyle, text, urls: noteImageAssetUrls, embed: false }), [theme, fontStyle]);- return <FontLabel label={label} fontId={isRemoteNoteImageFont(fontStyle) ? fontStyle : undefined} fontFamily={resolveNoteImageTypography(theme, fontStyle).bodyFamily} enabled={enabled} visibleOnly={visibleOnly} loadFont={loadFont} />;+ return <FontLabel onStatusChange={onStatusChange} status={status} retryKey={retryKey} label={label} fontId={isRemoteNoteImageFont(fontStyle) ? fontStyle : undefined} fontFamily={resolveNoteImageTypography(theme, fontStyle).bodyFamily} enabled={enabled} visibleOnly={visibleOnly} loadFont={loadFont} />;};diff --git a/apps/web/src/components/dialogs/ShareNoteImageDialog.tsx b/apps/web/src/components/dialogs/ShareNoteImageDialog.tsxindex a17c1b2b..2f347133 100644--- a/apps/web/src/components/dialogs/ShareNoteImageDialog.tsx+++ b/apps/web/src/components/dialogs/ShareNoteImageDialog.tsx@@ -1,3 +1,6 @@+import type { FontLoadStatus } from "@/lib/font-load-state";+import { useFontPreviewStatus } from "@/lib/use-font-preview-status";+import { FontLoadFeedback } from "@/components/FontLoadFeedback";import { FONT_CATALOG, FONT_IDS } from "@edgeever/shared/font-catalog";import { prepareNoteImageAssets } from "@edgeever/shared/note-image-fonts";import { noteImageAssetUrls } from "@edgeever/shared/note-image-assets";@@ -143,6 +146,8 @@ export const ShareNoteImageDialog = ({const [error, setError] = useState<false | true | "font">(false);const [retry, setRetry] = useState(0);const [copyState, setCopyState] = useState<"idle" | "copying" | "copied" | "failed">("idle");+ const [contentFontStatus, setContentFontStatus] = useState<FontLoadStatus>("loading");+ const { status: selectedFontStatus, onPreviewStatus } = useFontPreviewStatus(`${fontStyle}:${theme}:${retry}`, contentFontStatus);const generationRef = useRef(0);const copyAttemptRef = useRef(0);@@ -153,6 +158,7 @@ export const ShareNoteImageDialog = ({setCopyState("idle");setPrepared(null);setError(false);+ setContentFontStatus("loading");const controller = new AbortController();const timer = window.setTimeout(() => {void createNoteImage({@@ -175,6 +181,7 @@ export const ShareNoteImageDialog = ({tags: showTags ? source.tags : [],updatedAt: showUpdatedAt ? source.updatedAt : "",signal: controller.signal,+ onFontLoadStatus: status => { if (generation === generationRef.current) setContentFontStatus(status); },}).then((result) => {if (generation !== generationRef.current) return;@@ -190,6 +197,7 @@ export const ShareNoteImageDialog = ({}, 180);return () => {window.clearTimeout(timer);+ if (generationRef.current === generation) generationRef.current++;controller.abort();};}, [@@ -349,17 +357,18 @@ export const ShareNoteImageDialog = ({<Select value={fontStyle} onOpenChange={setFontMenuOpen} onValueChange={(value) => setPreference("fontStyle", value as NoteImageFontStyle)}><SelectTrigger aria-label={t("editor.imageShare.fontStyle")} className="h-9 w-full text-xs font-normal"><SelectValue>- <NoteImageFontLabel label={t(FONT_OPTIONS.find(item => item.id === fontStyle)!.labelKey)} fontStyle={fontStyle} theme={theme} enabled={open} />+ <NoteImageFontLabel label={t(FONT_OPTIONS.find(item => item.id === fontStyle)!.labelKey)} fontStyle={fontStyle} theme={theme} enabled={open} status={error === true ? undefined : selectedFontStatus} onStatusChange={onPreviewStatus} retryKey={retry} /></SelectValue></SelectTrigger><SelectContent className="max-h-80">{FONT_OPTIONS.map((item) => (- <SelectItem key={item.id} value={item.id}>+ <SelectItem key={item.id} value={item.id} textValue={t(item.labelKey)}><NoteImageFontLabel label={t(item.labelKey)} fontStyle={item.id} theme={theme} enabled={open && fontMenuOpen} visibleOnly /></SelectItem>))}</SelectContent></Select>+ {error === true ? null : <FontLoadFeedback status={selectedFontStatus} onRetry={() => setRetry(value => value + 1)} />}{/* Font Size */}<div className="space-y-1.5 pt-1">diff --git a/apps/web/src/components/poster/PosterFontPicker.tsx b/apps/web/src/components/poster/PosterFontPicker.tsxindex a1b5660a..e0921b73 100644--- a/apps/web/src/components/poster/PosterFontPicker.tsx+++ b/apps/web/src/components/poster/PosterFontPicker.tsx@@ -1,3 +1,6 @@+import { useFontPreviewStatus } from "@/lib/use-font-preview-status";+import type { FontLoadStatus } from "@/lib/font-load-state";+import { FontLoadFeedback } from "@/components/FontLoadFeedback";import { useCallback, useState } from "react";import { useTranslation } from "react-i18next";import { findCatalogFont } from "@edgeever/shared/font-catalog";@@ -5,17 +8,20 @@ import { FontLabel } from "@/components/FontLabel";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { POSTER_FONTS, loadPosterFont } from "@/lib/poster-design/fonts";-const PosterFontName = ({ family, label, enabled, visibleOnly = false }: {- family: string; label: string; enabled: boolean; visibleOnly?: boolean;+const PosterFontName = ({ family, label, enabled, visibleOnly = false, status, onStatusChange, retryKey }: {+ family: string; label: string; enabled: boolean; visibleOnly?: boolean; status?: FontLoadStatus; onStatusChange?: (status: FontLoadStatus) => void; retryKey?: number;}) => {const loadFont = useCallback((text: string) => loadPosterFont(family, text), [family]);- return <FontLabel label={label} fontId={findCatalogFont(family)} registrationFamily={family} fontFamily={["sans-serif", "serif", "monospace"].includes(family) ? family : `"${family}", sans-serif`} enabled={enabled} visibleOnly={visibleOnly} loadFont={loadFont} />;+ return <FontLabel onStatusChange={onStatusChange} status={status} retryKey={retryKey} label={label} fontId={findCatalogFont(family)} registrationFamily={family} fontFamily={["sans-serif", "serif", "monospace"].includes(family) ? family : `"${family}", sans-serif`} enabled={enabled} visibleOnly={visibleOnly} loadFont={loadFont} />;};-export const PosterFontPicker = ({ value, disabled, zh, onChange }: {+export const PosterFontPicker = ({ value, disabled, zh, onChange, status, onRetry }: {+ status: FontLoadStatus; onRetry: () => void;value: string; disabled: boolean; zh: boolean; onChange: (family: string) => void;}) => {const { t } = useTranslation();+ const [retryKey, setRetryKey] = useState(0);+ const { status: selectedStatus, onPreviewStatus } = useFontPreviewStatus(`${value}:${retryKey}`, status);const [open, setOpen] = useState(false);const choices = [{ family: "sans-serif", label: t("poster.sans") },@@ -23,14 +29,14 @@ export const PosterFontPicker = ({ value, disabled, zh, onChange }: {{ family: "monospace", label: t("poster.mono") },...POSTER_FONTS.map(font => ({ family: font.family, label: zh ? font.zh : font.en })),];- return <Select value={value} disabled={disabled} onOpenChange={setOpen} onValueChange={onChange}>+ return <div className="space-y-1"><Select value={value} disabled={disabled} onOpenChange={setOpen} onValueChange={onChange}><SelectTrigger aria-label={t("poster.fontFamily")} className="h-9 w-full">- <SelectValue><PosterFontName family={value} label={choices.find(font => font.family === value)?.label ?? value} enabled /></SelectValue>+ <SelectValue><PosterFontName family={value} label={choices.find(font => font.family === value)?.label ?? value} enabled onStatusChange={onPreviewStatus} status={selectedStatus} retryKey={retryKey} /></SelectValue></SelectTrigger><SelectContent className="max-h-80">- {choices.map(font => <SelectItem key={font.family} value={font.family}>+ {choices.map(font => <SelectItem key={font.family} value={font.family} textValue={font.label}><PosterFontName family={font.family} label={font.label} enabled={open} visibleOnly /></SelectItem>)}</SelectContent>- </Select>;+ </Select><FontLoadFeedback status={selectedStatus} onRetry={() => { setRetryKey(value => value + 1); onRetry(); }} /></div>;};diff --git a/apps/web/src/components/poster/PosterInspector.tsx b/apps/web/src/components/poster/PosterInspector.tsxindex 9fa35624..2aed2e74 100644--- a/apps/web/src/components/poster/PosterInspector.tsx+++ b/apps/web/src/components/poster/PosterInspector.tsx@@ -1,3 +1,4 @@+import type { FontLoadStatus } from "@/lib/font-load-state";import {AlignCenter,AlignHorizontalDistributeCenter,@@ -35,6 +36,8 @@ export type PosterAlign ="left" | "center" | "right" | "top" | "middle" | "bottom";export function PosterInspector({elements,+ fontStatus,+ onRetryFont,disabled,onPatch,onAlign,@@ -43,6 +46,8 @@ export function PosterInspector({onImageFit,zh,}: {+ fontStatus: FontLoadStatus;+ onRetryFont: () => void;elements: PosterElement[];disabled: boolean;onPatch: (patch: Partial<PosterElement>) => void;@@ -112,6 +117,8 @@ export function PosterInspector({</div>{active?.type === "text" && (<PosterFontPicker+ status={fontStatus}+ onRetry={onRetryFont}value={active.fontFamily}disabled={!editable}zh={zh}diff --git a/apps/web/src/components/settings/PreferenceCard.tsx b/apps/web/src/components/settings/PreferenceCard.tsxindex 313c5ca8..f9b74eb1 100644--- a/apps/web/src/components/settings/PreferenceCard.tsx+++ b/apps/web/src/components/settings/PreferenceCard.tsx@@ -1,7 +1,10 @@+import { useFontPreviewStatus } from "@/lib/use-font-preview-status";import { FONT_CATALOG, FONT_IDS, isRemoteNoteImageFont } from "@edgeever/shared/font-catalog";+import { FontLoadFeedback } from "@/components/FontLoadFeedback";+import { editorFontLoadState, retryEditorCatalogFont } from "@/lib/editor-catalog-fonts";import { FontLabel } from "@/components/FontLabel";import { AlignVerticalSpaceAround, AppWindow, BookOpenText, ChartNoAxesCombined, Code2, Image, Keyboard, Languages, ListTree, MousePointerClick, Palette, Sparkles, SpellCheck, SunMoon, Type } from "lucide-react";-import { useState, useEffect, type ReactNode } from "react";+import { useState, useEffect, useSyncExternalStore, type ReactNode } from "react";import { useTranslation } from "react-i18next";import type { NoteProsePatch, NoteProsePaletteChoice, ResolvedNoteProse } from "@edgeever/shared";import { DEFAULT_NOTE_PROSE_CSS, MAX_NOTE_PROSE_CSS_BYTES, NOTE_PROSE_FONT_SIZES, NOTE_PROSE_PALETTE_CHOICES, NOTE_PROSE_PALETTES, noteProseCssDropsDeclarations } from "@edgeever/shared";@@ -91,6 +94,10 @@ const FontChoiceFields = ({}) => {const { t } = useTranslation();const [fontOpen, setFontOpen] = useState(false);+ const [fontRetry, setFontRetry] = useState(0);+ const bodyStatus = useSyncExternalStore(editorFontLoadState.subscribe, editorFontLoadState.getSnapshot, editorFontLoadState.getSnapshot);+ const catalogSelected = includeCatalog && isRemoteNoteImageFont(preference.choice);+ const { status: selectedStatus, onPreviewStatus } = useFontPreviewStatus(`${preference.choice}:${fontRetry}`, bodyStatus === "idle" ? "loading" : bodyStatus);return (<div className="flex w-full shrink-0 flex-col gap-2 sm:w-80"><Select@@ -99,7 +106,7 @@ const FontChoiceFields = ({onValueChange={(value) => onChange({ choice: value as EditorBodyFontChoice, customFamily: preference.customFamily })}><SelectTrigger aria-label={label} className="h-9 bg-card">- <SelectValue>{includeCatalog && isRemoteNoteImageFont(preference.choice) ? <FontLabel label={t(FONT_CATALOG[preference.choice].labelKey)} fontId={preference.choice} enabled /> : undefined}</SelectValue>+ <SelectValue>{includeCatalog && isRemoteNoteImageFont(preference.choice) ? <FontLabel label={t(FONT_CATALOG[preference.choice].labelKey)} fontId={preference.choice} enabled onStatusChange={onPreviewStatus} status={selectedStatus} retryKey={fontRetry} /> : undefined}</SelectValue></SelectTrigger><SelectContent className="max-h-80"><SelectItem value="system">{t("settings.editorBodyFonts.system")}</SelectItem>@@ -144,13 +151,14 @@ const FontChoiceFields = ({</span></SelectItem>{(includeCatalog ? FONT_IDS : ["wenkai", "zhuque"] as const).map(id => (- <SelectItem key={id} value={id}>+ <SelectItem key={id} value={id} textValue={t(FONT_CATALOG[id].labelKey)}><FontLabel label={t(FONT_CATALOG[id].labelKey)} fontId={includeCatalog ? id : undefined} fontFamily={includeCatalog ? undefined : BUNDLED_FONT_STACKS[id as "wenkai" | "zhuque"]} enabled={fontOpen} visibleOnly /></SelectItem>))}<SelectItem value="custom">{t("settings.editorBodyFonts.custom")}</SelectItem></SelectContent></Select>+ {catalogSelected ? <FontLoadFeedback status={selectedStatus} onRetry={() => { setFontRetry(value => value + 1); retryEditorCatalogFont(); }} /> : null}{preference.choice === "custom" ? (<div className="flex flex-col gap-1.5"><Inputdiff --git a/apps/web/src/lib/editor-catalog-fonts.ts b/apps/web/src/lib/editor-catalog-fonts.tsindex aac5cb3a..4b733fd6 100644--- a/apps/web/src/lib/editor-catalog-fonts.ts+++ b/apps/web/src/lib/editor-catalog-fonts.ts@@ -1,12 +1,20 @@-import type { RemoteNoteImageFont } from "@edgeever/shared/font-catalog";+import { FONT_CATALOG, type RemoteNoteImageFont } from "@edgeever/shared/font-catalog";import { loadCatalogFont } from "@edgeever/shared/font-loader";+import { createFontLoadState } from "./font-load-state";++export const editorFontLoadState = createFontLoadState();+let retryCurrent: (() => void) | undefined;+export const retryEditorCatalogFont = () => retryCurrent?.();+let stop: (() => void) | undefined;/** Refresh character subsets when notes mount, navigation changes them, or text is edited. */export const watchEditorCatalogFont = (font: RemoteNoteImageFont | undefined) => {stop?.();stop = undefined;+ retryCurrent = undefined;+ editorFontLoadState.reset();if (!font || typeof MutationObserver === "undefined" || !document.body) return;let timer: ReturnType<typeof setTimeout> | undefined;let active = true;@@ -16,21 +24,23 @@ export const watchEditorCatalogFont = (font: RemoteNoteImageFont | undefined) =>.map(node => node instanceof HTMLTextAreaElement ? node.value : node.textContent ?? "").join(" ");// Character order and repeated paragraphs do not cause redundant loads.const characters = Array.from(new Set(Array.from(text))).sort().join("");- if (!characters || characters === last) return;+ if (characters === last && editorFontLoadState.getSnapshot() !== "idle") return;last = characters;- void loadCatalogFont(font, characters).catch(() => { if (active) last = ""; });+ void editorFontLoadState.run(() => loadCatalogFont(font, `${FONT_CATALOG[font].zh} ${FONT_CATALOG[font].en} ${characters}`)).catch(() => { /* Expose failure until an explicit retry, new text, or reconnect. */ });};+ retryCurrent = () => { if (active) { last = ""; editorFontLoadState.reset(); refresh(); } };const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 120); };const observer = new MutationObserver(schedule);observer.observe(document.body, { childList: true, subtree: true, characterData: true });document.addEventListener("input", schedule);- window.addEventListener("online", schedule);+ const reconnect = () => retryCurrent?.();+ window.addEventListener("online", reconnect);schedule();stop = () => {active = false;clearTimeout(timer);observer.disconnect();document.removeEventListener("input", schedule);- window.removeEventListener("online", schedule);+ window.removeEventListener("online", reconnect);};};diff --git a/apps/web/src/lib/font-load-state.test.mjs b/apps/web/src/lib/font-load-state.test.mjsnew file mode 100644index 00000000..f9333f0c--- /dev/null+++ b/apps/web/src/lib/font-load-state.test.mjs@@ -0,0 +1,53 @@+import { describe, expect, test } from "bun:test";+import { createFontLoadState, combineFontLoadStatus } from "./font-load-state.ts";+const deferred = () => { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; };++describe("font loading feedback", () => {+ test("reports loading, failure, and a successful explicit retry", async () => {+ const state = createFontLoadState();+ const events = [];+ const unsubscribe = state.subscribe(() => events.push(state.getSnapshot()));+ const first = deferred();+ const failed = state.run(() => first.promise);+ expect(state.getSnapshot()).toBe("loading");+ first.reject(new Error("offline"));+ await expect(failed).rejects.toThrow("offline");+ expect(state.getSnapshot()).toBe("error");+ await state.run(() => Promise.resolve("cached font"));+ expect(events).toEqual(["loading", "error", "loading", "ready"]);+ unsubscribe();+ state.reset();+ expect(events.length).toBe(4);+ });+ test("late completion from the previous font cannot hide a new failure", async () => {+ const state = createFontLoadState();+ const old = deferred();+ const oldRequest = state.run(() => old.promise);+ await expect(state.run(() => Promise.reject(new Error("new font offline")))).rejects.toThrow();+ old.resolve(); await oldRequest;+ expect(state.getSnapshot()).toBe("error");+ });+ test("late failure cannot overwrite a newer ready font", async () => {+ const state = createFontLoadState();+ const old = deferred();+ const oldRequest = state.run(() => old.promise);+ await state.run(() => Promise.resolve());+ old.reject(new Error("old request"));+ await expect(oldRequest).rejects.toThrow();+ expect(state.getSnapshot()).toBe("ready");+ });+ test("changing to system font invalidates pending remote status", async () => {+ const state = createFontLoadState();+ const old = deferred();+ const request = state.run(() => old.promise);+ state.reset(); old.resolve(); await request;+ expect(state.getSnapshot()).toBe("idle");+ });+ test("a ready name preview never implies the content is ready", () => {+ expect(combineFontLoadStatus("loading", "ready")).toBe("loading");+ expect(combineFontLoadStatus("error", "ready")).toBe("error");+ expect(combineFontLoadStatus("ready", "error")).toBe("error");+ expect(combineFontLoadStatus("ready", "loading")).toBe("loading");+ expect(combineFontLoadStatus("ready", "ready")).toBe("ready");+ });+});diff --git a/apps/web/src/lib/font-load-state.ts b/apps/web/src/lib/font-load-state.tsnew file mode 100644index 00000000..a67f5957--- /dev/null+++ b/apps/web/src/lib/font-load-state.ts@@ -0,0 +1,37 @@+export type FontLoadStatus = "idle" | "loading" | "ready" | "error";++/** A newer request owns the status; late completions cannot overwrite it. */+export const createFontLoadState = () => {+ let status: FontLoadStatus = "idle";+ let generation = 0;+ const listeners = new Set<() => void>();+ const publish = (next: FontLoadStatus) => {+ if (status === next) return;+ status = next;+ listeners.forEach(listener => listener());+ };+ return {+ getSnapshot: () => status,+ subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; },+ reset: () => { generation++; publish("idle"); },+ async run<T>(load: () => Promise<T>): Promise<T> {+ const request = ++generation;+ publish("loading");+ try {+ const result = await load();+ if (request === generation) publish("ready");+ return result;+ } catch (error) {+ if (request === generation) publish("error");+ throw error;+ }+ },+ };+};++/** Content and the name preview must both succeed before showing ready. */+export const combineFontLoadStatus = (content: FontLoadStatus, preview: FontLoadStatus): FontLoadStatus => {+ if (content === "error" || preview === "error") return "error";+ if (content === "idle" && preview === "idle") return "idle";+ return content === "ready" && preview === "ready" ? "ready" : "loading";+};diff --git a/apps/web/src/lib/note-image-export.ts b/apps/web/src/lib/note-image-export.tsindex 662737f9..fe75dded 100644--- a/apps/web/src/lib/note-image-export.ts+++ b/apps/web/src/lib/note-image-export.ts@@ -1,3 +1,4 @@+import type { FontLoadStatus } from "./font-load-state";import { prepareNoteImageAssets } from "@edgeever/shared/note-image-fonts";import { noteImageAssetUrls } from "@edgeever/shared/note-image-assets";import { toCanvas } from "html-to-image";@@ -68,6 +69,7 @@ export type DownloadNoteImageOptions = NoteHtmlExportMeta & {readingTimeText?: string;styles: string;signal?: AbortSignal;+ onFontLoadStatus?: (status: FontLoadStatus) => void;};export type PreparedNoteImage = {@@ -211,6 +213,7 @@ export const createNoteImage = async ({readingTimeText = "",styles,signal,+ onFontLoadStatus,}: DownloadNoteImageOptions): Promise<PreparedNoteImage> => {checkAborted(signal);const resolvedTheme = resolveTheme(background, theme);@@ -218,7 +221,10 @@ export const createNoteImage = async ({const themeCfg = NOTE_IMAGE_THEMES[resolvedTheme];const prepared = await prepareNoteBodyHtmlForExport(bodyHtml);- const assets = await prepareNoteImageAssets({ theme: resolvedTheme, fontStyle, text: [title, notebook, ...(tags || []), updatedAt, author, readingTimeText, prepared.bodyHtml].join(" "), urls: noteImageAssetUrls });+ onFontLoadStatus?.("loading");+ const assets = await prepareNoteImageAssets({ theme: resolvedTheme, fontStyle, text: [title, notebook, ...(tags || []), updatedAt, author, readingTimeText, prepared.bodyHtml].join(" "), urls: noteImageAssetUrls })+ .then(result => { onFontLoadStatus?.("ready"); return result; })+ .catch(error => { onFontLoadStatus?.("error"); throw error; });checkAborted(signal);const host = document.createElement("div");host.style.cssText = [diff --git a/apps/web/src/lib/use-font-preview-status.ts b/apps/web/src/lib/use-font-preview-status.tsnew file mode 100644index 00000000..3f238da7--- /dev/null+++ b/apps/web/src/lib/use-font-preview-status.ts@@ -0,0 +1,10 @@+import { useCallback, useState } from "react";+import { combineFontLoadStatus, type FontLoadStatus } from "./font-load-state";++export const useFontPreviewStatus = (key: string, contentStatus: FontLoadStatus) => {+ const [preview, setPreview] = useState<{ key: string; status: FontLoadStatus }>({ key: "", status: "idle" });+ const onPreviewStatus = useCallback((status: FontLoadStatus) => {+ setPreview(current => current.key === key && current.status === status ? current : { key, status });+ }, [key]);+ return { onPreviewStatus, status: combineFontLoadStatus(contentStatus, preview.key === key ? preview.status : "loading") };+};diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 983cd5f0..116fa058 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";// Shared by the PWA and native mobile clients.export const enUS = {+ fontLoad: {"loading": "Loading font…", "ready": "Font ready", "error": "Font could not load", "retry": "Retry"},noteProperties: {"heading": "Note properties", "source": "Show YAML source", "name": "Property name", "type": "Property type", "add": "Add property", "remove": "Remove {{name}}", "invalidName": "Use a unique name that is not a system property.", "invalidYaml": "Properties need attention:", "invalidNumber": "Enter a valid number.", "listHint": "One value per line", "text": "Text", "list": "List", "number": "Number", "checkbox": "Checkbox", "date": "Date"},poster: {design: {diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex f91881f8..e2e53995 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";// Shared by the PWA and native mobile clients.export const ja = {+ fontLoad: {"loading": "フォントを読み込み中…", "ready": "フォントの準備完了", "error": "フォントを読み込めませんでした", "retry": "再試行"},noteProperties: {"heading": "ノートのプロパティ", "source": "YAML ソースを表示", "name": "プロパティ名", "type": "プロパティの種類", "add": "プロパティを追加", "remove": "{{name}} を削除", "invalidName": "重複しない、システム予約名以外の名前を入力してください。", "invalidYaml": "プロパティを確認してください:", "invalidNumber": "有効な数値を入力してください。", "listHint": "1 行に 1 つの値", "text": "テキスト", "list": "リスト", "number": "数値", "checkbox": "チェックボックス", "date": "日付"},poster: {design: {diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex b28abfe3..9d8543b1 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";// Shared by the PWA and native mobile clients.export const pl = {+ fontLoad: {"loading": "Ładowanie czcionki…", "ready": "Czcionka gotowa", "error": "Nie udało się załadować czcionki", "retry": "Ponów próbę"},noteProperties: {"heading": "Właściwości notatki", "source": "Pokaż źródło YAML", "name": "Nazwa właściwości", "type": "Typ właściwości", "add": "Dodaj właściwość", "remove": "Usuń {{name}}", "invalidName": "Użyj unikalnej nazwy, która nie jest właściwością systemową.", "invalidYaml": "Sprawdź właściwości:", "invalidNumber": "Wprowadź poprawną liczbę.", "listHint": "Jedna wartość w wierszu", "text": "Tekst", "list": "Lista", "number": "Liczba", "checkbox": "Pole wyboru", "date": "Data"},poster: {design: {diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 30cd51ec..bafefa55 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2,6 +2,7 @@ import { memoTemplateSeedTranslations } from "../memo-template-seeds";// Shared by the PWA and native mobile clients.export const zhCN = {+ fontLoad: {"loading": "字体加载中…", "ready": "字体已就绪", "error": "字体加载失败", "retry": "重试"},noteProperties: {"heading": "笔记属性", "source": "显示 YAML 源码", "name": "属性名称", "type": "属性类型", "add": "添加属性", "remove": "删除 {{name}}", "invalidName": "请输入不重复且非系统保留的属性名称。", "invalidYaml": "请检查笔记属性:", "invalidNumber": "请输入有效数字。", "listHint": "每行一个值", "text": "文本", "list": "列表", "number": "数字", "checkbox": "复选框", "date": "日期"},poster: {design: {