{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"price-band","title":"Price band","description":"A price band as a picture: how far from the market a line can sit across shelf prices (log scale) before it reads as priced above or below market, with tiers as steps, dollar limits as narrowing, a hover readout and optional line counts; plus a table-row mini.","registryDependencies":["https://ui.twelfth.ai/r/market-side.json","https://ui.twelfth.ai/r/retail-format.json"],"files":[{"path":"src/registry/catman/ui/price-band.tsx","content":"\"use client\"\n\nimport { useState, type PointerEvent } from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { formatUnits } from \"@/registry/catman/lib/retail-format\"\n\n/**\n * A price band as a picture: how far from the market price a line can sit,\n * across our shelf prices, before it reads as priced above or below market.\n * Shelf price runs left to right on a log scale; the gap to market runs up\n * (we're dearer) and down (we're cheaper). The plain middle is in line; the\n * tinted top and bottom are above and below market. A dollar limit narrows the\n * middle as the price grows; a price tier steps it.\n *\n * It prints no wording for the band itself (\"±10% under $500\"): that is the\n * caller's, beside the picture, so there is one source for how a band reads.\n *\n * Part of the twelfth catman registry (`@twelfth/price-band`). The zones read\n * the `favourable` and `exposed` colour tokens installed by market-side.\n */\n\n/** One tier: in line from `belowPct` under to `abovePct` over market, each side optionally capped at a dollar gap. */\nexport type PriceBandTier = { abovePct: number; belowPct: number; aboveAmount?: number; belowAmount?: number }\n\n/** The band from $0, then any tiers that take over from a higher shelf price. */\nexport type PriceBandShape = PriceBandTier & { tiers?: Array<PriceBandTier & { fromPrice: number }> }\n\nexport type PriceBandLineCounts = { below: number; inLine: number; above: number }\n\nexport type PriceBandLabels = {\n  /** The top zone. */\n  above: string\n  /** The bottom zone. */\n  below: string\n  /** The middle. */\n  inLine: string\n  /** The zero line, on the gap scale. */\n  market: string\n  /** The shelf-price axis. */\n  axis: string\n  /** What the picture shows, for a screen reader. */\n  description: string\n}\n\nconst DEFAULT_LABELS: PriceBandLabels = {\n  above: \"Above market\",\n  below: \"Below market\",\n  inLine: \"In line\",\n  market: \"Market\",\n  axis: \"Shelf $\",\n  description: \"Price band by shelf price: lines within it read as in line with market; further above, as priced above market; further below, as priced below market.\",\n}\n\ntype Tier = PriceBandTier & { fromPrice: number }\n\nconst cents = (dollars: number) => Math.round(dollars * 100)\n\n/** The tiers in force from $0, cheapest first. */\nfunction tierList(band: PriceBandShape): Tier[] {\n  return [{ ...band, fromPrice: 0 }, ...(band.tiers ?? [])]\n}\n\n/** The tier a line at shelf price `price` takes: the last whose from-price is at or below it. */\nfunction tierAt(tiers: Tier[], price: number): Tier {\n  let chosen = tiers[0]!\n  for (const tier of tiers) if (cents(tier.fromPrice) <= cents(price)) chosen = tier\n  return chosen\n}\n\n/** The in-line gap at a shelf price, in percent of the market price: up to `above` over, `below` under. A side's\n * dollar limit, when it is the lower of the two, sets that side. */\nfunction priceBandAt(band: PriceBandShape, price: number): { above: number; below: number } {\n  const tier = tierAt(tierList(band), price)\n  const above = tier.aboveAmount !== undefined && price > tier.aboveAmount ? Math.min(tier.abovePct, (100 * tier.aboveAmount) / (price - tier.aboveAmount)) : tier.abovePct\n  const below = tier.belowAmount !== undefined ? Math.min(tier.belowPct, (100 * tier.belowAmount) / (price + tier.belowAmount)) : tier.belowPct\n  return { above, below }\n}\n\n/** The shelf prices worth drawing: whole decades around every tier start and every price a dollar limit starts to bite. */\nfunction priceDomain(band: PriceBandShape): [number, number] {\n  const points = [100]\n  for (const tier of tierList(band)) {\n    if (tier.fromPrice > 0) points.push(tier.fromPrice)\n    if (tier.aboveAmount !== undefined && tier.abovePct > 0) points.push(tier.aboveAmount * (1 + 100 / tier.abovePct))\n    if (tier.belowAmount !== undefined && tier.belowPct > 0 && tier.belowPct < 100) points.push(tier.belowAmount * (100 / tier.belowPct - 1))\n  }\n  const lo = Math.max(1, 10 ** Math.floor(Math.log10(Math.min(...points) / 4)))\n  const hi = Math.min(1_000_000, 10 ** Math.ceil(Math.log10(Math.max(...points) * 4)))\n  return [lo, hi]\n}\n\nconst SAMPLES = 96\n\n/** The plot's half-height in percent of gap: a round scale value at or above `gap`, never under 4%. */\nfunction niceSpan(gap: number): number {\n  return [4, 5, 10, 15, 20, 30, 40, 50, 60, 80, 100].find((step) => step >= gap) ?? 100\n}\n\ntype Geometry = {\n  lo: number\n  hi: number\n  /** Half the plot's height, in percent of gap. */\n  span: number\n  upper: string\n  lower: string\n  within: string\n  starts: number[]\n}\n\n/** The plot in a 100 × 100 box: x is the share of the log price range, y runs from +span (0) to −span (100). */\nfunction geometry(band: PriceBandShape): Geometry {\n  const [lo, hi] = priceDomain(band)\n  const starts = (band.tiers ?? []).map((tier) => tier.fromPrice).filter((price) => price > lo && price < hi)\n  const prices: number[] = []\n  for (let index = 0; index <= SAMPLES; index++) prices.push(lo * (hi / lo) ** (index / SAMPLES))\n  // A tier steps the band at its from-price: draw both sides of the step.\n  for (const start of starts) prices.push(start - 0.01, start)\n  prices.sort((a, b) => a - b)\n  const sides = prices.map((price) => ({ price, ...priceBandAt(band, price) }))\n  const maxAbove = Math.max(...sides.map((side) => side.above))\n  const maxBelow = Math.max(...sides.map((side) => side.below))\n  const span = niceSpan(Math.max(maxAbove, maxBelow) * 2)\n  const x = (price: number) => (100 * Math.log(price / lo)) / Math.log(hi / lo)\n  const y = (gap: number) => 50 - (50 * gap) / span\n  const top = sides.map((side) => `${x(side.price).toFixed(2)},${y(side.above).toFixed(2)}`)\n  const bottom = sides.map((side) => `${x(side.price).toFixed(2)},${y(-side.below).toFixed(2)}`)\n  return {\n    lo,\n    hi,\n    span,\n    upper: `M${top.join(\"L\")}`,\n    lower: `M${bottom.join(\"L\")}`,\n    within: `M${top.join(\"L\")}L${[...bottom].reverse().join(\"L\")}Z`,\n    starts,\n  }\n}\n\nconst logShare = (price: number, lo: number, hi: number) => (100 * Math.log(price / lo)) / Math.log(hi / lo)\n\n/** \"$10\", \"$1k\", \"$10k\", \"$1m\" for a decade tick. */\nconst decadeText = (price: number) => (price >= 1_000_000 ? `$${price / 1_000_000}m` : price >= 1000 ? `$${price / 1000}k` : `$${price}`)\n\n/** \"5%\", \"4.8%\", \"0.5%\". */\nconst pctText = (value: number) => `${Number(value.toFixed(1))}%`\n\nconst snapPrice = (price: number) => (price >= 10 ? Math.round(price) : Math.round(price * 100) / 100)\n\n/** \"$250\", \"$2,500\"; to the cent only below $10. */\nfunction priceText(price: number): string {\n  const total = cents(snapPrice(price))\n  const whole = String(Math.trunc(total / 100)).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\")\n  const part = total % 100\n  return part === 0 ? `$${whole}` : `$${whole}.${String(part).padStart(2, \"0\")}`\n}\n\nfunction Zones({ shape, hoverX }: { shape: Geometry; hoverX?: number | null }) {\n  return (\n    <svg viewBox=\"0 0 100 100\" preserveAspectRatio=\"none\" className=\"absolute inset-0 size-full overflow-visible\" aria-hidden=\"true\">\n      <rect x={0} y={0} width={100} height={50} className=\"fill-exposed\" />\n      <rect x={0} y={50} width={100} height={50} className=\"fill-favourable\" />\n      <path d={shape.within} className=\"fill-background\" />\n      <line x1={0} x2={100} y1={50} y2={50} strokeWidth={1} strokeDasharray=\"3 3\" vectorEffect=\"non-scaling-stroke\" className=\"stroke-border\" />\n      {shape.starts.map((start) => {\n        const x = logShare(start, shape.lo, shape.hi)\n        return <line key={start} x1={x} x2={x} y1={0} y2={100} strokeWidth={1} strokeDasharray=\"2 2\" vectorEffect=\"non-scaling-stroke\" className=\"stroke-border\" />\n      })}\n      <path d={shape.upper} fill=\"none\" strokeWidth={1.25} vectorEffect=\"non-scaling-stroke\" className=\"stroke-muted-foreground/80\" />\n      <path d={shape.lower} fill=\"none\" strokeWidth={1.25} vectorEffect=\"non-scaling-stroke\" className=\"stroke-muted-foreground/80\" />\n      {hoverX != null ? <line x1={hoverX} x2={hoverX} y1={0} y2={100} strokeWidth={1} vectorEffect=\"non-scaling-stroke\" className=\"stroke-foreground/90\" /> : null}\n    </svg>\n  )\n}\n\n/** The band, drawn: the zones across shelf prices, a readout of the price under the pointer, and, when given, how\n * many lines sit in each zone today. */\nexport function PriceBandChart({ band, counts, countsNote, labels, className }: {\n  band: PriceBandShape\n  /** Lines below, in line and above today, shown under the plot while nothing is hovered. */\n  counts?: PriceBandLineCounts | null\n  /** What the counts cover, before them, e.g. \"Your lines now:\". */\n  countsNote?: string\n  /** The chart's own words: zone names, the axis, the screen-reader description. */\n  labels?: Partial<PriceBandLabels>\n  className?: string\n}) {\n  const text = { ...DEFAULT_LABELS, ...labels }\n  const shape = geometry(band)\n  const [hover, setHover] = useState<number | null>(null)\n  const decades: number[] = []\n  for (let price = shape.lo; price <= shape.hi * 1.0001; price *= 10) decades.push(Math.round(price))\n  // A tier start close to a decade (within a sixth of one) takes that decade's place on the axis.\n  const shownDecades = decades.filter((decade) => shape.starts.every((start) => Math.abs(Math.log10(start / decade)) > 1 / 6))\n  // Snapped to the dollar (the cent under $10) so the readout's price and its market range agree.\n  const hoverPrice = hover === null ? null : snapPrice(shape.lo * (shape.hi / shape.lo) ** (hover / 100))\n  const readout = hoverPrice === null ? null : priceBandAt(band, hoverPrice)\n\n  function move(event: PointerEvent<HTMLDivElement>) {\n    const box = event.currentTarget.getBoundingClientRect()\n    setHover(Math.min(100, Math.max(0, (100 * (event.clientX - box.left)) / box.width)))\n  }\n\n  const gutter = \"w-10 shrink-0\"\n  return (\n    <figure className={cn(\"w-full max-w-xl text-[11px] text-muted-foreground\", className)} data-price-band>\n      <div className=\"flex gap-2\">\n        {/* The gap scale, not the band: the band's own words are the caller's, beside the picture. */}\n        <div className={cn(gutter, \"relative h-24 text-right tabular-nums\")} aria-hidden=\"true\">\n          <span className=\"absolute right-0 top-0\">+{shape.span}%</span>\n          <span className=\"absolute right-0 top-1/2 -translate-y-1/2\">{text.market}</span>\n          <span className=\"absolute bottom-0 right-0\">−{shape.span}%</span>\n        </div>\n        <div\n          role=\"img\"\n          aria-label={text.description}\n          className=\"relative h-24 min-w-0 flex-1 touch-none overflow-hidden rounded-sm border\"\n          onPointerMove={move}\n          onPointerDown={move}\n          onPointerLeave={() => setHover(null)}\n        >\n          <Zones shape={shape} hoverX={hover} />\n          <span aria-hidden=\"true\" className=\"absolute right-1.5 top-1 font-medium text-exposed-foreground\">{text.above}</span>\n          <span aria-hidden=\"true\" className=\"absolute bottom-1 right-1.5 font-medium text-favourable-foreground\">{text.below}</span>\n          <span aria-hidden=\"true\" className=\"absolute left-1.5 top-1/2 -translate-y-1/2 text-foreground\">{text.inLine}</span>\n        </div>\n      </div>\n      <div className=\"mt-1 flex gap-2\" aria-hidden=\"true\">\n        <span className={cn(gutter, \"text-right\")}>{text.axis}</span>\n        <div className=\"relative h-4 min-w-0 flex-1 tabular-nums\">\n          {shownDecades.map((decade) => <AxisTick key={`d${decade}`} at={logShare(decade, shape.lo, shape.hi)}>{decadeText(decade)}</AxisTick>)}\n          {shape.starts.map((start) => <AxisTick key={`t${start}`} at={logShare(start, shape.lo, shape.hi)} strong>{priceText(start)}</AxisTick>)}\n        </div>\n      </div>\n      <figcaption className=\"ml-12 mt-1 min-h-4 tabular-nums\" aria-live=\"polite\">\n        {hoverPrice !== null && readout ? (\n          <span className=\"text-foreground\">\n            At {priceText(hoverPrice)}: in line from {pctText(readout.below)} under to {pctText(readout.above)} over market\n            <span className=\"text-muted-foreground\"> · market {priceText(hoverPrice / (1 + readout.above / 100))}–{readout.below >= 100 ? \"any\" : priceText(hoverPrice / (1 - readout.below / 100))}</span>\n          </span>\n        ) : counts ? <PriceBandCounts counts={counts} note={countsNote} /> : null}\n      </figcaption>\n    </figure>\n  )\n}\n\nfunction AxisTick({ at, strong, children }: { at: number; strong?: boolean; children: string }) {\n  // The two ends hug the plot's edges rather than hang past them.\n  const shift = at <= 2 ? \"translate-x-0\" : at >= 98 ? \"-translate-x-full\" : \"-translate-x-1/2\"\n  return <span className={cn(\"absolute top-0 whitespace-nowrap\", shift, strong && \"font-medium text-foreground\")} style={{ left: `${at}%` }}>{children}</span>\n}\n\nfunction Swatch({ className }: { className: string }) {\n  return <span aria-hidden=\"true\" className={cn(\"inline-block size-2 rounded-[2px] border\", className)} />\n}\n\n/** \"Your lines now: ■ 30 below · □ 140 in line · ■ 12 above\", each swatch its zone's tint. */\nexport function PriceBandCounts({ counts, note, className }: { counts: PriceBandLineCounts; note?: string; className?: string }) {\n  return (\n    <span className={cn(\"inline-flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-[11px] tabular-nums text-muted-foreground\", className)}>\n      {note !== undefined ? <span>{note}</span> : null}\n      <span className=\"inline-flex items-center gap-1\"><Swatch className=\"bg-favourable\" /><span className=\"text-foreground\">{formatUnits(counts.below)}</span> below</span>\n      <span aria-hidden=\"true\">·</span>\n      <span className=\"inline-flex items-center gap-1\"><Swatch className=\"bg-background\" /><span className=\"text-foreground\">{formatUnits(counts.inLine)}</span> in line</span>\n      <span aria-hidden=\"true\">·</span>\n      <span className=\"inline-flex items-center gap-1\"><Swatch className=\"bg-exposed\" /><span className=\"text-foreground\">{formatUnits(counts.above)}</span> above</span>\n    </span>\n  )\n}\n\n/** The same picture at a table row's size: no axis, no labels. The row's words beside it say the band, so a screen\n * reader skips it. */\nexport function PriceBandMini({ band, className }: { band: PriceBandShape; className?: string }) {\n  const shape = geometry(band)\n  return (\n    <span aria-hidden=\"true\" className={cn(\"relative inline-block h-7 w-20 shrink-0 overflow-hidden rounded-[3px] border align-middle\", className)} data-price-band-mini>\n      <Zones shape={shape} />\n    </span>\n  )\n}\n","type":"registry:ui"}],"type":"registry:ui"}