-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstyled.tsx
74 lines (64 loc) · 2.09 KB
/
styled.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { forwardRef, type ExoticComponent } from "react";
import { VariantProps } from "tailwind-variants";
import { cn } from "./cn";
import { DataAttributes } from "./create-styled-context";
const mergeProps = <T extends Record<string, any>>(
baseProps: T,
propsToMerge: Partial<T>,
): T => ({
...baseProps,
...propsToMerge,
});
type GenericProps = Record<string, unknown>;
type StyleRecipe = {
(props?: GenericProps): string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
variantKeys: (string | number)[];
};
type Component<ComponentProps extends {}> =
| ExoticComponent<ComponentProps>
| ((prop: ComponentProps) => JSX.Element);
export const splitVariantProps = (
variantKeys: (string | number)[],
props: Record<string, any>,
) => {
const variantProps: any = {};
const otherProps: any = {};
for (const [key, value] of Object.entries(props)) {
if (variantKeys.includes(key)) {
variantProps[key] = value;
continue;
}
otherProps[key] = value;
}
return [variantProps, otherProps];
};
// TODO: improve typings
export const styled = <ComponentProps extends {}, R extends StyleRecipe>(
Component: Component<ComponentProps>,
recipe: R,
defaultProps?: Partial<ComponentProps & VariantProps<R> & DataAttributes>,
) => {
const Comp = forwardRef<
typeof Component,
ComponentProps & VariantProps<R> & DataAttributes & { unstyled?: boolean }
>((allProps, ref) => {
const { unstyled, ...props } = allProps as any;
const [variantProps, otherProps] = splitVariantProps(recipe.variantKeys, {
...defaultProps,
...props,
});
const classNames = recipe(variantProps);
const componentProps = mergeProps(otherProps, {
className: props.unstyled
? props.className
: cn(classNames, (props as any).className),
} as any);
return <Component {...componentProps} ref={ref} />;
});
// @ts-expect-error - it exists
Comp.displayName = Component.displayName || Component.name;
return Comp;
};