File size: 4,822 Bytes
2471af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { useMemo, useState } from "react"
import { Bar, BarChart, CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart"
import { REL_NAME, type Lineage, type Rel } from "@/lib/types"
import { relConfig, RelLegend, axisTick } from "@/components/rel"
import { md } from "@/lib/format"

const day = (d: Date) => d.toISOString().slice(0, 10)
const addDays = (s: string, n: number) => {
  const d = new Date(s + "T00:00:00Z")
  d.setUTCDate(d.getUTCDate() + n)
  return day(d)
}

/** Running total of each kind of derivative, from the creation dates (full history). */
export function GrowthLines({ L, rel, today }: { L: Lineage; rel: Rel[]; today: string }) {
  const { rows, present } = useMemo(() => {
    const present = rel.filter((r) => L.by_relation[r].n > 0)
    if (!L.growth.length) return { rows: [], present }
    const byDate = new Map<string, Partial<Record<Rel, number>>>()
    for (const g of L.growth) {
      const m = byDate.get(g.date) ?? {}
      m[g.rel] = (m[g.rel] ?? 0) + g.n
      byDate.set(g.date, m)
    }
    const start = [...byDate.keys()].sort()[0]
    const run: Record<string, number> = Object.fromEntries(present.map((r) => [r, 0]))
    const rows: Record<string, string | number>[] = []
    for (let d = start; d <= today; d = addDays(d, 1)) {
      for (const [r, n] of Object.entries(byDate.get(d) ?? {})) run[r] = (run[r] ?? 0) + n
      rows.push({ date: d, ...run })
    }
    // Long histories are drawn from one point a week, which keeps the curves smooth.
    const step = rows.length > 90 ? 7 : 1
    const thin = rows.filter((_, i) => i % step === 0 || i === rows.length - 1)
    return { rows: thin, present }
  }, [L, rel, today])
  const [hidden, setHidden] = useState<Set<Rel>>(new Set())
  const toggle = (r: Rel) => setHidden((h) => { const n = new Set(h); if (n.has(r)) n.delete(r); else n.add(r); return n })

  return (
    <>
      <RelLegend rels={present} hidden={hidden} onToggle={toggle} />
      <ChartContainer config={relConfig(present)} className="aspect-auto h-[320px] w-full">
        <LineChart data={rows} margin={{ left: 4, right: 12, top: 8 }}>
          <CartesianGrid vertical={false} />
          <XAxis dataKey="date" tickLine={false} axisLine={false} tick={axisTick} tickFormatter={md} minTickGap={48} />
          <YAxis tickLine={false} axisLine={false} tick={axisTick} width={44} />
          <ChartTooltip content={<ChartTooltipContent labelFormatter={(v) => md(String(v))} />} />
          {present.filter((r) => !hidden.has(r)).map((r) => (
            <Line key={r} dataKey={r} name={REL_NAME[r]} type="monotone" stroke={`var(--color-${r})`}
                  strokeWidth={2} dot={false} animationDuration={900} animationEasing="ease-out" />
          ))}
        </LineChart>
      </ChartContainer>
    </>
  )
}

/** New derivatives per finished week (Monday start); the current week would read as a drop. */
export function WeeklyBars({ L, today, color = "var(--brand)" }: { L: Lineage; today: string; color?: string }) {
  const rows = useMemo(() => {
    const monday = (s: string) => {
      const d = new Date(s + "T00:00:00Z")
      d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 6) % 7))
      return day(d)
    }
    const weeks = new Map<string, number>()
    for (const g of L.growth) weeks.set(monday(g.date), (weeks.get(monday(g.date)) ?? 0) + g.n)
    const keys = [...weeks.keys()].sort()
    const end = monday(today)
    const out: { week: string; n: number }[] = []
    for (let w = keys[0]; w && w < end; w = addDays(w, 7)) out.push({ week: w, n: weeks.get(w) ?? 0 })
    return out
  }, [L, today])
  const config = { n: { label: "New", color } } satisfies ChartConfig
  const weekMax = Math.max(1, ...rows.map((r) => r.n))
  const step = weekMax > 200 ? 100 : weekMax > 60 ? 50 : weekMax > 20 ? 10 : 5

  return (
    <ChartContainer config={config} className="aspect-auto h-[356px] w-full">
      <BarChart data={rows} margin={{ left: 4, right: 4, top: 8 }}>
        <CartesianGrid vertical={false} />
        <XAxis dataKey="week" tickLine={false} axisLine={false} tick={axisTick} tickFormatter={md} minTickGap={40} />
        <YAxis tickLine={false} axisLine={false} tick={axisTick} width={36} allowDecimals={false}
               domain={[0, (max: number) => Math.ceil(max / step) * step]} tickCount={Math.max(2, Math.ceil(weekMax / step) + 1)} />
        <ChartTooltip cursor={{ fill: "var(--muted)" }}
                      content={<ChartTooltipContent labelFormatter={(v) => `Week of ${md(String(v))}`} />} />
        <Bar dataKey="n" fill="var(--color-n)" radius={[4, 4, 0, 0]} maxBarSize={22} animationDuration={900} animationEasing="ease-out" />
      </BarChart>
    </ChartContainer>
  )
}