Inital commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import { throttle } from "lodash";
|
||||
import type { GlobalSettings } from "../interface";
|
||||
import { BasicEventEmitter } from "../utils/eventEmitter";
|
||||
import { A4_HEIGHT, A4_WIDTH } from "../constants";
|
||||
|
||||
function defaultGlobalSetting(): GlobalSettings {
|
||||
return {
|
||||
DPI: 96,
|
||||
scale: 1,
|
||||
paperHeight: A4_HEIGHT,
|
||||
paperWidth: A4_WIDTH,
|
||||
grid: "none",
|
||||
landscape: false,
|
||||
};
|
||||
}
|
||||
|
||||
export class GlobalSettingsHandler {
|
||||
private STORAGE_SETTINGS_KEY = "settings";
|
||||
public readonly emitter = new BasicEventEmitter<{
|
||||
"settings-update": [];
|
||||
}>();
|
||||
private _settings: GlobalSettings = defaultGlobalSetting();
|
||||
private store!: LocalForage;
|
||||
|
||||
async init(store: LocalForage) {
|
||||
this.store = store;
|
||||
this._settings = (await this.store.getItem<GlobalSettings>(this.STORAGE_SETTINGS_KEY)) || this._settings;
|
||||
}
|
||||
setSettings(settings: Partial<GlobalSettings>) {
|
||||
const entries = Object.entries(settings);
|
||||
let emitUpdate = false;
|
||||
for (const [key, value] of entries) {
|
||||
const diff = (this._settings as any)[key] !== value;
|
||||
(this._settings as any)[key] = value;
|
||||
if (diff) {
|
||||
emitUpdate = true;
|
||||
}
|
||||
}
|
||||
if (emitUpdate) {
|
||||
this.emitter.emit("settings-update");
|
||||
this.save();
|
||||
}
|
||||
}
|
||||
async clear() {
|
||||
this._settings = defaultGlobalSetting();
|
||||
await this.store.setItem(this.STORAGE_SETTINGS_KEY, this._settings);
|
||||
}
|
||||
get settings() {
|
||||
return { ...this._settings };
|
||||
}
|
||||
private save = throttle(async () => {
|
||||
await this.store.setItem(this.STORAGE_SETTINGS_KEY, this._settings);
|
||||
}, 1000);
|
||||
}
|
||||
Reference in New Issue
Block a user