Files
apf_portal/libs/shared/charts/src/lib/bar-chart/bar-chart.ts
T
julien 9e7eb4af15
CI / check (push) Successful in 6m42s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 3m14s
CI / a11y (push) Successful in 2m38s
CI / perf (push) Successful in 4m33s
fix(audit): chart colours + Charts-tab layout regressions (#175)
## Summary

Follow-up polish on the audit-log Charts tab shipped in #174. Three small but visible regressions surfaced once real data was loaded:

1. **"Events per day" bar chart cycled a categorical palette across the X axis** — every day got a different colour, which read as "categorical meaning per day" when the X axis is just a time bucket. Switched to a single fixed fill (curated blue from the lib palette).
2. **"Outcome breakdown" donut painted slices in Set2 order** — `success` came out teal, `denied` came out orange. With orange = "danger" in most readers' mental model, this is the wrong way around. Added a `colorMap` input on `<lib-donut-chart>` and a curated `semanticStatusColors` export so the audit page can map `success → green`, `denied → orange`, `failure → red`.
3. **Charts tab caused a body scrollbar + empty space below the footer.** Plot renders into a hidden `[hidden]` panel on first switch, so `canvas.clientWidth` is 0 and Plot falls back to its 600/720 default — the resulting fixed-width SVG was wider than the grid column, dragged horizontal overflow up the tree, and (because the grid item defaults to `min-width: auto`) wouldn't shrink. The shell layout broke. Fixed by constraining the chart envelope and the grid items so the SVG can scale down to the actual column width.

## What lands

### Bar chart — single fill, lib-owned default

- `Plot.barY` mark no longer encodes colour from `xKey`. The `fill` parameter is now a literal-string colour, applied uniformly to every bar.
- New `fillColor` input on `<lib-bar-chart>` for the rare case a consumer needs a different shade; defaults to `DEFAULT_BAR_FILL = '#1d4ed8'` (≈ Tailwind blue-700, picked for AA contrast against both light and dark surfaces, colour-blind-safe).
- Removed the now-unused `color: { type: 'ordinal', range: palette }` scale and the `colorScheme` input on the bar chart — the categorical palette only made sense when `fill: xKey` was the default behaviour.

### Donut chart — optional semantic mapping

- New `colorMap?: Readonly<Record<string, string>>` input on `<lib-donut-chart>`. When provided, slice fill resolves to `colorMap[category]` first, falling back to the categorical palette for any unmapped category. Lib still owns the palette per ADR-0023; the map only constrains *which colour the consumer picks for which category*, not what colours exist.
- New `semanticStatusColors` export from `shared-charts` — a curated 5-entry map (`success / warning / error / info / neutral`) tuned for AA contrast and deuteranopia/protanopia distinguishability. Consumers stay inside the lib's palette without authoring their own hex codes.
- The audit page now ships `outcomeColorMap = { success: green, failure: red, denied: orange }` and passes it to the donut. The donut's `description` (screen-reader fallback) and the legend chip semantics now line up.

### Chart envelope — overflow containment

`libs/shared/charts/src/lib/_internal/chart-envelope.scss`:

- Force `display: block` + `min-width: 0` on every chart host element (`lib-bar-chart`, `lib-donut-chart`, `lib-stacked-bar-chart`). Angular custom-element hosts default to `display: inline`, which lets the inner `<figure>` escape parent sizing constraints — the root cause of the body-scrollbar symptom.
- `.chart-canvas` gets `min-width: 0` and constrains every inner `figure { max-width: 100% }` + `svg { max-width: 100%; height: auto }`. The SVG keeps its viewBox aspect ratio while scaling down to the actual column width.

`apps/portal-admin/src/app/pages/audit/audit.scss`:

- `.chart-tile { min-width: 0; }` — grid items default to `min-width: auto`, which prevents shrinking below the intrinsic content width. Without it, Plot's fixed-width SVG could still push the grid column past `1fr` even with the lib-side fixes.

## Notes for the reviewer

- **Why a hardcoded hex (`#1d4ed8`) for `DEFAULT_BAR_FILL` rather than a brand token?** The chart lib is intentionally decoupled from `libs/shared/tokens` — it has no SCSS/CSS-vars dependency and Plot writes the fill as an SVG attribute, not a CSS value, so a CSS variable wouldn't apply anyway. The hex stays inside the lib, marked as the canonical default, with the docstring promising AA contrast + colour-blind safety. If the brand wants to take it over later, swap the constant in one place.
- **`semanticStatusColors` is a curated map, not an open extension point.** Five entries (`success / warning / error / info / neutral`) covers the audit module and any future status-bearing donut (user list, integrations health, etc.). Adding a sixth entry needs a small PR + an a11y-contrast check, which is the right friction.
- **The `aria-label="bar"` selector in the new bar-chart spec.** Plot tags its bar-mark `<g>` with `aria-label="bar"` (and similarly `"rule"` for `Plot.ruleY`). Selecting on it scopes the fill-uniqueness check to actual bars, not axes / ticks / labels. If Plot changes that label upstream the spec breaks loudly — preferable to a fragile geometric selector.
- **Lazy fetch policy and the empty-state edge case** from #174 are unchanged. The donut still receives `colorMap` even when `data` is empty; the lib's `arcs.forEach` short-circuits on zero arcs so no colour lookup happens.
- **`audit.scss` is now 7.5 KB**, still over the 6 KB component-style warning (untouched from #174) and well under the 8 KB error. The new `.chart-tile { min-width: 0 }` rule is two lines.

## Test plan

- [x] `pnpm nx test shared-charts` — **15 specs pass** (was 14: +1 donut `colorMap` test, +1 bar single-fill test, -1 obsolete bar palette assumption).
- [x] `pnpm nx test portal-admin` — **62 specs pass** (unchanged from #174 — semantic mapping is a template-only change, behavioural tests still hold).
- [x] `pnpm nx run-many -t lint test build -p portal-shell,portal-admin,portal-bff,shared-charts` — clean. Same three pre-existing lint warnings, no new ones; bundle sizes unchanged within ±0.1 KB.
- [ ] **Manual smoke** — `pnpm nx serve portal-admin` + `pnpm nx serve portal-bff`, sign in with `Portal.Admin`, navigate to `/admin/audit`:
  - Switch to **Charts** tab — daily-volume bars all render the same blue.
  - Donut centre matches `s.total`, the green slice is `success`, the orange slice is `denied`, the red slice is `failure`. Hover each slice — `<title>` shows `<category>: <count>` (untouched a11y contract from the lib).
  - Body scrollbar stays absent; footer stays anchored at the viewport bottom with no white-space gap.
  - Resize the window through the `(max-width: 800px)` breakpoint — grid collapses to one column, charts re-flow without horizontal overflow.
  - Dark mode toggle — colours stay readable, no contrast regressions.

## What's next

Nothing in this chantier. The audit dashboard is now visually coherent and layout-stable. Two background items to track separately when the CMS / user-list pages land their own dashboards:

- Tab-state URL persistence (carried forward from #174's "what's next").
- Promote the WAI-ARIA tab pattern out of `audit.html` into `libs/shared/ui/tabs/` once a second consumer appears.

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #175
2026-05-17 01:17:33 +02:00

160 lines
5.9 KiB
TypeScript

import {
ChangeDetectionStrategy,
Component,
ElementRef,
ViewEncapsulation,
computed,
effect,
inject,
input,
} from '@angular/core';
import * as Plot from '@observablehq/plot';
import { chartId, findChartSvg, injectSvgTitleDesc, prefersReducedMotion } from '../_internal/a11y';
import type { ChartBaseInputs } from '../_internal/chart-types';
import { DEFAULT_BAR_FILL } from '../_internal/palette';
/**
* `<lib-bar-chart>` — vertical bar chart over a categorical X axis.
*
* Backed by `@observablehq/plot`'s `barY` mark per ADR-0023. Every
* row in `data` becomes one bar with its height encoding `yKey` and
* its position encoding `xKey`.
*
* Every bar is filled with the same colour by default — a single-
* series bar chart's X axis is typically a *label* (day, bucket,
* name) rather than a category that meaningfully encodes colour, so
* rotating through a categorical palette adds visual noise without
* carrying signal. Consumers that genuinely want per-bar colouring
* (a categorical axis where each bar IS a category with semantic
* meaning) should use `<lib-donut-chart>` instead, or pass an
* explicit `fillColor` if they really do want a different shade.
*
* Per the lib's a11y contract:
* - outer `<figure>` carries `role="img"` + `aria-labelledby` +
* `aria-describedby`,
* - SVG gets `<title>` + `<desc>` prepended (Plot doesn't emit
* them; the helper in `_internal/a11y.ts` does),
* - `<details>` disclosure with a `<table>` fallback ships every
* data point in a screen-reader-friendly form,
* - fill defaults to `DEFAULT_BAR_FILL` from
* `_internal/palette.ts` (a colour-blind-safe blue),
* - `prefers-reduced-motion` skips transitions.
*/
export interface BarChartInputs<T> extends ChartBaseInputs<T> {
/** Key in `T` whose value provides the X-axis category. */
readonly xKey: keyof T & string;
/** Key in `T` whose value provides the bar height. */
readonly yKey: keyof T & string;
/** Human-readable axis labels (no implicit i18n inside the lib). */
readonly xLabel?: string;
readonly yLabel?: string;
/**
* Override the default single fill colour. Caller-owned — keep it
* colour-blind-safe and contrasted against the surrounding surface.
* Most consumers should leave it unset and accept the lib default.
*/
readonly fillColor?: string;
}
@Component({
selector: 'lib-bar-chart',
templateUrl: './bar-chart.html',
styleUrl: './bar-chart.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
// Plot renders into a host SVG outside Angular's template
// (imperatively appended via `nativeElement.append(...)`). We
// disable view encapsulation so the lib's stylesheet (axis ticks,
// dark-mode tokens) applies to that injected DOM.
encapsulation: ViewEncapsulation.None,
})
export class BarChart<T extends Record<string, unknown>> {
private readonly host = inject(ElementRef<HTMLElement>);
readonly data = input.required<readonly T[]>();
readonly xKey = input.required<keyof T & string>();
readonly yKey = input.required<keyof T & string>();
readonly caption = input.required<string>();
readonly description = input.required<string>();
readonly ariaLabel = input.required<string>();
readonly xLabel = input<string | undefined>(undefined);
readonly yLabel = input<string | undefined>(undefined);
readonly fillColor = input<string>(DEFAULT_BAR_FILL);
protected readonly chartId = chartId();
protected readonly titleId = `${this.chartId}-title`;
protected readonly descId = `${this.chartId}-desc`;
/** Tabular fallback rendered under `<details>`. One row per datum. */
protected readonly tableRows = computed(() =>
this.data().map((row) => ({
x: String(row[this.xKey()]),
y: Number(row[this.yKey()]),
})),
);
constructor() {
// Re-render whenever any input that affects the visual changes.
// Plot's `Plot.plot()` returns a fresh DOM node each call — we
// replace the previous one in the host's `.chart-canvas`.
effect(() => {
this.renderPlot();
});
}
private renderPlot(): void {
const canvas = (this.host.nativeElement as HTMLElement).querySelector<HTMLDivElement>(
'.chart-canvas',
);
if (!canvas) {
return;
}
const data = this.data();
const xKey = this.xKey();
const yKey = this.yKey();
const xLabel = this.xLabel() ?? null;
const yLabel = this.yLabel() ?? null;
const fill = this.fillColor();
const plot = Plot.plot({
// Mirrors the host element's available width so the chart is
// responsive. Plot computes a sensible height from the mark.
width: canvas.clientWidth || 600,
marginLeft: 56,
marginBottom: 40,
x: { label: xLabel, type: 'band' },
y: { label: yLabel, grid: true, nice: true },
marks: [
Plot.barY(data as Plot.Data, {
x: xKey,
y: yKey,
// Literal-string fill — Plot interprets non-key strings as
// a fixed colour. Same shade on every bar, by design.
fill,
// Plot's default tooltip would require interaction wiring
// we haven't shipped yet — the tabular fallback under
// `<details>` is the v1 substitute for hover values.
}),
Plot.ruleY([0]),
],
// Plot's CSS-in-style inline output respects our dark-mode
// tokens via the host stylesheet (.chart-canvas .plot-d6a7b1).
});
// Honor the a11y contract — prepend <title> + <desc> to the
// inner SVG before swapping it into the canvas, so screen
// readers see them on first render rather than after a re-
// attach. `findChartSvg` handles both Plot return shapes (bare
// SVG or <figure> wrapping a legend + SVG).
const svg = findChartSvg(plot);
if (svg) {
injectSvgTitleDesc(svg, this.caption(), this.description());
}
if (prefersReducedMotion()) {
plot.setAttribute('data-no-transitions', '');
}
canvas.replaceChildren(plot);
}
}