printerCardPrefs.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Per-printer view preferences for the printer card.
  3. *
  4. * These are browser-local, like every other printer-page view preference
  5. * (`printerCardSize`, `hideDisconnectedPrinters`, `printerCollapsedSections`).
  6. * They describe how one person wants their own screen to look, not anything
  7. * about the printer, so they deliberately do not go to the backend.
  8. *
  9. * Keyed by printer id rather than held as a single global flag: the toggle
  10. * lives on the card itself, so hiding the external spool on one printer must
  11. * not silently rearrange every other card in a fleet.
  12. */
  13. const HIDDEN_EXTERNAL_SPOOLS_KEY = 'printerHiddenExternalSpools';
  14. function readHiddenExternalSpools(): Record<string, boolean> {
  15. try {
  16. const saved = localStorage.getItem(HIDDEN_EXTERNAL_SPOOLS_KEY);
  17. if (!saved) return {};
  18. const parsed: unknown = JSON.parse(saved);
  19. // Anything that isn't a plain object (an older format, or a value another
  20. // tab mangled) is discarded rather than indexed into.
  21. if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
  22. return parsed as Record<string, boolean>;
  23. } catch {
  24. // Malformed JSON, or localStorage unavailable (private mode / blocked
  25. // cookies). Showing the external spool is the safe default either way.
  26. return {};
  27. }
  28. }
  29. /** Whether this printer's external spool should be left out of the card. */
  30. export function isExternalSpoolHidden(printerId: number): boolean {
  31. return readHiddenExternalSpools()[String(printerId)] === true;
  32. }
  33. /**
  34. * Persist the toggle. Re-reads before writing so two cards toggled in the same
  35. * session can't clobber each other's entry, and drops the key entirely when
  36. * shown again so the stored object doesn't accumulate `false` for every printer
  37. * the user ever toggled twice.
  38. */
  39. export function setExternalSpoolHidden(printerId: number, hidden: boolean): void {
  40. const next = readHiddenExternalSpools();
  41. if (hidden) {
  42. next[String(printerId)] = true;
  43. } else {
  44. delete next[String(printerId)];
  45. }
  46. try {
  47. localStorage.setItem(HIDDEN_EXTERNAL_SPOOLS_KEY, JSON.stringify(next));
  48. } catch {
  49. // Quota exceeded or private mode — the toggle still applies for this
  50. // session, it just won't survive a reload.
  51. }
  52. }