Debian Codegraph @

frontend/src/charts/ScatterPlot.svelte

raw
1 <script lang="ts">
2 import { extent } from "d3-array";
3 import { axisBottom, axisLeft } from "d3-axis";
4 import { quadtree } from "d3-quadtree";
5 import { scalePoint, scaleUtc } from "d3-scale";
6
7 import { day } from "../format";
8 import Axis from "./Axis.svelte";
9 import { scatterplotScale } from "./helpers";
10 import type { ScatterPlot, ScatterPlotDatum } from "./scatterplot";
11 import type { TooltipFindNode } from "./tooltip";
12 import { domHelpers, positionedTooltip } from "./tooltip";
13
14 interface Props {
15 chart: ScatterPlot;
16 width: number;
17 }
18
19 let { chart, width }: Props = $props();
20
21 const today = new Date();
22 const margin = { top: 10, right: 10, bottom: 30, left: 70 };
23 const height = 250;
24 let innerWidth = $derived(width - margin.left - margin.right);
25 let innerHeight = $derived(height - margin.top - margin.bottom);
26
27 // Scales
28 let dateExtent = $derived(extent(chart.data, (d) => d.date));
29 let x = $derived(
30 scaleUtc([0, innerWidth]).domain(dateExtent[0] ? dateExtent : [0, 1]),
31 );
32 let y = $derived(
33 scalePoint([innerHeight, 0])
34 .domain(chart.data.map((d) => d.type))
35 .padding(1),
36 );
37
38 // Axes
39 let xAxis = $derived(axisBottom(x).tickSizeOuter(0));
40 let yAxis = $derived(
41 axisLeft(y)
42 .tickPadding(6)
43 .tickSize(-innerWidth)
44 .tickFormat((d) => d),
45 );
46
47 /** Quadtree for hover. */
48 let quad = $derived(
49 quadtree(
50 [...chart.data],
51 (d) => x(d.date),
52 (d) => y(d.type) ?? 0,
53 ),
54 );
55
56 function tooltipText(d: ScatterPlotDatum) {
57 return [domHelpers.t(d.description), domHelpers.em(day(d.date))];
58 }
59
60 const tooltipFindNode: TooltipFindNode = (xPos, yPos) => {
61 const d = quad.find(xPos, yPos);
62 return d && [x(d.date), y(d.type) ?? 0, tooltipText(d)];
63 };
64 </script>
65
66 <svg viewBox={`0 0 ${width.toString()} ${height.toString()}`}>
67 <g
68 use:positionedTooltip={tooltipFindNode}
69 transform={`translate(${margin.left.toString()},${margin.top.toString()})`}
70 >
71 <Axis x axis={xAxis} {innerHeight} />
72 <Axis y axis={yAxis} />
73 <g>
74 {#each chart.data as dot}
75 <circle
76 r="5"
77 fill={scatterplotScale(dot.type)}
78 cx={x(dot.date)}
79 cy={y(dot.type)}
80 class:desaturate={dot.date > today}
81 />
82 {/each}
83 </g>
84 </g>
85 </svg>
86
87 <style>
88 svg > g {
89 pointer-events: all;
90 }
91
92 .desaturate {
93 filter: saturate(50%);
94 }
95 </style>