eb8b65c7bc
## Summary Implementation of [ADR-0023](docs/decisions/0023-charts-d3-observable-plot.md) — the foundations of the workspace's chart library. PR 2 of the chantier: | PR | Périmètre | | --- | --- | | PR 1 ✅ | ADR-0023 — decision + a11y contract + bundle plan. | | **PR 2 (this one)** | `libs/shared/charts/` foundations + `<lib-bar-chart>`, `<lib-donut-chart>`, `<lib-stacked-bar-chart>`. | | PR 3 | Integration on the `/audit` page — daily-volume bar + outcome-breakdown donut + event-type-over-time stacked bar. | ## What lands ### Workspace deps ``` d3 — top-level toolkit, types via @types/d3 d3-shape — used directly by <lib-donut-chart> d3-scale-chromatic — colour-blind-safe palette source @observablehq/plot — declarative layer over D3, used by bar + stacked-bar ``` All four (+ matching `@types/*`) land in the workspace root `devDependencies`. Tree-shaken at build time per ADR-0023's bundle plan. ### New lib `libs/shared/charts/` ``` libs/shared/charts/src/lib/ ├── _internal/ ← single source of truth for the a11y contract │ ├── a11y.ts ← chartId, findChartSvg, injectSvgTitleDesc, prefersReducedMotion, resolveTheme │ ├── chart-envelope.scss ← shared figure / caption / fallback / dark-mode rules │ ├── chart-types.ts ← `ChartBaseInputs<T>` extended by each component │ └── palette.ts ← Viridis / Cividis (sequential) + ColorBrewer Set2 (categorical) ├── bar-chart/ ← Plot.barY ├── donut-chart/ ← raw d3-shape (pie + arc); Plot has no donut mark └── stacked-bar-chart/ ← Plot.barY with `fill: <seriesKey>` (auto-stacked, legend on) ``` ### A11y contract baked in for v1 Per ADR-0023's six commitments, every chart component produces (and unit-tests for): 1. `<figure role="img" aria-labelledby aria-describedby>` wrapping the SVG. 2. SVG `<title>` + `<desc>` as the **first two children** — injected post-render via `injectSvgTitleDesc` because Plot doesn't emit them itself. `findChartSvg` handles both Plot output shapes (bare SVG, or `<figure>` wrapping a legend + SVG for `legend: true` configs). 3. A `<details>` disclosure with a `<table>` rendering every data point — the keyboard-navigable / screen-reader-friendly fallback for non-visual users. 4. Palette from `_internal/palette.ts` only — Viridis / Cividis for sequential, ColorBrewer Set2 for categorical. Both colour-blind-safe. 5. AA-contrast axis text via `:where(.dark)` flips in `_internal/chart-envelope.scss`. 6. `prefers-reduced-motion` → `data-no-transitions` marker on the SVG, CSS strips animations + transitions. A custom ESLint rule in [`libs/shared/charts/eslint.config.mjs`](libs/shared/charts/eslint.config.mjs) bans direct imports of `d3-scale-chromatic` outside `_internal/palette.ts` so a future contributor can't bypass the colour-blind-safe contract. ### Component contract Every `<lib-*-chart>` exposes the same Signal-based shape per ADR-0023: ```ts [data]: readonly T[]; [caption]: string; [description]: string; [ariaLabel]: string; [colorScheme]?: 'sequential' | 'categorical'; // + chart-specific keys (xKey, yKey, categoryKey, valueKey, seriesKey, …) ``` Re-renders triggered by Angular's `effect()` on input changes; the previous SVG is `replaceChildren`-d out so there's no DOM accumulation across data updates. ## Notes for the reviewer - **Why three SCSS files importing one shared envelope?** Extracted at the third consumer per CLAUDE.md's "three similar lines is better than a premature abstraction" rule — bar + donut + stacked-bar share ~70 LOC of figure / caption / fallback / dark-mode chrome. `_internal/chart-envelope.scss` is the consolidation; each chart's `.scss` is now 4-20 LOC of chart-specific tweaks. - **Why is `<lib-donut-chart>` raw D3 rather than Plot?** Plot's design philosophy explicitly excludes pie/donut marks ("a bar chart is almost always more legible"). The audit-log outcome breakdown reads naturally as a donut (the centre carries the total). Raw `d3-shape` is the lower-level fallback ADR-0023 reserves precisely for this kind of case; the component's API is identical to the Plot-backed siblings. - **Why does the donut also stamp per-slice `<title>`?** Belt-and-suspenders. The top-level SVG `<title>` reads the caption; per-slice `<title>` reads "category: value" on hover (the SVG-native tooltip convention) for keyboard / screen-reader users who land on a specific slice. - **Why no `pnpm.overrides` adjustment for `d3-*` transitives?** None of the new deps brought a vulnerability in this install. The `pnpm audit --audit-level=moderate` gate from #161 stays green. - **What's deliberately deferred to PR 3?** The `/audit`-page integration — data aggregation from the current page (`AdminAuditPage` rows already loaded), the actual `<lib-*-chart>` placements above the existing table, the i18n strings for the captions / descriptions / aria-labels. No mock SAMPLE data shipped in this PR — every test uses local fixtures so the lib stays decoupled from any specific consumer. ## Test plan - [x] `pnpm nx test shared-charts` — **13 specs pass** across the three components. - [x] `pnpm nx lint shared-charts` — clean, including the custom `no-restricted-imports` guard on `d3-scale-chromatic`. - [x] `pnpm nx build shared-charts` — clean (TS strict + ng-packagr). - [x] `pnpm nx run-many -t lint test build --projects=shared-charts,portal-shell,portal-admin` — 12/12 tasks green. - [x] `pnpm nx build portal-shell --configuration=production` — i18n-strict prod build clean. The lib ships no i18n marks (axis labels are caller-supplied per ADR-0023's i18n posture), so no xlf entry change here. - [ ] **Visual smoke (deferred to PR 3 when the components are placed on `/audit`)** — `<figure>` + caption visible, SVG `<title>` exposed by VoiceOver / NVDA, `<details>` fallback expands to a table, dark-mode toggle flips axis text + Cividis palette, `prefers-reduced-motion` strips Plot's fade-in. ## What's next PR 3 wires the three components onto the `/audit` page: aggregates `AdminAuditPage.items` client-side into the three required shapes (daily totals, outcome counts, daily-by-event-type pivots), places them above the existing filter form, ships the i18n strings for the captions and descriptions in `messages.fr.xlf`. Bundle impact on the lazy `audit` chunk gets verified there (the ~65 KB gzip plan from the ADR). --------- Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr> Reviewed-on: #171
79 lines
3.2 KiB
TypeScript
79 lines
3.2 KiB
TypeScript
import { TestBed } from '@angular/core/testing';
|
|
import { DonutChart } from './donut-chart';
|
|
|
|
interface OutcomeRow {
|
|
readonly outcome: string;
|
|
readonly count: number;
|
|
}
|
|
|
|
const SAMPLE: readonly OutcomeRow[] = [
|
|
{ outcome: 'success', count: 120 },
|
|
{ outcome: 'failure', count: 6 },
|
|
{ outcome: 'denied', count: 3 },
|
|
];
|
|
|
|
function render() {
|
|
TestBed.configureTestingModule({ imports: [DonutChart] });
|
|
const fixture = TestBed.createComponent<DonutChart<OutcomeRow>>(DonutChart);
|
|
fixture.componentRef.setInput('data', SAMPLE);
|
|
fixture.componentRef.setInput('categoryKey', 'outcome');
|
|
fixture.componentRef.setInput('valueKey', 'count');
|
|
fixture.componentRef.setInput('caption', 'Outcome breakdown');
|
|
fixture.componentRef.setInput(
|
|
'description',
|
|
'Donut chart of audit-event outcomes for the current page (success, failure, denied).',
|
|
);
|
|
fixture.componentRef.setInput('ariaLabel', 'Outcome breakdown — donut chart');
|
|
fixture.componentRef.setInput('centerLabel', '129');
|
|
fixture.detectChanges();
|
|
return fixture;
|
|
}
|
|
|
|
describe('DonutChart', () => {
|
|
beforeEach(() => TestBed.resetTestingModule());
|
|
|
|
it('wraps the chart in a <figure role="img"> with aria-labelledby + aria-describedby', () => {
|
|
const fixture = render();
|
|
const figure = (fixture.nativeElement as HTMLElement).querySelector('figure.chart-figure');
|
|
expect(figure?.getAttribute('role')).toBe('img');
|
|
expect(figure?.getAttribute('aria-labelledby')).toMatch(/^chart-\d+-title$/);
|
|
expect(figure?.getAttribute('aria-describedby')).toMatch(/^chart-\d+-desc$/);
|
|
});
|
|
|
|
it('renders an SVG with <title> + <desc> as the first two children + one <path> per slice', () => {
|
|
const fixture = render();
|
|
const root = fixture.nativeElement as HTMLElement;
|
|
const svg = root.querySelector<SVGSVGElement>('.chart-canvas svg');
|
|
expect(svg).not.toBeNull();
|
|
const children = Array.from(svg?.children ?? []);
|
|
expect(children[0]?.tagName).toBe('title');
|
|
expect(children[1]?.tagName).toBe('desc');
|
|
const slices = children.filter((c) => c.tagName === 'path');
|
|
expect(slices.length).toBe(SAMPLE.length);
|
|
});
|
|
|
|
it('each slice has its own <title> child carrying "<category>: <value>"', () => {
|
|
const fixture = render();
|
|
const root = fixture.nativeElement as HTMLElement;
|
|
const slices = root.querySelectorAll<SVGPathElement>('.chart-canvas svg path');
|
|
expect(slices.length).toBe(SAMPLE.length);
|
|
expect(slices[0]?.querySelector('title')?.textContent).toBe('success: 120');
|
|
expect(slices[1]?.querySelector('title')?.textContent).toBe('failure: 6');
|
|
});
|
|
|
|
it('renders the centerLabel in a <text> when supplied', () => {
|
|
const fixture = render();
|
|
const root = fixture.nativeElement as HTMLElement;
|
|
expect(root.querySelector('.donut-center-label')?.textContent?.trim()).toBe('129');
|
|
});
|
|
|
|
it('renders a <details> tabular fallback with one row per category', () => {
|
|
const fixture = render();
|
|
const root = fixture.nativeElement as HTMLElement;
|
|
const rows = root.querySelectorAll('details.chart-fallback tbody tr');
|
|
expect(rows.length).toBe(SAMPLE.length);
|
|
expect(rows[0]?.querySelector('th')?.textContent?.trim()).toBe('success');
|
|
expect(rows[0]?.querySelector('td')?.textContent?.trim()).toBe('120');
|
|
});
|
|
});
|