/
factory.ts
37 lines (33 loc) · 952 Bytes
/
factory.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
import { DOMElements } from "./system.utils"
import { ChakraStyledOptions, HTMLChakraComponents, styled } from "./system"
import { As, ChakraComponent } from "./system.types"
type ChakraFactory = {
<T extends As, P = {}>(
component: T,
options?: ChakraStyledOptions,
): ChakraComponent<T, P>
}
function factory() {
const cache = new Map<DOMElements, ChakraComponent<DOMElements>>()
return new Proxy(styled, {
/**
* @example
* const Div = chakra("div")
* const WithChakra = chakra(AnotherComponent)
*/
apply(target, thisArg, argArray: [DOMElements, ChakraStyledOptions]) {
return styled(...argArray)
},
/**
* @example
* <chakra.div />
*/
get(_, element: DOMElements) {
if (!cache.has(element)) {
cache.set(element, styled(element))
}
return cache.get(element)
},
}) as ChakraFactory & HTMLChakraComponents
}
export const chakra = factory()