{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "money-flow-chart",
  "title": "Money flow chart",
  "description": "Income ribbons converge on a pooled fund and flow out to spending, with year selection, hover tracing and pinned bands.",
  "dependencies": [
    "motion",
    "liquid-gooey"
  ],
  "registryDependencies": [
    "https://bash-ui-registry.vercel.app/r/info-tooltip.json"
  ],
  "files": [
    {
      "path": "registry/items/money-flow-chart/money-flow-chart.tsx",
      "content": "\"use client\";\n\nimport { type CSSProperties, useEffect, useId, useMemo, useRef, useState } from \"react\";\n\nimport { formatCompactGbp, formatGbp } from \"./fund-flow-format\";\nimport type { FlowBand, FundFlow } from \"./fund-flow-types\";\nimport { useReducedMotionConfig } from \"motion/react\";\nimport { Liquid } from \"liquid-gooey\";\nimport { InfoTooltip } from \"@/components/ui/info-tooltip\";\nimport { BELOW_MD_QUERY, useMediaQuery } from \"./fund-flow-media\";\nimport { formatUkDate } from \"./fund-flow-format\";\n\nconst PLATE = \"var(--ff-plate)\";\nconst PLATE_EDGE = \"var(--ff-plate-edge)\";\nconst FF_INK = \"var(--ff-ink)\";\nconst FF_DIM = \"var(--ff-dim)\";\nconst FF_FAINT = \"var(--ff-faint)\";\nconst FF_RULE = \"var(--ff-rule)\";\n\nconst IN_RAMP = [\n  \"var(--ff-in-0)\",\n  \"var(--ff-in-1)\",\n  \"var(--ff-in-2)\",\n  \"var(--ff-in-3)\",\n  \"var(--ff-in-4)\",\n  \"var(--ff-in-5)\",\n];\nconst OUT_RAMP = [\n  \"var(--ff-out-0)\",\n  \"var(--ff-out-1)\",\n  \"var(--ff-out-2)\",\n  \"var(--ff-out-3)\",\n  \"var(--ff-out-4)\",\n  \"var(--ff-out-5)\",\n];\n\nconst RESIDUAL_FILL = \"var(--ff-residual)\";\n\nconst HUB_FILL = IN_RAMP[0];\n\nconst VIEW_W = 900;\nconst VIEW_H = 505;\nconst PAD = 16;\n\nconst TRIO_Y = 27;\n\nconst HEAD_Y = 60;\nconst LEGEND_Y = 78;\nconst SWATCH_Y = 82;\nconst SWATCH_H = 7;\nconst SWATCH_W = 22;\nconst SWATCH_GAP = 2;\n\nconst PLOT_TOP = 104;\nconst PLOT_BOTTOM = VIEW_H - 25;\nconst PLOT_H = PLOT_BOTTOM - PLOT_TOP;\n\nconst NODE_W = 10;\n\nconst COL_L_X = 238;\nconst COL_R_X = VIEW_W - 238 - NODE_W;\nconst HUB_X = VIEW_W / 2 - NODE_W / 2;\nconst TEXT_L = PAD;\nconst TEXT_R = VIEW_W - PAD;\n\nconst ELBOW = 26;\n\nconst CROP_X = COL_L_X - 2;\nconst CROP_W = COL_R_X + NODE_W + 2 - CROP_X;\nconst CROP_Y = PLOT_TOP - 4;\nconst CROP_H = PLOT_H + 8;\n\nconst YEAR_TAB_WIDTH = 58;\n\nconst FEATHER = 70;\n\nconst POUR_IN_FROM = COL_L_X;\nconst POUR_IN_SPAN = HUB_X + NODE_W - COL_L_X;\nconst POUR_OUT_FROM = HUB_X;\nconst POUR_OUT_SPAN = COL_R_X + NODE_W - HUB_X;\n\nconst GAP_L = 10;\nconst GAP_R = 16;\n\nconst LABEL_PITCH = 28;\n\nconst MIN_BAND_H = 1.4;\n\ntype Placed = {\n  band: FlowBand;\n  y: number;\n  height: number;\n  hubY: number;\n  hubHeight: number;\n  share: number;\n  shade: string;\n  \n  labelY: number;\n};\n\nfunction shadeAt(ramp: string[], rank: number, count: number): string {\n  if (count <= 1) return ramp[0];\n  const step = Math.round((rank * (ramp.length - 1)) / (count - 1));\n  return ramp[Math.min(step, ramp.length - 1)];\n}\n\nfunction declash(centres: number[], pitch: number, top: number, bottom: number): number[] {\n  const out = [...centres];\n  for (let i = 1; i < out.length; i += 1) out[i] = Math.max(out[i], out[i - 1] + pitch);\n  for (let i = out.length - 1; i >= 0; i -= 1) {\n    const ceiling = i === out.length - 1 ? bottom : out[i + 1] - pitch;\n    out[i] = Math.min(out[i], ceiling);\n  }\n  for (let i = 0; i < out.length; i += 1) {\n    const floor = i === 0 ? top : out[i - 1] + pitch;\n    out[i] = Math.max(out[i], floor);\n  }\n  return out;\n}\n\nfunction stack(bands: FlowBand[], total: number, gap: number, ramp: string[]): Placed[] {\n  const ordered = [...bands].sort((a, b) => {\n    const residual = (band: FlowBand) => (band.kind === \"filed\" ? 0 : 1);\n    return residual(a) - residual(b) || b.amount - a.amount;\n  });\n  const filedCount = ordered.filter((band) => band.kind === \"filed\").length;\n  const gapAbove = ordered.map((_, index) => (index === 0 ? 0 : gap));\n  const gaps = gapAbove.reduce((sum, each) => sum + each, 0);\n  const drawable = Math.max(0, PLOT_H - gaps);\n  let y = PLOT_TOP;\n  let hubY = PLOT_TOP;\n\n  const laid = ordered.map((band, rank) => {\n    y += gapAbove[rank];\n    const share = total > 0 ? band.amount / total : 0;\n    const height = share * drawable;\n    const hubHeight = share * PLOT_H;\n    const placed: Placed = {\n      band,\n      y,\n      height,\n      hubY,\n      hubHeight,\n      share,\n      shade: band.kind === \"filed\" ? shadeAt(ramp, rank, filedCount) : RESIDUAL_FILL,\n      labelY: y + height / 2,\n    };\n    y += height;\n    hubY += hubHeight;\n    return placed;\n  });\n\n  const centres = declash(\n    laid.map((placed) => placed.labelY),\n    LABEL_PITCH,\n    // Inset so the topmost name clears the column headers and the lowest\n    // bracket clears the plot edge.\n    PLOT_TOP + 12,\n    PLOT_BOTTOM - 14,\n  );\n  return laid.map((placed, index) => ({ ...placed, labelY: centres[index] }));\n}\n\nfunction share(fraction: number): string {\n  const percent = fraction * 100;\n  if (percent > 0 && percent < 1) return \"<1%\";\n  return `${Math.round(percent)}%`;\n}\n\nfunction ribbon(\n  x0: number,\n  x1: number,\n  top0: number,\n  bottom0: number,\n  top1: number,\n  bottom1: number,\n): string {\n  const mid = (x0 + x1) / 2;\n  return (\n    `M${x0} ${top0} C${mid} ${top0} ${mid} ${top1} ${x1} ${top1} ` +\n    `L${x1} ${bottom1} C${mid} ${bottom1} ${mid} ${bottom0} ${x0} ${bottom0} Z`\n  );\n}\n\nfunction bracket(\n  side: \"in\" | \"out\",\n  labelY: number,\n  bandCentre: number,\n): string {\n  const ruleY = labelY + 12;\n  if (side === \"in\") {\n    const turn = COL_L_X - ELBOW;\n    return `M${TEXT_L} ${ruleY} L${turn} ${ruleY} L${COL_L_X} ${bandCentre}`;\n  }\n  const nodeEdge = COL_R_X + NODE_W;\n  const turn = nodeEdge + ELBOW;\n  return `M${TEXT_R} ${ruleY} L${turn} ${ruleY} L${nodeEdge} ${bandCentre}`;\n}\n\nexport type { FundFlow, FlowBand } from \"./fund-flow-types\";\nexport type MoneyFlowChartProps = { flows: FundFlow[]; animated?: boolean; showDetails?: boolean };\nexport function MoneyFlowChart({ flows, animated = true, showDetails = true }: MoneyFlowChartProps) {\n  const reducedMotion = useReducedMotionConfig();\n  const [yearIndex, setYearIndex] = useState(0);\n  const [hovered, setHovered] = useState<string | null>(null);\n  const [pinned, setPinned] = useState<string | null>(null);\n  const [enteredView, setRevealed] = useState(false);\n  const revealed = !animated || reducedMotion || enteredView;\n  \n  const rawId = useId().replace(/:/g, \"\");\n  const POUR_IN = `${rawId}-pour-in`;\n  const POUR_OUT = `${rawId}-pour-out`;\n  \n  const [replay, setReplay] = useState(0);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const compact = useMediaQuery(BELOW_MD_QUERY);\n\n  // Nothing to draw is a legitimate state, not an error: most charities file a\n  // year that cannot be squared, and the caller renders the income panel\n  // instead. Guarded here as well so the component is safe on its own terms —\n  // an empty list would otherwise index to -1 and read `.inflows` of undefined.\n  const flow = flows.length > 0 ? flows[Math.min(yearIndex, flows.length - 1)] : null;\n\n  const inflows = useMemo(\n    () => (flow ? stack(flow.inflows, flow.total, GAP_L, IN_RAMP) : []),\n    [flow],\n  );\n  const outflows = useMemo(\n    () => (flow ? stack(flow.outflows, flow.total, GAP_R, OUT_RAMP) : []),\n    [flow],\n  );\n\n  // Scroll into view to play; click anywhere on the figure to replay.\n  useEffect(() => {\n    const node = rootRef.current;\n    if (!node) return;\n    if (typeof IntersectionObserver === \"undefined\") {\n      // No observer to wait on, so reveal on the next frame rather than during\n      // this effect — a synchronous setState here cascades a second render.\n      const frame = requestAnimationFrame(() => setRevealed(true));\n      return () => cancelAnimationFrame(frame);\n    }\n    const observer = new IntersectionObserver(\n      (entries) => {\n        if (entries.some((entry) => entry.isIntersecting)) {\n          setRevealed(true);\n          observer.disconnect();\n        }\n      },\n      { threshold: 0.25 },\n    );\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n\n  // After every hook, so the hook order stays fixed across renders.\n  if (!flow) return null;\n\n  const focus = pinned ?? hovered;\n  const active =\n    [...inflows, ...outflows].find((placed) => placed.band.id === focus) ?? null;\n\n  const bandOpacity = (id: string) => (focus === null || focus === id ? 1 : 0.26);\n  const ribbonOpacity = (id: string) =>\n    focus === null ? 0.72 : focus === id ? 0.92 : 0.1;\n  const labelOpacity = (id: string) => (focus === null || focus === id ? 1 : 0.3);\n\n  const sides = [\n    { key: \"in\" as const, placed: inflows, ramp: IN_RAMP },\n    { key: \"out\" as const, placed: outflows, ramp: OUT_RAMP },\n  ];\n\n  const coarseSides = [\n    flow.incomeIsTotalOnly ? \"what came in\" : null,\n    flow.spendIsTotalOnly ? \"what it paid for\" : null,\n  ].filter((side): side is string => side !== null);\n\n  const incomeTotal = flow.inflows\n    .filter((band) => band.kind === \"filed\")\n    .reduce((sum, band) => sum + band.amount, 0);\n  const spendTotal = flow.outflows\n    .filter((band) => band.kind === \"filed\")\n    .reduce((sum, band) => sum + band.amount, 0);\n  const net = incomeTotal - spendTotal;\n  const netFill = net > 0 ? IN_RAMP[0] : net < 0 ? OUT_RAMP[0] : FF_DIM;\n  const netTag = net > 0 ? \"SURPLUS\" : net < 0 ? \"DEFICIT\" : \"BALANCED\";\n\n  return (\n    <div ref={rootRef} className=\"fund-flow-plate w-full min-w-0 font-body\" data-ff-motion={animated && !reducedMotion ? \"on\" : \"off\"}>\n      <style>{`\n        \n        @keyframes ffRise { from { opacity: 0; transform: translateY(11px) } }\n        \n        @keyframes ffGrowUp { from { transform: scaleY(0) } to { transform: scaleY(1) } }\n        \n        @keyframes ffPour { to { transform: translateX(var(--ff-travel)) } }\n        @keyframes ffSlideIn { from { opacity: 0; transform: translateX(-15px) } }\n        @keyframes ffSlideOut { from { opacity: 0; transform: translateX(15px) } }\n        @keyframes ffDraw { from { stroke-dashoffset: 1 } to { stroke-dashoffset: 0 } }\n\n        .ff-rise { animation: ffRise .6s cubic-bezier(.22,.68,.24,1) both }\n        .ff-grow { animation: ffGrowUp .5s cubic-bezier(.22,.68,.24,1) both; transform-box: view-box }\n        .ff-pour { animation: ffPour .76s cubic-bezier(.36,.1,.24,1) both; transform-box: view-box }\n        .ff-slide-in { animation: ffSlideIn .52s cubic-bezier(.22,.68,.24,1) both }\n        .ff-slide-out { animation: ffSlideOut .52s cubic-bezier(.22,.68,.24,1) both }\n        .ff-draw { stroke-dasharray: 1; animation: ffDraw .52s cubic-bezier(.22,.68,.24,1) both }\n\n        [data-ff-motion=\"off\"] .ff-rise, [data-ff-motion=\"off\"] .ff-grow,\n        [data-ff-motion=\"off\"] .ff-pour, [data-ff-motion=\"off\"] .ff-slide-in,\n        [data-ff-motion=\"off\"] .ff-slide-out, [data-ff-motion=\"off\"] .ff-draw { animation: none }\n        [data-ff-motion=\"off\"] .ff-draw { stroke-dasharray: none }\n        [data-ff-motion=\"off\"] .ff-pour { transform: translateX(var(--ff-travel)) }\n        @media (prefers-reduced-motion: reduce) {\n          .ff-rise, .ff-grow, .ff-pour,\n          .ff-slide-in, .ff-slide-out, .ff-draw { animation: none }\n          \n          .ff-draw { stroke-dasharray: none }\n          .ff-pour { transform: translateX(var(--ff-travel)) }\n        }\n      `}</style>\n\n      <div className=\"flex flex-wrap items-center justify-between gap-x-4 gap-y-2\">\n        <h4 className=\"text-[16.5px] font-medium font-body tracking-[-0.02em] text-ink\">\n          Spent{\" \"}\n          <span style={{ color: OUT_RAMP[0] }}>\n            {formatCompactGbp(spendTotal)}\n          </span>{\" \"}\n          against{\" \"}\n          <span className=\"text-go\">\n            {formatCompactGbp(incomeTotal)}\n          </span>{\" \"}\n          of income,{\" \"}\n          {net < 0 ? (\n            <>\n              ending the year with a{\" \"}\n              <span className=\"text-stop\">\n                {formatCompactGbp(-net)} deficit\n              </span>\n              .\n            </>\n          ) : net > 0 ? (\n            <>\n              ending the year with a{\" \"}\n              <span className=\"text-go\">\n                {formatCompactGbp(net)} surplus\n              </span>\n              .\n            </>\n          ) : (\n            \"ending the year balanced.\"\n          )}\n        </h4>\n        {flows.length > 1 && (\n          <Liquid\n            blur={5}\n            contrast={18}\n            fill=\"var(--ink)\"\n            shadow=\"0 2px 6px color-mix(in oklab, var(--ink) 25%, transparent)\"\n            className=\"relative inline-flex items-center overflow-x-auto rounded-full border border-rule-soft bg-paper p-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n            role=\"group\"\n            aria-label=\"Filed year\"\n          >\n            <Liquid.Item effect=\"move\" move={{ springiness: 0.6, trail: 0.5, stretch: 0.25 }}>\n              <div\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute top-0.5 bottom-0.5 left-0.5 rounded-full bg-ink transition-transform duration-300 ease-out motion-reduce:transition-none\"\n                style={{\n                  width: `${YEAR_TAB_WIDTH}px`,\n                  transform: `translateX(${yearIndex * YEAR_TAB_WIDTH}px)`,\n                }}\n              />\n            </Liquid.Item>\n\n            <div className=\"relative z-10 flex items-center\">\n              {flows.map((candidate, index) => (\n                <button\n                  key={candidate.periodEnd}\n                  type=\"button\"\n                  onClick={() => {\n                    setYearIndex(index);\n                    setPinned(null);\n                    setReplay((n) => n + 1);\n                  }}\n                  aria-pressed={index === yearIndex}\n                  style={{ width: `${YEAR_TAB_WIDTH}px` }}\n                  className={`flex h-7 shrink-0 cursor-pointer items-center justify-center rounded-full font-mono text-[11px] font-semibold tracking-[0.06em] whitespace-nowrap transition-colors duration-200 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ink ${\n                    index === yearIndex\n                      ? \"text-on-solid\"\n                      : \"text-faint hover:text-dim\"\n                  }`}\n                >\n                  {candidate.label}\n                </button>\n              ))}\n            </div>\n          </Liquid>\n        )}\n      </div>\n\n      <p className=\"mt-1 text-[13.5px] text-dim\">\n        Ribbon width = pounds through the year · year ended{\" \"}\n        {formatUkDate(flow.periodEnd)}\n      </p>\n\n      <div className=\"mt-3\" onClick={() => setPinned(null)}>\n        <div>\n          <svg\n            key={`${flow.periodEnd}-${replay}`}\n            viewBox={\n              compact\n                ? `${CROP_X} ${CROP_Y} ${CROP_W} ${CROP_H}`\n                : `0 0 ${VIEW_W} ${VIEW_H}`\n            }\n            className=\"w-full cursor-default\"\n            role=\"img\"\n            aria-label={`Fund flow for ${flow.label}. In: ${flow.inflows\n              .map((band) => `${band.label} ${formatGbp(band.amount)}`)\n              .join(\", \")}. Out: ${flow.outflows\n              .map((band) => `${band.label} ${formatGbp(band.amount)}`)\n              .join(\", \")}.`}\n          >\n            <rect\n              x={0}\n              y={0}\n              width={VIEW_W}\n              height={VIEW_H}\n              fill={PLATE}\n            />\n\n            <defs>\n              {[\n                {\n                  id: POUR_IN,\n                  from: POUR_IN_FROM,\n                  span: POUR_IN_SPAN,\n                  delay: \"0.22s\",\n                },\n                {\n                  id: POUR_OUT,\n                  from: POUR_OUT_FROM,\n                  span: POUR_OUT_SPAN,\n                  delay: \"0.60s\",\n                },\n              ].map(({ id, from, span, delay }) => {\n                // The rect carries its own feather, so it must travel its own\n                // width for the solid part to clear the far end.\n                const travel = span + FEATHER;\n                return (\n                  <mask\n                    key={id}\n                    id={id}\n                    maskUnits=\"userSpaceOnUse\" style={{ maskType: \"alpha\" }}\n                    x={0}\n                    y={0}\n                    width={VIEW_W}\n                    height={VIEW_H}\n                  >\n                    \n                    <linearGradient id={`${id}-front`} x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">\n                      <stop offset={0} stopColor=\"currentColor\" stopOpacity={1} /> \n                      <stop offset={span / travel} stopColor=\"currentColor\" stopOpacity={1} /> \n                      <stop offset={1} stopColor=\"currentColor\" stopOpacity={0} /> \n                    </linearGradient>\n                    <rect\n                      x={from - travel}\n                      y={PLOT_TOP - 8}\n                      width={travel}\n                      height={PLOT_H + 16}\n                      fill={`url(#${id}-front)`}\n                      className={revealed ? \"ff-pour\" : undefined}\n                      style={\n                        {\n                          \"--ff-travel\": `${travel}px`,\n                          animationDelay: delay,\n                        } as CSSProperties\n                      }\n                    />\n                  </mask>\n                );\n              })}\n            </defs>\n\n          {!compact && (\n            <>\n          \n          <text\n            x={VIEW_W / 2}\n            y={TRIO_Y}\n            textAnchor=\"middle\"\n            \n            className={revealed ? \"ff-rise\" : undefined}\n            style={{ animationDelay: \"1.0s\" }}\n            opacity={revealed ? 1 : 0}\n          >\n            <tspan fontSize={12.5} fontWeight={800} fill={IN_RAMP[0]}>\n              {formatCompactGbp(incomeTotal).toUpperCase()}\n            </tspan>\n            <tspan\n              fontSize={7.5}\n              fontWeight={700}\n              letterSpacing=\"0.12em\"\n              fill={FF_DIM}\n            >\n              {\"  IN  \"}\n            </tspan>\n            <tspan fontSize={10} fill={FF_FAINT}>\n              {\"·\"}\n            </tspan>\n            <tspan fontSize={12.5} fontWeight={800} fill={OUT_RAMP[0]}>\n              {`  ${formatCompactGbp(spendTotal).toUpperCase()}`}\n            </tspan>\n            <tspan\n              fontSize={7.5}\n              fontWeight={700}\n              letterSpacing=\"0.12em\"\n              fill={FF_DIM}\n            >\n              {\"  OUT  \"}\n            </tspan>\n            <tspan fontSize={10} fill={FF_FAINT}>\n              {\"·\"}\n            </tspan>\n            <tspan fontSize={12.5} fontWeight={800} fill={netFill}>\n              {`  ${net === 0 ? \"\" : formatCompactGbp(Math.abs(net)).toUpperCase()}${net === 0 ? \"\" : \" \"}${netTag}`}\n            </tspan>\n          </text>\n\n          <text\n            x={TEXT_L}\n            y={HEAD_Y}\n            fontSize={11}\n            fontWeight={800}\n            letterSpacing=\"0.09em\"\n            fill={FF_INK}\n          >\n            MONEY IN\n          </text>\n          <text\n            x={TEXT_R}\n            y={HEAD_Y}\n            textAnchor=\"end\"\n            fontSize={11}\n            fontWeight={800}\n            letterSpacing=\"0.09em\"\n            fill={FF_INK}\n          >\n            MONEY OUT\n          </text>\n\n          {sides.map(({ key, ramp, placed }) => {\n            // One band carries no rank, so its ramp is a legend for a scale\n            // that is not being used. Residual bands sit outside the ramp and\n            // do not count towards having one.\n            if (placed.filter((entry) => entry.band.kind === \"filed\").length < 2) return null;\n            const width = ramp.length * SWATCH_W + (ramp.length - 1) * SWATCH_GAP;\n            const x0 = key === \"in\" ? TEXT_L : TEXT_R - width;\n            const wordProps = {\n              fontSize: 6.5,\n              fontWeight: 600,\n              letterSpacing: \"0.12em\",\n              fill: FF_FAINT,\n            } as const;\n            return (\n              <g key={`legend-${key}`}>\n                <text x={x0} y={LEGEND_Y} textAnchor=\"start\" {...wordProps}>\n                  SMALLEST\n                </text>\n                <text\n                  x={x0 + width}\n                  y={LEGEND_Y}\n                  textAnchor=\"end\"\n                  {...wordProps}\n                >\n                  LARGEST\n                </text>\n                {[...ramp].reverse().map((fill, index) => (\n                  <rect\n                    key={fill}\n                    x={x0 + index * (SWATCH_W + SWATCH_GAP)}\n                    y={SWATCH_Y}\n                    width={SWATCH_W}\n                    height={SWATCH_H}\n                    fill={fill}\n                  />\n                ))}\n              </g>\n            );\n          })}\n\n            </>\n          )}\n\n          <g>\n            <g mask={`url(#${POUR_IN})`}>\n              {inflows.map((placed) => (\n                <path\n                  key={`in-${placed.band.id}`}\n                  d={ribbon(\n                    COL_L_X + NODE_W,\n                    HUB_X,\n                    placed.y,\n                    placed.y + Math.max(placed.height, MIN_BAND_H),\n                    placed.hubY,\n                    placed.hubY + Math.max(placed.hubHeight, MIN_BAND_H),\n                  )}\n                  fill={placed.shade}\n                  opacity={revealed ? ribbonOpacity(placed.band.id) : 0}\n                  className=\"cursor-pointer transition-opacity\"\n                  onMouseEnter={() => setHovered(placed.band.id)}\n                  onMouseLeave={() => setHovered(null)}\n                  onClick={(event) => {\n                    event.stopPropagation();\n                    setPinned((current) =>\n                      current === placed.band.id ? null : placed.band.id,\n                    );\n                  }}\n                >\n                  <title>{`${placed.band.label}: ${formatGbp(placed.band.amount)}`}</title>\n                </path>\n              ))}\n            </g>\n            <g mask={`url(#${POUR_OUT})`}>\n              {outflows.map((placed) => (\n                <path\n                  key={`out-${placed.band.id}`}\n                  d={ribbon(\n                    HUB_X + NODE_W,\n                    COL_R_X,\n                    placed.hubY,\n                    placed.hubY + Math.max(placed.hubHeight, MIN_BAND_H),\n                    placed.y,\n                    placed.y + Math.max(placed.height, MIN_BAND_H),\n                  )}\n                  fill={placed.shade}\n                  opacity={revealed ? ribbonOpacity(placed.band.id) : 0}\n                  className=\"cursor-pointer transition-opacity\"\n                  onMouseEnter={() => setHovered(placed.band.id)}\n                  onMouseLeave={() => setHovered(null)}\n                  onClick={(event) => {\n                    event.stopPropagation();\n                    setPinned((current) =>\n                      current === placed.band.id ? null : placed.band.id,\n                    );\n                  }}\n                >\n                  <title>{`${placed.band.label}: ${formatGbp(placed.band.amount)}`}</title>\n                </path>\n              ))}\n            </g>\n          </g>\n\n          <rect\n            x={HUB_X}\n            y={PLOT_TOP}\n            width={NODE_W}\n            height={PLOT_H}\n            fill={HUB_FILL}\n            className={revealed ? \"ff-grow\" : undefined}\n            style={{ transformOrigin: `${HUB_X}px ${PLOT_BOTTOM}px` }}\n            opacity={revealed ? 1 : 0}\n          />\n\n          {sides.map(({ key, placed }) => {\n            const x = key === \"in\" ? COL_L_X : COL_R_X;\n            const anchor = key === \"in\" ? (\"start\" as const) : (\"end\" as const);\n            const textX = key === \"in\" ? TEXT_L : TEXT_R;\n            // Written per side rather than derived from one margin: the two\n            // gutters happen to be the same width today, and a hit target that\n            // silently depends on that is a trap for whoever changes one.\n            const hitX = key === \"in\" ? TEXT_L - 6 : COL_R_X;\n            const hitW =\n              key === \"in\" ? COL_L_X + NODE_W - TEXT_L + 12 : TEXT_R - COL_R_X + 6;\n            \n            const beat = key === \"in\" ? 0.06 : 0.46;\n            return placed.map((entry, index) => {\n              const centre = entry.y + Math.max(entry.height, MIN_BAND_H) / 2;\n              const step = beat + index * 0.04;\n              const picked = focus === entry.band.id;\n              // Compact has no labels to reach, so the target is the band alone\n              // — stretched to the label it would have overlapped a neighbour.\n              const hitTop = compact ? entry.y - 3 : Math.min(entry.labelY - 15, entry.y - 3);\n              const hitBottom = compact\n                ? entry.y + entry.height + 3\n                : Math.max(entry.labelY + 16, entry.y + entry.height + 3);\n              return (\n                <g\n                  key={`${key}-${entry.band.id}`}\n                  onMouseEnter={() => setHovered(entry.band.id)}\n                  onMouseLeave={() => setHovered(null)}\n                  onFocus={() => setHovered(entry.band.id)}\n                  onBlur={() => setHovered(null)}\n                  onClick={(event) => {\n                    event.stopPropagation();\n                    setPinned((current) =>\n                      current === entry.band.id ? null : entry.band.id,\n                    );\n                  }}\n                  role=\"button\"\n                  aria-pressed={pinned === entry.band.id}\n                  onKeyDown={(event) => {\n                    if (event.key === \"Enter\" || event.key === \" \") {\n                      event.preventDefault();\n                      event.stopPropagation();\n                      setPinned((current) => current === entry.band.id ? null : entry.band.id);\n                    }\n                  }}\n                  tabIndex={0}\n                  aria-label={`${entry.band.label}: ${formatGbp(entry.band.amount)}`}\n                  className=\"cursor-pointer outline-none\"\n                >\n                  \n                  <rect\n                    x={hitX}\n                    y={hitTop}\n                    width={hitW}\n                    height={Math.max(hitBottom - hitTop, 12)}\n                    // Paints nothing — the hit area, where only the box matters.\n                    fill=\"currentColor\"\n                    fillOpacity={0}\n                  />\n                  {!compact && (\n                  <path\n                    d={bracket(key, entry.labelY, centre)}\n                    fill=\"none\"\n                    stroke={picked ? FF_INK : FF_RULE}\n                    strokeWidth={picked ? 1 : 0.7}\n                    \n                    pathLength={1}\n                    opacity={revealed ? labelOpacity(entry.band.id) : 0}\n                    className={revealed ? \"ff-draw transition-opacity\" : undefined}\n                    style={{ animationDelay: `${step + 0.15}s` }}\n                  />\n                  )}\n                  <rect\n                    x={x}\n                    y={entry.y}\n                    width={NODE_W}\n                    height={Math.max(entry.height, 2)}\n                    fill={entry.shade}\n                    opacity={revealed ? bandOpacity(entry.band.id) : 0}\n                    className={revealed ? \"ff-grow transition-opacity\" : undefined}\n                    style={{\n                      transformOrigin: `${x}px ${entry.y + Math.max(entry.height, 2)}px`,\n                      animationDelay: `${step}s`,\n                    }}\n                  />\n                  {!compact && (\n                  <g\n                    className={\n                      revealed\n                        ? key === \"in\"\n                          ? \"ff-slide-in\"\n                          : \"ff-slide-out\"\n                        : undefined\n                    }\n                    opacity={revealed ? labelOpacity(entry.band.id) : 0}\n                    style={{ animationDelay: `${step + 0.12}s` }}\n                  >\n                    <text\n                      x={textX}\n                      y={entry.labelY - 3}\n                      textAnchor={anchor}\n                      fontSize={10}\n                      fontWeight={700}\n                      fill={FF_INK}\n                    >\n                      {entry.band.label}\n                    </text>\n                    <text\n                      x={textX}\n                      y={entry.labelY + 8}\n                      textAnchor={anchor}\n                      fontSize={9.5}\n                      fill={FF_DIM}\n                    >\n                      {formatCompactGbp(entry.band.amount)} · {share(entry.share)}\n                    </text>\n                  </g>\n                  )}\n                </g>\n              );\n            });\n          })}\n        </svg>\n        </div>\n\n        {compact && (\n          <div className=\"mt-3 grid gap-4\">\n            {sides.map(({ key, placed }) => (\n              <div key={`list-${key}`}>\n                <p className=\"text-[11px] font-extrabold tracking-[0.09em] text-ink\">\n                  {key === \"in\" ? \"MONEY IN\" : \"MONEY OUT\"}\n                </p>\n                <ul className=\"mt-1\">\n                  {placed.map((entry) => (\n                    <li key={`list-${key}-${entry.band.id}`}>\n                      <button\n                        type=\"button\"\n                        aria-pressed={pinned === entry.band.id}\n                        onClick={(event) => {\n                          event.stopPropagation();\n                          setPinned((current) =>\n                            current === entry.band.id ? null : entry.band.id,\n                          );\n                        }}\n                        style={{ opacity: labelOpacity(entry.band.id) }}\n                        className=\"flex min-h-11 w-full cursor-pointer items-center gap-2.5 border-b border-rule-soft text-left transition-opacity focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-lead\"\n                      >\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"size-3 shrink-0 rounded-inset\"\n                          style={{ backgroundColor: entry.shade }}\n                        />\n                        <span className=\"min-w-0 flex-1 text-[13px] font-semibold text-ink\">\n                          {entry.band.label}\n                        </span>\n                        <span className=\"shrink-0 font-mono text-[12px] tabular-nums text-dim\">\n                          {formatCompactGbp(entry.band.amount)} · {share(entry.share)}\n                        </span>\n                      </button>\n                    </li>\n                  ))}\n                </ul>\n              </div>\n            ))}\n          </div>\n        )}\n\n      <p className=\"mt-2 min-h-[22px] text-[14px] leading-snug font-medium text-lead\" aria-live=\"polite\">\n        {active ? (\n          <>\n            <span className=\"font-semibold text-ink\">{active.band.label}</span> —{\" \"}\n            {formatGbp(active.band.amount)}, {share(active.share)} of the{\" \"}\n            {formatCompactGbp(flow.total)} that passed through\n            {active.band.kind === \"surplus\" &&\n              \" · what the year's income left after spending\"}\n            {active.band.kind === \"reserves\" &&\n              \" · spending the year's income did not cover\"}\n            {pinned && (\n              <span className=\"ml-2 font-mono text-[9.5px] font-bold tracking-[0.1em] text-faint\">\n                PINNED · CLICK AGAIN TO RELEASE\n              </span>\n            )}\n          </>\n        ) : (\n          coarseSides.length === 2\n            ? \"Both bands are the year's filed totals. Select one to trace it; select it again to unpin.\"\n            : \"Every band is money the annual return itself reports. Select one to trace it; select it again to unpin.\"\n        )}\n      </p>\n\n      {coarseSides.length > 0 && (\n        <p className=\"mt-1.5 text-[12px] leading-[1.5] text-faint\">\n          \n          {coarseSides.length === 2\n            ? \"Drawn from the year's filed totals — no breakdown of income or spending was published for this year.\"\n            : `Drawn from the year's filed total for ${coarseSides[0]} — no breakdown of it was published for this year.`}\n        </p>\n      )}\n    </div>\n\n      {showDetails && (flow.incomeDetail.length > 0 || flow.spendDetail.length > 0) && (\n        <div\n          className=\"mt-3 rounded-inset border px-4 py-3\"\n          style={{ borderColor: PLATE_EDGE, backgroundColor: PLATE }}\n        >\n          <div className=\"grid gap-x-8 gap-y-4 sm:grid-cols-2\">\n            {flow.incomeDetail.length > 0 && (\n              <div>\n                <div className=\"flex items-center gap-1.5\">\n                  <h4\n                    className=\"text-[12.5px] font-semibold\"\n                    style={{ color: FF_INK }}\n                  >\n                    Included in income\n                  </h4>\n                  <InfoTooltip content=\"Already counted in the bands above\" />\n                </div>\n                <ul\n                  className=\"mt-2 space-y-1.5 border-t pt-2\"\n                  style={{ borderColor: `color-mix(in oklab, ${FF_RULE} 50%, transparent)` }}\n                >\n                  {flow.incomeDetail.map((source) => (\n                    <li\n                      key={source.label}\n                      className=\"flex items-baseline justify-between gap-3 text-[12.5px]\"\n                    >\n                      <span style={{ color: FF_DIM }}>{source.label}</span>\n                      <span\n                        className=\"font-mono tabular-nums font-medium\"\n                        style={{ color: FF_INK }}\n                      >\n                        {formatCompactGbp(source.amount)}\n                      </span>\n                    </li>\n                  ))}\n                </ul>\n              </div>\n            )}\n            {flow.spendDetail.length > 0 && (\n              <div>\n                <div className=\"flex items-center gap-1.5\">\n                  <h4\n                    className=\"text-[12.5px] font-semibold\"\n                    style={{ color: FF_INK }}\n                  >\n                    Included in spending\n                  </h4>\n                  <InfoTooltip content=\"Already counted in the bands above\" />\n                </div>\n                <ul\n                  className=\"mt-2 space-y-1.5 border-t pt-2\"\n                  style={{ borderColor: `color-mix(in oklab, ${FF_RULE} 50%, transparent)` }}\n                >\n                  {flow.spendDetail.map((use) => (\n                    <li\n                      key={use.label}\n                      className=\"flex items-baseline justify-between gap-3 text-[12.5px]\"\n                    >\n                      <span style={{ color: FF_DIM }}>\n                        {use.label}\n                        {use.within && (\n                          <span className=\"text-[11.5px]\" style={{ color: FF_FAINT }}>\n                            {\" \"}\n                            (inside {use.within})\n                          </span>\n                        )}\n                      </span>\n                      <span\n                        className=\"font-mono tabular-nums font-medium\"\n                        style={{ color: FF_INK }}\n                      >\n                        {formatCompactGbp(use.amount)}\n                      </span>\n                    </li>\n                  ))}\n                </ul>\n              </div>\n            )}\n          </div>\n          {Math.max(flow.incomeDrift, flow.spendDrift) > 0.001 && (\n            <p\n              className=\"mt-2.5 border-t pt-2 text-[11.5px] leading-[1.5]\"\n              style={{ borderColor: FF_RULE, color: FF_FAINT }}\n            >\n              The filed lines and the filed totals differ by ${(\n                Math.max(flow.incomeDrift, flow.spendDrift) * 100\n              ).toFixed(1)}% this year, which is the return restating a figure between the two.\n            </p>\n          )}\n        </div>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/money-flow-chart/fund-flow-types.ts",
      "content": "export type FlowDetail = { label: string; amount: number; within?: string | null };\nexport type FlowBand = {\n  \n  id: string;\n  label: string;\n  amount: number;\n  \n  kind: \"filed\" | \"surplus\" | \"reserves\";\n  \n  government?: boolean;\n};\n\nexport type FundFlow = {\n  \n  label: string;\n  periodEnd: string;\n  \n  headline: string;\n  \n  inflows: FlowBand[];\n  \n  outflows: FlowBand[];\n  \n  total: number;\n  \n  governmentIncome: number | null;\n  \n  incomeDetail: FlowDetail[];\n  spendDetail: FlowDetail[];\n  \n  incomeIsTotalOnly: boolean;\n  spendIsTotalOnly: boolean;\n  \n  incomeDrift: number;\n  spendDrift: number;\n};\n\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/money-flow-chart/fund-flow-format.ts",
      "content": "const GBP_FORMATTER = new Intl.NumberFormat(\"en-GB\", {\n  style: \"currency\",\n  currency: \"GBP\",\n  maximumFractionDigits: 0,\n});\n\n/** Formats a monetary number into standard GBP, or returns \"Not disclosed\" if null/undefined. */\nexport function formatGbp(amount: number | null | undefined): string {\n  if (amount === null || amount === undefined || Number.isNaN(amount)) {\n    return \"Not disclosed\";\n  }\n  return GBP_FORMATTER.format(amount);\n}\n\n/** Formats a monetary number into a compact string (e.g. £450k, £1.2m). */\nexport function formatCompactGbp(amount: number | null | undefined): string {\n  if (amount === null || amount === undefined || Number.isNaN(amount)) {\n    return \"Not disclosed\";\n  }\n  const abs = Math.abs(amount);\n  const sign = amount < 0 ? \"-\" : \"\";\n  if (abs >= 1_000_000) {\n    return `${sign}£${(abs / 1_000_000).toFixed(1).replace(/\\.0$/, \"\")}m`;\n  }\n  if (abs >= 1_000) {\n    return `${sign}£${Math.round(abs / 1_000)}k`;\n  }\n  return `${sign}£${abs.toLocaleString(\"en-GB\")}`;\n}\n\n\nexport function formatUkDate(value: string) {\n  const date = new Date(value.length === 10 ? value + \"T00:00:00Z\" : value);\n  return Number.isNaN(date.getTime()) ? \"Unknown date\" : date.toLocaleDateString(\"en-GB\", { day: \"numeric\", month: \"long\", year: \"numeric\", timeZone: \"UTC\" });\n}\n",
      "type": "registry:block"
    },
    {
      "path": "registry/items/money-flow-chart/fund-flow-media.ts",
      "content": "\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\nexport function useMediaQuery(query: string): boolean {\n  return useSyncExternalStore(\n    (onChange) => {\n      const media = window.matchMedia(query);\n      media.addEventListener(\"change\", onChange);\n      return () => media.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n\nexport const PHONE_QUERY = \"(width < 40rem)\";\n\nexport const BELOW_MD_QUERY = \"(width < 48rem)\";\n",
      "type": "registry:block"
    }
  ],
  "meta": {
    "kind": "pattern",
    "whenToUse": "Use for balanced money flows through a shared pot. Each side must sum to total; include a surplus or reserves band to balance the year. It does not claim which source funded which activity.",
    "origin": {
      "project": "180Connect",
      "path": "src/app/(app)/clients/[id]/financials/fund-flow-sankey.tsx"
    },
    "credits": [
      {
        "name": "liquid-gooey",
        "url": "https://github.com/Jakubantalik/Libraries",
        "license": "MIT"
      }
    ]
  },
  "type": "registry:block"
}
