/
responsive.ts
66 lines (57 loc) · 1.56 KB
/
responsive.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { isObject } from "@chakra-ui/shared-utils"
export const breakpoints = Object.freeze([
"base",
"sm",
"md",
"lg",
"xl",
"2xl",
])
export function mapResponsive(prop: any, mapper: (val: any) => any) {
if (Array.isArray(prop)) {
return prop.map((item) => (item === null ? null : mapper(item)))
}
if (isObject(prop)) {
return Object.keys(prop).reduce((result: Record<string, any>, key) => {
result[key] = mapper(prop[key])
return result
}, {})
}
if (prop != null) {
return mapper(prop)
}
return null
}
export function objectToArrayNotation(
obj: Record<string, any>,
bps = breakpoints,
) {
const result = bps.map((br) => obj[br] ?? null)
const lastItem = result[result.length - 1]
while (lastItem === null) result.pop()
return result
}
export function arrayToObjectNotation(values: any[], bps = breakpoints) {
const result = {} as Record<string, any>
values.forEach((value, index) => {
const key = bps[index]
if (value == null) return
result[key] = value
})
return result
}
export function isResponsiveObjectLike(
obj: Record<string, any>,
bps = breakpoints,
) {
const keys = Object.keys(obj)
return keys.length > 0 && keys.every((key) => bps.includes(key))
}
/**
* since breakpoints are defined as custom properties on an array, you may
* `Object.keys(theme.breakpoints)` to retrieve both regular numeric indices
* and custom breakpoints as string.
*
* This function returns true given a custom array property.
*/
export const isCustomBreakpoint = (v: string) => Number.isNaN(Number(v))