]> BookStack Code Mirror - bookstack/blob - resources/js/components/setting-app-color-picker.js
Merge branch 'fix-1575' of git://github.com/james-geiger/BookStack into james-geiger...
[bookstack] / resources / js / components / setting-app-color-picker.js
1
2 class SettingAppColorPicker {
3
4     constructor(elem) {
5         this.elem = elem;
6         this.colorInput = elem.querySelector('input[type=color]');
7         this.lightColorInput = elem.querySelector('input[name="setting-app-color-light"]');
8         this.resetButton = elem.querySelector('[setting-app-color-picker-reset]');
9
10         this.colorInput.addEventListener('change', this.updateColor.bind(this));
11         this.colorInput.addEventListener('input', this.updateColor.bind(this));
12         this.resetButton.addEventListener('click', event => {
13             this.colorInput.value = '#206ea7';
14             this.updateColor();
15         });
16     }
17
18     /**
19      * Update the app colors as a preview, and create a light version of the color.
20      */
21     updateColor() {
22         const hexVal = this.colorInput.value;
23         const rgb = this.hexToRgb(hexVal);
24         const rgbLightVal = 'rgba('+ [rgb.r, rgb.g, rgb.b, '0.15'].join(',') +')';
25
26         this.lightColorInput.value = rgbLightVal;
27
28         const customStyles = document.getElementById('custom-styles');
29         const oldColor = customStyles.getAttribute('data-color');
30         const oldColorLight = customStyles.getAttribute('data-color-light');
31
32         customStyles.innerHTML = customStyles.innerHTML.split(oldColor).join(hexVal);
33         customStyles.innerHTML = customStyles.innerHTML.split(oldColorLight).join(rgbLightVal);
34
35         customStyles.setAttribute('data-color', hexVal);
36         customStyles.setAttribute('data-color-light', rgbLightVal);
37     }
38
39     /**
40      * Covert a hex color code to rgb components.
41      * @attribution https://stackoverflow.com/a/5624139
42      * @param hex
43      * @returns {*}
44      */
45     hexToRgb(hex) {
46         const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
47         return {
48             r: result ? parseInt(result[1], 16) : 0,
49             g: result ? parseInt(result[2], 16) : 0,
50             b: result ? parseInt(result[3], 16) : 0
51         };
52     }
53
54 }
55
56 export default SettingAppColorPicker;