aboutsummaryrefslogtreecommitdiff
path: root/src/services/theme_data/theme_data_3.service.js
blob: 88bff2aa51b61b35cf6c6a1036c2b13245523126 (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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
import { convert, brightness } from 'chromatism'
import {
  alphaBlend,
  getTextColor,
  rgba2css,
  mixrgb,
  relativeLuminance
} from '../color_convert/color_convert.js'

import {
  colorFunctions,
  shadowFunctions,
  process
} from './theme3_slot_functions.js'

import {
  getCssShadow,
  getCssShadowFilter,
  getCssColorString
} from './css_utils.js'

const DEBUG = false

// Ensuring the order of components
const components = {
  Root: null,
  Text: null,
  FunText: null,
  Link: null,
  Icon: null,
  Border: null,
  Panel: null,
  Chat: null,
  ChatMessage: null
}

const findColor = (color, dynamicVars, staticVars) => {
  if (typeof color !== 'string' || (!color.startsWith('--') && !color.startsWith('$'))) return color
  let targetColor = null
  if (color.startsWith('--')) {
    const [variable, modifier] = color.split(/,/g).map(str => str.trim())
    const variableSlot = variable.substring(2)
    if (variableSlot === 'stack') {
      const { r, g, b } = dynamicVars.stacked
      targetColor = { r, g, b }
    } else if (variableSlot.startsWith('parent')) {
      if (variableSlot === 'parent') {
        const { r, g, b } = dynamicVars.lowerLevelBackground
        targetColor = { r, g, b }
      } else {
        const virtualSlot = variableSlot.replace(/^parent/, '')
        targetColor = convert(dynamicVars.lowerLevelVirtualDirectivesRaw[virtualSlot]).rgb
      }
    } else {
      switch (variableSlot) {
        case 'inheritedBackground':
          targetColor = convert(dynamicVars.inheritedBackground).rgb
          break
        case 'background':
          targetColor = convert(dynamicVars.background).rgb
          break
        default:
          targetColor = convert(staticVars[variableSlot]).rgb
      }
    }

    if (modifier) {
      const effectiveBackground = dynamicVars.lowerLevelBackground ?? targetColor
      const isLightOnDark = relativeLuminance(convert(effectiveBackground).rgb) < 0.5
      const mod = isLightOnDark ? 1 : -1
      targetColor = brightness(Number.parseFloat(modifier) * mod, targetColor).rgb
    }
  }

  if (color.startsWith('$')) {
    try {
      targetColor = process(color, colorFunctions, findColor, dynamicVars, staticVars)
    } catch (e) {
      console.error('Failure executing color function', e)
      targetColor = '#FF00FF'
    }
  }
  // Color references other color
  return targetColor
}

const getTextColorAlpha = (directives, intendedTextColor, dynamicVars, staticVars) => {
  const opacity = directives.textOpacity
  const backgroundColor = convert(dynamicVars.lowerLevelBackground).rgb
  const textColor = convert(findColor(intendedTextColor, dynamicVars, staticVars)).rgb
  if (opacity === null || opacity === undefined || opacity >= 1) {
    return convert(textColor).hex
  }
  if (opacity === 0) {
    return convert(backgroundColor).hex
  }
  const opacityMode = directives.textOpacityMode
  switch (opacityMode) {
    case 'fake':
      return convert(alphaBlend(textColor, opacity, backgroundColor)).hex
    case 'mixrgb':
      return convert(mixrgb(backgroundColor, textColor)).hex
    default:
      return rgba2css({ a: opacity, ...textColor })
  }
}

export const getCssRules = (rules, staticVars) => rules.map(rule => {
  let selector = rule.selector
  if (!selector) {
    selector = 'body'
  }
  const header = selector + ' {'
  const footer = '}'

  const virtualDirectives = Object.entries(rule.virtualDirectives || {}).map(([k, v]) => {
    return '  ' + k + ': ' + v
  }).join(';\n')

  let directives
  if (rule.component !== 'Root') {
    directives = Object.entries(rule.directives).map(([k, v]) => {
      switch (k) {
        case 'roundness': {
          return '  ' + [
            '--roundness: ' + v + 'px'
          ].join(';\n  ')
        }
        case 'shadow': {
          return '  ' + [
            '--shadow: ' + getCssShadow(rule.dynamicVars.shadow),
            '--shadowFilter: ' + getCssShadowFilter(rule.dynamicVars.shadow),
            '--shadowInset: ' + getCssShadow(rule.dynamicVars.shadow, true)
          ].join(';\n  ')
        }
        case 'background': {
          if (v === 'transparent') {
            return [
              rule.directives.backgroundNoCssColor !== 'yes' ? ('background-color: ' + v) : '',
              '  --background: ' + v
            ].filter(x => x).join(';\n')
          }
          const color = getCssColorString(rule.dynamicVars.background, rule.directives.opacity)
          return [
            rule.directives.backgroundNoCssColor !== 'yes' ? ('background-color: ' + color) : '',
            '  --background: ' + color
          ].filter(x => x).join(';\n')
        }
        case 'textColor': {
          if (rule.directives.textNoCssColor === 'yes') { return '' }
          return 'color: ' + v
        }
        default:
          if (k.startsWith('--')) {
            const [type, value] = v.split('|').map(x => x.trim()) // woah, Extreme!
            switch (type) {
              case 'color':
                return k + ': ' + rgba2css(findColor(value, rule.dynamicVars, staticVars))
              default:
                return ''
            }
          }
          return ''
      }
    }).filter(x => x).map(x => '  ' + x).join(';\n')
  } else {
    directives = {}
  }

  return [
    header,
    directives + ';',
    (!rule.virtual && rule.directives.textNoCssColor !== 'yes') ? '  color: var(--text);' : '',
    '',
    virtualDirectives,
    footer
  ].join('\n')
}).filter(x => x)

// Loading all style.js[on] files dynamically
const componentsContext = require.context('src', true, /\.style.js(on)?$/)
componentsContext.keys().forEach(key => {
  const component = componentsContext(key).default
  if (components[component.name] != null) {
    console.warn(`Component in file ${key} is trying to override existing component ${component.name}! You have collisions/duplicates!`)
  }
  components[component.name] = component
})

// "Unrolls" a tree structure of item: { parent: { ...item2, parent: { ...item3, parent: {...} } }}
// into an array [item2, item3] for iterating
const unroll = (item) => {
  const out = []
  let currentParent = item
  while (currentParent) {
    out.push(currentParent)
    currentParent = currentParent.parent
  }
  return out
}

// This gives you an array of arrays of all possible unique (i.e. order-insensitive) combinations
export const getAllPossibleCombinations = (array) => {
  const combos = [array.map(x => [x])]
  for (let comboSize = 2; comboSize <= array.length; comboSize++) {
    const previous = combos[combos.length - 1]
    const selfSet = new Set()
    const newCombos = previous.map(self => {
      self.forEach(x => selfSet.add(x))
      const nonSelf = array.filter(x => !selfSet.has(x))
      return nonSelf.map(x => [...self, x])
    })
    const flatCombos = newCombos.reduce((acc, x) => [...acc, ...x], [])
    combos.push(flatCombos)
  }
  return combos.reduce((acc, x) => [...acc, ...x], [])
}

// Converts rule, parents and their criteria into a CSS (or path if ignoreOutOfTreeSelector == true) selector
export const ruleToSelector = (rule, ignoreOutOfTreeSelector, isParent) => {
  if (!rule && !isParent) return null
  const component = components[rule.component]
  const { states, variants, selector, outOfTreeSelector } = component

  const applicableStates = ((rule.state || []).filter(x => x !== 'normal')).map(state => states[state])

  const applicableVariantName = (rule.variant || 'normal')
  let applicableVariant = ''
  if (applicableVariantName !== 'normal') {
    applicableVariant = variants[applicableVariantName]
  } else {
    applicableVariant = variants?.normal ?? ''
  }

  let realSelector
  if (selector === ':root') {
    realSelector = ''
  } else if (isParent) {
    realSelector = selector
  } else {
    if (outOfTreeSelector && !ignoreOutOfTreeSelector) realSelector = outOfTreeSelector
    else realSelector = selector
  }

  const selectors = [realSelector, applicableVariant, ...applicableStates]
    .toSorted((a, b) => {
      if (a.startsWith(':')) return 1
      if (/^[a-z]/.exec(a)) return -1
      else return 0
    })
    .join('')

  if (rule.parent) {
    return (ruleToSelector(rule.parent, ignoreOutOfTreeSelector, true) + ' ' + selectors).trim()
  }
  return selectors.trim()
}

const combinationsMatch = (criteria, subject, strict) => {
  if (criteria.component !== subject.component) return false

  // All variants inherit from normal
  if (subject.variant !== 'normal' || strict) {
    if (criteria.variant !== subject.variant) return false
  }

  // Subject states > 1 essentially means state is "normal" and therefore matches
  if (subject.state.length > 1 || strict) {
    const subjectStatesSet = new Set(subject.state)
    const criteriaStatesSet = new Set(criteria.state)

    const setsAreEqual =
      [...criteriaStatesSet].every(state => subjectStatesSet.has(state)) &&
      [...subjectStatesSet].every(state => criteriaStatesSet.has(state))

    if (!setsAreEqual) return false
  }
  return true
}

const findRules = (criteria, strict) => subject => {
  // If we searching for "general" rules - ignore "specific" ones
  if (criteria.parent === null && !!subject.parent) return false
  if (!combinationsMatch(criteria, subject, strict)) return false

  if (criteria.parent !== undefined && criteria.parent !== null) {
    if (!subject.parent && !strict) return true
    const pathCriteria = unroll(criteria)
    const pathSubject = unroll(subject)
    if (pathCriteria.length < pathSubject.length) return false

    // Search: .a .b .c
    // Matches: .a .b .c; .b .c; .c; .z .a .b .c
    // Does not match .a .b .c .d, .a .b .e
    for (let i = 0; i < pathCriteria.length; i++) {
      const criteriaParent = pathCriteria[i]
      const subjectParent = pathSubject[i]
      if (!subjectParent) return true
      if (!combinationsMatch(criteriaParent, subjectParent, strict)) return false
    }
  }
  return true
}

const normalizeCombination = rule => {
  rule.variant = rule.variant ?? 'normal'
  rule.state = [...new Set(['normal', ...(rule.state || [])])]
}

export const init = (extraRuleset, palette) => {
  const stacked = {}
  const computed = {}

  const eagerRules = []
  const lazyRules = []

  const rulesetUnsorted = [
    ...Object.values(components)
      .map(c => (c.defaultRules || []).map(r => ({ component: c.name, ...r })))
      .reduce((acc, arr) => [...acc, ...arr], []),
    ...extraRuleset
  ].map(rule => {
    normalizeCombination(rule)
    let currentParent = rule.parent
    while (currentParent) {
      normalizeCombination(currentParent)
      currentParent = currentParent.parent
    }

    return rule
  })

  const ruleset = rulesetUnsorted
    .map((data, index) => ({ data, index }))
    .sort(({ data: a, index: ai }, { data: b, index: bi }) => {
      const parentsA = unroll(a).length
      const parentsB = unroll(b).length

      if (parentsA === parentsB) {
        if (a.component === 'Text') return -1
        if (b.component === 'Text') return 1
        return ai - bi
      }
      if (parentsA === 0 && parentsB !== 0) return -1
      if (parentsB === 0 && parentsA !== 0) return 1
      return parentsA - parentsB
    })
    .map(({ data }) => data)

  const virtualComponents = new Set(Object.values(components).filter(c => c.virtual).map(c => c.name))

  let counter = 0
  const promises = []
  const processInnerComponent = (component, rules, parent) => {
    const addRule = (rule) => {
      rules.push(rule)
    }

    const parentSelector = ruleToSelector(parent, true)
    // const parentList = parent ? unroll(parent).reverse().map(c => c.component) : []
    // if (!component.virtual) {
    //   const path = [...parentList, component.name].join(' > ')
    //   console.log('Component ' + path + ' process starting')
    // }
    // const t0 = performance.now()
    const {
      validInnerComponents = [],
      states: originalStates = {},
      variants: originalVariants = {},
      name
    } = component

    // Normalizing states and variants to always include "normal"
    const states = { normal: '', ...originalStates }
    const variants = { normal: '', ...originalVariants }
    const innerComponents = (validInnerComponents).map(name => {
      const result = components[name]
      if (result === undefined) console.error(`Component ${component.name} references a component ${name} which does not exist!`)
      return result
    })

    // Optimization: we only really need combinations without "normal" because all states implicitly have it
    const permutationStateKeys = Object.keys(states).filter(s => s !== 'normal')
    const stateCombinations = [
      ['normal'],
      ...getAllPossibleCombinations(permutationStateKeys)
        .map(combination => ['normal', ...combination])
        .filter(combo => {
          // Optimization: filter out some hard-coded combinations that don't make sense
          if (combo.indexOf('disabled') >= 0) {
            return !(
              combo.indexOf('hover') >= 0 ||
                combo.indexOf('focused') >= 0 ||
                combo.indexOf('pressed') >= 0
            )
          }
          return true
        })
    ]

    const stateVariantCombination = Object.keys(variants).map(variant => {
      return stateCombinations.map(state => ({ variant, state }))
    }).reduce((acc, x) => [...acc, ...x], [])

    stateVariantCombination.forEach(combination => {
      counter++
      // const tt0 = performance.now()

      combination.component = component.name
      const soloSelector = ruleToSelector(combination, true)
      const soloCssSelector = ruleToSelector(combination)
      const selector = [parentSelector, soloSelector].filter(x => x).join(' ')
      const cssSelector = [parentSelector, soloCssSelector].filter(x => x).join(' ')

      const lowerLevelSelector = parentSelector
      const lowerLevelBackground = computed[lowerLevelSelector]?.background
      const lowerLevelVirtualDirectives = computed[lowerLevelSelector]?.virtualDirectives
      const lowerLevelVirtualDirectivesRaw = computed[lowerLevelSelector]?.virtualDirectivesRaw

      const dynamicVars = computed[selector] || {
        lowerLevelBackground,
        lowerLevelVirtualDirectives,
        lowerLevelVirtualDirectivesRaw
      }

      // Inheriting all of the applicable rules
      const existingRules = ruleset.filter(findRules({ component: component.name, ...combination, parent }))
      const computedDirectives = existingRules.map(r => r.directives).reduce((acc, directives) => ({ ...acc, ...directives }), {})
      const computedRule = {
        component: component.name,
        ...combination,
        parent,
        directives: computedDirectives
      }

      computed[selector] = computed[selector] || {}
      computed[selector].computedRule = computedRule
      computed[selector].dynamicVars = dynamicVars

      if (virtualComponents.has(component.name)) {
        const virtualName = [
          '--',
          component.name.toLowerCase(),
          combination.variant === 'normal'
            ? ''
            : combination.variant[0].toUpperCase() + combination.variant.slice(1).toLowerCase(),
          ...combination.state.filter(x => x !== 'normal').toSorted().map(state => state[0].toUpperCase() + state.slice(1).toLowerCase())
        ].join('')

        let inheritedTextColor = computedDirectives.textColor
        let inheritedTextAuto = computedDirectives.textAuto
        let inheritedTextOpacity = computedDirectives.textOpacity
        let inheritedTextOpacityMode = computedDirectives.textOpacityMode
        const lowerLevelTextSelector = [...selector.split(/ /g).slice(0, -1), soloSelector].join(' ')
        const lowerLevelTextRule = computed[lowerLevelTextSelector]

        if (inheritedTextColor == null || inheritedTextOpacity == null || inheritedTextOpacityMode == null) {
          inheritedTextColor = computedDirectives.textColor ?? lowerLevelTextRule.textColor
          inheritedTextAuto = computedDirectives.textAuto ?? lowerLevelTextRule.textAuto
          inheritedTextOpacity = computedDirectives.textOpacity ?? lowerLevelTextRule.textOpacity
          inheritedTextOpacityMode = computedDirectives.textOpacityMode ?? lowerLevelTextRule.textOpacityMode
        }

        const newTextRule = {
          ...computedRule,
          directives: {
            ...computedRule.directives,
            textColor: inheritedTextColor,
            textAuto: inheritedTextAuto ?? 'preserve',
            textOpacity: inheritedTextOpacity,
            textOpacityMode: inheritedTextOpacityMode
          }
        }

        dynamicVars.inheritedBackground = lowerLevelBackground
        dynamicVars.stacked = convert(stacked[lowerLevelSelector]).rgb

        const intendedTextColor = convert(findColor(inheritedTextColor, dynamicVars, palette)).rgb
        const textColor = newTextRule.directives.textAuto === 'no-auto'
          ? intendedTextColor
          : getTextColor(
            convert(stacked[lowerLevelSelector]).rgb,
            intendedTextColor,
            newTextRule.directives.textAuto === 'preserve'
          )

        // Updating previously added rule
        const earlyLowerLevelRules = rules.filter(findRules(parent, true))
        const earlyLowerLevelRule = earlyLowerLevelRules.slice(-1)[0]

        const virtualDirectives = earlyLowerLevelRule.virtualDirectives || {}
        const virtualDirectivesRaw = earlyLowerLevelRule.virtualDirectivesRaw || {}

        // Storing color data in lower layer to use as custom css properties
        virtualDirectives[virtualName] = getTextColorAlpha(newTextRule.directives, textColor, dynamicVars)
        virtualDirectivesRaw[virtualName] = textColor
        earlyLowerLevelRule.virtualDirectives = virtualDirectives
        earlyLowerLevelRule.virtualDirectivesRaw = virtualDirectivesRaw
        computed[lowerLevelSelector].virtualDirectives = virtualDirectives
        computed[lowerLevelSelector].virtualDirectivesRaw = virtualDirectivesRaw

        // Debug: lets you see what it think background color should be
        if (!DEBUG) return

        const directives = {
          textColor,
          background: convert(computed[lowerLevelSelector].background).hex,
          ...inheritedTextOpacity
        }

        addRule({
          dynamicVars,
          selector: cssSelector,
          virtual: true,
          component: component.name,
          parent,
          ...combination,
          directives,
          virtualDirectives,
          virtualDirectivesRaw
        })
      } else {
        computed[selector] = computed[selector] || {}

        // TODO: DEFAULT TEXT COLOR
        const lowerLevelStackedBackground = stacked[lowerLevelSelector] || convert('#FF00FF').rgb

        if (computedDirectives.background) {
          let inheritRule = null
          const variantRules = ruleset.filter(findRules({ component: component.name, variant: combination.variant, parent }))
          const lastVariantRule = variantRules[variantRules.length - 1]
          if (lastVariantRule) {
            inheritRule = lastVariantRule
          } else {
            const normalRules = ruleset.filter(findRules({ component: component.name, parent }))
            const lastNormalRule = normalRules[normalRules.length - 1]
            inheritRule = lastNormalRule
          }

          const inheritSelector = ruleToSelector({ ...inheritRule, parent }, true)
          const inheritedBackground = computed[inheritSelector].background

          dynamicVars.inheritedBackground = inheritedBackground

          const rgb = convert(findColor(computedDirectives.background, dynamicVars, palette)).rgb

          if (!stacked[selector]) {
            let blend
            const alpha = computedDirectives.opacity
            if (alpha >= 1) {
              blend = rgb
            } else if (alpha <= 0) {
              blend = lowerLevelStackedBackground
            } else {
              blend = alphaBlend(rgb, computedDirectives.opacity, lowerLevelStackedBackground)
            }
            stacked[selector] = blend
            computed[selector].background = { ...rgb, a: computedDirectives.opacity ?? 1 }
          }
        }

        if (computedDirectives.shadow) {
          dynamicVars.shadow = (computedDirectives.shadow || []).map(shadow => {
            let targetShadow
            if (typeof shadow === 'string') {
              if (shadow.startsWith('$')) {
                targetShadow = process(shadow, shadowFunctions, findColor, dynamicVars, palette)
              }
            } else {
              targetShadow = shadow
            }

            return {
              ...targetShadow,
              color: findColor(targetShadow.color, dynamicVars, palette)
            }
          })
        }

        if (!stacked[selector]) {
          computedDirectives.background = 'transparent'
          computedDirectives.opacity = 0
          stacked[selector] = lowerLevelStackedBackground
          computed[selector].background = { ...lowerLevelStackedBackground, a: 0 }
        }

        dynamicVars.stacked = lowerLevelStackedBackground
        dynamicVars.background = computed[selector].background

        addRule({
          dynamicVars,
          selector: cssSelector,
          component: component.name,
          ...combination,
          parent,
          directives: computedDirectives
        })
      }

      innerComponents.forEach(innerComponent => {
        if (innerComponent.lazy) {
          promises.push(new Promise((resolve, reject) => {
            setTimeout(() => {
              try {
                processInnerComponent(innerComponent, lazyRules, { parent, component: name, ...combination })
                resolve()
              } catch (e) {
                reject(e)
              }
            }, 0)
          }))
        } else {
          processInnerComponent(innerComponent, rules, { parent, component: name, ...combination })
        }
      })
      // const tt1 = performance.now()
      // if (!component.virtual) {
      //   console.log('State-variant ' + combination.variant + ' : ' + combination.state.join('+') + ' procession time: ' + (tt1 - tt0) + 'ms')
      // }
    })

    // const t1 = performance.now()
    // if (!component.virtual) {
    //   const path = [...parentList, component.name].join(' > ')
    //   console.log('Component ' + path + ' procession time: ' + (t1 - t0) + 'ms')
    // }
  }

  processInnerComponent(components.Root, eagerRules)
  console.log('TOTAL COMBOS: ' + counter)
  const lazyExec = Promise.all(promises).then(() => {
    console.log('TOTAL COMBOS: ' + counter)
  }).then(() => lazyRules)

  return {
    lazy: lazyExec,
    eager: eagerRules
  }
}