-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseStyles.ts
42 lines (33 loc) · 1.29 KB
/
useStyles.ts
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
import deepmerge from 'deepmerge';
import isNil from 'lodash.isnil';
import { ComponentStyles, Theme } from '../themes';
import { MaybeThunk, resolveThunk } from '../utils';
import { useBlueBase } from './useBlueBase';
import { useTheme } from './useTheme';
export function useStyles<T = ComponentStyles>(
componentName: string,
props: { styles?: Partial<T> } & any = {},
defaultStyles?: T | ((theme: Theme, props: any) => T)
): T {
const BB = useBlueBase();
const { theme } = useTheme();
const { styles: stylesProp, ...rest } = props;
// Find styles in the component registry
const stylesParam = BB.Components.getStyles(componentName);
// Extract component style rules from theme
let themedStyles: MaybeThunk<ComponentStyles>;
if (componentName) {
const themeComponentStyles = theme.components;
// Extract style rules for this component
themedStyles = themeComponentStyles[componentName];
}
// Put all style rules in an array
const stylesArr = [defaultStyles!, stylesParam!, themedStyles!, stylesProp!]
// Remove those styles which are nil
.filter((a: any) => !isNil(a))
// If any item is a thunk, resolve it
.map((a: any) => a && resolveThunk(a, theme, rest)) as ComponentStyles[];
// Merge all into a single object
const styles = deepmerge.all(stylesArr) as any;
return styles;
}