@micha.bigler/ui-core-micha 3.2.0 → 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 +43 -0
- package/WORK_ORDERS.md +2 -0
- package/dist/components/charts/ChartFrame.js +7 -3
- package/dist/components/charts/chartDefaults.js +34 -2
- package/dist/components/charts/exportChart.js +147 -23
- package/dist/i18n/chartsTranslations.js +17 -0
- package/docs/CHART-LAYOUT.md +9 -7
- package/package.json +1 -1
- package/src/components/charts/ChartFrame.jsx +29 -20
- package/src/components/charts/chartDefaults.js +35 -1
- package/src/components/charts/exportChart.js +157 -23
- package/src/i18n/chartsTranslations.ts +17 -0
- package/tests/ChartFrame.test.jsx +15 -0
- package/tests/chartAxisTickBand.test.jsx +95 -0
- package/tests/chartDefaults.test.js +40 -0
- package/tests/exportChart.test.js +184 -0
- package/work-orders/UCM-CHART-16.md +169 -0
- package/work-orders/UCM-CHART-17.md +195 -0
|
@@ -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,95 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import React from 'react';
|
|
3
|
+
import {
|
|
4
|
+
afterAll, afterEach, beforeAll, describe, expect, it,
|
|
5
|
+
} from 'vitest';
|
|
6
|
+
import { cleanup, render } from '@testing-library/react';
|
|
7
|
+
import { ThemeProvider, createTheme } from '@mui/material/styles';
|
|
8
|
+
|
|
9
|
+
import { BarChart } from '../src/components/charts/BarChart';
|
|
10
|
+
|
|
11
|
+
// UCM-CHART-16: MUI's own tick-label fit check (`shortenLabels`, weighed against
|
|
12
|
+
// `tickLabelsMaxHeight`) depends on a REAL SVG text measurement (`getBBox`), which jsdom does not
|
|
13
|
+
// implement -- `SVGElement.prototype.getBBox` is not a function here, so MUI's own
|
|
14
|
+
// `getStringSize` falls back to `getBoundingClientRect`, which jsdom always reports as 0x0. Every
|
|
15
|
+
// measured height therefore comes back 0, MUI's fit check trivially "fits" any text, and the real
|
|
16
|
+
// defect (every tick label blanked) can never be observed by rendering the unmocked chart as-is --
|
|
17
|
+
// a test that skips this setup would pass whether or not the resolver's band is correct, i.e. be
|
|
18
|
+
// exactly the "mocked prop-assertion" trap this package's own tests warn against elsewhere.
|
|
19
|
+
//
|
|
20
|
+
// This installs a deterministic `getBBox` instead, so the SAME code MUI itself runs is actually
|
|
21
|
+
// exercised: height scaled off the measurement span's own `fontSize`, at a ratio (1.28) chosen to
|
|
22
|
+
// sit inside the real near-miss window this WO's own work order measured against a real browser
|
|
23
|
+
// (`resolveXAxisGeometry`'s `TICK_TEXT_HEIGHT_FACTOR` comment) -- large enough that the pre-fix
|
|
24
|
+
// unconditional floor already fails a titled axis at the theme's own default tick font, small
|
|
25
|
+
// enough that the untitled default (never broken) still passes. Width is deliberately near-zero so
|
|
26
|
+
// only the HEIGHT dimension of MUI's fit check is exercised; each chart also sets an explicit
|
|
27
|
+
// `width` so MUI's real responsive sizing (ResizeObserver, unavailable in jsdom) never enters into
|
|
28
|
+
// it.
|
|
29
|
+
function installHeightOnlyTextMeasurement() {
|
|
30
|
+
const original = SVGElement.prototype.getBBox;
|
|
31
|
+
// eslint-disable-next-line func-names
|
|
32
|
+
SVGElement.prototype.getBBox = function getBBox() {
|
|
33
|
+
const fontSize = Number.parseFloat(this.style.fontSize) || 12;
|
|
34
|
+
return { x: 0, y: 0, width: 1, height: fontSize * 1.28 };
|
|
35
|
+
};
|
|
36
|
+
return () => {
|
|
37
|
+
SVGElement.prototype.getBBox = original;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
describe('x-axis tick band leaves MUI room for one real line of tick text (UCM-CHART-16)', () => {
|
|
42
|
+
let restoreGetBBox;
|
|
43
|
+
|
|
44
|
+
beforeAll(() => {
|
|
45
|
+
restoreGetBBox = installHeightOnlyTextMeasurement();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
afterAll(() => {
|
|
49
|
+
restoreGetBBox();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
afterEach(cleanup);
|
|
53
|
+
|
|
54
|
+
// WO scope item 1's own signature: an axis title AND horizontal tick labels sharing the same
|
|
55
|
+
// band, at the theme's own default tick font -- no explicit `height`/`tickLabelStyle` overrides
|
|
56
|
+
// anywhere, so this exercises the resolver's own default reservation end to end, the exact path
|
|
57
|
+
// two hram consumers had to work around by hand.
|
|
58
|
+
it('renders non-empty tick labels when the axis has both a title and horizontal ticks', () => {
|
|
59
|
+
const { container } = render(
|
|
60
|
+
<ThemeProvider theme={createTheme()}>
|
|
61
|
+
<BarChart
|
|
62
|
+
series={[{ data: [24, 36, 28], label: 'Opened' }]}
|
|
63
|
+
xAxis={[{ data: ['A', 'B', 'C'] }]}
|
|
64
|
+
xAxisLabel="Category"
|
|
65
|
+
width={600}
|
|
66
|
+
/>
|
|
67
|
+
</ThemeProvider>,
|
|
68
|
+
);
|
|
69
|
+
const tickTexts = Array.from(container.querySelectorAll('.MuiChartsAxis-bottom .MuiChartsAxis-tickLabel'))
|
|
70
|
+
.map((node) => node.textContent);
|
|
71
|
+
expect(tickTexts).toHaveLength(3);
|
|
72
|
+
expect(tickTexts.every((text) => text.length > 0)).toBe(true);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Non-goal guardrail: the rotated path projects its own band from real measured/estimated text
|
|
76
|
+
// width and must stay exactly as before -- this WO only touches the flat (angle 0) case.
|
|
77
|
+
it('leaves the rotated tick path unaffected', () => {
|
|
78
|
+
const { container } = render(
|
|
79
|
+
<ThemeProvider theme={createTheme()}>
|
|
80
|
+
<BarChart
|
|
81
|
+
series={[{ data: [24, 36, 28, 12, 9, 7, 15] }]}
|
|
82
|
+
xAxis={[{
|
|
83
|
+
data: Array.from({ length: 7 }, (_, i) => `A rather long category label ${i}`),
|
|
84
|
+
}]}
|
|
85
|
+
xLabels="angled"
|
|
86
|
+
width={600}
|
|
87
|
+
/>
|
|
88
|
+
</ThemeProvider>,
|
|
89
|
+
);
|
|
90
|
+
const tickTexts = Array.from(container.querySelectorAll('.MuiChartsAxis-bottom .MuiChartsAxis-tickLabel'))
|
|
91
|
+
.map((node) => node.textContent);
|
|
92
|
+
expect(tickTexts).toHaveLength(7);
|
|
93
|
+
expect(tickTexts.every((text) => text.length > 0)).toBe(true);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
@@ -594,6 +594,46 @@ describe('resolveChartLayout size tokens and height escape (UCM-CHART-12, UCM-CH
|
|
|
594
594
|
});
|
|
595
595
|
});
|
|
596
596
|
|
|
597
|
+
describe('resolveChartLayout flat x-axis tick band leaves MUI room to render (UCM-CHART-16)', () => {
|
|
598
|
+
// Third occurrence (WO Part A): no title, just a tick font 1px above the untitled default --
|
|
599
|
+
// already enough to blank every label under the pre-fix, unconditional TICK_BAND_BASE_PX=25.
|
|
600
|
+
// 26 is not invented: binary-searched against the real, unmocked `BarChart` rendered in this
|
|
601
|
+
// repo's own dev harness (Chrome, this package's own DM Sans default) -- 25 still blanked every
|
|
602
|
+
// tick, 26 was the smallest axis height that didn't. A test computing its own expectation from
|
|
603
|
+
// `CHART_TICK_TEXT_HEIGHT_FACTOR`-style constants would pass whatever those constants say,
|
|
604
|
+
// proving nothing; this number came from outside the code under test.
|
|
605
|
+
it('reserves enough room for a tick font one pixel above the untitled default (measured threshold: 26px)', () => {
|
|
606
|
+
const layout = resolveChartLayout({
|
|
607
|
+
xAxis: [{
|
|
608
|
+
scaleType: 'band',
|
|
609
|
+
data: ['Urban', 'Peri-urban', 'Rural', 'Access', 'Village'],
|
|
610
|
+
tickLabelStyle: { fontSize: 13 },
|
|
611
|
+
}],
|
|
612
|
+
yAxis: [{ scaleType: 'linear' }],
|
|
613
|
+
xLabels: 'horizontal',
|
|
614
|
+
spacing: theme.spacing,
|
|
615
|
+
});
|
|
616
|
+
expect(layout.xAxis[0].height).toBeGreaterThanOrEqual(26);
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
// Rule 2 (WO non-goal guardrail): an axis without a title still reserves only the tick band --
|
|
620
|
+
// this WO's extra title-driven margin must not leak in when there is no title to share it with.
|
|
621
|
+
// Reviewer finding: asserting `xTitleBand === 0` alone passes whether or not the +2px title
|
|
622
|
+
// margin leaked into `xAxisBand` instead -- the band/height values themselves have to be
|
|
623
|
+
// checked against the same tick font's no-title formula (`ceil(fontSize * 1.3) + 9`).
|
|
624
|
+
it('does not add the title margin when the axis has no label', () => {
|
|
625
|
+
const layout = resolveChartLayout({
|
|
626
|
+
xAxis: [{ scaleType: 'band', data: ['A', 'B'], tickLabelStyle: { fontSize: 13 } }],
|
|
627
|
+
yAxis: [{ scaleType: 'linear' }],
|
|
628
|
+
xLabels: 'horizontal',
|
|
629
|
+
spacing: theme.spacing,
|
|
630
|
+
});
|
|
631
|
+
expect(layout.bands.xTitleBand).toBe(0);
|
|
632
|
+
expect(layout.bands.xAxisBand).toBe(26);
|
|
633
|
+
expect(layout.xAxis[0].height).toBe(26);
|
|
634
|
+
});
|
|
635
|
+
});
|
|
636
|
+
|
|
597
637
|
describe('resolveChartLayout xLabels rotation (UCM-CHART-12)', () => {
|
|
598
638
|
it('"horizontal" never rotates, regardless of tick count or label length', () => {
|
|
599
639
|
const layout = resolveChartLayout({
|
|
@@ -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
|
+
});
|