UNPKG

asciitorium

Version:
61 lines (60 loc) 2.11 kB
import { State } from './State.js'; import { isWebEnvironment } from './environment.js'; export class PersistentState extends State { constructor(initialValue, storageKey) { // Try to load from localStorage first, fall back to initialValue const storedValue = PersistentState.loadFromStorage(storageKey, initialValue); super(storedValue); this.storageKey = storageKey; } get value() { const currentValue = super.value; return currentValue; } set value(newValue) { // Call parent setter which triggers listeners super.value = newValue; // Save to localStorage if in web environment this.saveToStorage(newValue); } saveToStorage(value) { if (isWebEnvironment()) { try { const key = `asciitorium-${this.storageKey}`; localStorage.setItem(key, JSON.stringify(value)); } catch (error) { // Silently fail if localStorage is not available console.warn('Failed to save state to localStorage:', error); } } } static loadFromStorage(storageKey, fallback) { if (isWebEnvironment()) { try { const key = `asciitorium-${storageKey}`; const stored = localStorage.getItem(key); if (stored !== null) { return JSON.parse(stored); } } catch (error) { // Silently fail if localStorage is not available or data is corrupted console.warn('Failed to load state from localStorage:', error); } } return fallback; } // Optional method to clear stored state clearStorage() { if (isWebEnvironment()) { try { const key = `asciitorium-${this.storageKey}`; localStorage.removeItem(key); } catch (error) { console.warn('Failed to clear state from localStorage:', error); } } } }