File size: 2,342 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
import {
  type Dict,
  compact,
  isObject,
  isString,
  memo,
  mergeWith,
  walkObject,
} from "../utils"
import type { SystemStyleObject } from "./css.types"
import { sortAtRules } from "./sort-at-rules"
import type { SystemContext } from "./types"

const importantRegex = /\s*!(important)?/i

const isImportant = (v: unknown) =>
  isString(v) ? importantRegex.test(v) : false

const withoutImportant = (v: unknown) =>
  isString(v) ? v.replace(importantRegex, "").trim() : v

type CssFnOptions = Pick<SystemContext, "conditions"> & {
  normalize: (styles: Dict) => Dict
  transform: (prop: string, value: any) => Dict | undefined
}

export function createCssFn(context: CssFnOptions) {
  const { transform, conditions, normalize } = context
  const mergeFn = mergeCss(context)

  return memo(function cssFn(...styleArgs: SystemStyleObject[]) {
    const styles = mergeFn(...styleArgs)

    const normalized = normalize(styles)
    const result: Dict = Object.create(null)

    walkObject(normalized, (value, paths) => {
      const important = isImportant(value)
      if (value == null) return

      const [prop, ...selectors] = conditions
        .sort(paths)
        .map(conditions.resolve)

      if (important) {
        value = withoutImportant(value)
      }

      let transformed = transform(prop, value) ?? Object.create(null)

      transformed = walkObject(
        transformed,
        (v) => (isString(v) && important ? `${v} !important` : v),
        { getKey: (prop) => conditions.expandAtRule(prop) },
      )

      mergeByPath(result, selectors.flat(), transformed)
    })

    return sortAtRules(result)
  })
}

function mergeByPath(target: Dict, paths: string[], value: Dict) {
  let acc = target
  for (const path of paths) {
    if (!path) continue
    if (!acc[path]) acc[path] = Object.create(null)
    acc = acc[path]
  }
  mergeWith(acc, value)
}

function compactFn(...styles: Dict[]) {
  return styles.filter(
    (style) => isObject(style) && Object.keys(compact(style)).length > 0,
  )
}

function mergeCss(ctx: CssFnOptions) {
  function resolve(styles: Dict[]) {
    const comp = compactFn(...styles)
    if (comp.length === 1) return comp
    return comp.map((style) => ctx.normalize(style))
  }
  return memo(function mergeFn(...styles: Dict[]) {
    return mergeWith({}, ...resolve(styles))
  })
}