aboutsummaryrefslogtreecommitdiff
path: root/src/services/style_setter/style_setter.js
blob: a98456d30b32a0fef0bf7153bc1481c1e1384a21 (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
import { hex2rgb } from '../color_convert/color_convert.js'
import { generatePreset } from '../theme_data/theme_data.service.js'
import { init, getEngineChecksum } from '../theme_data/theme_data_3.service.js'
import { convertTheme2To3 } from '../theme_data/theme2_to_theme3.js'
import { getCssRules } from '../theme_data/css_utils.js'
import { defaultState } from '../../modules/config.js'
import { chunk } from 'lodash'

export const generateTheme = async (input, callbacks) => {
  const {
    onNewRule = (rule, isLazy) => {},
    onLazyFinished = () => {},
    onEagerFinished = () => {}
  } = callbacks

  let extraRules
  if (input.themeFileVersion === 1) {
    extraRules = convertTheme2To3(input)
  } else {
    const { theme } = generatePreset(input)
    extraRules = convertTheme2To3(theme)
  }

  // Assuming that "worst case scenario background" is panel background since it's the most likely one
  const themes3 = init(extraRules, extraRules[0].directives['--bg'].split('|')[1].trim())

  getCssRules(themes3.eager, themes3.staticVars).forEach(rule => {
    // Hacks to support multiple selectors on same component
    if (rule.match(/::-webkit-scrollbar-button/)) {
      const parts = rule.split(/[{}]/g)
      const newRule = [
        parts[0],
        ', ',
        parts[0].replace(/button/, 'thumb'),
        ', ',
        parts[0].replace(/scrollbar-button/, 'resizer'),
        ' {',
        parts[1],
        '}'
      ].join('')
      onNewRule(newRule, false)
    } else {
      onNewRule(rule, false)
    }
  })
  onEagerFinished()

  // Optimization - instead of processing all lazy rules in one go, process them in small chunks
  // so that UI can do other things and be somewhat responsive while less important rules are being
  // processed
  let counter = 0
  const chunks = chunk(themes3.lazy, 200)
  // let t0 = performance.now()
  const processChunk = () => {
    const chunk = chunks[counter]
    Promise.all(chunk.map(x => x())).then(result => {
      getCssRules(result.filter(x => x), themes3.staticVars).forEach(rule => {
        if (rule.match(/\.modal-view/)) {
          const parts = rule.split(/[{}]/g)
          const newRule = [
            parts[0],
            ', ',
            parts[0].replace(/\.modal-view/, '#modal'),
            ', ',
            parts[0].replace(/\.modal-view/, '.shout-panel'),
            ' {',
            parts[1],
            '}'
          ].join('')
          onNewRule(newRule, true)
        } else {
          onNewRule(rule, true)
        }
      })
      // const t1 = performance.now()
      // console.debug('Chunk ' + counter + ' took ' + (t1 - t0) + 'ms')
      // t0 = t1
      counter += 1
      if (counter < chunks.length) {
        setTimeout(processChunk, 0)
      } else {
        onLazyFinished()
      }
    })
  }

  return { lazyProcessFunc: processChunk }
}

export const tryLoadCache = () => {
  const json = localStorage.getItem('pleroma-fe-theme-cache')
  if (!json) return null
  let cache
  try {
    cache = JSON.parse(json)
  } catch (e) {
    console.error('Failed to decode theme cache:', e)
    return false
  }
  if (cache.engineChecksum === getEngineChecksum()) {
    const styleSheet = new CSSStyleSheet()
    const lazyStyleSheet = new CSSStyleSheet()

    cache.data[0].forEach(rule => styleSheet.insertRule(rule, 'index-max'))
    cache.data[1].forEach(rule => lazyStyleSheet.insertRule(rule, 'index-max'))

    document.adoptedStyleSheets = [styleSheet, lazyStyleSheet]

    return true
  } else {
    console.warn('Engine checksum doesn\'t match, cache not usable, clearing')
    localStorage.removeItem('pleroma-fe-theme-cache')
  }
}

export const applyTheme = async (input, onFinish = (data) => {}) => {
  const styleSheet = new CSSStyleSheet()
  const styleArray = []
  const lazyStyleSheet = new CSSStyleSheet()
  const lazyStyleArray = []

  const { lazyProcessFunc } = await generateTheme(
    input,
    {
      onNewRule (rule, isLazy) {
        if (isLazy) {
          lazyStyleSheet.insertRule(rule, 'index-max')
          lazyStyleArray.push(rule)
        } else {
          styleSheet.insertRule(rule, 'index-max')
          styleArray.push(rule)
        }
      },
      onEagerFinished () {
        document.adoptedStyleSheets = [styleSheet]
      },
      onLazyFinished () {
        document.adoptedStyleSheets = [styleSheet, lazyStyleSheet]
        const cache = { engineChecksum: getEngineChecksum(), data: [styleArray, lazyStyleArray] }
        onFinish(cache)
        localStorage.setItem('pleroma-fe-theme-cache', JSON.stringify(cache))
      }
    }
  )

  setTimeout(lazyProcessFunc, 0)

  return Promise.resolve()
}

const configColumns = ({
  sidebarColumnWidth,
  contentColumnWidth,
  notifsColumnWidth,
  emojiReactionsScale,
  textSize
}) => ({
  sidebarColumnWidth,
  contentColumnWidth,
  notifsColumnWidth,
  emojiReactionsScale,
  textSize
})

const defaultConfigColumns = configColumns(defaultState)

export const applyConfig = (config) => {
  const columns = configColumns(config)

  if (columns === defaultConfigColumns) {
    return
  }

  const head = document.head
  const body = document.body
  body.classList.add('hidden')

  const rules = Object
    .entries(columns)
    .filter(([k, v]) => v)
    .map(([k, v]) => `--${k}: ${v}`).join(';')

  const styleEl = document.createElement('style')
  head.appendChild(styleEl)
  const styleSheet = styleEl.sheet

  styleSheet.toString()
  styleSheet.insertRule(`:root { ${rules} }`, 'index-max')

  body.classList.remove('hidden')
}

export const getThemes = () => {
  const cache = 'no-store'

  return window.fetch('/static/styles.json', { cache })
    .then((data) => data.json())
    .then((themes) => {
      return Object.entries(themes).map(([k, v]) => {
        let promise = null
        if (typeof v === 'object') {
          promise = Promise.resolve(v)
        } else if (typeof v === 'string') {
          promise = window.fetch(v, { cache })
            .then((data) => data.json())
            .catch((e) => {
              console.error(e)
              return null
            })
        }
        return [k, promise]
      })
    })
    .then((promises) => {
      return promises
        .reduce((acc, [k, v]) => {
          acc[k] = v
          return acc
        }, {})
    })
}

export const getPreset = (val) => {
  return getThemes()
    .then((themes) => themes[val] ? themes[val] : themes['pleroma-dark'])
    .then((theme) => {
      const isV1 = Array.isArray(theme)
      const data = isV1 ? {} : theme.theme

      if (isV1) {
        const bg = hex2rgb(theme[1])
        const fg = hex2rgb(theme[2])
        const text = hex2rgb(theme[3])
        const link = hex2rgb(theme[4])

        const cRed = hex2rgb(theme[5] || '#FF0000')
        const cGreen = hex2rgb(theme[6] || '#00FF00')
        const cBlue = hex2rgb(theme[7] || '#0000FF')
        const cOrange = hex2rgb(theme[8] || '#E3FF00')

        data.colors = { bg, fg, text, link, cRed, cBlue, cGreen, cOrange }
      }

      return { theme: data, source: theme.source }
    })
}

export const setPreset = (val) => getPreset(val).then(data => applyTheme(data))