ui-next: better page data context

This commit is contained in:
Baoshuo committed 2026-05-10 01:12:46 +08:00
1 parent 0d16157deb
commit 2bc1f5842e
2 files changed
+27 -12

No files matched your search

+14 -9
View File
@@ -1,6 +1,7 @@
import { createContext, type ReactNode, useContext, useState } from 'react'; import { createContext, type ReactNode, useContext, useMemo, useState } from 'react';
export interface PageData { export interface PageData {
HYDRO_INJECTED?: boolean;
name: string; name: string;
args: Record<string, any>; args: Record<string, any>;
url: string; url: string;
@@ -8,20 +9,24 @@ export interface PageData {
[key: string]: any; [key: string]: any;
} }
type PageDataSetter = (data: PageData) => void;
interface PageDataContextValue { interface PageDataContextValue {
data: PageData; data: PageData;
setData: (data: PageData) => void; setData: PageDataSetter;
} }
const PageDataContext = createContext<PageDataContextValue | null>(null); const PageDataContext = createContext<PageDataContextValue | null>(null);
export function PageDataProvider({ initial, children }: { initial: PageData, children: ReactNode }) { interface PageDataProviderProps {
initial: PageData;
children: ReactNode;
}
export function PageDataProvider({ initial, children }: PageDataProviderProps) {
const [data, setData] = useState<PageData>(initial); const [data, setData] = useState<PageData>(initial);
return ( const value = useMemo(() => ({ data, setData }), [data]);
<PageDataContext.Provider value={{ data, setData }}>
{children} return <PageDataContext.Provider value={value}>{children}</PageDataContext.Provider>;
</PageDataContext.Provider>
);
} }
// eslint-disable-next-line react-refresh/only-export-components // eslint-disable-next-line react-refresh/only-export-components
+13 -3
View File
@@ -11,9 +11,19 @@ for (const plugin of plugins) {
} }
const injectionEl = document.getElementById('__HYDRO_INJECTION__'); const injectionEl = document.getElementById('__HYDRO_INJECTION__');
const initialData: PageData = injectionEl let initialData: PageData = {
? JSON.parse(injectionEl.textContent!) name: '',
: { name: 'invalid_init', args: {}, url: window.location.pathname }; args: {},
url: window.location.pathname,
routeMap: {},
};
if (injectionEl) {
try {
initialData = JSON.parse(injectionEl.textContent!);
} catch (e) {
console.error('[Hydro] Failed to parse injection data:', e);
}
}
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>