From 889e7596560a78bbf882b00ee3351a2131db28f2 Mon Sep 17 00:00:00 2001 From: maofeng Date: Thu, 19 Jun 2025 22:39:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=BA=90=E4=B8=8A=E4=B8=8B?= =?UTF-8?q?=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/source.tsx | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/core/source.tsx diff --git a/src/core/source.tsx b/src/core/source.tsx new file mode 100644 index 0000000..d6933ed --- /dev/null +++ b/src/core/source.tsx @@ -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(undefined); + +/** + * 数据源描述提供器 + * + * 允许一些特殊的输入为它们的子源添加前缀或后缀。 + * + * @example + * + * ```jsx + * const sourceContext = { + * getSource: source => `coordinates.${source}`, + * getLabel: source => `resources.posts.fields.${source}`, + * } + * + * const CoordinatesInput = () => { + * return ( + * + * + * + * + * ); + * }; + * ``` + */ +export function SourceContextProvider({ children, value }: ProviderProps) { + return ( + + {children} + + ); +} + +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); +}