重新设计记录上下文

This commit is contained in:
maofeng 2025-06-19 22:40:14 +08:00
parent 889e759656
commit da8e866a2b

View File

@ -1,4 +1,5 @@
import { createContext, useContext, useMemo } from "react"; import { createContext, type ReactNode, useContext, useMemo } from "react";
import { type Validator } from "./types";
/** /**
* *
@ -12,19 +13,163 @@ export type RecordContextValue<T extends object = object> = {
/** /**
* Component hook : * Component hook :
* *
* - RecordProvider * - RecordContextProvider
* - useRecord * - useRecordContext
* - useNamedRecord *
* @internal
*/ */
const RecordContext = createContext<RecordContextValue | null>(null); const RecordContext = createContext<RecordContextValue | null>(null);
type RecordProviderProps<T extends object> = { /**
children: React.ReactNode; *
*
* @example
*
*
*
* ```jsx
* <RecordContextProvider name="..." value={{ name: 'John', age: 30 }}>
* {useRecordContext().name}
* </RecordContextProvider>
* ```
*
* @example
*
*
*
* ```jsx
* <RecordContextProvider name="..." value={{ name: 'John', age: 30 }}>
* <RecordContextProvider name="..." value={{ email: 'Jane@example.com', phone: '1234567890' }}>
* {useRecordContext((value) => 'email' in value).phone}
* </RecordContextProvider>
* </RecordContextProvider>
* ```
*
* @example
*
*
*
* ```jsx
* <RecordContextProvider name="user.2" value={{ id: 2, name: 'John', age: 30 }}>
* {useRecordContext('user.2').name}
* </RecordContextProvider>
* ```
*/
export function useRecordContext<T extends object = object>(): T | null;
export function useRecordContext<T extends object = object>(name: string): T | null;
export function useRecordContext<T extends object = object>(validator: Validator<object>): T | null;
export function useRecordContext<T extends object = object>(name: string, validator: Validator<object>): T | null;
export function useRecordContext<T extends object = object>(...args: unknown[]): T | null {
let name: string | undefined;
let validator: Validator<object> | undefined;
if (typeof args[0] === 'string') {
name = args[0];
if (typeof args[1] === 'function') {
validator = args[1] as Validator<object>;
}
} else if (typeof args[0] === 'function') {
validator = args[0] as Validator<object>;
}
let context = useContext(RecordContext);
if (!context) {
throw new Error("useRecordContext must be used within RecordContextProvider");
}
if (validator == null && name == null) {
return context.value as T;
}
return resolveRecord(context, c => {
return (name == null || c.name === name)
&& (validator == null || validator(c.value));
})
}
function resolveRecord<T extends object = object>(
context: RecordContextValue,
validate: (ctx: RecordContextValue) => boolean,
): T | null {
while (true) {
if (validate(context)) {
return context.value as T;
}
if (!context.parent) {
return null;
}
context = context.parent;
}
}
/**
*
*/
export interface RecordProviderProps<T extends object> {
/**
*
*
*
*/
children: ReactNode;
/**
*
*
* useRecordContext
*
* @example
*
* ```jsx
* function UserName({ id }: { id: number }) {
* const user = useRecordContext<User>(`user.${id}`);
* return <div>{user.name}</div>
* }
*
* <RecordContextProvider name="user.1" value={{ id: 1, name: "John" }}>
* <RecordContextProvider name="user.2" value={{ id: 2, name: "Jane" }}>
* <p>
* user name for id equal 2 is
* <UserName id={2} />
* </p>
* <p>
* user name for id equal 1 is
* <UserName id={1} />
* </p>
* </RecordContextProvider>
* </RecordContextProvider>
* ```
*/
name: string; name: string;
/**
*
*/
value: T; value: T;
}; };
export function RecordProvider<T extends object>({ /**
*
*
* @example
*
* ```jsx
* <RecordContextProvider name="user.1" value={{ id: 1, name: "John" }}>
* <RecordContextProvider name="user.2" value={{ id: 2, name: "Jane" }}>
* <p>
* user name for id equal 2 is
* <UserName id={2} />
* </p>
* <p>
* user name for id equal 1 is
* <UserName id={1} />
* </p>
* </RecordContextProvider>
* </RecordContextProvider>
* ```
*/
export function RecordContextProvider<T extends object>({
children, children,
...context ...context
}: RecordProviderProps<T>) { }: RecordProviderProps<T>) {
@ -36,48 +181,109 @@ export function RecordProvider<T extends object>({
Object.values(context), Object.values(context),
) as RecordContextValue; ) as RecordContextValue;
return <RecordContext value={value}>{children}</RecordContext>; return (
<RecordContext value={value}>
{children}
</RecordContext>
);
} }
export function useRecord<T extends object = object>( /**
validate?: (value: unknown) => boolean, *
): T | null { *
let context = useContext(RecordContext); * RecordContextProvider
if (!context) { *
throw new Error("useRecord must be used within RecordProvider"); *
} * @example
if (validate == null) { *
return context.value as T; * ```jsx
} * const RecordTitle = ({ record }) => (
while (true) { * <OptionalRecordProvider name="post.1" value={record}>
if (validate(context.value)) { * <TextField source="title" />
return context.value as T; * </OptionalRecordProvider>
} * );
if (!context.parent) { * ```
return null; */
} export function OptionalRecordProvider<T extends object>({
context = context.parent; children,
} name,
value,
}: Omit<RecordProviderProps<T>, 'value'> & {
value?: T | null | undefined;
}) {
if (value != null) {
return (
<RecordContextProvider
name={name}
value={value}
>
{children}
</RecordContextProvider>
);
} }
export function useNamedRecord<T extends object = object>( return children;
name: string,
validate?: (value: unknown) => boolean,
): T | null {
let context = useContext(RecordContext);
if (!context) {
throw new Error("useNamedRecord must be used within RecordProvider");
} }
while (true) {
if (context!.name === name) { export interface WithRecordProps<T extends object = object> {
if (validate && !validate(context.value)) { /**
throw new Error("Invalid record value"); *
*
* @type {string}
*/
name?: string;
/**
*
*
* @param {T} record
* @returns {ReactNode}
*/
render: (record: T) => ReactNode;
/**
*
*
* @param {boolean} hasContext
* @returns {ReactNode}
*/
fallback?: ReactNode | ((hasContext: boolean) => ReactNode);
} }
return context!.value as T;
/**
*
*
* 使 useRecordContext
*
*
* @example
*
* ```jsx
* const BookShow = () => (
* <Show>
* <SimpleShowLayout>
* <WithRecord render={record => <span>{record.title}</span>} />
* </SimpleShowLayout>
* </Show>
* );
* ```
*/
export function WithRecord<T extends object = object>({
name,
render,
fallback,
}: WithRecordProps<T>) {
const context = useContext(RecordContext);
const record = context != null
? resolveRecord<T>(context, c => name == null || c.name == name)
: null;
if (record == null) {
if (typeof fallback === 'function') {
return fallback(context != null);
} }
if (!context.parent) { return fallback ?? null;
return null;
}
context = context!.parent;
} }
return <>{render(record)}</>
} }