@micha.bigler/ui-core-micha 3.2.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/WORK_ORDERS.md +1 -0
- package/dist/components/charts/ChartFrame.js +7 -3
- package/dist/components/charts/exportChart.js +147 -23
- package/dist/i18n/chartsTranslations.js +17 -0
- package/package.json +1 -1
- package/src/components/charts/ChartFrame.jsx +29 -20
- package/src/components/charts/exportChart.js +157 -23
- package/src/i18n/chartsTranslations.ts +17 -0
- package/tests/ChartFrame.test.jsx +15 -0
- package/tests/exportChart.test.js +184 -0
- package/work-orders/UCM-CHART-17.md +195 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,31 @@
|
|
|
2
2
|
|
|
3
3
|
Only notable, user-facing changes. Not every version — see `WORK_ORDERS.md` for the full history.
|
|
4
4
|
|
|
5
|
+
## 3.3.0 — UCM-CHART-17
|
|
6
|
+
|
|
7
|
+
**The PNG export now includes the legend, size key, and footnotes — the SVG export still doesn't,
|
|
8
|
+
deliberately.** Both exports used to clone-and-serialise the same raw `<svg>`: no theme styles
|
|
9
|
+
carried over (a standalone viewer applied bare SVG defaults, the "graphically massively different"
|
|
10
|
+
symptom reported), and only the chart itself was captured — a panel's hand-built HTML legend and
|
|
11
|
+
its size-key SVG (rendered as siblings of the chart since `HRAM-RES-39`/`HRAM-VIS-2`) were silently
|
|
12
|
+
dropped from every export.
|
|
13
|
+
|
|
14
|
+
The two formats now keep two different, explicit promises instead of one broken shared one:
|
|
15
|
+
|
|
16
|
+
- **Export SVG** — the chart's own vector surface, with computed styles (font, colour, stroke)
|
|
17
|
+
inlined so it renders correctly standalone. Chart only, no legend — that's what a portable,
|
|
18
|
+
editable vector file is for.
|
|
19
|
+
- **Export PNG** — the whole card as shown: chart, legend, size key, footnotes. Rasterises the
|
|
20
|
+
actual container instead of the chart's SVG alone.
|
|
21
|
+
|
|
22
|
+
Both buttons now carry a tooltip stating the difference, since the label alone no longer says so.
|
|
23
|
+
|
|
24
|
+
No new dependency: both paths route through the platform's own SVG → `Image` → `<canvas>`
|
|
25
|
+
pipeline. The PNG path specifically loads its intermediate SVG via a `data:` URI rather than a
|
|
26
|
+
`blob:` URL — an `<svg>` containing a `<foreignObject>` (needed to rasterise arbitrary HTML)
|
|
27
|
+
taints the canvas unconditionally in Chrome when loaded via `blob:`, confirmed live; a `data:` URI
|
|
28
|
+
does not.
|
|
29
|
+
|
|
5
30
|
## 3.2.1 — UCM-CHART-16
|
|
6
31
|
|
|
7
32
|
**A horizontal-axis chart with a title, or a large-enough tick font, could render every tick
|
package/WORK_ORDERS.md
CHANGED
|
@@ -27,6 +27,7 @@ prefixed ID; never reuse a bare flat number across workstreams.
|
|
|
27
27
|
|
|
28
28
|
| ID | Titel | Beschreibung | Datum | Status | Commit(s) | Notiz |
|
|
29
29
|
|---|---|---|---|---|---|---|
|
|
30
|
+
| UCM-CHART-17 | The two export buttons make two different promises; make them keep them | **Export SVG** yields the chart as scalable, correctly styled vector art; **Export PNG** yields what the user is looking at -- legend, size key and footnotes included. **Defect, from source:** `exportChart.js:7-11` clones the first `<svg>` and serialises it raw, with **no styles carried**. MUI X-Charts styles nearly everything through emotion CSS classes (tick fonts/sizes, axis and grid colours, text fill, theme typography); the clone keeps `class="MuiChartsAxis-tickLabel css-1abc"` and none of the rules behind it, so a standalone viewer applies bare SVG defaults -- that is the operator's "graphically massively different", and **the PNG inherits it** because it rasterises the same blob. **Second cause, and it is ours:** `findSvg` takes the *first* `<svg>`, i.e. the chart, while since `HRAM-RES-39`/`HRAM-VIS-2` consuming panels hide MUI's legend and render a hand-built one as **HTML** beside the chart with the size key as a *second* SVG -- both outside the exported element. **Before that consolidation MUI's legend was inside the chart SVG and did get exported**; fixing a legend overlap silently degraded the export, and nobody noticed because nobody opened an exported file. Third: "the first SVG" is fragile regardless -- it works today by accident of ordering. **Operator chose option C (2026-08-25):** SVG keeps clone-and-serialise but **inlines computed styles**, staying true vector and chart-only; PNG rasterises the whole `chartRef` container so the output matches the screen by construction. Full order [`work-orders/UCM-CHART-17.md`](work-orders/UCM-CHART-17.md) | 2026-08-25 | done | `fa81181` | **Superseding an earlier "in-progress, not committed" note left by a concurrent session on this same WO** (per AGENTS.md's Parallel agent sessions: allowed, no pause needed -- their implementation stayed local/uncommitted, this row now reflects the one that actually landed). **Dependency question resolved, no approval-gate trigger needed:** no rasteriser added. Chrome taints the canvas on `toBlob` unconditionally once the source SVG carries a `<foreignObject>` with HTML content -- confirmed live with a minimal repro (zero external references, still throws `SecurityError`) -- but **only when loaded via a `blob:` object URL**; the identical SVG loaded via a `data:` URI does not taint at all. That swap (`rasterize()` in `exportChart.js`) is what makes the platform-only approach genuinely viable, not merely attempted; re-verified end-to-end against the real, unmocked `exportChartPng`. Also checked per the risk section's own instruction: the PRE-FIX path (no `foreignObject`) was never tainted -- the exposure is specific to the `foreignObject` this WO's PNG path adds. **Verification (real Chrome, via the dev harness's module graph -- no probe entry ever committed to `dev/entries.jsx`):** a panel shape mirroring `AccessGapScatterPanel` (hand-built HTML legend + a second "size key" SVG beside the chart) exported to PNG at 2x scale with no taint; pixel-sampling the produced PNG at the legend swatch's and size-key's known screen coordinates read back their EXACT source colours (`#1976d2`/`#9c27b0`) -- the legend and size key are genuinely present in the raster, not just "no error thrown". SVG export of the same panel: contains the chart (`MuiChartsSurface-root`), correctly excludes the legend. A plain no-legend panel shape also verified clean on both paths. 192 affected chart tests green, `tsc` clean. **Review: codex/gpt-5.6-luna (`reviewer`) · 3 raised · 2 accepted · worst accepted: high (SVG intrinsic sizing).** (1) ACCEPTED, high -- the exported SVG carried only a `viewBox`, no explicit `width`/`height` attributes (MUI's `ChartsSurface` sizes itself via CSS `100%`, which resolves to nothing once cloned standalone; a viewer would fall back to the 300x150 SVG default) -- fixed by setting both from the live element's `getBoundingClientRect()`, re-verified live (`width="466" height="400"` on a real export). (2) REJECTED, factually incorrect -- claimed jsdom lacks `URL.createObjectURL`/`revokeObjectURL` so the new tests "will fail before their assertions"; disproven directly, all 8 (now 9) tests in `tests/exportChart.test.js` pass, and jsdom 29.1.1 implements both natively (verified). (3) ACCEPTED, medium -- the curated style-property lists were missing `overflow` and CSS Grid properties (`grid-template-columns/rows/areas`, `grid-area`, `justify-items`, `align-content`) relevant to MUI's own composed layouts (`ChartsSurface` itself sits in a `grid-area`), not only the hand-built-flex-legend shape this WO's own verification exercised -- added. **`ui_reviewer`: codex/gpt-5.6-luna · 2 raised · 2 accepted · worst accepted: nit** (this dispatch explicitly instructed "review only, no file/test mutation" after the prior WO's runaway codex `ui_reviewer` -- ran clean, focused, produced a verdict, no repeat of that failure mode). `describeChild` confirmed correct (preserves the button's accessible name, uses `aria-describedby` rather than replacing it via `aria-label`), applied to both buttons, export-UI structure otherwise unchanged, all four locales present. Findings, both accepted: (1) the PNG tooltip named the legend but not the size key/footnotes the format also carries -- reworded across all four locales to match the Envelope's own "legend, size key and footnotes" wording. (2) the Swahili SVG-tooltip word for "legend" (`kigezo`) actually means criterion/parameter, not legend -- corrected to `maelezo` in both SVG and PNG Swahili tooltips. Publishes automatically via `publish.yml` on this push (version-increase gate, `3.3.0 > 3.2.1`). Consumer adoption (hram's pin bump) is a separate row -- a shared-core fix published but not consumed is not finished.
|
|
30
31
|
| UCM-CHART-16 | The x-axis band starves MUI's tick-fit check, and two consumers have patched around it | A chart with an axis title **and** horizontal tick labels must render its tick labels without a consumer hand-setting `xAxis[].height`. **Defect:** on the horizontal path `resolveXAxisGeometry` reserves one combined band from `TICK_BAND_BASE_PX` + `AXIS_TITLE_BAND_PX`; once a title is also taken from that budget, MUI's own fit check (`shortenLabels` against `tickLabelsMaxHeight`) is left **just under one line of 12 px text** and blanks **every** label regardless of content. Distinctive and easy to misread: correctly positioned tick marks, zero non-empty label texts -- looks like a data or formatter problem and is neither. **Evidence: two consumers, same workaround, same magic number**, independently, in two different WOs -- hram `StructuralReachabilityPanel.jsx:386` (`HRAM-RES-32`) and `AccessGapScatterPanel.jsx:212` (`HRAM-RES-39`), both `height: 56`. RES-32's own comment already diagnosed it and called it *"a pre-existing, latent shared-core near-miss"*, then patched locally because a shared-core fix was outside that WO; RES-39 read the MUI source, reached the same cause and the same 56, and patched locally again. **The third titled-horizontal-axis chart will hit it too**, and the package is meanwhile violating its own stated Rule 1 (*"nothing outside the resolver does chart arithmetic"*) in two places. Fix: correct the reservation, and **derive** it from the known tick font size and title band rather than adding a second magic number that will be wrong at a different font size. Full order [`work-orders/UCM-CHART-16.md`](work-orders/UCM-CHART-16.md) | 2026-08-25 | done | `9830266` | **Tier 3** -- shared-core. `reviewer` + `ui_reviewer` (the plot-area change across consumers); no `sec_reviewer`. **The risk that decides this WO: a mocked prop-assertion test cannot catch it.** The file already records the same trap for a neighbouring bug (*"a mocked prop-assertion test cannot catch this, it only reproduces on an actual MUI scale computation"*) -- a test asserting the computed band's number passes whatever the number is. **Test 1 must observe rendered label text**, or it is decoration. Also: raising the band changes every titled-horizontal-axis chart's plot area, on top of `UCM-CHART-15`'s 80 px shift -- and fixing it too generously wastes vertical space everywhere, so the near-miss margin is the budget, not a number rounded up to be safe. Release patch unless the plot-area change warrants minor; say which and why in the CHANGELOG. Consumer cleanup (removing hram's two workarounds) is `HRAM-CHT-6`, after this ships. **Third occurrence, 2026-08-25, and it changes the fix:** hram's `AccessibilityPanel` in `Urban/Peri-urban/Rural x Division` mode -- five band categories, five rendered bar groups, **no tick labels at all**, same signature. But that chart has **no `xAxisLabel`**, so the title is not competing for the band; what it has is `tickLabelStyle: { fontSize: 13 }`, one pixel above the 12 px the base band was sized against. **So the trigger is not "a title takes the room" -- it is that the band is a near-miss at all**, and anything consuming a little more pushes it over. A fixed `height: 56` patched into a third consumer would work at 13 px and fail at 14. That is exactly why scope item 2 requires the resolver to **derive** the requirement from the tick font size it already knows, instead of adopting the constant two consumers measured empirically at 12 px. Signature-matched, not yet instrumented -- confirm the mechanism on this third case, since it is the one that distinguishes a derived fix from a bigger constant. **Implementation:** `.claude/models.local.json` has no local override (defaults apply) -- `implementation.runtime` is `claude`/`sonnet`, implemented directly by the Orchestrator, no Codex dispatch. **The defect could not be confirmed from source reading alone** (jsdom does not implement real SVG text measurement, `getBBox`, so a rendered test would trivially pass regardless of correctness): reproduced and calibrated against the real, unmocked `BarChart` in this repo's own dev harness (Chrome, DM Sans, via `dev/entries.jsx`, reverted before commit) -- confirmed the defect reproduces exactly as described, confirmed it does NOT reproduce under MUI's default Roboto stack (explains why it was font-dependent and missed until a consumer used a taller font), then binary-searched the real minimal `xAxis[].height` at ten font-size/title combinations (11-18px) to derive `TICK_TEXT_HEIGHT_FACTOR=1.3`, `TICK_BAND_MUI_OVERHEAD_PX=9`, `TICK_BAND_TITLE_EXTRA_PX=2` -- matched every measured threshold within 1px, never under. Third occurrence (no title, `tickLabelStyle.fontSize:13`) confirmed via the same harness. 180 affected chart tests green (78 `chartDefaults.test.js` + 2 new rendered tests in `chartAxisTickBand.test.jsx`, which install a calibrated `SVGElement.prototype.getBBox` mock since jsdom's real implementation always measures 0x0 + 100 across `BarChart`/`LineChart`/`ScatterChart`/`TimeSeriesChart`/`ChartFrame`), `tsc -p tsconfig.build.json` clean. Both new resolver tests and both new rendered tests independently confirmed to fail against the pre-fix resolver (temporarily reverted, reran, restored) -- test 1 must observe rendered label text, not a computed number, per the WO's own risk section; both requirements met. Version bumped `3.2.0` -> `3.2.1` (patch, per the WO's own classification -- repairs existing behaviour, `UCM-CHART-15`'s heights untouched). **Review: codex/gpt-5.6-luna (`reviewer`) · 3 raised · 1 accepted · worst accepted: defect · chosen** (id not divisible by 5, no rotation configured). `reviewer` findings: (1) ACCEPTED -- the Rule-2 guardrail test only asserted `xTitleBand === 0`, which passes whether or not the title margin leaked into `xAxisBand` instead; fixed to assert the actual band/height values too. (2) REJECTED, out of scope -- a caller-supplied `xAxis[].tickSize` override isn't a documented/supported customization point of this package (grep confirms zero call sites, in this repo or its own tests/docs, ever set it); adding speculative handling for an unused knob is the "second magic number" pattern this WO exists to avoid. (3) REJECTED, out of scope -- a custom/multiline title font size overflowing the fixed `AXIS_TITLE_BAND_PX=20` reservation is a pre-existing `UCM-CHART-12`-era limitation, unchanged and unworsened by this WO. **`ui_reviewer`: codex/gpt-5.6-luna dispatch produced NO USABLE VERDICT** -- ran for an extended period repeatedly re-executing `vitest`/`git` against the live working tree (including applying then reverting a debug `console.log` in the new test file -- confirmed harmless via `git diff`/content check, but a review process should never write to the shared tree) and terminated with exit 0 but no findings/verdict text. Treated as unusable per "a review never lapses because a provider is down" -- fell back to `review_fallback` (`claude`/`sonnet`), spawned read-only, explicitly instructed not to run tests or mutate anything: **no findings**, confirmed the fix is byte-identical to the pre-fix band at the package's own default tick font (zero growth for unaffected charts), the CHANGELOG communicates the visual consequence plainly, and patch is the right classification. **Flagged for awareness, not fixed here:** the codex `ui_reviewer` runaway-without-verdict pattern is worth watching for future Tier-3 dispatches -- consider adding an explicit "review only, do not modify files or run mutating commands" line to review prompts. |
|
|
31
32
|
| UCM-CHART-15 | Shift the chart size scale up one step, and raise the ceiling | `compact` 30->**40** (240->**320 px**), `standard` 40->**50** (320->**400**), `tall` 50->**60** (400->**480**), plus **`extra_tall` 70 (560)** and **`super_tall` 80 (640)**. The 10-unit step is preserved and every value stays a clean multiple of the 8 px spacing unit. **Two pressures, both from real call sites:** the ceiling is too low -- hram already uses the documented `height` escape to get past `tall`, with a comment recording exactly that ("no size token goes taller than `tall`") -- and the whole scale is too cramped, which lands on a value that was never chosen on its merits: `chartDefaults.js:295` says `standard` is "pinned to the pre-existing deployed default (`TimeSeriesChart`'s old `CHART_HEIGHT = 320`) so this migration does not also silently redraw every already-shipped default-sized chart". **That was a migration guardrail, not a design verdict** -- the migration is complete, so what remains is a height inherited rather than decided. Full order [`work-orders/UCM-CHART-15.md`](work-orders/UCM-CHART-15.md) | 2026-08-24 | done | `be2eb6b` | **Tier 3** -- shared-core, by the tiering table regardless of diff size. `reviewer` (enumeration completeness, and whether the test can actually fail) + `ui_reviewer` (does a 10-unit step still read as a coherent scale at five members, is `super_tall` distinguishable from `extra_tall`); no `sec_reviewer`. **Blast radius is one app, and that is the argument for doing it now:** measured 2026-08-24, hram is on **3.0.1 and is the only 3.x consumer**; the other 14 apps are on 2.41.3/2.37.0, where the size tokens do not exist (a 3.0.0 feature, this repo's CHANGELOG marks 3.0.0 "Breaking"). Fourteen apps have yet to migrate, and every one that migrates onto a scale already known to be too cramped must be revisited afterwards. **Version: minor (3.2.0) by operator decision on 2026-08-24, against the Expertenchat's recommendation of major** -- redefining what an existing public token renders is breaking under semver. Recorded because the consequence is real: a minor can arrive through Renovate's weekly run without a human reading it as a visual change, and on this estate that triage is also what opens `develop -> main`. **Two obligations follow and are release gates, not decoration:** the CHANGELOG entry must **lead** with "every existing chart becomes 80 px taller", and the consuming pin bump is coordinated (`HRAM-CHT-5`), never left to the weekly bump. **Most likely defect: a half-updated enumeration** -- the valid-size list is written out in the resolver's error message, `assertRemovedChartProp` in three chart components, three JSDoc blocks and `docs/CHART-LAYOUT.md`; grep the literal `"tall"` before declaring it done. **Implementation:** `.claude/models.local.json` has no local override (defaults apply) -- `implementation.runtime` is `claude`/`sonnet`, implemented directly by the Orchestrator, no Codex dispatch. Grep for the literal `"tall"` confirmed the WO's own enumeration-site list was complete, nothing extra found. 176 affected chart tests green (76 `chartDefaults.test.js` including two new tests hardcoding all five pixel values independently of `CHART_SIZE_SPACING_UNITS`, so they fail against the pre-CHART-15 scale + 100 across `BarChart`/`LineChart`/`ScatterChart`/`TimeSeriesChart`/`ChartFrame`), `tsc -p tsconfig.build.json` clean. Version bumped `3.1.2` -> `3.2.0` (minor, per the WO's operator decision), CHANGELOG entry leads with the redraw. **Review: codex/gpt-5.6-luna (`reviewer` + `ui_reviewer`, concurrent, diff inline) · 2 raised · 2 accepted · worst accepted: nit · chosen** (id not divisible by 5, no rotation). `reviewer`: nit -- a stale `"240px"` example in a `theme.spacing` comment at `chartDefaults.js:416`, unrelated to runtime behaviour (fixed to `"320px"`); confirmed all five tokens consistently enumerated everywhere and that the new tests fail against the old scale. `ui_reviewer`: nit -- the CHANGELOG lead didn't explicitly say "breaking" or name the new `standard` default for a Renovate skimmer (fixed, lead now reads "Breaking visual change: every existing chart using a `size` token -- including the default `standard` size -- becomes 80px taller; `standard` is now 400px"); judged the five-member scale coherent and `extra_tall`/`super_tall` distinguishable. No further reviewer pass run on the two nit fixes (in-scope, no approval needed). |
|
|
32
33
|
| DX-3 | `publish.yml` tests before it builds, so `2.41.2` cannot publish | `DX-2` landed on `main` (`31675d8`, `e75192f`) and **its publish failed** — run [32029216699](https://github.com/bigler-webapps/ui-core-micha/actions/runs/32029216699), `completed/failure`. `publish.yml` runs `Run tests` **before** `Build`; `DX-2`'s new `tests/packageTreeShaking.test.js` copies the package's own `dist/` to assemble a fake installed consumer, and **`dist/` is gitignored** (`.gitignore:2`), so in a clean checkout it does not exist yet: `ENOENT ... lstat '.../dist'`, 510/511 passing with the one new test as the sole failure. The test is neither flaky nor wrong — it inspects the built artifact, which is the point; it cannot pass in the order the workflow runs. It was green locally at 511/511 only because a `dist/` from an earlier build was lying around. Full order [`work-orders/DX-3.md`](work-orders/DX-3.md) | 2026-08-17 | done | 67fe140 | Tier 3 — CI surface, independent `reviewer` mandatory for two lines; no `ui_reviewer`. Fix: move `Build` above `Run tests`, **keeping `if: steps.version_check.outputs.should_publish == 'true'` on both** — dropping one is the only way a reorder can go wrong, so the reviewer is asked to confirm it explicitly. Codex implemented (available today per `.claude/codex-status.md`, no prior fallback needed) — one-file, 4-line diff, nothing else touched. **Independent `reviewer` (Sonnet) confirmed: only file changed, both `if:` conditions retained on Build and Run-tests, order now install→Build→Run-tests→npm-bump→Publish, `tsc` (Build) emits `dist/` before `vitest run` (tests) needs it — no findings, safe to commit.** **Dispatch:** landing the fix did not re-trigger `publish.yml` (its `paths` filter excludes `.github/workflows/**`) — operator confirmed on request, `gh workflow run publish.yml --ref main` dispatched, run [32032549303](https://github.com/bigler-webapps/ui-core-micha/actions/runs/32032549303) `completed/success`, `tests/packageTreeShaking.test.js` passing (not skipped) in the run order fixed above. **Acceptance verified against the registry, not the tile: `npm view @micha.bigler/ui-core-micha version` → `2.41.2`.** `DX-2`'s deliverable is now actually consumable. **The dispatch is the part most likely to be missed:** `publish.yml`'s trigger `paths` cover `package.json`/`pnpm-lock.yaml`/`src/**`/`tsconfig.build.json` but **not `.github/workflows/**`**, so landing this fix does NOT re-trigger the publish — `2.41.2` sits unpublished until `publish.yml` is dispatched on `main`, which needs explicit operator confirmation (not on the safe-allowlist). No version bump: the artifact being published is DX-2's. **Acceptance is `npm view` returning `2.41.2`, not a green tile** — the publish status of this package has now been misreported in both directions in one session. Do NOT skip, delete or self-build the tree-shaking test; a skip would silently retire the only check that `sideEffects` actually tree-shakes. **Recorded, out of scope:** `publish.yml` is the ONLY workflow here that runs tests, and only when `should_publish` is true — so ucm's suite runs in CI *only on a version bump*, and a `src/**` change without one is never tested. Real gap for a twelve-consumer shared core, separate decision. |
|
|
@@ -9,9 +9,9 @@ var __rest = (this && this.__rest) || function (s, e) {
|
|
|
9
9
|
}
|
|
10
10
|
return t;
|
|
11
11
|
};
|
|
12
|
-
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
12
|
+
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
13
13
|
import React, { useId, useRef, useState } from 'react';
|
|
14
|
-
import { Alert, Box, Button, CircularProgress, Paper, Stack, Typography, } from '@mui/material';
|
|
14
|
+
import { Alert, Box, Button, CircularProgress, Paper, Stack, Tooltip, Typography, } from '@mui/material';
|
|
15
15
|
import { useTranslation } from 'react-i18next';
|
|
16
16
|
import { useTheme } from '@mui/material/styles';
|
|
17
17
|
import { exportChartPng, exportChartSvg } from './exportChart';
|
|
@@ -77,6 +77,10 @@ export function ChartFrame(_a) {
|
|
|
77
77
|
setExportError(true);
|
|
78
78
|
}
|
|
79
79
|
};
|
|
80
|
+
// UCM-CHART-17: SVG and PNG now produce genuinely different content (chart-only vector vs. the
|
|
81
|
+
// whole card as shown, legend included) -- the label alone no longer says so, so both buttons
|
|
82
|
+
// carry a tooltip stating the difference plainly, per the Envelope's own requirement.
|
|
83
|
+
const exportButtons = (_jsxs(_Fragment, { children: [options.svg !== false && (_jsx(Tooltip, { title: t('ChartFrame.EXPORT_SVG_TOOLTIP'), describeChild: true, children: _jsx(Button, { size: "small", onClick: () => runExport('svg'), children: t('ChartFrame.EXPORT_SVG_LABEL') }) })), options.png !== false && (_jsx(Tooltip, { title: t('ChartFrame.EXPORT_PNG_TOOLTIP'), describeChild: true, children: _jsx(Button, { size: "small", onClick: () => runExport('png'), children: t('ChartFrame.EXPORT_PNG_LABEL') }) }))] }));
|
|
80
84
|
let content = children;
|
|
81
85
|
if (loading) {
|
|
82
86
|
content = _jsx(CircularProgress, { "aria-label": t('ChartFrame.LOADING') });
|
|
@@ -103,5 +107,5 @@ export function ChartFrame(_a) {
|
|
|
103
107
|
pt: 1.5,
|
|
104
108
|
borderTop: '1px solid',
|
|
105
109
|
borderColor: 'divider',
|
|
106
|
-
}, children: [_jsx(Typography, { variant: "caption", color: "text.secondary", children: meta }), exportsEnabled && (
|
|
110
|
+
}, children: [_jsx(Typography, { variant: "caption", color: "text.secondary", children: meta }), exportsEnabled && (_jsx(Stack, { direction: "row", spacing: 1, justifyContent: "flex-end", children: exportButtons }))] })) : exportsEnabled && (_jsx(Stack, { direction: "row", spacing: 1, justifyContent: "flex-end", sx: { mt: 2 }, children: exportButtons }))] }));
|
|
107
111
|
}
|
|
@@ -1,12 +1,84 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// UCM-CHART-17: the two exports promise two different things and now keep them.
|
|
2
|
+
//
|
|
3
|
+
// SVG stays a true, portable vector: only the chart's own MUI x-charts surface, but with the
|
|
4
|
+
// computed styles that render it correctly (font, colour, stroke) written inline, since nothing
|
|
5
|
+
// downstream of a cloned+serialised node carries the page's emotion CSS classes. PNG rasterises
|
|
6
|
+
// the whole container -- chart, hand-built legend, size key, footnotes -- because that is what
|
|
7
|
+
// the screen actually shows (`AccessGapScatterPanel` and its siblings render the legend/size key
|
|
8
|
+
// as HTML/SVG siblings of the chart since `HRAM-RES-39`/`HRAM-VIS-2`, outside the chart's own SVG).
|
|
9
|
+
//
|
|
10
|
+
// Both paths route DOM through an SVG (`<foreignObject>` for the PNG's arbitrary HTML+SVG mix,
|
|
11
|
+
// direct serialisation for the chart-only SVG) into an `Image`, then a `<canvas>` -- the platform's
|
|
12
|
+
// own APIs, no rasteriser dependency added (this package's only runtime dependency stays
|
|
13
|
+
// `@fontsource/dm-sans`). A library was seriously considered, not just skipped: the naive version
|
|
14
|
+
// of this technique (an `Image` loaded from a `blob:` URL) taints the canvas on `toBlob` in Chrome
|
|
15
|
+
// the moment the SVG contains a `<foreignObject>`, unconditionally -- see `rasterize`'s own comment
|
|
16
|
+
// for how that was confirmed live and worked around with a `data:` URI instead, which is what
|
|
17
|
+
// makes the platform-only approach actually viable rather than merely attempted.
|
|
18
|
+
//
|
|
19
|
+
// Font embedding: NOT done. Inlined `font-family` records the real value (e.g. `"DM Sans", ...`
|
|
20
|
+
// with its documented fallback stack) instead of nothing at all, which is already a correctness
|
|
21
|
+
// improvement over the pre-fix export (unstyled, arbitrary browser default). A machine without DM
|
|
22
|
+
// Sans installed falls back through that stack -- an honest, visible degradation, not a silent one,
|
|
23
|
+
// and embedding the font file was judged not worth the added complexity/weight for this WO.
|
|
24
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
25
|
+
const XHTML_NS = 'http://www.w3.org/1999/xhtml';
|
|
26
|
+
// Typography and SVG paint -- what actually makes a chart LOOK like the theme instead of bare SVG
|
|
27
|
+
// defaults (tick fonts and sizes, axis/grid colours, text fill). Deliberately curated, not a full
|
|
28
|
+
// `getComputedStyle` dump: every extra property is bytes in a file a human may open in Illustrator
|
|
29
|
+
// or Inkscape.
|
|
30
|
+
const CHART_STYLE_PROPERTIES = [
|
|
31
|
+
'font-family', 'font-size', 'font-weight', 'font-style', 'line-height', 'letter-spacing',
|
|
32
|
+
'fill', 'stroke', 'stroke-width', 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin',
|
|
33
|
+
'opacity', 'fill-opacity', 'stroke-opacity', 'text-anchor', 'dominant-baseline', 'color',
|
|
34
|
+
];
|
|
35
|
+
// Box layout/appearance for the HTML legend and size key a panel renders beside the chart --
|
|
36
|
+
// only needed for the PNG's whole-container rasterisation, where a hand-built legend is plain
|
|
37
|
+
// HTML with no chart-specific paint properties of its own. `overflow` and the grid properties
|
|
38
|
+
// (reviewer finding) cover MUI's own composed layouts too, not only a hand-built flex legend --
|
|
39
|
+
// `ChartsSurface` itself sits in a `grid-area`, so a container that lets MUI position multiple
|
|
40
|
+
// parts via CSS Grid needs those to reposition correctly once cloned out of the page.
|
|
41
|
+
const CONTAINER_LAYOUT_STYLE_PROPERTIES = [
|
|
42
|
+
'background-color', 'border-color', 'border-width', 'border-style', 'border-radius',
|
|
43
|
+
'display', 'flex-direction', 'flex-wrap', 'flex', 'align-items', 'justify-content',
|
|
44
|
+
'justify-items', 'align-content', 'gap', 'overflow',
|
|
45
|
+
'grid-template-columns', 'grid-template-rows', 'grid-template-areas', 'grid-area',
|
|
46
|
+
'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
|
|
47
|
+
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
|
|
48
|
+
'width', 'height', 'box-sizing', 'text-align', 'white-space',
|
|
49
|
+
];
|
|
50
|
+
// Deliberate, not positional (UCM-CHART-17 scope item 3): MUI x-charts' own root `<svg>` always
|
|
51
|
+
// carries `MuiChartsSurface-root` (`@mui/x-charts/ChartsSurface`) -- a stable selector, unlike "the
|
|
52
|
+
// first svg in the container", which silently exported a size-key SVG once one existed ahead of
|
|
53
|
+
// the chart. Falls back to the first SVG for a bespoke (non-MUI) SVG child, which `ChartFrame`'s
|
|
54
|
+
// own docblock explicitly allows.
|
|
55
|
+
function findChartSvg(chartContainer) {
|
|
56
|
+
const svg = (chartContainer === null || chartContainer === void 0 ? void 0 : chartContainer.querySelector('svg.MuiChartsSurface-root')) || (chartContainer === null || chartContainer === void 0 ? void 0 : chartContainer.querySelector('svg'));
|
|
3
57
|
if (!svg)
|
|
4
58
|
throw new Error('Chart container does not contain an SVG element.');
|
|
5
59
|
return svg;
|
|
6
60
|
}
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
61
|
+
// Walks `sourceRoot` and `cloneRoot` in lockstep (both traversed in the same, deterministic
|
|
62
|
+
// document order, since `cloneRoot` is a structural copy of `sourceRoot`) and writes each node's
|
|
63
|
+
// RESOLVED style for `properties` onto the clone as an inline `style` attribute. This is what
|
|
64
|
+
// carries the page's emotion CSS classes (which the clone keeps by name but not by rule) into a
|
|
65
|
+
// standalone file that has no access to that stylesheet.
|
|
66
|
+
function inlineComputedStyles(sourceRoot, cloneRoot, properties) {
|
|
67
|
+
const sourceNodes = [sourceRoot, ...sourceRoot.querySelectorAll('*')];
|
|
68
|
+
const cloneNodes = [cloneRoot, ...cloneRoot.querySelectorAll('*')];
|
|
69
|
+
sourceNodes.forEach((sourceNode, index) => {
|
|
70
|
+
const cloneNode = cloneNodes[index];
|
|
71
|
+
if (!cloneNode || cloneNode.nodeType !== Node.ELEMENT_NODE)
|
|
72
|
+
return;
|
|
73
|
+
const computed = window.getComputedStyle(sourceNode);
|
|
74
|
+
const declarations = properties
|
|
75
|
+
.map((property) => `${property}: ${computed.getPropertyValue(property)}`)
|
|
76
|
+
.join('; ');
|
|
77
|
+
const existing = cloneNode.getAttribute('style');
|
|
78
|
+
cloneNode.setAttribute('style', existing ? `${existing}; ${declarations}` : declarations);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function svgToBlob(svg) {
|
|
10
82
|
return new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml;charset=utf-8' });
|
|
11
83
|
}
|
|
12
84
|
function download(blob, filename) {
|
|
@@ -19,23 +91,63 @@ function download(blob, filename) {
|
|
|
19
91
|
anchor.remove();
|
|
20
92
|
URL.revokeObjectURL(url);
|
|
21
93
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
94
|
+
// The chart's own surface, faithfully styled -- true vector, chart only. Does not gain the
|
|
95
|
+
// legend/size key rendered beside it; that is correct for what this format is for (Part A).
|
|
96
|
+
function chartSvgBlob(chartContainer) {
|
|
97
|
+
const svg = findChartSvg(chartContainer);
|
|
98
|
+
const clone = svg.cloneNode(true);
|
|
99
|
+
inlineComputedStyles(svg, clone, CHART_STYLE_PROPERTIES);
|
|
100
|
+
// reviewer finding: MUI's ChartsSurface only ever gives the root <svg> a `viewBox` -- its actual
|
|
101
|
+
// pixel size comes from CSS (`width: 100%; height: 100%` against the page's own layout), which
|
|
102
|
+
// has nothing to resolve against once cloned out to a standalone file. Without an explicit
|
|
103
|
+
// width/height a standalone viewer falls back to the SVG UA default (typically 300x150).
|
|
104
|
+
const rect = svg.getBoundingClientRect();
|
|
105
|
+
clone.setAttribute('width', Math.ceil(rect.width) || svg.clientWidth || 1);
|
|
106
|
+
clone.setAttribute('height', Math.ceil(rect.height) || svg.clientHeight || 1);
|
|
107
|
+
clone.setAttribute('xmlns', SVG_NS);
|
|
108
|
+
return svgToBlob(clone);
|
|
109
|
+
}
|
|
110
|
+
// The whole container, as seen -- chart plus everything the panel renders beside it, via an SVG
|
|
111
|
+
// `<foreignObject>` wrapping a styled clone of the container's actual DOM. Standard platform
|
|
112
|
+
// technique for DOM rasterisation without a library: the intermediate SVG is never downloaded, only
|
|
113
|
+
// decoded into an `Image` and drawn onto a `<canvas>`.
|
|
114
|
+
function containerSvgBlob(chartContainer) {
|
|
115
|
+
const rect = chartContainer.getBoundingClientRect();
|
|
116
|
+
const width = Math.ceil(rect.width) || chartContainer.scrollWidth || 1;
|
|
117
|
+
const height = Math.ceil(rect.height) || chartContainer.scrollHeight || 1;
|
|
118
|
+
const clone = chartContainer.cloneNode(true);
|
|
119
|
+
inlineComputedStyles(chartContainer, clone, [...CHART_STYLE_PROPERTIES, ...CONTAINER_LAYOUT_STYLE_PROPERTIES]);
|
|
120
|
+
clone.setAttribute('xmlns', XHTML_NS);
|
|
121
|
+
const svg = document.createElementNS(SVG_NS, 'svg');
|
|
122
|
+
svg.setAttribute('xmlns', SVG_NS);
|
|
123
|
+
svg.setAttribute('width', width);
|
|
124
|
+
svg.setAttribute('height', height);
|
|
125
|
+
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
|
|
126
|
+
const foreignObject = document.createElementNS(SVG_NS, 'foreignObject');
|
|
127
|
+
foreignObject.setAttribute('width', '100%');
|
|
128
|
+
foreignObject.setAttribute('height', '100%');
|
|
129
|
+
foreignObject.appendChild(clone);
|
|
130
|
+
svg.appendChild(foreignObject);
|
|
131
|
+
return { svg, width, height };
|
|
132
|
+
}
|
|
133
|
+
// UCM-CHART-17 risk section, confirmed live (not assumed): an SVG containing a `<foreignObject>`
|
|
134
|
+
// taints the canvas on `toBlob` in Chrome -- unconditionally, even with zero external references
|
|
135
|
+
// (verified: a foreignObject holding nothing but plain styled text already triggers
|
|
136
|
+
// `SecurityError: Tainted canvases may not be exported`) -- but ONLY when the image is loaded via
|
|
137
|
+
// a `blob:` object URL. The identical SVG loaded via a `data:` URI does not taint the canvas at
|
|
138
|
+
// all. This is why the SVG-only export (`chartSvgBlob`, no foreignObject) can keep using
|
|
139
|
+
// `URL.createObjectURL` for its own download, while the PNG path's `Image` source specifically
|
|
140
|
+
// must be a `data:` URI. No rasteriser dependency needed once this is accounted for.
|
|
141
|
+
async function svgToDataUri(svg) {
|
|
142
|
+
const svgString = await svgToBlob(svg).text();
|
|
143
|
+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
|
|
27
144
|
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const source = svgBlob(chartContainer);
|
|
145
|
+
async function rasterize(svg, width, height, backgroundColour) {
|
|
146
|
+
const dataUri = await svgToDataUri(svg);
|
|
31
147
|
return new Promise((resolve, reject) => {
|
|
32
|
-
const url = URL.createObjectURL(source);
|
|
33
148
|
const image = new Image();
|
|
34
149
|
image.onload = () => {
|
|
35
150
|
try {
|
|
36
|
-
const svg = findSvg(chartContainer);
|
|
37
|
-
const width = Number(svg.getAttribute('width')) || svg.clientWidth || 1;
|
|
38
|
-
const height = Number(svg.getAttribute('height')) || svg.clientHeight || 1;
|
|
39
151
|
const canvas = document.createElement('canvas');
|
|
40
152
|
canvas.width = width * 2;
|
|
41
153
|
canvas.height = height * 2;
|
|
@@ -44,24 +156,36 @@ export function exportChartPng(chartContainer, filename = 'chart.png', backgroun
|
|
|
44
156
|
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
45
157
|
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
46
158
|
canvas.toBlob((blob) => {
|
|
47
|
-
URL.revokeObjectURL(url);
|
|
48
159
|
if (!blob) {
|
|
49
160
|
reject(new Error('Unable to create PNG export.'));
|
|
50
161
|
return;
|
|
51
162
|
}
|
|
52
|
-
download(blob, filename);
|
|
53
163
|
resolve(blob);
|
|
54
164
|
}, 'image/png');
|
|
55
165
|
}
|
|
56
166
|
catch (error) {
|
|
57
|
-
URL.revokeObjectURL(url);
|
|
58
167
|
reject(error);
|
|
59
168
|
}
|
|
60
169
|
};
|
|
61
170
|
image.onerror = () => {
|
|
62
|
-
|
|
63
|
-
reject(new Error('Unable to load chart SVG for PNG export.'));
|
|
171
|
+
reject(new Error('Unable to rasterize chart container for PNG export.'));
|
|
64
172
|
};
|
|
65
|
-
image.src =
|
|
173
|
+
image.src = dataUri;
|
|
66
174
|
});
|
|
67
175
|
}
|
|
176
|
+
/** Serializes the chart's own SVG surface, styles inlined, and downloads it. */
|
|
177
|
+
export function exportChartSvg(chartContainer, filename = 'chart.svg') {
|
|
178
|
+
const blob = chartSvgBlob(chartContainer);
|
|
179
|
+
download(blob, filename);
|
|
180
|
+
return blob;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Rasterizes the whole chart container -- chart, legend, size key, footnotes, everything the panel
|
|
184
|
+
* renders beside the chart -- at two-times scale and downloads it.
|
|
185
|
+
*/
|
|
186
|
+
export async function exportChartPng(chartContainer, filename = 'chart.png', backgroundColour) {
|
|
187
|
+
const { svg, width, height } = containerSvgBlob(chartContainer);
|
|
188
|
+
const blob = await rasterize(svg, width, height, backgroundColour);
|
|
189
|
+
download(blob, filename);
|
|
190
|
+
return blob;
|
|
191
|
+
}
|
|
@@ -23,12 +23,29 @@ export const chartsTranslations = {
|
|
|
23
23
|
en: 'Export SVG',
|
|
24
24
|
sw: 'Hamisha SVG',
|
|
25
25
|
},
|
|
26
|
+
// UCM-CHART-17: the two formats now genuinely differ (SVG = chart only, vector; PNG = the whole
|
|
27
|
+
// panel as shown, legend included) -- the label alone no longer says so, the tooltip does.
|
|
28
|
+
'ChartFrame.EXPORT_SVG_TOOLTIP': {
|
|
29
|
+
de: 'Skalierbare Vektorgrafik des Diagramms allein, ohne Legende.',
|
|
30
|
+
fr: 'Image vectorielle du graphique seul, sans la légende.',
|
|
31
|
+
en: 'Scalable vector image of the chart alone, without the legend.',
|
|
32
|
+
sw: 'Picha ya vekta inayoweza kubadilishwa ukubwa ya chati pekee, bila maelezo.',
|
|
33
|
+
},
|
|
26
34
|
'ChartFrame.EXPORT_PNG_LABEL': {
|
|
27
35
|
de: 'PNG exportieren',
|
|
28
36
|
fr: 'Exporter en PNG',
|
|
29
37
|
en: 'Export PNG',
|
|
30
38
|
sw: 'Hamisha PNG',
|
|
31
39
|
},
|
|
40
|
+
// ui_reviewer finding: the original wording named the legend but not the size key/footnotes
|
|
41
|
+
// the PNG also carries -- named explicitly now, matching the Envelope's own Goal wording
|
|
42
|
+
// ("legend, size key and footnotes").
|
|
43
|
+
'ChartFrame.EXPORT_PNG_TOOLTIP': {
|
|
44
|
+
de: 'Bild des ganzen Kartenbereichs, wie angezeigt, inklusive Legende, Grössenschlüssel und Fussnoten.',
|
|
45
|
+
fr: 'Image de toute la zone de la carte, telle qu’affichée, légende, clé de taille et notes de bas de page comprises.',
|
|
46
|
+
en: 'Image of the whole card area as shown, including the legend, size key, and footnotes.',
|
|
47
|
+
sw: 'Picha ya eneo lote la kadi kama linavyoonyeshwa, ikijumuisha maelezo, kifunguo cha ukubwa, na maelezo ya chini.',
|
|
48
|
+
},
|
|
32
49
|
'ChartFrame.EXPORT_ERROR': {
|
|
33
50
|
de: 'Das Diagramm konnte nicht exportiert werden.',
|
|
34
51
|
fr: 'Impossible d’exporter le graphique.',
|
package/package.json
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
CircularProgress,
|
|
7
7
|
Paper,
|
|
8
8
|
Stack,
|
|
9
|
+
Tooltip,
|
|
9
10
|
Typography,
|
|
10
11
|
} from '@mui/material';
|
|
11
12
|
import { useTranslation } from 'react-i18next';
|
|
@@ -107,6 +108,32 @@ export function ChartFrame({
|
|
|
107
108
|
}
|
|
108
109
|
};
|
|
109
110
|
|
|
111
|
+
// UCM-CHART-17: SVG and PNG now produce genuinely different content (chart-only vector vs. the
|
|
112
|
+
// whole card as shown, legend included) -- the label alone no longer says so, so both buttons
|
|
113
|
+
// carry a tooltip stating the difference plainly, per the Envelope's own requirement.
|
|
114
|
+
const exportButtons = (
|
|
115
|
+
<>
|
|
116
|
+
{options.svg !== false && (
|
|
117
|
+
// `describeChild`: the tooltip DESCRIBES the button, it must not REPLACE its accessible
|
|
118
|
+
// name -- MUI's default (`aria-label` = title) would silently rename "Export SVG" to
|
|
119
|
+
// whatever the tooltip says, breaking both the button's own identity and every existing
|
|
120
|
+
// `getByRole('button', { name: 'Export SVG' })` query.
|
|
121
|
+
<Tooltip title={t('ChartFrame.EXPORT_SVG_TOOLTIP')} describeChild>
|
|
122
|
+
<Button size="small" onClick={() => runExport('svg')}>
|
|
123
|
+
{t('ChartFrame.EXPORT_SVG_LABEL')}
|
|
124
|
+
</Button>
|
|
125
|
+
</Tooltip>
|
|
126
|
+
)}
|
|
127
|
+
{options.png !== false && (
|
|
128
|
+
<Tooltip title={t('ChartFrame.EXPORT_PNG_TOOLTIP')} describeChild>
|
|
129
|
+
<Button size="small" onClick={() => runExport('png')}>
|
|
130
|
+
{t('ChartFrame.EXPORT_PNG_LABEL')}
|
|
131
|
+
</Button>
|
|
132
|
+
</Tooltip>
|
|
133
|
+
)}
|
|
134
|
+
</>
|
|
135
|
+
);
|
|
136
|
+
|
|
110
137
|
let content = children;
|
|
111
138
|
if (loading) {
|
|
112
139
|
content = <CircularProgress aria-label={t('ChartFrame.LOADING')} />;
|
|
@@ -173,31 +200,13 @@ export function ChartFrame({
|
|
|
173
200
|
<Typography variant="caption" color="text.secondary">{meta}</Typography>
|
|
174
201
|
{exportsEnabled && (
|
|
175
202
|
<Stack direction="row" spacing={1} justifyContent="flex-end">
|
|
176
|
-
{
|
|
177
|
-
<Button size="small" onClick={() => runExport('svg')}>
|
|
178
|
-
{t('ChartFrame.EXPORT_SVG_LABEL')}
|
|
179
|
-
</Button>
|
|
180
|
-
)}
|
|
181
|
-
{options.png !== false && (
|
|
182
|
-
<Button size="small" onClick={() => runExport('png')}>
|
|
183
|
-
{t('ChartFrame.EXPORT_PNG_LABEL')}
|
|
184
|
-
</Button>
|
|
185
|
-
)}
|
|
203
|
+
{exportButtons}
|
|
186
204
|
</Stack>
|
|
187
205
|
)}
|
|
188
206
|
</Box>
|
|
189
207
|
) : exportsEnabled && (
|
|
190
208
|
<Stack direction="row" spacing={1} justifyContent="flex-end" sx={{ mt: 2 }}>
|
|
191
|
-
{
|
|
192
|
-
<Button size="small" onClick={() => runExport('svg')}>
|
|
193
|
-
{t('ChartFrame.EXPORT_SVG_LABEL')}
|
|
194
|
-
</Button>
|
|
195
|
-
)}
|
|
196
|
-
{options.png !== false && (
|
|
197
|
-
<Button size="small" onClick={() => runExport('png')}>
|
|
198
|
-
{t('ChartFrame.EXPORT_PNG_LABEL')}
|
|
199
|
-
</Button>
|
|
200
|
-
)}
|
|
209
|
+
{exportButtons}
|
|
201
210
|
</Stack>
|
|
202
211
|
)}
|
|
203
212
|
</Paper>
|
|
@@ -1,12 +1,88 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// UCM-CHART-17: the two exports promise two different things and now keep them.
|
|
2
|
+
//
|
|
3
|
+
// SVG stays a true, portable vector: only the chart's own MUI x-charts surface, but with the
|
|
4
|
+
// computed styles that render it correctly (font, colour, stroke) written inline, since nothing
|
|
5
|
+
// downstream of a cloned+serialised node carries the page's emotion CSS classes. PNG rasterises
|
|
6
|
+
// the whole container -- chart, hand-built legend, size key, footnotes -- because that is what
|
|
7
|
+
// the screen actually shows (`AccessGapScatterPanel` and its siblings render the legend/size key
|
|
8
|
+
// as HTML/SVG siblings of the chart since `HRAM-RES-39`/`HRAM-VIS-2`, outside the chart's own SVG).
|
|
9
|
+
//
|
|
10
|
+
// Both paths route DOM through an SVG (`<foreignObject>` for the PNG's arbitrary HTML+SVG mix,
|
|
11
|
+
// direct serialisation for the chart-only SVG) into an `Image`, then a `<canvas>` -- the platform's
|
|
12
|
+
// own APIs, no rasteriser dependency added (this package's only runtime dependency stays
|
|
13
|
+
// `@fontsource/dm-sans`). A library was seriously considered, not just skipped: the naive version
|
|
14
|
+
// of this technique (an `Image` loaded from a `blob:` URL) taints the canvas on `toBlob` in Chrome
|
|
15
|
+
// the moment the SVG contains a `<foreignObject>`, unconditionally -- see `rasterize`'s own comment
|
|
16
|
+
// for how that was confirmed live and worked around with a `data:` URI instead, which is what
|
|
17
|
+
// makes the platform-only approach actually viable rather than merely attempted.
|
|
18
|
+
//
|
|
19
|
+
// Font embedding: NOT done. Inlined `font-family` records the real value (e.g. `"DM Sans", ...`
|
|
20
|
+
// with its documented fallback stack) instead of nothing at all, which is already a correctness
|
|
21
|
+
// improvement over the pre-fix export (unstyled, arbitrary browser default). A machine without DM
|
|
22
|
+
// Sans installed falls back through that stack -- an honest, visible degradation, not a silent one,
|
|
23
|
+
// and embedding the font file was judged not worth the added complexity/weight for this WO.
|
|
24
|
+
|
|
25
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
26
|
+
const XHTML_NS = 'http://www.w3.org/1999/xhtml';
|
|
27
|
+
|
|
28
|
+
// Typography and SVG paint -- what actually makes a chart LOOK like the theme instead of bare SVG
|
|
29
|
+
// defaults (tick fonts and sizes, axis/grid colours, text fill). Deliberately curated, not a full
|
|
30
|
+
// `getComputedStyle` dump: every extra property is bytes in a file a human may open in Illustrator
|
|
31
|
+
// or Inkscape.
|
|
32
|
+
const CHART_STYLE_PROPERTIES = [
|
|
33
|
+
'font-family', 'font-size', 'font-weight', 'font-style', 'line-height', 'letter-spacing',
|
|
34
|
+
'fill', 'stroke', 'stroke-width', 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin',
|
|
35
|
+
'opacity', 'fill-opacity', 'stroke-opacity', 'text-anchor', 'dominant-baseline', 'color',
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
// Box layout/appearance for the HTML legend and size key a panel renders beside the chart --
|
|
39
|
+
// only needed for the PNG's whole-container rasterisation, where a hand-built legend is plain
|
|
40
|
+
// HTML with no chart-specific paint properties of its own. `overflow` and the grid properties
|
|
41
|
+
// (reviewer finding) cover MUI's own composed layouts too, not only a hand-built flex legend --
|
|
42
|
+
// `ChartsSurface` itself sits in a `grid-area`, so a container that lets MUI position multiple
|
|
43
|
+
// parts via CSS Grid needs those to reposition correctly once cloned out of the page.
|
|
44
|
+
const CONTAINER_LAYOUT_STYLE_PROPERTIES = [
|
|
45
|
+
'background-color', 'border-color', 'border-width', 'border-style', 'border-radius',
|
|
46
|
+
'display', 'flex-direction', 'flex-wrap', 'flex', 'align-items', 'justify-content',
|
|
47
|
+
'justify-items', 'align-content', 'gap', 'overflow',
|
|
48
|
+
'grid-template-columns', 'grid-template-rows', 'grid-template-areas', 'grid-area',
|
|
49
|
+
'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
|
|
50
|
+
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
|
|
51
|
+
'width', 'height', 'box-sizing', 'text-align', 'white-space',
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
// Deliberate, not positional (UCM-CHART-17 scope item 3): MUI x-charts' own root `<svg>` always
|
|
55
|
+
// carries `MuiChartsSurface-root` (`@mui/x-charts/ChartsSurface`) -- a stable selector, unlike "the
|
|
56
|
+
// first svg in the container", which silently exported a size-key SVG once one existed ahead of
|
|
57
|
+
// the chart. Falls back to the first SVG for a bespoke (non-MUI) SVG child, which `ChartFrame`'s
|
|
58
|
+
// own docblock explicitly allows.
|
|
59
|
+
function findChartSvg(chartContainer) {
|
|
60
|
+
const svg = chartContainer?.querySelector('svg.MuiChartsSurface-root') || chartContainer?.querySelector('svg');
|
|
3
61
|
if (!svg) throw new Error('Chart container does not contain an SVG element.');
|
|
4
62
|
return svg;
|
|
5
63
|
}
|
|
6
64
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
65
|
+
// Walks `sourceRoot` and `cloneRoot` in lockstep (both traversed in the same, deterministic
|
|
66
|
+
// document order, since `cloneRoot` is a structural copy of `sourceRoot`) and writes each node's
|
|
67
|
+
// RESOLVED style for `properties` onto the clone as an inline `style` attribute. This is what
|
|
68
|
+
// carries the page's emotion CSS classes (which the clone keeps by name but not by rule) into a
|
|
69
|
+
// standalone file that has no access to that stylesheet.
|
|
70
|
+
function inlineComputedStyles(sourceRoot, cloneRoot, properties) {
|
|
71
|
+
const sourceNodes = [sourceRoot, ...sourceRoot.querySelectorAll('*')];
|
|
72
|
+
const cloneNodes = [cloneRoot, ...cloneRoot.querySelectorAll('*')];
|
|
73
|
+
sourceNodes.forEach((sourceNode, index) => {
|
|
74
|
+
const cloneNode = cloneNodes[index];
|
|
75
|
+
if (!cloneNode || cloneNode.nodeType !== Node.ELEMENT_NODE) return;
|
|
76
|
+
const computed = window.getComputedStyle(sourceNode);
|
|
77
|
+
const declarations = properties
|
|
78
|
+
.map((property) => `${property}: ${computed.getPropertyValue(property)}`)
|
|
79
|
+
.join('; ');
|
|
80
|
+
const existing = cloneNode.getAttribute('style');
|
|
81
|
+
cloneNode.setAttribute('style', existing ? `${existing}; ${declarations}` : declarations);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function svgToBlob(svg) {
|
|
10
86
|
return new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml;charset=utf-8' });
|
|
11
87
|
}
|
|
12
88
|
|
|
@@ -21,26 +97,70 @@ function download(blob, filename) {
|
|
|
21
97
|
URL.revokeObjectURL(url);
|
|
22
98
|
}
|
|
23
99
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
100
|
+
// The chart's own surface, faithfully styled -- true vector, chart only. Does not gain the
|
|
101
|
+
// legend/size key rendered beside it; that is correct for what this format is for (Part A).
|
|
102
|
+
function chartSvgBlob(chartContainer) {
|
|
103
|
+
const svg = findChartSvg(chartContainer);
|
|
104
|
+
const clone = svg.cloneNode(true);
|
|
105
|
+
inlineComputedStyles(svg, clone, CHART_STYLE_PROPERTIES);
|
|
106
|
+
// reviewer finding: MUI's ChartsSurface only ever gives the root <svg> a `viewBox` -- its actual
|
|
107
|
+
// pixel size comes from CSS (`width: 100%; height: 100%` against the page's own layout), which
|
|
108
|
+
// has nothing to resolve against once cloned out to a standalone file. Without an explicit
|
|
109
|
+
// width/height a standalone viewer falls back to the SVG UA default (typically 300x150).
|
|
110
|
+
const rect = svg.getBoundingClientRect();
|
|
111
|
+
clone.setAttribute('width', Math.ceil(rect.width) || svg.clientWidth || 1);
|
|
112
|
+
clone.setAttribute('height', Math.ceil(rect.height) || svg.clientHeight || 1);
|
|
113
|
+
clone.setAttribute('xmlns', SVG_NS);
|
|
114
|
+
return svgToBlob(clone);
|
|
29
115
|
}
|
|
30
116
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
117
|
+
// The whole container, as seen -- chart plus everything the panel renders beside it, via an SVG
|
|
118
|
+
// `<foreignObject>` wrapping a styled clone of the container's actual DOM. Standard platform
|
|
119
|
+
// technique for DOM rasterisation without a library: the intermediate SVG is never downloaded, only
|
|
120
|
+
// decoded into an `Image` and drawn onto a `<canvas>`.
|
|
121
|
+
function containerSvgBlob(chartContainer) {
|
|
122
|
+
const rect = chartContainer.getBoundingClientRect();
|
|
123
|
+
const width = Math.ceil(rect.width) || chartContainer.scrollWidth || 1;
|
|
124
|
+
const height = Math.ceil(rect.height) || chartContainer.scrollHeight || 1;
|
|
34
125
|
|
|
126
|
+
const clone = chartContainer.cloneNode(true);
|
|
127
|
+
inlineComputedStyles(chartContainer, clone, [...CHART_STYLE_PROPERTIES, ...CONTAINER_LAYOUT_STYLE_PROPERTIES]);
|
|
128
|
+
clone.setAttribute('xmlns', XHTML_NS);
|
|
129
|
+
|
|
130
|
+
const svg = document.createElementNS(SVG_NS, 'svg');
|
|
131
|
+
svg.setAttribute('xmlns', SVG_NS);
|
|
132
|
+
svg.setAttribute('width', width);
|
|
133
|
+
svg.setAttribute('height', height);
|
|
134
|
+
svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
|
|
135
|
+
const foreignObject = document.createElementNS(SVG_NS, 'foreignObject');
|
|
136
|
+
foreignObject.setAttribute('width', '100%');
|
|
137
|
+
foreignObject.setAttribute('height', '100%');
|
|
138
|
+
foreignObject.appendChild(clone);
|
|
139
|
+
svg.appendChild(foreignObject);
|
|
140
|
+
|
|
141
|
+
return { svg, width, height };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// UCM-CHART-17 risk section, confirmed live (not assumed): an SVG containing a `<foreignObject>`
|
|
145
|
+
// taints the canvas on `toBlob` in Chrome -- unconditionally, even with zero external references
|
|
146
|
+
// (verified: a foreignObject holding nothing but plain styled text already triggers
|
|
147
|
+
// `SecurityError: Tainted canvases may not be exported`) -- but ONLY when the image is loaded via
|
|
148
|
+
// a `blob:` object URL. The identical SVG loaded via a `data:` URI does not taint the canvas at
|
|
149
|
+
// all. This is why the SVG-only export (`chartSvgBlob`, no foreignObject) can keep using
|
|
150
|
+
// `URL.createObjectURL` for its own download, while the PNG path's `Image` source specifically
|
|
151
|
+
// must be a `data:` URI. No rasteriser dependency needed once this is accounted for.
|
|
152
|
+
async function svgToDataUri(svg) {
|
|
153
|
+
const svgString = await svgToBlob(svg).text();
|
|
154
|
+
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgString)}`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function rasterize(svg, width, height, backgroundColour) {
|
|
158
|
+
const dataUri = await svgToDataUri(svg);
|
|
35
159
|
return new Promise((resolve, reject) => {
|
|
36
|
-
const url = URL.createObjectURL(source);
|
|
37
160
|
const image = new Image();
|
|
38
161
|
|
|
39
162
|
image.onload = () => {
|
|
40
163
|
try {
|
|
41
|
-
const svg = findSvg(chartContainer);
|
|
42
|
-
const width = Number(svg.getAttribute('width')) || svg.clientWidth || 1;
|
|
43
|
-
const height = Number(svg.getAttribute('height')) || svg.clientHeight || 1;
|
|
44
164
|
const canvas = document.createElement('canvas');
|
|
45
165
|
canvas.width = width * 2;
|
|
46
166
|
canvas.height = height * 2;
|
|
@@ -49,23 +169,37 @@ export function exportChartPng(chartContainer, filename = 'chart.png', backgroun
|
|
|
49
169
|
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
50
170
|
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
|
51
171
|
canvas.toBlob((blob) => {
|
|
52
|
-
URL.revokeObjectURL(url);
|
|
53
172
|
if (!blob) {
|
|
54
173
|
reject(new Error('Unable to create PNG export.'));
|
|
55
174
|
return;
|
|
56
175
|
}
|
|
57
|
-
download(blob, filename);
|
|
58
176
|
resolve(blob);
|
|
59
177
|
}, 'image/png');
|
|
60
178
|
} catch (error) {
|
|
61
|
-
URL.revokeObjectURL(url);
|
|
62
179
|
reject(error);
|
|
63
180
|
}
|
|
64
181
|
};
|
|
65
182
|
image.onerror = () => {
|
|
66
|
-
|
|
67
|
-
reject(new Error('Unable to load chart SVG for PNG export.'));
|
|
183
|
+
reject(new Error('Unable to rasterize chart container for PNG export.'));
|
|
68
184
|
};
|
|
69
|
-
image.src =
|
|
185
|
+
image.src = dataUri;
|
|
70
186
|
});
|
|
71
187
|
}
|
|
188
|
+
|
|
189
|
+
/** Serializes the chart's own SVG surface, styles inlined, and downloads it. */
|
|
190
|
+
export function exportChartSvg(chartContainer, filename = 'chart.svg') {
|
|
191
|
+
const blob = chartSvgBlob(chartContainer);
|
|
192
|
+
download(blob, filename);
|
|
193
|
+
return blob;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Rasterizes the whole chart container -- chart, legend, size key, footnotes, everything the panel
|
|
198
|
+
* renders beside the chart -- at two-times scale and downloads it.
|
|
199
|
+
*/
|
|
200
|
+
export async function exportChartPng(chartContainer, filename = 'chart.png', backgroundColour) {
|
|
201
|
+
const { svg, width, height } = containerSvgBlob(chartContainer);
|
|
202
|
+
const blob = await rasterize(svg, width, height, backgroundColour);
|
|
203
|
+
download(blob, filename);
|
|
204
|
+
return blob;
|
|
205
|
+
}
|
|
@@ -23,12 +23,29 @@ export const chartsTranslations = {
|
|
|
23
23
|
en: 'Export SVG',
|
|
24
24
|
sw: 'Hamisha SVG',
|
|
25
25
|
},
|
|
26
|
+
// UCM-CHART-17: the two formats now genuinely differ (SVG = chart only, vector; PNG = the whole
|
|
27
|
+
// panel as shown, legend included) -- the label alone no longer says so, the tooltip does.
|
|
28
|
+
'ChartFrame.EXPORT_SVG_TOOLTIP': {
|
|
29
|
+
de: 'Skalierbare Vektorgrafik des Diagramms allein, ohne Legende.',
|
|
30
|
+
fr: 'Image vectorielle du graphique seul, sans la légende.',
|
|
31
|
+
en: 'Scalable vector image of the chart alone, without the legend.',
|
|
32
|
+
sw: 'Picha ya vekta inayoweza kubadilishwa ukubwa ya chati pekee, bila maelezo.',
|
|
33
|
+
},
|
|
26
34
|
'ChartFrame.EXPORT_PNG_LABEL': {
|
|
27
35
|
de: 'PNG exportieren',
|
|
28
36
|
fr: 'Exporter en PNG',
|
|
29
37
|
en: 'Export PNG',
|
|
30
38
|
sw: 'Hamisha PNG',
|
|
31
39
|
},
|
|
40
|
+
// ui_reviewer finding: the original wording named the legend but not the size key/footnotes
|
|
41
|
+
// the PNG also carries -- named explicitly now, matching the Envelope's own Goal wording
|
|
42
|
+
// ("legend, size key and footnotes").
|
|
43
|
+
'ChartFrame.EXPORT_PNG_TOOLTIP': {
|
|
44
|
+
de: 'Bild des ganzen Kartenbereichs, wie angezeigt, inklusive Legende, Grössenschlüssel und Fussnoten.',
|
|
45
|
+
fr: 'Image de toute la zone de la carte, telle qu’affichée, légende, clé de taille et notes de bas de page comprises.',
|
|
46
|
+
en: 'Image of the whole card area as shown, including the legend, size key, and footnotes.',
|
|
47
|
+
sw: 'Picha ya eneo lote la kadi kama linavyoonyeshwa, ikijumuisha maelezo, kifunguo cha ukubwa, na maelezo ya chini.',
|
|
48
|
+
},
|
|
32
49
|
'ChartFrame.EXPORT_ERROR': {
|
|
33
50
|
de: 'Das Diagramm konnte nicht exportiert werden.',
|
|
34
51
|
fr: 'Impossible d’exporter le graphique.',
|
|
@@ -22,7 +22,9 @@ const resources = {
|
|
|
22
22
|
'ChartFrame.EMPTY_DEFAULT': 'No data available.',
|
|
23
23
|
'ChartFrame.ERROR_DEFAULT': 'The chart could not be loaded.',
|
|
24
24
|
'ChartFrame.EXPORT_SVG_LABEL': 'Export SVG',
|
|
25
|
+
'ChartFrame.EXPORT_SVG_TOOLTIP': 'Scalable vector image of the chart alone, without the legend.',
|
|
25
26
|
'ChartFrame.EXPORT_PNG_LABEL': 'Export PNG',
|
|
27
|
+
'ChartFrame.EXPORT_PNG_TOOLTIP': 'Image of the whole card area as shown, including the legend, size key, and footnotes.',
|
|
26
28
|
'ChartFrame.EXPORT_ERROR': 'The chart could not be exported.',
|
|
27
29
|
},
|
|
28
30
|
},
|
|
@@ -32,7 +34,9 @@ const resources = {
|
|
|
32
34
|
'ChartFrame.EMPTY_DEFAULT': 'Aucune donnée disponible.',
|
|
33
35
|
'ChartFrame.ERROR_DEFAULT': 'Impossible de charger le graphique.',
|
|
34
36
|
'ChartFrame.EXPORT_SVG_LABEL': 'Exporter en SVG',
|
|
37
|
+
'ChartFrame.EXPORT_SVG_TOOLTIP': 'Image vectorielle du graphique seul, sans la légende.',
|
|
35
38
|
'ChartFrame.EXPORT_PNG_LABEL': 'Exporter en PNG',
|
|
39
|
+
'ChartFrame.EXPORT_PNG_TOOLTIP': 'Image de toute la zone de la carte, telle qu’affichée, légende, clé de taille et notes de bas de page comprises.',
|
|
36
40
|
'ChartFrame.EXPORT_ERROR': 'Impossible d’exporter le graphique.',
|
|
37
41
|
},
|
|
38
42
|
},
|
|
@@ -162,6 +166,17 @@ describe('ChartFrame', () => {
|
|
|
162
166
|
await vi.waitFor(() => expect(onExportPng).toHaveBeenCalledOnce());
|
|
163
167
|
});
|
|
164
168
|
|
|
169
|
+
// UCM-CHART-17: the two formats now genuinely differ (chart-only vector vs. the whole card as
|
|
170
|
+
// shown) -- each button must say so, without silently renaming itself in the process (MUI
|
|
171
|
+
// Tooltip's default `aria-label` behaviour would do exactly that; `describeChild` avoids it).
|
|
172
|
+
it('describes what each export format contains without replacing the button\'s own accessible name', () => {
|
|
173
|
+
renderFrame({ exportOptions: true });
|
|
174
|
+
const svgButton = screen.getByRole('button', { name: 'Export SVG' });
|
|
175
|
+
const pngButton = screen.getByRole('button', { name: 'Export PNG' });
|
|
176
|
+
expect(svgButton.getAttribute('title')).toBe('Scalable vector image of the chart alone, without the legend.');
|
|
177
|
+
expect(pngButton.getAttribute('title')).toBe('Image of the whole card area as shown, including the legend, size key, and footnotes.');
|
|
178
|
+
});
|
|
179
|
+
|
|
165
180
|
it('keeps the controls row rendered in the loading, error and empty states', () => {
|
|
166
181
|
const controls = <button type="button">View selector</button>;
|
|
167
182
|
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import {
|
|
3
|
+
afterEach, beforeEach, describe, expect, it, vi,
|
|
4
|
+
} from 'vitest';
|
|
5
|
+
|
|
6
|
+
import { exportChartPng, exportChartSvg } from '../src/components/charts/exportChart';
|
|
7
|
+
|
|
8
|
+
// UCM-CHART-17: a container shaped like `AccessGapScatterPanel` -- the chart's own MUI surface,
|
|
9
|
+
// PLUS a second SVG (the hand-built size key) and an HTML legend beside it, exactly the shape that
|
|
10
|
+
// broke "the first SVG" (scope item 3) and dropped the legend from every export (Part A, defect 2).
|
|
11
|
+
function buildContainer() {
|
|
12
|
+
const container = document.createElement('div');
|
|
13
|
+
container.innerHTML = `
|
|
14
|
+
<div class="legend">Legend HTML</div>
|
|
15
|
+
<svg class="MuiChartsSurface-root" width="300" height="200">
|
|
16
|
+
<g><text class="MuiChartsAxis-tickLabel">Alpha</text></g>
|
|
17
|
+
<line class="MuiChartsAxis-line" x1="0" x2="300" y1="10" y2="10"></line>
|
|
18
|
+
</svg>
|
|
19
|
+
<svg class="size-key" width="40" height="40"><circle r="4"></circle></svg>
|
|
20
|
+
`;
|
|
21
|
+
document.body.appendChild(container);
|
|
22
|
+
return container;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('exportChartSvg (UCM-CHART-17)', () => {
|
|
26
|
+
afterEach(() => {
|
|
27
|
+
document.body.innerHTML = '';
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('resolves with its existing signature and returns a Blob', () => {
|
|
31
|
+
const container = buildContainer();
|
|
32
|
+
const blob = exportChartSvg(container, 'chart.svg');
|
|
33
|
+
expect(blob).toBeInstanceOf(Blob);
|
|
34
|
+
expect(blob.type).toBe('image/svg+xml;charset=utf-8');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
// reviewer finding: MUI's ChartsSurface only ever carries a `viewBox` -- its real pixel size is
|
|
38
|
+
// CSS (`width: 100%`), which has nothing to resolve against once cloned out of the page. Without
|
|
39
|
+
// an explicit width/height a standalone viewer falls back to the SVG UA default (300x150), i.e.
|
|
40
|
+
// the wrong size regardless of how faithfully everything else is styled.
|
|
41
|
+
it('sets explicit width/height attributes on the exported SVG, not just the source viewBox', async () => {
|
|
42
|
+
const container = buildContainer();
|
|
43
|
+
const blob = exportChartSvg(container);
|
|
44
|
+
const text = await blob.text();
|
|
45
|
+
expect(text).toMatch(/<svg[^>]*\bwidth="\d+"/);
|
|
46
|
+
expect(text).toMatch(/<svg[^>]*\bheight="\d+"/);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// WO scope item 3: the legend sits BEFORE the chart's own svg in this fixture (as it does in
|
|
50
|
+
// `AccessGapScatterPanel`), and a second, unrelated SVG (the size key) sits after it -- "the
|
|
51
|
+
// first SVG" would grab neither of those correctly. `MuiChartsSurface-root` is the deliberate,
|
|
52
|
+
// non-positional signal.
|
|
53
|
+
it('takes the chart surface deliberately, not the first (or any other) SVG in the container', async () => {
|
|
54
|
+
const container = buildContainer();
|
|
55
|
+
const blob = exportChartSvg(container);
|
|
56
|
+
const text = await blob.text();
|
|
57
|
+
expect(text).toContain('MuiChartsSurface-root');
|
|
58
|
+
expect(text).toContain('Alpha');
|
|
59
|
+
expect(text).not.toContain('size-key');
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// WO defect 1 + Unit tests: the clone must carry the RESOLVED style, not just the (rule-less,
|
|
63
|
+
// once serialised standalone) class name -- this is the whole point of the fix.
|
|
64
|
+
it('inlines computed styles for tick labels and axis strokes onto the cloned SVG', async () => {
|
|
65
|
+
const container = buildContainer();
|
|
66
|
+
const tickLabel = container.querySelector('.MuiChartsAxis-tickLabel');
|
|
67
|
+
tickLabel.style.fontFamily = 'DM Sans';
|
|
68
|
+
tickLabel.style.fill = 'rgb(10, 20, 30)';
|
|
69
|
+
const axisLine = container.querySelector('.MuiChartsAxis-line');
|
|
70
|
+
axisLine.style.stroke = 'rgb(200, 200, 200)';
|
|
71
|
+
|
|
72
|
+
const blob = exportChartSvg(container);
|
|
73
|
+
const text = await blob.text();
|
|
74
|
+
expect(text).toContain('font-family: "DM Sans"');
|
|
75
|
+
expect(text).toContain('fill: rgb(10, 20, 30)');
|
|
76
|
+
expect(text).toContain('stroke: rgb(200, 200, 200)');
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('does not gain the legend or size key -- true vector, chart only', async () => {
|
|
80
|
+
const container = buildContainer();
|
|
81
|
+
const blob = exportChartSvg(container);
|
|
82
|
+
const text = await blob.text();
|
|
83
|
+
expect(text).not.toContain('Legend HTML');
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('throws when the container has no SVG at all', () => {
|
|
87
|
+
const container = document.createElement('div');
|
|
88
|
+
document.body.appendChild(container);
|
|
89
|
+
expect(() => exportChartSvg(container)).toThrow(/does not contain an SVG/);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
describe('exportChartPng (UCM-CHART-17)', () => {
|
|
94
|
+
let originalGetContext;
|
|
95
|
+
let originalToBlob;
|
|
96
|
+
let originalImage;
|
|
97
|
+
|
|
98
|
+
beforeEach(() => {
|
|
99
|
+
originalGetContext = HTMLCanvasElement.prototype.getContext;
|
|
100
|
+
originalToBlob = HTMLCanvasElement.prototype.toBlob;
|
|
101
|
+
// jsdom has no real canvas/image-decoding backend (`getContext('2d')` returns null, `Image`
|
|
102
|
+
// never fires `onload`) -- this stands in for the platform pipeline `exportChartPng` drives,
|
|
103
|
+
// to test its OWN plumbing (does it resolve, with the right Blob type, for the documented
|
|
104
|
+
// input shape), not visual output. Visual correctness is the WO's own explicit non-unit-test
|
|
105
|
+
// gate: open the exported files.
|
|
106
|
+
HTMLCanvasElement.prototype.getContext = vi.fn(() => ({
|
|
107
|
+
fillStyle: '',
|
|
108
|
+
fillRect: vi.fn(),
|
|
109
|
+
drawImage: vi.fn(),
|
|
110
|
+
}));
|
|
111
|
+
HTMLCanvasElement.prototype.toBlob = function toBlob(callback) {
|
|
112
|
+
callback(new Blob(['png-bytes'], { type: 'image/png' }));
|
|
113
|
+
};
|
|
114
|
+
originalImage = global.Image;
|
|
115
|
+
global.Image = class MockImage {
|
|
116
|
+
set src(value) {
|
|
117
|
+
this._src = value;
|
|
118
|
+
queueMicrotask(() => this.onload?.());
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// eslint-disable-next-line class-methods-use-this
|
|
122
|
+
get src() {
|
|
123
|
+
return this._src;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
afterEach(() => {
|
|
129
|
+
document.body.innerHTML = '';
|
|
130
|
+
HTMLCanvasElement.prototype.getContext = originalGetContext;
|
|
131
|
+
HTMLCanvasElement.prototype.toBlob = originalToBlob;
|
|
132
|
+
global.Image = originalImage;
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// WO Unit tests: "the PNG path resolves for a container holding more than one SVG" -- the exact
|
|
136
|
+
// shape (chart surface + size key) that the pre-fix `findSvg`'s "first SVG" logic depended on
|
|
137
|
+
// being ordered correctly.
|
|
138
|
+
it('resolves with its existing signature for a container holding more than one SVG', async () => {
|
|
139
|
+
const container = buildContainer();
|
|
140
|
+
const blob = await exportChartPng(container, 'chart.png', '#ffffff');
|
|
141
|
+
expect(blob).toBeInstanceOf(Blob);
|
|
142
|
+
expect(blob.type).toBe('image/png');
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// Risk section, confirmed live against a real browser (see `rasterize`'s own comment): a
|
|
146
|
+
// `blob:` object URL taints the canvas the moment the SVG carries a `<foreignObject>`, in every
|
|
147
|
+
// case tested, `toBlob` then throws regardless of content. A `data:` URI does not. Locking this
|
|
148
|
+
// in so a future edit reaching back for `URL.createObjectURL` here regresses to the taint, not
|
|
149
|
+
// just to a style change.
|
|
150
|
+
it('loads the container SVG as a data: URI, never a blob: URL, to avoid canvas tainting', async () => {
|
|
151
|
+
const container = buildContainer();
|
|
152
|
+
let capturedSrc;
|
|
153
|
+
global.Image = class CapturingImage {
|
|
154
|
+
set src(value) {
|
|
155
|
+
capturedSrc = value;
|
|
156
|
+
this._src = value;
|
|
157
|
+
queueMicrotask(() => this.onload?.());
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// eslint-disable-next-line class-methods-use-this
|
|
161
|
+
get src() {
|
|
162
|
+
return this._src;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
await exportChartPng(container, 'chart.png', '#ffffff');
|
|
166
|
+
expect(capturedSrc).toMatch(/^data:image\/svg\+xml/);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('rejects when the container fails to rasterize', async () => {
|
|
170
|
+
global.Image = class FailingImage {
|
|
171
|
+
set src(value) {
|
|
172
|
+
this._src = value;
|
|
173
|
+
queueMicrotask(() => this.onerror?.());
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// eslint-disable-next-line class-methods-use-this
|
|
177
|
+
get src() {
|
|
178
|
+
return this._src;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
const container = buildContainer();
|
|
182
|
+
await expect(exportChartPng(container)).rejects.toThrow(/rasterize/);
|
|
183
|
+
});
|
|
184
|
+
});
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# UCM-CHART-17 — The two export buttons make two different promises; make them keep them
|
|
2
|
+
|
|
3
|
+
## Part A — Envelope
|
|
4
|
+
|
|
5
|
+
*Authored by the Expertenchat. Authoritative WHAT/WHY.*
|
|
6
|
+
|
|
7
|
+
### Goal
|
|
8
|
+
|
|
9
|
+
**Export SVG** yields the chart as scalable, correctly styled vector art. **Export PNG** yields what
|
|
10
|
+
the user is looking at — legend, size key and footnotes included.
|
|
11
|
+
|
|
12
|
+
### The defect, from the source
|
|
13
|
+
|
|
14
|
+
`exportChart.js:7-11` clones the first `<svg>` in the container and serialises it raw:
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
const svg = findSvg(chartContainer).cloneNode(true);
|
|
18
|
+
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
|
19
|
+
return new Blob([new XMLSerializer().serializeToString(svg)], …)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Three consequences, and they compound:
|
|
23
|
+
|
|
24
|
+
1. **No styles are carried.** MUI X-Charts styles nearly everything through emotion CSS classes —
|
|
25
|
+
tick fonts and sizes, axis and grid colours, text fill, the theme's typography. The clone keeps
|
|
26
|
+
`class="MuiChartsAxis-tickLabel css-1abc"` and none of the rules behind it, so a standalone
|
|
27
|
+
viewer applies bare SVG defaults. This is the "graphically massively different" the operator
|
|
28
|
+
reported. **The PNG inherits it**, because it rasterises the same blob.
|
|
29
|
+
|
|
30
|
+
2. **The legend is gone, and that is ours.** `findSvg` takes the *first* `<svg>`, i.e. the chart.
|
|
31
|
+
Since `HRAM-RES-39`/`HRAM-VIS-2`, consuming panels hide MUI's own legend and render a hand-built
|
|
32
|
+
one as **HTML** beside the chart, with the size key as a *second* SVG. Both sit outside the
|
|
33
|
+
exported element. **Before that consolidation, MUI's legend was inside the chart SVG and did get
|
|
34
|
+
exported** — unstyled, but present. Fixing a legend overlap silently degraded the export, and
|
|
35
|
+
nobody noticed because nobody opened an exported file.
|
|
36
|
+
|
|
37
|
+
3. **"The first SVG" is fragile** regardless — a panel that renders any SVG ahead of the chart
|
|
38
|
+
exports the wrong element. It works today by accident of ordering.
|
|
39
|
+
|
|
40
|
+
### The decision: two paths, two meanings
|
|
41
|
+
|
|
42
|
+
The operator chose option C on 2026-08-25. The two buttons already promise different things and
|
|
43
|
+
should stop pretending to be one mechanism:
|
|
44
|
+
|
|
45
|
+
- **SVG — the chart, faithfully styled.** Keep the clone-and-serialise path, but **inline computed
|
|
46
|
+
styles onto the cloned nodes** before serialising. Stays true vector: scalable, editable in
|
|
47
|
+
Illustrator/Inkscape, chart only. It does **not** gain the legend, and that is correct for what
|
|
48
|
+
this format is for.
|
|
49
|
+
- **PNG — the container, as seen.** Rasterise the whole `chartRef` node rather than the chart SVG, so
|
|
50
|
+
legend, size key and footnotes are in the file and the output matches the screen by construction.
|
|
51
|
+
|
|
52
|
+
**Make the difference legible to the user, not only to us.** Two buttons that produce visibly
|
|
53
|
+
different content need labels or tooltips saying so; today they read as one thing in two formats.
|
|
54
|
+
|
|
55
|
+
### Scope
|
|
56
|
+
|
|
57
|
+
**`src/components/charts/exportChart.js`**
|
|
58
|
+
|
|
59
|
+
1. **Inline computed styles** into the SVG clone before serialisation. Walk the clone against the
|
|
60
|
+
live tree and write the resolved properties as inline style. Keep it to the properties that matter
|
|
61
|
+
for chart rendering rather than dumping every computed property — a full dump produces enormous
|
|
62
|
+
files and is its own defect.
|
|
63
|
+
2. **Rasterise the container for PNG.** The `chartRef` node ChartFrame already passes
|
|
64
|
+
(`ChartFrame.jsx:138`) is the right root — it holds the chart plus everything the panel renders
|
|
65
|
+
beside it.
|
|
66
|
+
3. **Stop relying on "the first SVG"** for the SVG path — take the chart deliberately, not
|
|
67
|
+
positionally.
|
|
68
|
+
4. **Preserve the public signatures.** `exportChartSvg(container, filename)` and
|
|
69
|
+
`exportChartPng(container, filename, backgroundColour)` are consumed by `ChartFrame` and possibly
|
|
70
|
+
directly; the change is what they produce, not how they are called.
|
|
71
|
+
|
|
72
|
+
**`src/components/charts/ChartFrame.jsx`** — labels or tooltips that distinguish the two outputs.
|
|
73
|
+
Translated via the existing `chartsTranslations` path, not hard-coded.
|
|
74
|
+
|
|
75
|
+
### Non-goals / do not touch
|
|
76
|
+
|
|
77
|
+
- The chart presets, `resolveChartLayout`, the size scale, the axis bands.
|
|
78
|
+
- Consuming apps. hram's six panels with `exportOptions` gain the fix through the pin bump; that is
|
|
79
|
+
a separate row.
|
|
80
|
+
- Adding export to panels that do not have it (`HRAM-RES-43` did that for one panel in hram).
|
|
81
|
+
|
|
82
|
+
### Risks
|
|
83
|
+
|
|
84
|
+
- **A rasteriser is a new dependency in shared-core**, and this package currently has exactly one
|
|
85
|
+
runtime dependency (`@fontsource/dm-sans`). Adding a second is a real decision — check whether the
|
|
86
|
+
job can be done with the platform's own APIs first, and if a library is warranted, say why in the
|
|
87
|
+
WO's implementation record rather than just installing one.
|
|
88
|
+
- **Canvas tainting.** DOM-to-canvas rasterisation routes through an SVG `foreignObject`; any
|
|
89
|
+
external image or font reference taints the canvas and `toBlob` throws. The existing PNG path
|
|
90
|
+
already has this exposure and may already be failing on it — worth checking before assuming the new
|
|
91
|
+
path introduces it.
|
|
92
|
+
- **Fonts in the SVG.** Inlining computed styles records `font-family: "DM Sans"`, which a machine
|
|
93
|
+
without that font will substitute. Either embed the font or accept the substitution — but decide it
|
|
94
|
+
and write it down, because a silently substituted font is exactly the "looks different" complaint
|
|
95
|
+
this WO is fixing.
|
|
96
|
+
- **Style inlining can bloat.** See scope item 1.
|
|
97
|
+
- **This has no test that can see it.** A unit test can assert that a `style` attribute exists; it
|
|
98
|
+
cannot see that the file looks right. See verification.
|
|
99
|
+
|
|
100
|
+
### Verification
|
|
101
|
+
|
|
102
|
+
**Open the exported files.** That is the whole gate, and its absence is why this defect shipped: the
|
|
103
|
+
SVG in a viewer and the PNG in an image viewer, both compared against the rendered panel.
|
|
104
|
+
|
|
105
|
+
Do it for **two** panels with different shapes — one with a hand-built legend and size key
|
|
106
|
+
(`AccessGapScatterPanel`), one without — because the legend behaviour is precisely what differs
|
|
107
|
+
between the two export paths.
|
|
108
|
+
|
|
109
|
+
Unit tests: the SVG clone carries inlined styles for tick labels and axis strokes; both entry points
|
|
110
|
+
still resolve with their existing signatures; the PNG path resolves for a container holding more than
|
|
111
|
+
one SVG.
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## Part B — Implementation map
|
|
116
|
+
|
|
117
|
+
`.claude/models.local.json` has no local override, so the default applies: `implementation.runtime`
|
|
118
|
+
is `claude`/`sonnet` — the Orchestrator implemented directly, no Codex dispatch.
|
|
119
|
+
|
|
120
|
+
**Dependency decision (risk section, and Part C's approval gate):** no library added. Checked
|
|
121
|
+
first, per the WO's own instruction, and it held up: the platform's own `<foreignObject>` → `Image`
|
|
122
|
+
→ `<canvas>` pipeline works for arbitrary DOM rasterisation with no dependency at all. The one
|
|
123
|
+
obstacle — **confirmed live, not assumed** — is that Chrome taints the canvas on `toBlob`
|
|
124
|
+
unconditionally the moment the source SVG contains a `<foreignObject>` with HTML content, even with
|
|
125
|
+
zero external references (a minimal repro: a `<foreignObject>` holding one `<div>` with inline
|
|
126
|
+
`color: red` styling and no images/fonts/external refs still throws `SecurityError: Tainted
|
|
127
|
+
canvases may not be exported` when the SVG is loaded via `URL.createObjectURL`). The SAME SVG loaded
|
|
128
|
+
via a `data:` URI instead does **not** taint the canvas — confirmed with an identical minimal repro,
|
|
129
|
+
then re-confirmed end-to-end against the real `exportChartPng`/`ChartFrame` (real Chrome, via the
|
|
130
|
+
dev harness). This is why the approval gate never triggered: the platform-only approach IS viable,
|
|
131
|
+
it just needed the `blob:` → `data:` URI swap in `rasterize` (`exportChart.js`), documented inline
|
|
132
|
+
there.
|
|
133
|
+
|
|
134
|
+
**Canvas tainting on the PRE-FIX path:** checked per the risk section's own instruction ("may
|
|
135
|
+
already be failing on it"). It was not — a plain SVG-only blob (no `foreignObject`) loaded via
|
|
136
|
+
`URL.createObjectURL` does **not** taint the canvas; the exposure is specific to the `foreignObject`
|
|
137
|
+
this WO's PNG path adds, not a pre-existing defect.
|
|
138
|
+
|
|
139
|
+
**Verification (both real-browser, via the dev harness's module graph — `dev/entries.jsx` never
|
|
140
|
+
committed a probe entry, all verification was done by dynamically rendering `ChartFrame` into a
|
|
141
|
+
detached container and calling the real `exportChartSvg`/`exportChartPng`):**
|
|
142
|
+
|
|
143
|
+
- Panel shape WITH a hand-built legend + size key (mirroring `AccessGapScatterPanel`: MUI's own
|
|
144
|
+
legend hidden, a `<div>` HTML legend with a coloured swatch, a second `<svg>` "size key" beside
|
|
145
|
+
the chart): PNG rasterised at 2x scale, no taint, and pixel-sampling the produced PNG at the
|
|
146
|
+
swatch's and size-key's known screen coordinates read back their EXACT source colours
|
|
147
|
+
(`rgb(25,118,210)` / `#1976d2` and `rgb(156,39,176)` / `#9c27b0`) — the legend and size key are
|
|
148
|
+
genuinely present in the raster, not just "no error thrown". SVG export of the same panel:
|
|
149
|
+
contains `MuiChartsSurface-root` (the chart), does NOT contain the legend's own text/markup —
|
|
150
|
+
chart-only as designed.
|
|
151
|
+
- Panel shape WITHOUT a hand-built legend (plain `BarChart` inside `ChartFrame`): both exports
|
|
152
|
+
resolve cleanly, no regression for the common case.
|
|
153
|
+
|
|
154
|
+
Context package used: `exportChart.js` (rewritten in full, was short), `ChartFrame.jsx:42-108`
|
|
155
|
+
(the `runExport`/`exportOptions` wiring) and `:137-151` (`chartRef`, the export root — confirmed
|
|
156
|
+
correct: it wraps `content` only, excluding the meta/export-button footer), `chartsTranslations.ts`
|
|
157
|
+
(new `EXPORT_SVG_TOOLTIP`/`EXPORT_PNG_TOOLTIP` keys, all four locales).
|
|
158
|
+
|
|
159
|
+
---
|
|
160
|
+
|
|
161
|
+
## Part C — Orchestrator only
|
|
162
|
+
|
|
163
|
+
> **STOP — everything below addresses the Orchestrator.**
|
|
164
|
+
|
|
165
|
+
**Tier 3 · verification: opened files for two panel shapes, plus the unit tests above**
|
|
166
|
+
|
|
167
|
+
Shared-core, and — depending on scope item 2's answer — a dependency addition, which is its own
|
|
168
|
+
approval surface under Core Behaviour. If a library is needed, **stop and get the operator's
|
|
169
|
+
approval for that specific dependency** before adding it; the approval given on 2026-08-25 was for
|
|
170
|
+
the approach, not for a named package.
|
|
171
|
+
|
|
172
|
+
- `reviewer` — the inlining's completeness and the taint/font questions.
|
|
173
|
+
- `ui_reviewer` — whether the two buttons now read as two different things to a user.
|
|
174
|
+
- `sec_reviewer` — not run; no auth, data or exposure surface.
|
|
175
|
+
|
|
176
|
+
### Release
|
|
177
|
+
|
|
178
|
+
**Minor → 3.3.0**, per the operator. The PNG's *content* changes (it now includes the legend and
|
|
179
|
+
footnotes), so the CHANGELOG entry must **lead** with that, in the style `UCM-CHART-15` established:
|
|
180
|
+
a consumer who bumps and finds their exported PNGs different should read why in the first line, not
|
|
181
|
+
find it in a bullet.
|
|
182
|
+
|
|
183
|
+
### Register
|
|
184
|
+
|
|
185
|
+
Row `UCM-CHART-17`, both review notes, the published version, landing SHA(s) in a second commit
|
|
186
|
+
before the push. Record what the opened files actually looked like — that evidence is the point.
|
|
187
|
+
|
|
188
|
+
Consumer adoption (hram's pin bump) is a separate row; a shared-core fix that is published but not
|
|
189
|
+
consumed is not finished.
|
|
190
|
+
|
|
191
|
+
### Log
|
|
192
|
+
|
|
193
|
+
- **2026-08-25** — Envelope authored after the operator reported exports producing graphically very
|
|
194
|
+
different plots. Diagnosed from source, not reproduced by the Expertenchat: the operator has seen
|
|
195
|
+
the files. Option C chosen — SVG stays vector and chart-only, PNG becomes what the screen shows.
|