| 1 | 'use client' |
| 2 | |
| 3 | import { useAction } from 'next-safe-action/hooks' |
| 4 | import { useEffect, useRef |
| 5 | import { updateTimezoneAction } |
| 6 | import { authClient } |
| 7 | |
| 8 | /** |
| 9 | * Invisibly keeps `users.timezone` in sync with the viewer's device zone. Runs |
| 10 | * for any authenticated viewer (no-op when logged out) and writes only when the |
| 11 | * detected zone differs from what's stored — so it captures the zone right |
| 12 | * after sign-up and follows the user if they later change timezones. |
| 13 | */ |
| 14 | export function TimezoneSync() |
| 15 | const { data: |
| 16 | const { execute |
| 17 | |
| 18 | const userId = |
| 19 | const stored = |
| 20 | const lastSentTimezone = |
| 21 | |
| 22 | useEffect(() => |
| 23 | if (!userId) |
| 24 | return |
| 25 | } |
| 26 | const sync = |
| 27 | const detected = |
| 28 | if ( |
| 29 | detected && |
| 30 | detected !== stored |
| 31 | detected !== lastSentTimezone. |
| 32 | ) { |
| 33 | lastSentTimezone.current = |
| 34 | execute({ timezone: |
| 35 | } |
| 36 | } |
| 37 | sync() |
| 38 | const onVisible = |
| 39 | if (document.visibilityState |
| 40 | sync() |
| 41 | } |
| 42 | } |
| 43 | document.addEventListener('visibilitychange |
| 44 | const id = |
| 45 | return () => |
| 46 | document.removeEventListener('visibilitychange |
| 47 | window.clearInterval(id |
| 48 | } |
| 49 | }, [userId, |
| 50 | |
| 51 | return null |
| 52 | } |