Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder. WebView storage can be lost, and the host cannot read it. The file has a schema number, a revision number, and one value for each section: general, appearance, customThemes, customThemesLegacy, and language. - settings_read gives all sections, the revision, and a one-time notice. - settings_write replaces one section, writes the file atomically, and sends settings-changed to all windows. The limit is 8 MiB. - settings_migrate writes the first file only when no file exists. - The host moves a damaged file to settings.corrupt-<seconds>.json, starts from the defaults, and reports this one time. Each window loads the sections before its first render. One store in src/lib/settings/store.ts replaces the storage listeners. When no file exists, the window normalizes the old localStorage values and migrates them. The old keys stay in place for one release. The window layout and the open tabs stay in localStorage on purpose. The browser preview keeps all preferences in localStorage. Keep tab transfer offers in host memory, not in localStorage, because an offer can hold unsaved text. A window takes an offer once. The host checks the workspace root and a 120 second expiry. When the receiver accepts the tab, the host sends tab-transfer-accepted to the source window only. A refused offer stays open, and the source tab stays open. A new window and a drop on the tab ribbon use one check. The smoke harness serves the new commands from one shared state for each browser context. Tests read saved values from the mock settings file. Rust, unit, and smoke tests cover the changes.
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
// User preferences. The desktop host keeps them in `<app config dir>/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'] as const;
|
||||
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
|
||||
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
||||
|
||||
/** The old localStorage key of each section: the browser preview storage, and the source of the first desktop file. */
|
||||
export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
|
||||
general: 'runestone.settings',
|
||||
appearance: 'runestone.appearance',
|
||||
customThemes: 'runestone.custom-themes',
|
||||
customThemesLegacy: 'runestone.custom-themes.legacy',
|
||||
language: 'runestone.language',
|
||||
};
|
||||
|
||||
/** 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<SettingsSection, number>();
|
||||
const subscribers = new Map<SettingsSection, Set<() => void>>();
|
||||
const queued = new Map<SettingsSection, { value: unknown; waiters: Waiter[] }>();
|
||||
const writing = new Set<SettingsSection>();
|
||||
// The newest change from another window that arrived during a local write of the same section.
|
||||
const deferred = new Map<SettingsSection, Change>();
|
||||
let started: Promise<void> | 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<Change>('settings-changed', event => receive(event.payload));
|
||||
let snapshot: Snapshot;
|
||||
try { snapshot = await invoke<Snapshot>('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<Snapshot>('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<void> {
|
||||
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<Change>('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<void> {
|
||||
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); };
|
||||
}
|
||||
Reference in New Issue
Block a user