]> BookStack Code Mirror - bookstack/blob - resources/js/markdown/settings.js
e2e1fce5e379ee0aa466e576bbe711af31741f97
[bookstack] / resources / js / markdown / settings.js
1 export class Settings {
2
3     constructor(settingInputs) {
4         this.settingMap = {
5             scrollSync: true,
6             showPreview: true,
7             editorWidth: 50,
8             plainEditor: false,
9         };
10         this.changeListeners = {};
11         this.loadFromLocalStorage();
12         this.applyToInputs(settingInputs);
13         this.listenToInputChanges(settingInputs);
14     }
15
16     applyToInputs(inputs) {
17         for (const input of inputs) {
18             const name = input.getAttribute('name').replace('md-', '');
19             input.checked = this.settingMap[name];
20         }
21     }
22
23     listenToInputChanges(inputs) {
24         for (const input of inputs) {
25             input.addEventListener('change', () => {
26                 const name = input.getAttribute('name').replace('md-', '');
27                 this.set(name, input.checked);
28             });
29         }
30     }
31
32     loadFromLocalStorage() {
33         const lsValString = window.localStorage.getItem('md-editor-settings');
34         if (!lsValString) {
35             return;
36         }
37
38         const lsVals = JSON.parse(lsValString);
39         for (const [key, value] of Object.entries(lsVals)) {
40             if (value !== null && this.settingMap[key] !== undefined) {
41                 this.settingMap[key] = value;
42             }
43         }
44     }
45
46     set(key, value) {
47         this.settingMap[key] = value;
48         window.localStorage.setItem('md-editor-settings', JSON.stringify(this.settingMap));
49         for (const listener of (this.changeListeners[key] || [])) {
50             listener(value);
51         }
52     }
53
54     get(key) {
55         return this.settingMap[key] || null;
56     }
57
58     onChange(key, callback) {
59         const listeners = this.changeListeners[key] || [];
60         listeners.push(callback);
61         this.changeListeners[key] = listeners;
62     }
63
64 }