aboutsummaryrefslogtreecommitdiff
path: root/src/services/theme_data/iss_deserializer.js
blob: 5d71f35fa60989e94fb41bc209fffbb039299969 (plain)
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
import { flattenDeep } from 'lodash'

const parseShadow = string => {
  const modes = ['_full', 'inset', 'x', 'y', 'blur', 'spread', 'color', 'alpha']
  const regexPrep = [
    // inset keyword (optional)
    '^(?:(inset)\\s+)?',
    // x
    '(?:(-?[0-9]+(?:\\.[0-9]+)?)\\s+)',
    // y
    '(?:(-?[0-9]+(?:\\.[0-9]+)?)\\s+)',
    // blur (optional)
    '(?:(-?[0-9]+(?:\\.[0-9]+)?)\\s+)?',
    // spread (optional)
    '(?:(-?[0-9]+(?:\\.[0-9]+)?)\\s+)?',
    // either hex, variable or function
    '(#[0-9a-f]{6}|--[a-z\\-_]+|\\$[a-z\\-()_]+)',
    // opacity (optional)
    '(?:\\s+\\/\\s+([0-9]+(?:\\.[0-9]+)?)\\s*)?$'
  ].join('')
  const regex = new RegExp(regexPrep, 'gis') // global, (stable) indices, single-string
  const result = regex.exec(string)
  if (result == null) {
    return string
  } else {
    const numeric = new Set(['x', 'y', 'blur', 'spread', 'alpha'])
    const { x, y, blur, spread, alpha, inset, color } = Object.fromEntries(modes.map((mode, i) => {
      if (numeric.has(mode)) {
        return [mode, Number(result[i])]
      } else if (mode === 'inset') {
        return [mode, !!result[i]]
      } else {
        return [mode, result[i]]
      }
    }).filter(([k, v]) => v !== false).slice(1))

    return { x, y, blur, spread, color, alpha, inset }
  }
}
// this works nearly the same as HTML tree converter
const parseIss = (input) => {
  const buffer = [{ selector: null, content: [] }]
  let textBuffer = ''

  const getCurrentBuffer = () => {
    let current = buffer[buffer.length - 1]
    if (current == null) {
      current = { selector: null, content: [] }
    }
    return current
  }

  // Processes current line buffer, adds it to output buffer and clears line buffer
  const flushText = (kind) => {
    if (textBuffer === '') return
    if (kind === 'content') {
      getCurrentBuffer().content.push(textBuffer.trim())
    } else {
      getCurrentBuffer().selector = textBuffer.trim()
    }
    textBuffer = ''
  }

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

    if (char === ';') {
      flushText('content')
    } else if (char === '{') {
      flushText('header')
    } else if (char === '}') {
      flushText('content')
      buffer.push({ selector: null, content: [] })
      textBuffer = ''
    } else {
      textBuffer += char
    }
  }

  return buffer
}
export const deserialize = (input) => {
  const ast = parseIss(input)
  const finalResult = ast.filter(i => i.selector != null).map(item => {
    const { selector, content } = item
    let stateCount = 0
    const selectors = selector.split(/,/g)
    const result = selectors.map(selector => {
      const output = { component: '' }
      let currentDepth = null

      selector.split(/ /g).reverse().forEach((fragment, index, arr) => {
        const fragmentObject = { component: '' }

        let mode = 'component'
        for (let i = 0; i < fragment.length; i++) {
          const char = fragment[i]
          switch (char) {
            case '.': {
              mode = 'variant'
              fragmentObject.variant = ''
              break
            }
            case ':': {
              mode = 'state'
              fragmentObject.state = fragmentObject.state || []
              stateCount++
              break
            }
            default: {
              if (mode === 'state') {
                const currentState = fragmentObject.state[stateCount - 1]
                if (currentState == null) {
                  fragmentObject.state.push('')
                }
                fragmentObject.state[stateCount - 1] += char
              } else {
                fragmentObject[mode] += char
              }
            }
          }
        }
        if (currentDepth !== null) {
          currentDepth.parent = { ...fragmentObject }
          currentDepth = currentDepth.parent
        } else {
          Object.keys(fragmentObject).forEach(key => {
            output[key] = fragmentObject[key]
          })
          if (index !== (arr.length - 1)) {
            output.parent = { component: '' }
          }
          currentDepth = output
        }
      })

      output.directives = Object.fromEntries(content.map(d => {
        const [property, value] = d.split(':')
        let realValue = value.trim()
        if (property === 'shadow') {
          realValue = value.split(',').map(v => parseShadow(v.trim()))
        } if (!Number.isNaN(Number(value))) {
          realValue = Number(value)
        }
        return [property, realValue]
      }))

      return output
    })
    return result
  })
  return flattenDeep(finalResult)
}