{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "link-target",
  "title": "Link target",
  "description": "A link to one item of a block, such as #cancel, that shows it first when it is out of sight (a closed answer, another topic, a release a filter hides), then brings it into view and moves focus to it.",
  "dependencies": [],
  "registryDependencies": [
    "https://kinoui.com/r/scroll.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/lib/link-target.ts",
      "content": "'use client'\n\nimport { reducesMotion } from '@/registry/lib/reduce-motion'\nimport { holdAtEdge, topEdge } from '@/registry/lib/scroll'\nimport { type RefObject, useEffect, useRef } from 'react'\n\n/*\n * A link to one item of a block, `#cancel`, that may be out of sight: an\n * answer that is closed, a question on another topic, a release a filter\n * hides. The block shows it first (opens it, picks its topic, clears the\n * filter), then the item scrolls to the top of the screen and takes the\n * focus, so the keyboard goes on from there and a screen reader says it.\n * The FAQ blocks and the Changelog blocks share it.\n */\n\n/**\n * A target a link scrolls to stops short of the top, so the line above it\n * shows too: `--link-target-top` below it, which a page with a sticky header\n * sets to the header's height and some room.\n */\nconst linkTargetClassName = 'scroll-mt-(--link-target-top,--spacing(8))'\n\n/** On the block's root: while the page loads on a link, the item lands shown, with nothing moving. */\nconst linkLandingClassName =\n  'data-landing:**:transition-none! data-landing:[&_*::before]:transition-none! data-landing:[&_*::after]:transition-none!'\n\n/** The blocks on the page and the items each has, so a link reaches the first that has its item. */\nconst rootsOnPage = new Map<HTMLElement, (value: string) => boolean>()\n\n/** Frames an item has to appear in once it is revealed, such as a topic's panel mounting. */\nconst REVEAL_FRAMES = 10\n\n/** Frames the page holds still after it loads on a link to an item. */\nconst LANDING_FRAMES = 4\n\n/** The item a link names, or nothing: `#cancel` names `cancel`. */\nfunction targetOfHash(hash: string): string | null {\n  if (hash.length < 2) return null\n  try {\n    return decodeURIComponent(hash.slice(1))\n  } catch {\n    return null\n  }\n}\n\n/** `Node.DOCUMENT_POSITION_PRECEDING`, which a server has no `Node` to read from. */\nconst PRECEDING = 2\n\n/** Of the blocks that have the item, the one first on the page. */\nfunction firstWith<Root extends { compareDocumentPosition(other: Root): number }>(\n  value: string,\n  roots: Map<Root, (value: string) => boolean>,\n) {\n  let first: Root | null = null\n  for (const [root, has] of roots) {\n    if (!has(value)) continue\n    if (!first || first.compareDocumentPosition(root) & PRECEDING) {\n      first = root\n    }\n  }\n  return first\n}\n\n/** The hash of a link that stays on the page it is on, `#cancel`, or nothing for one that leaves it. */\nfunction hashOnPage(href: string, page: string): string | null {\n  const url = new URL(href, page)\n  const here = new URL(page)\n  return url.origin === here.origin &&\n    url.pathname === here.pathname &&\n    url.search === here.search\n    ? url.hash\n    : null\n}\n\n/** Whether a click on a link stays on this page, where only the hash may change. */\nfunction linkOnPage(event: MouseEvent): string | null {\n  if (\n    event.defaultPrevented ||\n    event.button !== 0 ||\n    event.metaKey ||\n    event.ctrlKey ||\n    event.shiftKey ||\n    event.altKey\n  ) {\n    return null\n  }\n  const link = event.target instanceof Element ? event.target.closest('a[href]') : null\n  if (!(link instanceof HTMLAnchorElement) || (link.target && link.target !== '_self'))\n    return null\n  return hashOnPage(link.href, window.location.href)\n}\n\n/**\n * Shows the item a link names, `#cancel`, when the page loads with it, when\n * the link changes, and when a link to it is followed again, then scrolls it\n * to the top of the screen, past the scroller's `scroll-padding-top` and its\n * own `scroll-margin-top` (`linkTargetClassName`), and holds it there while\n * what is above it closes. Each item carries its value as\n * `data-link-target`; focus moves to the element in it marked\n * `data-link-focus`, such as an answer's trigger, or to the item itself,\n * which then needs `tabIndex={-1}`. Of several blocks with that item, the\n * first on the page shows it. While the page loads on the link, the root\n * carries `data-landing`, so the block lands with nothing moving\n * (`linkLandingClassName`).\n */\nfunction useLinkTarget(\n  ref: RefObject<HTMLElement | null>,\n  has: (value: string) => boolean,\n  /** Shows the item: opens it, picks its topic, clears a filter that hides it. */\n  reveal: (value: string) => void,\n) {\n  // The latest of each, so a render never shows the item again.\n  const latest = useRef({ has, reveal })\n  useEffect(() => {\n    latest.current = { has, reveal }\n  })\n\n  useEffect(() => {\n    const root = ref.current\n    if (!root) return\n    rootsOnPage.set(root, (value) => latest.current.has(value))\n    let frame = 0\n    /** `landing` when the page loads on the link: the item is there at once, with nothing moving. */\n    const follow = (hash: string, landing = false) => {\n      const value = targetOfHash(hash)\n      if (value === null || firstWith(value, rootsOnPage) !== root) return\n      if (landing) root.setAttribute('data-landing', '')\n      latest.current.reveal(value)\n      cancelAnimationFrame(frame)\n      let left = REVEAL_FRAMES\n      const show = () => {\n        const item = root.querySelector<HTMLElement>(\n          `[data-link-target=\"${CSS.escape(value)}\"]:not([data-leaving])`,\n        )\n        // After the render that shows it, and its topic's.\n        if (!item || item.closest('[hidden]')) {\n          if (--left > 0) frame = requestAnimationFrame(show)\n          else root.removeAttribute('data-landing')\n          return\n        }\n        ;(item.querySelector<HTMLElement>('[data-link-focus]') ?? item).focus({\n          preventScroll: true,\n        })\n        item.scrollIntoView({\n          block: 'start',\n          behavior: landing || reducesMotion(root) ? 'instant' : 'smooth',\n        })\n        holdAtEdge(item, root, topEdge(item))\n        // An opening starts, and a tab's highlight is placed, a few frames after it renders: those land too.\n        if (landing) {\n          let wait = LANDING_FRAMES\n          const land = () => {\n            if (--wait > 0) frame = requestAnimationFrame(land)\n            else root.removeAttribute('data-landing')\n          }\n          frame = requestAnimationFrame(land)\n        }\n      }\n      frame = requestAnimationFrame(show)\n    }\n    const changed = () => follow(window.location.hash)\n    // A link followed again changes no hash, and a router's link changes it with no event.\n    const clicked = (event: MouseEvent) => {\n      const hash = linkOnPage(event)\n      if (hash) follow(hash)\n    }\n    follow(window.location.hash, true)\n    window.addEventListener('hashchange', changed)\n    document.addEventListener('click', clicked)\n    return () => {\n      rootsOnPage.delete(root)\n      cancelAnimationFrame(frame)\n      root.removeAttribute('data-landing')\n      window.removeEventListener('hashchange', changed)\n      document.removeEventListener('click', clicked)\n    }\n  }, [ref])\n}\n\nexport {\n  firstWith,\n  hashOnPage,\n  linkLandingClassName,\n  linkTargetClassName,\n  targetOfHash,\n  useLinkTarget,\n}\n",
      "type": "registry:lib",
      "target": "@lib/link-target.ts"
    }
  ],
  "type": "registry:lib"
}