File size: 2,138 Bytes
1187b53 f71b691 1187b53 f71b691 1187b53 f71b691 1187b53 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | const SESSION_PREFIX = "masters_toolkit_tab_session_v2:";
const MAX_SESSION_CHARS = 850_000;
const SAVE_DEBOUNCE_MS = 220;
const saveTimers = new Map<string, number>();
const pendingSerialized = new Map<string, string>();
export function loadTabSession<T>(tabKey: string): T | null {
if (typeof window === "undefined") return null;
try {
const raw = window.localStorage.getItem(`${SESSION_PREFIX}${tabKey}`);
if (!raw) return null;
return JSON.parse(raw) as T;
} catch {
return null;
}
}
export function saveTabSession<T>(tabKey: string, value: T): boolean {
if (typeof window === "undefined") return false;
try {
const serialized = JSON.stringify(value);
if (serialized.length > MAX_SESSION_CHARS) return false;
window.localStorage.setItem(`${SESSION_PREFIX}${tabKey}`, serialized);
return true;
} catch {
return false;
}
}
export function saveTabSessionDebounced<T>(tabKey: string, value: T, debounceMs = SAVE_DEBOUNCE_MS): void {
if (typeof window === "undefined") return;
try {
const serialized = JSON.stringify(value);
if (serialized.length > MAX_SESSION_CHARS) return;
pendingSerialized.set(tabKey, serialized);
const prev = saveTimers.get(tabKey);
if (typeof prev === "number") window.clearTimeout(prev);
const t = window.setTimeout(() => {
const payload = pendingSerialized.get(tabKey);
if (!payload) return;
try {
window.localStorage.setItem(`${SESSION_PREFIX}${tabKey}`, payload);
} catch {
// ignore
} finally {
pendingSerialized.delete(tabKey);
saveTimers.delete(tabKey);
}
}, Math.max(80, debounceMs));
saveTimers.set(tabKey, t);
} catch {
// ignore
}
}
export function clearTabSession(tabKey: string): void {
if (typeof window === "undefined") return;
try {
const pending = saveTimers.get(tabKey);
if (typeof pending === "number") {
window.clearTimeout(pending);
saveTimers.delete(tabKey);
}
pendingSerialized.delete(tabKey);
window.localStorage.removeItem(`${SESSION_PREFIX}${tabKey}`);
} catch {
// ignore
}
}
|