{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "intent",
  "type": "registry:lib",
  "title": "User intent hooks and provider",
  "description": "@interlace/ui — typed, vendor-neutral user intent: activate, view, dwell, commit, disclosure and form hooks, `data-intent` for server components, rage clicks and page view/leave, all reported through one `IntentProvider` adapter. Sends nothing that identifies a person.",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "foundation",
    "util"
  ],
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/interlace-ui/lib/intent.ts",
      "target": "hooks/use-intent.ts",
      "type": "registry:lib",
      "content": "'use client';\n\nimport {\n  createContext,\n  createElement,\n  useCallback,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n  type ReactNode,\n} from 'react';\n\n// @interlace/intent v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/intent\n// What changed since: https://ds.interlace.tools/c/intent#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * User intent: what a person meant to do, as typed events, sent wherever the\n * app chooses.\n *\n * A raw DOM event says a button was clicked. An intent says the person meant\n * it: they activated \"Join\" with the keyboard, read the pricing table for a\n * second, opened the filters and dismissed them with Escape, started the form\n * and left the page. Product analytics, funnels and UX research want the\n * second, and every app ends up writing the same timers and observers to get\n * it. This module writes them once.\n *\n * ## Shape\n *\n * - **Hooks** report one kind of intent each. `useActivateIntent`,\n *   `useViewIntent`, `useDwellIntent`, `useCommitIntent`,\n *   `useDisclosureIntent` and `useFormIntent` return props to spread on the\n *   element (or a callback ref). Each takes a `name` and an optional\n *   `onIntent` callback.\n * - **`IntentProvider`** is the one sink. Every hook below it also reports to\n *   the provider's `onIntent`, so a whole app needs one adapter: the place\n *   that turns an `IntentEvent` into a call to whichever analytics tool the\n *   app uses. Nothing in this file names a vendor.\n * - **Declarative intent** needs no hook: any element with `data-intent=\"…\"`\n *   reports an `activate` when clicked, through the provider. That works in\n *   server components, which cannot call hooks.\n * - **Page signals** come from the provider too: `page_view` and `page_leave`\n *   (how long the page was visible and how far down it was read) when given a\n *   `page`, and `rage_click` when someone clicks the same spot again and again\n *   because nothing seemed to happen.\n *\n * ## Privacy by construction\n *\n * An event carries a name the developer chose, numbers and enums. It never\n * carries what a person typed (`commit` reports the length, not the value),\n * element text, or anything about who they are. The adapter decides what\n * leaves the device; this module gives it nothing that identifies anyone.\n *\n * ## Never in the way\n *\n * A sink that throws is caught and ignored: analytics never breaks a page.\n * Nothing here touches a browser API during render, so every hook is safe in\n * server rendering and can be called with no options.\n */\n\n/** How an activation happened. `keyboard` is Enter or Space on a control. */\nexport type IntentInput = 'keyboard' | 'mouse' | 'touch' | 'pen';\n\nexport type IntentEvent =\n  | { kind: 'activate'; name: string; input: IntentInput }\n  | { kind: 'view'; name: string; visibleMs: number }\n  | {\n      kind: 'dwell';\n      name: string;\n      input: 'pointer' | 'keyboard';\n      dwellMs: number;\n    }\n  | { kind: 'commit'; name: string; length: number }\n  | { kind: 'disclosure'; name: string; open: boolean; reason: string }\n  | {\n      kind: 'form';\n      name: string;\n      phase: 'start' | 'submit' | 'abandon';\n      reason?: 'cancel' | 'page_leave';\n    }\n  | { kind: 'rage_click'; name: string; clicks: number }\n  | { kind: 'page_view'; name: string }\n  | { kind: 'page_leave'; name: string; visibleMs: number; depth: number };\n\nexport type IntentKind = IntentEvent['kind'];\n\nexport type IntentSink = (event: IntentEvent) => void;\n\n/** A pointer must rest this long before a hover counts (ms). */\nexport const DWELL_INTENT_DELAY_MS = 500;\n/** An element must stay in view this long before it counts as seen (ms). */\nexport const VIEW_INTENT_DELAY_MS = 1000;\n/** The share of an element that must be visible to count as in view. */\nexport const VIEW_INTENT_THRESHOLD = 0.5;\n/** A typed value commits after this long without a change (ms). */\nexport const COMMIT_INTENT_DELAY_MS = 400;\n/** Clicks closer together than this (ms and px) belong to one burst. */\nexport const RAGE_CLICK_WINDOW_MS = 700;\nexport const RAGE_CLICK_RADIUS_PX = 30;\n/** Clicks in one burst before it counts as a rage click. */\nexport const RAGE_CLICK_COUNT = 3;\n\nconst IntentContext = createContext<IntentSink | null>(null);\n\nfunction safely(sink: IntentSink | null | undefined, event: IntentEvent) {\n  try {\n    sink?.(event);\n  } catch {\n    // A failing adapter must never break the interaction it measures.\n  }\n}\n\nfunction useLatest<T>(value: T) {\n  const ref = useRef(value);\n  useEffect(() => {\n    ref.current = value;\n  });\n  return ref;\n}\n\n/**\n * The reporter a hook uses: the hook's own `onIntent` first, then the\n * provider's. Stable for the life of the component.\n */\nfunction useReporter(local?: IntentSink): IntentSink {\n  const shared = useContext(IntentContext);\n  const localRef = useLatest(local);\n  const sharedRef = useLatest(shared);\n  return useCallback(\n    (event: IntentEvent) => {\n      safely(localRef.current, event);\n      safely(sharedRef.current, event);\n    },\n    [localRef, sharedRef],\n  );\n}\n\n/**\n * Report an intent by hand, for a moment no hook covers (a server confirmed\n * a booking, a game round ended). Reports to the nearest `IntentProvider`;\n * without one it does nothing.\n */\nexport function useIntent(): IntentSink {\n  return useReporter();\n}\n\ntype ClickLike = {\n  detail: number;\n  nativeEvent?: { pointerType?: string };\n  pointerType?: string;\n};\n\n/** Enter or Space on a control fires a click with `detail` 0. */\nexport function inputOf(event: ClickLike): IntentInput {\n  if (event.detail === 0) return 'keyboard';\n  const type = event.nativeEvent?.pointerType ?? event.pointerType;\n  return type === 'touch' || type === 'pen' ? type : 'mouse';\n}\n\n/** The name an element reports under: its intent, else its slot, else its tag. */\nfunction nameOf(target: EventTarget | null): string | null {\n  if (!(target instanceof Element)) return null;\n  const declared = target.closest('[data-intent]');\n  if (declared) return declared.getAttribute('data-intent');\n  const slot = target.closest('[data-slot]');\n  if (slot) return slot.getAttribute('data-slot');\n  return target.tagName.toLowerCase();\n}\n\nfunction scrollDepth(): number {\n  const doc = document.documentElement;\n  const height = doc.scrollHeight;\n  if (height <= 0) return 100;\n  const seen = (window.scrollY + window.innerHeight) / height;\n  return Math.round(Math.min(1, Math.max(0, seen)) * 100);\n}\n\n/* ---------------------------------------------------------------- Provider */\n\nexport interface IntentProviderProps {\n  /** Where every intent below this provider goes: the app's adapter. */\n  onIntent: IntentSink;\n  /**\n   * The current page's name, usually its route. When set, the provider\n   * reports `page_view` for it, and `page_leave` when it changes or the\n   * document is hidden for good (`pagehide`), with the visible time and the\n   * deepest point read (0–100).\n   */\n  page?: string;\n  /** Report rage clicks anywhere below the document. Default `true`. */\n  rageClicks?: boolean;\n  /** Report clicks on `[data-intent]` elements as `activate`. Default `true`. */\n  declarative?: boolean;\n  children?: ReactNode;\n}\n\nexport function IntentProvider({\n  onIntent,\n  page,\n  rageClicks = true,\n  declarative = true,\n  children,\n}: IntentProviderProps) {\n  const sinkRef = useLatest(onIntent);\n  const [sink] = useState<IntentSink>(\n    () => (event: IntentEvent) => safely(sinkRef.current, event),\n  );\n\n  // Declarative activations and rage clicks share one document listener.\n  useEffect(() => {\n    if (!declarative && !rageClicks) return;\n    let burst: { x: number; y: number; at: number; clicks: number } | null =\n      null;\n    const onClick = (event: MouseEvent) => {\n      if (declarative && event.target instanceof Element) {\n        const declared = event.target.closest('[data-intent]');\n        if (declared) {\n          sink({\n            kind: 'activate',\n            name: declared.getAttribute('data-intent') as string,\n            input: inputOf(event as MouseEvent & { pointerType?: string }),\n          });\n        }\n      }\n      if (!rageClicks || event.detail === 0) return;\n      const at = event.timeStamp;\n      const prev = burst;\n      const near =\n        prev !== null &&\n        at - prev.at <= RAGE_CLICK_WINDOW_MS &&\n        Math.hypot(event.clientX - prev.x, event.clientY - prev.y) <=\n          RAGE_CLICK_RADIUS_PX;\n      burst = {\n        x: event.clientX,\n        y: event.clientY,\n        at,\n        clicks: near ? prev.clicks + 1 : 1,\n      };\n      // Once per burst: the third click reports, the fourth does not.\n      if (burst.clicks === RAGE_CLICK_COUNT) {\n        sink({\n          kind: 'rage_click',\n          name: nameOf(event.target) ?? 'document',\n          clicks: burst.clicks,\n        });\n      }\n    };\n    document.addEventListener('click', onClick);\n    return () => document.removeEventListener('click', onClick);\n  }, [declarative, rageClicks, sink]);\n\n  // Page view and leave, with visible time and read depth.\n  useEffect(() => {\n    if (page === undefined) return;\n    let visibleMs = 0;\n    let since: number | null =\n      document.visibilityState === 'visible' ? Date.now() : null;\n    let depth = scrollDepth();\n    let left = false;\n    sink({ kind: 'page_view', name: page });\n\n    const onScroll = () => {\n      depth = Math.max(depth, scrollDepth());\n    };\n    const onVisibility = () => {\n      if (document.visibilityState === 'visible') {\n        since ??= Date.now();\n      } else if (since !== null) {\n        visibleMs += Date.now() - since;\n        since = null;\n      }\n    };\n    const leave = () => {\n      if (left) return;\n      left = true;\n      onVisibility();\n      const total = visibleMs + (since === null ? 0 : Date.now() - since);\n      sink({ kind: 'page_leave', name: page, visibleMs: total, depth });\n    };\n    // A page restored from the back-forward cache is a new view.\n    const onShow = (event: PageTransitionEvent) => {\n      if (!event.persisted) return;\n      left = false;\n      visibleMs = 0;\n      since = Date.now();\n      sink({ kind: 'page_view', name: page });\n    };\n    window.addEventListener('scroll', onScroll, { passive: true });\n    document.addEventListener('visibilitychange', onVisibility);\n    window.addEventListener('pagehide', leave);\n    window.addEventListener('pageshow', onShow);\n    return () => {\n      window.removeEventListener('scroll', onScroll);\n      document.removeEventListener('visibilitychange', onVisibility);\n      window.removeEventListener('pagehide', leave);\n      window.removeEventListener('pageshow', onShow);\n      leave();\n    };\n  }, [page, sink]);\n\n  return createElement(IntentContext.Provider, { value: sink }, children);\n}\n\n/* ------------------------------------------------------------------- Hooks */\n\ninterface BaseOptions {\n  /** What this intent is called in reports, e.g. `join_room`. */\n  name?: string;\n  /** Called for this element's intents, before the provider's sink. */\n  onIntent?: IntentSink;\n}\n\n/**\n * Every activation, at once, with how it happened. A click is already\n * intentional, so there is no delay. Call `onClick` from the control's own\n * click handler.\n */\nexport function useActivateIntent({\n  name = 'activate',\n  onIntent,\n}: BaseOptions = {}) {\n  const report = useReporter(onIntent);\n  const onClick = useCallback(\n    (event: ClickLike) => report({ kind: 'activate', name, input: inputOf(event) }),\n    [report, name],\n  );\n  return { onClick };\n}\n\nexport interface ViewIntentOptions extends BaseOptions {\n  /** Time in view before it counts. Default 1000 ms. */\n  delayMs?: number;\n  /** Share visible to count as in view, 0–1. Default 0.5. Lower it for tall elements. */\n  threshold?: number;\n  /** Report at most once per mount. Default `true`; `false` reports each stay. */\n  once?: boolean;\n}\n\n/**\n * The element was seen: at least `threshold` of it stayed visible for\n * `delayMs`. Scrolling past reports nothing. Without `IntersectionObserver`\n * it never reports, because a false \"seen\" is worse than a missing one.\n */\nexport function useViewIntent({\n  name = 'view',\n  onIntent,\n  delayMs = VIEW_INTENT_DELAY_MS,\n  threshold = VIEW_INTENT_THRESHOLD,\n  once = true,\n}: ViewIntentOptions = {}) {\n  const report = useReporter(onIntent);\n  const [element, setElement] = useState<Element | null>(null);\n\n  useEffect(() => {\n    if (!element || typeof IntersectionObserver === 'undefined') return;\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const observer = new IntersectionObserver(\n      (entries) => {\n        const entry = entries.at(-1) as IntersectionObserverEntry;\n        const inView =\n          entry.isIntersecting && entry.intersectionRatio >= threshold;\n        if (inView && timer === undefined) {\n          timer = setTimeout(() => {\n            report({ kind: 'view', name, visibleMs: delayMs });\n            if (once) observer.disconnect();\n          }, delayMs);\n        } else if (!inView) {\n          clearTimeout(timer);\n          timer = undefined;\n        }\n      },\n      { threshold: [0, threshold] },\n    );\n    observer.observe(element);\n    return () => {\n      clearTimeout(timer);\n      observer.disconnect();\n    };\n  }, [element, delayMs, threshold, once, name, report]);\n\n  return { ref: setElement };\n}\n\nexport interface DwellIntentOptions extends BaseOptions {\n  /** Rest time before it counts. Default 500 ms. */\n  delayMs?: number;\n  /** Report at most once per mount. Default `true`. */\n  once?: boolean;\n}\n\n/**\n * Attention that rested: a pointer hovering, or keyboard focus sitting, on\n * the element for `delayMs`. Passing over it reports nothing. Touch never\n * dwells (a tap is an activation), and focus counts only when it is visible\n * keyboard focus, never focus a click or the app moved.\n *\n * A disabled button gets no pointer events: spread these on a wrapper.\n */\nexport function useDwellIntent({\n  name = 'dwell',\n  onIntent,\n  delayMs = DWELL_INTENT_DELAY_MS,\n  once = true,\n}: DwellIntentOptions = {}) {\n  const report = useReporter(onIntent);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  const done = useRef(false);\n\n  const cancel = useCallback(() => {\n    clearTimeout(timer.current);\n    timer.current = undefined;\n  }, []);\n  const start = useCallback(\n    (input: 'pointer' | 'keyboard') => {\n      if (done.current) return;\n      cancel();\n      timer.current = setTimeout(() => {\n        timer.current = undefined;\n        if (once) done.current = true;\n        report({ kind: 'dwell', name, input, dwellMs: delayMs });\n      }, delayMs);\n    },\n    [cancel, delayMs, name, once, report],\n  );\n  useEffect(() => cancel, [cancel]);\n\n  return {\n    onPointerEnter: (event: { pointerType?: string }) => {\n      if (event.pointerType !== 'touch') start('pointer');\n    },\n    onPointerLeave: cancel,\n    onFocus: (event: { currentTarget: Element }) => {\n      let visible = false;\n      try {\n        visible = event.currentTarget.matches(':focus-visible');\n      } catch {\n        visible = false;\n      }\n      if (visible) start('keyboard');\n    },\n    onBlur: cancel,\n  };\n}\n\nexport interface CommitIntentOptions<T> extends BaseOptions {\n  /** The field's current value. Its value at mount is the baseline. */\n  value?: T;\n  /** Pause after the last change before the value commits. Default 400 ms. */\n  delayMs?: number;\n}\n\n/**\n * A typed value the person settled on: `delayMs` after the last change, or at\n * once when they leave the field. Never per keystroke, never the same value\n * twice in a row. Reports the value's length only, never the value.\n */\nexport function useCommitIntent<T>({\n  name = 'commit',\n  onIntent,\n  value,\n  delayMs = COMMIT_INTENT_DELAY_MS,\n}: CommitIntentOptions<T> = {}) {\n  const report = useReporter(onIntent);\n  const last = useRef(value);\n  const pending = useRef<{ value: T } | null>(null);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n  const flush = useCallback(() => {\n    clearTimeout(timer.current);\n    const next = pending.current;\n    pending.current = null;\n    if (!next || Object.is(next.value, last.current)) return;\n    last.current = next.value;\n    if (next.value === undefined || next.value === null) return;\n    report({ kind: 'commit', name, length: String(next.value).length });\n  }, [name, report]);\n\n  useEffect(() => {\n    if (Object.is(value, last.current) && !pending.current) return;\n    pending.current = { value: value as T };\n    clearTimeout(timer.current);\n    timer.current = setTimeout(flush, delayMs);\n  }, [value, delayMs, flush]);\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  return { onBlur: flush };\n}\n\nexport interface DisclosureIntentOptions extends BaseOptions {\n  /** Whether the overlay is open at mount. Default `false`. */\n  initialOpen?: boolean;\n}\n\n/**\n * Each real open and close of an overlay (dialog, popover, menu, drawer),\n * with why it closed. Pass `onOpenChange` to the overlay, or call it from\n * yours. A controlled overlay repeating its state reports nothing. `reason`\n * is whatever the overlay gives (Base UI: `escape-key`, `outside-press`, …),\n * or `none`.\n */\nexport function useDisclosureIntent({\n  name = 'disclosure',\n  onIntent,\n  initialOpen = false,\n}: DisclosureIntentOptions = {}) {\n  const report = useReporter(onIntent);\n  const open = useRef(initialOpen);\n  const onOpenChange = useCallback(\n    (next: boolean, details?: { reason?: string }) => {\n      if (next === open.current) return;\n      open.current = next;\n      report({\n        kind: 'disclosure',\n        name,\n        open: next,\n        reason: details?.reason ?? 'none',\n      });\n    },\n    [name, report],\n  );\n  return { onOpenChange };\n}\n\n/**\n * A form's life: `start` on the first change, `submit`, or `abandon` when it\n * was started and then cancelled or the page was left. Each reports at most\n * once per mount, and nothing follows a submit.\n */\nexport function useFormIntent({ name = 'form', onIntent }: BaseOptions = {}) {\n  const report = useReporter(onIntent);\n  const [phase, setPhase] = useState<'idle' | 'started' | 'done'>('idle');\n  const phaseRef = useRef(phase);\n  const move = useCallback((next: 'started' | 'done') => {\n    phaseRef.current = next;\n    setPhase(next);\n  }, []);\n\n  const onChange = useCallback(() => {\n    if (phaseRef.current !== 'idle') return;\n    move('started');\n    report({ kind: 'form', name, phase: 'start' });\n  }, [move, name, report]);\n  const markSubmitted = useCallback(() => {\n    if (phaseRef.current === 'done') return;\n    move('done');\n    report({ kind: 'form', name, phase: 'submit' });\n  }, [move, name, report]);\n  const markCancelled = useCallback(() => {\n    if (phaseRef.current !== 'started') return;\n    move('done');\n    report({ kind: 'form', name, phase: 'abandon', reason: 'cancel' });\n  }, [move, name, report]);\n\n  useEffect(() => {\n    if (phase !== 'started') return;\n    const onLeave = () => {\n      if (phaseRef.current !== 'started') return;\n      move('done');\n      report({ kind: 'form', name, phase: 'abandon', reason: 'page_leave' });\n    };\n    window.addEventListener('pagehide', onLeave);\n    return () => window.removeEventListener('pagehide', onLeave);\n  }, [phase, move, name, report]);\n\n  return { onChange, markSubmitted, markCancelled };\n}\n"
    }
  ],
  "meta": {
    "tier": "util",
    "client": true,
    "minViewport": null,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/intent\n\nInstalled to `hooks/use-intent.ts`.\n\n```tsx\nimport { /* … */ } from '@/hooks/use-intent';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/intent"
}
