feat(app): store settings in the local storage
This commit is contained in:
@@ -1,20 +1,57 @@
|
||||
import { z } from "zod/mini";
|
||||
|
||||
const STORAGE_ID = "app_settings";
|
||||
|
||||
const settingsSchema = z.object({
|
||||
color: z.object({
|
||||
col: z.number(),
|
||||
row: z.number(),
|
||||
}),
|
||||
});
|
||||
|
||||
type Settings = z.infer<typeof settingsSchema>;
|
||||
|
||||
const defaultSettings = (): Settings => ({
|
||||
color: { col: 0, row: 0 },
|
||||
});
|
||||
|
||||
const loadSettings = (): Settings => {
|
||||
const stored = localStorage.getItem(STORAGE_ID);
|
||||
try {
|
||||
const result = settingsSchema.safeParse(JSON.parse(stored ?? ""));
|
||||
if (result.success) {
|
||||
return result.data;
|
||||
}
|
||||
} catch {
|
||||
// JSON.parse failed
|
||||
}
|
||||
|
||||
const settings = defaultSettings();
|
||||
saveSettings(settings);
|
||||
return settings;
|
||||
};
|
||||
|
||||
const saveSettings = (settings: Settings) => {
|
||||
localStorage.setItem(STORAGE_ID, JSON.stringify(settings));
|
||||
};
|
||||
|
||||
export const useAppStore = defineStore("app", {
|
||||
state: () => ({
|
||||
booted: false,
|
||||
_color: { col: 0, row: 0 },
|
||||
settings: loadSettings(),
|
||||
}),
|
||||
|
||||
actions: {
|
||||
setColor(col: number, row: number) {
|
||||
this._color = { col, row };
|
||||
this.settings.color = { col, row };
|
||||
},
|
||||
},
|
||||
|
||||
getters: {
|
||||
color: (state) => ({
|
||||
col: state._color.col,
|
||||
row: state._color.row,
|
||||
hex: APP_COLORS[state._color.row]![state._color.col]!,
|
||||
col: state.settings.color.col,
|
||||
row: state.settings.color.row,
|
||||
hex: APP_COLORS[state.settings.color.row]![state.settings.color.col]!,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user