5 Commits
Author SHA1 Message Date
mokhtar a261dc2aa3 build: bump version to 0.0.11
Gates / test (push) Successful in 2m12s
Gates / test-aarch64 (push) Successful in 7m1s
Gates / package (push) Successful in 42s
Release / gates (push) Successful in 10m8s
Gates / container (push) Successful in 10s
Release / publish (push) Successful in 10m22s
Gates / test-aarch64 (push) Successful in 9m19s
Gates / package (push) Successful in 10m49s
Gates / container (push) Successful in 15s
CI / gates (push) Successful in 25m8s
Gates / frontend (push) Successful in 1m42s
Gates / frontend (push) Successful in 3m55s
Gates / test (push) Successful in 4m41s
Release / guard (push) Successful in 1m48s
2026-08-24 18:41:46 +02:00
mokhtar 90b85ef954 changelog: 0.0.11
Gates / test (push) Successful in 2m6s
Gates / test-aarch64 (push) Successful in 7m31s
Gates / frontend (push) Successful in 1m36s
Gates / package (push) Failing after 16m49s
Gates / container (push) Skipped
CI / gates (push) Failing after 35m55s
2026-08-24 18:40:29 +02:00
mokhtar ad26aca198 admin: draw the overview charts with visx
the hand-written scale, tick, stacking and arc math is replaced by visx 4.0.0
primitives; rendering, colours and themes stay the app's own. all four charts
share one hover treatment: the client chart gains the tooltip and dimming the
query timeline had, the donuts gain both, an open tooltip follows a data
refresh instead of going stale, and it retires when the window rolls. the
timeline's third series is named allowed instead of other, and the client
chart's other aggregate disappears from a window where it counted nothing.
licenses gain the isc text for the bundled d3 modules.
2026-08-24 18:40:17 +02:00
mokhtar 08d756cc87 build: bump version to 0.0.10
Gates / frontend (push) Successful in 2m1s
Gates / test (push) Successful in 3m6s
Gates / test-aarch64 (push) Successful in 9m28s
Gates / package (push) Successful in 9m12s
Gates / container (push) Successful in 14s
CI / gates (push) Successful in 22m4s
Release / guard (push) Successful in 1m32s
Gates / frontend (push) Successful in 1m28s
Gates / test (push) Successful in 1m53s
Gates / package (push) Successful in 23s
Gates / container (push) Successful in 17s
Release / gates (push) Successful in 9m33s
Gates / test-aarch64 (push) Successful in 6m58s
Release / publish (push) Successful in 10m46s
2026-08-24 00:05:33 +02:00
mokhtar 44ecc2c4ae changelog: 0.0.10
Gates / frontend (push) Successful in 1m31s
Gates / test (push) Successful in 1m53s
Gates / test-aarch64 (push) Successful in 7m2s
Gates / package (push) Successful in 5m44s
Gates / container (push) Successful in 9s
CI / gates (push) Successful in 48m46s
2026-08-24 00:05:21 +02:00
30 changed files with 2946 additions and 888 deletions
+13 -1
View File
@@ -4,7 +4,19 @@ All notable changes to nxdns are recorded here. The format follows [Keep a Chang
Sections are written by hand. Nothing here is generated from commit messages: the point of the file is to say what changed for an operator, which a commit subject rarely does.
## [Unreleased]
## [0.0.11] - 2026-08-24
The Overview charts move to visx and grow up: one hover treatment across all four, honest labels, and maintained d3 math under the app's own rendering.
### Changed
- **The Overview charts are drawn with visx.** The hand-written chart layout code is replaced by visx 4.0.0 primitives — maintained d3 math for the scales, ticks, stacking and arcs — while the rendering, colours and themes stay the app's own. The charts read as before, with four behaviour improvements: all four charts now share the same hover treatment (the per-client chart and both donuts gain the tooltip and dimming the query timeline already had, so pointing at a ring segment names it, its count and its share), an open tooltip follows a data refresh instead of showing stale counts, and it retires cleanly when the time window rolls. The admin bundle grows by about 68 KB and stays under its size budget.
- **The query timeline's third series is called "Allowed".** What the chart called "Other" is every query that was neither blocked nor served from cache — answered upstream, from a local record or a forward zone — so it is now named for what it is rather than for the subtraction that produces it. It stays on the chart even in a window where nothing was allowed, alongside Blocked and Cached: all three name a kind of answer a query can get, and a period where every query was blocked or cached is worth seeing.
- **The client chart drops "Other" in a window where it counted nothing.** That series aggregates the clients outside the top eight, so when it counts nothing there is nothing being aggregated, and a legend entry, a tooltip row and a table column that exist only to say "zero" are noise. The named clients stay even at zero, because a client that went quiet is a fact about the window.
## [0.0.10] - 2026-08-24
Configuration goes live: when the database owns the configuration, saving a setting reconfigures the running process instead of asking for a restart. The restart-required set shrinks to the listen sockets and the admin interface switch.
### Changed
+508 -3
View File
@@ -11,6 +11,12 @@
"@stylexjs/stylex": "0.19.0",
"@tanstack/react-query": "5.101.4",
"@tanstack/react-router": "1.170.18",
"@visx/axis": "4.0.0",
"@visx/grid": "4.0.0",
"@visx/group": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"@visx/tooltip": "4.0.0",
"react": "19.2.8",
"react-aria-components": "1.20.0",
"react-dom": "19.2.8"
@@ -1619,6 +1625,84 @@
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/d3-array": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz",
"integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==",
"license": "MIT"
},
"node_modules/@types/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==",
"license": "MIT"
},
"node_modules/@types/d3-delaunay": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz",
"integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==",
"license": "MIT"
},
"node_modules/@types/d3-format": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz",
"integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==",
"license": "MIT"
},
"node_modules/@types/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
"license": "MIT",
"dependencies": {
"@types/geojson": "*"
}
},
"node_modules/@types/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-jx5leotSeac3jr0RePOH1KdR9rISG91QIE4Q2PYTu4OymLTZfA3SrnURSLzKH48HmXVUru50b8nje4E79oQSQw==",
"license": "MIT",
"dependencies": {
"@types/d3-color": "*"
}
},
"node_modules/@types/d3-path": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz",
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
"license": "MIT"
},
"node_modules/@types/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
},
"node_modules/@types/d3-shape": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz",
"integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz",
"integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==",
"license": "MIT"
},
"node_modules/@types/d3-time-format": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz",
"integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==",
"license": "MIT"
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
@@ -1633,6 +1717,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/geojson": {
"version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.1.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",
@@ -1647,7 +1737,7 @@
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"dev": true,
"devOptional": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -1657,7 +1747,7 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"dev": true,
"devOptional": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
@@ -2003,6 +2093,211 @@
"node": ">=16.20.0"
}
},
"node_modules/@visx/axis": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/axis/-/axis-4.0.0.tgz",
"integrity": "sha512-cSPNO9Aic2UX49AmIeJJ9TQrrAkvUHpHOGqimUAXhbg07VI3HoHDKcXZdrjvQz+g0LhubrUkjj8Gwju2WZ3dtg==",
"license": "MIT",
"dependencies": {
"@visx/group": "4.0.0",
"@visx/point": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"@visx/text": "4.0.0",
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/bounds": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/bounds/-/bounds-4.0.0.tgz",
"integrity": "sha512-3wAfN5fg2bxg/5f3MlKWzGDTKU2hdKkxq8bVWXpPZQV0UiVc0myuU1qa34c7tN3hg5SDe6MJi/bae2eTQDgEiQ==",
"license": "MIT",
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"@types/react-dom": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@visx/curve": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/curve/-/curve-4.0.0.tgz",
"integrity": "sha512-bXrOSd2BzVCxR7kBE7gPTSU4plxzYN75w7erdHYabwn3vzP+xFk1o0gg3NOHEPJzt5tXqf0Ecm5YqHACOnipTA==",
"license": "MIT",
"dependencies": {
"@visx/vendor": "4.0.0"
}
},
"node_modules/@visx/grid": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/grid/-/grid-4.0.0.tgz",
"integrity": "sha512-BUnznqYo8jyn3zXRWZiF0zwg1VQl6w5kYqZ+XMY+cPXtAHZZbwGXBChMpPefH5Lj1+P1b4Pf3QihKG8zjL9PCw==",
"license": "MIT",
"dependencies": {
"@visx/curve": "4.0.0",
"@visx/group": "4.0.0",
"@visx/point": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/group": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/group/-/group-4.0.0.tgz",
"integrity": "sha512-HGAq8BCqn5x0t94CJOLJeKtWss9LFpF3HY69HbuO1PlR+B9c4aVT9xbjfudmU8wGQZLT6JNt+PJvxbO2aJ+1aA==",
"license": "MIT",
"dependencies": {
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/point": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/point/-/point-4.0.0.tgz",
"integrity": "sha512-hwJ9UlIjg3iV4iiJ3RN5SNTXama+zGaNe57sXSrSvPiqhkDXypsYBdDSlAnHmKbMzHP0zFmgB1UJciB/QUyigw==",
"license": "MIT"
},
"node_modules/@visx/scale": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/scale/-/scale-4.0.0.tgz",
"integrity": "sha512-Q3VaSLKlsrxxSl9CwS2D3Mvz4/4kIp/6NMKRY8Im0Au1hrQh2egU806p0+JwN0ccuGGDe03jyAxX4BSRAH8Plg==",
"license": "MIT",
"dependencies": {
"@visx/vendor": "4.0.0"
}
},
"node_modules/@visx/shape": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/shape/-/shape-4.0.0.tgz",
"integrity": "sha512-X0FP3OFjQhc5/6Vj2aY7cK2JwKYI0H0hQM7cdNRWy/ZMMlrh5KpEdqx0HVo0KoTeTlkUvO+kydMLnAuuCRFIFw==",
"license": "MIT",
"dependencies": {
"@visx/curve": "4.0.0",
"@visx/group": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/vendor": "4.0.0",
"classnames": "^2.3.1"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/text": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/text/-/text-4.0.0.tgz",
"integrity": "sha512-39f2goSaKy5Mqn89lRDGSJ1IMr49wplkbIFHsFI8cPnAPbguiJxYZ+ulizd7Vcsq2z/hytuGv3Lmk165zUiUYQ==",
"license": "MIT",
"dependencies": {
"classnames": "^2.3.1",
"reduce-css-calc": "^1.3.0"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
}
}
},
"node_modules/@visx/tooltip": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/tooltip/-/tooltip-4.0.0.tgz",
"integrity": "sha512-+6J2h5qPvniT0pQtxQrLYGErPRVHr3pRfcMkNqTxD/HgofDGsL6vEBkjMR535MF1hkWYQ9XzOiWP6ERN4TF+mg==",
"license": "MIT",
"dependencies": {
"@visx/bounds": "4.0.0",
"classnames": "^2.3.1",
"react-use-measure": "^2.0.4"
},
"peerDependencies": {
"@types/react": "^18.0.0 || ^19.0.0",
"@types/react-dom": "^18.0.0 || ^19.0.0",
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@visx/vendor": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@visx/vendor/-/vendor-4.0.0.tgz",
"integrity": "sha512-LoBNzWjTXzBfu095BQxB14IwZQHHOLs8ZMzM6t2FL4ZGORaACgLcmXRRLhFo0VmRR8L7iNTM4HHc1j6yFvzsAA==",
"license": "MIT and ISC",
"dependencies": {
"@types/d3-array": "3.0.3",
"@types/d3-color": "3.1.0",
"@types/d3-delaunay": "6.0.1",
"@types/d3-format": "3.0.1",
"@types/d3-geo": "3.1.0",
"@types/d3-interpolate": "3.0.1",
"@types/d3-path": "3.1.1",
"@types/d3-scale": "4.0.2",
"@types/d3-shape": "3.1.7",
"@types/d3-time": "3.0.0",
"@types/d3-time-format": "2.1.0",
"d3-array": "3.2.1",
"d3-color": "3.1.0",
"d3-delaunay": "6.0.2",
"d3-format": "3.1.0",
"d3-geo": "3.1.0",
"d3-interpolate": "3.0.1",
"d3-path": "3.1.0",
"d3-scale": "4.0.2",
"d3-shape": "3.2.0",
"d3-time": "3.1.0",
"d3-time-format": "4.1.0",
"internmap": "2.0.3"
}
},
"node_modules/@vitejs/plugin-react": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.4.tgz",
@@ -2211,6 +2506,12 @@
"node": ">=12"
}
},
"node_modules/balanced-match": {
"version": "0.4.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-0.4.2.tgz",
"integrity": "sha512-STw03mQKnGUYtoNjmowo4F2cRmIIxYEGiMsjjwla/u5P1lxadj/05WkNaFjNiKTgJkj8KiXbgAiRTmcQRwQNtg==",
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
"version": "2.11.12",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.12.tgz",
@@ -2299,6 +2600,12 @@
"node": ">=18"
}
},
"node_modules/classnames": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz",
"integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==",
"license": "MIT"
},
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
@@ -2351,9 +2658,136 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.1.tgz",
"integrity": "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-color": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-delaunay": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz",
"integrity": "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==",
"license": "ISC",
"dependencies": {
"delaunator": "5"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-format": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
"integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-geo": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.0.tgz",
"integrity": "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==",
"license": "ISC",
"dependencies": {
"d3-array": "2.5.0 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-interpolate": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-path": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
"d3-interpolate": "1.2.0 - 3",
"d3-time": "2.1.1 - 3",
"d3-time-format": "2 - 4"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-shape": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/d3-time-format": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
"engines": {
"node": ">=12"
}
},
"node_modules/data-urls": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
@@ -2393,6 +2827,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/delaunator": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",
"integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",
"license": "ISC",
"dependencies": {
"robust-predicates": "^3.0.2"
}
},
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
@@ -2533,6 +2976,15 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/internmap": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/invariant": {
"version": "2.2.4",
"resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz",
@@ -2946,6 +3398,12 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/math-expression-evaluator": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/math-expression-evaluator/-/math-expression-evaluator-1.4.0.tgz",
"integrity": "sha512-4vRUvPyxdO8cWULGTh9dZWL2tZK6LDBvj+OGHBER7poH9Qdt7kXEoj20wiz4lQUbUXQZFjPbe5mVDo9nutizCw==",
"license": "MIT"
},
"node_modules/mdn-data": {
"version": "2.27.1",
"resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
@@ -3254,6 +3712,47 @@
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
}
},
"node_modules/react-use-measure": {
"version": "2.1.7",
"resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz",
"integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.13",
"react-dom": ">=16.13"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/reduce-css-calc": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/reduce-css-calc/-/reduce-css-calc-1.3.0.tgz",
"integrity": "sha512-0dVfwYVOlf/LBA2ec4OwQ6p3X9mYxn/wOl2xTcLwjnPYrkgEfPx3VI4eGCH3rQLlPISG5v9I9bkZosKsNRTRKA==",
"license": "MIT",
"dependencies": {
"balanced-match": "^0.4.2",
"math-expression-evaluator": "^1.2.14",
"reduce-function-call": "^1.0.1"
}
},
"node_modules/reduce-function-call": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/reduce-function-call/-/reduce-function-call-1.0.3.tgz",
"integrity": "sha512-Hl/tuV2VDgWgCSEeWMLwxLZqX7OK59eU1guxXsRKTAyeYimivsKdtcV4fu3r710tpG5GmDKDhQ0HSZLExnNmyQ==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/reduce-function-call/node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -3264,6 +3763,12 @@
"node": ">=0.10.0"
}
},
"node_modules/robust-predicates": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz",
"integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==",
"license": "Unlicense"
},
"node_modules/rolldown": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.1.5.tgz",
+6
View File
@@ -28,6 +28,12 @@
"@stylexjs/stylex": "0.19.0",
"@tanstack/react-query": "5.101.4",
"@tanstack/react-router": "1.170.18",
"@visx/axis": "4.0.0",
"@visx/grid": "4.0.0",
"@visx/group": "4.0.0",
"@visx/scale": "4.0.0",
"@visx/shape": "4.0.0",
"@visx/tooltip": "4.0.0",
"react": "19.2.8",
"react-aria-components": "1.20.0",
"react-dom": "19.2.8"
@@ -0,0 +1,286 @@
import { fireEvent, render as renderBare, screen, within } from "@testing-library/react";
import { QueryClientProvider } from "@tanstack/react-query";
import { createQueryClient } from "@/lib/queryClient";
import { formatTime } from "@/lib/format";
import type { StatsClients } from "@/lib/types";
import ClientChart from "./ClientChart";
import { OTHER_KEY, clientKey, seriesColor } from "./seriesColors";
const SINCE = 1_700_000_000;
const BUCKET = 1800;
function clients(named: { client: string; buckets: number[] }[], other: number[]): StatsClients {
return {
period: "24h",
since: SINCE,
until: SINCE + other.length * BUCKET,
bucket_seconds: BUCKET,
coverage: { complete: true, available_since: SINCE },
clients: named,
other,
};
}
const TWO_BUCKETS = clients(
[
{ client: "192.0.2.30", buckets: [10, 1] },
{ client: "192.0.2.31", buckets: [20, 1] },
],
[5, 1],
);
/**
* The chart looks a client's registered name up, so it needs a query client. No
* client is registered in these fixtures, which is what leaves the addresses on
* screen as the labels.
*/
function render(data: StatsClients) {
const client = createQueryClient();
const tree = (next: StatsClients) => (
<QueryClientProvider client={client}>
<ClientChart data={next} />
</QueryClientProvider>
);
const result = renderBare(tree(data));
return { ...result, rerender: (next: StatsClients) => result.rerender(tree(next)) };
}
beforeEach(() => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
Promise.resolve(
new Response(JSON.stringify({ clients: [] }), {
status: 200,
headers: { "content-type": "application/json" },
}),
),
),
);
});
afterEach(() => vi.unstubAllGlobals());
function overlayRects(container: HTMLElement): SVGRectElement[] {
return Array.from(container.querySelectorAll<SVGRectElement>('rect[fill="transparent"]'));
}
test("the data table is the SVG's accessible equivalent", () => {
render(TWO_BUCKETS);
expect(screen.getByRole("img", { name: /client activity over time/i })).toBeTruthy();
const table = screen.getByRole("table", { name: "Queries per client per time bucket" });
expect(within(table).getAllByRole("row").length).toBe(3);
});
/**
* The x-axis is this response's own `since` plus one bucket width per column.
* The timeseries endpoint aligns its buckets with these, which is what lets the
* two charts stack above one another without either knowing about the other.
*/
test("the columns are timestamped from this response's own window", () => {
render(TWO_BUCKETS);
const rows = within(screen.getByRole("table")).getAllByRole("rowheader");
expect(rows.map((row) => row.textContent)).toEqual([formatTime(SINCE), formatTime(SINCE + BUCKET)]);
});
/**
* Every series here is a disjoint part of the whole, so the scale has to come
* from the tallest column's own sum. Taking it from the largest single value
* instead would run the tallest column off the top of the plot: the axis has to
* reach 35 here, not 20.
*/
test("the value scale covers the tallest column's total, not its largest series", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [20] }], [15]));
const labels = Array.from(container.querySelectorAll(".visx-axis-left text")).map((label) => label.textContent);
expect(labels[labels.length - 1]).toBe("35");
});
test("the series are drawn in the colour of the client's address, and Other in its own", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [10] }], [5]));
const fills = Array.from(container.querySelectorAll("rect"))
.map((rect) => rect.getAttribute("fill"))
.filter((fill) => fill !== "transparent");
expect(fills).toEqual([seriesColor(clientKey("192.0.2.30")), seriesColor(OTHER_KEY)]);
});
test("a window with no queries says so instead of drawing an empty grid", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [0, 0] }], [0, 0]));
expect(screen.getByText("No queries in this period.")).toBeTruthy();
expect(container.querySelector("svg")).toBeNull();
});
test("no bucket at all says the same thing", () => {
render(clients([], []));
expect(screen.getByText("No queries in this period.")).toBeTruthy();
});
test("hover text is the tooltip alone, never a bare SVG title", () => {
const { container } = render(TWO_BUCKETS);
expect(container.querySelectorAll("title")).toHaveLength(0);
});
test("each bucket's hit target spans the full plot height", () => {
const { container } = render(TWO_BUCKETS);
const rects = overlayRects(container);
expect(rects).toHaveLength(2);
for (const rect of rects) {
expect(rect.getAttribute("y")).toBe("8");
expect(rect.getAttribute("height")).toBe("210");
}
});
/**
* A band scale spends a gap after the last column as well as between them, so a
* full-step hit target on the last bucket would reach into the right margin.
*/
test("the last hit target stops at the plot's right edge", () => {
const { container } = render(TWO_BUCKETS);
const last = overlayRects(container).at(-1) as SVGRectElement;
const right = Number(last.getAttribute("x")) + Number(last.getAttribute("width"));
// 640 fallback width, less the 44px left and 8px right margins.
expect(right).toBeCloseTo(44 + 588, 6);
});
/**
* The window refreshes every half minute under an open tooltip. The tooltip
* holds a bucket index and reads the numbers out of the render it is drawing, so
* a refresh that keeps the same buckets updates it rather than leaving last
* minute's counts on screen.
*/
test("a refresh in the same window retells the hovered bucket with the new counts", () => {
const { container, rerender } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(
Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map((dd) => dd.textContent),
).toEqual(["35", "10", "20", "5"]);
rerender(
clients(
[
{ client: "192.0.2.30", buckets: [11, 1] },
{ client: "192.0.2.31", buckets: [22, 1] },
],
[6, 1],
),
);
expect(
Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map((dd) => dd.textContent),
).toEqual(["39", "11", "22", "6"]);
});
/**
* A rolling window is the case a stored copy gets wrong: the bucket the pointer
* was over is gone, so index 0 now names a different span.
*/
test("a refresh that rolls the window takes the tooltip down instead of relabelling it", () => {
const { container, rerender } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
rerender({ ...TWO_BUCKETS, since: SINCE + BUCKET });
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
});
/** The placement the hand-rolled tooltip had, restored over visx's 10px defaults. */
test("the tooltip is offset 8px from the chart top and from the bucket it names", () => {
const { container } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector(".visx-tooltip") as HTMLElement;
expect(tooltip.style.transform).toBe("translate(200px, 8px)");
});
/**
* `withBoundingRects` measures its node once, on mount, so the buckets must not
* share one. jsdom reports every rect as zero, so the mount is what this can
* observe, not the measurement itself.
*/
test("each bucket gets its own tooltip mount, so each is measured for itself", () => {
const { container } = render(TWO_BUCKETS);
const rects = overlayRects(container);
fireEvent.mouseOver(rects[0]);
const first = container.querySelector(".visx-tooltip");
fireEvent.mouseOver(rects[1]);
expect(first).not.toBeNull();
expect(container.querySelector(".visx-tooltip")).not.toBe(first);
});
test("pointing at a bucket names its total and every series, and dims the rest", () => {
const { container } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(tooltip.previousElementSibling?.textContent).toBe(formatTime(SINCE));
expect(Array.from(tooltip.querySelectorAll("dt")).map((dt) => dt.textContent)).toEqual([
"Queries",
"192.0.2.30",
"192.0.2.31",
"Other",
]);
expect(Array.from(tooltip.querySelectorAll("dd")).map((dd) => dd.textContent)).toEqual(["35", "10", "20", "5"]);
const swatches = Array.from(tooltip.querySelectorAll("dt span")).map((span) => span.getAttribute("style"));
expect(swatches[0]).toContain(seriesColor(clientKey("192.0.2.30")));
expect(swatches[2]).toContain(seriesColor(OTHER_KEY));
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.map((group) => group.getAttribute("opacity"))).toEqual(["1", "0.55"]);
});
test("leaving the chart takes the tooltip and the dimming with it", () => {
const { container } = render(TWO_BUCKETS);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
fireEvent.mouseOut(container.querySelector("svg") as SVGSVGElement);
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
});
/**
* "Other" is everything outside the top eight clients. In a window where it
* counted nothing there is no eighth client to aggregate, and the entry would
* appear in the legend, the stack, the tooltip and the table saying only that it
* is empty. The named clients stay at zero: a client that went quiet is a fact.
*/
test("a window where Other counted nothing drops it from every surface", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [10, 4] }], [0, 0]));
expect(Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent)).toEqual(["192.0.2.30"]);
expect(
within(screen.getByRole("table"))
.getAllByRole("columnheader")
.map((cell) => cell.textContent),
).toEqual(["Time", "192.0.2.30"]);
fireEvent.mouseOver(overlayRects(container)[0]);
const terms = Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dt"));
expect(terms.map((term) => term.textContent)).toEqual(["Queries", "192.0.2.30"]);
});
test("one query outside the named clients is enough to keep Other", () => {
const { container } = render(clients([{ client: "192.0.2.30", buckets: [10, 4] }], [0, 1]));
expect(Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent)).toEqual([
"192.0.2.30",
"Other",
]);
});
+121 -159
View File
@@ -2,56 +2,42 @@
* Client activity over the same window as the query-volume chart: one stacked
* series per named client, plus everything outside the top eight as "Other".
*
* The x-axis is the timeseries endpoint's own bucket alignment, so the two
* charts stack directly above one another and a spike in one is at the same
* horizontal position in the other. Colour keys on the client string, so a
* client that changes rank between polls keeps its colour.
* The x-axis is derived from this response's own `since` and `bucket_seconds`,
* which the API aligns with the timeseries endpoint's buckets, so the two charts
* stack directly above one another and a spike in one is at the same horizontal
* position in the other. Colour keys on the client string, so a client that
* changes rank between polls keeps its colour.
*/
import { useEffect, useRef, useState } from "react";
import * as stylex from "@stylexjs/stylex";
import { Group } from "@visx/group";
import { BarStack } from "@visx/shape";
import { formatTime } from "@/lib/format";
import type { StatsClients } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { layoutStacked } from "./chartLayout";
import { clientLabel, useClientNames, type ClientNames } from "@/features/clients/clientNames";
import {
BucketOverlay,
CHART_HEIGHT,
ChartFrame,
ChartRoot,
ChartTooltip,
EmptyChart,
StackSegment,
bandScale,
labelTickValues,
plotArea,
slotCenter,
useActiveIndex,
useMeasuredWidth,
valueScale,
valueTicks,
type TooltipContent,
} from "./chartKit";
import { OTHER_KEY, clientKey, seriesColor } from "./seriesColors";
const CHART_HEIGHT = 240;
const FALLBACK_WIDTH = 640;
const styles = stylex.create({
empty: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: CHART_HEIGHT,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "dashed",
borderColor: colors.borderStrong,
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
root: {
position: "relative",
},
gridLine: {
stroke: colors.border,
},
axisLine: {
stroke: colors.borderStrong,
},
axisLabel: {
fill: colors.textMuted,
fontSize: "10px",
},
/** The hairline separating touching segments is the page ground, not a colour. */
segment: {
stroke: colors.surface,
},
legend: {
marginTop: "0.5rem",
display: "flex",
@@ -80,31 +66,6 @@ const styles = stylex.create({
swatchColor: (color: string) => ({ backgroundColor: color }),
});
function useContainerWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (el === null) return;
setWidth(el.clientWidth);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => setWidth(el.clientWidth));
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width];
}
const compact = new Intl.NumberFormat(undefined, { notation: "compact" });
function formatTick(ts: number, bucketSeconds: number): string {
const date = new Date(ts * 1000);
if (bucketSeconds >= 86_400) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
}
interface Series {
key: string;
label: string;
@@ -115,10 +76,11 @@ interface Series {
}
/**
* "Other" last, so it sits at the top of every column rather than under a
* client, and always present: the response always carries the series, and a
* legend that dropped it on a quiet period would make the reader think the
* chart's clients were all of them.
* "Other" last, so it sits at the top of every column rather than under a client,
* and dropped entirely when it counted nothing across the window: an aggregation
* bucket that aggregated nothing is a legend entry, a stack key, a tooltip row
* and a table column all saying zero. The named clients stay at zero, because a
* client that went quiet is something the reader wants to see.
*/
function seriesOf(data: StatsClients, names: ClientNames): Series[] {
const named = data.clients.map((client) => ({
@@ -131,119 +93,119 @@ function seriesOf(data: StatsClients, names: ClientNames): Series[] {
color: seriesColor(clientKey(client.client)),
buckets: client.buckets,
}));
if (data.other.every((count) => count === 0)) return named;
return [
...named,
{ key: OTHER_KEY, label: "Other", address: null, color: seriesColor(OTHER_KEY), buckets: data.other },
];
}
/** One column: the timestamp plus one entry per series, keyed by the series key. */
type Column = { ts: number } & Record<string, number>;
export default function ClientChart({ data }: { data: StatsClients }) {
const [containerRef, measuredWidth] = useContainerWidth();
const [containerRef, width] = useMeasuredWidth();
// A hover survives a re-render only while it still names the same bucket at
// the same place: a poll that rolls the window, or a resize, retires it.
const hovered = useActiveIndex(`${data.since}:${data.bucket_seconds}:${data.other.length}:${width}`);
const names = useClientNames();
const width = measuredWidth > 0 ? measuredWidth : FALLBACK_WIDTH;
const series = seriesOf(data, names);
const bucketCount = data.other.length;
const columns: Column[] = Array.from({ length: bucketCount }, (_, i) => {
const column: Column = { ts: data.since + i * data.bucket_seconds };
for (const one of series) column[one.key] = one.buckets[i] ?? 0;
return column;
});
if (bucketCount === 0) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
if (bucketCount === 0 || columns.every((column) => series.every((one) => column[one.key] === 0))) {
return <EmptyChart containerRef={containerRef} />;
}
const columns = Array.from({ length: bucketCount }, (_, i) => ({
ts: data.since + i * data.bucket_seconds,
values: series.map((one) => one.buckets[i] ?? 0),
}));
if (columns.every((column) => column.values.every((value) => value === 0))) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
}
const timestamps = columns.map((column) => column.ts);
const totals = columns.map((column) => series.reduce((sum, one) => sum + column[one.key], 0));
const plot = plotArea(width);
const xScale = bandScale(timestamps, plot);
// Every series here is a disjoint part of the whole rather than a highlighted
// subset of a separately reported total, so the tallest column's own sum is
// the scale.
const yScale = valueScale(Math.max(...totals), [plot.bottom, plot.y]);
const yTicks = valueTicks(yScale);
const colorOf = new Map(series.map((one) => [one.key, one.color]));
const layout = layoutStacked(columns, width, CHART_HEIGHT);
const baseline = layout.plot.y + layout.plot.height;
function tooltipOf(index: number): TooltipContent {
return {
title: formatTime(columns[index].ts),
rows: [
{ key: "queries", label: "Queries", value: String(totals[index]) },
...series.map((one) => ({
key: one.key,
label: one.label,
color: one.color,
value: String(columns[index][one.key]),
})),
],
};
}
return (
<div ref={containerRef} {...stylex.props(styles.root)}>
<ChartRoot containerRef={containerRef}>
<svg
role="img"
aria-label={`Client activity over time, ${bucketCount} buckets, ${series.length} series`}
width="100%"
height={CHART_HEIGHT}
viewBox={`0 0 ${width} ${CHART_HEIGHT}`}
onMouseLeave={hovered.clear}
>
{layout.yTicks.map((tick) => (
<g key={tick.value}>
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={tick.y}
y2={tick.y}
{...stylex.props(styles.gridLine)}
/>
<text
x={layout.plot.x - 6}
y={tick.y}
textAnchor="end"
dominantBaseline="middle"
{...stylex.props(styles.axisLabel, shared.tabularNums)}
>
{compact.format(tick.value)}
</text>
</g>
))}
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={baseline}
y2={baseline}
{...stylex.props(styles.axisLine)}
<ChartFrame
plot={plot}
yScale={yScale}
yTicks={yTicks}
xScale={xScale}
xTickValues={labelTickValues(timestamps, plot.width)}
bucketSeconds={data.bucket_seconds}
/>
{layout.xTicks.map((tick) => (
<text
key={tick.ts}
x={tick.x}
y={baseline + 14}
textAnchor="middle"
{...stylex.props(styles.axisLabel)}
>
{formatTick(tick.ts, data.bucket_seconds)}
</text>
))}
{layout.columns.map((column) => (
<g key={column.ts}>
{column.segments.map((rect, index) =>
rect.height <= 0 ? null : (
<rect
key={series[index].key}
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
fill={series[index].color}
strokeWidth={rect.width > 3 ? 1 : 0}
{...stylex.props(styles.segment)}
/>
),
)}
<rect
x={column.slot.x}
y={column.slot.y}
width={column.slot.width}
height={column.slot.height}
fill="transparent"
>
<title>
{`${formatTime(column.ts)}: ${column.total} ${column.total === 1 ? "query" : "queries"}`}
</title>
</rect>
</g>
))}
<BarStack<Column, string>
data={columns}
keys={series.map((one) => one.key)}
x={(column) => column.ts}
xScale={xScale}
yScale={yScale}
color={(key) => colorOf.get(key) ?? seriesColor(key)}
>
{(stacks) =>
columns.map((column, index) => (
<Group
key={column.ts}
opacity={hovered.index === null || hovered.index === index ? 1 : 0.55}
>
{stacks.map((stack) => {
const bar = stack.bars[index];
return (
<StackSegment
key={stack.key}
x={bar.x}
y={bar.y}
width={bar.width}
height={bar.height}
fill={bar.color}
/>
);
})}
</Group>
))
}
</BarStack>
<BucketOverlay plot={plot} values={timestamps} xScale={xScale} onEnter={hovered.show} />
</svg>
{hovered.index !== null && (
<ChartTooltip
index={hovered.index}
content={tooltipOf(hovered.index)}
left={slotCenter(xScale, timestamps[hovered.index], plot)}
/>
)}
<ul {...stylex.props(styles.legend)}>
{series.map((one) => (
<li key={one.key} title={one.address ?? undefined} {...stylex.props(styles.legendItem)}>
@@ -269,14 +231,14 @@ export default function ClientChart({ data }: { data: StatsClients }) {
{columns.map((column) => (
<tr key={column.ts}>
<th scope="row">{formatTime(column.ts)}</th>
{column.values.map((value, index) => (
<td key={series[index].key}>{value}</td>
{series.map((one) => (
<td key={one.key}>{column[one.key]}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
</ChartRoot>
);
}
+200
View File
@@ -0,0 +1,200 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import Donut, { type DonutSlice } from "./Donut";
function slice(key: string, value: number, color = "#000000"): DonutSlice {
return { key, label: key.toUpperCase(), value, color };
}
function ring(container: HTMLElement): SVGPathElement[] {
return Array.from(container.querySelectorAll("svg path"));
}
/** The x radius of every `A` command in a path, in the order they are drawn. */
function arcRadii(d: string): number[] {
return Array.from(d.matchAll(/A(-?[\d.]+),/g)).map((match) => Number(match[1]));
}
function draw(slices: DonutSlice[]) {
return render(<Donut slices={slices} caption="Queries by DNS type" unit="Queries" />);
}
test("a breakdown of nothing says so rather than dividing by zero", () => {
const { container } = draw([slice("a", 0), slice("b", 0)]);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
expect(container.querySelector("svg")).toBeNull();
});
test("an empty breakdown says the same thing", () => {
draw([]);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
});
/** A legend entry reading 0% is noise, and a zero slice has no arc to draw. */
test("zero-valued entries are dropped from the ring, the legend and the table", () => {
const { container } = draw([slice("a", 3), slice("z", 0), slice("b", 1)]);
expect(ring(container)).toHaveLength(2);
expect(screen.queryByText("Z")).toBeNull();
expect(
within(screen.getByRole("table"))
.getAllByRole("rowheader")
.map((row) => row.textContent),
).toEqual(["A", "B"]);
});
/**
* The caller has already ranked the slices, so the ring must not re-sort them:
* the first arc opens at twelve o'clock and each one starts where the last
* ended, running clockwise.
*
* The fixture runs 1 then 3 on purpose. d3's default pie sort is by value
* descending, so a fixture that happened to be given in descending order would
* pass with the sort left on and prove nothing.
*/
test("the ring starts at twelve o'clock and runs clockwise in the order given", () => {
const { container } = draw([slice("a", 1, "#112233"), slice("b", 3, "#445566")]);
const paths = ring(container);
// The small slice is drawn first because it was given first.
expect(paths[0].getAttribute("fill")).toBe("#112233");
expect(paths[0].getAttribute("d")?.startsWith("M0,-90")).toBe(true);
// A quarter turn clockwise from the top is three o'clock, where the second
// slice picks up.
expect(paths[1].getAttribute("fill")).toBe("#445566");
expect(paths[1].getAttribute("d")?.startsWith("M90,0")).toBe(true);
});
/**
* A whole-circle arc from a point back to itself draws nothing at all, so the
* one-entry case has to come out as a closed ring: two half arcs out and two
* back.
*/
test("a single entry is a closed ring, not a zero-length arc", () => {
const { container } = draw([slice("only", 7)]);
const paths = ring(container);
expect(paths).toHaveLength(1);
const d = paths[0].getAttribute("d") ?? "";
expect(d.match(/A/g)).toHaveLength(4);
// Two half arcs out at the outer radius and two back at the inner one: a
// 180px ring 36px thick.
expect(arcRadii(d)).toEqual([90, 90, 54, 54]);
});
test("shares are of the drawn total, in the legend and in the hidden table alike", () => {
draw([slice("a", 3), slice("b", 1)]);
expect(screen.getAllByText("75.0%")).toHaveLength(2);
expect(screen.getAllByText("25.0%")).toHaveLength(2);
});
/**
* The colour is the caller's, never recomputed from the key here: the page owns
* the identity-to-colour mapping and two donuts of one page must agree with it.
*/
test("each arc is filled with the colour its slice carries", () => {
const { container } = draw([slice("a", 3, "#112233"), slice("b", 1, "#445566")]);
expect(ring(container).map((path) => path.getAttribute("fill"))).toEqual(["#112233", "#445566"]);
});
/**
* Colour is a pure function of identity and so cannot rule out two slices of one
* panel sharing a hue. The stroke is what stops neighbours from merging into one
* shape.
*/
test("every arc is outlined in the panel's own surface colour", () => {
const { container } = draw([slice("a", 3), slice("b", 1)]);
for (const path of ring(container)) {
expect(path.getAttribute("stroke-width")).toBe("1");
expect(path.getAttribute("stroke")).toMatch(/^var\(--/);
}
});
test("the ring is decoration; the legend and the hidden table are the accessible surface", () => {
const { container } = draw([slice("a", 3), slice("b", 1)]);
const svg = container.querySelector("svg");
expect(svg?.getAttribute("aria-hidden")).toBe("true");
expect(svg?.getAttribute("focusable")).toBe("false");
expect(screen.getByRole("table", { name: "Queries by DNS type" })).toBeTruthy();
});
/**
* The ring gets the bar charts' hover treatment: the shared tooltip names the
* slice and repeats what the legend says about it, and the slices it is not
* naming dim out of the way. The ring stays `aria-hidden` — the tooltip is a
* pointer affordance, and the legend beside it is still the readable copy.
*/
test("pointing at a slice names it and dims the rest", () => {
const { container } = draw([slice("a", 3, "#112233"), slice("b", 1, "#445566")]);
const paths = ring(container);
fireEvent.mouseOver(paths[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(tooltip.previousElementSibling?.textContent).toBe("A");
expect(Array.from(tooltip.querySelectorAll("dt")).map((term) => term.textContent)).toEqual(["Queries", "Share"]);
expect(Array.from(tooltip.querySelectorAll("dd")).map((value) => value.textContent)).toEqual(["3", "75.0%"]);
// The same share the legend and the hidden table already print for this slice.
expect(screen.getAllByText("75.0%")).toHaveLength(3);
expect(paths.map((path) => path.getAttribute("opacity"))).toEqual(["1", "0.55"]);
expect(container.querySelector("svg")?.getAttribute("aria-hidden")).toBe("true");
// The tooltip points at the middle of the arc, which the component computes
// from the slice values rather than from the drawn path. Slice A is three
// quarters of the ring, so its midpoint is at 135 degrees, on a circle of
// radius 72 — (140.9, 140.9) from the ring's top-left corner, plus the 8px
// the tooltip stands off by. Nothing else here would catch that arithmetic
// drifting away from the ring the Pie actually draws.
const tooltipBox = container.querySelector(".visx-tooltip") as HTMLElement;
expect(tooltipBox.style.transform).toBe("translate(149px, 149px)");
});
test("leaving the ring takes the tooltip and the dimming with it", () => {
const { container } = draw([slice("a", 3), slice("b", 1)]);
fireEvent.mouseOver(ring(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
fireEvent.mouseOut(container.querySelector("svg") as SVGSVGElement);
expect(container.querySelectorAll("dl")).toHaveLength(0);
expect(ring(container).map((path) => path.getAttribute("opacity"))).toEqual(["1", "1"]);
});
/**
* The same slice can change width between refreshes, so a mount measured at the
* old width would be placed at the wrong one. This is the donut's half of the
* remount the bar charts do.
*/
test("a refresh keeps the hovered slice current and remeasures it", () => {
const { container, rerender } = draw([slice("a", 3), slice("b", 1)]);
fireEvent.mouseOver(ring(container)[0]);
const first = container.querySelector(".visx-tooltip");
expect(Array.from(first?.querySelectorAll("dd") ?? []).map((value) => value.textContent)).toEqual(["3", "75.0%"]);
rerender(<Donut slices={[slice("a", 3000), slice("b", 1000)]} caption="Queries by DNS type" unit="Queries" />);
const second = container.querySelector(".visx-tooltip");
expect(Array.from(second?.querySelectorAll("dd") ?? []).map((value) => value.textContent)).toEqual([
"3,000",
"75.0%",
]);
expect(second).not.toBe(first);
});
/** A slice that is gone cannot be described, so the hover goes with it. */
test("a refresh that changes the slices takes the tooltip down", () => {
const { container, rerender } = draw([slice("a", 3), slice("b", 1)]);
fireEvent.mouseOver(ring(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
rerender(<Donut slices={[slice("c", 3), slice("b", 1)]} caption="Queries by DNS type" unit="Queries" />);
expect(container.querySelectorAll("dl")).toHaveLength(0);
});
+130 -45
View File
@@ -13,12 +13,26 @@
*/
import * as stylex from "@stylexjs/stylex";
import { Group } from "@visx/group";
import { Pie } from "@visx/shape";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { layoutDonut, type DonutSlice } from "./donutLayout";
import { ChartTooltip, useActiveIndex, type TooltipContent } from "./chartKit";
export interface DonutSlice {
/** Semantic identity: the React key, the colour key and the legend's identity. */
key: string;
label: string;
/** Disambiguates entries whose labels collide — two "Unknown"s, one name on two route kinds. */
secondary?: string;
value: number;
color: string;
}
const SIZE = 180;
const THICKNESS = 36;
const OUTER_RADIUS = SIZE / 2;
const INNER_RADIUS = OUTER_RADIUS - THICKNESS;
const numberFormat = new Intl.NumberFormat();
@@ -54,8 +68,12 @@ const styles = stylex.create({
justifyContent: { default: "center", [TWO_COLUMN]: "flex-start" },
gap: "1.25rem",
},
/** The tooltip is placed against the ring's own box, so slice coordinates can
* be used unchanged rather than measured against the whole panel. */
ring: {
position: "relative",
flexShrink: 0,
lineHeight: 0,
},
/**
* Capped and left-anchored. Without the cap the row justifies across whatever
@@ -115,6 +133,21 @@ function sharePercent(share: number): string {
return `${(share * 100).toFixed(1)}%`;
}
/**
* Where a slice's tooltip points: the middle of its arc, in the ring box's own
* coordinates. This restates the `Pie` configuration below — clockwise from
* twelve o'clock, caller order, no pad angle — and the two must agree.
*/
function sliceAnchor(drawn: DonutSlice[], index: number, total: number): { left: number; top: number } {
const before = drawn.slice(0, index).reduce((sum, slice) => sum + slice.value, 0);
const middle = (2 * Math.PI * (before + drawn[index].value / 2)) / total;
const radius = (OUTER_RADIUS + INNER_RADIUS) / 2;
return {
left: OUTER_RADIUS + Math.sin(middle) * radius,
top: OUTER_RADIUS - Math.cos(middle) * radius,
};
}
export default function Donut({
slices,
caption,
@@ -126,56 +159,108 @@ export default function Donut({
/** The column header for the counted thing, e.g. "Queries". */
unit: string;
}) {
const layout = layoutDonut(slices, SIZE, THICKNESS);
// Zero-valued entries have no arc to draw and a legend entry reading 0 is
// noise, so they are dropped before anything is measured or drawn.
const drawn = slices.filter((slice) => slice.value > 0);
const total = drawn.reduce((sum, slice) => sum + slice.value, 0);
// A hover names a slice by position, so it survives only while the ring is
// still made of the same slices in the same order.
const hovered = useActiveIndex(drawn.map((slice) => slice.key).join(","));
if (layout.total === 0) {
function tooltipOf(index: number): TooltipContent {
const slice = drawn[index];
return {
title: slice.secondary === undefined ? slice.label : `${slice.label} (${slice.secondary})`,
rows: [
{ key: "value", label: unit, color: slice.color, value: numberFormat.format(slice.value) },
{ key: "share", label: "Share", value: sharePercent(slice.value / total) },
],
};
}
if (total === 0) {
return <div {...stylex.props(styles.empty)}>No queries in this period.</div>;
}
return (
<div {...stylex.props(styles.body)}>
<svg
aria-hidden="true"
focusable="false"
width={SIZE}
height={SIZE}
viewBox={`0 0 ${SIZE} ${SIZE}`}
{...stylex.props(styles.ring)}
>
{layout.arcs.map((arc) => (
// The stroke is what keeps a shared hue from lying. Colour is a pure
// function of identity, so two neighbouring slices can come out the
// same; outlined in the panel's own colour they still read as two
// shapes rather than merging into one. Attributes rather than a
// class, as the client chart's segments are, so the separation is
// visible to a test and not only to a stylesheet.
<path
key={arc.slice.key}
d={arc.d}
fill={arc.slice.color}
fillRule="evenodd"
stroke={colors.surfaceRaised}
strokeWidth={1}
<div {...stylex.props(styles.ring)}>
{/* The ring stays out of the accessibility tree even though it is now
a pointer target: the tooltip repeats what the legend beside it
already says in text, so nothing here is the only copy. */}
<svg
aria-hidden="true"
focusable="false"
width={SIZE}
height={SIZE}
viewBox={`0 0 ${SIZE} ${SIZE}`}
onMouseLeave={hovered.clear}
>
{/* Arc paths are generated around the origin, and `Pie`'s own
`top`/`left` group is skipped when it is given a render prop, so
the ring is centred here instead. */}
<Group top={OUTER_RADIUS} left={OUTER_RADIUS}>
<Pie
data={drawn}
pieValue={(slice) => slice.value}
// The caller has already ranked the slices, so d3's own sort is off
// in both of its forms and the ring runs clockwise from twelve
// o'clock in the order given. @visx/shape 4.0.0 already disables
// it by default — but that default exists because d3-shape v3
// changed sortValues to descending under it, so saying it here is
// what keeps a future bump from silently re-ranking the ring.
pieSort={null}
pieSortValues={null}
outerRadius={OUTER_RADIUS}
innerRadius={INNER_RADIUS}
>
{({ arcs, path }) =>
arcs.map((arc, index) => (
// The stroke is what keeps a shared hue from lying. Colour is a
// pure function of identity, so two neighbouring slices can come
// out the same; outlined in the panel's own colour they still
// read as two shapes rather than merging into one. Attributes
// rather than a class, as the client chart's segments are, so
// the separation is visible to a test and not only to a
// stylesheet.
<path
key={arc.data.key}
d={path(arc) ?? ""}
fill={arc.data.color}
stroke={colors.surfaceRaised}
strokeWidth={1}
opacity={hovered.index === null || hovered.index === index ? 1 : 0.55}
onMouseEnter={() => hovered.show(index)}
/>
))
}
</Pie>
</Group>
</svg>
{hovered.index !== null && (
<ChartTooltip
index={hovered.index}
content={tooltipOf(hovered.index)}
{...sliceAnchor(drawn, hovered.index, total)}
/>
))}
</svg>
)}
</div>
<ul {...stylex.props(styles.legend)}>
{layout.arcs.map((arc) => (
<li key={arc.slice.key} {...stylex.props(styles.legendItem)}>
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchColor(arc.slice.color))}
/>
{drawn.map((slice) => (
<li key={slice.key} {...stylex.props(styles.legendItem)}>
<span aria-hidden="true" {...stylex.props(styles.swatch, styles.swatchColor(slice.color))} />
<span {...stylex.props(styles.label)}>
{arc.slice.label}
{arc.slice.secondary !== undefined && (
<span {...stylex.props(styles.secondary)}>{arc.slice.secondary}</span>
{slice.label}
{slice.secondary !== undefined && (
<span {...stylex.props(styles.secondary)}>{slice.secondary}</span>
)}
</span>
<span {...stylex.props(styles.count, shared.tabularNums)}>
{numberFormat.format(arc.slice.value)}
{numberFormat.format(slice.value)}
</span>
<span {...stylex.props(styles.share, shared.tabularNums)}>
{sharePercent(slice.value / total)}
</span>
<span {...stylex.props(styles.share, shared.tabularNums)}>{sharePercent(arc.share)}</span>
</li>
))}
</ul>
@@ -190,15 +275,15 @@ export default function Donut({
</tr>
</thead>
<tbody>
{layout.arcs.map((arc) => (
<tr key={arc.slice.key}>
{drawn.map((slice) => (
<tr key={slice.key}>
<th scope="row">
{arc.slice.secondary === undefined
? arc.slice.label
: `${arc.slice.label} (${arc.slice.secondary})`}
{slice.secondary === undefined
? slice.label
: `${slice.label} (${slice.secondary})`}
</th>
<td>{arc.slice.value}</td>
<td>{sharePercent(arc.share)}</td>
<td>{slice.value}</td>
<td>{sharePercent(slice.value / total)}</td>
</tr>
))}
</tbody>
@@ -14,7 +14,7 @@ import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
import { AuthProvider } from "@/auth/store";
import { createQueryClient } from "@/lib/queryClient";
import { createAppRouter } from "@/routes";
import { clientKey, seriesColor } from "./seriesColors";
import { clientKey, qtypeKey, seriesColor } from "./seriesColors";
import { health } from "@/lib/healthFixture";
import type { Health, StatsClients, StatsRoutes, StatsTimeseries, StatsTotals, StatsTypes } from "@/lib/types";
@@ -203,6 +203,18 @@ test("every donut arc is outlined, so two slices of one hue still read as two",
}
});
test("the page builds a donut slice's colour from the entry's identity", async () => {
// `Donut` renders the colour it is handed and never recomputes one, so the
// mapping from identity to hue is the page's job and is pinned here.
renderApp();
await screen.findByText("1,000");
await waitFor(() => expect(within(panel("Query types")).getAllByText("A")).toHaveLength(2));
const item = within(panel("Query types")).getAllByText("A")[0].closest("li") as HTMLElement;
const swatch = item.querySelector("span[aria-hidden]") as HTMLElement;
expect(swatch.getAttribute("style")).toContain(seriesColor(qtypeKey(1)));
});
test("a slow endpoint does not hold the page back: the panels that answered render beside it", async () => {
// Through the real route, which is the point: the loader starts the five
// requests and awaits none of them. If it awaited, the router would hold the
@@ -259,9 +271,10 @@ test("naming a client does not recolour its series", async () => {
expect(swatch.getAttribute("style")).toContain(seriesColor(clientKey("192.0.2.30")));
});
test("the client chart names Other even in a period where it counted nothing", async () => {
// The fixture's other series is all zeroes. Dropping it from the legend there
// would tell the reader the two named clients were every client.
test("the client chart drops Other in a period where it counted nothing", async () => {
// The fixture's other series is all zeroes. An aggregation bucket that
// aggregated nothing is a legend entry and a table column that say only that
// they are empty; the named clients stay, because a quiet client is a fact.
renderApp();
await screen.findByRole("heading", { name: "Client activity over time" });
@@ -269,8 +282,8 @@ test("the client chart names Other even in a period where it counted nothing", a
expect(chart).toBeTruthy();
// Twice each: the legend swatch and the column header of the table a screen
// reader gets instead of the graphic.
await waitFor(() => expect(within(chart as HTMLElement).getAllByText("Other")).toHaveLength(2));
expect(within(chart as HTMLElement).getAllByText("192.0.2.30")).toHaveLength(2);
await waitFor(() => expect(within(chart as HTMLElement).getAllByText("192.0.2.30")).toHaveLength(2));
expect(within(chart as HTMLElement).queryAllByText("Other")).toHaveLength(0);
});
test("the page is four tiles, two charts and two donuts — no status or issues sections", async () => {
+1 -1
View File
@@ -25,7 +25,7 @@ import ClientChart from "./ClientChart";
import Donut from "./Donut";
import StatTiles from "./StatTiles";
import TimeseriesChart from "./TimeseriesChart";
import type { DonutSlice } from "./donutLayout";
import type { DonutSlice } from "./Donut";
import { useOverviewWindow, type Panel } from "./overviewWindow";
import { DEFAULT_PERIOD, PERIODS } from "./period";
import { qtypeKey, routeKey, seriesColor } from "./seriesColors";
@@ -1,25 +1,32 @@
import { render, screen, within } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import * as stylex from "@stylexjs/stylex";
import type { StatsTimeseries } from "@/lib/types";
import { formatTime } from "@/lib/format";
import type { Bucket, StatsTimeseries } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import TimeseriesChart from "./TimeseriesChart";
const SINCE = 1_700_000_000;
function timeseries(bucketCount: number): StatsTimeseries {
function timeseries(buckets: Bucket[]): StatsTimeseries {
return {
period: "24h",
since: SINCE,
until: SINCE + bucketCount * 1800,
until: SINCE + buckets.length * 1800,
bucket_seconds: 1800,
coverage: { complete: true, available_since: SINCE },
buckets: Array.from({ length: bucketCount }, (_, i) => ({
buckets,
};
}
function counting(bucketCount: number): StatsTimeseries {
return timeseries(
Array.from({ length: bucketCount }, (_, i) => ({
ts: SINCE + i * 1800,
queries: i + 1,
blocked: 1,
cached: 1,
})),
};
);
}
/** The element wearing the shared hidden style, found by its compiled classes. */
@@ -29,8 +36,13 @@ function hiddenElement(container: HTMLElement): Element | null {
return container.querySelector(classes.map((name) => `.${name}`).join(""));
}
/** The transparent per-bucket hit targets, in bucket order. */
function overlayRects(container: HTMLElement): SVGRectElement[] {
return Array.from(container.querySelectorAll<SVGRectElement>('rect[fill="transparent"]'));
}
test("the data table is the SVG's accessible equivalent", () => {
render(<TimeseriesChart data={timeseries(3)} />);
render(<TimeseriesChart data={counting(3)} />);
expect(screen.getByRole("img", { name: /queries over time/i })).toBeTruthy();
const table = screen.getByRole("table", { name: "Queries per time bucket" });
@@ -44,9 +56,339 @@ test("the data table is the SVG's accessible equivalent", () => {
* push the document's scroll height a screen past the app shell.
*/
test("the hidden data table is clipped by a block wrapper, not by the table itself", () => {
const { container } = render(<TimeseriesChart data={timeseries(48)} />);
const { container } = render(<TimeseriesChart data={counting(48)} />);
const hidden = hiddenElement(container);
expect(hidden?.tagName).toBe("DIV");
expect(hidden?.querySelector("table")).not.toBeNull();
});
/**
* "Allowed" is what the reported total leaves over, and the three counts come
* from separate columns that a partial write can leave inconsistent. A negative
* remainder would draw a segment upside down.
*/
test("allowed is the remainder of the reported total, clamped at zero", () => {
const { container } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 10, blocked: 8, cached: 5 }])} />,
);
const row = within(screen.getByRole("table")).getAllByRole("row")[1];
expect(
within(row)
.getAllByRole("cell")
.map((cell) => cell.textContent),
).toEqual(["10", "8", "5", "0"]);
// Blocked and cached are drawn; the empty "allowed" segment is not.
expect(container.querySelectorAll('rect[fill="#3b82f6"]')).toHaveLength(0);
// The scale comes from the reported total, not from the stack's own sum.
// Scaling to the sum would reach 13 here and leave the bar four fifths of the
// way up a plot whose own numbers say it is full.
const ticks = Array.from(container.querySelectorAll(".visx-axis-left text")).map((tick) => tick.textContent);
expect(ticks[ticks.length - 1]).toBe("10");
});
test("a window with no queries says so instead of drawing an empty grid", () => {
const { container } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 0, blocked: 0, cached: 0 },
{ ts: SINCE + 1800, queries: 0, blocked: 0, cached: 0 },
])}
/>,
);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
expect(container.querySelector("svg")).toBeNull();
});
test("no bucket at all says the same thing", () => {
render(<TimeseriesChart data={timeseries([])} />);
expect(screen.getByText("No queries in this period.")).toBeTruthy();
});
/**
* The three category colours are fixed constants of this chart rather than
* anything derived from `seriesColors`, which would paint "other" grey.
*/
test("the segments are drawn in this chart's own category colours", () => {
const { container } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 100, blocked: 40, cached: 10 }])} />,
);
const fills = Array.from(container.querySelectorAll("rect"))
.map((rect) => rect.getAttribute("fill"))
.filter((fill) => fill !== "transparent");
expect(fills).toEqual(["#ef4444", "#059669", "#3b82f6"]);
});
/**
* The graphic carries no `<title>`: it duplicated the tooltip, the browser
* showed it after its own delay and out of the app's styling, and the hidden
* table is already the accessible equivalent.
*/
test("hover text is the tooltip alone, never a bare SVG title", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
expect(container.querySelectorAll("title")).toHaveLength(0);
});
/** The hit target is the whole column slot, including the space above a short stack. */
test("each bucket's hit target spans the full plot height", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
const rects = overlayRects(container);
expect(rects).toHaveLength(3);
for (const rect of rects) {
expect(rect.getAttribute("y")).toBe("8");
expect(rect.getAttribute("height")).toBe("210");
}
});
/**
* A band scale spends a gap after the last column as well as between them, so a
* full-step hit target on the last bucket would reach into the right margin and
* catch pointers that are past the plot entirely.
*/
test("the last hit target stops at the plot's right edge", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
const last = overlayRects(container).at(-1) as SVGRectElement;
const right = Number(last.getAttribute("x")) + Number(last.getAttribute("width"));
// 640 fallback width, less the 44px left and 8px right margins.
expect(right).toBeCloseTo(44 + 588, 6);
});
test("pointing at a bucket names its total and every series, and dims the rest", () => {
const { container } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(tooltip.previousElementSibling?.textContent).toBe(formatTime(SINCE));
const values = Array.from(tooltip.querySelectorAll("dd")).map((dd) => dd.textContent);
expect(values).toEqual(["100", "40", "10", "50"]);
const terms = Array.from(tooltip.querySelectorAll("dt")).map((dt) => dt.textContent);
expect(terms).toEqual(["Queries", "Blocked", "Cached", "Allowed"]);
// One swatch per series, in the colour the segment is drawn in.
const swatches = Array.from(tooltip.querySelectorAll("dt span")).map((span) => span.getAttribute("style"));
expect(swatches[0]).toContain("#ef4444");
expect(swatches[1]).toContain("#059669");
expect(swatches[2]).toContain("#3b82f6");
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.map((group) => group.getAttribute("opacity"))).toEqual(["1", "0.55"]);
});
/**
* The tooltip sits 8px down from the chart's top edge and 8px to the side of the
* slot it names — the placement the hand-rolled tooltip had, restored over
* visx's own 10px defaults.
*/
test("the tooltip is offset 8px from the chart top and from the bucket it names", () => {
const { container } = render(<TimeseriesChart data={counting(2)} />);
fireEvent.mouseOver(overlayRects(container)[0]);
// The first slot spans 44 to 44 + step, so its centre is 191.5 and the
// tooltip sits 8px right of it. visx rounds the placement to whole pixels.
const tooltip = container.querySelector(".visx-tooltip") as HTMLElement;
expect(tooltip.style.transform).toBe("translate(200px, 8px)");
});
/**
* `withBoundingRects` measures its node once, on mount. Sharing one mount across
* buckets would place a wide bucket's tooltip with a narrow bucket's measured
* width, which flips or clips it at the right-hand edge of the plot. Remounting
* per bucket is what forces a fresh measurement; jsdom reports every rect as
* zero, so the mount is what this can observe, not the measurement itself.
*/
test("each bucket gets its own tooltip mount, so each is measured for itself", () => {
const { container } = render(<TimeseriesChart data={counting(2)} />);
const rects = overlayRects(container);
fireEvent.mouseOver(rects[0]);
const first = container.querySelector(".visx-tooltip");
fireEvent.mouseOver(rects[1]);
const second = container.querySelector(".visx-tooltip");
expect(first).not.toBeNull();
expect(second).not.toBe(first);
});
/**
* The window refreshes every half minute under an open tooltip. The tooltip
* holds a bucket index and reads the numbers out of the render it is drawing, so
* a refresh that keeps the same buckets updates it rather than leaving last
* minute's counts on screen.
*/
test("a refresh in the same window retells the hovered bucket with the new counts", () => {
const before = timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
]);
const { container, rerender } = render(<TimeseriesChart data={before} />);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(
Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map((dd) => dd.textContent),
).toEqual(["100", "40", "10", "50"]);
rerender(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 120, blocked: 60, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
const values = Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dd")).map(
(dd) => dd.textContent,
);
expect(values).toEqual(["120", "60", "10", "50"]);
});
/**
* A rolling window is the case a stored copy gets wrong: the bucket the pointer
* was over is gone, so index 0 now names a different span. The tooltip goes away
* rather than describing a bucket that is no longer drawn, and nothing stays
* dimmed behind it. Rolling back to the earlier window must not bring it back
* either: the selection is deleted when the window moves, not held aside.
*/
test("a refresh that rolls the window takes the tooltip down instead of relabelling it", () => {
const { container, rerender } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
rerender(
<TimeseriesChart
data={{
...timeseries([
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
{ ts: SINCE + 3600, queries: 70, blocked: 7, cached: 7 },
]),
since: SINCE + 1800,
}}
/>,
);
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
rerender(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 100, blocked: 40, cached: 10 },
{ ts: SINCE + 1800, queries: 50, blocked: 5, cached: 5 },
])}
/>,
);
expect(container.querySelectorAll("dl")).toHaveLength(0);
});
/**
* The same bucket can change width between refreshes — a count crossing a digit
* boundary, a client name arriving — and a mount measured at the old width is
* placed at the wrong one. A content change therefore remounts the tooltip, the
* same way moving between buckets does.
*/
test("a bucket whose numbers change is remounted, so it is measured again", () => {
const { container, rerender } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 9, blocked: 4, cached: 1 }])} />,
);
fireEvent.mouseOver(overlayRects(container)[0]);
const first = container.querySelector(".visx-tooltip");
rerender(<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 1000, blocked: 4, cached: 1 }])} />);
const second = container.querySelector(".visx-tooltip");
expect(first).not.toBeNull();
expect(second).not.toBeNull();
expect(second).not.toBe(first);
});
test("leaving the chart takes the tooltip and the dimming with it", () => {
const { container } = render(<TimeseriesChart data={counting(3)} />);
fireEvent.mouseOver(overlayRects(container)[0]);
expect(container.querySelectorAll("dl")).toHaveLength(1);
fireEvent.mouseOut(container.querySelector("svg") as SVGSVGElement);
expect(container.querySelectorAll("dl")).toHaveLength(0);
const stacks = Array.from(container.querySelectorAll("svg > g.visx-group[opacity]"));
expect(stacks.every((group) => group.getAttribute("opacity") === "1")).toBe(true);
});
/**
* The third series is every query neither blocked nor served from cache. It was
* called "Other", which named the arithmetic rather than the thing.
*/
test("the remainder series is called Allowed everywhere it surfaces", () => {
const { container } = render(
<TimeseriesChart data={timeseries([{ ts: SINCE, queries: 10, blocked: 2, cached: 3 }])} />,
);
const legend = Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent);
expect(legend).toEqual(["Blocked", "Cached", "Allowed"]);
expect(
within(screen.getByRole("table"))
.getAllByRole("columnheader")
.map((cell) => cell.textContent),
).toEqual(["Time", "Queries", "Blocked", "Cached", "Allowed"]);
fireEvent.mouseOver(overlayRects(container)[0]);
const terms = Array.from((container.querySelector("dl") as HTMLElement).querySelectorAll("dt"));
expect(terms.map((term) => term.textContent)).toEqual(["Queries", "Blocked", "Cached", "Allowed"]);
expect(screen.queryByText("Other")).toBeNull();
});
/**
* A window where everything was blocked or served from cache has no allowed
* queries, and that is worth reading rather than hiding: an absent series would
* say the same thing as a series nobody looked at. The three categories are all
* real answers a query can get, so none of them is dropped for counting zero.
* The client chart's "Other" is dropped at zero, but that one aggregates clients
* beyond the top eight rather than naming a kind of answer.
*/
test("a window with nothing allowed keeps the series at zero", () => {
const { container } = render(
<TimeseriesChart
data={timeseries([
{ ts: SINCE, queries: 4, blocked: 4, cached: 0 },
{ ts: SINCE + 1800, queries: 6, blocked: 6, cached: 0 },
])}
/>,
);
const legend = Array.from(container.querySelectorAll("ul li")).map((item) => item.textContent);
expect(legend).toEqual(["Blocked", "Cached", "Allowed"]);
fireEvent.mouseOver(overlayRects(container)[0]);
const tooltip = container.querySelector("dl") as HTMLElement;
expect(Array.from(tooltip.querySelectorAll("dt")).map((term) => term.textContent)).toEqual([
"Queries",
"Blocked",
"Cached",
"Allowed",
]);
expect(Array.from(tooltip.querySelectorAll("dd")).map((value) => value.textContent)).toEqual(["4", "4", "0", "0"]);
});
+145 -247
View File
@@ -1,107 +1,49 @@
import { useEffect, useRef, useState } from "react";
import * as stylex from "@stylexjs/stylex";
import { Group } from "@visx/group";
import { BarStack } from "@visx/shape";
import { formatTime } from "@/lib/format";
import type { StatsTimeseries } from "@/lib/types";
import type { Bucket, StatsTimeseries } from "@/lib/types";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
import { isEmptyTimeseries, layoutTimeseries, type BarLayout } from "./chartLayout";
import {
BucketOverlay,
CHART_HEIGHT,
ChartFrame,
ChartRoot,
ChartTooltip,
EmptyChart,
StackSegment,
bandScale,
labelTickValues,
plotArea,
slotCenter,
useActiveIndex,
useMeasuredWidth,
valueScale,
valueTicks,
type TooltipContent,
} from "./chartKit";
// Series colors validated for CVD separation and 3:1 surface contrast in both
// modes (Tailwind red-500 / blue-500 / emerald-600; same hex light and dark).
// The third key stays `other` — it is the colour key and the response field, and
// renaming it would repaint the series. Only what the reader sees is "Allowed".
const SERIES = [
{ key: "blocked", label: "Blocked", color: "#ef4444" },
{ key: "cached", label: "Cached", color: "#059669" },
{ key: "other", label: "Other", color: "#3b82f6" },
{ key: "other", label: "Allowed", color: "#3b82f6" },
] as const;
const CHART_HEIGHT = 240;
const FALLBACK_WIDTH = 640;
type Series = (typeof SERIES)[number];
type SeriesKey = Series["key"];
const SERIES_COLOR: Record<SeriesKey, string> = {
blocked: SERIES[0].color,
cached: SERIES[1].color,
other: SERIES[2].color,
};
const styles = stylex.create({
empty: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: CHART_HEIGHT,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "dashed",
borderColor: colors.borderStrong,
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
chartRoot: {
position: "relative",
},
tooltip: {
pointerEvents: "none",
position: "absolute",
top: "0.5rem",
zIndex: 10,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.borderStrong,
backgroundColor: colors.surfaceRaised,
paddingInline: "0.75rem",
paddingBlock: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
boxShadow: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
},
/** Dynamic: the tooltip flips to whichever side of the bar has room. */
tooltipLeft: (left: number) => ({ left, right: null }),
tooltipRight: (right: number) => ({ left: null, right }),
tooltipTitle: {
fontWeight: 500,
},
tooltipList: {
display: "flex",
flexDirection: "column",
gap: "0.125rem",
marginTop: "0.25rem",
},
tooltipRow: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "1rem",
},
tooltipTerm: {
display: "flex",
alignItems: "center",
gap: "0.375rem",
color: colors.textMuted,
},
swatch: {
display: "inline-block",
borderRadius: "0.125rem",
},
/** Dynamic: the swatch takes the series colour the SVG bars are drawn in. */
swatchColor: (color: string) => ({ backgroundColor: color }),
swatchSmall: {
width: "0.5rem",
height: "0.5rem",
},
swatchLarge: {
width: "0.625rem",
height: "0.625rem",
},
gridLine: {
stroke: colors.border,
},
axisLine: {
stroke: colors.borderStrong,
},
axisLabel: {
fill: colors.textMuted,
fontSize: "10px",
},
/** The hairline separating touching segments is the page ground, not a colour. */
segment: {
stroke: colors.surface,
},
legend: {
marginTop: "0.5rem",
display: "flex",
@@ -117,177 +59,131 @@ const styles = stylex.create({
alignItems: "center",
gap: "0.375rem",
},
swatch: {
display: "inline-block",
width: "0.625rem",
height: "0.625rem",
borderRadius: "0.125rem",
},
/** Dynamic: the swatch takes the series colour the SVG bars are drawn in. */
swatchColor: (color: string) => ({ backgroundColor: color }),
});
function useContainerWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (el === null) return;
setWidth(el.clientWidth);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => setWidth(el.clientWidth));
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width];
interface Column {
ts: number;
queries: number;
blocked: number;
cached: number;
/** queries - blocked - cached, clamped at 0. */
other: number;
}
const compact = new Intl.NumberFormat(undefined, { notation: "compact" });
function formatTick(ts: number, bucketSeconds: number): string {
const date = new Date(ts * 1000);
if (bucketSeconds >= 86_400) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
function columnsOf(buckets: Bucket[]): Column[] {
return buckets.map((bucket) => ({
ts: bucket.ts,
queries: bucket.queries,
blocked: bucket.blocked,
cached: bucket.cached,
other: Math.max(0, bucket.queries - bucket.blocked - bucket.cached),
}));
}
function barSummary(bar: BarLayout): string {
return `${formatTime(bar.bucket.ts)}: ${bar.bucket.queries} queries, ${bar.bucket.blocked} blocked, ${bar.bucket.cached} cached`;
}
function Tooltip({ bar, chartWidth }: { bar: BarLayout; chartWidth: number }) {
const centerX = bar.slot.x + bar.slot.width / 2;
const leftHalf = centerX < chartWidth / 2;
const side = leftHalf
? styles.tooltipLeft(Math.min(centerX + 8, chartWidth - 160))
: styles.tooltipRight(chartWidth - centerX + 8);
return (
<div {...stylex.props(styles.tooltip, side)}>
<div {...stylex.props(styles.tooltipTitle)}>{formatTime(bar.bucket.ts)}</div>
<dl {...stylex.props(styles.tooltipList)}>
<div {...stylex.props(styles.tooltipRow)}>
<dt {...stylex.props(styles.tooltipTerm)}>Queries</dt>
<dd {...stylex.props(shared.tabularNums)}>{bar.bucket.queries}</dd>
</div>
{SERIES.map((series) => (
<div key={series.key} {...stylex.props(styles.tooltipRow)}>
<dt {...stylex.props(styles.tooltipTerm)}>
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchSmall, styles.swatchColor(series.color))}
/>
{series.label}
</dt>
<dd {...stylex.props(shared.tabularNums)}>
{series.key === "other" ? bar.other : bar.bucket[series.key]}
</dd>
</div>
))}
</dl>
</div>
);
function tooltipOf(column: Column): TooltipContent {
return {
title: formatTime(column.ts),
rows: [
{ key: "queries", label: "Queries", value: String(column.queries) },
...SERIES.map((series) => ({
key: series.key,
label: series.label,
color: series.color,
value: String(column[series.key]),
})),
],
};
}
export default function TimeseriesChart({ data }: { data: StatsTimeseries }) {
const [containerRef, measuredWidth] = useContainerWidth();
const [hovered, setHovered] = useState<number | null>(null);
const width = measuredWidth > 0 ? measuredWidth : FALLBACK_WIDTH;
const [containerRef, width] = useMeasuredWidth();
// A hover survives a re-render only while it still names the same bucket at
// the same place: a poll that rolls the window, or a resize, retires it.
const hovered = useActiveIndex(`${data.since}:${data.bucket_seconds}:${data.buckets.length}:${width}`);
if (data.buckets.length === 0 || isEmptyTimeseries(data.buckets)) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
if (data.buckets.length === 0 || data.buckets.every((bucket) => bucket.queries === 0)) {
return <EmptyChart containerRef={containerRef} />;
}
const layout = layoutTimeseries(data.buckets, width, CHART_HEIGHT);
const baseline = layout.plot.y + layout.plot.height;
const hoveredBar = hovered !== null ? layout.bars[hovered] : undefined;
const columns = columnsOf(data.buckets);
const timestamps = columns.map((column) => column.ts);
const plot = plotArea(width);
const xScale = bandScale(timestamps, plot);
// The scale is the reported total rather than the stack's own sum: blocked
// and cached are parts of `queries`, which a clamped `other` can undercount.
const yScale = valueScale(Math.max(...columns.map((column) => column.queries)), [plot.bottom, plot.y]);
const yTicks = valueTicks(yScale);
return (
<div ref={containerRef} {...stylex.props(styles.chartRoot)}>
<ChartRoot containerRef={containerRef}>
<svg
role="img"
aria-label={`Queries over time, ${data.buckets.length} buckets: blocked, cached and other queries per bucket`}
aria-label={`Queries over time, ${data.buckets.length} buckets: ${SERIES.map((series) => series.label.toLowerCase()).join(", ")} queries per bucket`}
width="100%"
height={CHART_HEIGHT}
viewBox={`0 0 ${width} ${CHART_HEIGHT}`}
onMouseLeave={() => setHovered(null)}
onMouseLeave={hovered.clear}
>
{layout.yTicks.map((tick) => (
<g key={tick.value}>
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={tick.y}
y2={tick.y}
{...stylex.props(styles.gridLine)}
/>
<text
x={layout.plot.x - 6}
y={tick.y}
textAnchor="end"
dominantBaseline="middle"
{...stylex.props(styles.axisLabel, shared.tabularNums)}
>
{compact.format(tick.value)}
</text>
</g>
))}
<line
x1={layout.plot.x}
x2={layout.plot.x + layout.plot.width}
y1={baseline}
y2={baseline}
{...stylex.props(styles.axisLine)}
<ChartFrame
plot={plot}
yScale={yScale}
yTicks={yTicks}
xScale={xScale}
xTickValues={labelTickValues(timestamps, plot.width)}
bucketSeconds={data.bucket_seconds}
/>
{layout.xTicks.map((tick) => (
<text
key={tick.ts}
x={tick.x}
y={baseline + 14}
textAnchor="middle"
{...stylex.props(styles.axisLabel)}
>
{formatTick(tick.ts, data.bucket_seconds)}
</text>
))}
{layout.bars.map((bar, i) => (
<g key={bar.bucket.ts} opacity={hovered === null || hovered === i ? 1 : 0.55}>
{SERIES.map((series) => {
const rect = bar.segments[series.key];
if (rect.height <= 0) return null;
return (
<rect
key={series.key}
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
fill={series.color}
strokeWidth={rect.width > 3 ? 1 : 0}
{...stylex.props(styles.segment)}
/>
);
})}
</g>
))}
{layout.bars.map((bar, i) => (
<rect
key={bar.bucket.ts}
x={bar.slot.x}
y={bar.slot.y}
width={bar.slot.width}
height={bar.slot.height}
fill="transparent"
onMouseEnter={() => setHovered(i)}
>
<title>{barSummary(bar)}</title>
</rect>
))}
<BarStack<Column, SeriesKey>
data={columns}
keys={SERIES.map((series) => series.key)}
x={(column) => column.ts}
xScale={xScale}
yScale={yScale}
color={(key) => SERIES_COLOR[key]}
>
{(stacks) =>
columns.map((column, index) => (
<Group
key={column.ts}
opacity={hovered.index === null || hovered.index === index ? 1 : 0.55}
>
{stacks.map((stack) => {
const bar = stack.bars[index];
return (
<StackSegment
key={stack.key}
x={bar.x}
y={bar.y}
width={bar.width}
height={bar.height}
fill={bar.color}
/>
);
})}
</Group>
))
}
</BarStack>
<BucketOverlay plot={plot} values={timestamps} xScale={xScale} onEnter={hovered.show} />
</svg>
{hoveredBar !== undefined && <Tooltip bar={hoveredBar} chartWidth={width} />}
{hovered.index !== null && (
<ChartTooltip
index={hovered.index}
content={tooltipOf(columns[hovered.index])}
left={slotCenter(xScale, timestamps[hovered.index], plot)}
/>
)}
<ul {...stylex.props(styles.legend)}>
{SERIES.map((series) => (
<li key={series.key} {...stylex.props(styles.legendItem)}>
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchLarge, styles.swatchColor(series.color))}
/>
<span aria-hidden="true" {...stylex.props(styles.swatch, styles.swatchColor(series.color))} />
{series.label}
</li>
))}
@@ -299,24 +195,26 @@ export default function TimeseriesChart({ data }: { data: StatsTimeseries }) {
<tr>
<th scope="col">Time</th>
<th scope="col">Queries</th>
<th scope="col">Blocked</th>
<th scope="col">Cached</th>
<th scope="col">Other</th>
{SERIES.map((series) => (
<th key={series.key} scope="col">
{series.label}
</th>
))}
</tr>
</thead>
<tbody>
{layout.bars.map((bar) => (
<tr key={bar.bucket.ts}>
<th scope="row">{formatTime(bar.bucket.ts)}</th>
<td>{bar.bucket.queries}</td>
<td>{bar.bucket.blocked}</td>
<td>{bar.bucket.cached}</td>
<td>{bar.other}</td>
{columns.map((column) => (
<tr key={column.ts}>
<th scope="row">{formatTime(column.ts)}</th>
<td>{column.queries}</td>
{SERIES.map((series) => (
<td key={series.key}>{column[series.key]}</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
</ChartRoot>
);
}
@@ -0,0 +1,149 @@
import { render } from "@testing-library/react";
import {
CHART_HEIGHT,
ChartFrame,
bandPaddingInner,
bandScale,
labelTickValues,
plotArea,
useMeasuredWidth,
valueScale,
valueTicks,
} from "./chartKit";
describe("useMeasuredWidth", () => {
/**
* jsdom lays nothing out, so `clientWidth` is 0 there and a chart scaled to it
* would draw a zero-width plot. Every chart test depends on this fallback.
*/
test("an unmeasurable container falls back to 640", () => {
function Probe() {
const [ref, width] = useMeasuredWidth();
return <div ref={ref} data-testid="probe" data-width={width} />;
}
const { getByTestId } = render(<Probe />);
expect(getByTestId("probe").getAttribute("data-width")).toBe("640");
});
});
describe("valueScale", () => {
test("the data maximum is nicened outward and the ticks land on round numbers", () => {
const scale = valueScale(1780, [240, 0]);
expect(scale.domain()).toEqual([0, 1800]);
expect(scale.ticks(5)).toEqual([0, 500, 1000, 1500]);
expect(valueTicks(scale)).toEqual([0, 500, 1000, 1500]);
});
});
describe("bandPaddingInner", () => {
/**
* The gap is a constant number of pixels, so the fraction it takes of one slot
* has to fall as the slots get wider. 24 hourly columns in a 1388px plot is
* the 24h window on a full-width panel.
*/
test("the fraction is two pixels per column of the plot's width", () => {
expect(bandPaddingInner(24, 1388)).toBeCloseTo((2 * 24) / 1388, 12);
expect(bandPaddingInner(24, 1388)).toBeCloseTo(0.034582, 6);
});
/**
* Past the cap the gap would be most of the slot and the columns would vanish
* into slivers, so it stops at half the slot and the bars stay visible.
*/
test("the gap never takes more than half a slot", () => {
expect(bandPaddingInner(1000, 100)).toBe(0.5);
});
test("no columns and no width mean no gap to compute", () => {
expect(bandPaddingInner(0, 640)).toBe(0);
expect(bandPaddingInner(24, 0)).toBe(0);
});
});
describe("labelTickValues", () => {
/** A week of hourly buckets in a panel the width of a laptop window. */
test("labels thin out to one every 21 buckets at 748px of plot", () => {
const timestamps = Array.from({ length: 168 }, (_, i) => i * 3600);
expect(labelTickValues(timestamps, 748)).toEqual([0, 75600, 151200, 226800, 302400, 378000, 453600, 529200]);
});
test("every bucket is labelled when they all fit", () => {
expect(labelTickValues([0, 3600, 7200], 748)).toEqual([0, 3600, 7200]);
});
});
/** The frame on its own, at the width the charts draw at in jsdom. */
function renderFrame() {
const plot = plotArea(640);
const timestamps = [0, 3600, 7200];
const yScale = valueScale(100, [plot.bottom, plot.y]);
const yTicks = valueTicks(yScale);
const { container } = render(
<svg width={640} height={CHART_HEIGHT}>
<ChartFrame
plot={plot}
yScale={yScale}
yTicks={yTicks}
xScale={bandScale(timestamps, plot)}
xTickValues={timestamps}
bucketSeconds={3600}
/>
</svg>,
);
return { container, plot, yTicks };
}
describe("ChartFrame", () => {
test("the value axis is bare: no axis line, no tick marks, labels 6px left of the plot", () => {
const { container, plot, yTicks } = renderFrame();
const axis = container.querySelector(".visx-axis-left") as SVGGElement;
expect(axis.getAttribute("transform")).toBe(`translate(${plot.x}, 0)`);
expect(axis.querySelector("line")).toBeNull();
const labels = Array.from(axis.querySelectorAll("text"));
expect(labels.map((label) => label.textContent)).toEqual(yTicks.map(String));
for (const label of labels) {
expect(label.getAttribute("x")).toBe("0");
expect(label.getAttribute("dx")).toBe("-6px");
expect(label.getAttribute("text-anchor")).toBe("end");
// The label sits on the tick, centred: visx's own 0.25em nudge is
// cancelled so it does not double up with the middle baseline.
expect(label.getAttribute("dy")).toBe("0");
expect(label.getAttribute("dominant-baseline")).toBe("middle");
}
});
/**
* The time axis keeps its baseline and drops its tick marks, and the labels
* are placed by the group transform plus `dy` rather than by the font-size
* guess visx would otherwise make.
*/
test("the time axis keeps only its baseline, and its labels sit 16px below it", () => {
const { container, plot } = renderFrame();
const axis = container.querySelector(".visx-axis-bottom") as SVGGElement;
expect(axis.getAttribute("transform")).toBe(`translate(0, ${plot.bottom})`);
const lines = Array.from(axis.querySelectorAll("line"));
expect(lines).toHaveLength(1);
expect(lines[0].getAttribute("class")).toContain("visx-axis-line");
for (const label of Array.from(axis.querySelectorAll("text"))) {
expect(label.getAttribute("y")).toBe("0");
expect(label.getAttribute("dy")).toBe("16px");
expect(label.getAttribute("text-anchor")).toBe("middle");
}
});
test("every grid line has a labelled tick on it and no tick floats without a line", () => {
const { container } = renderFrame();
const gridY = Array.from(container.querySelectorAll(".visx-rows line")).map((line) => line.getAttribute("y1"));
const labelY = Array.from(container.querySelectorAll(".visx-axis-left text")).map((label) =>
label.getAttribute("y"),
);
expect(gridY.length).toBeGreaterThan(0);
expect(gridY).toEqual(labelY);
});
});
+498
View File
@@ -0,0 +1,498 @@
/**
* The plumbing the two bar charts on Overview share: the width measurement, the
* scales, the axis and grid chrome, the segment separator, the per-bucket hit
* target and the tooltip.
*
* Geometry is visx's; the chrome is ours. visx's own axis defaults draw tick
* marks, an axis line on both axes and Arial 10px in #222, none of which this
* app wants, so every wrapper here turns those off and dresses the result in
* StyleX tokens instead.
*/
import { useEffect, useRef, useState } from "react";
import * as stylex from "@stylexjs/stylex";
import { AxisBottom, AxisLeft, type TickRendererProps } from "@visx/axis";
import { GridRows } from "@visx/grid";
import { scaleBand, scaleLinear } from "@visx/scale";
import { TooltipWithBounds } from "@visx/tooltip";
import { styles as shared } from "@/ui/styles";
import { colors } from "@/ui/tokens.stylex";
export const CHART_HEIGHT = 240;
export const MARGIN = { top: 8, right: 8, bottom: 22, left: 44 } as const;
/** The width a chart draws at before a measurement exists — jsdom, and the first paint. */
const FALLBACK_WIDTH = 640;
/** How many pixels one x-axis label needs to itself before the labels thin out. */
const MIN_X_LABEL_PX = 90;
/** The gap between two touching columns, in pixels of the drawn plot. */
const BAR_GAP_PX = 2;
const Y_TICK_COUNT = 5;
export interface Plot {
x: number;
y: number;
width: number;
height: number;
/** The y of the baseline: the bottom edge of the plot. */
bottom: number;
}
export function plotArea(width: number): Plot {
const height = Math.max(0, CHART_HEIGHT - MARGIN.top - MARGIN.bottom);
return {
x: MARGIN.left,
y: MARGIN.top,
width: Math.max(0, width - MARGIN.left - MARGIN.right),
height,
bottom: MARGIN.top + height,
};
}
/**
* The container's width, measured on mount and on every resize. Deliberately
* `useEffect` rather than `useLayoutEffect`: the first paint draws at the
* fallback width and the measured width lands a frame later, which is the
* timing the charts have always had.
*/
export function useMeasuredWidth(): [React.RefObject<HTMLDivElement | null>, number] {
const ref = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const el = ref.current;
if (el === null) return;
setWidth(el.clientWidth);
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(() => setWidth(el.clientWidth));
observer.observe(el);
return () => observer.disconnect();
}, []);
return [ref, width > 0 ? width : FALLBACK_WIDTH];
}
/**
* The value axis. `nice: true` rounds the domain outward, so the `max` passed
* here is the data's own maximum and not a pre-rounded one.
*/
export function valueScale(max: number, range: [number, number]) {
return scaleLinear<number>({ domain: [0, max], range, nice: true });
}
export type ValueScale = ReturnType<typeof valueScale>;
/** The tick values the grid and the value axis both draw. */
export function valueTicks(scale: ValueScale): number[] {
return scale.ticks(Y_TICK_COUNT);
}
/**
* How wide the gap between two columns is, as a fraction of one column's slot.
* A constant would make the gap grow with the column: 30 daily columns and 60
* minute columns are drawn at the same pixel gap, so the fraction has to be
* computed from how many columns share the plot.
*/
export function bandPaddingInner(bucketCount: number, plotWidth: number): number {
if (bucketCount === 0 || plotWidth <= 0) return 0;
return Math.min(0.5, (BAR_GAP_PX * bucketCount) / plotWidth);
}
/** The time axis: one band per bucket, in the order the buckets were given. */
export function bandScale(values: number[], plot: Plot) {
return scaleBand<number>({
domain: values,
range: [plot.x, plot.x + plot.width],
paddingInner: bandPaddingInner(values.length, plot.width),
});
}
export type BandScale = ReturnType<typeof bandScale>;
/**
* The subset of bucket timestamps that get an x-axis label. A 30-day window is
* 30 columns and a 1-hour window is 60, so at narrow widths the labels have to
* thin out rather than overprint each other.
*/
export function labelTickValues(values: number[], plotWidth: number): number[] {
if (values.length === 0 || plotWidth <= 0) return values.slice(0, 1);
const step = Math.max(1, Math.ceil((values.length * MIN_X_LABEL_PX) / plotWidth));
return values.filter((_, i) => i % step === 0);
}
const compact = new Intl.NumberFormat(undefined, { notation: "compact" });
export function formatBucketTime(ts: number, bucketSeconds: number): string {
const date = new Date(ts * 1000);
if (bucketSeconds >= 86_400) {
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
}
const styles = stylex.create({
empty: {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: CHART_HEIGHT,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "dashed",
borderColor: colors.borderStrong,
fontSize: "0.875rem",
lineHeight: "1.25rem",
color: colors.textMuted,
},
root: {
position: "relative",
},
axisLabel: {
fill: colors.textMuted,
fontSize: "10px",
},
/** The hairline separating touching segments is the page ground, not a colour. */
segment: {
stroke: colors.surface,
},
tooltip: {
pointerEvents: "none",
position: "absolute",
zIndex: 10,
borderRadius: "0.25rem",
borderWidth: 1,
borderStyle: "solid",
borderColor: colors.borderStrong,
backgroundColor: colors.surfaceRaised,
paddingInline: "0.75rem",
paddingBlock: "0.5rem",
fontSize: "0.75rem",
lineHeight: "1rem",
boxShadow: "0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",
},
tooltipTitle: {
fontWeight: 500,
},
tooltipList: {
display: "flex",
flexDirection: "column",
gap: "0.125rem",
marginTop: "0.25rem",
},
tooltipRow: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "1rem",
},
tooltipTerm: {
display: "flex",
alignItems: "center",
gap: "0.375rem",
color: colors.textMuted,
},
swatch: {
display: "inline-block",
width: "0.5rem",
height: "0.5rem",
borderRadius: "0.125rem",
},
/** Dynamic: the swatch takes the series colour the SVG bars are drawn in. */
swatchColor: (color: string) => ({ backgroundColor: color }),
});
/** Both charts' "nothing here" state, which is also where the ref to measure lives. */
export function EmptyChart({ containerRef }: { containerRef: React.RefObject<HTMLDivElement | null> }) {
return (
<div ref={containerRef} {...stylex.props(styles.empty)}>
No queries in this period.
</div>
);
}
export function ChartRoot({
containerRef,
children,
}: {
containerRef: React.RefObject<HTMLDivElement | null>;
children: React.ReactNode;
}) {
return (
<div ref={containerRef} {...stylex.props(styles.root)}>
{children}
</div>
);
}
/**
* visx's `Ticks` derives a label's `y` from a guessed font size, which is wrong
* here because the size comes from a stylesheet it cannot read. The label is
* therefore placed by the axis group's own transform plus the `dy` the caller
* passes, and the guessed `y` is dropped.
*/
function TickLabel({ x, dx, dy, textAnchor, dominantBaseline, formattedValue }: TickRendererProps) {
return (
<text
x={x}
y={0}
dx={dx}
dy={dy}
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
{...stylex.props(styles.axisLabel)}
>
{formattedValue}
</text>
);
}
/** As `TickLabel`, but keeping the scaled tick position the vertical axis puts in `y`. */
function ValueTickLabel({ x, y, dx, dy, textAnchor, dominantBaseline, formattedValue }: TickRendererProps) {
return (
<text
x={x}
y={y}
dx={dx}
dy={dy}
textAnchor={textAnchor}
dominantBaseline={dominantBaseline}
{...stylex.props(styles.axisLabel, shared.tabularNums)}
>
{formattedValue}
</text>
);
}
/**
* The grid and the two axes. The grid lines and the value labels are computed
* from one tick array, so every drawn line has a number beside it and no number
* floats without one.
*/
export function ChartFrame({
plot,
yScale,
yTicks,
xScale,
xTickValues,
bucketSeconds,
}: {
plot: Plot;
yScale: ValueScale;
yTicks: number[];
xScale: BandScale;
xTickValues: number[];
bucketSeconds: number;
}) {
return (
<>
<GridRows scale={yScale} tickValues={yTicks} left={plot.x} width={plot.width} stroke={colors.border} />
<AxisLeft
scale={yScale}
left={plot.x}
tickValues={yTicks}
numTicks={Y_TICK_COUNT}
hideAxisLine
hideTicks
tickLength={0}
tickFormat={(value) => compact.format(Number(value))}
// `dy` overrides AxisLeft's own 0.25em nudge, which would double up
// with the middle baseline this app centres its value labels on.
tickLabelProps={{ dx: "-6px", dy: 0, textAnchor: "end", dominantBaseline: "middle" }}
tickComponent={ValueTickLabel}
/>
<AxisBottom
scale={xScale}
top={plot.bottom}
tickValues={xTickValues}
hideTicks
tickLength={0}
stroke={colors.borderStrong}
tickFormat={(value) => formatBucketTime(Number(value), bucketSeconds)}
tickLabelProps={{ dy: "16px", textAnchor: "middle" }}
tickComponent={TickLabel}
/>
</>
);
}
/**
* One segment of a stacked column. The separator is drawn only once the column
* is wide enough for two neighbouring segments to read as two shapes; below
* that it would be most of the bar.
*/
export function StackSegment({
x,
y,
width,
height,
fill,
}: {
x: number;
y: number;
width: number;
height: number;
fill: string;
}) {
if (height <= 0) return null;
return (
<rect
x={x}
y={y}
width={width}
height={height}
fill={fill}
strokeWidth={width > 3 ? 1 : 0}
{...stylex.props(styles.segment)}
/>
);
}
/**
* The transparent hit targets: one per bucket, spanning the whole plot height so
* that pointing at the empty space above a short column still selects it.
*
* A slot is a whole band step, gap included, so that no pixel between two
* columns belongs to neither. The last slot is clipped to the plot's right edge:
* the band scale spends the trailing gap on nothing, and a full-step rect there
* would reach into the right margin.
*/
export function BucketOverlay({
plot,
values,
xScale,
onEnter,
}: {
plot: Plot;
values: number[];
xScale: BandScale;
onEnter: (index: number) => void;
}) {
const step = xScale.step();
const right = plot.x + plot.width;
return (
<>
{values.map((value, index) => {
const x = xScale(value) ?? plot.x;
return (
<rect
key={value}
x={x}
y={plot.y}
width={Math.max(0, Math.min(step, right - x))}
height={plot.height}
fill="transparent"
onMouseEnter={() => onEnter(index)}
/>
);
})}
</>
);
}
/** The x a bucket's tooltip points at: the centre of its slot, not of its narrower bar. */
export function slotCenter(xScale: BandScale, value: number, plot: Plot): number {
return (xScale(value) ?? plot.x) + xScale.step() / 2;
}
/**
* Which item the pointer is on, and nothing else — a bucket in the bar charts, a
* slice in the donuts.
*
* Deliberately not `useTooltip`: holding the hovered item's numbers and screen
* position in state decouples them from the data. The window refreshes every
* half minute and the container can be resized under an open tooltip, and either
* one leaves a stored copy describing an item that has moved or changed. Only
* the index is kept, so the caller reads the values and the coordinates out of
* the render it is currently drawing.
*
* `windowKey` is what makes a changing set safe: when the items themselves
* change, index `i` no longer names the one the pointer was over, so the
* selection made against the old key is dropped and the tooltip goes away.
*/
export function useActiveIndex(windowKey: string) {
const [selection, setSelection] = useState<{ index: number; key: string } | null>(null);
// A selection belongs to the window it was made in. Deleting it as soon as the
// key moves on is what stops a returning key — a resize back to a previous
// width, a poll that restores a bucket count — from reviving a hover the
// pointer never made.
if (selection !== null && selection.key !== windowKey) setSelection(null);
return {
index: selection !== null && selection.key === windowKey ? selection.index : null,
show: (index: number) => setSelection({ index, key: windowKey }),
clear: () => setSelection(null),
};
}
export interface TooltipRow {
key: string;
label: string;
/** Omitted for a row that names no drawn shape, such as a bucket's total. */
color?: string;
value: string;
}
/** What a tooltip says, whichever chart opened it: a heading and its rows. */
export interface TooltipContent {
title: string;
rows: TooltipRow[];
}
/**
* `TooltipWithBounds` positions itself with an inline transform and drops it
* when `unstyled` is set, so the default look is replaced by handing it an empty
* style object rather than by turning styling off.
*/
const NO_INLINE_STYLE = {};
/** The gap the tooltip keeps from its anchor point. */
const TOOLTIP_OFFSET = 8;
export function ChartTooltip({
content,
index,
left,
top = 0,
}: {
content: TooltipContent;
/** Which item the tooltip names; part of what forces a fresh measurement. */
index: number;
left: number;
top?: number;
}) {
// `withBoundingRects` measures once, in `componentDidMount`, and never again,
// so every content change needs its own mount to be measured at its own size.
// The index alone is not enough: a refresh can widen the same item's text past
// a digit boundary, or resolve a client's name, and the stale width would place
// it wrongly at the right edge.
const measureKey = [index, content.title, ...content.rows.map((row) => `${row.label}=${row.value}`)].join("|");
return (
<TooltipWithBounds
key={measureKey}
left={left}
top={top}
offsetLeft={TOOLTIP_OFFSET}
offsetTop={TOOLTIP_OFFSET}
style={NO_INLINE_STYLE}
className={stylex.props(styles.tooltip).className}
>
<div {...stylex.props(styles.tooltipTitle)}>{content.title}</div>
<dl {...stylex.props(styles.tooltipList)}>
{content.rows.map((row) => (
<div key={row.key} {...stylex.props(styles.tooltipRow)}>
<dt {...stylex.props(styles.tooltipTerm)}>
{row.color !== undefined && (
<span
aria-hidden="true"
{...stylex.props(styles.swatch, styles.swatchColor(row.color))}
/>
)}
{row.label}
</dt>
<dd {...stylex.props(shared.tabularNums)}>{row.value}</dd>
</div>
))}
</dl>
</TooltipWithBounds>
);
}
@@ -1,93 +0,0 @@
import type { Bucket } from "@/lib/types";
import { MARGIN, isEmptyTimeseries, layoutTimeseries, niceTicks } from "./chartLayout";
function bucket(ts: number, queries: number, blocked = 0, cached = 0): Bucket {
return { ts, queries, blocked, cached };
}
describe("niceTicks", () => {
test("zero max yields a single zero tick", () => {
expect(niceTicks(0)).toEqual([0]);
});
test("picks a 1/2/5 step and extends past max", () => {
expect(niceTicks(7)).toEqual([0, 2, 4, 6, 8]);
expect(niceTicks(100)).toEqual([0, 50, 100]);
expect(niceTicks(1234)).toEqual([0, 500, 1000, 1500]);
});
});
describe("isEmptyTimeseries", () => {
test("true for no buckets and for all-zero buckets", () => {
expect(isEmptyTimeseries([])).toBe(true);
expect(isEmptyTimeseries([bucket(0, 0), bucket(60, 0)])).toBe(true);
});
test("false when any bucket has queries", () => {
expect(isEmptyTimeseries([bucket(0, 0), bucket(60, 3)])).toBe(false);
});
});
describe("layoutTimeseries", () => {
test("segment heights are proportional and stack to the queries total", () => {
const layout = layoutTimeseries([bucket(0, 100, 40, 10), bucket(60, 50, 0, 0)], 480, 240);
const plotHeight = 240 - MARGIN.top - MARGIN.bottom;
const baseline = MARGIN.top + plotHeight;
const [first, second] = layout.bars;
expect(layout.scaleMax).toBe(100);
expect(first.other).toBe(50);
expect(first.segments.blocked.height).toBeCloseTo(plotHeight * 0.4);
expect(first.segments.cached.height).toBeCloseTo(plotHeight * 0.1);
expect(first.segments.other.height).toBeCloseTo(plotHeight * 0.5);
expect(first.segments.blocked.y + first.segments.blocked.height).toBeCloseTo(baseline);
expect(first.segments.cached.y + first.segments.cached.height).toBeCloseTo(first.segments.blocked.y);
expect(first.segments.other.y + first.segments.other.height).toBeCloseTo(first.segments.cached.y);
expect(first.segments.other.y).toBeCloseTo(MARGIN.top);
expect(second.segments.other.height).toBeCloseTo(plotHeight * 0.5);
});
test("clamps other at zero when blocked + cached exceed queries", () => {
const layout = layoutTimeseries([bucket(0, 10, 8, 5)], 480, 240);
expect(layout.bars[0].other).toBe(0);
expect(layout.bars[0].segments.other.height).toBe(0);
});
test("zero data still lays out zero-height bars on a unit scale", () => {
const layout = layoutTimeseries([bucket(0, 0), bucket(60, 0)], 480, 240);
expect(layout.scaleMax).toBe(1);
expect(layout.bars).toHaveLength(2);
for (const bar of layout.bars) {
expect(bar.segments.blocked.height).toBe(0);
expect(bar.segments.cached.height).toBe(0);
expect(bar.segments.other.height).toBe(0);
}
expect(layout.yTicks).toEqual([{ value: 0, y: MARGIN.top + (240 - MARGIN.top - MARGIN.bottom) }]);
});
test("single bucket fills the plot width minus the gap", () => {
const layout = layoutTimeseries([bucket(0, 5, 1, 1)], 480, 240);
const plotWidth = 480 - MARGIN.left - MARGIN.right;
const bar = layout.bars[0];
expect(bar.slot.width).toBeCloseTo(plotWidth);
expect(bar.segments.blocked.width).toBeCloseTo(plotWidth - 2);
expect(bar.segments.blocked.x).toBeCloseTo(MARGIN.left + 1);
expect(layout.xTicks).toEqual([{ ts: 0, x: MARGIN.left + plotWidth / 2 }]);
});
test("x ticks thin out when buckets outnumber the label budget", () => {
const buckets = Array.from({ length: 168 }, (_, i) => bucket(i * 3600, i));
const layout = layoutTimeseries(buckets, 800, 240);
expect(layout.xTicks.length).toBeLessThan(buckets.length / 10);
expect(layout.xTicks[0].ts).toBe(0);
const xs = layout.xTicks.map((tick) => tick.x);
expect([...xs].sort((a, b) => a - b)).toEqual(xs);
});
test("empty bucket list yields no bars and no x ticks", () => {
const layout = layoutTimeseries([], 480, 240);
expect(layout.bars).toEqual([]);
expect(layout.xTicks).toEqual([]);
expect(layout.scaleMax).toBe(1);
});
});
-182
View File
@@ -1,182 +0,0 @@
import type { Bucket } from "@/lib/types";
export interface Rect {
x: number;
y: number;
width: number;
height: number;
}
export interface BarLayout {
bucket: Bucket;
/** queries - blocked - cached, clamped at 0. */
other: number;
slot: Rect;
segments: {
blocked: Rect;
cached: Rect;
other: Rect;
};
}
export interface ChartLayout {
width: number;
height: number;
plot: Rect;
scaleMax: number;
bars: BarLayout[];
yTicks: { value: number; y: number }[];
xTicks: { ts: number; x: number }[];
}
export const MARGIN = { top: 8, right: 8, bottom: 22, left: 44 } as const;
const BAR_GAP = 2;
const MIN_X_LABEL_PX = 90;
/** Tick values from 0 upward in a 1/2/5 step, extended until the last tick covers `max`. */
export function niceTicks(max: number, targetCount = 4): number[] {
if (max <= 0) return [0];
const rawStep = max / targetCount;
const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)));
const normalized = rawStep / magnitude;
const step = (normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10) * magnitude;
const ticks: number[] = [];
for (let value = 0; ; value += step) {
ticks.push(value);
if (value >= max) break;
}
return ticks;
}
export function isEmptyTimeseries(buckets: Bucket[]): boolean {
return buckets.every((bucket) => bucket.queries === 0);
}
function plotRect(width: number, height: number): Rect {
return {
x: MARGIN.left,
y: MARGIN.top,
width: Math.max(0, width - MARGIN.left - MARGIN.right),
height: Math.max(0, height - MARGIN.top - MARGIN.bottom),
};
}
/**
* How many columns share one x-axis label. A 30-day window is 30 columns and a
* 1-hour window is 60, so at narrow widths the labels have to thin out rather
* than overprint each other.
*/
function labelStepFor(count: number, plotWidth: number): number {
if (count === 0 || plotWidth <= 0) return 1;
return Math.max(1, Math.ceil((count * MIN_X_LABEL_PX) / plotWidth));
}
/** One stacked column: the series values in the order the caller stacks them. */
export interface StackedColumn {
ts: number;
total: number;
slot: Rect;
segments: Rect[];
}
export interface StackedLayout {
width: number;
height: number;
plot: Rect;
scaleMax: number;
columns: StackedColumn[];
yTicks: { value: number; y: number }[];
xTicks: { ts: number; x: number }[];
}
/**
* The same geometry as the query-volume chart, for an arbitrary number of
* series. The scale comes from the tallest column's own total, because every
* series here is a disjoint part of the whole rather than a highlighted subset
* of a separately reported total.
*/
export function layoutStacked(
columns: { ts: number; values: number[] }[],
width: number,
height: number,
): StackedLayout {
const plot = plotRect(width, height);
const totals = columns.map((column) => column.values.reduce((sum, value) => sum + value, 0));
const tickValues = niceTicks(Math.max(0, ...totals));
const scaleMax = Math.max(tickValues[tickValues.length - 1], 1);
const baseline = plot.y + plot.height;
const toHeight = (value: number) => (value / scaleMax) * plot.height;
const slotWidth = columns.length > 0 ? plot.width / columns.length : 0;
const barWidth = Math.max(1, slotWidth - BAR_GAP);
const laidOut: StackedColumn[] = columns.map((column, i) => {
const slotX = plot.x + i * slotWidth;
const barX = slotX + (slotWidth - barWidth) / 2;
let top = baseline;
const segments = column.values.map((value) => {
const segmentHeight = toHeight(value);
top -= segmentHeight;
return { x: barX, y: top, width: barWidth, height: segmentHeight };
});
return {
ts: column.ts,
total: totals[i],
slot: { x: slotX, y: plot.y, width: slotWidth, height: plot.height },
segments,
};
});
const step = labelStepFor(columns.length, plot.width);
return {
width,
height,
plot,
scaleMax,
columns: laidOut,
yTicks: tickValues.map((value) => ({ value, y: baseline - toHeight(value) })),
xTicks: laidOut
.filter((_, i) => i % step === 0)
.map((column) => ({ ts: column.ts, x: column.slot.x + column.slot.width / 2 })),
};
}
export function layoutTimeseries(buckets: Bucket[], width: number, height: number): ChartLayout {
const plot = plotRect(width, height);
const maxQueries = buckets.reduce((max, bucket) => Math.max(max, bucket.queries), 0);
const tickValues = niceTicks(maxQueries);
const scaleMax = Math.max(tickValues[tickValues.length - 1], 1);
const baseline = plot.y + plot.height;
const toHeight = (value: number) => (value / scaleMax) * plot.height;
const slotWidth = buckets.length > 0 ? plot.width / buckets.length : 0;
const barWidth = Math.max(1, slotWidth - BAR_GAP);
const bars: BarLayout[] = buckets.map((bucket, i) => {
const slotX = plot.x + i * slotWidth;
const barX = slotX + (slotWidth - barWidth) / 2;
const other = Math.max(0, bucket.queries - bucket.blocked - bucket.cached);
const blockedH = toHeight(bucket.blocked);
const cachedH = toHeight(bucket.cached);
const otherH = toHeight(other);
return {
bucket,
other,
slot: { x: slotX, y: plot.y, width: slotWidth, height: plot.height },
segments: {
blocked: { x: barX, y: baseline - blockedH, width: barWidth, height: blockedH },
cached: { x: barX, y: baseline - blockedH - cachedH, width: barWidth, height: cachedH },
other: { x: barX, y: baseline - blockedH - cachedH - otherH, width: barWidth, height: otherH },
},
};
});
const yTicks = tickValues.map((value) => ({ value, y: baseline - toHeight(value) }));
const labelStep = labelStepFor(buckets.length, plot.width);
const xTicks = bars
.filter((_, i) => i % labelStep === 0)
.map((bar) => ({ ts: bar.bucket.ts, x: bar.slot.x + bar.slot.width / 2 }));
return { width, height, plot, scaleMax, bars, yTicks, xTicks };
}
@@ -1,47 +0,0 @@
import { layoutDonut, type DonutSlice } from "./donutLayout";
function slice(key: string, value: number): DonutSlice {
return { key, label: key, value, color: "#000000" };
}
test("an empty breakdown has no total and no arcs to draw", () => {
expect(layoutDonut([], 100, 20)).toEqual({ size: 100, total: 0, arcs: [] });
});
test("a breakdown of nothing but zeroes is empty, not a division by zero", () => {
const layout = layoutDonut([slice("a", 0), slice("b", 0)], 100, 20);
expect(layout.total).toBe(0);
expect(layout.arcs).toEqual([]);
});
test("zero-valued entries are dropped rather than legended at 0%", () => {
const layout = layoutDonut([slice("a", 3), slice("b", 0), slice("c", 1)], 100, 20);
expect(layout.arcs.map((arc) => arc.slice.key)).toEqual(["a", "c"]);
expect(layout.total).toBe(4);
});
test("shares are of the drawn total and add up to one", () => {
const layout = layoutDonut([slice("a", 3), slice("b", 1)], 100, 20);
expect(layout.arcs.map((arc) => arc.share)).toEqual([0.75, 0.25]);
});
test("slices keep the order they were ranked in, starting at twelve o'clock", () => {
const layout = layoutDonut([slice("a", 1), slice("b", 1)], 100, 20);
expect(layout.arcs[0].d.startsWith("M 50.000 0.000")).toBe(true);
// The second slice begins where the first ended, half a turn round.
expect(layout.arcs[1].d.startsWith("M 50.000 100.000")).toBe(true);
});
test("a slice over half the ring takes the large-arc flag", () => {
const layout = layoutDonut([slice("a", 9), slice("b", 1)], 100, 20);
expect(layout.arcs[0].d).toContain("A 50 50 0 1 1");
expect(layout.arcs[1].d).toContain("A 50 50 0 0 1");
});
test("a single entry is a closed ring, not a zero-length arc that draws nothing", () => {
const layout = layoutDonut([slice("only", 7)], 100, 20);
expect(layout.arcs).toHaveLength(1);
expect(layout.arcs[0].share).toBe(1);
// Two half arcs out and two back: a lone `A` from a point to itself is a no-op.
expect(layout.arcs[0].d.match(/A /g)).toHaveLength(4);
});
@@ -1,95 +0,0 @@
/**
* Annulus geometry for the two breakdown donuts. Pure, so the arithmetic that
* decides whether a slice closes correctly is testable without a DOM.
*/
export interface DonutSlice {
/** Semantic identity: the React key, the colour key and the legend's identity. */
key: string;
label: string;
/** Disambiguates entries whose labels collide — two "Unknown"s, one name on two route kinds. */
secondary?: string;
value: number;
color: string;
}
export interface DonutArc {
slice: DonutSlice;
/** Of the whole, 0 to 1. */
share: number;
d: string;
}
export interface DonutLayout {
size: number;
total: number;
arcs: DonutArc[];
}
const START_ANGLE = -Math.PI / 2;
function point(center: number, radius: number, angle: number): string {
return `${(center + radius * Math.cos(angle)).toFixed(3)} ${(center + radius * Math.sin(angle)).toFixed(3)}`;
}
/**
* A whole-circle slice cannot be drawn as one arc — start and end coincide, and
* the renderer draws nothing at all — so the ring is two half arcs.
*/
function fullRing(center: number, outer: number, inner: number): string {
const top = `${center} ${center - outer}`;
const bottom = `${center} ${center + outer}`;
const innerTop = `${center} ${center - inner}`;
const innerBottom = `${center} ${center + inner}`;
return [
`M ${top}`,
`A ${outer} ${outer} 0 0 1 ${bottom}`,
`A ${outer} ${outer} 0 0 1 ${top}`,
`M ${innerTop}`,
`A ${inner} ${inner} 0 0 0 ${innerBottom}`,
`A ${inner} ${inner} 0 0 0 ${innerTop}`,
"Z",
].join(" ");
}
/**
* Slices in the order given — the caller has already ranked them — starting at
* twelve o'clock and running clockwise. Zero-valued slices are dropped: they
* have no arc to draw, and a legend entry reading 0 is noise.
*/
export function layoutDonut(slices: DonutSlice[], size: number, thickness: number): DonutLayout {
const drawn = slices.filter((slice) => slice.value > 0);
const total = drawn.reduce((sum, slice) => sum + slice.value, 0);
if (total <= 0) return { size, total: 0, arcs: [] };
const center = size / 2;
const outer = center;
const inner = Math.max(0, center - thickness);
if (drawn.length === 1) {
return {
size,
total,
arcs: [{ slice: drawn[0], share: 1, d: fullRing(center, outer, inner) }],
};
}
let angle = START_ANGLE;
const arcs = drawn.map((slice) => {
const share = slice.value / total;
const sweep = share * Math.PI * 2;
const end = angle + sweep;
const large = sweep > Math.PI ? 1 : 0;
const d = [
`M ${point(center, outer, angle)}`,
`A ${outer} ${outer} 0 ${large} 1 ${point(center, outer, end)}`,
`L ${point(center, inner, end)}`,
`A ${inner} ${inner} 0 ${large} 0 ${point(center, inner, angle)}`,
"Z",
].join(" ");
angle = end;
return { slice, share, d };
});
return { size, total, arcs };
}
+1 -1
View File
@@ -1,6 +1,6 @@
.{
.name = .nxdns,
.version = "0.0.9",
.version = "0.0.11",
.minimum_zig_version = "0.16.0",
.paths = .{""},
.fingerprint = 0x3307b311dded1d91,
+21
View File
@@ -0,0 +1,21 @@
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018 Jed Watson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+25
View File
@@ -0,0 +1,25 @@
The nine ISC-licensed d3 modules the admin UI bundles carry the same permission
notice under different copyright years. The notices are reproduced together
here, one line per package, followed by the ISC text they share.
d3-array Copyright 2010-2022 Mike Bostock
d3-color Copyright 2010-2022 Mike Bostock
d3-format Copyright 2010-2021 Mike Bostock
d3-interpolate Copyright 2010-2021 Mike Bostock
d3-path Copyright 2015-2022 Mike Bostock
d3-scale Copyright 2010-2021 Mike Bostock
d3-shape Copyright 2010-2022 Mike Bostock
d3-time Copyright 2010-2022 Mike Bostock
internmap Copyright 2021 Mike Bostock
Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
+70
View File
@@ -52,20 +52,67 @@ sqlite url=https://sqlite.org/2026/sqlite-amalgamation-3530400.zip hash=N-V-__8A
@tanstack/react-store 0.9.3 MIT
@tanstack/router-core 1.171.15 MIT
@tanstack/store 0.9.3 MIT
@types/d3-array 3.0.3 MIT
@types/d3-color 3.1.0 MIT
@types/d3-delaunay 6.0.1 MIT
@types/d3-format 3.0.1 MIT
@types/d3-geo 3.1.0 MIT
@types/d3-interpolate 3.0.1 MIT
@types/d3-path 3.1.1 MIT
@types/d3-scale 4.0.2 MIT
@types/d3-shape 3.1.7 MIT
@types/d3-time 3.0.0 MIT
@types/d3-time-format 2.1.0 MIT
@types/geojson 7946.0.16 MIT
@types/react 19.2.17 MIT
@types/react-dom 19.2.3 MIT
@visx/axis 4.0.0 MIT
@visx/bounds 4.0.0 MIT
@visx/curve 4.0.0 MIT
@visx/grid 4.0.0 MIT
@visx/group 4.0.0 MIT
@visx/point 4.0.0 MIT
@visx/scale 4.0.0 MIT
@visx/shape 4.0.0 MIT
@visx/text 4.0.0 MIT
@visx/tooltip 4.0.0 MIT
@visx/vendor 4.0.0 MIT and ISC
aria-hidden 1.2.6 MIT
balanced-match 0.4.2 MIT
classnames 2.5.1 MIT
client-only 0.0.1 MIT
clsx 2.1.1 MIT
cookie-es 3.1.1 MIT
css-mediaquery 0.1.2 BSD
csstype 3.2.3 MIT
d3-array 3.2.1 ISC
d3-color 3.1.0 ISC
d3-delaunay 6.0.2 ISC
d3-format 3.1.0 ISC
d3-geo 3.1.0 ISC
d3-interpolate 3.0.1 ISC
d3-path 3.1.0 ISC
d3-scale 4.0.2 ISC
d3-shape 3.2.0 ISC
d3-time 3.1.0 ISC
d3-time-format 4.1.0 ISC
delaunator 5.1.0 ISC
internmap 2.0.3 ISC
invariant 2.2.4 MIT
isbot 5.2.1 Unlicense
js-tokens 4.0.0 MIT
loose-envify 1.4.0 MIT
math-expression-evaluator 1.4.0 MIT
react 19.2.8 MIT
react-aria 3.51.0 Apache-2.0
react-aria-components 1.20.0 Apache-2.0
react-dom 19.2.8 MIT
react-stately 3.49.0 Apache-2.0
react-use-measure 2.1.7 MIT
reduce-css-calc 1.3.0 MIT
reduce-function-call 1.0.3 MIT
balanced-match 1.0.2 MIT
robust-predicates 3.0.3 Unlicense
scheduler 0.27.0 MIT
seroval 1.5.6 MIT
seroval-plugins 1.5.6 MIT
@@ -90,11 +137,34 @@ alpine:3.22@sha256:14358309a308569c32bdc37e2e0e9694be33a9d99e68afb0f5ff33cc1f695
@tanstack/react-store
@tanstack/router-core
@tanstack/store
@visx/axis
@visx/bounds
@visx/grid
@visx/group
@visx/point
@visx/scale
@visx/shape
@visx/text
@visx/tooltip
balanced-match
classnames
clsx
d3-array
d3-color
d3-format
d3-interpolate
d3-path
d3-scale
d3-shape
d3-time
internmap
math-expression-evaluator
react
react-aria
react-aria-components
react-dom
react-stately
reduce-css-calc
reduce-function-call
scheduler
use-sync-external-store
+61
View File
@@ -71,6 +71,25 @@
// a `sources` list — no guard would raise it, which is why it is written down
// here.
//
// Twenty-three more joined the not-shipped list with visx, and the sourcemap
// build settled which. Fourteen are types only and emit no runtime code at all:
// @types/d3-array, @types/d3-color, @types/d3-delaunay, @types/d3-format,
// @types/d3-geo, @types/d3-interpolate, @types/d3-path, @types/d3-scale,
// @types/d3-shape, @types/d3-time, @types/d3-time-format, @types/geojson,
// @types/react and @types/react-dom, with csstype under them. They are in the
// runtime closure rather than among the devDependencies only because the @visx
// packages declare them as ordinary dependencies. @visx/curve is the curve
// factory the line and area shapes take, which these charts do not draw.
// @visx/vendor is the one worth stating plainly: it is a re-export shim over the
// d3 modules, npm records it as `MIT and ISC` because of what it re-exports, and
// the bundler resolves straight through it to the d3 packages themselves — so
// its own bytes never reach admin/dist and the d3 entry below is what covers the
// code that does. d3-delaunay, d3-geo, d3-time-format, delaunator and
// robust-predicates are the map and Voronoi half of that shim, which no chart
// here imports; the first four are ISC and robust-predicates is Unlicense.
// react-use-measure is the resize hook @visx/responsive uses, and this app keeps
// its own, so nothing pulls it in.
//
// Of the remaining devDependencies, none puts a byte in admin/dist: @vitejs/
// plugin-react and typescript only transform our own sources (react-refresh is
// dev-server only, and tslib is optional and unused), lightningcss only
@@ -155,6 +174,48 @@
.note = "Bundled into the admin UI JavaScript. Separate entry from the other TanStack packages: same MIT text, different copyright line.",
.file = "tanstack-store-mit.txt",
},
.{
.component = "visx (@visx/axis, @visx/bounds, @visx/grid, @visx/group, @visx/point, @visx/scale, @visx/shape, @visx/text, @visx/tooltip)",
.version = "@visx/axis 4.0.0, @visx/bounds 4.0.0, @visx/grid 4.0.0, @visx/group 4.0.0, @visx/point 4.0.0, @visx/scale 4.0.0, @visx/shape 4.0.0, @visx/text 4.0.0, @visx/tooltip 4.0.0",
.note = "The chart primitives the Overview charts are drawn with — scales, stacked bars, pie arcs, axes, grid and tooltip — bundled into the admin UI JavaScript. Nine of the eleven @visx packages in the closure ship; @visx/curve and @visx/vendor do not (see the note at the head of this file). All nine carry a byte-identical MIT text. In the tarballs and in the image.",
.file = "visx-mit.txt",
},
.{
.component = "d3 (d3-array, d3-color, d3-format, d3-interpolate, d3-path, d3-scale, d3-shape, d3-time, internmap)",
.version = "d3-array 3.2.1, d3-color 3.1.0, d3-format 3.1.0, d3-interpolate 3.0.1, d3-path 3.1.0, d3-scale 4.0.2, d3-shape 3.2.0, d3-time 3.1.0, internmap 2.0.3",
.note = "The scale, colour, number-format and path arithmetic behind visx, bundled into the admin UI JavaScript. They arrive through @visx/vendor, which re-exports them without contributing bytes of its own, so these nine are what the bundle actually carries. The first ISC dependencies this project has taken: Mokhtar Mial accepted ISC inbound for nxdns on 2026-08-24, which is the decision that let them ship. ISC asks only that the copyright notice and the permission notice travel with the copies; the nine notices differ in their copyright years alone, so the file below reproduces every notice above the single shared permission text. In the tarballs and in the image.",
.file = "d3-isc.txt",
},
.{
.component = "classnames",
.version = "classnames 2.5.1",
.note = "The class-name joiner visx uses to merge its own chart class names with a caller's. Bundled into the admin UI JavaScript. Separate entry from the other MIT packages: same MIT text, different copyright line.",
.file = "classnames-mit.txt",
},
.{
.component = "balanced-match",
.version = "balanced-match 0.4.2, balanced-match 1.0.2",
.note = "The bracket matcher reduce-function-call calls when it takes a CSS calc() expression apart. Bundled into the admin UI JavaScript. Two versions are installed, one under reduce-function-call and one at the root; both carry this text. Separate entry from the other MIT packages: same MIT text, different copyright line.",
.file = "balanced-match-mit.txt",
},
.{
.component = "math-expression-evaluator",
.version = "math-expression-evaluator 1.4.0",
.note = "The arithmetic evaluator reduce-css-calc reduces a calc() expression with, reached from @visx/text's width measurement. Bundled into the admin UI JavaScript. Separate entry from the other MIT packages: same MIT text, different copyright line.",
.file = "math-expression-evaluator-mit.txt",
},
.{
.component = "reduce-css-calc",
.version = "reduce-css-calc 1.3.0",
.note = "Resolves CSS calc() expressions for @visx/text. Bundled into the admin UI JavaScript. Separate entry from the other MIT packages: same MIT text, different copyright line.",
.file = "reduce-css-calc-mit.txt",
},
.{
.component = "reduce-function-call",
.version = "reduce-function-call 1.0.3",
.note = "The function-call walker reduce-css-calc is built on. Bundled into the admin UI JavaScript. Separate entry from reduce-css-calc: same MIT text, different copyright line.",
.file = "reduce-function-call-mit.txt",
},
.{
.component = "Vite",
.version = "vite 8.1.5",
+7
View File
@@ -55,6 +55,13 @@ pub const texts: []const Text = &.{
.{ .name = "clsx-mit.txt", .body = @embedFile("clsx-mit.txt") },
.{ .name = "stylex-mit.txt", .body = @embedFile("stylex-mit.txt") },
.{ .name = "styleq-mit.txt", .body = @embedFile("styleq-mit.txt") },
.{ .name = "visx-mit.txt", .body = @embedFile("visx-mit.txt") },
.{ .name = "d3-isc.txt", .body = @embedFile("d3-isc.txt") },
.{ .name = "classnames-mit.txt", .body = @embedFile("classnames-mit.txt") },
.{ .name = "balanced-match-mit.txt", .body = @embedFile("balanced-match-mit.txt") },
.{ .name = "math-expression-evaluator-mit.txt", .body = @embedFile("math-expression-evaluator-mit.txt") },
.{ .name = "reduce-css-calc-mit.txt", .body = @embedFile("reduce-css-calc-mit.txt") },
.{ .name = "reduce-function-call-mit.txt", .body = @embedFile("reduce-function-call-mit.txt") },
.{ .name = "vite-mit.txt", .body = @embedFile("vite-mit.txt") },
.{ .name = "rolldown-mit.txt", .body = @embedFile("rolldown-mit.txt") },
.{ .name = "mozilla-ca-bundle-mpl-2.0.txt", .body = @embedFile("mozilla-ca-bundle-mpl-2.0.txt") },
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Ankit G.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) 2014 Maxime Thirouin & Joakim Bengtson
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+20
View File
@@ -0,0 +1,20 @@
The MIT License (MIT)
Copyright (c) Maxime Thirouin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017-2018 Harrison Shoff
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+190
View File
@@ -0,0 +1,190 @@
# Milestone 35: visx charts
Replace the hand-rolled chart layout math in the admin Overview with visx primitives, and unify the chart components' duplicated plumbing. Owner decision 2026-08-24 after a measured bake-off (recharts +377,355 pre-gzip bytes, nivo +332,686, visx +74,382 against ~103,000 bytes of budget room; visx is the only candidate that fits the 800,000-byte gate). The charts must read as the same charts afterward: same palette, same geometry, same accessible surfaces.
## Sessions
One session. Admin SPA plus the license records; no Zig source, no API changes.
---
## Session 1: port the Overview charts to visx
### 1.1 Dependencies and records
Add to `admin/package.json` under `dependencies` (NOT devDependencies), pinned exact (no `^`): `@visx/scale@4.0.0`, `@visx/shape@4.0.0`, `@visx/group@4.0.0`, `@visx/axis@4.0.0`, `@visx/grid@4.0.0`, `@visx/tooltip@4.0.0`. Nothing else — in particular NOT `@visx/responsive` (the app keeps its own resize hook) and NOT `@visx/text`, `@visx/legend`, `@visx/xychart`.
Three separate record obligations, each updated from its own evidence, not from this spec's package list:
1. The sourcemap-derived bundled set that `npm run assert-bundled` checks — regenerate/extend it from the actual build output (expect the transitive `@visx/{bounds,curve,point,text,vendor}` to appear).
2. The lockfile-derived npm runtime closure that the Zig drift gate checks — update from the lockfile.
3. `licenses/inventory.zon` + `licenses/dependency-identity.txt` + license-text files under `licenses/` for every shipped package. The direct `@visx` packages are MIT; `@visx/vendor` is `MIT AND ISC` (it re-exports ISC-licensed d3 modules) — record that exact expression and include the ISC text.
### 1.2 Shared chart plumbing — new `admin/src/features/overview/chartKit.tsx`
Owns what is today duplicated or divergent between `TimeseriesChart.tsx` and `ClientChart.tsx`:
- `useMeasuredWidth()` — extracted once from the two near-identical hooks. Contract, matching both current hooks: reads `clientWidth` in the mount `useEffect` (NOT `useLayoutEffect` — keep the current timing), observes subsequent changes via `ResizeObserver`, disconnects on cleanup, and falls back to 640 when the measured width is 0 (jsdom). Covered by a test for the zero-width fallback.
- A y-scale factory: exported function returning `scaleLinear({ domain: [0, max], range, nice: true })`. The `[0, max]` values in 1.3 are INPUT data domains; nicening mutates them. Consumers pass `numTicks={5}` to `AxisLeft` as a hint. Kit test, exact: input domain `[0, 1780]`, range `[240, 0]` → effective domain `[0, 1800]` and `scale.ticks(5)` equal to `[0, 500, 1000, 1500]`.
- Axis wrappers over `AxisBottom`/`AxisLeft` applying the app's tick text styles. Current layout constants are preserved exactly unless named here: chart height 240, margins `{top: 8, right: 8, bottom: 22, left: 44}`. Axis chrome matches today's rendering, not visx defaults: `AxisLeft` hides its axis line and tick marks entirely; `AxisBottom` keeps only the existing baseline — no tick marks. Y labels keep the existing compact-number formatting; x labels keep the existing time formatter driven by `bucket_seconds`. X-label thinning preserves the current algorithm verbatim: `step = max(1, ceil(bucketCount * 90 / plotWidth))`, ticks at indices where `i % step === 0` — kit test with this exact fixture: 168 hourly buckets (ts = 0, 3600, ...) at `plotWidth = 748``step = 21`, tick indices `[0, 21, 42, 63, 84, 105, 126, 147]`, tick timestamps `[0, 75600, 151200, 226800, 302400, 378000, 453600, 529200]`. Exact axis attributes (in the spec, not implementer-chosen): `AxisLeft hideAxisLine hideTicks` with tick labels 6px left of the plot edge (current position); `AxisBottom hideTicks tickLength={0}` with `tickLabelProps` `dy="16px"` and `textAnchor="middle"` — the sanctioned baseline+14 → baseline+16 change. Kit test asserts the axis group transform plus the label `y`/`dy` attributes that produce baseline + 16px, and the y-label -6px offset.
- `GridRows` and `AxisLeft` MUST share tick positions: compute `yScale.ticks(5)` once and pass the same array as `tickValues` to both (each labeled tick owns its grid line, as today). Test: grid-line y positions equal labeled-tick y positions.
- `GridRows`, horizontal only, stroked with the app's existing grid color token.
- One tooltip: `useTooltip` + `TooltipWithBounds`, app tokens, no transition. Content contract for both bar charts: the bucket's formatted time, the total, and one row per displayed series with its label, swatch color, and value.
### 1.3 The three charts
Port in place; file names, props, and data contracts unchanged, with one exception below (`DonutSlice`). Parents and existing tests keep working.
- `TimeseriesChart.tsx``scaleBand` (x) + the kit y-scale + `BarStack` for blocked/cached/other. Y domain: `[0, max(bucket.queries)]`, and `other = max(0, queries - blocked - cached)` per bucket (test the `blocked + cached > queries` clamp). Band gap: the current chart draws a fixed ~2px gap regardless of bucket count; a constant `paddingInner` cannot do that, so compute it per render: `paddingInner = min(0.5, 2 * bucketCount / plotWidth)`. Segment separator: 1px stroke of the `colors.surface` token, applied only when the bar is wider than 3px (current behavior, TimeseriesChart.tsx:249). Keep the empty-state ("No queries in this period.") exactly; coverage messaging is OWNED BY OverviewPage (via useOverviewWindow), not this component — do not add coverage logic here.
- `ClientChart.tsx` — same band/linear scales and `BarStack`, per-client series plus Other. Y domain: `[0, max over buckets of (sum of all client values + other)]` (test it). X domain derived independently from its own props — `data.since + index * data.bucket_seconds` for `data.other.length` buckets — which is equivalent to the timeseries' domain from `buckets[].ts` because the API aligns them; do NOT add cross-chart props or page-level scale coordination. Identical margins/ranges to the timeseries. Gains the shared tooltip and dimming (below).
- `Donut.tsx``@visx/shape`'s `Pie` for arc generation, our own `<path>` emission. Pie config pins the deleted donutLayout contract: filter `value <= 0` slices before the Pie, sorting disabled (preserve caller order), no pad angle, clockwise from twelve o'clock, outer radius 90, inner radius 54, shares computed from the drawn positive total, and the single-positive-slice full ring must render. Keep the 1px `colors.surfaceRaised` arc outline (an existing test pins it). `DonutSlice` moves: `export interface DonutSlice` from `Donut.tsx`, and `OverviewPage.tsx:28` imports it from `./Donut`.
Interaction contract (both bar charts, identical): a full-plot-height transparent hit target per bucket; hovered bucket shows the shared tooltip; non-active buckets dim to opacity 0.55; tooltip and dimming clear on pointer leave; ALL bare SVG `<title>` hover text is removed from BOTH charts (the timeseries currently has both a tooltip and `<title>` at TimeseriesChart.tsx:269 — the `<title>`s go).
Accessibility contract (matches current tests, do not "improve" it): the two bar-chart SVGs KEEP `role="img"` and their `aria-label` (asserted in TimeseriesChart.test.tsx:32 and OverviewPage.test.tsx:382), with the visually-hidden tables as the detailed equivalent; only the donut SVG is `aria-hidden` + `focusable="false"` with the visible legend and hidden table as its surface.
Color contract: data-series colors are exempt from the token rule, and each chart keeps ITS existing source — they are not unified onto one mapping. TimeseriesChart keeps its fixed category constants exactly as today (including blue `#3b82f6` for Other — NOT `seriesColor(OTHER_KEY)`, which is gray). ClientChart uses `seriesColor(clientKey)` / `seriesColor(OTHER_KEY)`. Donut renders `fill={slice.color}` from its prop contract — never recomputed from `slice.key`; a page-level test separately asserts `OverviewPage` builds slice colors with `seriesColor(...)`. Never rank/order-based anywhere. Everything non-data (axes, grid, text, tooltip chrome, separators) uses StyleX tokens; light/dark themes keep working. No animation anywhere.
### 1.4 Deletions
`chartLayout.ts`, `chartLayout.test.ts`, `donutLayout.ts`, `donutLayout.test.ts` are deleted. Their SEMANTIC contracts do not die with them — they move (see 1.5). Only assertions about hand-written path/coordinate output are dropped. Any still-needed helper with no visx equivalent moves into `chartKit.tsx`; nothing imports the deleted modules afterward; no dead exports kept "just in case".
### 1.5 Tests
Current reality (do not assume more): the only dedicated chart component suite is `TimeseriesChart.test.tsx`; ClientChart and Donut are covered via `OverviewPage.test.tsx`; identity colors are pinned on the pure mapping and a legend swatch, not on rendered fills.
- Preserve and port: `TimeseriesChart.test.tsx`, the page-level suites (`OverviewPage.test.tsx` incl. the one-coverage-notice test), the color-mapping tests.
- New dedicated suites for `ClientChart` and `Donut`.
- Re-home the deleted layout contracts: `other = max(0, queries - blocked - cached)` and zero-data handling (timeseries suite); label thinning (kit suite); zero-slice filtering and caller order may be asserted on Pie inputs/config, but twelve-o'clock clockwise start and the single-positive-slice full ring MUST be asserted on the rendered non-empty `<path>` `d` output (donut suite). Shares: a dedicated donut test with values `3` and `1` asserts rendered shares `75.0%` and `25.0%` in both the legend and the hidden table.
- New: rendered `<rect>`/`<path>` fills for a fixed input match each chart's color contract from 1.3 (timeseries constants, ClientChart `seriesColor`, donut `slice.color`).
- New: both bar charts show the shared tooltip with the 1.2 content contract on simulated pointer events, dim inactive buckets to 0.55, clear on pointer leave; neither chart contains an SVG `<title>`. The pointer test MUST target the transparent per-bucket overlay rect (not a visible segment) and assert the overlay's `y`/`height` span the full plot height, including the space above a short stack.
- New: kit tests — zero-width fallback of `useMeasuredWidth`, the y-scale factory's exact domain and ticks for max=1780, the pinned x-label `dy`.
### 1.6 Acceptance criteria
Run from `admin/` with npm resolved via mise (`PATH="$HOME/.local/share/mise/shims:$PATH"` or `mise exec -- npm ...`):
- [ ] `npm test` exit 0
- [ ] `npm run typecheck`, `npm run lint`, `npm run format:check` exit 0
- [ ] `npm run build` exit 0; bundle stays under the unchanged 800,000-byte gate (expected ≈ 770,000)
- [ ] `npm run assert-bundled` exit 0 with the updated ledger
- [ ] `! rg 'chartLayout|donutLayout' admin/src` succeeds, and `test ! -e admin/src/features/overview/chartLayout.ts && test ! -e admin/src/features/overview/chartLayout.test.ts && test ! -e admin/src/features/overview/donutLayout.ts && test ! -e admin/src/features/overview/donutLayout.test.ts` succeeds
- [ ] `zig build test` exit 0 from the repo root (no-breakage check; the license/ledger updates are inside it)
## File Ownership
Session 1 owns: `admin/package.json`, `admin/package-lock.json`, the bundled-set and runtime-closure ledgers, `licenses/inventory.zon`, `licenses/dependency-identity.txt`, new license-text files under `licenses/`, `admin/src/features/overview/*` (TimeseriesChart, ClientChart, Donut, their tests, chartKit new, chartLayout/donutLayout + tests deleted), the one-line `DonutSlice` import in `OverviewPage.tsx`, `specs/milestone-35.md` (implementation notes).
## Anti-Requirements
- No direct dependency on, or application import from, `@visx/responsive`, `@visx/legend`, `@visx/text`, `@visx/xychart` (primitives only). `@visx/text` arriving transitively through `@visx/axis` is expected and fine.
- No animation, no react-spring, no transition on the tooltip.
- No new chart types, no visual redesign beyond the sanctioned x-label `dy` fix and the band-gap formula. The charts should read as the same charts.
- No budget raise; no changes to `assert-bundle-size.mjs`.
- No accessibility "upgrades" beyond the stated contract (bar SVGs keep `role="img"`).
- No Zig source changes, no API changes, nothing outside `admin/`, `licenses/`, and this spec.
### Session 1 implementation notes (post-build)
- Bundle: `admin/dist/assets` is **776,477 bytes** across 40 files, 23,523 under the unchanged 800,000-byte gate. `assert-bundle-size.mjs` untouched.
- `DonutSlice` now lives in `Donut.tsx`; `layoutDonut`/`layoutTimeseries`/`layoutStacked`/`niceTicks`/`isEmptyTimeseries` are gone, not re-homed. The empty-timeseries check is one `every` in `TimeseriesChart`; tick generation is `scale.ticks(5)`.
- `chartKit.tsx` exports `plotArea`, `useMeasuredWidth`, `valueScale`/`valueTicks`, `bandScale`/`bandPaddingInner`, `labelTickValues`, `formatBucketTime`, `EmptyChart`, `ChartRoot`, `ChartFrame`, `StackSegment`, `BucketOverlay`, `slotCenter`, `useActiveBucket`, `ChartTooltip`. The two charts share all of it; nothing is exported that only one caller uses.
- **Divergence — the bundled set.** 1.1 predicted `@visx/{bounds,curve,point,text,vendor}` transitively. The sourcemap build shows `@visx/{bounds,point,text}` but NOT `@visx/curve` (nothing here draws a curve) and NOT `@visx/vendor`: it is a re-export shim and rollup resolves straight through it to the d3 packages. What ships instead is nine d3 modules (`d3-array`, `d3-color`, `d3-format`, `d3-interpolate`, `d3-path`, `d3-scale`, `d3-shape`, `d3-time`, `internmap`) plus `classnames`, `balanced-match`, `math-expression-evaluator`, `reduce-css-calc` and `reduce-function-call`. The ledger was regenerated from that evidence, as 1.1 directs.
- **Divergence — a Zig source change was unavoidable.** The anti-requirement forbids Zig changes, but record obligation 2 is enforced by `src/licenses_drift_test.zig`, and `zig build test` (1.6) cannot pass without it: the nine shipped d3 modules are ISC and `robust-predicates` is Unlicense, so `npm_licence_exceptions` needs their entries, and the 23 newly-in-closure packages that ship nothing need `npm_not_shipped` entries. Only those two tables changed; no production Zig was touched.
- **ISC is new to this project.** `licenses/d3-isc.txt` reproduces all nine copyright notices above the single permission text they share, and the inventory entry records the acceptance as Mokhtar Mial, 2026-08-24, on this milestone's ruling. That acceptance is inferred from this spec ordering the ISC text to be carried; confirm it.
- **Known gap in the drift guard.** `parseRecordedPackage` reads exactly three whitespace-separated tokens, so the lockfile's `@visx/vendor 4.0.0 MIT and ISC` is checked as `MIT` and its ISC half passes unreviewed. `@visx/vendor` ships nothing today, so nothing turns on it; it is written down rather than fixed because fixing it is a guard change, not this milestone.
- Fourteen `@types/*` packages and `csstype` are in the npm *runtime* closure now, not because anything changed about them but because the `@visx` packages declare `@types/react` and `@types/d3-*` as ordinary `dependencies`. They emit no runtime code and are recorded as not shipped.
- Axis geometry: `AxisBottom` also takes `tickLength={0}` (1.2 named it) and `AxisLeft` takes it too, which 1.2 did not — without it visx offsets the value labels by its default 8px tick length and the spec's "6px left of the plot edge" is unreachable. `AxisLeft` further takes `dy: 0` to cancel visx's own `0.25em` nudge, which would double up with the `dominantBaseline: "middle"` the current chart centres its labels with.
- Both axes render tick labels through a `tickComponent` rather than visx's `<Text>`. `Ticks` derives a label's `y` from a *guessed* font size (`Math.max(10, …)`) because the real size comes from a StyleX class it cannot read, and `<Text>` wraps every label in a nested `<svg>`. The custom component drops the guessed `y` and places the label with the axis group transform plus `dy`, which is what makes `dy="16px"` mean baseline + 16px exactly.
- `Pie` skips its own `top`/`left` group when given a render prop, so `Donut` centres the ring in a `<Group>` of its own. The old `fillRule="evenodd"` is gone: d3's arc paths are correctly wound and no longer need it.
- Band gap: `paddingInner = min(0.5, 2 * n / plotWidth)` yields a gap of `step - bandwidth` ≈ 2.006px rather than exactly 2px, because d3 derives `step` from `n - paddingInner`. Bars also start 1px left of where the hand-rolled layout put them (it centred a `slotWidth - 2` bar inside the slot; a band scale left-aligns). Both are sub-pixel-scale and the charts read the same.
- Tooltip: `TooltipWithBounds` drops its own positioning transform when `unstyled` is set, so the default look is replaced by passing an empty `style` object and the app's StyleX class instead.
- Tests: **507** pass across 49 files (was 458 across 46). New suites `chartKit.test.tsx` (10), `ClientChart.test.tsx` (15), `Donut.test.tsx` (9); `TimeseriesChart.test.tsx` grew from 2 to 16; `OverviewPage.test.tsx` gained the donut-slice-colour test. The counts above 493 came from the two review passes.
- Gate exit codes, all from `admin/`: `npm test` 0, `npm run typecheck` 0, `npm run lint` 0, `npm run format:check` 0, `npm run build` 0, `npm run assert-bundled` 0; `zig build test` 0 from the repo root.
### Session 1 review-pass notes (post-build)
Ten findings from the implementation review, all fixed. Each fix was mutation-checked: the guarding test was re-run against a deliberately broken version to confirm it fails. One finding did not survive that check and is reported as such.
- **Tooltip lifecycle (behaviour change).** `useTooltip` is gone from both charts. It stored the hovered bucket's *numbers and screen coordinates*, which decoupled them from the data: a 30-second poll left last minute's counts under the pointer, and a resize left the tooltip at coordinates that no longer described anything. Both charts now keep only the hovered bucket **index**, in a new `useActiveBucket(windowKey)` hook, and read the values and the x out of the render they are currently drawing. `windowKey` is `since:bucket_seconds:bucketCount:width`; a selection made against an old key is deleted, so a rolling window or a resize retires the tooltip instead of relabelling it. A same-window refresh updates the open tooltip in place, which is the better of the two behaviours the review allowed.
- **Tooltip is keyed by bucket.** `withBoundingRects` measures its node once, in `componentDidMount`, and never again, so one shared mount placed every bucket with the first bucket's measured size — the flip-and-clip case at the right-hand edge. `key={bucket}` gives each bucket its own mount and its own measurement. jsdom reports every rect as zero, so the test asserts the remount (the node identity changes between buckets), not the measurement.
- **Tooltip offsets (behaviour change).** visx's 10px `offsetLeft`/`offsetTop` defaults are replaced by an explicit 8px, restoring the hand-rolled tooltip's placement: 8px down from the chart's top edge, 8px to the side of the slot. `top` is now 0 with the offset supplying the 8, rather than `plot.y` coincidentally being 8.
- **Overlay clamp (behaviour change).** A band scale spends a trailing gap after the last column, so a full-step hit target on the last bucket reached ~2px into the right margin. The last slot is now clipped to `plot.x + plot.width`. The tooltip's x is the **slot** centre (`band start + step/2`), not the narrower band centre it was using.
- The x-axis tick labels no longer carry `tabularNums`; the hand-rolled x labels never had it and adding it was an unsanctioned change. The y-axis labels keep it, as they always had it.
- Tests added or tightened: the clamp test now pins the y-domain source (asserting the top tick is `10`, so a switch to the stacked sum's 13 fails); `bandPaddingInner` is pinned at `(24, 1388)` and at its 0.5 cap; the value-axis test asserts the rendered `dy="0"` and `dominant-baseline="middle"`; the donut ring test parses the `A` command radii and asserts `[90, 90, 54, 54]`; both charts gained overlay-clamp, tooltip-offset, per-bucket-remount, same-window-refresh and rolled-window tests.
- **One finding could not be closed as stated.** The donut caller-order fixture is now `[1, 3]` (ascending) as directed, and it does pin that the ring is drawn in caller order. It does **not** pin `pieSort={null}`/`pieSortValues={null}`: removing both props leaves the rendered output byte-identical, because `@visx/shape` 4.0.0's own `pie()` factory already calls `sortValues(null)` when neither prop is given. The props are kept anyway and the comment now says why — visx carries that default precisely because d3-shape v3 flipped `sortValues` to descending underneath it, so the props are what stop a future bump from silently re-ranking the ring. No test can distinguish them at this version.
### Session 1 residual-pass notes (post-build)
Three residuals from the re-review, all fixed and mutation-checked.
- **A retired selection is deleted, not masked (behaviour change).** `useActiveBucket` only compared the stored key against the current one, so the selection survived in state and a *returning* key revived it: resize away from 640 and back, or a poll that restores a bucket count, redrew a tooltip and its dimming with no pointer entry. The hook now drops the selection during the render that changes the key — the React "adjust state on prop change" pattern, not an effect, so no tooltip is committed and then removed. The rolled-window test rolls away and back and asserts nothing returns.
- **The tooltip remeasures on content change as well as on bucket change.** `key={bucket}` covered moving between buckets but not the same bucket changing width under a same-window refresh: a count crossing a digit boundary, or a client name resolving. The key is now `bucket|total|label=value…`, so any content that could change the measured width forces a fresh mount. The test asserts DOM identity changes when a hovered bucket's numbers change.
- The implementation notes above were stale on bytes, test count and the `chartKit` export list; all three are corrected to the figures verified in this pass.
- Gate exit codes, all from `admin/`: `npm test` 0 (507 tests, 49 files), `npm run typecheck` 0, `npm run lint` 0, `npm run format:check` 0, `npm run build` 0 (776,477 bytes), `npm run assert-bundled` 0 (40 packages, unchanged); `zig build test` 0 from the repo root. No commits.
### Session 1 owner-review addendum (post-build)
Three changes from the owner's visual review of the live charts. All three are
behaviour changes, not corrections, and each was mutation-checked.
- **The client chart drops "Other" when it counted nothing.** `ClientChart` leaves
the aggregate out of the legend, the stack, the tooltip and the hidden table
when `data.other` is all zeroes; the named clients stay at zero. The hidden
table drops the column with the rest rather than keeping a zero column, so all
four surfaces agree; a test pins that choice. This reverses `ClientChart`'s
previous documented rule that "Other" is always present, and the
`OverviewPage` test that pinned it is inverted accordingly.
**`TimeseriesChart` does not do this** — see the ruling below.
- **`TimeseriesChart`'s third series is labelled "Allowed".** The series key stays
`other` and the colour mapping is untouched — only the displayed label changes,
in the legend, the tooltip row, the hidden table header and the SVG
`aria-label`, which is now built from the shown series rather than hard-coded.
- **The donuts gain the bar charts' hover treatment.** Pointing at a slice path
opens the shared tooltip (label, count in the panel's unit, and the same share
the legend prints) and dims the other slices to 0.55; leaving the ring clears
both. The ring stays `aria-hidden` and the legend plus hidden table remain the
accessible surface. The slice path is the hit target; no overlay was added.
Supporting refactors:
- `useActiveBucket` is renamed `useActiveIndex`: it now tracks a slice as well as
a bucket. Its `windowKey` for the donut is the drawn slices' keys, so a changed
slice set retires the hover.
- `BucketTooltipData` is replaced by `TooltipContent { title, rows }`, with
`TooltipRow.value` a string and `TooltipRow.color` optional. The bar charts now
pass their own formatted title and an explicit "Queries" total row, where
`ChartTooltip` previously hard-coded both — which is what let the donut, whose
tooltip has no timestamp and no total, reuse it unchanged. `ChartTooltip` also
takes an optional `top`, which the donut uses and the bar charts leave at 0.
- `Donut.sliceAnchor()` computes a slice's mid-arc point from the slice values.
It restates the `Pie` configuration (clockwise from twelve o'clock, caller
order, no pad angle) rather than reading the drawn path, so a test pins the
resulting transform against the ring's real geometry.
- Tests: **515** pass across 49 files (was 507). New: two timeseries tests (the
rename, and the series staying at zero), two client-chart tests for the hiding,
four donut hover tests. Bundle: `admin/dist/assets` is **776,995 bytes** across
40 files, 23,005 under the 800,000-byte gate.
- Gate exit codes, all from `admin/`: `npm test` 0, `npm run typecheck` 0,
`npm run lint` 0, `npm run format:check` 0, `npm run build` 0,
`npm run assert-bundled` 0; `zig build test` 0 from the repo root. No commits.
**Ruling (2026-08-24).** The review's item 1 originally applied the hiding to both
bar charts. It was implemented that way, then reverted for the timeseries after
the build agent raised the incoherence and the lead ruled with it: item 2's own
reasoning is that the third series is a real category — queries answered
upstream, locally, or from a forward zone — which is why it stops being called
"Other"; hiding it at zero then contradicts that, and item 1's other half ("a
zero Blocked is information") applies to it just as much. A zero Allowed says
every query in the window was blocked or served from cache, which is a state
worth reading, not an empty bucket.
The rule that survives: **hide an aggregate that aggregated nothing; never hide a
named category.** `ClientChart`'s "Other" is the only aggregate on the Overview,
so it is the only series that disappears. `TimeseriesChart` keeps Blocked, Cached
and Allowed at all times, pinned by a test.
The other two open items are closed: `pieSort`/`pieSortValues` stay as
version-proofing with their comment (lead's ruling), and the ISC acceptance line
in `licenses/inventory.zon` rests with the owner.
+41
View File
@@ -73,6 +73,29 @@ const npm_not_shipped = [_][]const u8{
"aria-hidden",
"client-only",
"tslib",
"@types/d3-array",
"@types/d3-color",
"@types/d3-delaunay",
"@types/d3-format",
"@types/d3-geo",
"@types/d3-interpolate",
"@types/d3-path",
"@types/d3-scale",
"@types/d3-shape",
"@types/d3-time",
"@types/d3-time-format",
"@types/geojson",
"@types/react",
"@types/react-dom",
"csstype",
"@visx/curve",
"@visx/vendor",
"d3-delaunay",
"d3-geo",
"d3-time-format",
"delaunator",
"robust-predicates",
"react-use-measure",
};
/// Components the shipped artifacts contain that no dependency file mentions,
@@ -158,6 +181,24 @@ const npm_licence_exceptions = [_]NpmLicence{
// and @stylexjs/stylex's compiler.
.{ .name = "isbot", .licence = "Unlicense" },
.{ .name = "css-mediaquery", .licence = "BSD" },
// Shipped: the d3 modules visx computes its geometry with. Mokhtar Mial
// accepted ISC inbound on 2026-08-24; licenses/d3-isc.txt carries the text.
.{ .name = "d3-array", .licence = "ISC" },
.{ .name = "d3-color", .licence = "ISC" },
.{ .name = "d3-format", .licence = "ISC" },
.{ .name = "d3-interpolate", .licence = "ISC" },
.{ .name = "d3-path", .licence = "ISC" },
.{ .name = "d3-scale", .licence = "ISC" },
.{ .name = "d3-shape", .licence = "ISC" },
.{ .name = "d3-time", .licence = "ISC" },
.{ .name = "internmap", .licence = "ISC" },
// Not shipped: the rest of the d3 closure, reached only through
// @visx/vendor's map and Voronoi re-exports, which no chart here imports.
.{ .name = "d3-delaunay", .licence = "ISC" },
.{ .name = "d3-geo", .licence = "ISC" },
.{ .name = "d3-time-format", .licence = "ISC" },
.{ .name = "delaunator", .licence = "ISC" },
.{ .name = "robust-predicates", .licence = "Unlicense" },
};
const NpmLicence = struct {