69 lines
2.5 KiB
TypeScript
69 lines
2.5 KiB
TypeScript
import { createContext, useCallback, useContext, useEffect, useState } from "react";
|
|
import type { PropsWithChildren } from "react";
|
|
import type { RuntimeWorkspace } from "@personal-brand/types";
|
|
import { projectBrandAliases } from "@personal-brand/types";
|
|
import { loadWorkspace } from "./api";
|
|
const Context = createContext<{
|
|
workspace?: RuntimeWorkspace;
|
|
error: string;
|
|
loading: boolean;
|
|
setBrandDraft: (brand: Partial<RuntimeWorkspace["brand"]>) => void;
|
|
setWorkspaceDraft: (workspace: RuntimeWorkspace) => void;
|
|
reload: () => void;
|
|
}>({ error: "", loading: true, setBrandDraft() {}, setWorkspaceDraft() {}, reload() {} });
|
|
export function WorkspaceProvider({ children }: PropsWithChildren) {
|
|
const [baseWorkspace, setBaseWorkspace] = useState<RuntimeWorkspace>();
|
|
const [brandDraft, setBrandDraft] = useState<Partial<RuntimeWorkspace["brand"]>>({});
|
|
const [workspaceDraft, setWorkspaceDraft] = useState<RuntimeWorkspace>();
|
|
const workspace = workspaceDraft ?? baseWorkspace;
|
|
const resolvedWorkspace = workspace
|
|
? {
|
|
...workspace,
|
|
brand: projectBrandAliases(
|
|
{ ...workspace.brand, ...brandDraft },
|
|
brandDraft.config && typeof brandDraft.config === "object"
|
|
? (brandDraft.config as Record<string, unknown>)
|
|
: ((workspace.brand.config as Record<string, unknown> | undefined) ?? {}),
|
|
),
|
|
}
|
|
: undefined;
|
|
const [error, setError] = useState("");
|
|
const [loading, setLoading] = useState(true);
|
|
const reload = useCallback(() => {
|
|
setLoading(true);
|
|
setError("");
|
|
const editorPreview =
|
|
process.env.TARO_ENV === "h5" &&
|
|
new URLSearchParams(window.location.search).get("editor") === "1";
|
|
const workspacePromise = editorPreview ? Promise.resolve(undefined) : loadWorkspace();
|
|
void workspacePromise
|
|
.then((value) => {
|
|
if (value) setBaseWorkspace(value);
|
|
})
|
|
.catch((error: unknown) =>
|
|
setError(error instanceof Error ? error.message : "加载失败,请重试"),
|
|
)
|
|
.finally(() => setLoading(!editorPreview));
|
|
}, []);
|
|
useEffect(reload, [reload]);
|
|
return (
|
|
<Context.Provider
|
|
value={{
|
|
workspace: resolvedWorkspace,
|
|
error,
|
|
loading:
|
|
process.env.TARO_ENV === "h5" &&
|
|
new URLSearchParams(window.location.search).get("editor") === "1"
|
|
? !workspace
|
|
: loading,
|
|
setBrandDraft,
|
|
setWorkspaceDraft,
|
|
reload,
|
|
}}
|
|
>
|
|
{children}
|
|
</Context.Provider>
|
|
);
|
|
}
|
|
export const useWorkspace = () => useContext(Context);
|