File size: 1,439 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
import { type Dict, isObject, walkObject } from "../utils"
import type { SystemContext } from "./types"

export function createSerializeFn(
  options: Pick<SystemContext, "conditions" | "isValidProperty">,
) {
  const { conditions, isValidProperty } = options

  return function serialize(styles: Dict) {
    return walkObject(styles, (value) => value, {
      getKey: (prop, value) => {
        if (!isObject(value)) return prop

        if (!conditions.has(prop) && !isValidProperty(prop)) {
          return parseSelectors(prop)
            .map((s) => "&" + s)
            .join(", ")
        }

        return prop
      },
    })
  }
}

function parseSelectors(selector: string): string[] {
  const result = [] as string[]
  let parenCount = 0
  let currentSelector = ""
  let inEscape = false

  for (let i = 0; i < selector.length; i++) {
    const char = selector[i]

    if (char === "\\" && !inEscape) {
      inEscape = true
      currentSelector += char
      continue
    }

    if (inEscape) {
      inEscape = false
      currentSelector += char
      continue
    }

    if (char === "(") {
      parenCount++
    } else if (char === ")") {
      parenCount--
    }

    if (char === "," && parenCount === 0) {
      result.push(currentSelector.trim())
      currentSelector = ""
    } else {
      currentSelector += char
    }
  }

  if (currentSelector) {
    result.push(currentSelector.trim())
  }

  return result
}