2022-11-28 07:12:36 -05:00
|
|
|
export class Settings {
|
|
|
|
|
2022-11-28 09:08:20 -05:00
|
|
|
constructor(settingInputs) {
|
|
|
|
this.settingMap = {
|
|
|
|
scrollSync: true,
|
|
|
|
showPreview: true,
|
|
|
|
editorWidth: 50,
|
|
|
|
};
|
2022-11-28 07:12:36 -05:00
|
|
|
this.changeListeners = {};
|
2022-11-28 09:08:20 -05:00
|
|
|
this.loadFromLocalStorage();
|
|
|
|
this.applyToInputs(settingInputs);
|
|
|
|
this.listenToInputChanges(settingInputs);
|
|
|
|
}
|
|
|
|
|
|
|
|
applyToInputs(inputs) {
|
|
|
|
for (const input of inputs) {
|
|
|
|
const name = input.getAttribute('name').replace('md-', '');
|
|
|
|
input.checked = this.settingMap[name];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
listenToInputChanges(inputs) {
|
|
|
|
for (const input of inputs) {
|
2023-04-19 10:20:04 -04:00
|
|
|
input.addEventListener('change', () => {
|
2022-11-28 09:08:20 -05:00
|
|
|
const name = input.getAttribute('name').replace('md-', '');
|
|
|
|
this.set(name, input.checked);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
loadFromLocalStorage() {
|
|
|
|
const lsValString = window.localStorage.getItem('md-editor-settings');
|
|
|
|
if (!lsValString) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const lsVals = JSON.parse(lsValString);
|
|
|
|
for (const [key, value] of Object.entries(lsVals)) {
|
|
|
|
if (value !== null && this.settingMap[key] !== undefined) {
|
|
|
|
this.settingMap[key] = value;
|
|
|
|
}
|
|
|
|
}
|
2022-11-28 07:12:36 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
set(key, value) {
|
|
|
|
this.settingMap[key] = value;
|
2022-11-28 09:08:20 -05:00
|
|
|
window.localStorage.setItem('md-editor-settings', JSON.stringify(this.settingMap));
|
2022-11-28 07:12:36 -05:00
|
|
|
for (const listener of (this.changeListeners[key] || [])) {
|
|
|
|
listener(value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
get(key) {
|
2022-11-28 09:08:20 -05:00
|
|
|
return this.settingMap[key] || null;
|
2022-11-28 07:12:36 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
onChange(key, callback) {
|
2022-11-28 09:08:20 -05:00
|
|
|
const listeners = this.changeListeners[key] || [];
|
2022-11-28 07:12:36 -05:00
|
|
|
listeners.push(callback);
|
2022-11-28 09:08:20 -05:00
|
|
|
this.changeListeners[key] = listeners;
|
2022-11-28 07:12:36 -05:00
|
|
|
}
|
2023-04-18 17:20:02 -04:00
|
|
|
|
|
|
|
}
|