|
| 1 | +import { clsx } from "clsx"; |
| 2 | +import { createContext, useContext, useMemo } from "react"; |
| 3 | + |
| 4 | +export type ClassNameInjector<Props, Keys extends keyof Props> = ( |
| 5 | + props: Pick<Props, Keys>, |
| 6 | +) => string | undefined; |
| 7 | + |
| 8 | +interface ClassNameInjectorEntry<Props> { |
| 9 | + fn: (props: Props) => string | undefined; |
| 10 | + keys: (keyof Props)[]; |
| 11 | +} |
| 12 | + |
| 13 | +export type ClassNameInjectionRegistry = Record< |
| 14 | + string, |
| 15 | + // biome-ignore lint/suspicious/noExplicitAny: refer to ClassNameInjector which derives it's entry type based on the Props |
| 16 | + ClassNameInjectorEntry<any>[] |
| 17 | +>; |
| 18 | + |
| 19 | +const InjectionContext = createContext<ClassNameInjectionRegistry | null>(null); |
| 20 | + |
| 21 | +export type ClassNameInjectionProviderProps = { |
| 22 | + children: React.ReactNode; |
| 23 | + value?: ClassNameInjectionRegistry; |
| 24 | +}; |
| 25 | + |
| 26 | +export function ClassNameInjectionProvider({ |
| 27 | + children, |
| 28 | + value, |
| 29 | +}: ClassNameInjectionProviderProps) { |
| 30 | + const registry = useMemo(() => value ?? {}, [value]); |
| 31 | + return ( |
| 32 | + <InjectionContext.Provider value={registry}> |
| 33 | + {children} |
| 34 | + </InjectionContext.Provider> |
| 35 | + ); |
| 36 | +} |
| 37 | + |
| 38 | +export function useInjectedClassName< |
| 39 | + // biome-ignore lint/suspicious/noExplicitAny: props are passed through to the callback as-is |
| 40 | + Props extends Record<string, any>, |
| 41 | +>(component: string, props: Props): { className: string; props: Props } { |
| 42 | + const registry = useContext(InjectionContext); |
| 43 | + if (!registry) { |
| 44 | + return { className: props?.className || "", props }; |
| 45 | + } |
| 46 | + const entries = registry[component] ?? []; |
| 47 | + const injected = entries.map((e) => e.fn(props)).filter(Boolean); |
| 48 | + const className = clsx(props?.className, injected); |
| 49 | + |
| 50 | + const cleanProps: Props = { ...props }; |
| 51 | + |
| 52 | + for (const entry of entries) { |
| 53 | + for (const key of entry.keys) { |
| 54 | + delete cleanProps[key as string]; |
| 55 | + } |
| 56 | + } |
| 57 | + return { className, props: cleanProps }; |
| 58 | +} |
| 59 | + |
| 60 | +export function registerClassInjector<Props, Keys extends keyof Props>( |
| 61 | + registry: ClassNameInjectionRegistry, |
| 62 | + component: string, |
| 63 | + keys: Keys[], |
| 64 | + injector: ClassNameInjector<Props, Keys>, |
| 65 | +) { |
| 66 | + registry[component] ??= []; |
| 67 | + const wrapped = (props: Props) => injector(props as Props); |
| 68 | + registry[component] = [...registry[component], { fn: wrapped, keys }]; |
| 69 | +} |
0 commit comments