aboutsummaryrefslogtreecommitdiffstats
path: root/src/features/accentColor/index.js
blob: a0f57a2fa28e154ffa784bb350c93b06db28c67e (plain) (blame)
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
import { reaction } from 'mobx';
import themeInfo from '../../assets/themeInfo.json';
import { DEFAULT_APP_SETTINGS } from '../../config';

const STYLE_ELEMENT_ID = 'accent-color';

function createAccentStyleElement() {
  const styles = document.createElement('style');
  styles.id = STYLE_ELEMENT_ID;

  document.querySelector('head').appendChild(styles);
}

function setAccentStyle(style) {
  const styleElement = document.getElementById(STYLE_ELEMENT_ID);
  styleElement.innerHTML = style;
}

function generateAccentStyle(color) {
  let style = '';

  Object.keys(themeInfo).forEach((property) => {
    style += `
      ${themeInfo[property]} {
        ${property}: ${color};
      }
    `;
  });

  return style;
}

export default function initAccentColor(stores) {
  const { settings } = stores;
  createAccentStyleElement();

  // Update accent color
  reaction(
    () => (
      settings.all.app.accentColor
    ),
    (color) => {
      if (color === DEFAULT_APP_SETTINGS.accentColor) {
        // Reset accent style to return to default color scheme
        setAccentStyle('');
      } else {
        const style = generateAccentStyle(color);
        setAccentStyle(style);
      }
    },
    {
      fireImmediately: true,
    },
  );
}