34 lines
1.1 KiB
TypeScript
34 lines
1.1 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState } from "react";
|
|
import { HIDE_AMOUNTS_EVENT } from "@/ds";
|
|
import { isHidden } from "@/ds/money";
|
|
|
|
/**
|
|
* Tracks the global hide-amounts flag reactively. `tugrik()`/`isHidden()`
|
|
* read `localStorage` synchronously but don't cause a re-render on their
|
|
* own — pages that show masked amounts need to listen for the
|
|
* `HideAmountsToggle`-dispatched event (and other tabs' storage writes) to
|
|
* update immediately when the switch flips.
|
|
*/
|
|
export function useHiddenAmounts(): boolean {
|
|
const [hidden, setHiddenState] = useState<boolean>(() => isHidden());
|
|
|
|
useEffect(() => {
|
|
function onToggle(e: Event) {
|
|
const detail = (e as CustomEvent<{ hidden: boolean }>).detail;
|
|
setHiddenState(detail ? detail.hidden : isHidden());
|
|
}
|
|
function onStorage() {
|
|
setHiddenState(isHidden());
|
|
}
|
|
window.addEventListener(HIDE_AMOUNTS_EVENT, onToggle);
|
|
window.addEventListener("storage", onStorage);
|
|
return () => {
|
|
window.removeEventListener(HIDE_AMOUNTS_EVENT, onToggle);
|
|
window.removeEventListener("storage", onStorage);
|
|
};
|
|
}, []);
|
|
|
|
return hidden;
|
|
}
|