{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "nonprofit-hero",
  "title": "Nonprofit: Hero",
  "description": "The donation hero on a full-bleed band of the sea: the amount and the families it reaches roll in the headline over twenty drawn jars that fill, one per family, and a paper card works the sum plainly (what you give, one-off or monthly, the slider and amounts, £45 ÷ £15 = 3 families, what families get, Donate, and the appeal's bar with the gift). It plays one example by itself after a beat, yields the moment someone acts, and keeps the chosen gift for the donate page.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://eased.dev/r/eased-tokens.json",
    "https://eased.dev/r/eased-motion.json",
    "https://eased.dev/r/nonprofit-core.json",
    "https://eased.dev/r/template-core.json",
    "https://eased.dev/r/slider.json",
    "https://eased.dev/r/segmented.json",
    "https://eased.dev/r/number-roll.json",
    "https://eased.dev/r/text-swap.json",
    "https://eased.dev/r/button.json"
  ],
  "files": [
    {
      "path": "src/registry/eased/templates/nonprofit/hero.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState, type RefObject } from \"react\";\nimport { Button } from \"../../button/button\";\nimport { NumberRoll } from \"../../number-roll/number-roll\";\nimport { Segmented } from \"../../segmented/segmented\";\nimport { Slider } from \"../../slider/slider\";\nimport { TextSwap } from \"../../text-swap/text-swap\";\nimport { BaseLink } from \"../_shared/base\";\nimport { AppealBar, appealWith, useAppealTime } from \"./appeal\";\nimport { Jar, Station } from \"./art\";\nimport { appeal, formatMoney, frequencies, giving, hero, locale, money, spend } from \"./content\";\nimport { useDemo } from \"./demo\";\nimport { amountOf, setShownGift, stepped, useGift, type Gift } from \"./gift\";\nimport { countOf, jarFills, largestRemainder, nounOf, parseAmount, remainderFor, sumOf, unitsFor, yearly } from \"./giving\";\nimport { COLUMN, LABEL, LINK } from \"./kit\";\n\n/**\n * The first screen, and the template's signature: choose a gift and see what it does. On a\n * full-bleed band of the sea, the amount set as large as the column allows and what it gives on\n * the left, over twenty drawn jars, one per family, that fill as the amount moves (the last one\n * part-way with what is left over), and two lines on the appeal and the share that reaches a\n * home. On the right, a paper card does the sum in rows: what you give (typed, with one-off or\n * monthly), the slider and four amounts, the unit cost, the months, the remainder, what families\n * get, and Donate. The appeal's bar at the card's foot and along the header grows by the gift.\n *\n * A beat after the jars come into view it plays one example by itself (demo.ts), yields the\n * moment someone acts, and can be played again. Only a person's own choices are kept (gift.tsx),\n * and they follow them to the donate page.\n */\nexport function Hero() {\n  const { gift: saved, chosen, live, choose } = useGift();\n  const jars = useRef<HTMLDivElement>(null);\n  const demo = useDemo(jars, !chosen);\n  const [dragging, setDragging] = useState(false);\n  const gift = demo.gift ?? saved;\n  const jump = !live || dragging || demo.tweening;\n\n  // The header's appeal bar adds whatever the hero shows; it adds nothing once the hero is gone.\n  useEffect(() => setShownGift(gift), [gift]);\n  useEffect(() => () => setShownGift(null), []);\n\n  /** A person's own change: the example stops first, so nothing of it sticks. A gift chosen here goes to the appeal. */\n  const { stop } = demo;\n  const act = useCallback(\n    (patch: Partial<Gift>) => {\n      stop();\n      choose({ ...patch, project: null });\n    },\n    [stop, choose],\n  );\n  const time = useAppealTime();\n\n  return (\n    <section aria-labelledby=\"hero-title\" data-nf-sea=\"\" className=\"bg-bg text-text\" {...demo.yieldOn}>\n      <div\n        className={`${COLUMN} grid gap-x-group-lg gap-y-pad-md pt-pad-md pb-pad-lg [grid-template-areas:'copy'_'card'_'trust'] sm:pt-pad-xl lg:min-h-[min(calc(100svh-var(--nf-header)),56rem)] lg:grid-cols-[minmax(0,7fr)_minmax(0,5fr)] lg:items-center lg:gap-y-pad-lg lg:py-pad-xl lg:[grid-template-areas:'copy_card'_'trust_card']`}\n      >\n        <div className=\"flex min-w-0 flex-col gap-pad-sm [grid-area:copy] lg:self-end\">\n          <p className={`nf-rise ${LABEL}`}>{time.closed ? appeal.general : appeal.name}</p>\n          <Headline gift={gift} jump={jump} />\n          <p className=\"nf-rise max-w-xl text-ui-md text-pretty text-text-secondary [--i:2] max-sm:hidden sm:text-ui-lg\">{hero.lead}</p>\n          <div ref={jars} className=\"nf-rise mt-pad-sm flex flex-col gap-pad-xs [--i:3]\">\n            <Jars gift={gift} jump={jump} />\n            <div className=\"flex min-h-11 items-center justify-between gap-in\">\n              <Caption gift={gift} />\n              {/* On phones the card's Donate is below the first screen, so one sits here too. */}\n              <Button variant=\"primary\" size=\"md\" nativeButton={false} render={<BaseLink href=\"/donate\" onClick={() => choose({ project: null })} />} className=\"h-11! sm:hidden\">\n                <TextSwap>{hero.donate(formatMoney(amountOf(gift)), hero.per[gift.frequency])}</TextSwap>\n              </Button>\n              <DemoControl demo={demo} />\n            </div>\n          </div>\n        </div>\n        <div data-nf-paper=\"\" className=\"nf-rise rounded-surface bg-bg p-pad-base text-text shadow-overlay [--i:2] [grid-area:card] sm:p-pad-md\">\n          <Card gift={gift} jump={jump} closed={time.closed} act={act} onDrag={setDragging} />\n        </div>\n        <Trust />\n      </div>\n      <Spoken gift={saved} chosen={chosen} playing={demo.playing} />\n    </section>\n  );\n}\n\n/* ---------- The headline ---------------------------------------------------------------- */\n\n/**\n * The amount, as large as the column allows, and what it gives. The visible figures roll and are\n * hidden from screen readers; the h1 carries the same sentence as plain text.\n */\nfunction Headline({ gift, jump }: { gift: Gift; jump: boolean }) {\n  const amount = amountOf(gift);\n  const f = gift.frequency;\n  const n = unitsFor(amount, f, giving.unit);\n  const left = giving.unit.cost - remainderFor(amount, f, giving.unit);\n  const what = f === \"monthly\" ? hero.what.monthly : hero.what.once;\n  const spoken = n > 0 ? hero.spoken(formatMoney(amount), hero.per[f], countOf(n, giving.unit), what) : hero.spokenToward(formatMoney(amount), formatMoney(left), hero.per[f]);\n  return (\n    <h1 id=\"hero-title\" className=\"flex flex-col gap-pad-xs\">\n      <span className=\"sr-only\">{spoken}</span>\n      <span aria-hidden data-nf-restore=\"\" className=\"nf-rise flex items-baseline gap-x-3 [--i:1]\">\n        <NumberRoll\n          value={amount}\n          format={money}\n          locale={locale}\n          animated={!jump}\n          aria-hidden\n          className=\"-my-[0.08em] min-w-[3ch] font-display text-[clamp(4.25rem,min(11vw,17svh),10rem)] leading-[1.08] font-bold tracking-[-0.055em] tabular-nums\"\n        />\n        <span className=\"font-display text-display-2xl font-semibold tracking-display whitespace-nowrap text-text-secondary sm:text-display-4xl\">\n          {/* A no-break space for one-off, so the line keeps its height when \"a month\" swaps in. */}\n          <TextSwap>{hero.per[f] || \" \"}</TextSwap>\n        </span>\n      </span>\n      <span\n        aria-hidden\n        data-nf-restore=\"\"\n        className=\"nf-rise max-w-[22ch] font-display text-[clamp(1.6rem,min(3.4vw,6svh),3.25rem)] leading-[1.08] font-semibold tracking-[-0.035em] text-balance [--i:2]\"\n      >\n        {n > 0 ? (\n          <>\n            {hero.gives}{\" \"}\n            <span className=\"whitespace-nowrap text-(--nf-sun)\">\n              <NumberRoll value={n} animated={!jump} locale={locale} aria-hidden className=\"tabular-nums\" /> <TextSwap>{nounOf(n, giving.unit)}</TextSwap>\n            </span>{\" \"}\n            {what}\n          </>\n        ) : (\n          hero.toward(formatMoney(left), f === \"monthly\")\n        )}\n      </span>\n    </h1>\n  );\n}\n\n/* ---------- The jars -------------------------------------------------------------------- */\n\n/** Twenty jars in two rows of ten, one per family, filled by the gift. */\nfunction Jars({ gift, jump }: { gift: Gift; jump: boolean }) {\n  const fills = jarFills(amountOf(gift), gift.frequency, giving.unit, giving.jars);\n  return (\n    <div role=\"img\" aria-label={hero.jarsLabel} data-nf-restore=\"\" className=\"grid grid-cols-10 gap-x-[2%] gap-y-2 sm:gap-y-3\">\n      {fills.map((fill, i) => (\n        <Jar key={i} fill={fill} instant={jump} />\n      ))}\n    </div>\n  );\n}\n\n/** What a jar means, or how many more families the gift reaches past the twentieth. From sm; phones have Donate there. */\nfunction Caption({ gift }: { gift: Gift }) {\n  const beyond = unitsFor(amountOf(gift), gift.frequency, giving.unit) - giving.jars;\n  return <p className=\"min-w-0 text-ui-sm text-text-secondary max-sm:hidden\">{beyond > 0 ? <TextSwap swapKey=\"beyond\">{hero.more(beyond.toLocaleString(locale))}</TextSwap> : hero.jarsCaption}</p>;\n}\n\n/** Play, stop and play again: one button whose label swaps, anchored to the caption row's end. */\nfunction DemoControl({ demo }: { demo: ReturnType<typeof useDemo> }) {\n  const label = demo.playing ? hero.stop : demo.played ? hero.replay : hero.play;\n  return (\n    <Button\n      variant=\"ghost\"\n      size=\"md\"\n      edge=\"end\"\n      hitArea\n      data-nf-demo=\"\"\n      swapKey={label}\n      onClick={demo.playing ? demo.stop : demo.play}\n      className=\"text-text hover-fine:not-data-disabled:text-text\"\n    >\n      {demo.playing ? <StopIcon /> : <PlayIcon />}\n      {label}\n    </Button>\n  );\n}\n\n/* ---------- Trust ----------------------------------------------------------------------- */\n\n/** The share of spending that reaches a home, worked out from the same lines as the split. */\nconst shares = largestRemainder(spend.lines.map((l) => l.amount));\nconst reach = spend.lines.reduce((sum, l, i) => sum + (spend.reach.includes(l.id) ? shares[i] : 0), 0);\n\n/** Two lines under the jars: the share that reaches a home, and the follow-up visits. */\nfunction Trust() {\n  return (\n    <ul className=\"nf-rise grid gap-pad-md [--i:4] [grid-area:trust] sm:grid-cols-2 lg:self-start\">\n      <li className=\"flex items-start gap-in\">\n        <Station id=\"fitted\" className=\"size-11 shrink-0\" />\n        <span className=\"flex flex-col items-start\">\n          <span className=\"text-ui-md font-medium text-text\">{hero.trust.visits}</span>\n          <BaseLink href={hero.trust.visitsLink.href} className={`inline-flex min-h-11 items-center text-ui sm:min-h-0 ${LINK}`}>\n            {hero.trust.visitsLink.label}\n          </BaseLink>\n        </span>\n      </li>\n      <li className=\"flex items-start gap-in\">\n        <Station id=\"glass\" className=\"size-11 shrink-0\" />\n        <span className=\"flex flex-col items-start\">\n          <span className=\"text-ui-md font-medium text-text\">{hero.trust.reach(reach)}</span>\n          <BaseLink href={hero.trust.reachLink.href} className={`inline-flex min-h-11 items-center text-ui sm:min-h-0 ${LINK}`}>\n            {hero.trust.reachLink.label}\n          </BaseLink>\n        </span>\n      </li>\n    </ul>\n  );\n}\n\n/* ---------- The card -------------------------------------------------------------------- */\n\n/**\n * The sum, in the order it is worked: what you give (typed, one-off or monthly), the slider and\n * the amounts, then the sum itself and what is left over, then what families get, the two ways\n * on, and the appeal with the gift in it (or, once it has closed, where gifts go instead). Every\n * change here is the person's own (`act`); a slider, amount or frequency change clears a typed\n * amount and its error. On touch the slider takes a sideways drag or a tap, and lets a swipe up\n * or down scroll the page (`useTouchSlide`).\n */\nfunction Card({ gift, jump, closed, act, onDrag }: { gift: Gift; jump: boolean; closed: boolean; act: (p: Partial<Gift>) => void; onDrag: (d: boolean) => void }) {\n  const f = gift.frequency;\n  const range = f === \"monthly\" ? giving.monthly : giving.once;\n  const amount = amountOf(gift);\n  const [text, setText] = useState<string | null>(null);\n  const [error, setError] = useState<string | null>(null);\n  const clear = () => {\n    setText(null);\n    setError(null);\n  };\n  const set = (n: number) => {\n    clear();\n    act(f === \"monthly\" ? { monthly: n } : { once: n });\n  };\n  const typed = (value: string) => {\n    setText(value);\n    const n = parseAmount(value);\n    if (value.trim() === \"\") return setError(null);\n    if (n === null || n < giving.typed.min) return setError(hero.otherInvalid(formatMoney(giving.typed.min)));\n    if (n > giving.typed.max) return setError(hero.otherTooMuch(formatMoney(giving.typed.max)));\n    setError(null);\n    act(f === \"monthly\" ? { monthly: n } : { once: n });\n  };\n  const slide = useRef<HTMLDivElement>(null);\n  useTouchSlide(slide, range, set, onDrag);\n  const n = unitsFor(amount, f, giving.unit);\n\n  return (\n    <div className=\"flex flex-col gap-pad-sm\">\n      <div className=\"flex flex-col gap-1\">\n        <div className=\"flex min-h-16 items-stretch gap-pad-xs rounded-control border border-line-strong bg-surface p-1.5 ps-pad-sm focus-within:border-text-muted has-aria-invalid:border-danger\">\n          <label className=\"flex min-w-0 flex-1 flex-col justify-center\">\n            <span className=\"text-ui-sm text-text-secondary\">{hero.card.give}</span>\n            <span className=\"flex items-baseline gap-0.5 text-display-2xl font-semibold tracking-display text-text\">\n              <span aria-hidden>£</span>\n              <input\n                inputMode=\"numeric\"\n                aria-label={hero.other}\n                value={text ?? String(amount)}\n                onChange={(e) => typed(e.target.value)}\n                onBlur={() => !error && setText(null)}\n                aria-invalid={error ? true : undefined}\n                aria-describedby=\"hero-give-help\"\n                data-nf-restore=\"\"\n                className=\"w-full min-w-0 bg-transparent tabular-nums outline-none\"\n              />\n            </span>\n          </label>\n          <Segmented\n            options={frequencies}\n            value={f}\n            onValueChange={(v) => {\n              clear();\n              act({ frequency: v });\n            }}\n            size=\"md\"\n            aria-label={hero.frequencyLabel}\n            className=\"self-center max-sm:h-12 max-sm:[&>button]:min-h-11 max-[359px]:[&>button]:px-2\"\n          />\n        </div>\n        <p id=\"hero-give-help\" aria-live=\"polite\" className={`text-ui-sm ${error ? \"text-danger-text\" : \"sr-only\"}`}>\n          {error}\n        </p>\n      </div>\n      <div ref={slide} onPointerDown={(e) => e.pointerType === \"mouse\" && onDrag(true)} onPointerUp={() => onDrag(false)} onLostPointerCapture={() => onDrag(false)}>\n        <Slider\n          value={Math.min(range.max, Math.max(range.min, stepped(amount, f)))}\n          onValueChange={set}\n          onValueCommitted={() => onDrag(false)}\n          min={range.min}\n          max={range.max}\n          step={range.step}\n          largeStep={range.step * 5}\n          format={money}\n          locale={locale}\n          aria-label={hero.sliderLabel[f]}\n          className=\"[&_.touch-none]:h-11 [&_.touch-none]:cursor-pointer [&_.touch-none]:touch-pan-y [&_.touch-none>div]:h-2\"\n        />\n      </div>\n      <div role=\"group\" aria-label={hero.presetsLabel} className=\"grid grid-cols-4 gap-1.5\">\n        {/* Keyed by slot, not value: flipping frequency changes each slot's amount in place. */}\n        {range.presets.map((p, i) => (\n          <Button\n            key={i}\n            variant=\"secondary\"\n            size=\"md\"\n            aria-pressed={p === amount}\n            onClick={() => set(p)}\n            className=\"tabular-nums max-sm:h-11 aria-pressed:bg-text aria-pressed:text-bg hover-fine:aria-pressed:bg-text\"\n          >\n            {formatMoney(p)}\n          </Button>\n        ))}\n      </div>\n      <Sum gift={gift} />\n      <div className=\"flex items-center justify-between gap-pad-base rounded-control border border-line-subtle bg-surface-sunken px-pad-sm py-2.5\">\n        <span className=\"text-ui-sm text-text-secondary\">{hero.card.get}</span>\n        <span className=\"text-display-xl font-semibold tracking-display text-text\">\n          <NumberRoll value={n} animated={!jump} locale={locale} className=\"tabular-nums\" /> <TextSwap>{nounOf(n, giving.unit)}</TextSwap>\n        </span>\n      </div>\n      <div className=\"grid grid-cols-2 gap-pad-xs max-[359px]:grid-cols-1\">\n        <Button variant=\"secondary\" size=\"lg\" nativeButton={false} render={<BaseLink href={hero.card.where.href} />} className=\"max-sm:h-11\">\n          {hero.card.where.label}\n        </Button>\n        <Button variant=\"primary\" size=\"lg\" nativeButton={false} render={<BaseLink href=\"/donate\" onClick={() => act({})} />} className=\"min-w-0 max-sm:h-11 max-sm:px-2\">\n          <TextSwap>{hero.donate(formatMoney(amount), hero.per[f])}</TextSwap>\n        </Button>\n      </div>\n      {closed ? <p className=\"border-t border-line-subtle pt-pad-sm text-ui-sm text-pretty text-text-secondary\">{appeal.after}</p> : <Reached gift={gift} jump={jump} />}\n    </div>\n  );\n}\n\n/**\n * The sum, plainly: \"£45 ÷ £15 = 3 families\", or \"£10 × 12 = £120 ÷ £15 = 8 families\", and under\n * it what is left over toward the next family, when anything is. The second line keeps its height\n * when empty, so nothing under it moves.\n */\nfunction Sum({ gift }: { gift: Gift }) {\n  const f = gift.frequency;\n  const amount = amountOf(gift);\n  const { yearly: year, units, rest } = sumOf(amount, f, giving.unit);\n  const perYear = f === \"monthly\" ? formatMoney(year) : null;\n  const cost = formatMoney(giving.unit.cost);\n  const under = units === 0;\n  const line = under ? hero.card.sumUnder(formatMoney(amount), perYear, cost) : hero.card.sum(formatMoney(amount), perYear, cost, countOf(units, giving.unit));\n  return (\n    <div className=\"flex flex-col gap-0.5 px-1 text-ui-sm\">\n      <p className=\"font-medium text-text tabular-nums\">\n        <TextSwap swapKey={line}>{line}</TextSwap>\n      </p>\n      <p className={`text-text-secondary ${rest > 0 && !under ? \"\" : \"invisible\"}`} aria-hidden={rest > 0 && !under ? undefined : true}>\n        {hero.card.left(formatMoney(rest))}\n      </p>\n    </div>\n  );\n}\n\n/** The appeal with the gift in it: families funded with it, and the bar. */\nfunction Reached({ gift, jump }: { gift: Gift; jump: boolean }) {\n  const added = yearly(amountOf(gift), gift.frequency);\n  const { before, after } = appealWith(added);\n  return (\n    <div className=\"flex flex-col gap-2 border-t border-line-subtle pt-pad-sm\">\n      <p className=\"flex flex-wrap items-baseline justify-between gap-x-pad-base gap-y-1 text-ui-sm text-text-secondary\">\n        <span>\n          <span className=\"font-medium text-text tabular-nums\">{before}</span> {appeal.of(appeal.target)} {appeal.families}\n        </span>\n        <span className=\"flex items-baseline gap-1.5\">\n          <span aria-hidden className=\"size-2.5 self-center rounded-[3px] bg-(--nf-sun)\" />\n          {hero.withGift}\n          <NumberRoll value={after} animated={!jump} locale={locale} className=\"font-medium text-text tabular-nums\" />\n        </span>\n      </p>\n      <AppealBar added={added} instant={jump} className=\"h-2.5 rounded-pill\" trackClassName=\"bg-surface-sunken inset-shadow-well\" />\n    </div>\n  );\n}\n\n/**\n * What screen readers hear after a person's own change, once it settles: the sentence, said\n * politely half a second after the last change. The example is never announced.\n */\nfunction Spoken({ gift, chosen, playing }: { gift: Gift; chosen: boolean; playing: boolean }) {\n  const [said, setSaid] = useState(\"\");\n  const amount = amountOf(gift);\n  const f = gift.frequency;\n  useEffect(() => {\n    if (!chosen || playing) return;\n    const n = unitsFor(amount, f, giving.unit);\n    const left = formatMoney(giving.unit.cost - remainderFor(amount, f, giving.unit));\n    const text = n > 0 ? hero.spoken(formatMoney(amount), hero.per[f], countOf(n, giving.unit), f === \"monthly\" ? hero.what.monthly : hero.what.once) : hero.spokenToward(formatMoney(amount), left, hero.per[f]);\n    const timer = window.setTimeout(() => setSaid(text), 500);\n    return () => window.clearTimeout(timer);\n  }, [amount, f, chosen, playing]);\n  return (\n    <p aria-live=\"polite\" className=\"sr-only\">\n      {said}\n    </p>\n  );\n}\n\n/* ---------- Touch ----------------------------------------------------------------------- */\n\n/** Movement before a touch counts as a drag or a scroll. */\nconst SLOP = 8;\n\n/**\n * The slider on touch. A finger that moves sideways first drags it; one that moves up or down\n * first scrolls the page and leaves the value alone; a tap sets the value under it. The slider's\n * own touch handling is kept out (it would move the value on the first contact, before the\n * gesture is known); mouse, pen and keys go to it as usual.\n */\nfunction useTouchSlide(ref: RefObject<HTMLDivElement | null>, range: { min: number; max: number; step: number }, set: (n: number) => void, onDrag: (d: boolean) => void) {\n  const latest = useRef({ range, set, onDrag });\n  useEffect(() => {\n    latest.current = { range, set, onDrag };\n  });\n  useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    let start: { x: number; y: number } | null = null;\n    let mode: \"pending\" | \"drag\" | \"scroll\" = \"pending\";\n    const valueAt = (x: number) => {\n      const control = el.querySelector(\".touch-none\");\n      if (!control) return null;\n      const box = control.getBoundingClientRect();\n      const { min, max, step } = latest.current.range;\n      const t = Math.min(1, Math.max(0, (x - box.left) / box.width));\n      return Math.min(max, min + Math.round((t * (max - min)) / step) * step);\n    };\n    const apply = (x: number) => {\n      const v = valueAt(x);\n      if (v !== null) latest.current.set(v);\n    };\n    const onPointer = (e: PointerEvent) => {\n      if (e.pointerType === \"touch\") e.stopPropagation();\n    };\n    const onStart = (e: TouchEvent) => {\n      e.stopPropagation();\n      const t = e.touches[0];\n      start = t ? { x: t.clientX, y: t.clientY } : null;\n      mode = \"pending\";\n    };\n    const onMove = (e: TouchEvent) => {\n      const t = e.touches[0];\n      if (!start || !t || mode === \"scroll\") return;\n      const dx = t.clientX - start.x;\n      const dy = t.clientY - start.y;\n      if (mode === \"pending\") {\n        if (Math.abs(dy) > SLOP && Math.abs(dy) >= Math.abs(dx)) mode = \"scroll\";\n        else if (Math.abs(dx) > SLOP) {\n          mode = \"drag\";\n          latest.current.onDrag(true);\n        }\n      }\n      if (mode === \"drag\") apply(t.clientX);\n    };\n    const onEnd = (e: TouchEvent) => {\n      const t = e.changedTouches[0];\n      if (start && t && mode === \"pending\" && e.type === \"touchend\") apply(t.clientX);\n      if (mode === \"drag\") latest.current.onDrag(false);\n      start = null;\n    };\n    el.addEventListener(\"pointerdown\", onPointer, { capture: true });\n    el.addEventListener(\"touchstart\", onStart, { capture: true, passive: true });\n    el.addEventListener(\"touchmove\", onMove, { passive: true });\n    el.addEventListener(\"touchend\", onEnd);\n    el.addEventListener(\"touchcancel\", onEnd);\n    return () => {\n      el.removeEventListener(\"pointerdown\", onPointer, { capture: true });\n      el.removeEventListener(\"touchstart\", onStart, { capture: true });\n      el.removeEventListener(\"touchmove\", onMove);\n      el.removeEventListener(\"touchend\", onEnd);\n      el.removeEventListener(\"touchcancel\", onEnd);\n    };\n  }, [ref]);\n}\n\n/* ---------- Icons ----------------------------------------------------------------------- */\n\n/** Shifted right about 10% of its width, so it sits optically centred (rule 57). */\nfunction PlayIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" className=\"size-4 shrink-0\" fill=\"currentColor\" aria-hidden>\n      <path d=\"M5.5 3.6v8.8a.75.75 0 0 0 1.14.64l7-4.4a.75.75 0 0 0 0-1.28l-7-4.4a.75.75 0 0 0-1.14.64Z\" />\n    </svg>\n  );\n}\n\nfunction StopIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" className=\"size-4 shrink-0\" fill=\"currentColor\" aria-hidden>\n      <rect x=\"4\" y=\"4\" width=\"8\" height=\"8\" rx=\"1.5\" />\n    </svg>\n  );\n}\n",
      "type": "registry:component",
      "target": "@components/eased/templates/nonprofit/hero.tsx"
    },
    {
      "path": "src/registry/eased/templates/nonprofit/demo.ts",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type FocusEvent, type PointerEvent, type RefObject } from \"react\";\nimport { useSafeReducedMotion } from \"../../lib/motion\";\nimport { giving } from \"./content\";\nimport { REST, stepped, type Gift } from \"./gift\";\n\n/**\n * The hero's example: one gift chosen by itself, so a visitor sees what the controls do before\n * touching them. A beat after the jars are well in view it slides the one-off amount up, flips to\n * monthly, flips back and slides home to where it started, about six seconds in all. It plays\n * once per visit, only for someone who hasn't chosen a gift yet, and never under reduced motion\n * (Play the example shows it as a few still steps then).\n *\n * It yields the moment the person acts: a mouse or pen press anywhere in the hero, a key\n * anywhere on the page, focus moving in, or a change to any control (a touch counts only when it changes something, so a\n * swipe that scrolls the page leaves it playing). Stopping drops the example's gift entirely,\n * so the hero shows the person's own (or the resting one) and nothing of the example sticks. It\n * also stops for good when the hero leaves the screen, and pauses while the tab is hidden.\n */\n\n/** Milliseconds: the beat before it moves, the slide up, the hold, monthly, back, the slide home. */\nconst BEAT = 1000;\nconst UP = 1000;\nconst HOLD = 1200;\nconst MONTHLY = 1600;\nconst BACK = 500;\nconst HOME = 800;\nconst END = BEAT + UP + HOLD + MONTHLY + BACK + HOME;\n\ntype Frame = { gift: Gift; tweening: boolean; ended: boolean };\n\n/** The ease-in-out curve (`ease.inOut`) for the slides, as a function. */\nconst inOut = (p: number) => (p < 0.5 ? 4 * p * p * p : 1 - (-2 * p + 2) ** 3 / 2);\n\nfunction slide(from: number, to: number, p: number, reduced: boolean) {\n  if (reduced) return p < 1 ? from : to;\n  return stepped(from + (to - from) * inOut(Math.min(1, Math.max(0, p))), \"once\");\n}\n\n/** The example at `t` ms. Under reduced motion the slides become single steps. */\nexport function exampleAt(t: number, reduced: boolean): Frame {\n  const peak = giving.example.once;\n  const once = (amount: number, tweening = false): Frame => ({ gift: { ...REST, once: amount }, tweening: tweening && !reduced, ended: false });\n  if (t < BEAT) return once(REST.once);\n  if (t < BEAT + UP) return once(slide(REST.once, peak, (t - BEAT) / UP, reduced), true);\n  if (t < BEAT + UP + HOLD) return once(peak);\n  if (t < BEAT + UP + HOLD + MONTHLY) return { gift: { ...REST, frequency: \"monthly\", once: peak, monthly: giving.example.monthly }, tweening: false, ended: false };\n  if (t < END - HOME) return once(peak);\n  if (t < END) return once(slide(peak, REST.once, (t - (END - HOME)) / HOME, reduced), true);\n  return { ...once(REST.once), ended: true };\n}\n\nconst same = (a: Frame | null, b: Frame | null) =>\n  a === b || (!!a && !!b && a.tweening === b.tweening && a.ended === b.ended && a.gift.frequency === b.gift.frequency && a.gift.once === b.gift.once && a.gift.monthly === b.gift.monthly);\n\nconst subscribeVisibility = (onChange: () => void) => {\n  document.addEventListener(\"visibilitychange\", onChange);\n  return () => document.removeEventListener(\"visibilitychange\", onChange);\n};\nconst useTabVisible = () => useSyncExternalStore(subscribeVisibility, () => document.visibilityState === \"visible\", () => true);\n\n/** Whether an event came from the example's own button, which must not stop what it starts. */\nconst fromControl = (target: EventTarget | null) => target instanceof Element && target.closest(\"[data-nf-demo]\") !== null;\n\nexport function useDemo(panel: RefObject<HTMLElement | null>, autoplay: boolean) {\n  const reduced = useSafeReducedMotion();\n  const visible = useTabVisible();\n  const [playing, setPlaying] = useState(false);\n  const [played, setPlayed] = useState(false);\n  const [frame, setFrame] = useState<Frame | null>(null);\n  const clock = useRef(0);\n\n  const stop = useCallback(() => {\n    setPlaying(false);\n    setFrame(null);\n  }, []);\n\n  const play = useCallback(() => {\n    clock.current = 0;\n    auto.current = false;\n    setPlayed(true);\n    setPlaying(true);\n  }, []);\n\n  // Once per visit, for someone who hasn't chosen yet, when the jars are half in view; out of\n  // view, it stops for good, so it never plays on above someone who scrolled away.\n  const started = useRef(false);\n  const allowed = useRef(false);\n  /** Whether this run started by itself: one that did stops if reduced motion or a saved gift turns up during its first beat. */\n  const auto = useRef(false);\n  useEffect(() => {\n    allowed.current = autoplay && !reduced;\n  });\n  useEffect(() => {\n    const el = panel.current;\n    if (!el) return;\n    const io = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.intersectionRatio === 0) stop();\n        else if (entry.intersectionRatio >= 0.5 && !started.current && allowed.current) {\n          started.current = true;\n          play();\n          auto.current = true;\n        }\n      },\n      { threshold: [0, 0.5] },\n    );\n    io.observe(el);\n    return () => io.disconnect();\n  }, [panel, play, stop]);\n\n  // A key anywhere on the page counts: someone tabbing in from the top bar is taking over.\n  useEffect(() => {\n    if (!playing) return;\n    const onKey = (e: KeyboardEvent) => !fromControl(e.target) && stop();\n    window.addEventListener(\"keydown\", onKey, { capture: true });\n    return () => window.removeEventListener(\"keydown\", onKey, { capture: true });\n  }, [playing, stop]);\n\n  // The clock runs in animation frames while playing and the tab is visible.\n  useEffect(() => {\n    if (!playing || !visible) return;\n    let raf = 0;\n    let last = performance.now();\n    const tick = (now: number) => {\n      clock.current += now - last;\n      last = now;\n      const next = exampleAt(clock.current, reduced);\n      if (next.ended || (auto.current && !allowed.current)) {\n        stop();\n        return;\n      }\n      setFrame((prev) => (same(prev, next) ? prev : next));\n      raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [playing, visible, reduced, stop]);\n\n  /** On the hero: the person's own press or focus stops it. Touch waits for a real change. */\n  const yieldOn = useMemo(\n    () => ({\n      onPointerDownCapture: (e: PointerEvent) => {\n        if (e.pointerType !== \"touch\" && !fromControl(e.target)) stop();\n      },\n      onFocusCapture: (e: FocusEvent) => {\n        if (!fromControl(e.target)) stop();\n      },\n    }),\n    [stop],\n  );\n\n  return { gift: playing ? (frame?.gift ?? null) : null, tweening: playing && !!frame?.tweening, playing, played, play, stop, yieldOn };\n}\n",
      "type": "registry:component",
      "target": "@components/eased/templates/nonprofit/demo.ts"
    }
  ],
  "meta": {
    "template": "nonprofit",
    "kind": "template-section",
    "industries": [
      "health"
    ]
  },
  "type": "registry:block"
}