{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"relative-time","type":"registry:component","title":"Relative time","description":"Says \"4 min ago\" and changes only at the moment the words would change.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/relative-time.tsx","type":"registry:component","content":"\"use client\";\n\nimport {\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\nconst SEC = 1000;\nconst MIN = 60 * SEC;\nconst HOUR = 60 * MIN;\nconst DAY = 24 * HOUR;\nconst WEEK = 7 * DAY;\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// A digit roll: long enough to read as motion, short enough that a\n// seconds counter never has two rolls overlapping.\nconst ROLL = { duration: 0.3, ease: [0.32, 0.72, 0, 1] } as const;\n// Tooltips: first one waits so passing over text doesn't flash it, then\n// neighbours open instantly while the group is still \"warm\".\nconst OPEN_DELAY = 400;\nconst WARM_FOR = 500;\nlet lastClosedAt = 0;\n\nconst tooltipFormat = () =>\n  new Intl.DateTimeFormat(undefined, {\n    weekday: \"short\",\n    month: \"short\",\n    day: \"numeric\",\n    year: \"numeric\",\n    hour: \"numeric\",\n    minute: \"2-digit\",\n  });\n\nfunction label(diff: number, time: number) {\n  if (diff < 10 * SEC) return \"just now\";\n  if (diff < MIN) return `${Math.floor(diff / SEC)} sec ago`;\n  if (diff < HOUR) return `${Math.floor(diff / MIN)} min ago`;\n  if (diff < DAY) return `${Math.floor(diff / HOUR)} hr ago`;\n  if (diff < 2 * DAY) return \"yesterday\";\n  if (diff < WEEK) return `${Math.floor(diff / DAY)} days ago`;\n  return new Intl.DateTimeFormat(undefined, {\n    month: \"short\",\n    day: \"numeric\",\n  }).format(time);\n}\n\n// Milliseconds until label() would return something different, so the\n// component wakes exactly once per visible change instead of every second.\nfunction untilChange(diff: number) {\n  if (diff < 0) return -diff;\n  if (diff < 10 * SEC) return 10 * SEC - diff;\n  // Past a week it shows a calendar date; an hourly check is plenty.\n  if (diff >= WEEK) return HOUR;\n  const unit = diff < MIN ? SEC : diff < HOUR ? MIN : diff < DAY ? HOUR : DAY;\n  return unit - (diff % unit);\n}\n\n// setTimeout overflows past ~24.8 days and fires immediately.\nconst MAX_TIMEOUT = 2 ** 31 - 1;\n// Lands just past the boundary so floor() has definitely moved.\nconst SETTLE_MS = 20;\n\nfunction useRelativeLabel(time: number | null, now?: number) {\n  const pinned = now !== undefined;\n  const subscribe = useCallback(\n    (notify: () => void) => {\n      // A pinned clock only changes when the caller passes a new one.\n      if (time === null || pinned) return () => {};\n      let timer: ReturnType<typeof setTimeout>;\n      const schedule = () => {\n        const wait = untilChange(Date.now() - time) + SETTLE_MS;\n        timer = setTimeout(\n          () => {\n            notify();\n            schedule();\n          },\n          Math.min(wait, MAX_TIMEOUT),\n        );\n      };\n      schedule();\n      // Background tabs throttle timers; catch up the moment we're seen.\n      const onVisible = () => {\n        if (document.visibilityState !== \"visible\") return;\n        clearTimeout(timer);\n        notify();\n        schedule();\n      };\n      document.addEventListener(\"visibilitychange\", onVisible);\n      return () => {\n        clearTimeout(timer);\n        document.removeEventListener(\"visibilitychange\", onVisible);\n      };\n    },\n    [time, pinned],\n  );\n  const getSnapshot = useCallback(\n    () => (time === null ? null : label((now ?? Date.now()) - time, time)),\n    [time, now],\n  );\n  // The server has no idea what \"now\" is on the reader's clock, so it\n  // renders nothing time-based and the client fills in after hydration.\n  return useSyncExternalStore(subscribe, getSnapshot, () => null);\n}\n\nexport function RelativeTime({\n  date,\n  now,\n  className,\n}: {\n  /** Pass null while the moment isn't known yet (it renders a placeholder). */\n  date: Date | number | string | null;\n  /** Pins \"now\" to this moment instead of the live clock (tests, replays). */\n  now?: number;\n  className?: string;\n}) {\n  const time = date === null ? null : new Date(date).getTime();\n  const text = useRelativeLabel(time, now);\n  const reduceMotion = useReducedMotion();\n  const tipId = useId();\n  const [open, setOpen] = useState(false);\n  const [instant, setInstant] = useState(false);\n  const openTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  const show = (delayed: boolean) => {\n    clearTimeout(openTimer.current);\n    const warm = Date.now() - lastClosedAt < WARM_FOR;\n    if (!delayed || warm) {\n      setInstant(warm);\n      setOpen(true);\n      return;\n    }\n    setInstant(false);\n    openTimer.current = setTimeout(() => setOpen(true), OPEN_DELAY);\n  };\n  const hide = () => {\n    clearTimeout(openTimer.current);\n    if (open) lastClosedAt = Date.now();\n    setOpen(false);\n  };\n\n  const match = text?.match(/^(\\d+)(.*)$/);\n  const digits = match ? match[1] : \"\";\n  const rest = match ? match[2] : (text ?? \"\");\n\n  return (\n    <time\n      dateTime={time === null ? undefined : new Date(time).toISOString()}\n      tabIndex={text === null ? undefined : 0}\n      aria-describedby={open ? tipId : undefined}\n      onPointerEnter={(e) => {\n        if (e.pointerType !== \"touch\") show(true);\n      }}\n      onPointerLeave={hide}\n      onFocus={() => show(false)}\n      onBlur={hide}\n      onKeyDown={(e) => {\n        if (e.key === \"Escape\") hide();\n      }}\n      className={cn(\n        // Brightens on hover so the text reads as something with more to say.\n        \"relative inline-flex cursor-default rounded-sm whitespace-nowrap tabular-nums transition-[color] duration-150 ease-out hover:text-foreground focus-visible:text-foreground outline-hidden focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid focus-visible:outline-foreground\",\n        className,\n      )}\n    >\n      {text === null ? (\n        // Holds roughly the right width so the line doesn't reflow on fill.\n        <span aria-hidden className=\"invisible\">\n          0 min ago\n        </span>\n      ) : (\n        <>\n          <span className=\"sr-only\">{text}</span>\n          <span aria-hidden className=\"inline-flex\">\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              {[...digits].map((d, i) => (\n                // Keyed from the right, so 9 -> 10 rolls the ones and\n                // brings a new tens digit in beside it.\n                <DigitSlot\n                  key={`slot-${digits.length - i}`}\n                  digit={d}\n                  reduceMotion={reduceMotion}\n                />\n              ))}\n            </AnimatePresence>\n            <span className=\"relative inline-flex\">\n              <AnimatePresence initial={false} mode=\"popLayout\">\n                <motion.span\n                  key={rest}\n                  className=\"inline-block whitespace-pre\"\n                  initial={roll.enter(reduceMotion)}\n                  animate={roll.center}\n                  exit={roll.exit(reduceMotion)}\n                  transition={ROLL}\n                >\n                  {rest}\n                </motion.span>\n              </AnimatePresence>\n            </span>\n          </span>\n          <AnimatePresence>\n            {open && time !== null ? (\n              <Tooltip\n                id={tipId}\n                time={time}\n                instant={instant}\n                reduceMotion={reduceMotion}\n              />\n            ) : null}\n          </AnimatePresence>\n        </>\n      )}\n    </time>\n  );\n}\n\n// New values come up from below and old ones leave upward: time only\n// moves forward, so the roll always runs the same way.\nconst roll = {\n  enter: (reduce: boolean | null) =>\n    reduce ? { opacity: 0 } : { opacity: 0, y: \"0.55em\", filter: \"blur(3px)\" },\n  center: { opacity: 1, y: 0, filter: \"blur(0px)\" },\n  exit: (reduce: boolean | null) =>\n    reduce\n      ? { opacity: 0 }\n      : // Travels less than the entrance did: the exit shouldn't hold the eye.\n        { opacity: 0, y: \"-0.4em\", filter: \"blur(3px)\" },\n};\n\nfunction DigitSlot({\n  digit,\n  reduceMotion,\n}: {\n  digit: string;\n  reduceMotion: boolean | null;\n}) {\n  return (\n    <motion.span\n      className=\"relative inline-flex\"\n      initial={roll.enter(reduceMotion)}\n      animate={roll.center}\n      exit={roll.exit(reduceMotion)}\n      transition={ROLL}\n    >\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.span\n          key={digit}\n          className=\"inline-block\"\n          initial={roll.enter(reduceMotion)}\n          animate={roll.center}\n          exit={roll.exit(reduceMotion)}\n          transition={ROLL}\n        >\n          {digit}\n        </motion.span>\n      </AnimatePresence>\n    </motion.span>\n  );\n}\n\nconst VIEWPORT_GUTTER = 8;\n\nfunction Tooltip({\n  id,\n  time,\n  instant,\n  reduceMotion,\n}: {\n  id: string;\n  time: number;\n  instant: boolean;\n  reduceMotion: boolean | null;\n}) {\n  const ref = useRef<HTMLSpanElement>(null);\n\n  // Starts centred on the text; nudged sideways only if that would poke\n  // past the viewport (and widen a phone-sized page).\n  useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const r = el.getBoundingClientRect();\n    const max = document.documentElement.clientWidth - VIEWPORT_GUTTER;\n    const shift =\n      r.left < VIEWPORT_GUTTER\n        ? VIEWPORT_GUTTER - r.left\n        : r.right > max\n          ? max - r.right\n          : 0;\n    el.style.marginLeft = `${Math.round(shift)}px`;\n  }, []);\n\n  return (\n    <span className=\"pointer-events-none absolute bottom-full left-1/2 z-10 -translate-x-1/2 pb-1.5\">\n      <motion.span\n        ref={ref}\n        id={id}\n        role=\"tooltip\"\n        className=\"block origin-bottom rounded-md bg-foreground px-2 py-1 text-xs font-medium whitespace-nowrap text-background shadow-raised\"\n        initial={\n          instant || reduceMotion\n            ? { opacity: instant ? 1 : 0 }\n            : { opacity: 0, scale: 0.9, y: 3, filter: \"blur(2px)\" }\n        }\n        animate={{\n          opacity: 1,\n          scale: 1,\n          y: 0,\n          filter: \"blur(0px)\",\n          transition: { duration: instant ? 0 : 0.16, ease: EASE_OUT },\n        }}\n        exit={{\n          opacity: 0,\n          scale: reduceMotion ? 1 : 0.97,\n          transition: { duration: 0.1, ease: EASE_OUT },\n        }}\n      >\n        {tooltipFormat().format(time)}\n      </motion.span>\n    </span>\n  );\n}\n\n// The moment the demo first rendered on the client. The server snapshot is\n// null, so the demo's timestamps only exist after hydration.\nlet clientNow: number | null = null;\nconst noSubscribe = () => () => {};\nconst getClientNow = () => (clientNow ??= Date.now());\n\n// The index card's show: the clock runs fast for a moment, so every label\n// rolls the way it would over the next few minutes. Seconds tip over into\n// minutes, minutes count up; then a pause, and the clock returns.\nconst SHOW: [wait: number, skip: number][] = [\n  [500, 30 * SEC],\n  [900, MIN],\n  [900, 2 * MIN],\n  [900, 3 * MIN],\n];\n// How long the last reading stays up before the clock returns, and the\n// calm beat at the live time before it runs again.\nconst SHOW_HOLD = 1800;\nconst SHOW_REST = 1400;\n\nexport default function RelativeTimeDemo() {\n  const now = useSyncExternalStore(noSubscribe, getClientNow, () => null);\n  const ago = (ms: number) => (now === null ? null : now - ms);\n  const play = usePreviewPlay();\n  // Undefined: the real clock. Only the hover show pins it.\n  const [pinned, setPinned] = useState<number>();\n\n  useEffect(() => {\n    if (play !== true) return;\n    let start = Date.now();\n    let timer: ReturnType<typeof setTimeout>;\n    const step = (i: number) => {\n      if (i === 0) start = Date.now();\n      if (i === SHOW.length) {\n        timer = setTimeout(() => {\n          setPinned(undefined);\n          timer = setTimeout(() => step(0), SHOW_REST);\n        }, SHOW_HOLD);\n        return;\n      }\n      const [wait, skip] = SHOW[i];\n      timer = setTimeout(() => {\n        setPinned(start + skip);\n        step(i + 1);\n      }, wait);\n    };\n    step(0);\n    // Unhovering hands the labels back to the live clock; they roll home.\n    return () => {\n      clearTimeout(timer);\n      setPinned(undefined);\n    };\n  }, [play]);\n\n  return (\n    <p className=\"max-w-full text-sm leading-6 text-muted-foreground\">\n      {/* Each clause wraps as a unit, so a narrow line never starts on a dot. */}\n      <span className=\"whitespace-nowrap\">\n        <span className=\"font-medium text-foreground\">Ana Ruiz</span> opened\n        this <RelativeTime now={pinned} date={ago(2 * HOUR + 14 * MIN)} />\n        <span aria-hidden className=\"pl-1.5\">\n          ·\n        </span>\n      </span>{\" \"}\n      <span className=\"whitespace-nowrap\">\n        edited <RelativeTime now={pinned} date={ago(4 * MIN + 51 * SEC)} />\n        <span aria-hidden className=\"pl-1.5\">\n          ·\n        </span>\n      </span>{\" \"}\n      <span className=\"whitespace-nowrap\">\n        synced <RelativeTime now={pinned} date={ago(12 * SEC)} />\n      </span>\n    </p>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["text"],"docs":"From ui lab: https://lab.xevrion.dev/lab/relative-time"}