File size: 7,915 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import { isCssProperty } from "@pandacss/is-valid-prop"
import {
  type Dict,
  compact,
  flatten,
  isObject,
  memo,
  mergeWith,
  splitProps,
} from "../utils"
import { createBreakpoints } from "./breakpoints"
import { createConditions } from "./conditions"
import { mergeConfigs } from "./config"
import { createCssFn } from "./css"
import { createRecipeFn } from "./cva"
import { createLayers } from "./layers"
import { createNormalizeFn } from "./normalize"
import { createPreflight } from "./preflight"
import { createSerializeFn } from "./serialize"
import { createSlotRecipeFn } from "./sva"
import { createTokenDictionary } from "./token-dictionary"
import type {
  SystemConfig,
  SystemContext,
  SystemQuery,
  Token,
  TokenCategory,
  TokenDictionary,
  TokenFn,
} from "./types"
import { createUtility } from "./utility"

const EMPTY_OBJECT = {}

export function createSystem(...configs: SystemConfig[]): SystemContext {
  const config = mergeConfigs(...configs)
  const {
    theme = {},
    utilities = {},
    globalCss = {},
    cssVarsRoot = ":where(:root, :host)",
    cssVarsPrefix = "chakra",
    preflight,
  } = config

  const layers = createLayers(config)

  const tokens = createTokenDictionary({
    breakpoints: theme.breakpoints,
    tokens: theme.tokens,
    semanticTokens: theme.semanticTokens,
    prefix: cssVarsPrefix,
  })

  const breakpoints = createBreakpoints(theme.breakpoints ?? EMPTY_OBJECT)

  const conditions = createConditions({
    conditions: config.conditions ?? EMPTY_OBJECT,
    breakpoints,
  })

  const utility = createUtility({
    config: utilities,
    tokens,
  })

  function assignComposition() {
    const { textStyles, layerStyles, animationStyles } = theme

    const compositions = compact({
      textStyle: textStyles,
      layerStyle: layerStyles,
      animationStyle: animationStyles,
    })

    for (const [key, values] of Object.entries(compositions)) {
      const flatValues = flatten(values ?? EMPTY_OBJECT, stop)

      utility.register(key, {
        values: Object.keys(flatValues),
        transform(value) {
          return css(flatValues[value])
        },
      })
    }
  }

  assignComposition()
  utility.addPropertyType(
    "animationName",
    Object.keys(theme.keyframes ?? EMPTY_OBJECT),
  )

  const properties = new Set(["css", ...utility.keys(), ...conditions.keys()])

  const isValidProperty = memo(
    (prop: string) => properties.has(prop) || isCssProperty(prop),
  )

  const normalizeValue = (value: any): any => {
    if (Array.isArray(value)) {
      return value.reduce((acc, current, index) => {
        const key = conditions.breakpoints[index]
        if (current != null) acc[key] = current
        return acc
      }, {})
    }
    return value
  }

  const normalizeFn = createNormalizeFn({
    utility,
    normalize: normalizeValue,
  })

  const serialize = createSerializeFn({
    conditions,
    isValidProperty,
  })

  const css = createCssFn({
    transform: utility.transform,
    conditions,
    normalize: normalizeFn,
  })

  const cva = createRecipeFn({
    css: css as any,
    conditions,
    normalize: normalizeFn,
    layers,
  })

  const sva = createSlotRecipeFn({ cva })

  function getTokenCss() {
    const result: Dict = {}

    for (const [key, values] of tokens.cssVarMap.entries()) {
      const varsObj = Object.fromEntries(values) as any
      if (Object.keys(varsObj).length === 0) continue
      const selector = key === "base" ? cssVarsRoot : conditions.resolve(key)
      const isAtRule = selector.startsWith("@")
      const cssObject = css(
        serialize({
          [selector]: isAtRule ? { [cssVarsRoot]: varsObj } : varsObj,
        }),
      )
      mergeWith(result, cssObject)
    }

    return layers.wrap("tokens", result)
  }

  function getGlobalCss() {
    const keyframes = Object.fromEntries(
      Object.entries(theme.keyframes ?? EMPTY_OBJECT).map(([key, value]) => [
        `@keyframes ${key}`,
        value,
      ]),
    )
    const result = Object.assign({}, keyframes, css(serialize(globalCss)))
    return layers.wrap("base", result)
  }

  function splitCssProps(props: any) {
    return splitProps(props, isValidProperty as any)
  }

  function getPreflightCss() {
    const result = createPreflight({ preflight })
    return layers.wrap("reset", result)
  }

  const tokenMap = getTokenMap(tokens)

  const tokenFn: TokenFn = (path: string, fallback?: any) => {
    return tokenMap.get(path)?.value || fallback
  }

  tokenFn.var = (path: string, fallback?: any) => {
    return tokenMap.get(path)?.variable || fallback
  }

  function getRecipe(key: string, fallback?: any) {
    return theme.recipes?.[key] ?? fallback
  }

  function getSlotRecipe(key: string, fallback?: any) {
    return theme.slotRecipes?.[key] ?? fallback
  }

  function isRecipe(key: string) {
    return Object.hasOwnProperty.call(theme.recipes ?? EMPTY_OBJECT, key)
  }

  function isSlotRecipe(key: string) {
    return Object.hasOwnProperty.call(theme.slotRecipes ?? EMPTY_OBJECT, key)
  }

  function hasRecipe(key: string) {
    return isRecipe(key) || isSlotRecipe(key)
  }

  const _global = [getPreflightCss(), getGlobalCss(), getTokenCss()]

  const query: SystemQuery = {
    layerStyles: compositionQuery(theme.layerStyles ?? EMPTY_OBJECT),
    textStyles: compositionQuery(theme.textStyles ?? EMPTY_OBJECT),
    animationStyles: compositionQuery(theme.animationStyles ?? EMPTY_OBJECT),
    tokens: semanticTokenQuery(
      tokens,
      Object.keys(theme.tokens ?? EMPTY_OBJECT),
      (value, key) =>
        !value.extensions.conditions && !key.includes("colorPalette"),
    ),
    semanticTokens: semanticTokenQuery(
      tokens,
      Object.keys(theme.semanticTokens ?? EMPTY_OBJECT),
      (value) => !!value.extensions.conditions,
    ),
    keyframes: basicQuery(theme.keyframes ?? EMPTY_OBJECT),
    breakpoints: basicQuery(theme.breakpoints ?? EMPTY_OBJECT),
  }

  return {
    $$chakra: true,
    _config: config,
    _global,
    breakpoints,
    tokens,
    conditions,
    utility,
    token: tokenFn,
    properties,
    layers,
    isValidProperty,
    splitCssProps: splitCssProps as any,
    normalizeValue,
    getTokenCss,
    getGlobalCss,
    getPreflightCss,
    css: css as any,
    cva,
    sva,
    getRecipe,
    getSlotRecipe,
    hasRecipe,
    isRecipe,
    isSlotRecipe,
    query,
  }
}

function getTokenMap(tokens: TokenDictionary) {
  const map = new Map<string, { value: string; variable: string }>()

  tokens.allTokens.forEach((token) => {
    const { cssVar, virtual, conditions } = token.extensions
    const value = !!conditions || virtual ? cssVar!.ref : token.value
    map.set(token.name, { value, variable: cssVar!.ref })
  })

  return map
}

export const isValidSystem = (mod: unknown): mod is SystemContext => {
  return isObject(mod) && !!Reflect.get(mod, "$$chakra")
}

const stop = (v: any) => isObject(v) && "value" in v

const compositionQuery = (dict: Record<string, any>) => ({
  list() {
    return Object.keys(flatten(dict, stop))
  },
  search(query: string) {
    return this.list().filter((style) => style.includes(query))
  },
})

const semanticTokenQuery = (
  tokens: TokenDictionary,
  categoryKeys: string[],
  predicate: (value: Token<any>, key: string) => boolean,
) => ({
  categoryKeys,
  list(category: TokenCategory) {
    return Array.from(tokens.categoryMap.get(category)?.entries() ?? []).reduce(
      (acc, [key, value]) => {
        if (predicate(value, key)) acc.push(key)
        return acc
      },
      [] as string[],
    )
  },
  search(category: TokenCategory, query: string) {
    return this.list(category).filter((style) => style.includes(query))
  },
})

const basicQuery = (dict: Record<string, any>) => ({
  list() {
    return Object.keys(dict)
  },
  search(query: string) {
    return this.list().filter((style) => style.includes(query))
  },
})