File size: 6,339 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"use client"

import { forwardRef, useMemo } from "react"
import { createContext } from "../create-context"
import { mergeProps } from "../merge-props"
import { cx } from "../utils"
import type { SystemStyleObject } from "./css.types"
import { EMPTY_SLOT_STYLES } from "./empty"
import { chakra } from "./factory"
import type { JsxFactoryOptions } from "./factory.types"
import type { ConfigRecipeSlots } from "./generated/recipes.gen"
import type { SystemSlotRecipeFn } from "./recipe.types"
import {
  type SlotRecipeKey,
  type UseSlotRecipeOptions,
  useSlotRecipe,
} from "./use-slot-recipe"

interface WrapElementProps<P> {
  wrapElement?(element: React.ReactElement, props: P): React.ReactElement
}

export interface WithRootProviderOptions<P> extends WrapElementProps<P> {
  defaultProps?: Partial<P> | undefined
}

export interface WithProviderOptions<P>
  extends JsxFactoryOptions<P>,
    WrapElementProps<P> {}

export interface WithContextOptions<P> extends JsxFactoryOptions<P> {}

const upperFirst = (str: string) => str.charAt(0).toUpperCase() + str.slice(1)

export const createSlotRecipeContext = <R extends SlotRecipeKey>(
  options: UseSlotRecipeOptions<R>,
) => {
  const { key: recipeKey, recipe: recipeConfig } = options

  const contextName = upperFirst(
    recipeKey || (recipeConfig as any).className || "Component",
  )

  const [StylesProvider, useStyles] = createContext<
    Record<string, SystemStyleObject>
  >({
    name: `${contextName}StylesContext`,
    errorMessage: `use${contextName}Styles returned is 'undefined'. Seems you forgot to wrap the components in "<${contextName}.Root />" `,
  })

  const [ClassNamesProvider, useClassNames] = createContext<
    Record<string, string>
  >({
    name: `${contextName}ClassNameContext`,
    errorMessage: `use${contextName}ClassNames returned is 'undefined'. Seems you forgot to wrap the components in "<${contextName}.Root />" `,
    strict: false,
  })

  const [PropsProvider, usePropsContext] = createContext<Record<string, any>>({
    strict: false,
    name: `${contextName}PropsContext`,
    providerName: `${contextName}PropsContext`,
    defaultValue: {},
  })

  function useRecipeResult(props: any) {
    const { unstyled, ...restProps } = props

    const slotRecipe = useSlotRecipe({
      key: recipeKey,
      recipe: restProps.recipe || recipeConfig,
    }) as SystemSlotRecipeFn<string, {}, {}>

    // @ts-ignore
    const [variantProps, otherProps] = useMemo(
      () => slotRecipe.splitVariantProps(restProps),
      [restProps, slotRecipe],
    )
    const styles = useMemo(
      () => (unstyled ? EMPTY_SLOT_STYLES : slotRecipe(variantProps)),
      [unstyled, variantProps, slotRecipe],
    )

    return {
      styles: styles as Record<string, SystemStyleObject>,
      classNames: slotRecipe.classNameMap as Record<string, string>,
      props: otherProps,
    }
  }

  function withRootProvider<P>(
    Component: React.ElementType<any>,
    options: WithRootProviderOptions<P> = {},
  ): React.FC<React.PropsWithoutRef<P>> {
    const { defaultProps } = options

    const StyledComponent = (inProps: any) => {
      const propsContext = usePropsContext()
      const props = useMemo(
        () => mergeProps(defaultProps, propsContext, inProps),
        [propsContext, inProps],
      )
      const { styles, classNames, props: rootProps } = useRecipeResult(props)

      return (
        <StylesProvider value={styles}>
          <ClassNamesProvider value={classNames}>
            <Component {...rootProps} />
          </ClassNamesProvider>
        </StylesProvider>
      )
    }

    // @ts-expect-error
    StyledComponent.displayName = Component.displayName || Component.name
    return StyledComponent as any
  }

  const withProvider = <T, P>(
    Component: React.ElementType<any>,
    slot: R extends keyof ConfigRecipeSlots ? ConfigRecipeSlots[R] : string,
    options?: WithProviderOptions<P>,
  ): React.ForwardRefExoticComponent<
    React.PropsWithoutRef<P> & React.RefAttributes<T>
  > => {
    const { defaultProps, ...restOptions } = options ?? {}
    const SuperComponent = chakra(Component, {}, restOptions as any)

    const StyledComponent = forwardRef<any, any>((inProps, ref) => {
      const propsContext = usePropsContext()
      const props = useMemo(
        () => mergeProps(defaultProps ?? {}, propsContext, inProps),
        [propsContext, inProps],
      )
      const { styles, props: rootProps, classNames } = useRecipeResult(props)
      const className = classNames[slot as keyof typeof classNames]

      const element = (
        <StylesProvider value={styles}>
          <ClassNamesProvider value={classNames}>
            <SuperComponent
              ref={ref}
              {...rootProps}
              css={[styles[slot], props.css]}
              className={cx(props.className, className)}
            />
          </ClassNamesProvider>
        </StylesProvider>
      )

      return options?.wrapElement?.(element, props) ?? element
    })

    // @ts-expect-error
    StyledComponent.displayName = Component.displayName || Component.name

    return StyledComponent as any
  }

  const withContext = <T, P>(
    Component: React.ElementType<any>,
    slot?: R extends keyof ConfigRecipeSlots ? ConfigRecipeSlots[R] : string,
    options?: WithContextOptions<P>,
  ): React.ForwardRefExoticComponent<
    React.PropsWithoutRef<P> & React.RefAttributes<T>
  > => {
    const SuperComponent = chakra(Component, {}, options as any)
    const StyledComponent = forwardRef<any, any>((props, ref) => {
      const { unstyled, ...restProps } = props
      const styles = useStyles()
      const classNames = useClassNames()
      const className = classNames?.[slot as keyof typeof classNames]

      return (
        <SuperComponent
          {...restProps}
          css={[!unstyled && slot ? styles[slot] : undefined, props.css]}
          ref={ref}
          className={cx(props.className, className)}
        />
      )
    })

    // @ts-expect-error
    StyledComponent.displayName = Component.displayName || Component.name
    return StyledComponent as any
  }

  return {
    StylesProvider,
    ClassNamesProvider,
    PropsProvider,
    usePropsContext,
    useRecipeResult,
    withProvider,
    withContext,
    withRootProvider,
    useStyles,
    useClassNames,
  }
}