Some checks failed
CI / Verify (push) Has been cancelled
Bought items now move down to a 'Comprados hoy' collapsible section (expanded by default) below the pending ones, and are only visible on the local day they were bought. Items bought on previous days stay completed in the database but are hidden from the list.
36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
import { useEffect, useState } from 'react'
|
|
|
|
/** Milliseconds until the next local midnight, plus a small buffer. */
|
|
function msUntilNextLocalDay(now: Date): number {
|
|
const nextMidnight = new Date(now)
|
|
nextMidnight.setHours(24, 0, 0, 0)
|
|
|
|
return nextMidnight.getTime() - now.getTime() + 5_000
|
|
}
|
|
|
|
/**
|
|
* The current date, refreshed when the local day changes (via a timer set to
|
|
* the next midnight) and when the tab regains focus. Components selling a
|
|
* "today only" view use it so bought items disappear once the day rolls over
|
|
* even if the page has been open all night.
|
|
*/
|
|
export function useToday(): Date {
|
|
const [today, setToday] = useState(() => new Date())
|
|
|
|
useEffect(() => {
|
|
const refresh = () => setToday(new Date())
|
|
|
|
const timer = setTimeout(refresh, msUntilNextLocalDay(new Date()))
|
|
window.addEventListener('focus', refresh)
|
|
document.addEventListener('visibilitychange', refresh)
|
|
|
|
return () => {
|
|
clearTimeout(timer)
|
|
window.removeEventListener('focus', refresh)
|
|
document.removeEventListener('visibilitychange', refresh)
|
|
}
|
|
}, [])
|
|
|
|
return today
|
|
}
|