Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

fix(studio): preload fonts and clarify picker loading states

罗高09afd674d207
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index 277d7cfe..b3a955a1 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -231,7 +231,7 @@ flowchart LR
Local asset import through phase-one MCP and internal legacy tools allows at most 500 MB (500000000 bytes) per file, using a shared byte check before and after copying. The OpenMotion workspace host enforces the same decimal threshold before forwarding Studio uploads to the pinned engine, counting each complete multipart request including all files and form overhead; it rejects oversized requests before saving files, including streamed uploads without Content-Length. Existing project media and historical restoration are not re-imports.
-The font picker offers detected local fonts, imported project fonts and fonts declared by the current composition, retaining the selected family even when it is unavailable. It does not suggest remote catalogs or uninstalled presets. Installed-font discovery reads actual family/weight metadata from the engine's system font directories; selecting a family copies its nearest upright regular face into project assets. TTC faces are extracted with their original glyph and shaping tables. Imports use the same metadata and collection preparation, then require successful browser decoding before upload and application. Project listings retain font metadata across reopening, and composition fonts are discovered from the preview document rather than Studio chrome. Reads and preparation retain the shared 500 MB cap and no-follow file guard; original imported collections and authored declarations are not rewritten automatically.
+The font picker offers detected local fonts, imported project fonts and fonts declared by the current composition, retaining the selected family even when it is unavailable. It does not suggest remote catalogs or uninstalled presets. Studio preloads the installed-font list when the project connection is ready and shares it for the page session. The picker keeps a stable height, shows a localized loading status and placeholders while discovery is pending, and offers an explicit retry on failure without removing known project/current fonts. List preparation still waits for input to become idle. Installed-font discovery reads actual family/weight metadata from the engine's system font directories; selecting a family copies its nearest upright regular face into project assets. TTC faces are extracted with their original glyph and shaping tables. Imports use the same metadata and collection preparation, then require successful browser decoding before upload and application. Project listings retain font metadata across reopening, and composition fonts are discovered from the preview document rather than Studio chrome. Reads and preparation retain the shared 500 MB cap and no-follow file guard; original imported collections and authored declarations are not rewritten automatically.
| 数据范围 | 当前内容 | 可移交 / 恢复语义 |
| --- | --- | --- |
diff --git a/studio/src/App.tsx b/studio/src/App.tsx
index 36e875ab..a75c801d 100644
--- a/studio/src/App.tsx
+++ b/studio/src/App.tsx
@@ -1,6 +1,6 @@
import { useOwnPreviewIframe, usePreviewIframeStore } from "./player/store/previewIframeStore";
import { buildProjectApiPath } from "./utils/projectRouting";
-import { Fragment, useState, useCallback, useRef, useMemo, type SetStateAction } from "react";
+import { Fragment, useState, useCallback, useRef, useMemo, useEffect, type SetStateAction } from "react";
import { useStableHandlers } from "./hooks/useStableHandlers";
import { useHistoryFlags, useToolbarSession } from "./hooks/useShellSlices";
import { useDismissingTabSetter, useRightPanelIntent } from "./hooks/useRightPanelIntents";
@@ -63,6 +63,7 @@ import { readStudioUrlStateFromWindow, resolveMasterCompositionPath } from "./ut
import { useActiveComposition } from "./hooks/useActiveComposition";
import { requestPreviewReload } from "./player/previewReloading";
import { useStudioHost } from "./motion/StudioHost";
+import { preloadFontLists } from "./components/editor/propertyPanelFont";
const getTimelineSelectionSet = () => usePlayerStore.getState().selectedElementIds;
export interface StudioAppProps {
@@ -77,6 +78,9 @@ export function StudioApp({ readOnlyPreview = false, readOnlyPreviewReason }: St
const AppFrame = useStudioHost()?.AppFrame ?? Fragment;
const EditorFrame = useStudioHost()?.EditorFrame ?? Fragment;
const { projectId, resolving, waitingForServer } = useServerConnection();
+ useEffect(() => {
+ if (!resolving && !waitingForServer && projectId) preloadFontLists();
+ }, [projectId, resolving, waitingForServer]);
const initialUrlStateRef = useRef(readStudioUrlStateFromWindow());
useStudioSessionStart(projectId, resolving, waitingForServer);
const [compIdToSrc, setCompIdToSrc] = useState<Map<string, string>>(new Map());
diff --git a/studio/src/components/editor/propertyPanelFont.test.tsx b/studio/src/components/editor/propertyPanelFont.test.tsx
index da310104..bd3e371c 100644
--- a/studio/src/components/editor/propertyPanelFont.test.tsx
+++ b/studio/src/components/editor/propertyPanelFont.test.tsx
@@ -90,7 +90,7 @@ describe("FontFamilyField font list", () => {
describe("FontFamilyField session font lists", () => {
const fresh = async () => {
vi.resetModules();
- const { FontFamilyField } = await import("./propertyPanelFont");
+ const { FontFamilyField, preloadFontLists } = await import("./propertyPanelFont");
const { uniqueFontFamilies } = await import("./propertyPanelHelpers");
const loop = await import("./overlayFrameLoop");
vi.mocked(uniqueFontFamilies).mockClear();
@@ -106,9 +106,64 @@ describe("FontFamilyField session font lists", () => {
host.remove();
loop.resetOverlayFrameLoopForTests();
};
- return { uniqueFontFamilies, loop, host, render, toggle, done };
+ return { uniqueFontFamilies, loop, host, render, toggle, done, preloadFontLists };
};
+ it("preloads once before the field mounts and shows an explicit pending state until the shared list arrives", async () => {
+ let complete!: (response: Response) => void;
+ vi.mocked(fetch).mockReturnValue(new Promise<Response>(resolve => { complete = resolve; }));
+ const t = await fresh();
+ try {
+ t.preloadFontLists();
+ t.preloadFontLists();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ await act(async () => t.render("Georgia"));
+ await act(async () => t.toggle());
+ expect(document.querySelector('[aria-busy="true"]')).not.toBeNull();
+ expect(document.querySelector('[role="status"]')?.textContent).toContain("Loading fonts…");
+ expect(document.body.textContent).not.toContain("No fonts found.");
+ expect(document.querySelector('[role="status"] [aria-hidden="true"]')?.children).toHaveLength(5);
+ expect(document.querySelector('[role="combobox"]')).toBe(document.activeElement);
+
+ await act(async () => {
+ complete(new Response(JSON.stringify({ fonts: ["Arial", "Menlo"] })));
+ await new Promise(resolve => setTimeout(resolve, 10));
+ });
+ expect(document.querySelector('[aria-busy="true"]')).toBeNull();
+ expect(document.querySelector('[role="status"]')).toBeNull();
+ expect(document.body.textContent).toContain("Menlo");
+ await act(async () => t.toggle());
+ await act(async () => t.toggle());
+ expect(document.body.textContent).toContain("Menlo");
+ expect(document.querySelector('[role="status"]')).toBeNull();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ } finally { t.done(); }
+ });
+
+ it("reports HTTP failures and retries in place without hiding the current font", async () => {
+ vi.mocked(fetch).mockResolvedValue(new Response(JSON.stringify({ fonts: ["Wrong response"] }), { status: 503 }));
+ const t = await fresh();
+ try {
+ await act(async () => t.render("Georgia"));
+ await act(async () => t.toggle());
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain("Couldn't load local fonts.");
+ expect(document.body.textContent).not.toContain("No fonts found.");
+ expect(document.body.textContent).not.toContain("Wrong response");
+ expect(document.querySelector('[data-font-option-index="0"]')?.textContent).toContain("Georgia");
+ let complete!: (response: Response) => void;
+ vi.mocked(fetch).mockReturnValue(new Promise<Response>(resolve => { complete = resolve; }));
+ await act(async () => document.querySelector<HTMLButtonElement>('[role="alert"] button')?.click());
+ expect(document.querySelector('[role="alert"]')).toBeNull();
+ expect(document.querySelector('[role="status"]')?.textContent).toContain("Loading fonts…");
+ await act(async () => {
+ complete(new Response(JSON.stringify({ fonts: ["Menlo"] })));
+ await new Promise(resolve => setTimeout(resolve, 10));
+ });
+ expect(document.querySelector('[role="status"]')).toBeNull();
+ expect(document.body.textContent).toContain("Menlo");
+ } finally { t.done(); }
+ });
+
it("does no list work in a drag's frames when the lists land mid-drag", async () => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance", "Date"] });
const raf = window.requestAnimationFrame;
diff --git a/studio/src/components/editor/propertyPanelFont.tsx b/studio/src/components/editor/propertyPanelFont.tsx
index faa8cbee..a1f4dc53 100644
--- a/studio/src/components/editor/propertyPanelFont.tsx
+++ b/studio/src/components/editor/propertyPanelFont.tsx
@@ -91,40 +91,50 @@ async function loadImportedFontStylesheet(asset: ImportedFontAsset): Promise<voi
type FontLists = {
loaded: boolean;
+ error: boolean;
installed: string[];
};
let fontLists: FontLists = {
loaded: false,
+ error: false,
installed: [],
};
let fontListsRequest: Promise<void> | null = null;
const fontListListeners = new Set<() => void>();
async function fetchFontList(url: string): Promise<string[]> {
- const data = (await (await studioApiFetch(url)).json()) as { fonts?: unknown };
+ const response = await studioApiFetch(url);
+ if (!response.ok) throw new Error(`${url} returned ${response.status}`);
+ const data = (await response.json()) as { fonts?: unknown };
if (!Array.isArray(data.fonts)) throw new Error(`${url} returned no font list`);
return data.fonts as string[];
}
-function loadFontLists(): void {
- if (fontLists.loaded) return;
- fontListsRequest ??= fetchFontList("/api/fonts")
+export function preloadFontLists(): void {
+ if (fontLists.loaded || fontListsRequest) return;
+ if (fontLists.error) {
+ fontLists = { ...fontLists, error: false };
+ for (const listener of fontListListeners) listener();
+ }
+ fontListsRequest = fetchFontList("/api/fonts")
.then((installed) => {
runWhenInputIdle(() => {
- fontLists = { loaded: true, installed: uniqueFontFamilies(installed) };
+ fontLists = { loaded: true, error: false, installed: uniqueFontFamilies(installed) };
for (const listener of fontListListeners) listener();
return true;
});
})
.catch(() => {
fontListsRequest = null;
+ fontLists = { ...fontLists, error: true };
+ for (const listener of fontListListeners) listener();
});
}
function subscribeFontLists(listener: () => void): () => void {
fontListListeners.add(listener);
- loadFontLists();
+ preloadFontLists();
return () => fontListListeners.delete(listener);
}
@@ -166,7 +176,7 @@ export function FontFamilyField({
};
useEffect(() => {
- if (open) loadFontLists();
+ if (open) preloadFontLists();
}, [open]);
const handleImportFonts = async (files: FileList | File[] | null) => {
@@ -281,7 +291,7 @@ export function FontFamilyField({
};
const dropdown = open && (
- <div className="flex max-h-[min(360px,var(--available-height))] min-h-0 flex-col">
+ <div className="flex h-[320px] max-h-[min(360px,var(--available-height))] min-h-0 flex-col">
<div className="grid shrink-0 grid-cols-[minmax(0,1fr)_auto] gap-2 border-b border-neutral-800 p-2">
<SearchInput
ref={inputRef}
@@ -351,8 +361,8 @@ export function FontFamilyField({
{fontNotice}
</div>
)}
- <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-1">
- {filteredOptions.length === 0 ? (
+ <div aria-busy={!lists.loaded && !lists.error} className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-1">
+ {filteredOptions.length === 0 && lists.loaded ? (
<div className="px-2 py-3 text-[11px] text-neutral-500">{t("No fonts found.")}</div>
) : (
filteredOptions.map((option, index) => (
@@ -382,6 +392,22 @@ export function FontFamilyField({
</button>
))
)}
+ {!lists.loaded && !lists.error && (
+ <div role="status" className="px-2 py-2 text-[11px] text-neutral-500">
+ {t("Loading fonts…")}
+ <div aria-hidden="true" className="mt-2 space-y-4 motion-safe:animate-pulse">
+ {[0, 1, 2, 3, 4].map(row => <div key={row} className="h-3 w-3/5 rounded bg-neutral-800" />)}
+ </div>
+ </div>
+ )}
+ {lists.error && (
+ <div role="alert" className="px-2 py-3 text-[11px] text-neutral-500">
+ <p>{t("Couldn't load local fonts.")}</p>
+ <button type="button" onClick={preloadFontLists} className="mt-2 rounded px-2 py-1 text-neutral-300 hover:bg-neutral-900">
+ {t("Retry")}
+ </button>
+ </div>
+ )}
</div>
</div>
);
diff --git a/studio/src/i18n/de.json b/studio/src/i18n/de.json
index 8ce9940e..a4229fd5 100644
--- a/studio/src/i18n/de.json
+++ b/studio/src/i18n/de.json
@@ -1807,5 +1807,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Verlaufsdateien fehlen, sind nicht lesbar oder beschädigt: {files}. Diese Version wurde nicht wiederhergestellt. Das aktuelle Projekt bleibt unverändert.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Verlaufsdateien konnten nicht für die Wiederherstellung vorbereitet werden: {files}. Das aktuelle Projekt bleibt unverändert.",
"Failed to add media": "Medien konnten nicht hinzugefügt werden",
- "Could not read media duration. Try adding the file again.": "Die Mediendauer konnte nicht gelesen werden. Fügen Sie die Datei erneut hinzu."
+ "Could not read media duration. Try adding the file again.": "Die Mediendauer konnte nicht gelesen werden. Fügen Sie die Datei erneut hinzu.",
+ "Loading fonts…": "Schriftarten werden geladen…",
+ "Couldn't load local fonts.": "Lokale Schriftarten konnten nicht geladen werden."
}
diff --git a/studio/src/i18n/es.json b/studio/src/i18n/es.json
index 42085d72..66caf8d8 100644
--- a/studio/src/i18n/es.json
+++ b/studio/src/i18n/es.json
@@ -1807,5 +1807,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Faltan archivos del historial, no se pueden leer o están dañados: {files}. Esta versión no se ha restaurado. El proyecto actual no ha cambiado.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "No se pudieron preparar los archivos del historial para la restauración: {files}. El proyecto actual no ha cambiado.",
"Failed to add media": "No se pudo añadir el archivo multimedia",
- "Could not read media duration. Try adding the file again.": "No se pudo leer la duración del archivo multimedia. Intenta añadirlo de nuevo."
+ "Could not read media duration. Try adding the file again.": "No se pudo leer la duración del archivo multimedia. Intenta añadirlo de nuevo.",
+ "Loading fonts…": "Cargando fuentes…",
+ "Couldn't load local fonts.": "No se pudieron cargar las fuentes locales."
}
diff --git a/studio/src/i18n/fr.json b/studio/src/i18n/fr.json
index 62c7666b..eee48e60 100644
--- a/studio/src/i18n/fr.json
+++ b/studio/src/i18n/fr.json
@@ -1807,5 +1807,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Des fichiers de l’historique sont manquants, illisibles ou endommagés : {files}. Cette version n’a pas été restaurée. Le projet actuel reste inchangé.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossible de préparer les fichiers de l’historique pour la restauration : {files}. Le projet actuel reste inchangé.",
"Failed to add media": "Échec de l’ajout du média",
- "Could not read media duration. Try adding the file again.": "Impossible de lire la durée du média. Essayez d’ajouter à nouveau le fichier."
+ "Could not read media duration. Try adding the file again.": "Impossible de lire la durée du média. Essayez d’ajouter à nouveau le fichier.",
+ "Loading fonts…": "Chargement des polices…",
+ "Couldn't load local fonts.": "Impossible de charger les polices locales."
}
diff --git a/studio/src/i18n/it.json b/studio/src/i18n/it.json
index d65219ea..b094f2ae 100644
--- a/studio/src/i18n/it.json
+++ b/studio/src/i18n/it.json
@@ -1807,5 +1807,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Alcuni file della cronologia sono mancanti, illeggibili o danneggiati: {files}. Questa versione non è stata ripristinata. Il progetto attuale rimane invariato.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Impossibile preparare i file della cronologia per il ripristino: {files}. Il progetto attuale rimane invariato.",
"Failed to add media": "Impossibile aggiungere il file multimediale",
- "Could not read media duration. Try adding the file again.": "Impossibile leggere la durata del file multimediale. Prova ad aggiungere nuovamente il file."
+ "Could not read media duration. Try adding the file again.": "Impossibile leggere la durata del file multimediale. Prova ad aggiungere nuovamente il file.",
+ "Loading fonts…": "Caricamento dei caratteri…",
+ "Couldn't load local fonts.": "Impossibile caricare i caratteri locali."
}
diff --git a/studio/src/i18n/ja.json b/studio/src/i18n/ja.json
index e9bbd5d5..7fdf29ac 100644
--- a/studio/src/i18n/ja.json
+++ b/studio/src/i18n/ja.json
@@ -1771,5 +1771,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "履歴ファイルが見つからないか、読み取れないか、破損しています:{files}。このバージョンは復元されませんでした。現在のプロジェクトは変更されていません。",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "復元に必要な履歴ファイルを準備できませんでした:{files}。現在のプロジェクトは変更されていません。",
"Failed to add media": "メディアを追加できませんでした",
- "Could not read media duration. Try adding the file again.": "メディアの長さを読み取れませんでした。ファイルをもう一度追加してください。"
+ "Could not read media duration. Try adding the file again.": "メディアの長さを読み取れませんでした。ファイルをもう一度追加してください。",
+ "Loading fonts…": "フォントを読み込み中…",
+ "Couldn't load local fonts.": "ローカルフォントを読み込めませんでした。"
}
diff --git a/studio/src/i18n/ko.json b/studio/src/i18n/ko.json
index ccb94086..47dae029 100644
--- a/studio/src/i18n/ko.json
+++ b/studio/src/i18n/ko.json
@@ -1771,5 +1771,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "이전 버전의 파일이 없거나 읽을 수 없거나 손상되었습니다: {files}. 이 버전은 복원되지 않았습니다. 현재 프로젝트는 변경되지 않았습니다.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "복원에 필요한 이전 버전의 파일을 준비하지 못했습니다: {files}. 현재 프로젝트는 변경되지 않았습니다.",
"Failed to add media": "미디어를 추가하지 못했습니다",
- "Could not read media duration. Try adding the file again.": "미디어 길이를 읽을 수 없습니다. 파일을 다시 추가해 주세요."
+ "Could not read media duration. Try adding the file again.": "미디어 길이를 읽을 수 없습니다. 파일을 다시 추가해 주세요.",
+ "Loading fonts…": "글꼴 로딩 중…",
+ "Couldn't load local fonts.": "로컬 글꼴을 불러오지 못했습니다."
}
diff --git a/studio/src/i18n/pt-BR.json b/studio/src/i18n/pt-BR.json
index 47339fc1..377354b5 100644
--- a/studio/src/i18n/pt-BR.json
+++ b/studio/src/i18n/pt-BR.json
@@ -1807,5 +1807,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Arquivos do histórico estão ausentes, ilegíveis ou danificados: {files}. Esta versão não foi restaurada. O projeto atual permanece inalterado.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Não foi possível preparar os arquivos do histórico para restauração: {files}. O projeto atual permanece inalterado.",
"Failed to add media": "Não foi possível adicionar a mídia",
- "Could not read media duration. Try adding the file again.": "Não foi possível ler a duração da mídia. Tente adicionar o arquivo novamente."
+ "Could not read media duration. Try adding the file again.": "Não foi possível ler a duração da mídia. Tente adicionar o arquivo novamente.",
+ "Loading fonts…": "Carregando fontes…",
+ "Couldn't load local fonts.": "Não foi possível carregar as fontes locais."
}
diff --git a/studio/src/i18n/ru.json b/studio/src/i18n/ru.json
index b7c41572..a8046cad 100644
--- a/studio/src/i18n/ru.json
+++ b/studio/src/i18n/ru.json
@@ -1831,5 +1831,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Файлы истории отсутствуют, недоступны для чтения или повреждены: {files}. Эта версия не восстановлена. Текущий проект не изменён.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Не удалось подготовить файлы истории для восстановления: {files}. Текущий проект не изменён.",
"Failed to add media": "Не удалось добавить медиафайл",
- "Could not read media duration. Try adding the file again.": "Не удалось определить длительность медиафайла. Попробуйте добавить файл ещё раз."
+ "Could not read media duration. Try adding the file again.": "Не удалось определить длительность медиафайла. Попробуйте добавить файл ещё раз.",
+ "Loading fonts…": "Загрузка шрифтов…",
+ "Couldn't load local fonts.": "Не удалось загрузить локальные шрифты."
}
diff --git a/studio/src/i18n/tr.json b/studio/src/i18n/tr.json
index 45eae53a..9f7e92aa 100644
--- a/studio/src/i18n/tr.json
+++ b/studio/src/i18n/tr.json
@@ -1771,5 +1771,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "Geçmiş dosyaları eksik, okunamıyor veya hasarlı: {files}. Bu sürüm geri yüklenmedi. Mevcut proje değişmedi.",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "Geçmiş dosyaları geri yükleme için hazırlanamadı: {files}. Mevcut proje değişmedi.",
"Failed to add media": "Medya eklenemedi",
- "Could not read media duration. Try adding the file again.": "Medya süresi okunamadı. Dosyayı tekrar eklemeyi deneyin."
+ "Could not read media duration. Try adding the file again.": "Medya süresi okunamadı. Dosyayı tekrar eklemeyi deneyin.",
+ "Loading fonts…": "Yazı tipleri yükleniyor…",
+ "Couldn't load local fonts.": "Yerel yazı tipleri yüklenemedi."
}
diff --git a/studio/src/i18n/zh-CN.json b/studio/src/i18n/zh-CN.json
index 9af57ea7..3be71e6b 100644
--- a/studio/src/i18n/zh-CN.json
+++ b/studio/src/i18n/zh-CN.json
@@ -1771,5 +1771,7 @@
"Historical files are missing, unreadable or damaged: {files}. This version was not restored. Your current project is unchanged.": "历史文件缺失、无法读取或已损坏:{files}。未恢复此版本,当前工程保持不变。",
"Could not prepare historical files for restoration: {files}. Your current project is unchanged.": "无法准备恢复所需的历史文件:{files}。当前工程保持不变。",
"Failed to add media": "添加素材失败",
- "Could not read media duration. Try adding the file again.": "无法读取素材时长,请重新添加文件。"
+ "Could not read media duration. Try adding the file again.": "无法读取素材时长,请重新添加文件。",
+ "Loading fonts…": "正在加载字体…",
+ "Couldn't load local fonts.": "本地字体加载失败。"
}
diff --git a/studio/tests/e2e/local-fonts.mjs b/studio/tests/e2e/local-fonts.mjs
index 477dbc01..c011d7d5 100644
--- a/studio/tests/e2e/local-fonts.mjs
+++ b/studio/tests/e2e/local-fonts.mjs
@@ -71,6 +71,13 @@ try {
};
const remoteFontRequests = [];
page.on('request', request => { if (/fonts\.(googleapis|gstatic)\.com/.test(request.url())) remoteFontRequests.push(request.url()); });
+ await page.setRequestInterception(true);
+ let catalogRequests = 0;
+ const holdCatalog = request => {
+ if (new URL(request.url()).pathname === '/api/fonts') catalogRequests++;
+ else void request.continue();
+ };
+ page.on('request', holdCatalog);
const url = `${origin}/?project=${store.projectId}#project/${store.projectId}`;
const preview = () => page.evaluateHandle(() => document.querySelector('hyperframes-player').shadowRoot.querySelector('iframe').contentDocument);
const selectTitle = async () => {
@@ -116,8 +123,40 @@ try {
}, {}, { family, id: store.projectId });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
};
+ const firstCatalogRequest = page.waitForRequest(request => new URL(request.url()).pathname === '/api/fonts');
await page.goto(url, { waitUntil: 'domcontentloaded' });
+ const heldCatalog = await firstCatalogRequest;
+ assert.equal(await page.$('[data-flat-font-trigger]'), null, 'Catalog preloads before a text selection mounts the font field');
await selectTitle();
+ await page.click('[data-flat-font-trigger]');
+ await page.waitForSelector('[role="dialog"] [aria-busy="true"] [role="status"]');
+ await capture('font-list-loading.png');
+ const pickerHeight = await page.$eval('[role="dialog"]', element => element.getBoundingClientRect().height);
+ assert.ok(pickerHeight >= 300);
+ assert.equal(await page.$eval('input[role="combobox"]', element => element === document.activeElement), true);
+ await heldCatalog.respond({ status: 503, contentType: 'application/json', body: '{"error":"temporary test failure"}' });
+ await page.waitForSelector('[role="dialog"] [role="alert"] button');
+ await capture('font-list-error.png');
+ const retriedCatalogRequest = page.waitForRequest(request => new URL(request.url()).pathname === '/api/fonts');
+ await page.click('[role="dialog"] [role="alert"] button');
+ const retriedCatalog = await retriedCatalogRequest;
+ await page.waitForSelector('[role="dialog"] [aria-busy="true"] [role="status"]');
+ await retriedCatalog.continue();
+ await page.waitForSelector('[role="dialog"] [aria-busy="false"]');
+ await capture('font-list-ready.png');
+ const readyHeight = await page.$eval('[role="dialog"]', element => element.getBoundingClientRect().height);
+ assert.ok(Math.abs(readyHeight - pickerHeight) < 0.5, `Picker height changed: ${pickerHeight} → ${readyHeight}`);
+ assert.equal(catalogRequests, 2);
+ await page.keyboard.press('Escape');
+ await page.click('[data-flat-font-trigger]');
+ assert.equal(await page.$('[role="dialog"] [role="status"]'), null);
+ assert.equal(catalogRequests, 2, 'Reopening reuses the loaded catalog');
+ await page.keyboard.press('Escape');
+ results.catalogPreloadedBeforeSelection = true;
+ results.catalogLoadingRetryAndCache = true;
+ results.pickerHeight = pickerHeight;
+ page.off('request', holdCatalog);
+ await page.setRequestInterception(false);
for (const font of results.fonts) {
await choose(font.family); await applied(font.family);
await page.waitForFunction(family => document.querySelector('hyperframes-player').shadowRoot.querySelector('iframe').contentDocument.querySelector('#title').style.fontFamily.includes(family), {}, font.family);