{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "presence",
  "type": "registry:ui",
  "title": "Presence",
  "description": "Content that arrives and leaves instead of popping in and out. `Presence` keeps a block on the page for the moment it takes to leave, so a hint, a result or a \"you got it\" note fades away rather than vanishing. `Swap` trades one piece of content for the…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "decorative",
    "effect"
  ],
  "dependencies": [
    "@base-ui/react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/effects/presence.tsx",
      "target": "components/ui/effects/presence.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport { useRender } from '@base-ui/react/use-render';\n\n// @interlace/presence v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/presence\n// What changed since: https://ds.interlace.tools/c/presence#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — Presence and Swap\n *\n * Content that arrives and leaves instead of popping in and out. `Presence`\n * keeps a block on the page for the moment it takes to leave, so a hint, a\n * result or a \"you got it\" note fades away rather than vanishing. `Swap` trades\n * one piece of content for the next (a quiz question for the following one,\n * one step for another, today's card for tomorrow's): the old one leaves,\n * then the new one arrives, so the reader sees that something changed and in\n * which direction.\n *\n * ## How to use it\n *\n *   <Presence show={answered} effect=\"rise\">\n *     <Callout>Right, and here is why.</Callout>\n *   </Presence>\n *\n *   <Swap swapKey={question.id} effect=\"slide\" direction=\"forward\">\n *     <QuizQuestion … />\n *   </Swap>\n *\n * `Presence` renders nothing while `show` is false and it has finished\n * leaving. `Swap` always renders exactly one version of its content: the old\n * one until it has left, then the new one, never both at once, so the reading\n * order never holds two copies.\n *\n * ## Content first\n *\n * The server renders what is shown, with no inline style, so a crawler or a\n * reader without scripts gets the content. Content on its way out is `inert`\n * and hidden from assistive technology at once: it can't take focus or be\n * read while it fades. When the content that leaves held the keyboard focus,\n * `Swap` moves focus to the new content (the wrapper takes `tabIndex={-1}`\n * for that moment), so a keyboard or screen reader user is never dropped back\n * to the top of the page.\n *\n * ## Motion\n *\n * Web Animations on `opacity`, `transform` and (for `blur`) `filter` only,\n * which the compositor runs, so nothing around the block reflows while it\n * moves; when the size changes, it changes once, while the content is\n * invisible. Arrival takes `--duration-medium` on `--ease-enter`; leaving is\n * quicker, `--duration-base` on `--ease-exit`. Both read the brand's motion\n * tokens when they play, so a brand that retunes motion retunes these too.\n * `slide` moves along the reading direction, and flips in a right-to-left\n * page. It travels 1.5rem past the block's edge, so a Swap as wide as its\n * page needs a container with `overflow-x: clip`, or the page scrolls\n * sideways for the length of the slide. A change that comes back before the leave has finished turns the\n * leave around instead of starting over. Under `prefers-reduced-motion:\n * reduce`, or without `element.animate`, content simply appears and goes.\n *\n * ## Composition\n *\n *   Presence                            (div by default, or `render` — data-slot=\"presence\", data-state, data-effect)\n *     └─ children\n *   Swap                                (div by default, or `render` — data-slot=\"swap\", data-state, data-effect)\n *     └─ children                       (the version now shown)\n *\n * | Rule | Concept                 | Where in this file                                   |\n * | ---- | ----------------------- | ---------------------------------------------------- |\n * | R4   | Extends native el       | `div` props                                          |\n * | R6   | data-slot per part      | presence / swap                                      |\n * | R7   | cn + ...rest            | `cn(className)` + `{...props}` + `useRender`         |\n * | R8   | Enums, not booleans     | `effect`, `direction`                                |\n * | R13  | Ecosystem first         | `useRender` to be the element itself                 |\n * | R19  | Tokens only             | `--duration-*`, `--ease-*` read at play time         |\n * | R25  | Client component        | plays in the browser                                 |\n * | R26  | A11y                    | leaving content is inert; focus follows a swap       |\n */\n\nimport * as React from 'react';\n\nimport { cn } from '@/lib/utils';\nimport { motionDuration, motionEase } from '@/lib/motion-token';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\n\nexport type PresenceEffect = 'fade' | 'rise' | 'scale' | 'blur';\nexport type SwapEffect = PresenceEffect | 'slide';\nexport type SwapDirection = 'forward' | 'back';\n\n/** Where each effect starts from when arriving. Every one rests at the element's own style. */\nconst AWAY = {\n  fade: { opacity: 0 },\n  rise: { opacity: 0, transform: 'translateY(0.75rem)' },\n  scale: { opacity: 0, transform: 'scale(0.96)' },\n  blur: { opacity: 0, filter: 'blur(0.375rem)' },\n} as const satisfies Record<PresenceEffect, Keyframe>;\n\nconst HERE = {\n  fade: { opacity: 1 },\n  rise: { opacity: 1, transform: 'none' },\n  scale: { opacity: 1, transform: 'none' },\n  blur: { opacity: 1, filter: 'none' },\n} as const satisfies Record<PresenceEffect, Keyframe>;\n\ntype Phase = 'enter' | 'exit';\n\n/** The brand's motion tokens as they stand when the animation starts: arrival is slower than leaving. */\nfunction motionTiming(el: Element, phase: Phase): KeyframeAnimationOptions {\n  return {\n    duration: motionDuration(el, phase === 'enter' ? 'medium' : 'base'),\n    easing: motionEase(el, phase),\n  };\n}\n\nfunction canAnimate(el: HTMLElement | null): el is HTMLElement {\n  return !!el && typeof el.animate === 'function';\n}\n\nfunction slide(el: Element, offset: 1 | -1): [Keyframe, Keyframe] {\n  const rtl = el.closest('[dir]')?.getAttribute('dir') === 'rtl';\n  const x = `${(rtl ? -offset : offset) * 1.5}rem`;\n  return [\n    { opacity: 0, transform: `translateX(${x})` },\n    { opacity: 1, transform: 'none' },\n  ];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Presence                                                                   */\n/* -------------------------------------------------------------------------- */\n\nexport interface PresenceProps extends React.ComponentPropsWithoutRef<'div'> {\n  /** Whether the content is on the page. Turning it off plays the leave, then removes it. */\n  show: boolean;\n  /** How it arrives and leaves. Every effect fades; `rise` also lifts, `scale` grows, `blur` sharpens. @default 'fade' */\n  effect?: PresenceEffect;\n  /** Play the arrival on the first render too, not only when `show` turns on later. @default false */\n  appear?: boolean;\n  /** Called once the content has left and is no longer rendered. */\n  onExited?: () => void;\n  /** Replace the rendered element, e.g. `<section />` or `<li />`. */\n  render?: useRender.RenderProp;\n}\n\nexport function Presence({\n  show,\n  effect = 'fade',\n  appear = false,\n  onExited,\n  render,\n  className,\n  children,\n  ...props\n}: PresenceProps) {\n  const reduced = useReducedMotion();\n  const ref = React.useRef<HTMLElement>(null);\n  const [mounted, setMounted] = React.useState(show);\n  const first = React.useRef(true);\n  const running = React.useRef<{ animation: Animation; phase: Phase } | null>(null);\n  // Whether the content is on the page, as the layout effect last left it.\n  const onPage = React.useRef(show);\n  const exited = React.useRef(onExited);\n  React.useLayoutEffect(() => {\n    exited.current = onExited;\n  });\n\n  // Turning on mounts at once, in the same render, so there is no blank frame.\n  if (show && !mounted) setMounted(true);\n\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    const isFirst = first.current;\n    first.current = false;\n    const current = running.current;\n\n    if (show) {\n      onPage.current = true;\n      if (current?.phase === 'exit') {\n        // Coming back mid-leave: turn the leave around from where it is.\n        current.animation.onfinish = null;\n        current.animation.reverse();\n        running.current = { animation: current.animation, phase: 'enter' };\n        return;\n      }\n      if ((isFirst && !appear) || reduced || !canAnimate(el)) return;\n      const animation = el.animate([AWAY[effect], HERE[effect]], motionTiming(el, 'enter'));\n      running.current = { animation, phase: 'enter' };\n      animation.onfinish = () => {\n        if (running.current?.animation === animation) running.current = null;\n      };\n      return;\n    }\n\n    if (!onPage.current) return;\n    const done = () => {\n      onPage.current = false;\n      running.current = null;\n      setMounted(false);\n      exited.current?.();\n    };\n    if (reduced || !canAnimate(el)) {\n      done();\n      return;\n    }\n    current?.animation.cancel();\n    const animation = el.animate([HERE[effect], AWAY[effect]], {\n      ...motionTiming(el, 'exit'),\n      fill: 'forwards',\n    });\n    running.current = { animation, phase: 'exit' };\n    animation.onfinish = done;\n  }, [show, reduced, effect, appear]);\n\n  React.useEffect(\n    () => () => {\n      running.current?.animation.cancel();\n    },\n    [],\n  );\n\n  const element = useRender({\n    render: render ?? <div />,\n    ref,\n    props: {\n      'data-slot': 'presence',\n      'data-state': show ? 'open' : 'closed',\n      'data-effect': effect,\n      inert: show ? undefined : true,\n      'aria-hidden': show ? undefined : true,\n      className: cn(className) || undefined,\n      ...props,\n      children,\n    },\n  });\n\n  return mounted ? element : null;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Swap                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport interface SwapProps extends React.ComponentPropsWithoutRef<'div'> {\n  /** Names the content now shown. When it changes, the old content leaves, then the new arrives. */\n  swapKey: React.Key;\n  /** How the versions trade places. `slide` moves along the reading direction. @default 'fade' */\n  effect?: SwapEffect;\n  /** For `slide`: `forward` (next, the default) arrives from the inline end; `back` from the inline start. @default 'forward' */\n  direction?: SwapDirection;\n  /** Replace the rendered element, e.g. `<section />` or `<li />`. */\n  render?: useRender.RenderProp;\n}\n\ntype Shown = { key: React.Key; node: React.ReactNode };\n\nexport function Swap({\n  swapKey,\n  effect = 'fade',\n  direction = 'forward',\n  render,\n  className,\n  children,\n  onBlur,\n  ...props\n}: SwapProps) {\n  const reduced = useReducedMotion();\n  const ref = React.useRef<HTMLElement>(null);\n  const [shown, setShown] = React.useState<Shown>({ key: swapKey, node: children });\n  const latest = React.useRef<Shown>({ key: swapKey, node: children });\n  const leave = React.useRef<Animation | null>(null);\n  const arrive = React.useRef<Animation | null>(null);\n  const hadFocus = React.useRef(false);\n  const arriving = React.useRef(false);\n  const ended = React.useRef<Animation | null>(null);\n  const [focusable, setFocusable] = React.useState(false);\n\n  // While the key holds, new children for it show at once.\n  const settled = swapKey === shown.key;\n  if (settled && children !== shown.node) setShown({ key: swapKey, node: children });\n\n  React.useLayoutEffect(() => {\n    latest.current = { key: swapKey, node: children };\n  });\n\n  const keyframes = React.useCallback(\n    (el: Element, phase: Phase): Keyframe[] => {\n      if (effect !== 'slide') {\n        return phase === 'enter' ? [AWAY[effect], HERE[effect]] : [HERE[effect], AWAY[effect]];\n      }\n      const forward = direction === 'forward' ? 1 : -1;\n      // Forward: the old one leaves toward the inline start, the new one comes from the inline end.\n      if (phase === 'enter') return slide(el, forward);\n      const [away, here] = slide(el, forward === 1 ? -1 : 1);\n      return [here, away];\n    },\n    [effect, direction],\n  );\n\n  // The key changed: play the leave, then show the latest content.\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    if (settled) {\n      // Came back to the shown key before the leave finished: stay.\n      if (leave.current) {\n        leave.current.onfinish = null;\n        leave.current.cancel();\n        leave.current = null;\n      }\n      return;\n    }\n    if (el && typeof document !== 'undefined' && el.contains(document.activeElement)) {\n      hadFocus.current = true;\n    }\n    const commit = () => {\n      ended.current = leave.current;\n      leave.current = null;\n      arriving.current = true;\n      setShown(latest.current);\n    };\n    if (reduced || !canAnimate(el)) {\n      commit();\n      return;\n    }\n    if (leave.current) return; // already leaving: the finish shows whatever is latest then\n    arrive.current?.cancel();\n    const animation = el.animate(keyframes(el, 'exit'), { ...motionTiming(el, 'exit'), fill: 'forwards' });\n    leave.current = animation;\n    animation.onfinish = commit;\n  }, [settled, swapKey, reduced, keyframes]);\n\n  // The new content is in: clear the leave's end state, play the arrival, hand focus over.\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    if (!arriving.current || !el) return;\n    arriving.current = false;\n    ended.current?.cancel();\n    ended.current = null;\n    if (!reduced && canAnimate(el)) {\n      arrive.current = el.animate(keyframes(el, 'enter'), motionTiming(el, 'enter'));\n    }\n    if (hadFocus.current) {\n      hadFocus.current = false;\n      setFocusable(true);\n    }\n  }, [shown.key, reduced, keyframes]);\n\n  // Focus moves once the wrapper can take it, then the wrapper leaves the tab order again on blur.\n  React.useEffect(() => {\n    if (!focusable) return;\n    ref.current?.focus({ preventScroll: true });\n  }, [focusable]);\n\n  React.useEffect(\n    () => () => {\n      leave.current?.cancel();\n      arrive.current?.cancel();\n    },\n    [],\n  );\n\n  const leaving = !settled;\n  return useRender({\n    render: render ?? <div />,\n    ref,\n    props: {\n      'data-slot': 'swap',\n      'data-state': leaving ? 'leaving' : 'shown',\n      'data-effect': effect,\n      inert: leaving ? true : undefined,\n      'aria-hidden': leaving ? true : undefined,\n      tabIndex: focusable ? -1 : undefined,\n      className: cn(className) || undefined,\n      ...props,\n      onBlur: (event: React.FocusEvent<HTMLDivElement>) => {\n        // Out of the tab order again once focus moves on from the wrapper itself.\n        if (focusable && event.target === event.currentTarget) setFocusable(false);\n        onBlur?.(event);\n      },\n      children: shown.node,\n    },\n  });\n}\n"
    }
  ],
  "meta": {
    "tier": "effect",
    "client": true,
    "minViewport": null,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/presence\n\nInstalled to `components/ui/effects/presence.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/effects/presence';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/presence\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
