数据源上下文

This commit is contained in:
maofeng 2025-06-19 22:39:47 +08:00
parent 43b445c10b
commit 889e759656

64
src/core/source.tsx Normal file
View File

@ -0,0 +1,64 @@
import { createContext, ProviderProps, useContext } from 'react';
/**
*
*/
export type SourceContextValue = {
/*
*
*/
getSource: (source: string) => string;
/*
*
* i18n/i10n
*/
getLabel: (source: string) => string;
};
const SourceContext = createContext<SourceContextValue | undefined>(undefined);
/**
*
*
*
*
* @example
*
* ```jsx
* const sourceContext = {
* getSource: source => `coordinates.${source}`,
* getLabel: source => `resources.posts.fields.${source}`,
* }
*
* const CoordinatesInput = () => {
* return (
* <SourceContextProvider value={sourceContext}>
* <TextInput source="lat" />
* <TextInput source="lng" />
* </SourceContextProvider>
* );
* };
* ```
*/
export function SourceContextProvider({ children, value }: ProviderProps<SourceContextValue>) {
return (
<SourceContext value={value}>
{children}
</SourceContext>
);
}
const defaultContextValue: SourceContextValue = {
getSource: (source: string) => source,
getLabel: (source: string) => source,
};
export function useSourceContext(): SourceContextValue {
const context = useContext(SourceContext);
return context ?? defaultContextValue;
}
export function useOptionalSourceContext(): SourceContextValue | undefined {
return useContext(SourceContext);
}