Files
doormilxpress_astryx/src/lib/preferences.js

66 lines
2.1 KiB
JavaScript

import * as React from 'react';
/**
* Console preferences — the operator's own display settings.
*
* These belong to the browser, not to the Doormile account: the admin API has
* no preferences resource, and table density is a per-machine choice anyway
* (the same operator wants tighter rows on a warehouse monitor and looser ones
* on a laptop). Stored in localStorage, and changes broadcast on a custom event
* so every mounted consumer re-renders — `storage` alone only fires in *other*
* tabs, which would leave the table that triggered the change unchanged.
*/
const STORAGE_KEY = 'doormilePreferences';
const CHANGE_EVENT = 'doormile:preferences';
export const DEFAULT_PREFERENCES = {
/** Tighter row heights across every table. */
compactDensity: false,
/** Rows per page the tables open on. */
defaultPageSize: 25,
};
const read = () => {
try {
const raw = localStorage.getItem(STORAGE_KEY);
return raw ? { ...DEFAULT_PREFERENCES, ...JSON.parse(raw) } : { ...DEFAULT_PREFERENCES };
} catch {
return { ...DEFAULT_PREFERENCES };
}
};
/** Merges a patch into the stored preferences and notifies every consumer. */
export const writePreferences = (patch) => {
const next = { ...read(), ...patch };
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch {
/* A refused write (private mode, quota) still applies for this session —
the event below fires either way, so the UI stays consistent. */
}
window.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: next }));
return next;
};
export function usePreferences() {
const [preferences, setPreferences] = React.useState(read);
React.useEffect(() => {
const sync = () => setPreferences(read());
window.addEventListener(CHANGE_EVENT, sync);
window.addEventListener('storage', sync);
return () => {
window.removeEventListener(CHANGE_EVENT, sync);
window.removeEventListener('storage', sync);
};
}, []);
return preferences;
}
/** `[preferences, update]` for screens that write as well as read. */
export function useUpdatePreferences() {
return React.useCallback((patch) => writePreferences(patch), []);
}