// User preferences. The desktop host keeps them in `/settings.json` (src-tauri/src/preferences.rs). // Each window loads all sections once at startup, then reads them from memory. // A write goes to the host, and the host sends `settings-changed` to all windows. // // Without the desktop host (`pnpm dev` in a browser), the sections stay in localStorage under their old keys. // // These values stay in localStorage on purpose, because they are per-machine view state that is harmless to lose: // `runestone.workbenchLayout` (src/lib/workspace/workbenchLayout.ts) and the open tabs of each workspace // (`documentSessionKey` in src/lib/workspace/documentSession.ts). import { invoke, isTauri } from '@tauri-apps/api/core'; import { listen } from '@tauri-apps/api/event'; export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background', 'terminal', 'projectManagement'] as const; export type SettingsSection = typeof SETTINGS_SECTIONS[number]; export type SettingsSections = Partial>; /** The old localStorage key of each section: the browser preview storage, and the source of the first desktop file. */ export const LEGACY_KEYS: Readonly> = { general: 'runestone.settings', appearance: 'runestone.appearance', customThemes: 'runestone.custom-themes', customThemesLegacy: 'runestone.custom-themes.legacy', language: 'runestone.language', features: 'runestone.features', background: 'runestone.background', terminal: 'runestone.terminal', projectManagement: 'runestone.project-management', }; /** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */ export type Migration = (read: (key: string) => string | null) => SettingsSections; type Snapshot = { exists: boolean; revision: number; sections: SettingsSections; notice?: string }; type Change = { section: SettingsSection; revision: number; value: unknown }; type Waiter = { resolve: () => void; reject: (reason: unknown) => void }; const cache: SettingsSections = {}; const revisions = new Map(); const subscribers = new Map void>>(); const queued = new Map(); const writing = new Set(); // The newest change from another window that arrived during a local write of the same section. const deferred = new Map(); let started: Promise | undefined; let notice: string | null = null; function desktop() { return isTauri(); } // The language section was a plain string in localStorage. The other sections were JSON. function decode(section: SettingsSection, raw: string | null): unknown { if (raw === null) return undefined; if (section === 'language') return raw; try { return JSON.parse(raw); } catch { return undefined; } } function encode(section: SettingsSection, value: unknown): string { return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value); } function notify(section: SettingsSection) { for (const callback of [...subscribers.get(section) ?? []]) { try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); } } } function receive(change: Change) { if (!(SETTINGS_SECTIONS as readonly string[]).includes(change.section)) return; // During a local write of this section, apply the newest change only after the write ends. // Otherwise an older event can show an old value for a moment. if (writing.has(change.section) || queued.has(change.section)) { if ((deferred.get(change.section)?.revision ?? -1) < change.revision) deferred.set(change.section, change); return; } if ((revisions.get(change.section) ?? -1) >= change.revision) return; revisions.set(change.section, change.revision); cache[change.section] = change.value ?? undefined; notify(change.section); } function applySnapshot(snapshot: Snapshot) { for (const section of SETTINGS_SECTIONS) { if ((revisions.get(section) ?? -1) >= snapshot.revision) continue; revisions.set(section, snapshot.revision); cache[section] = snapshot.sections[section]; } } async function start(migrate: Migration) { if (!desktop()) { // The browser preview: other tabs report their changes through storage events. window.addEventListener('storage', event => { if (event.key === null) { SETTINGS_SECTIONS.forEach(notify); return; } const section = SETTINGS_SECTIONS.find(item => LEGACY_KEYS[item] === event.key); if (section) notify(section); }); return; } // Listen before the read, so that no change between the read and the listener goes missing. await listen('settings-changed', event => receive(event.payload)); let snapshot: Snapshot; try { snapshot = await invoke('settings_read'); } catch (reason) { notice = `RuneStone could not read your settings, so the default settings apply: ${String(reason)}`; return; } if (!snapshot.exists) { const sections = migrate(key => { try { return localStorage.getItem(key); } catch { return null; } }); try { snapshot = await invoke('settings_migrate', { sections }); } catch (reason) { // Use the old values in this window, and keep them in localStorage for the next start. snapshot = { exists: false, revision: 0, sections }; notice = `RuneStone could not save your settings file: ${String(reason)}`; } } applySnapshot(snapshot); notice ??= snapshot.notice ?? null; } /** Load all sections once. Later calls return the same promise. */ export function initSettings(migrate: Migration): Promise { return started ??= start(migrate); } /** A message for the user about the settings file, at most once for each window. */ export function takeSettingsNotice(): string | null { const value = notice; notice = null; return value; } /** The stored value of a section, or undefined. Normalize it before use. */ export function readSection(section: SettingsSection): unknown { if (desktop()) return cache[section]; try { return decode(section, localStorage.getItem(LEGACY_KEYS[section])); } catch { return undefined; } } async function flush(section: SettingsSection) { writing.add(section); try { for (let entry = queued.get(section); entry; entry = queued.get(section)) { queued.delete(section); try { const change = await invoke('settings_write', { section, value: entry.value ?? null }); revisions.set(section, Math.max(revisions.get(section) ?? -1, change.revision)); entry.waiters.forEach(waiter => waiter.resolve()); } catch (reason) { entry.waiters.forEach(waiter => waiter.reject(reason)); } } } finally { writing.delete(section); const late = deferred.get(section); deferred.delete(section); // A write of another window that the host saved after this window's last write wins. if (late) receive(late); } } /** * Replace a section. This window reads the new value at once, and its subscribers run at once. * Without the desktop host, a refused browser storage write throws before anything changes. * On the desktop, the promise rejects when the host cannot save the file. Quick writes of one section * merge, so the host saves only the last value. */ export function writeSection(section: SettingsSection, value: unknown): Promise { if (!desktop()) { localStorage.setItem(LEGACY_KEYS[section], encode(section, value)); notify(section); return Promise.resolve(); } cache[section] = value; notify(section); return new Promise((resolve, reject) => { const entry = queued.get(section) ?? { value, waiters: [] }; entry.value = value; entry.waiters.push({ resolve, reject }); queued.set(section, entry); if (!writing.has(section)) void flush(section); }); } /** Run `callback` after each change of `section` in this window or another window. Returns a function that stops it. */ export function onSettingsChange(section: SettingsSection, callback: () => void): () => void { const list = subscribers.get(section) ?? new Set(); list.add(callback); subscribers.set(section, list); return () => { list.delete(callback); }; }