forked from stereobooster/unstyled-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
37 lines (34 loc) · 1.14 KB
/
index.js
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
import { h } from "preact";
import { createContext, useContext, memo, forwardRef } from "preact/compat";
const ThemeContext = createContext({});
export const ThemeProvider = ({ children, theme }) =>
h(ThemeContext.Provider, { value: theme }, children);
const filterObject = (rest, shouldForwardProp) =>
Object.keys(rest)
.filter(shouldForwardProp)
.reduce((obj, key) => {
obj[key] = rest[key];
return obj;
}, {});
export const styled = (defaultAs, options) => (styleCalback) => {
const { shouldForwardProp, label } = options || {};
function forwaded(element, ref) {
const { children, as = defaultAs, style = {}, ...props } = element || {};
const theme = useContext(ThemeContext);
return h(
as,
{
ref,
style: {
...styleCalback({ ...props, theme }),
...(typeof style === "function" ? style({ ...props, theme }) : style),
},
...(shouldForwardProp ? filterObject(props, shouldForwardProp) : props),
},
children
);
}
const component = memo(forwardRef(forwaded));
component.displayName = `${label || defaultAs}💅`;
return component;
};