Timezone pickerNew
A searchable IANA timezone picker with live local clocks, exact UTC offset deltas, a spring-driven 24-hour daylight hairline and one-click Detect.
Used forCalendar and booking flowsAccount and workspace settingsCron schedules and billing anchorsDistributed team rosters
Install with the shadcn CLI
$ npxnpx shadcn@latest add https://hairlineui.com/r/timezone-picker.jsonRegistered the namespace? Then it’s shadcn add @hairline/timezone-picker. Set it up
Templates
Need the whole page?
63 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 8 are free.
Where it’s used
Calendar and booking flows
Let invitees pick their local timezone with live wall-clock previews and an immediate daylight check before booking.
Account and workspace settings
Detect the browser timezone in one click or search by city, country, airport code, abbreviation or UTC offset.
Cron schedules and billing anchors
Pair with Cron input so operators know the exact UTC offset and local hour a scheduled job will run.
Distributed team rosters
Render the inline panel inside a sidebar or modal to compare teammate offsets and working-hour overlap.
What it handles for you
A real timezone control has to compute DST-aware offsets without shipping megabytes of zone tables and make local time immediately legible.
- 01
24-hour solar daylight hairline
Highlights night, twilight, daylight and 09:00 to 17:00 working hours with a spring-driven live needle that glides to every highlighted city.
- 02
Zero-dependency Intl engine
Computes live local times, DST-accurate UTC offsets and abbreviations straight from native Intl.DateTimeFormat, updating cleanly on minute boundaries.
- 03
Exact delta from your local time
Displays Local, Same time, +5.5h or -9h on every row so users immediately see how far away a city is.
- 04
Search by city, IANA, abbreviation or offset
Matches New York, Bengaluru, IST, PST, UTC+05:30, airport codes and country names with full ArrowUp/ArrowDown/Home/End/Enter keyboard navigation.
- 05
One-click local Detect
Resolves Intl.DateTimeFormat().resolvedOptions().timeZone and confirms selection with an inline emerald Detected flash.
- 06
Popover and inline modes
Use variant="popover" inside compact forms or variant="inline" directly inside scheduling modals and settings panels.
Overview
Selecting a timezone from an unsearchable list of 400 raw IANA strings forces people to guess offsets and daylight saving rules. TimezonePicker combines a curated 42-city global IANA table with native Intl.DateTimeFormat calculations (zero external timezone bundles) and accepts any valid IANA string passed in. As you hover or step through cities with the keyboard, a spring-driven needle glides across a 24-hour solar daylight hairline marking night, twilight, daytime and 09:00 to 17:00 business hours while live clocks and exact +/-Xh deltas against the browser timezone update in place. One-click Detect snaps directly to the user local timezone, and both popover and inline variants are included.
States
- closed trigger
- Shows the solar phase icon, city, IANA identifier, UTC offset and live local time inside a compact hairline field.
- searching and stepping
- Filtering narrows rows instantaneously while hovering or pressing Arrow keys glides the 24-hour daylight needle to each city solar hour.
- detected
- Pressing Detect snaps straight to the browser timezone and confirms with an emerald Check badge.
- inline panel
- Renders the full searchable card and daylight hairline embedded without a trigger or floating popover.
- reduced motion
- The 24-hour solar needle jumps directly to each timezone hour without spring travel.
Usage
import { TimezonePicker } from "@/components/timezone-picker";<TimezonePicker value={timezone} onChange={(iana) => setTimezone(iana)}/>Depends on lucide-react, installed for you by the CLI along with the keyframes it needs.
Works with
Profile preferences synced with browser detection
Store the canonical IANA string (never a raw UTC offset) so daylight saving changes stay accurate year-round.
"use client";import { useState } from "react";import { TimezonePicker, detectLocalTimezone } from "@/components/timezone-picker";export function ProfileTimezoneField({ initial }: { initial?: string }) { const [iana, setIana] = useState(() => initial ?? detectLocalTimezone()); return ( <div className="space-y-2"> <label className="text-xs font-medium text-foreground">Default timezone</label> <TimezonePicker value={iana} onChange={(nextIana) => setIana(nextIana)} /> </div> );}Props
| Prop | Type | Description |
|---|---|---|
| value / defaultValue / onChange | string / string / (iana, info) => void | Controlled or uncontrolled canonical IANA timezone string. |
| variant | "popover" | "inline"= "popover" | Compact form trigger with floating menu, or always-open embedded panel. |
| hour12 / showDiff / showHorizon / allowDetect | boolean= false / true / true / true | Toggle 12-hour formatting, local offset diff chips, the 24-hour daylight hairline and the Detect button. |
| zones | TimezoneEntry[]= COMMON_TIMEZONES | Override the curated 42-city table; arbitrary valid IANA values passed via value are preserved automatically. |
| getTimezoneInfo / detectLocalTimezone / formatOffsetDiff | exported utility functions | Compute live zone metadata, resolve the browser timezone and format offset differences elsewhere in your app. |
- value / defaultValue / onChange
- string / string / (iana, info) => void
- Controlled or uncontrolled canonical IANA timezone string.
- variant= "popover"
- "popover" | "inline"
- Compact form trigger with floating menu, or always-open embedded panel.
- hour12 / showDiff / showHorizon / allowDetect= false / true / true / true
- boolean
- Toggle 12-hour formatting, local offset diff chips, the 24-hour daylight hairline and the Detect button.
- zones= COMMON_TIMEZONES
- TimezoneEntry[]
- Override the curated 42-city table; arbitrary valid IANA values passed via value are preserved automatically.
- getTimezoneInfo / detectLocalTimezone / formatOffsetDiff
- exported utility functions
- Compute live zone metadata, resolve the browser timezone and format offset differences elsewhere in your app.
Accessibility and motion
- Timers align to the next minute boundary so open pickers update live clocks accurately without running a 1-second interval.
- Because Intl.DateTimeFormat computes offsets for the live Date, DST transitions are reflected automatically with zero static offset bugs.
- Any arbitrary valid IANA string passed in value (even if absent from COMMON_TIMEZONES) is humanized and injected cleanly into the list.
Requirements
React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.
The CLI also installs Text morph.
Source
"use client";import * as React from "react";import { Check, ChevronDown, Clock, Globe, LocateFixed, Moon, Search, Sun, Sunrise, X,} from "lucide-react";import { INTERACTION_FOCUS, INTERACTION_PRESS, createSpring, interactionIcon, useInteractionReducedMotion, type Spring,} from "./ui-interaction-motion";import { TextMorph } from "./text-morph";import { playSound } from "./ui-sounds";/* ───────────────────────────────────────────────────────── * TIMEZONE PICKER: searchable IANA selector with solar hairline * * horizon a 24-hour daylight hairline sits across the picker, * shading night, twilight and daylight bands with a * subtle 09:00–17:00 working-hours mark; a spring-driven * time needle glides smoothly to each highlighted city's * exact local solar hour as you hover or arrow-key * * live uses native Intl.DateTimeFormat with zero timezone * data bloat: live local clocks, accurate DST-aware UTC * offsets, exact +/-Xh delta against your local browser * timezone and instant one-tap Detect * ───────────────────────────────────────────────────────── */export interface TimezoneEntry { /** Canonical IANA identifier (e.g. "America/New_York", "Asia/Kolkata"). */ iana: string; /** Primary city or label (e.g. "New York", "Bengaluru / Mumbai"). */ city: string; /** Country or region label. */ region: string; /** Extra search terms (aliases, airport codes, alternate city names). */ keywords?: string[];}export interface TimezoneInfo { iana: string; offsetMinutes: number; offsetLabel: string; // e.g. "UTC+05:30" or "UTC-05:00" abbr: string; // e.g. "IST", "EST", "GMT" timeText: string; // e.g. "11:15 AM" or "11:15" hourFloat: number; // 0..24 local solar hour phase: "day" | "twilight" | "night"; inWorkHours: boolean;}export interface TimezonePickerProps extends Omit<React.HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange"> { /** Controlled IANA timezone string (e.g. "Europe/London"). */ value?: string; /** Initial uncontrolled IANA timezone string (defaults to browser local timezone). */ defaultValue?: string; /** Called when the user selects a timezone. */ onChange?: (iana: string, info: TimezoneInfo) => void; /** Presentation mode: compact form trigger with popover, or always-open inline panel. */ variant?: "popover" | "inline"; /** Optional custom list of timezones (defaults to curated 42-city global IANA table). */ zones?: TimezoneEntry[]; /** Use 12-hour clock format (default false -> 24-hour crisp monospace). */ hour12?: boolean; /** Show relative +/-Xh difference from the user's browser timezone (default true). */ showDiff?: boolean; /** Show the 24-hour solar daylight hairline bar (default true). */ showHorizon?: boolean; /** Show the one-click "Detect" local timezone button (default true). */ allowDetect?: boolean; /** Accessible label (default "Timezone"). */ label?: string; /** Placeholder when value is empty. */ placeholder?: string; /** Disabled state. */ disabled?: boolean; /** Opt-in Web Audio ticks (from ui-sounds.ts). */ sound?: boolean;}export const COMMON_TIMEZONES: TimezoneEntry[] = [ { iana: "Pacific/Honolulu", city: "Honolulu", region: "United States", keywords: ["hawaii", "hst"] }, { iana: "America/Anchorage", city: "Anchorage", region: "United States", keywords: ["alaska", "akst"] }, { iana: "America/Los_Angeles", city: "San Francisco", region: "United States", keywords: ["los angeles", "seattle", "pacific", "pst", "pdt", "sfo", "lax"] }, { iana: "America/Vancouver", city: "Vancouver", region: "Canada", keywords: ["pacific", "pst", "pdt", "yvr"] }, { iana: "America/Denver", city: "Denver", region: "United States", keywords: ["mountain", "mst", "mdt", "salt lake"] }, { iana: "America/Phoenix", city: "Phoenix", region: "United States", keywords: ["arizona", "mst"] }, { iana: "America/Chicago", city: "Chicago", region: "United States", keywords: ["central", "cst", "cdt", "austin", "dallas"] }, { iana: "America/Mexico_City", city: "Mexico City", region: "Mexico", keywords: ["cdmx", "cst"] }, { iana: "America/New_York", city: "New York", region: "United States", keywords: ["eastern", "est", "edt", "boston", "miami", "nyc"] }, { iana: "America/Toronto", city: "Toronto", region: "Canada", keywords: ["eastern", "est", "edt", "montreal", "yyz"] }, { iana: "America/Bogota", city: "Bogota", region: "Colombia", keywords: ["lima", "cot"] }, { iana: "America/Santiago", city: "Santiago", region: "Chile", keywords: ["clt"] }, { iana: "America/Sao_Paulo", city: "Sao Paulo", region: "Brazil", keywords: ["rio", "brt", "gru"] }, { iana: "America/Argentina/Buenos_Aires", city: "Buenos Aires", region: "Argentina", keywords: ["art", "eze"] }, { iana: "Atlantic/Reykjavik", city: "Reykjavik", region: "Iceland", keywords: ["gmt", "utc"] }, { iana: "UTC", city: "UTC", region: "Coordinated Universal Time", keywords: ["gmt", "zulu", "universal"] }, { iana: "Europe/London", city: "London", region: "United Kingdom", keywords: ["uk", "gmt", "bst", "lhr", "dublin"] }, { iana: "Europe/Lisbon", city: "Lisbon", region: "Portugal", keywords: ["wet", "west"] }, { iana: "Europe/Paris", city: "Paris", region: "France", keywords: ["cet", "cest", "cdg"] }, { iana: "Europe/Berlin", city: "Berlin", region: "Germany", keywords: ["cet", "cest", "munich", "frankfurt"] }, { iana: "Europe/Amsterdam", city: "Amsterdam", region: "Netherlands", keywords: ["cet", "cest", "ams"] }, { iana: "Europe/Zurich", city: "Zurich", region: "Switzerland", keywords: ["geneva", "cet", "cest"] }, { iana: "Europe/Madrid", city: "Madrid", region: "Spain", keywords: ["barcelona", "cet", "cest"] }, { iana: "Europe/Stockholm", city: "Stockholm", region: "Sweden", keywords: ["oslo", "copenhagen", "cet"] }, { iana: "Europe/Warsaw", city: "Warsaw", region: "Poland", keywords: ["prague", "cet", "cest"] }, { iana: "Africa/Lagos", city: "Lagos", region: "Nigeria", keywords: ["wat"] }, { iana: "Africa/Johannesburg", city: "Johannesburg", region: "South Africa", keywords: ["cape town", "sast"] }, { iana: "Africa/Cairo", city: "Cairo", region: "Egypt", keywords: ["eet"] }, { iana: "Europe/Athens", city: "Athens", region: "Greece", keywords: ["helsinki", "bucharest", "eet", "eest"] }, { iana: "Europe/Istanbul", city: "Istanbul", region: "Turkey", keywords: ["trt"] }, { iana: "Asia/Riyadh", city: "Riyadh", region: "Saudi Arabia", keywords: ["ast", "nairobi"] }, { iana: "Asia/Dubai", city: "Dubai", region: "United Arab Emirates", keywords: ["uae", "abu dhabi", "gst", "dxb"] }, { iana: "Asia/Karachi", city: "Karachi", region: "Pakistan", keywords: ["lahore", "pkt"] }, { iana: "Asia/Kolkata", city: "Bengaluru / Mumbai", region: "India", keywords: ["india", "delhi", "kolkata", "calcutta", "ist", "blr", "bom"] }, { iana: "Asia/Kathmandu", city: "Kathmandu", region: "Nepal", keywords: ["npt"] }, { iana: "Asia/Dhaka", city: "Dhaka", region: "Bangladesh", keywords: ["bst"] }, { iana: "Asia/Bangkok", city: "Bangkok", region: "Thailand", keywords: ["jakarta", "ho chi minh", "ict"] }, { iana: "Asia/Singapore", city: "Singapore", region: "Singapore", keywords: ["sgt", "sin", "kuala lumpur"] }, { iana: "Asia/Hong_Kong", city: "Hong Kong", region: "China", keywords: ["hkt", "shanghai", "beijing", "taipei", "cst"] }, { iana: "Asia/Tokyo", city: "Tokyo", region: "Japan", keywords: ["osaka", "jst", "tyo", "hnd"] }, { iana: "Asia/Seoul", city: "Seoul", region: "South Korea", keywords: ["korea", "kst", "icn"] }, { iana: "Australia/Adelaide", city: "Adelaide", region: "Australia", keywords: ["acst", "acdt"] }, { iana: "Australia/Sydney", city: "Sydney", region: "Australia", keywords: ["melbourne", "aest", "aedt", "syd"] }, { iana: "Pacific/Auckland", city: "Auckland", region: "New Zealand", keywords: ["wellington", "nzst", "nzdt"] },];const IANA_ALIASES: Record<string, string> = { "Asia/Calcutta": "Asia/Kolkata", "Asia/Saigon": "Asia/Bangkok", "Asia/Katmandu": "Asia/Kathmandu", "Europe/Kiev": "Europe/Kyiv", "US/Eastern": "America/New_York", "US/Central": "America/Chicago", "US/Mountain": "America/Denver", "US/Pacific": "America/Los_Angeles", "Etc/UTC": "UTC", "Etc/GMT": "UTC",};export function detectLocalTimezone(): string { try { const raw = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; return IANA_ALIASES[raw] ?? raw; } catch { return "UTC"; }}function parseOffsetMinutes(iana: string, now: Date): number { try { // Compute exact offset by formatting UTC parts vs local zone parts const fmt = new Intl.DateTimeFormat("en-US", { timeZone: iana, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", }); const parts = fmt.formatToParts(now); const get = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0); const asUtc = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour"), get("minute"), get("second")); const utcTrunc = Math.floor(now.getTime() / 1000) * 1000; return Math.round((asUtc - utcTrunc) / 60000); } catch { return 0; }}function formatUtcOffset(offsetMinutes: number): string { const sign = offsetMinutes >= 0 ? "+" : "-"; const abs = Math.abs(offsetMinutes); const hh = String(Math.floor(abs / 60)).padStart(2, "0"); const mm = String(abs % 60).padStart(2, "0"); return `UTC${sign}${hh}:${mm}`;}export function getTimezoneInfo(iana: string, now = new Date(), hour12 = false): TimezoneInfo { const offsetMinutes = parseOffsetMinutes(iana, now); const offsetLabel = formatUtcOffset(offsetMinutes); let abbr = offsetLabel; let timeText = "00:00"; let hourFloat = 12; try { const abbrParts = new Intl.DateTimeFormat("en-US", { timeZone: iana, timeZoneName: "short", }).formatToParts(now); const tzName = abbrParts.find((p) => p.type === "timeZoneName")?.value; if (tzName) abbr = tzName; timeText = new Intl.DateTimeFormat("en-US", { timeZone: iana, hour: "2-digit", minute: "2-digit", hour12, }).format(now); const hmParts = new Intl.DateTimeFormat("en-US", { timeZone: iana, hour: "2-digit", minute: "2-digit", hourCycle: "h23", }).formatToParts(now); const h = Number(hmParts.find((p) => p.type === "hour")?.value ?? 12); const m = Number(hmParts.find((p) => p.type === "minute")?.value ?? 0); hourFloat = (h % 24) + m / 60; } catch { // Fallback to UTC defaults } const phase: TimezoneInfo["phase"] = hourFloat >= 7.5 && hourFloat < 18 ? "day" : (hourFloat >= 5.5 && hourFloat < 7.5) || (hourFloat >= 18 && hourFloat < 20.5) ? "twilight" : "night"; const inWorkHours = hourFloat >= 9 && hourFloat < 17; return { iana, offsetMinutes, offsetLabel, abbr, timeText, hourFloat, phase, inWorkHours, };}export function formatOffsetDiff(targetOffsetMin: number, localOffsetMin: number, isSameIana = false): string { const diffMin = targetOffsetMin - localOffsetMin; if (diffMin === 0) return isSameIana ? "Local" : "Same time"; const sign = diffMin > 0 ? "+" : "-"; const abs = Math.abs(diffMin); const hours = abs / 60; if (abs % 60 === 0) return `${sign}${hours}h`; if (abs % 30 === 0) return `${sign}${hours.toFixed(1)}h`; return `${sign}${Math.floor(abs / 60)}h${abs % 60}m`;}function humanizeIana(iana: string): TimezoneEntry { const parts = iana.split("/"); const city = (parts[parts.length - 1] ?? iana).replace(/_/g, " "); const region = parts.length > 1 ? parts[0].replace(/_/g, " ") : "Timezone"; return { iana, city, region };}function PhaseIcon({ phase, className = "size-3.5" }: { phase: TimezoneInfo["phase"]; className?: string }) { if (phase === "day") { return <Sun className={`${className} text-amber-500`} strokeWidth={2} />; } if (phase === "twilight") { return <Sunrise className={`${className} text-orange-500/85`} strokeWidth={2} />; } return <Moon className={`${className} text-indigo-400`} strokeWidth={2} />;}/** 24-hour solar daylight hairline with spring-driven local hour cursor needle. */function DaylightHorizon({ info, city, diffLabel, reduced,}: { info: TimezoneInfo; city: string; diffLabel?: string; reduced: boolean;}) { const needleRef = React.useRef<HTMLDivElement | null>(null); const currentPctRef = React.useRef((info.hourFloat / 24) * 100); const springRef = React.useRef<Spring | null>(null); React.useEffect(() => { const targetPct = Math.max(0, Math.min(100, (info.hourFloat / 24) * 100)); springRef.current?.stop(); const el = needleRef.current; if (!el) return; if (reduced) { currentPctRef.current = targetPct; el.style.left = `${targetPct.toFixed(2)}%`; return; } const sp = createSpring( currentPctRef.current, { stiffness: 310, damping: 26 }, () => { const v = sp.get(); currentPctRef.current = v; if (needleRef.current) needleRef.current.style.left = `${v.toFixed(2)}%`; }, 0.05, ); sp.set(targetPct); springRef.current = sp; return () => sp.stop(); }, [info.hourFloat, reduced]); return ( <div className="border-b border-border/80 bg-muted/20 px-3 py-2.5" data-daylight-horizon="true"> <div className="mb-1.5 flex items-center justify-between gap-2 text-[11px]"> <div className="flex min-w-0 items-center gap-1.5"> <PhaseIcon phase={info.phase} className="size-3 shrink-0" /> <span className="truncate font-medium text-foreground"> <TextMorph>{city}</TextMorph> </span> <span className="font-mono text-[10.5px] text-muted-foreground"> <TextMorph>{info.offsetLabel}</TextMorph> </span> </div> <div className="flex shrink-0 items-center gap-1.5 font-mono tabular-nums"> <span className="font-semibold text-foreground"> <TextMorph duration={360}>{info.timeText}</TextMorph> </span> {diffLabel && ( <span className="rounded-[5px] border border-border/80 bg-background px-1.5 py-0 text-[10px] text-muted-foreground"> <TextMorph>{diffLabel}</TextMorph> </span> )} </div> </div> {/* 24-hour solar daylight strip: night -> dawn -> daylight (with 09–17 work tint) -> dusk -> night */} <div className="relative h-3 w-full"> <div aria-hidden="true" className="absolute inset-x-0 top-1/2 h-[4px] -translate-y-1/2 overflow-hidden rounded-full border border-border/60" style={{ background: "linear-gradient(90deg, rgba(99,102,241,0.22) 0%, rgba(99,102,241,0.18) 22%, rgba(245,158,11,0.38) 28%, rgba(251,191,36,0.45) 50%, rgba(249,115,22,0.36) 76%, rgba(99,102,241,0.2) 84%, rgba(99,102,241,0.22) 100%)", }} > {/* 09:00–17:00 business-hours hairline segment (37.5% to 70.83%) */} <div className="absolute inset-y-0 border-x border-foreground/30 bg-foreground/[0.08]" style={{ left: "37.5%", width: "33.33%" }} /> </div> {/* Live spring-driven needle */} <div ref={needleRef} aria-hidden="true" className="pointer-events-none absolute top-1/2 h-3 w-[2px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-foreground shadow-[0_0_0_1.5px_var(--card)]" style={{ left: `${((info.hourFloat / 24) * 100).toFixed(2)}%` }} /> </div> <div className="mt-1 flex items-center justify-between font-mono text-[9.5px] tabular-nums text-muted-foreground/70"> <span>00:00</span> <span>06:00</span> <span>12:00</span> <span>18:00</span> <span>24:00</span> </div> </div> );}const noopSubscribe = () => () => {};const useHydrated = () => React.useSyncExternalStore(noopSubscribe, () => true, () => false);const SSR_EPOCH = new Date(Date.UTC(2026, 0, 1, 12, 0, 0));/** Minute-aligned live clock tick, deterministic during SSR/hydration so visitor timezones never trigger #418. */function useMinuteNow(hydrated: boolean): Date { const [tickNow, setTickNow] = React.useState<Date | null>(null); React.useEffect(() => { if (!hydrated) return; let intervalId = 0; const raf = window.requestAnimationFrame(() => setTickNow(new Date())); const msUntilNextMin = 60_000 - (Date.now() % 60_000) + 120; const timeoutId = window.setTimeout(() => { setTickNow(new Date()); intervalId = window.setInterval(() => setTickNow(new Date()), 60_000); }, msUntilNextMin); return () => { window.cancelAnimationFrame(raf); window.clearTimeout(timeoutId); window.clearInterval(intervalId); }; }, [hydrated]); return hydrated && tickNow ? tickNow : SSR_EPOCH;}export function TimezonePicker({ value: controlledValue, defaultValue, onChange, variant = "popover", zones = COMMON_TIMEZONES, hour12 = false, showDiff = true, showHorizon = true, allowDetect = true, label = "Timezone", placeholder = "Select timezone", disabled = false, sound = false, className = "", ...props}: TimezonePickerProps) { const reduced = useInteractionReducedMotion(); const hydrated = useHydrated(); const now = useMinuteNow(hydrated); const localIana = React.useMemo(() => (hydrated ? detectLocalTimezone() : "UTC"), [hydrated]); const localOffsetMin = React.useMemo(() => parseOffsetMinutes(localIana, now), [localIana, now]); const [ownValue, setOwnValue] = React.useState<string | null>(() => defaultValue ?? null); const selectedIana = controlledValue !== undefined ? controlledValue : (ownValue ?? localIana); const [open, setOpen] = React.useState(variant === "inline"); const [query, setQuery] = React.useState(""); const [activeIdx, setActiveIdx] = React.useState(() => { const init = controlledValue ?? defaultValue ?? localIana; const idx = zones.findIndex((z) => z.iana === init); return idx >= 0 ? idx : 0; }); const [detectedFlash, setDetectedFlash] = React.useState(false); const rootRef = React.useRef<HTMLDivElement | null>(null); const triggerRef = React.useRef<HTMLButtonElement | null>(null); const searchRef = React.useRef<HTMLInputElement | null>(null); const listRef = React.useRef<HTMLDivElement | null>(null); const detectTimerRef = React.useRef(0); React.useEffect( () => () => { window.clearTimeout(detectTimerRef.current); }, [], ); // Close popover on outside click / Escape React.useEffect(() => { if (variant === "inline" || !open) return; const onDown = (e: MouseEvent) => { if (rootRef.current && !rootRef.current.contains(e.target as Node)) setOpen(false); }; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { setOpen(false); triggerRef.current?.focus(); } }; document.addEventListener("mousedown", onDown); document.addEventListener("keydown", onKey); return () => { document.removeEventListener("mousedown", onDown); document.removeEventListener("keydown", onKey); }; }, [open, variant]); // Ensure both selectedIana and browser localIana exist in the browsable catalogue const allEntries = React.useMemo(() => { const map = new Map<string, TimezoneEntry>(); for (const z of zones) map.set(z.iana, z); if (selectedIana && !map.has(selectedIana)) map.set(selectedIana, humanizeIana(selectedIana)); if (localIana && !map.has(localIana)) map.set(localIana, humanizeIana(localIana)); return Array.from(map.values()).map((entry) => ({ entry, info: getTimezoneInfo(entry.iana, now, hour12), })); }, [zones, selectedIana, localIana, now, hour12]); const filtered = React.useMemo(() => { const q = query.trim().toLowerCase(); if (!q) return allEntries; return allEntries.filter(({ entry, info }) => { const hay = [ entry.city, entry.region, entry.iana, entry.iana.replace(/_/g, " "), info.abbr, info.offsetLabel, ...(entry.keywords ?? []), ] .join(" ") .toLowerCase(); return hay.includes(q); }); }, [allEntries, query]); const selectedRecord = React.useMemo( () => allEntries.find((r) => r.entry.iana === selectedIana) ?? allEntries[0], [allEntries, selectedIana], ); const clampedIdx = filtered.length > 0 ? Math.min(activeIdx, filtered.length - 1) : 0; const previewRecord = filtered[clampedIdx] ?? selectedRecord; const commitSelection = React.useCallback( (iana: string, info: TimezoneInfo) => { if (controlledValue === undefined) setOwnValue(iana); onChange?.(iana, info); if (sound) playSound("tick", 0.3); if (variant === "popover") { setOpen(false); setQuery(""); } }, [controlledValue, onChange, sound, variant], ); const handleDetectLocal = () => { const detected = detectLocalTimezone(); const info = getTimezoneInfo(detected, now, hour12); if (controlledValue === undefined) setOwnValue(detected); onChange?.(detected, info); setQuery(""); setDetectedFlash(true); if (sound) playSound("success", 0.34); window.clearTimeout(detectTimerRef.current); detectTimerRef.current = window.setTimeout(() => setDetectedFlash(false), 1600); }; const handleOpenPopover = () => { if (disabled) return; setOpen((prev) => { const next = !prev; if (next) { setQuery(""); const idx = allEntries.findIndex((r) => r.entry.iana === selectedIana); setActiveIdx(idx >= 0 ? idx : 0); window.requestAnimationFrame(() => searchRef.current?.focus()); } return next; }); }; const handleListKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (filtered.length === 0) return; if (e.key === "ArrowDown") { e.preventDefault(); setActiveIdx((i) => (i + 1) % filtered.length); } else if (e.key === "ArrowUp") { e.preventDefault(); setActiveIdx((i) => (i - 1 + filtered.length) % filtered.length); } else if (e.key === "Home") { e.preventDefault(); setActiveIdx(0); } else if (e.key === "End") { e.preventDefault(); setActiveIdx(filtered.length - 1); } else if (e.key === "Enter") { e.preventDefault(); const chosen = filtered[clampedIdx]; if (chosen) commitSelection(chosen.entry.iana, chosen.info); } }; const panelBody = ( <div className={`flex w-full flex-col overflow-hidden rounded-[14px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${ variant === "popover" ? "shadow-[0_14px_38px_-10px_rgb(0_0_0/0.26)] dark:shadow-[0_16px_42px_-10px_rgb(0_0_0/0.62)]" : "" }`} > {/* Search + Detect bar */} <div className="flex items-center gap-1.5 border-b border-border/80 px-2.5 py-2"> <Search className="size-3.5 shrink-0 text-muted-foreground" strokeWidth={2} /> <input ref={searchRef} type="text" role="combobox" aria-expanded={variant === "inline" ? true : open} aria-controls="tz-listbox" aria-label="Search city, timezone or UTC offset" placeholder="Search city, IANA or UTC+5:30…" value={query} onChange={(e) => { setQuery(e.currentTarget.value); setActiveIdx(0); }} onKeyDown={handleListKeyDown} className="h-6 min-w-0 flex-1 bg-transparent text-[12.5px] text-foreground placeholder:text-muted-foreground/55 focus:outline-none" /> {query && ( <button type="button" aria-label="Clear search" onClick={() => { setQuery(""); setActiveIdx(0); searchRef.current?.focus(); }} className="inline-flex size-5 cursor-pointer items-center justify-center rounded-[5px] text-muted-foreground hover:bg-accent hover:text-foreground" > <X className="size-3" strokeWidth={2} /> </button> )} {allowDetect && ( <button type="button" onClick={handleDetectLocal} title={`Use detected timezone (${localIana})`} className={`inline-flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-[7px] border border-border bg-background px-2 text-[11px] font-medium hover:bg-accent ${ detectedFlash ? "border-emerald-500/40 text-emerald-700 dark:text-emerald-300" : "text-muted-foreground hover:text-foreground" } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`} > <span className="relative flex size-3 shrink-0 items-center justify-center"> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(!detectedFlash, reduced)}> <LocateFixed className="size-3" strokeWidth={2} /> </span> <span aria-hidden="true" className="absolute inset-0 flex items-center justify-center" style={interactionIcon(detectedFlash, reduced)}> <Check className="size-3" strokeWidth={2.3} /> </span> </span> <TextMorph>{detectedFlash ? "Detected" : "Detect"}</TextMorph> </button> )} </div> {/* Signature 24-hour solar daylight hairline reacting to the highlighted row */} {showHorizon && previewRecord && ( <DaylightHorizon info={previewRecord.info} city={previewRecord.entry.city} diffLabel={ showDiff ? formatOffsetDiff(previewRecord.info.offsetMinutes, localOffsetMin, previewRecord.entry.iana === localIana) : undefined } reduced={reduced} /> )} {/* Virtual-clean scrollable listbox */} <div ref={listRef} id="tz-listbox" role="listbox" aria-label={label} className="max-h-[264px] overflow-y-auto p-1" > {filtered.length === 0 ? ( <div className="flex flex-col items-center justify-center gap-1 py-7 text-center text-[12px] text-muted-foreground"> <Globe className="size-4 opacity-50" strokeWidth={1.8} /> <span>No timezones matching “{query}”</span> </div> ) : ( filtered.map(({ entry, info }, idx) => { const isSelected = entry.iana === selectedIana; const isActive = idx === clampedIdx; const diff = showDiff ? formatOffsetDiff(info.offsetMinutes, localOffsetMin, entry.iana === localIana) : null; return ( <button key={entry.iana} type="button" role="option" aria-selected={isSelected} data-tz-option={entry.iana} onMouseEnter={() => setActiveIdx(idx)} onClick={() => commitSelection(entry.iana, info)} className={`flex w-full cursor-pointer items-center justify-between gap-2.5 rounded-[9px] px-2.5 py-2 text-left transition-colors duration-75 ${ isActive ? "bg-accent text-foreground" : "text-foreground/90 hover:bg-accent/60" }`} > <div className="flex min-w-0 items-center gap-2"> <PhaseIcon phase={info.phase} className="size-3.5 shrink-0" /> <div className="min-w-0"> <div className="flex items-center gap-1.5"> <span className="truncate text-[12.5px] font-medium text-foreground">{entry.city}</span> <span className="truncate text-[11px] text-muted-foreground">{entry.region}</span> </div> <div className="flex items-center gap-1.5 font-mono text-[10.5px] text-muted-foreground/85"> <span>{entry.iana}</span> <span>·</span> <span>{info.offsetLabel}</span> </div> </div> </div> <div className="flex shrink-0 items-center gap-2"> <div className="text-right font-mono tabular-nums"> <div className="text-[12px] font-medium text-foreground">{info.timeText}</div> {diff && <div className="text-[10px] text-muted-foreground">{diff}</div>} </div> <span className="inline-flex size-4 items-center justify-center"> {isSelected && <Check className="size-3.5 text-foreground" strokeWidth={2.3} />} </span> </div> </button> ); }) )} </div> </div> ); if (variant === "inline") { return ( <div ref={rootRef} role="region" aria-label={label} data-timezone={selectedIana} className={`w-full max-w-[440px] ${className}`} {...props} > {panelBody} </div> ); } return ( <div ref={rootRef} data-timezone={selectedIana} className={`relative w-full max-w-[390px] ${className}`} {...props} > <button ref={triggerRef} type="button" disabled={disabled} aria-haspopup="listbox" aria-expanded={open} aria-label={label} onClick={handleOpenPopover} className={`flex h-11 w-full cursor-pointer items-center justify-between gap-2 overflow-hidden rounded-[12px] border border-border bg-card px-3 text-left text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] transition-colors hover:border-foreground/20 disabled:cursor-not-allowed disabled:opacity-50 dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${INTERACTION_FOCUS}`} > {selectedRecord ? ( <> <span className="flex min-w-0 flex-1 items-center gap-2.5 overflow-hidden"> <PhaseIcon phase={selectedRecord.info.phase} className="size-3.5 shrink-0" /> <span className="min-w-0 flex-1 overflow-hidden"> <span className="block truncate text-[13px] font-medium leading-tight text-foreground"> <TextMorph animateWidth={false}>{selectedRecord.entry.city}</TextMorph> </span> <span className="block truncate font-mono text-[10.5px] leading-tight text-muted-foreground"> <TextMorph animateWidth={false}>{`${selectedRecord.info.offsetLabel} · ${selectedRecord.entry.iana}`}</TextMorph> </span> </span> </span> <span className="flex shrink-0 items-center gap-2"> <span className="inline-flex items-center gap-1 rounded-[7px] border border-border/80 bg-background px-2 py-0.5 font-mono text-[11.5px] font-medium tabular-nums text-foreground"> <Clock className="size-3 text-muted-foreground" strokeWidth={2} /> <TextMorph duration={360}>{selectedRecord.info.timeText}</TextMorph> </span> <ChevronDown className={`size-4 text-muted-foreground transition-transform duration-150 ${open ? "rotate-180" : ""}`} strokeWidth={2} /> </span> </> ) : ( <> <span className="text-[13px] text-muted-foreground">{placeholder}</span> <ChevronDown className="size-4 text-muted-foreground" strokeWidth={2} /> </> )} </button> {open && <div className="absolute left-0 top-[calc(100%+6px)] z-40 w-full">{panelBody}</div>} </div> );}export default TimezonePicker;Registry item: /r/timezone-picker.json


