SPB Git

spb/rareindex

Public
7.8 KB · 156 lines tsx
1/**2 * Small server-renderable SVG charts for account pages: one system (hairlines, tabular numbers,3 * neutral ink, accents only for gain/loss/index). No client JS required.4 */5import { cn } from '@/lib/format';67const PALETTE = ['var(--ri-index)', 'var(--ri-gold)', 'var(--ri-rarity)', 'var(--ri-gain)', 'var(--ri-alert)', 'var(--ri-fg-muted)', 'var(--ri-loss)', 'var(--ri-fg-subtle)'];89export function Donut({ data, size = 120, thickness = 14, className, centerLabel, centerValue }: { data: Array<{ label: string; value: number }>; size?: number; thickness?: number; className?: string; centerLabel?: string; centerValue?: string }) {10  const total = data.reduce((a, d) => a + d.value, 0);11  const r = (size - thickness) / 2;12  const c = 2 * Math.PI * r;13  let offset = 0;14  return (15    <div className={cn('flex items-center gap-4', className)}>16      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} role="img" aria-label="Allocation">17        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--ri-bg-inset)" strokeWidth={thickness} />18        {total > 019          ? data.map((d, i) => {20              const len = (d.value / total) * c;21              const el = <circle key={d.label} cx={size / 2} cy={size / 2} r={r} fill="none" stroke={PALETTE[i % PALETTE.length]} strokeWidth={thickness} strokeDasharray={`${len} ${c - len}`} strokeDashoffset={-offset} transform={`rotate(-90 ${size / 2} ${size / 2})`} />;22              offset += len;23              return el;24            })25          : null}26        {centerValue ? (27          <>28            <text x="50%" y="48%" textAnchor="middle" fontSize={size / 9} fontWeight={600} fill="var(--ri-fg)" style={{ fontVariantNumeric: 'tabular-nums' }}>29              {centerValue}30            </text>31            {centerLabel ? (32              <text x="50%" y="62%" textAnchor="middle" fontSize={size / 13} fill="var(--ri-fg-subtle)">33                {centerLabel}34              </text>35            ) : null}36          </>37        ) : null}38      </svg>39      <ul className="min-w-0 flex-1 space-y-1 text-xs">40        {data.slice(0, 8).map((d, i) => (41          <li key={d.label} className="flex items-center gap-2">42            <span className="h-2 w-2 shrink-0 rounded-sm" style={{ background: PALETTE[i % PALETTE.length] }} />43            <span className="min-w-0 flex-1 truncate text-muted">{d.label}</span>44            <span className="num text-fg">{total > 0 ? `${((d.value / total) * 100).toFixed(0)}%` : '—'}</span>45          </li>46        ))}47        {data.length === 0 ? <li className="text-subtle">No valued items yet.</li> : null}48      </ul>49    </div>50  );51}5253export interface SeriesPoint {54  date: string;55  value: number;56}5758export function LineChart({ series, height = 180, className, formatY = (v: number) => v.toFixed(0), showArea = true, ariaLabel = 'Value over time' }: { series: Array<{ name: string; points: SeriesPoint[]; color?: string; dashed?: boolean }>; height?: number; className?: string; formatY?: (v: number) => string; showArea?: boolean; ariaLabel?: string }) {59  const all = series.flatMap((s) => s.points);60  if (all.length < 2) {61    return (62      <div className={cn('flex items-center justify-center rounded-md border border-dashed border-border text-xs text-subtle', className)} style={{ height }}>63        Not enough history yet — values are snapshotted daily.64      </div>65    );66  }67  const W = 640;68  const H = height;69  const padL = 44;70  const padR = 8;71  const padT = 8;72  const padB = 20;73  const dates = [...new Set(all.map((p) => p.date))].sort();74  const t0 = new Date(dates[0]!).getTime();75  const t1 = new Date(dates[dates.length - 1]!).getTime();76  const min = Math.min(...all.map((p) => p.value));77  const max = Math.max(...all.map((p) => p.value));78  const span = max - min || max || 1;79  const yMin = min - span * 0.08;80  const yMax = max + span * 0.08;81  const x = (d: string) => padL + ((new Date(d).getTime() - t0) / Math.max(1, t1 - t0)) * (W - padL - padR);82  const y = (v: number) => padT + (1 - (v - yMin) / (yMax - yMin)) * (H - padT - padB);83  const ticks = [yMin + (yMax - yMin) * 0.1, (yMin + yMax) / 2, yMax - (yMax - yMin) * 0.1];84  return (85    <svg viewBox={`0 0 ${W} ${H}`} className={cn('h-auto w-full', className)} role="img" aria-label={ariaLabel} preserveAspectRatio="none">86      {ticks.map((t) => (87        <g key={t}>88          <line x1={padL} x2={W - padR} y1={y(t)} y2={y(t)} stroke="var(--ri-border)" strokeDasharray="2 3" />89          <text x={padL - 6} y={y(t) + 3} textAnchor="end" fontSize={10} fill="var(--ri-fg-subtle)" style={{ fontVariantNumeric: 'tabular-nums' }}>90            {formatY(t)}91          </text>92        </g>93      ))}94      {series.map((s, i) => {95        const pts = [...s.points].sort((a, b) => a.date.localeCompare(b.date));96        const d = pts.map((p, j) => `${j === 0 ? 'M' : 'L'}${x(p.date).toFixed(1)},${y(p.value).toFixed(1)}`).join(' ');97        const color = s.color ?? PALETTE[i % PALETTE.length];98        const last = pts[pts.length - 1]!;99        return (100          <g key={s.name}>101            {showArea && i === 0 ? <path d={`${d} L${x(last.date).toFixed(1)},${H - padB} L${x(pts[0]!.date).toFixed(1)},${H - padB} Z`} fill={color} opacity={0.06} /> : null}102            <path d={d} fill="none" stroke={color} strokeWidth={1.6} strokeDasharray={s.dashed ? '4 3' : undefined} vectorEffect="non-scaling-stroke" />103            <circle cx={x(last.date)} cy={y(last.value)} r={2.5} fill={color} />104          </g>105        );106      })}107      <text x={padL} y={H - 6} fontSize={10} fill="var(--ri-fg-subtle)">108        {dates[0]}109      </text>110      <text x={W - padR} y={H - 6} fontSize={10} textAnchor="end" fill="var(--ri-fg-subtle)">111        {dates[dates.length - 1]}112      </text>113    </svg>114  );115}116117export function Sparkline({ points, width = 96, height = 24, positive }: { points: number[]; width?: number; height?: number; positive?: boolean | null }) {118  if (points.length < 2) return <span className="text-subtle">—</span>;119  const min = Math.min(...points);120  const max = Math.max(...points);121  const span = max - min || 1;122  const d = points.map((v, i) => `${i === 0 ? 'M' : 'L'}${((i / (points.length - 1)) * width).toFixed(1)},${(height - 2 - ((v - min) / span) * (height - 4)).toFixed(1)}`).join(' ');123  const stroke = positive === null || positive === undefined ? 'var(--ri-fg-muted)' : positive ? 'var(--ri-gain)' : 'var(--ri-loss)';124  return (125    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden>126      <path d={d} fill="none" stroke={stroke} strokeWidth={1.4} />127    </svg>128  );129}130131export function Bars({ data, className, format = (v: number) => v.toFixed(0) }: { data: Array<{ label: string; value: number; tone?: 'gain' | 'loss' | 'neutral' }>; className?: string; format?: (v: number) => string }) {132  const max = Math.max(1, ...data.map((d) => Math.abs(d.value)));133  return (134    <ul className={cn('space-y-1.5 text-xs', className)}>135      {data.map((d) => (136        <li key={d.label} className="grid grid-cols-[minmax(0,1fr)_120px_64px] items-center gap-2">137          <span className="truncate text-muted">{d.label}</span>138          <span className="h-2 rounded-sm bg-inset">139            <span className={cn('block h-2 rounded-sm', d.tone === 'loss' ? 'bg-loss' : d.tone === 'gain' ? 'bg-gain' : 'bg-index')} style={{ width: `${(Math.abs(d.value) / max) * 100}%` }} />140          </span>141          <span className={cn('num text-right', d.tone === 'loss' ? 'text-loss' : d.tone === 'gain' ? 'text-gain' : 'text-fg')}>{format(d.value)}</span>142        </li>143      ))}144    </ul>145  );146}147148export function Progress({ value, className }: { value: number; className?: string }) {149  const v = Math.max(0, Math.min(1, value));150  return (151    <span className={cn('block h-1.5 w-full rounded-full bg-inset', className)}>152      <span className={cn('block h-1.5 rounded-full', v >= 1 ? 'bg-gain' : 'bg-index')} style={{ width: `${v * 100}%` }} />153    </span>154  );155}156
Files · d93392862678cbf30e175697fcb812bc4ff0b5a7
Menu

Theme