windowStorage.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { kindOf, type DocKind } from "#office/contract.ts";
  2. import { PROFILE } from "#office/profile.ts";
  3. type StoragePort = Pick<Storage, "getItem" | "setItem">;
  4. export interface WindowState {
  5. path?: string;
  6. recent?: { path: string; kind: DocKind }[];
  7. }
  8. const KEY = `${PROFILE.name}:windows:v1`;
  9. const MAX_WINDOWS = 128;
  10. function readAll(storage: StoragePort): Record<string, WindowState> {
  11. try {
  12. const parsed: unknown = JSON.parse(storage.getItem(KEY) ?? "{}");
  13. return parsed && typeof parsed === "object" && !Array.isArray(parsed)
  14. ? (parsed as Record<string, WindowState>)
  15. : {};
  16. } catch {
  17. return {};
  18. }
  19. }
  20. export function readWindowState(storage: StoragePort, key: string): WindowState {
  21. const item = readAll(storage)[key];
  22. if (!item || typeof item !== "object") return {};
  23. return {
  24. ...(typeof item.path === "string" ? { path: item.path } : {}),
  25. ...(Array.isArray(item.recent)
  26. ? {
  27. recent: item.recent.filter(
  28. (file) => typeof file?.path === "string" && kindOf(file.path) === file.kind,
  29. ),
  30. }
  31. : {}),
  32. };
  33. }
  34. export function writeWindowState(storage: StoragePort, key: string, patch: WindowState): void {
  35. try {
  36. const items = readAll(storage);
  37. const value = { ...readWindowState(storage, key), ...patch };
  38. // 按最近使用顺序保留有限窗口,避免关闭标签页后无限累积独立 localStorage 键。
  39. delete items[key];
  40. items[key] = value;
  41. for (const oldest of Object.keys(items).slice(0, -MAX_WINDOWS)) delete items[oldest];
  42. storage.setItem(KEY, JSON.stringify(items));
  43. } catch {
  44. /* 禁用存储或达到配额时不阻断查看器。 */
  45. }
  46. }