{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"open-now-badge","type":"registry:ui","title":"Open now badge","description":"Live open or closed pill computed from weekly hours in the business's own time zone.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/items/open-now-badge/open-now-badge.tsx","type":"registry:ui","target":"components/facade/open-now-badge.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------\n   Hours model\n------------------------------------------------------------------- */\n\nexport type DayKey = \"sun\" | \"mon\" | \"tue\" | \"wed\" | \"thu\" | \"fri\" | \"sat\";\n\n/** 24h \"HH:mm\". A close time earlier than (or equal to) open runs past midnight. Use \"24:00\" for midnight. */\nexport interface TimeRange {\n  open: string;\n  close: string;\n}\n\n/** Missing day, `null` or an empty array means closed. Multiple ranges = split hours. */\nexport type WeeklyHours = Partial<Record<DayKey, TimeRange[] | null>>;\n\nexport interface OpenStatus {\n  isOpen: boolean;\n  /** True when open and closing within `closingSoonMinutes`. */\n  closingSoon: boolean;\n  /** Short label for the next change, e.g. \"closes 6 PM\" or \"opens 9 AM tomorrow\". */\n  detail: string;\n  /** Minutes until the next open/close change, null if never. */\n  minutesUntilChange: number | null;\n}\n\nconst DAY_KEYS: DayKey[] = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"];\nconst SHORT_DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\nconst WEEK = 7 * 1440;\n\nfunction toMinutes(t: string): number {\n  const [h, m = \"0\"] = t.split(\":\");\n  return Number(h) * 60 + Number(m);\n}\n\nexport function formatClock(totalMinutes: number): string {\n  const mins = ((totalMinutes % 1440) + 1440) % 1440;\n  const h = Math.floor(mins / 60);\n  const m = mins % 60;\n  if (h === 0 && m === 0) return \"midnight\";\n  if (h === 12 && m === 0) return \"noon\";\n  const period = h < 12 ? \"AM\" : \"PM\";\n  const h12 = h % 12 || 12;\n  return m ? `${h12}:${String(m).padStart(2, \"0\")} ${period}` : `${h12} ${period}`;\n}\n\n/** Weekday index (0 = Sunday) and minutes since midnight in the given IANA time zone. */\nexport function getZonedNow(date: Date, timeZone: string): { day: number; minutes: number } {\n  const parts = new Intl.DateTimeFormat(\"en-US\", {\n    timeZone,\n    weekday: \"short\",\n    hour: \"numeric\",\n    minute: \"numeric\",\n    hourCycle: \"h23\",\n  }).formatToParts(date);\n  const get = (type: Intl.DateTimeFormatPartTypes) => parts.find((p) => p.type === type)?.value ?? \"0\";\n  const day = Math.max(0, SHORT_DAYS.indexOf(get(\"weekday\")));\n  const minutes = (Number(get(\"hour\")) % 24) * 60 + Number(get(\"minute\"));\n  return { day, minutes };\n}\n\nfunction weekIntervals(hours: WeeklyHours): Array<[number, number]> {\n  const out: Array<[number, number]> = [];\n  DAY_KEYS.forEach((key, d) => {\n    for (const r of hours[key] ?? []) {\n      const s = toMinutes(r.open);\n      let e = toMinutes(r.close);\n      if (e <= s) e += 1440;\n      out.push([d * 1440 + s, d * 1440 + e]);\n    }\n  });\n  return out.sort((a, b) => a[0] - b[0]);\n}\n\nexport function getOpenStatus(\n  hours: WeeklyHours,\n  timeZone: string,\n  date: Date = new Date(),\n  closingSoonMinutes = 60,\n): OpenStatus {\n  const intervals = weekIntervals(hours);\n  if (intervals.length === 0) {\n    return { isOpen: false, closingSoon: false, detail: \"temporarily closed\", minutesUntilChange: null };\n  }\n  const { day, minutes } = getZonedNow(date, timeZone);\n  const now = day * 1440 + minutes;\n\n  /** Remaining minutes of the interval covering week-minute `t`, or null. */\n  const remainingAt = (t: number): number | null => {\n    for (const [s, e] of intervals) {\n      if (t >= s && t < e) return e - t;\n      // Saturday night ranges that spill into Sunday morning.\n      if (t + WEEK >= s && t + WEEK < e) return e - (t + WEEK);\n    }\n    return null;\n  };\n\n  const first = remainingAt(now);\n  if (first !== null) {\n    // Follow back-to-back ranges (e.g. 24h days) to find the real close time.\n    let end = now + first;\n    for (let i = 0; i < 14; i++) {\n      const more = remainingAt(end % WEEK);\n      if (more === null || more <= 0) break;\n      end += more;\n      if (end - now >= WEEK) {\n        return { isOpen: true, closingSoon: false, detail: \"open 24 hours\", minutesUntilChange: null };\n      }\n    }\n    const until = end - now;\n    const dayDiff = Math.floor(end / 1440) - day;\n    const when = formatClock(end);\n    const detail =\n      dayDiff <= 0 || (dayDiff === 1 && end % 1440 <= 360)\n        ? `closes ${when}`\n        : `closes ${SHORT_DAYS[(day + dayDiff) % 7]} ${when}`;\n    return { isOpen: true, closingSoon: until <= closingSoonMinutes, detail, minutesUntilChange: until };\n  }\n\n  let best: number | null = null;\n  for (const [s] of intervals) {\n    const delta = (((s - now) % WEEK) + WEEK) % WEEK || WEEK;\n    if (best === null || delta < best) best = delta;\n  }\n  const opensAt = now + (best ?? 0);\n  const dayDiff = Math.floor(opensAt / 1440) - day;\n  const when = formatClock(opensAt);\n  const detail =\n    dayDiff === 0\n      ? `opens ${when}`\n      : dayDiff === 1\n        ? `opens ${when} tomorrow`\n        : `opens ${SHORT_DAYS[(day + dayDiff) % 7]} ${when}`;\n  return { isOpen: false, closingSoon: false, detail, minutesUntilChange: best };\n}\n\n/* ------------------------------------------------------------------\n   Component\n------------------------------------------------------------------- */\n\nexport interface OpenNowBadgeProps {\n  hours: WeeklyHours;\n  /** IANA time zone of the business, e.g. \"America/Chicago\". */\n  timeZone: string;\n  /** Show the amber \"Closing soon\" state this many minutes before close. */\n  closingSoonMinutes?: number;\n  size?: \"sm\" | \"md\";\n  className?: string;\n}\n\nexport function OpenNowBadge({\n  hours,\n  timeZone,\n  closingSoonMinutes = 60,\n  size = \"md\",\n  className,\n}: OpenNowBadgeProps) {\n  // Time depends on the visitor's clock, so only compute after mount.\n  const [now, setNow] = React.useState<Date | null>(null);\n\n  React.useEffect(() => {\n    setNow(new Date());\n    const id = window.setInterval(() => setNow(new Date()), 30_000);\n    return () => window.clearInterval(id);\n  }, []);\n\n  const status = React.useMemo(\n    () => (now ? getOpenStatus(hours, timeZone, now, closingSoonMinutes) : null),\n    [now, hours, timeZone, closingSoonMinutes],\n  );\n\n  const tone = !status ? \"idle\" : status.isOpen ? (status.closingSoon ? \"soon\" : \"open\") : \"closed\";\n  const headline = !status ? \"\" : status.isOpen ? (status.closingSoon ? \"Closing soon\" : \"Open now\") : \"Closed\";\n\n  return (\n    <span\n      role=\"status\"\n      aria-live=\"polite\"\n      className={cn(\n        \"inline-flex items-center gap-2 rounded-full bg-muted text-foreground\",\n        size === \"sm\" ? \"h-7 px-2.5 text-xs\" : \"h-8 px-3.5 text-sm\",\n        className,\n      )}\n    >\n      <span className=\"relative flex size-2 shrink-0\" aria-hidden>\n        {(tone === \"open\" || tone === \"soon\") && (\n          <span\n            className={cn(\n              \"absolute inset-0 rounded-full animate-ping-slow motion-reduce:animate-none\",\n              tone === \"open\" ? \"bg-success/70\" : \"bg-warning/70\",\n            )}\n          />\n        )}\n        <span\n          className={cn(\n            \"relative size-2 rounded-full transition-colors duration-500\",\n            tone === \"open\" && \"bg-success\",\n            tone === \"soon\" && \"bg-warning\",\n            tone === \"closed\" && \"bg-muted-foreground/50\",\n            tone === \"idle\" && \"bg-muted-foreground/25\",\n          )}\n        />\n      </span>\n      <AnimatePresence mode=\"wait\" initial={false}>\n        {status ? (\n          <motion.span\n            key={`${headline}-${status.detail}`}\n            initial={{ opacity: 0, y: 4 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={{ opacity: 0, y: -4 }}\n            transition={{ duration: 0.35, ease: [0.16, 1, 0.3, 1] }}\n            className=\"flex items-center gap-1.5 whitespace-nowrap\"\n          >\n            <span\n              className={cn(\n                \"font-medium\",\n                tone === \"open\" && \"text-success\",\n                tone === \"soon\" && \"text-warning\",\n                tone === \"closed\" && \"text-foreground\",\n              )}\n            >\n              {headline}\n            </span>\n            <span className=\"text-muted-foreground/60\" aria-hidden>\n              ·\n            </span>\n            <span className=\"text-muted-foreground\">{status.detail}</span>\n          </motion.span>\n        ) : (\n          <span key=\"placeholder\" className=\"flex items-center\">\n            <span\n              aria-hidden\n              className=\"h-3 w-36 rounded-full bg-foreground/[0.06]\"\n            />\n            <span className=\"sr-only\">Checking hours</span>\n          </span>\n        )}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport default OpenNowBadge;\n"}],"categories":["local-business"],"meta":{"tier":"free","demo":"\"use client\";\n\nimport { MapPin, Star } from \"lucide-react\";\nimport { OpenNowBadge, type WeeklyHours } from \"./open-now-badge\";\n\nconst coffee: WeeklyHours = {\n  mon: [{ open: \"06:30\", close: \"19:00\" }],\n  tue: [{ open: \"06:30\", close: \"19:00\" }],\n  wed: [{ open: \"06:30\", close: \"19:00\" }],\n  thu: [{ open: \"06:30\", close: \"19:00\" }],\n  fri: [{ open: \"06:30\", close: \"20:00\" }],\n  sat: [{ open: \"07:30\", close: \"20:00\" }],\n  sun: [{ open: \"07:30\", close: \"16:00\" }],\n};\n\nconst dental: WeeklyHours = {\n  mon: [{ open: \"08:00\", close: \"17:00\" }],\n  tue: [{ open: \"08:00\", close: \"17:00\" }],\n  wed: [{ open: \"08:00\", close: \"12:00\" }, { open: \"13:00\", close: \"19:00\" }],\n  thu: [{ open: \"08:00\", close: \"17:00\" }],\n  fri: [{ open: \"08:00\", close: \"14:00\" }],\n};\n\nconst tacos: WeeklyHours = {\n  mon: [{ open: \"11:00\", close: \"23:00\" }],\n  tue: [{ open: \"11:00\", close: \"23:00\" }],\n  wed: [{ open: \"11:00\", close: \"23:00\" }],\n  thu: [{ open: \"11:00\", close: \"01:00\" }],\n  fri: [{ open: \"11:00\", close: \"03:00\" }],\n  sat: [{ open: \"10:00\", close: \"03:00\" }],\n  sun: [{ open: \"10:00\", close: \"22:00\" }],\n};\n\nconst places = [\n  {\n    name: \"Ember & Rye Coffee\",\n    kind: \"Coffee shop\",\n    where: \"South Congress, Austin\",\n    rating: \"4.8\",\n    hours: coffee,\n    tz: \"America/Chicago\",\n    initials: \"ER\",\n  },\n  {\n    name: \"Cherry Creek Family Dental\",\n    kind: \"Dentist\",\n    where: \"Cherry Creek, Denver\",\n    rating: \"4.9\",\n    hours: dental,\n    tz: \"America/Denver\",\n    initials: \"CC\",\n  },\n  {\n    name: \"La Pequeña Taquería\",\n    kind: \"Mexican restaurant\",\n    where: \"Wynwood, Miami\",\n    rating: \"4.7\",\n    hours: tacos,\n    tz: \"America/New_York\",\n    initials: \"LP\",\n  },\n];\n\nexport default function Demo() {\n  return (\n    <div className=\"mx-auto w-full max-w-xl rounded-[28px] bg-muted p-2\">\n      {places.map((p) => (\n        <article\n          key={p.name}\n          className=\"flex flex-col gap-4 rounded-[22px] p-4 transition-colors hover:bg-foreground/[0.03] sm:flex-row sm:items-center sm:px-5\"\n        >\n          <div className=\"flex min-w-0 flex-1 items-center gap-3.5\">\n            <div className=\"grid size-11 shrink-0 place-items-center rounded-full bg-background font-display text-sm font-semibold text-foreground dark:bg-foreground/[0.1]\">\n              {p.initials}\n            </div>\n            <div className=\"min-w-0\">\n              <h3 className=\"truncate text-[15px] font-medium tracking-[-0.01em]\">{p.name}</h3>\n              <p className=\"mt-0.5 flex flex-wrap items-center gap-x-1.5 text-[13px] text-muted-foreground\">\n                <Star className=\"size-3 fill-star text-star\" aria-hidden />\n                <span className=\"font-medium tabular-nums text-foreground\">{p.rating}</span>\n                <span aria-hidden>·</span>\n                <span>{p.kind}</span>\n                <span className=\"inline-flex items-center gap-1\"><MapPin className=\"size-3\" aria-hidden />{p.where}</span>\n              </p>\n            </div>\n          </div>\n          <OpenNowBadge hours={p.hours} timeZone={p.tz} size=\"sm\" className=\"bg-background dark:bg-foreground/[0.1]\" />\n        </article>\n      ))}\n    </div>\n  );\n}\n"}}