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