Persist web preferences to OPFS parameters
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { loadSettings, saveSettings } from "./settings-store.js";
|
||||
|
||||
export type WebPreferences = {
|
||||
unitSystem: string;
|
||||
@@ -25,7 +26,17 @@ export const loadWebPreferences = (): WebPreferences => {
|
||||
|
||||
export function PreferencesDialog({ onClose }: { onClose: () => void }) {
|
||||
const [preferences, setPreferences] = useState<WebPreferences>(loadWebPreferences);
|
||||
useEffect(() => { localStorage.setItem(KEY, JSON.stringify(preferences)); }, [preferences]);
|
||||
const hydrated = useRef(false);
|
||||
useEffect(() => {
|
||||
loadSettings<WebPreferences>("web-preferences.json", DEFAULTS).then(stored => {
|
||||
if (stored) setPreferences(stored);
|
||||
hydrated.current = true;
|
||||
});
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
localStorage.setItem(KEY, JSON.stringify(preferences));
|
||||
if (hydrated.current) void saveSettings("web-preferences.json", preferences);
|
||||
}, [preferences]);
|
||||
const update = <K extends keyof WebPreferences>(key: K, value: WebPreferences[K]) =>
|
||||
setPreferences(previous => ({ ...previous, [key]: value }));
|
||||
return <div className="web-preferences" role="dialog" aria-label="Preferences">
|
||||
|
||||
32
web/src/shell/settings-store.ts
Normal file
32
web/src/shell/settings-store.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { persist, saved } from "../parameter-storage.js";
|
||||
|
||||
const toBase64 = (text: string) => {
|
||||
const bytes = new TextEncoder().encode(text);
|
||||
let binary = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 8192)
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
|
||||
return btoa(binary);
|
||||
};
|
||||
const fromBase64 = (text: string) => {
|
||||
const binary = atob(text);
|
||||
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
|
||||
return new TextDecoder().decode(bytes);
|
||||
};
|
||||
|
||||
export async function loadSettings<T>(fileName: string, fallback: T): Promise<T> {
|
||||
try {
|
||||
const encoded = await saved(fileName);
|
||||
if (!encoded) return fallback;
|
||||
return { ...fallback, ...JSON.parse(fromBase64(encoded)) } as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveSettings<T>(fileName: string, value: T): Promise<void> {
|
||||
try {
|
||||
await persist(toBase64(JSON.stringify(value)), fileName);
|
||||
} catch {
|
||||
// OPFS unavailable: caller keeps localStorage fallback.
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user