mirror of
https://gitcode.com/gh_mirrors/hy/Hydro.git
synced 2026-10-17 17:36:08 +08:00
ui-next: better page data context
This commit is contained in:
2 files changed
+27
-12
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { createContext, type ReactNode, useContext, useState } from 'react';
|
||||
import { createContext, type ReactNode, useContext, useMemo, useState } from 'react';
|
||||
|
||||
export interface PageData {
|
||||
HYDRO_INJECTED?: boolean;
|
||||
name: string;
|
||||
args: Record<string, any>;
|
||||
url: string;
|
||||
@@ -8,20 +9,24 @@ export interface PageData {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
type PageDataSetter = (data: PageData) => void;
|
||||
|
||||
interface PageDataContextValue {
|
||||
data: PageData;
|
||||
setData: (data: PageData) => void;
|
||||
setData: PageDataSetter;
|
||||
}
|
||||
|
||||
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);
|
||||
return (
|
||||
<PageDataContext.Provider value={{ data, setData }}>
|
||||
{children}
|
||||
</PageDataContext.Provider>
|
||||
);
|
||||
const value = useMemo(() => ({ data, setData }), [data]);
|
||||
|
||||
return <PageDataContext.Provider value={value}>{children}</PageDataContext.Provider>;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line react-refresh/only-export-components
|
||||
|
||||
@@ -11,9 +11,19 @@ for (const plugin of plugins) {
|
||||
}
|
||||
|
||||
const injectionEl = document.getElementById('__HYDRO_INJECTION__');
|
||||
const initialData: PageData = injectionEl
|
||||
? JSON.parse(injectionEl.textContent!)
|
||||
: { name: 'invalid_init', args: {}, url: window.location.pathname };
|
||||
let initialData: PageData = {
|
||||
name: '',
|
||||
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(
|
||||
<StrictMode>
|
||||
|
||||
Reference in new issue
Block a user