refactor: 收敛渲染链路共享抽象
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export interface ThemeSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
description: string;
|
||||
bundled: boolean;
|
||||
source: "bundled" | "local";
|
||||
}
|
||||
|
||||
export function useThemeResources(
|
||||
themeId: string,
|
||||
onThemesLoaded: (themes: ThemeSummary[]) => void
|
||||
) {
|
||||
const [themes, setThemes] = useState<ThemeSummary[]>([]);
|
||||
const [themeCss, setThemeCss] = useState("");
|
||||
const [catalogError, setCatalogError] = useState("");
|
||||
const [cssError, setCssError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
void fetch("/api/themes", {
|
||||
signal: controller.signal
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error("无法加载主题清单");
|
||||
}
|
||||
return response.json() as Promise<{ themes: ThemeSummary[] }>;
|
||||
})
|
||||
.then(({ themes: availableThemes }) => {
|
||||
setThemes(availableThemes);
|
||||
setCatalogError("");
|
||||
onThemesLoaded(availableThemes);
|
||||
})
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogError(
|
||||
reason instanceof Error ? reason.message : "无法加载主题清单"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [onThemesLoaded]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setThemeCss("");
|
||||
setCssError("");
|
||||
|
||||
void fetch(`/api/themes/${encodeURIComponent(themeId)}/css`, {
|
||||
signal: controller.signal
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (!response.ok) {
|
||||
throw new Error("无法加载主题");
|
||||
}
|
||||
return response.text();
|
||||
})
|
||||
.then(setThemeCss)
|
||||
.catch((reason: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCssError(
|
||||
reason instanceof Error ? reason.message : "无法加载主题"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [themeId]);
|
||||
|
||||
return {
|
||||
error: catalogError || cssError,
|
||||
themeCss,
|
||||
themes
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user