okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
3cabb9e3f
main
1import { useEffect , useState } from 'react' ; 2import { tr } from './i18n' ; 3import { api } from './client' ; 4import { formatMoney , resolveCurrency , type ResolvedCurrency , type SystemLocale } from './currency' ; 5import { useStore } from './store' ; 6 7let asked :Promise < SystemLocale | null > | null = null ; 8 9/** The computer's regional format, read once from the host (null in a browser build that has none, or while it loads). */ 10export function useSystemLocale () :SystemLocale | null { 11const [ value , setValue ] = useState < SystemLocale | null >( null ); 12useEffect (() => { 13let alive = true ; 14asked ??= api . get < SystemLocale >( '/api/locale' ). catch (() => null ); 15void asked . then ( v => { if ( alive ) setValue ( v ); }); 16return () => { alive = false ; }; 17}, []); 18return value ; 19} 20 21/** The person's currency and locale for money (#3628) and a function that writes an amount in them. */ 22export function useMoney () :ResolvedCurrency & { format :( amount :number ) => string ; detected :string | null } { 23const system = useSystemLocale (), language = useStore ( s => s . language ), override = useStore ( s => s . electricityCurrency ); 24const browserLanguages = typeof navigator === 'undefined' ?[] :[ ...( navigator . languages ?? [ navigator . language ])]. filter ( Boolean ); 25const resolved = resolveCurrency ({ system, browserLanguages, language, override}); 26const detected = override ?resolveCurrency ({ system, browserLanguages, language}). currency :resolved . currency ; 27return { ...resolved , detected, format :amount => formatMoney ( amount , { ...resolved , lessThan :shown => tr ( 'less than {0}' , [ shown ]) }) }; 28}