master
Colby Knox
v0.12.7
263875b
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
/**
* Viewer preferences with a safe fallback. A sandboxed frame without
* allow-same-origin (the wiki's widget and readme frames) throws a
* SecurityError on ANY window.localStorage access, even a read. Preferences
* then live in this document only: the viewer behaves the same, nothing is
* remembered across loads, and the ready report says so (storage: ephemeral)
* instead of the caller inferring it from a thrown exception.
*/
const memory = new Map<string, string>();
let backend: 'persistent' | 'ephemeral' | null = null;
function storage(): Storage | null {
if (backend === 'ephemeral') return null;
try {
const s = typeof window !== 'undefined' ? window.localStorage : null;
if (!s) { backend = 'ephemeral'; return null; }
// A getter that resolves is not proof it works (private mode, quota
// 0, denied by policy); a probe write settles it once.
if (backend === null) {
const k = '__adom_viewer_probe';
s.setItem(k, '1');
s.removeItem(k);
backend = 'persistent';
}
return s;
} catch {
backend = 'ephemeral';
return null;
}
}
export function prefsBackend(): 'persistent' | 'ephemeral' {
storage();
return backend || 'ephemeral';
}
export function getPref(key: string): string | null {
const s = storage();
if (s) { try { return s.getItem(key); } catch { /* fall through */ } }
return memory.has(key) ? memory.get(key)! : null;
}
export function setPref(key: string, value: string): void {
const s = storage();
if (s) { try { s.setItem(key, value); return; } catch { /* fall through */ } }
memory.set(key, value);
}
/** Remove every preference whose key starts with `prefix`. */
export function removePrefsWithPrefix(prefix: string): void {
const s = storage();
if (s) {
try {
for (let i = s.length - 1; i >= 0; i--) {
const k = s.key(i);
if (k && k.startsWith(prefix)) s.removeItem(k);
}
} catch { /* storage went away: nothing to clear */ }
}
for (const k of [...memory.keys()]) if (k.startsWith(prefix)) memory.delete(k);
}