An open source design system that's fully customizable and agent ready
TypeScript
[experimental] render: draw recharts charts (#10382)
Joeye0821c1c5071
diff --git a/.changeset/render-draws-charts.md b/.changeset/render-draws-charts.mdnew file mode 100644index 0000000000..a7a00b0777--- /dev/null+++ b/.changeset/render-draws-charts.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[experimental] `astryx experimental render` draws recharts charts. A recharts chart draws only after its effects run, and a `ResponsiveContainer` measures its parent in a browser, so a rendered page showed an empty box for every chart. The render now draws each chart and `ResponsiveContainer` a page imports from recharts by name, after the server render, in a small document with no layout. A container starts at its own width and height, or at a width that follows its height, and the drawing scales to the width the page gives it. The `chart-size` warning counts the charts the render could not draw, and says when charts were drawn by themselves (when the page cannot be drawn again without a browser, or its effects change its charts or re-render the component that makes them). Charts show the data and props of the page's first render; a value a chart's parts read from a React context that an effect changes may show its later value.++@josephfarinadiff --git a/packages/cli/api/render/render.test.mjs b/packages/cli/api/render/render.test.mjsindex ea8887d29a..3014f9d054 100644--- a/packages/cli/api/render/render.test.mjs+++ b/packages/cli/api/render/render.test.mjs@@ -70,7 +70,7 @@ export default function Page() {`;beforeAll(async () => {- dir = makeLinkedFixture('astryx-render-test-', ['@astryxdesign', '@stylexjs', 'react', 'react-dom']);+ dir = makeLinkedFixture('astryx-render-test-', ['@astryxdesign', '@stylexjs', 'react', 'react-dom', 'recharts']);put('dot.png', PNG);put('page.tsx', PAGE);put('plain.html', '<!doctype html><html><body><h1>Hello</h1><p class="lead">Hi</p></body></html>');@@ -1281,3 +1281,448 @@ console.log(JSON.stringify({inside, outside}));expect(page.stylesheets).toContain('@astryxdesign/core/astryx.css');}, 60_000);});++describe('render(): charts', () => {+ const DATA = "const data = [{d: 'a', v: 1}, {d: 'b', v: 3}, {d: 'c', v: 2}];";++ it('draws a chart sized by its container and a chart of fixed size, and lets the first fit the width', async () => {+ put(+ 'charts.tsx',+ `import {ResponsiveContainer, LineChart, Line, XAxis, BarChart, Bar} from 'recharts';+${DATA}+export default function Page() {+ return (+ <div>+ <ResponsiveContainer width="100%" height={200}>+ <LineChart data={data}><XAxis dataKey="d" /><Line dataKey="v" /></LineChart>+ </ResponsiveContainer>+ <BarChart width={300} height={120} data={data}><Bar dataKey="v" /></BarChart>+ </div>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts.tsx', {cwd: dir}));+ expect(result.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('chart-size');+ const html = fs.readFileSync(path.join(dir, 'charts.html'), 'utf8');+ expect(html.match(/<svg[^>]*class="recharts-surface"/g)).toHaveLength(2);+ expect(html).toContain('recharts-line-curve');+ expect(html).toContain('recharts-bar-rectangle');+ // A container 200 pixels high starts two and a half times as wide.+ expect(html).toContain('viewBox="0 0 500 200"');+ expect(html).toContain('.recharts-responsive-container>.recharts-wrapper>svg.recharts-surface{width:100%!important');+ expect(html).not.toContain('<astryx-chart');+ }, 60_000);++ it('keeps room for a fixed chart\'s legend where its props place it, and gives a container chart\'s legend its own row', async () => {+ put(+ 'charts-legend.tsx',+ `import {ResponsiveContainer, LineChart, Line, XAxis, Legend} from 'recharts';+${DATA}+export default function Page() {+ return (+ <div>+ <ResponsiveContainer width="100%" height={200}>+ <LineChart data={data}><XAxis dataKey="d" /><Line dataKey="v" /><Legend /></LineChart>+ </ResponsiveContainer>+ <LineChart width={400} height={200} data={data}><XAxis dataKey="d" /><Line dataKey="v" /><Legend /></LineChart>+ <LineChart width={550} height={220} data={data}><XAxis dataKey="d" /><Line dataKey="v" name="Visits" /><Legend layout="vertical" align="right" verticalAlign="middle" /></LineChart>+ <ResponsiveContainer width="100%" height={220}>+ <LineChart data={data}><XAxis dataKey="d" /><Line dataKey="v" name="Visits" /><Legend layout="vertical" align="right" verticalAlign="middle" /></LineChart>+ </ResponsiveContainer>+ <ResponsiveContainer width="100%" height={220}>+ <LineChart data={data}><XAxis dataKey="d" /><Line dataKey="v" name="Wins" /><Legend layout="vertical" align="left" verticalAlign="bottom" /></LineChart>+ </ResponsiveContainer>+ <ResponsiveContainer width="100%" height={220}>+ <LineChart data={data}><XAxis dataKey="d" /><Line dataKey="v" name="Ties" /><Legend layout="vertical" align="center" verticalAlign="bottom" /></LineChart>+ </ResponsiveContainer>+ </div>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts-legend.tsx', {cwd: dir}));+ expect(result.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('chart-size');+ const html = fs.readFileSync(path.join(dir, 'charts-legend.html'), 'utf8');+ const axes = [...html.matchAll(/<line\b[^>]*class="recharts-cartesian-axis-line"[^>]*>/g)].map(m => ({+ y: Number(/\by1="([\d.]+)"/.exec(m[0])?.[1]),+ x2: Number(/\bx2="([\d.]+)"/.exec(m[0])?.[1]),+ }));+ // A container chart keeps no room in its picture: its legend takes its+ // own row under it, so the x-axis sits at 200 - 5 - 30 = 165.+ expect(axes[0].y).toBe(165);+ // A fixed chart keeps a row for a bottom legend: 200 - 5 - 24 - 30 = 141.+ expect(axes[1].y).toBe(141);+ // A legend at the side keeps room on the right: the plot ends before it.+ expect(axes[2].x2).toBeLessThan(550 - 40);+ expect(html).toContain('.recharts-responsive-container>.recharts-wrapper>.recharts-legend-wrapper{position:static!important;width:auto!important');+ expect(html).toContain('.recharts-legend-wrapper[style*="bottom"]{order:1}');+ // A vertical legend in a container chart sits beside the picture, centered.+ const sided = [...html.matchAll(/<div\b[^>]*class="recharts-wrapper"[^>]*>/g)].map(m => m[0]).filter(tag => tag.includes('data-legend-side'));+ // Right and middle, then left and bottom; a vertical legend centered+ // across takes its own row, unmarked.+ expect(sided).toHaveLength(2);+ expect(sided[0]).toContain('data-legend-side="right"');+ expect(sided[0]).toContain('data-legend-middle=""');+ expect(sided[1]).toContain('data-legend-side="left"');+ expect(sided[1]).not.toContain('data-legend-middle');+ expect(sided[1]).toContain('data-legend-bottom=""');+ // A bottom legend goes under the picture only when it is not beside it.+ expect(html).toContain('.recharts-wrapper:not([data-legend-side])>.recharts-legend-wrapper[style*="bottom"]{order:1}');+ expect(html).toContain('[data-legend-side]{flex-direction:row');+ // A side is physical: a right-to-left page reverses the row.+ expect(html).toContain('[data-legend-side]:dir(rtl){flex-direction:row-reverse}');+ expect(html).toContain('[data-legend-side="right"]>.recharts-legend-wrapper{order:1}');+ // Only the chart's own picture scales; a legend's icons keep their size.+ expect(html).toContain('.recharts-responsive-container>.recharts-wrapper>svg.recharts-surface{');+ expect(html).not.toContain('.recharts-responsive-container .recharts-surface');+ }, 60_000);++ it("draws a chart's parts in the React context the page gives them", async () => {+ put(+ 'charts-context.tsx',+ `import {createContext, useContext} from 'react';+import {BarChart, Bar, XAxis} from 'recharts';+${DATA}+const Units = createContext('items');+function Tick(props: any) {+ const units = useContext(Units);+ return <text x={props.x} y={props.y + 12}>{props.payload.value} {units}</text>;+}+export default function Page() {+ return (+ <Units.Provider value="km">+ <BarChart width={300} height={150} data={data}><XAxis dataKey="d" tick={<Tick />} /><Bar dataKey="v" /></BarChart>+ </Units.Provider>+ );+}+`,+ );+ await render('charts-context.tsx', {cwd: dir});+ const html = fs.readFileSync(path.join(dir, 'charts-context.html'), 'utf8');+ expect(html).toContain('a km');+ expect(html).not.toContain('a items');+ }, 60_000);++ it('draws inside a page that uses Core scrolling components, so context still reaches the chart', async () => {+ put(+ 'charts-core.tsx',+ `import {createContext, useContext} from 'react';+import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';+import {BarChart, Bar, XAxis} from 'recharts';+${DATA}+const Units = createContext('items');+function Tick(props: any) {+ return <text x={props.x} y={props.y + 12}>{props.payload.value} {useContext(Units)}</text>;+}+export default function Page() {+ console.log('rendered once');+ return (+ <Units.Provider value="km">+ <ScrollableArea>+ <BarChart width={300} height={150} data={data}><XAxis dataKey="d" tick={<Tick />} /><Bar dataKey="v" /></BarChart>+ </ScrollableArea>+ </Units.Provider>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts-core.tsx', {cwd: dir}));+ const html = fs.readFileSync(path.join(dir, 'charts-core.html'), 'utf8');+ expect(html).toContain('a km');+ expect(result.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('chart-size');+ // What the page prints is reported once, from the server render.+ const printed = result.data.warnings.filter((/** @type {any} */ w) => w.code === 'page-output');+ expect(printed.filter((/** @type {any} */ w) => w.message.includes('rendered once'))).toHaveLength(1);+ }, 60_000);++ it('says so when it draws each chart by itself', async () => {+ put(+ 'charts-alone.tsx',+ `import {BarChart, Bar} from 'recharts';+${DATA}+function OnlyOnServer() {+ // Throws only once a document exists, so the page draws on the server but not again.+ if (typeof document !== 'undefined') throw new Error('no second draw');+ return null;+}+export default function Page() {+ return <div><OnlyOnServer /><BarChart width={300} height={150} data={data}><Bar dataKey="v" /></BarChart></div>;+}+`,+ );+ const result = /** @type {any} */ (await render('charts-alone.tsx', {cwd: dir}));+ const html = fs.readFileSync(path.join(dir, 'charts-alone.html'), 'utf8');+ expect(html).toContain('recharts-bar-rectangle');+ const warning = result.data.warnings.find((/** @type {any} */ w) => w.code === 'chart-size');+ expect(warning?.message).toContain('each chart was drawn by itself');+ }, 60_000);++ it('draws charts as the first render gives them, not as the page\'s effects change it', async () => {+ put(+ 'charts-effects.tsx',+ `import {useEffect, useState} from 'react';+import {BarChart, Bar, XAxis} from 'recharts';+${DATA}+export default function Page() {+ const [rows, setRows] = useState<string[]>([]);+ useEffect(() => setRows(['order one']), []);+ return (+ <div>+ <p>{rows.length === 0 ? 'No orders yet' : rows.join(', ')}</p>+ {rows.length === 0 ? null : <BarChart width={300} height={150} data={data}><XAxis dataKey="d" /><Bar dataKey="v" /></BarChart>}+ <BarChart width={300} height={150} data={data}><XAxis dataKey="d" /><Bar dataKey="v" /></BarChart>+ </div>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts-effects.tsx', {cwd: dir}));+ const html = fs.readFileSync(path.join(dir, 'charts-effects.html'), 'utf8');+ expect(html).toContain('No orders yet');+ expect(html.match(/<svg[^>]*class="recharts-surface"/g)).toHaveLength(1);+ const warning = result.data.warnings.find((/** @type {any} */ w) => w.code === 'chart-size');+ expect(warning?.message).toContain('once its effects ran');+ }, 60_000);++ it('draws a chart as the first render gave it when an effect changes state a closure in it reads', async () => {+ put(+ 'charts-effect-closure.tsx',+ `import {useEffect, useState} from 'react';+import {BarChart, Bar, XAxis} from 'recharts';+const data = [{d: 'Mon', v: 1}, {d: 'Tue', v: 2}];+export default function Page() {+ const [unit, setUnit] = useState('items');+ useEffect(() => setUnit('km'), []);+ return (+ <div>+ <p>Unit: {unit}</p>+ <BarChart width={300} height={150} data={data}><XAxis dataKey="d" tickFormatter={(v: string) => v + ' ' + unit} /><Bar dataKey="v" /></BarChart>+ </div>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts-effect-closure.tsx', {cwd: dir}));+ const html = fs.readFileSync(path.join(dir, 'charts-effect-closure.html'), 'utf8');+ expect(html).toContain('Unit: items');+ expect(html).toContain('Mon items');+ expect(html).not.toContain('Mon km');+ expect(result.data.warnings.find((/** @type {any} */ w) => w.code === 'chart-size')?.message).toContain('A component that makes a chart rendered again');+ }, 60_000);++ it('names a re-render as the cause when a chart\'s maker only re-renders in an effect', async () => {+ put(+ 'charts-effect-mounted.tsx',+ `import {useEffect, useState} from 'react';+import {BarChart, Bar} from 'recharts';+const data = [{v: 1}, {v: 2}];+export default function Page() {+ const [, setMounted] = useState(false);+ useEffect(() => setMounted(true), []);+ return <BarChart width={300} height={150} data={data}><Bar dataKey="v" /></BarChart>;+}+`,+ );+ const result = /** @type {any} */ (await render('charts-effect-mounted.tsx', {cwd: dir}));+ const message = result.data.warnings.find((/** @type {any} */ w) => w.code === 'chart-size')?.message ?? '';+ expect(message).toContain('A component that makes a chart rendered again');+ expect(message).not.toContain('changed its charts');+ }, 60_000);++ it('keeps first-render data and props, and lets a context an effect changes reach the chart', async () => {+ // The guide promises a chart's data and props from the first render; a+ // value its parts read from a context that an effect changes may show its+ // later value.+ put(+ 'charts-effect-provider.tsx',+ `import {createContext, useContext, useEffect, useState} from 'react';+import {BarChart, Bar, XAxis} from 'recharts';+const data = [{d: 'a', v: 1}, {d: 'b', v: 2}];+const Units = createContext('items');+function UnitsProvider({children}: {children: any}) {+ const [unit, setUnit] = useState('items');+ useEffect(() => setUnit('km'), []);+ return <Units.Provider value={unit}><p>Unit: {unit}</p>{children}</Units.Provider>;+}+function Tick(props: any) {+ return <text x={props.x} y={props.y + 12}>{props.payload.value} {useContext(Units)}</text>;+}+export default function Page() {+ return (+ <UnitsProvider>+ <BarChart width={300} height={150} data={data}><XAxis dataKey="d" tick={<Tick />} /><Bar dataKey="v" /></BarChart>+ </UnitsProvider>+ );+}+`,+ );+ await render('charts-effect-provider.tsx', {cwd: dir});+ const html = fs.readFileSync(path.join(dir, 'charts-effect-provider.html'), 'utf8');+ expect(html).toContain('Unit: items');+ expect(html.match(/\brecharts-bar-rectangle\b(?!s)/g)).toHaveLength(2);+ expect(html).toMatch(/a (items|km)/);+ }, 60_000);++ it('draws a chart with the data of the first render when an effect replaces it', async () => {+ put(+ 'charts-effect-data.tsx',+ `import {useEffect, useState} from 'react';+import {BarChart, Bar, XAxis} from 'recharts';+export default function Page() {+ const [data, setData] = useState([{d: 'first', v: 1}]);+ useEffect(() => setData([{d: 'later', v: 2}]), []);+ return <BarChart width={300} height={150} data={data}><XAxis dataKey="d" /><Bar dataKey="v" /></BarChart>;+}+`,+ );+ const result = /** @type {any} */ (await render('charts-effect-data.tsx', {cwd: dir}));+ const html = fs.readFileSync(path.join(dir, 'charts-effect-data.html'), 'utf8');+ expect(html).toContain('>first<');+ expect(html).not.toContain('>later<');+ expect(result.data.warnings.find((/** @type {any} */ w) => w.code === 'chart-size')?.message).toContain('once its effects ran');+ }, 60_000);++ it('keeps room for a legend that wraps onto more rows', async () => {+ put(+ 'charts-wrap.tsx',+ `import {LineChart, Line, XAxis, Legend} from 'recharts';+const data = [{d: 'Mon', a: 1, b: 2, c: 3, e: 4, f: 5}, {d: 'Tue', a: 2, b: 3, c: 1, e: 2, f: 3}];+export default function Page() {+ return (+ <LineChart width={480} height={240} data={data}>+ <XAxis dataKey="d" />+ <Line dataKey="a" name="Northern region" /><Line dataKey="b" name="Southern region" />+ <Line dataKey="c" name="Eastern region" /><Line dataKey="e" name="Western region" />+ <Line dataKey="f" name="Central region" />+ <Legend />+ </LineChart>+ );+}+`,+ );+ await render('charts-wrap.tsx', {cwd: dir});+ const html = fs.readFileSync(path.join(dir, 'charts-wrap.html'), 'utf8');+ const axis = /<line\b[^>]*class="recharts-cartesian-axis-line"[^>]*>/.exec(html)?.[0] ?? '';+ // Five names of about 120 px each wrap into two rows in 470 px, so the+ // axis sits two legend rows up: 240 - 5 - 48 - 30 = 157.+ expect(Number(/\by1="([\d.]+)"/.exec(axis)?.[1])).toBe(157);+ // In a container chart the same legend takes its own row under the+ // picture, which keeps no room for it, so it cannot cover the axis.+ put('charts-wrap-rc.tsx', fs.readFileSync(path.join(dir, 'charts-wrap.tsx'), 'utf8')+ .replace("import {LineChart,", "import {ResponsiveContainer, LineChart,")+ .replace('<LineChart width={480} height={240} data={data}>', '<ResponsiveContainer width="100%" height={240}><LineChart data={data}>')+ .replace('</LineChart>', '</LineChart></ResponsiveContainer>'));+ await render('charts-wrap-rc.tsx', {cwd: dir});+ const rc = fs.readFileSync(path.join(dir, 'charts-wrap-rc.html'), 'utf8');+ const rcAxis = /<line\b[^>]*class="recharts-cartesian-axis-line"[^>]*>/.exec(rc)?.[0] ?? '';+ expect(Number(/\by1="([\d.]+)"/.exec(rcAxis)?.[1])).toBe(240 - 5 - 30);+ expect(rc).toContain('recharts-legend-wrapper');+ }, 60_000);++ it('lays out axis labels as a browser does: the last label stays inside, and crowded labels thin out', async () => {+ const times = Array.from({length: 25}, (_, i) => `Apr ${1 + Math.floor((14 + i) / 24)} ${String((14 + i) % 24).padStart(2, '0')}:00`);+ const cats = Array.from({length: 24}, (_, i) => `Category ${String(i + 1).padStart(2, '0')}`);+ put(+ 'charts-axis.tsx',+ `import {ResponsiveContainer, LineChart, Line, XAxis, BarChart, Bar} from 'recharts';+const times = ${JSON.stringify(times)}.map((t, i) => ({t, v: i}));+const cats = ${JSON.stringify(cats)}.map((c, i) => ({c, v: i}));+export default function Page() {+ return (+ <div>+ <ResponsiveContainer width="100%" height={300}>+ <LineChart data={times}><XAxis dataKey="t" /><Line dataKey="v" /></LineChart>+ </ResponsiveContainer>+ <BarChart width={400} height={200} data={cats}><XAxis dataKey="c" /><Bar dataKey="v" /></BarChart>+ </div>+ );+}+`,+ );+ await render('charts-axis.tsx', {cwd: dir});+ const html = fs.readFileSync(path.join(dir, 'charts-axis.html'), 'utf8');+ const ticks = [...html.matchAll(/<text\b([^>]*class="recharts-text recharts-cartesian-axis-tick-value"[^>]*)>\s*<tspan[^>]*>([^<]*)/g)].map(m => ({+ x: Number(/\bx="([\d.]+)"/.exec(m[1])?.[1]),+ anchor: /text-anchor="(\w+)"/.exec(m[1])?.[1],+ text: m[2],+ }));+ const timeTicks = ticks.filter(t => t.text.startsWith('Apr'));+ const last = timeTicks[timeTicks.length - 1];+ // The drawing is 750 wide; an 11-character label at 14 px is about 92 wide.+ expect(last.anchor).toBe('middle');+ expect(last.x + Math.round(last.text.length * 14 * 0.6) / 2).toBeLessThanOrEqual(750);+ expect(timeTicks.length).toBeLessThan(25);+ const catTicks = ticks.filter(t => t.text.startsWith('Category'));+ expect(catTicks.length).toBeGreaterThan(1);+ expect(catTicks.length).toBeLessThan(24);+ }, 60_000);++ it("keeps a StrictMode page's context in its charts", async () => {+ put(+ 'charts-strict.tsx',+ `import {StrictMode, createContext, useContext} from 'react';+import {BarChart, Bar, XAxis} from 'recharts';+${DATA}+const Units = createContext('items');+function Tick(props: any) {+ return <text x={props.x} y={props.y + 12}>{props.payload.value} {useContext(Units)}</text>;+}+export default function Page() {+ return (+ <StrictMode>+ <Units.Provider value="km">+ <BarChart width={300} height={150} data={data}><XAxis dataKey="d" tick={<Tick />} /><Bar dataKey="v" /></BarChart>+ </Units.Provider>+ </StrictMode>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts-strict.tsx', {cwd: dir}));+ const html = fs.readFileSync(path.join(dir, 'charts-strict.html'), 'utf8');+ expect(html).toContain('a km');+ expect(result.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('chart-size');+ }, 60_000);++ it('names a chart of fixed size it cannot draw', async () => {+ put(+ 'charts-ns-fixed.tsx',+ `import * as R from 'recharts';+${DATA}+export default function Page() {+ return <R.BarChart width={300} height={120} data={data}><R.Bar dataKey="v" /></R.BarChart>;+}+`,+ );+ const result = /** @type {any} */ (await render('charts-ns-fixed.tsx', {cwd: dir}));+ const warning = result.data.warnings.find((/** @type {any} */ w) => w.code === 'chart-size');+ expect(warning?.message).toContain("from recharts by name");+ expect(warning?.message).not.toContain('fixed width');+ }, 60_000);++ it('warns about a chart it cannot draw', async () => {+ put(+ 'charts-ns.tsx',+ `import * as R from 'recharts';+${DATA}+export default function Page() {+ return (+ <R.ResponsiveContainer width="100%" height={200}>+ <R.LineChart data={data}><R.Line dataKey="v" /></R.LineChart>+ </R.ResponsiveContainer>+ );+}+`,+ );+ const result = /** @type {any} */ (await render('charts-ns.tsx', {cwd: dir}));+ expect(result.data.warnings.map((/** @type {any} */ w) => w.code)).toContain('chart-size');+ }, 60_000);++ it('gives back a page with charts byte for byte', async () => {+ const source = fs.readFileSync(path.join(dir, 'charts.tsx'), 'utf8');+ const back = /** @type {any} */ (await render('charts.html', {cwd: dir, reverse: true, out: 'charts-back/charts.tsx'}));+ expect(back.data.exact).toBe(true);+ expect(fs.readFileSync(path.join(dir, 'charts-back', 'charts.tsx'), 'utf8')).toBe(source);+ }, 60_000);+});diff --git a/packages/cli/assets/docs/tree/render-pages.doc.mjs b/packages/cli/assets/docs/tree/render-pages.doc.mjsindex 808019a5c9..0f4a939556 100644--- a/packages/cli/assets/docs/tree/render-pages.doc.mjs+++ b/packages/cli/assets/docs/tree/render-pages.doc.mjs@@ -57,7 +57,7 @@ export const docs = {},{type: 'prose',- text: 'What it cannot keep: anything that needs a browser while running. State, effects, click handlers and data loaded after the first paint are gone, and a chart sized by its container is empty, so give charts a fixed size. Read browser-only values such as window inside an effect, or the render stops with ERR_RENDER_BROWSER_API.',+ text: 'What it cannot keep: anything that needs a browser while running. State, effects, click handlers and data loaded after the first paint are gone. Charts made with recharts are the exception: the render draws each chart and ResponsiveContainer a module of the page (not an installed package) imports from recharts by name (`import {LineChart} from \'recharts\'`), inside the page, so a custom tick, label or shape sees the page\'s React context. A chart sized by its container scales to the width the page gives it, and its legend stays out of the picture: a horizontal legend takes its own row under it (above it when the legend asks for the top), and a vertical legend on one side sits beside it, on that side; in a chart of fixed size, a legend keeps the place its props give it. Charts show the data and props of the page\'s first render, before its effects run: when the page cannot be drawn again without a browser, or its effects change its charts or re-render the component that makes them, each chart is drawn by itself and its parts see React context defaults. A value a chart\'s parts read from a React context that an effect changes may still show its later value. A `chart-size` warning counts the charts the render cannot draw (one used through `import * as R`, say), and says when charts were drawn by themselves. Read browser-only values such as window inside an effect, or the render stops with ERR_RENDER_BROWSER_API.',},],},diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex c276565149..d1cfe3a58d 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -355,9 +355,9 @@ const RUNNERS = {sites: ['importDocModule', 'importNativeModule ×3', 'importTemplateModule'],},'foundation/render/page-worker.mjs': {- runs: 'the page `astryx experimental render` renders, its local modules, React, and the StyleX compiler, in a worker; outside a project, Node resolves the packages its folder lacks, and React and StyleX for every module (resolve hooks for ES modules), from the package set the CLI runs from',+ runs: 'the page `astryx experimental render` renders, its local modules, React, and the StyleX compiler, in a worker, then React DOM and the recharts settings to draw its charts; outside a project, Node resolves the packages its folder lacks, and React and StyleX for every module (resolve hooks for ES modules), from the package set the CLI runs from',sites: [- '.import() ×3',+ '.import() ×6','createJiti ×2','module','module.register',diff --git a/packages/cli/foundation/render/charts.mjs b/packages/cli/foundation/render/charts.mjsnew file mode 100644index 0000000000..780a7ca8ca--- /dev/null+++ b/packages/cli/foundation/render/charts.mjs@@ -0,0 +1,216 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Charts in a rendered page. A recharts chart draws only after its+ * effects run, and a ResponsiveContainer measures its parent in a browser, so+ * a server render leaves them empty. The render worker draws each one again+ * in a small document, at the size the container starts at, and puts the+ * drawing in its place.+ *+ * @input The chart elements the server render set aside.+ * @output Their markup, and the CSS that lets a drawn chart fit its width.+ * @position foundation/render — read by page-worker.mjs and render-page.mjs.+ */++/** The global the render worker installs to set charts aside. SYNC: page-worker.mjs assigns it by this name. */+export const CHART_GLOBAL = '__astryxRenderChart';++/** The recharts exports that draw a chart, besides ResponsiveContainer. */+export const CHART_ROOTS = new Set([+ 'AreaChart',+ 'BarChart',+ 'ComposedChart',+ 'FunnelChart',+ 'LineChart',+ 'PieChart',+ 'RadarChart',+ 'RadialBarChart',+ 'Sankey',+ 'ScatterChart',+ 'SunburstChart',+ 'Treemap',+]);++/** Widest starting size for a chart its page lets fill the width. */+const CHART_MAX_WIDTH = 800;++/** Height of a chart that names none. */+const CHART_HEIGHT = 300;++/** Height up to which a chart counts as a sparkline. */+const SPARKLINE_HEIGHT = 60;++/**+ * The size a ResponsiveContainer starts at: its own numbers where it has+ * them. Otherwise the width follows the height: six times it for a+ * sparkline, which sits in a narrow card or a table cell, and two and a half+ * times it for a taller chart. The drawing then scales to the width the+ * page gives it, so its text stays near its own size in most layouts.+ * @param {{width?: unknown, height?: unknown, aspect?: unknown}} props+ * @returns {{width: number, height: number}}+ */+export function chartSize({width, height, aspect}) {+ const ratio = typeof aspect === 'number' && aspect > 0 ? aspect : null;+ const w = typeof width === 'number' && width > 0 ? width : null;+ const h =+ typeof height === 'number' && height > 0+ ? height+ : ratio+ ? (w ?? CHART_MAX_WIDTH) / ratio+ : CHART_HEIGHT;+ return {+ width:+ w ??+ (ratio+ ? h * ratio+ : Math.min(CHART_MAX_WIDTH, Math.round(h * (h <= SPARKLINE_HEIGHT ? 6 : 2.5)))),+ height: h,+ };+}++/**+ * A chart drawn at its starting size scales to the width the page gives it+ * and keeps its shape, so it never overflows its card. Its legend stays out+ * of the scaled picture, so its text never covers the chart however narrow+ * the page is. A horizontal legend takes its own row under the picture, or+ * above it when it asks for the top. A vertical legend on one side sits+ * beside the picture, on that side.+ */+export const CHART_CSS =+ '.recharts-responsive-container{width:100%}' ++ '.recharts-responsive-container>.recharts-wrapper{width:100%!important;height:auto!important;display:flex;flex-direction:column}' ++ // Only the chart's own picture scales; a legend's icons keep their size.+ '.recharts-responsive-container>.recharts-wrapper>svg.recharts-surface{width:100%!important;height:auto!important}' ++ '.recharts-responsive-container>.recharts-wrapper>.recharts-legend-wrapper{position:static!important;width:auto!important;height:auto!important}' ++ '.recharts-responsive-container>.recharts-wrapper:not([data-legend-side])>.recharts-legend-wrapper[style*="bottom"]{order:1}' ++ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]{flex-direction:row;align-items:flex-start}' ++ // A side is physical, as in a chart of fixed size: a right-to-left page+ // reverses the row so the legend stays on the side it asked for.+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]:dir(rtl){flex-direction:row-reverse}' ++ '.recharts-responsive-container>.recharts-wrapper[data-legend-side][data-legend-middle]{align-items:center}' ++ '.recharts-responsive-container>.recharts-wrapper[data-legend-side][data-legend-bottom]{align-items:flex-end}' ++ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]>svg.recharts-surface{flex:1 1 0;min-width:0}' ++ '.recharts-responsive-container>.recharts-wrapper[data-legend-side]>.recharts-legend-wrapper{flex:none}' ++ // recharts puts the legend before the picture; one on the right goes after it.+ '.recharts-responsive-container>.recharts-wrapper[data-legend-side="right"]>.recharts-legend-wrapper{order:1}';++/**+ * Mark each container chart whose legend is vertical and on one side with+ * that side, and whether it sits at the bottom or the middle, for+ * {@link CHART_CSS}. A vertically centered legend has a `top` near the+ * middle (no room is kept for it in a container chart). A vertical legend+ * centered across takes its own row, as a horizontal one does.+ * @param {any} root the element the charts were drawn in+ */+export function markLegends(root) {+ for (const wrapper of root.querySelectorAll('.recharts-responsive-container > .recharts-wrapper')) {+ const legend = wrapper.querySelector(':scope > .recharts-legend-wrapper');+ if (!legend) continue;+ const vertical = [...legend.querySelectorAll('.recharts-legend-item')].some(item =>+ /display:\s*block/.test(item.getAttribute('style') ?? ''),+ );+ if (!vertical) continue;+ const style = legend.getAttribute('style') ?? '';+ // recharts places a right-aligned legend with `right`, a left-aligned one+ // at the chart's left margin, and a centered one half way across.+ const width = Number(wrapper.getAttribute('width'));+ const left = Number(/(?:^|;)\s*left\s*:\s*(-?[\d.]+)px/.exec(style)?.[1]);+ const side = /(?:^|;)\s*right\s*:/.test(style)+ ? 'right'+ : Number.isFinite(left) && width > 0 && left < width * 0.2+ ? 'left'+ : null;+ if (!side) continue;+ wrapper.setAttribute('data-legend-side', side);+ const top = Number(/(?:^|;)\s*top\s*:\s*(-?[\d.]+)px/.exec(style)?.[1]);+ const height = Number(wrapper.getAttribute('height'));+ if (/(?:^|;)\s*bottom\s*:/.test(style)) wrapper.setAttribute('data-legend-bottom', '');+ else if (top > 0 && height > 0 && top > height * 0.2) wrapper.setAttribute('data-legend-middle', '');+ }+}++/**+ * The box a legend would measure in a browser, estimated from its items, so+ * a chart of fixed size keeps room for it where its props place it: rows for+ * a horizontal legend, one line per item for a vertical one. A chart sized by+ * its container keeps no room, because its legend takes its own row.+ * @param {any} el the legend wrapper+ */+function legendBox(el) {+ if (el.closest?.('.recharts-responsive-container')) return box(0, 0);+ const items = [...el.querySelectorAll('.recharts-legend-item')];+ const widths = items.map(item => 14 + 4 + 7 * (item.textContent ?? '').length + 10);+ const vertical = items.some(item => /display:\s*block/.test(item.getAttribute('style') ?? ''));+ if (vertical) return box(Math.max(0, ...widths), 20 * items.length + 10);+ // A row as wide as the legend's own width holds the items it can; the rest+ // wrap onto more rows.+ const total = widths.reduce((a, b) => a + b, 0);+ const room = Number(/(?:^|;)\s*width\s*:\s*([\d.]+)px/.exec(el.getAttribute('style') ?? '')?.[1]);+ const rows = room > 0 ? Math.max(1, Math.ceil(total / room)) : 1;+ return box(Math.min(total, room > 0 ? room : total), 24 * rows);+}++/** @param {number} width @param {number} height */+const box = (width, height) => ({x: 0, y: 0, top: 0, left: 0, right: width, bottom: height, width, height});++/** Font size of text that names none, as an axis tick's. */+const TEXT_SIZE = 14;++/**+ * The box recharts' measurement span would measure: its text at its font+ * size, about 0.6 em per character and 1.2 em high.+ * @param {any} el+ */+function textBox(el) {+ const fromStyle = el.style?.fontSize ?? /(?:^|;)\s*font-size\s*:\s*([^;]+)/.exec(el.getAttribute?.('style') ?? '')?.[1];+ const size = Number.parseFloat(String(fromStyle ?? '')) || TEXT_SIZE;+ return box(Math.round(String(el.textContent ?? '').length * size * 0.6), Math.round(size * 1.2));+}++/**+ * Give this thread the small document a chart draws in: no layout, no+ * motion, and no frames to wait for.+ * @returns {Promise<void>}+ */+export async function chartDocument() {+ const {parseHTML} = await import('linkedom');+ const {window} = parseHTML('<!doctype html><html><head></head><body></body></html>');+ const g = /** @type {any} */ (globalThis);+ const quiet = () => ({+ matches: true,+ addEventListener() {},+ removeEventListener() {},+ addListener() {},+ removeListener() {},+ });+ Object.assign(window, {+ matchMedia: quiet,+ // Every style property reads as empty, as for an element with no CSS.+ getComputedStyle: () => new Proxy({getPropertyValue: () => ''}, {get: (o, k) => (k in o ? /** @type {any} */ (o)[k] : '')}),+ requestAnimationFrame: (/** @type {(t: number) => void} */ cb) => setTimeout(() => cb(Date.now()), 0),+ cancelAnimationFrame: (/** @type {any} */ id) => clearTimeout(id),+ ResizeObserver: class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ });+ g.window = window;+ g.document = window.document;+ g.matchMedia = window.matchMedia;+ g.getComputedStyle = window.getComputedStyle;+ g.requestAnimationFrame = window.requestAnimationFrame;+ g.cancelAnimationFrame = window.cancelAnimationFrame;+ g.ResizeObserver = window.ResizeObserver;+ // Nothing is laid out, so every box measures zero, except a legend's and+ // the span recharts measures text with, which are estimated: the chart+ // keeps room for its legend, and lays out its axis labels as in a browser.+ Object.defineProperty(window.Element.prototype, 'getBoundingClientRect', {+ configurable: true,+ writable: true,+ value() {+ if (this.getAttribute?.('id') === 'recharts_measurement_span') return textBox(this);+ return String(this.getAttribute?.('class') ?? '').includes('recharts-legend-wrapper') ? legendBox(this) : box(0, 0);+ },+ });+}diff --git a/packages/cli/foundation/render/charts.test.mjs b/packages/cli/foundation/render/charts.test.mjsnew file mode 100644index 0000000000..5bb91c788d--- /dev/null+++ b/packages/cli/foundation/render/charts.test.mjs@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Tests for the size a render gives a recharts ResponsiveContainer.+ */++import {describe, expect, it} from 'vitest';+import {chartSize} from './charts.mjs';++describe('chartSize', () => {+ it("keeps the container's own numbers", () => {+ expect(chartSize({width: 320, height: 180})).toEqual({width: 320, height: 180});+ });++ it('makes a sparkline six times as wide as it is high, and a taller chart two and a half times', () => {+ expect(chartSize({width: '100%', height: 24})).toEqual({width: 144, height: 24});+ expect(chartSize({width: '100%', height: 200})).toEqual({width: 500, height: 200});+ expect(chartSize({width: '100%', height: 600})).toEqual({width: 800, height: 600});+ });++ it('follows an aspect ratio, and starts a chart with no numbers at 300 pixels high', () => {+ expect(chartSize({width: '100%', aspect: 2})).toEqual({width: 800, height: 400});+ expect(chartSize({width: 400, aspect: 2})).toEqual({width: 400, height: 200});+ expect(chartSize({})).toEqual({width: 750, height: 300});+ });+});diff --git a/packages/cli/foundation/render/page-worker.mjs b/packages/cli/foundation/render/page-worker.mjsindex 070495122c..6b177ea3e1 100644--- a/packages/cli/foundation/render/page-worker.mjs+++ b/packages/cli/foundation/render/page-worker.mjs@@ -12,6 +12,10 @@* from the package set the CLI runs from (served-packages.mjs), and React and* StyleX always come from that set, so the page loads one copy of each.*+ * Charts the page imports from recharts draw only after their effects run,+ * so the server render sets them aside and draws them after it with React+ * DOM in a small document (charts.mjs).+ ** @input workerData {entry, root, served}* @output one message: {ok: true, markup, css, files, texts, logs} or* {ok: false, error: {code, message, detail?}}@@ -29,6 +33,7 @@ import {createJiti} from 'jiti';import {assetDataUri, isAssetPath} from './assets.mjs';import {SINGLE_COPY, isServedPackage, packageOf} from './served-packages.mjs';import {findNodeModulesPackage} from '../fs/paths.mjs';+import {CHART_GLOBAL, CHART_ROOTS, chartDocument, chartSize, markLegends} from './charts.mjs';/** @typedef {{level: string, text: string}} PageLog */@@ -136,6 +141,219 @@ const NODE_MODULES = `${path.sep}node_modules${path.sep}`;const isLocal = file =>!file.includes(NODE_MODULES) && (file === entry || file.startsWith(ROOT_PREFIX));+/** Charts the server render set aside, drawn after it. @type {any[]} */+const charts = [];+/** The props each chart was last drawn with in the page-wide draw. @type {any[]} */+const pageCharts = [];+/**+ * Whether a chart rendered again after the page-wide draw first committed. A+ * chart renders again only when the component that made it renders again:+ * its effects changed its state, which a closure in the chart may read, so+ * the props alone cannot say the chart is the same. React's development+ * double render under StrictMode runs before the commit, so it does not+ * count.+ */+let renderedAfterCommit = false;++/**+ * A chart's props as a string that two renders of the same chart share:+ * data by value, functions by name, elements by type and props.+ * @param {unknown} value+ * @param {number} [depth]+ * @returns {string}+ */+function sameKey(value, depth = 0) {+ if (depth > 8) return '…';+ if (typeof value === 'function') return `fn:${value.name}`;+ if (typeof value === 'symbol') return String(value);+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';+ if (Array.isArray(value)) return `[${value.map(v => sameKey(v, depth + 1)).join(',')}]`;+ const record = /** @type {Record<string, unknown>} */ (value);+ if ('$$typeof' in record && 'props' in record) {+ const type = /** @type {any} */ (record.type);+ return `<${typeof type === 'string' ? type : (type?.displayName ?? type?.name ?? '?')} ${sameKey(record.props, depth + 1)}>`;+ }+ return `{${Object.keys(record)+ .filter(key => !key.startsWith('_'))+ .sort()+ .map(key => `${key}:${sameKey(record[key], depth + 1)}`)+ .join(',')}}`;+}+/** React's createElement, once the page's React has loaded. @type {any} */+let createElement = null;+/** React's useContext and useRef. @type {any} */+let useContext = null;+/** @type {any} */+let useRef = null;+/** @type {any} */+let useLayoutEffect = null;+/** Set inside a drawn chart, so a chart inside it is not wrapped again. @type {any} */+let InChart = null;+/**+ * `aside` while the server render sets charts aside; `page` while the whole+ * page is drawn again, so each chart sees the context it was rendered in;+ * `alone` while each chart is drawn by itself, when the page cannot be.+ * @type {'aside' | 'page' | 'alone'}+ */+let mode = 'aside';++/**+ * Wrap a recharts chart, or a ResponsiveContainer, so the server render sets+ * it aside and the drawing pass draws it: a container at the size it starts+ * at, in a box that lets the drawing fit the page's width.+ * @param {any} Chart+ * @param {boolean} container+ */+/** @type {any} */ (globalThis).__astryxRenderChart = (/** @type {any} */ Chart, /** @type {boolean} */ container) => {+ function RenderedChart(/** @type {any} */ props) {+ if (mode === 'aside') {+ charts.push(createElement(RenderedChart, props));+ return createElement('astryx-chart', {'data-chart': charts.length - 1});+ }+ const inside = useContext(InChart);+ // Each chart drawn in the page notes the props it was last drawn with,+ // by its place in the page, to compare with the first render's.+ const place = useRef(/** @type {number | null} */ (null));+ const committed = useRef(false);+ useLayoutEffect(() => {+ committed.current = true;+ });+ if (mode === 'page' && !inside) {+ place.current ??= pageCharts.length;+ pageCharts[place.current] = props;+ if (committed.current) renderedAfterCommit = true;+ }+ const drawn = container+ ? createElement('div', {className: 'recharts-responsive-container'}, createElement(Chart, {...props, ...chartSize(props)}))+ : createElement(Chart, props);+ if (mode === 'alone' || inside) return drawn;+ return createElement('astryx-chart', null, createElement(InChart.Provider, {value: true}, drawn));+ }+ return RenderedChart;+};++/**+ * Point the page's recharts charts, and its ResponsiveContainer, at the+ * wrapper the worker installs.+ * @param {any} p the import of 'recharts'+ * @param {any} t Babel's types+ */+function setChartsAside(p, t) {+ for (const s of p.node.specifiers) {+ if (s.type !== 'ImportSpecifier') continue;+ const name = s.imported.name ?? s.imported.value;+ const container = name === 'ResponsiveContainer';+ if (!container && !CHART_ROOTS.has(name)) continue;+ const original = p.scope.generateUidIdentifier(name);+ const local = s.local.name;+ s.local = original;+ p.insertAfter(+ t.variableDeclaration('const', [+ t.variableDeclarator(+ t.identifier(local),+ t.callExpression(t.memberExpression(t.identifier('globalThis'), t.identifier(CHART_GLOBAL)), [+ original,+ t.booleanLiteral(container),+ ]),+ ),+ ]),+ );+ }+}++/**+ * Draw the charts the server render set aside, and put each drawing where+ * its placeholder is.+ *+ * Draw the whole page first. A chart's own parts then see the React context+ * the page gives them. If that draw throws, or the page's effects change a+ * chart (its props, or which charts there are), draw each chart alone, from+ * the props of the first render. A chart that fails stays empty and is+ * counted.+ * @param {string} markup+ * @param {any} Page+ * @returns {Promise<{markup: string, failed: number, alone: false | 'error' | 'changed' | 'rerendered'}>}+ */+async function drawCharts(markup, Page) {+ const placeholder = /<astryx-chart data-chart="(\d+)"><\/astryx-chart>/g;+ /** @type {any} */+ let client;+ /** @type {any} */+ let flushSync;+ try {+ await chartDocument();+ client = await jiti.import('react-dom/client');+ ({flushSync} = /** @type {any} */ (await jiti.import('react-dom')));+ // recharts decided it runs on a server when it loaded for the server+ // render. Now there is a document, so it measures text and lays out+ // axis labels as in a browser.+ const recharts = /** @type {any} */ (await jiti.import('recharts'));+ if (recharts?.Global) recharts.Global.isSsr = false;+ } catch {+ // Without a document to draw in, every chart stays empty and is counted.+ return {markup: markup.replace(placeholder, ''), failed: charts.length, alone: /** @type {false} */ (false)};+ }+ /**+ * Render one element in its own root and hand its host to `read`.+ * @param {unknown} element+ * @param {(host: any) => string[]} read+ * @returns {string[] | null} null when the render failed+ */+ const drawIn = (element, read) => {+ /** @type {unknown} */+ let error = null;+ const host = /** @type {any} */ (globalThis).document.createElement('div');+ const root = client.createRoot(host, {+ onUncaughtError: (/** @type {unknown} */ e) => {+ error = e;+ },+ onRecoverableError: () => {},+ });+ try {+ flushSync(() => root.render(element));+ } catch (e) {+ error = e;+ }+ if (!error) markLegends(host);+ const out = error ? null : read(host);+ root.unmount();+ return out;+ };+ mode = 'page';+ let drawn = drawIn(createElement(Page), host => [...host.querySelectorAll('astryx-chart')].map(el => el.innerHTML));+ /** @type {false | 'error' | 'changed' | 'rerendered'} */+ let alone = false;+ if (!drawn) alone = 'error';+ // The page's effects changed a chart: its props, which charts there are,+ // or the state of the component that made it, which a closure or context+ // in the chart may read.+ else if (+ drawn.length !== charts.length ||+ pageCharts.length !== charts.length ||+ charts.some((chart, i) => sameKey(chart.props) !== sameKey(pageCharts[i]))+ ) {+ alone = 'changed';+ } else if (renderedAfterCommit) {+ alone = 'rerendered';+ }+ if (alone) {+ mode = 'alone';+ drawn = charts.map(chart => drawIn(chart, host => [host.innerHTML])?.[0] ?? '');+ }+ let failed = 0;+ // A chart that drew no picture counts as failed, once.+ const pictures = /** @type {string[]} */ (drawn).map(html => {+ if (html.includes('<svg')) return html;+ failed += 1;+ return '';+ });+ return {+ markup: markup.replace(placeholder, (_, i) => pictures[Number(i)] ?? ''),+ failed,+ alone,+ };+}+/*** Babel plugin: replace asset imports with data: URIs and stylesheet imports* with nothing (their CSS is inlined into the page), and record static text@@ -148,6 +366,7 @@ function pagePlugin(filename) {visitor: {ImportDeclaration(/** @type {any} */ p) {const spec = /** @type {string} */ (p.node.source.value);+ if (spec === 'recharts') setChartsAside(p, t);const raw = spec.split('?')[0];// A stylesheet, image or JSON file imported through a project alias// (`@/styles/site.css`) resolves the way modules do.@@ -582,6 +801,11 @@ try {let server;try {React = await jiti.import('react');+ createElement = React.createElement;+ useContext = React.useContext;+ useRef = React.useRef;+ useLayoutEffect = React.useLayoutEffect;+ InChart = React.createContext(false);server = await jiti.import('react-dom/server');} catch (e) {classify(e);@@ -589,8 +813,18 @@ try {}/** @type {string} */let markup;+ let chartsFailed = 0;+ /** @type {false | 'error' | 'changed' | 'rerendered'} */+ let chartsAlone = false;try {markup = server.renderToStaticMarkup(React.createElement(Page));+ if (charts.length > 0) {+ // Drawing the page again re-runs its code: what it prints then was+ // already reported by the server render.+ const printed = logs.length;+ ({markup, failed: chartsFailed, alone: chartsAlone} = await drawCharts(markup, Page));+ logs.length = printed;+ }} catch (e) {classify(e);throw null;@@ -613,6 +847,8 @@ try {packageCss,skippedCss,fromSet: [...fromSet].map(([name, dir]) => ({name, dir})),+ chartsFailed,+ chartsAlone,assets: [...assetsInlined],files: localFiles,texts,diff --git a/packages/cli/foundation/render/render-page.mjs b/packages/cli/foundation/render/render-page.mjsindex bc2f82fd6d..18156d128a 100644--- a/packages/cli/foundation/render/render-page.mjs+++ b/packages/cli/foundation/render/render-page.mjs@@ -25,6 +25,7 @@ import {classesIn, cutCss, layerOrderOf} from './css-cut.mjs';import {sourceBlock} from './source-block.mjs';import {embeddedPathProblem} from './embedded-files.mjs';import {resolveServed} from './served-packages.mjs';+import {CHART_CSS} from './charts.mjs';/** How long one page may take to render before it is stopped. */export const RENDER_TIMEOUT_MS = 60_000;@@ -522,15 +523,30 @@ export async function renderPage(entry, options = {}) {message: `<${t.component}> on line ${t.line} did not render the text "${t.text.length > 60 ? `${t.text.slice(0, 57)}...` : t.text}" it was given; it takes that text through a prop (often label=), so check its props.`,});}- for (const f of /** @type {string[]} */ (message.files ?? [])) {- const src = fs.readFileSync(f, 'utf8');- if (/\bResponsiveContainer\b/.test(src)) {- warnings.push({- code: 'chart-size',- message: `${path.basename(f)} sizes a chart with ResponsiveContainer, which has no size until a browser measures it, so the chart is empty here; give the chart a fixed width and height.`,- });- break;- }+ // A chart the render did not draw is an empty box: a ResponsiveContainer+ // holds only its sizing box, and a chart of fixed size an empty wrapper.+ const blankCharts =+ (markup.match(/<div class="recharts-responsive-container[" ][^>]*><div[^>]*><\/div><\/div>/g) ?? []).length ++ (markup.match(/<div\b[^>]*\bclass="recharts-wrapper"[^>]*><\/div>/g) ?? []).length ++ (message.chartsFailed ?? 0);+ if (blankCharts > 0) {+ warnings.push({+ code: 'chart-size',+ message: `${blankCharts === 1 ? 'A chart' : `${blankCharts} charts`} could not be drawn without a browser, so ${blankCharts === 1 ? 'it is' : 'they are'} empty here: the render draws a chart only when a module of the page (not an installed package) imports the chart, and its ResponsiveContainer, from recharts by name (\`import {LineChart} from 'recharts'\`).`,+ });+ }+ if (message.chartsAlone) {+ /** @type {Record<string, string>} */+ const causes = {+ changed: 'The page changed its charts once its effects ran (their data or props, or which charts it shows)',+ rerendered: 'A component that makes a chart rendered again once the page\'s effects ran',+ error: 'The page could not be drawn again without a browser',+ };+ const why = causes[message.chartsAlone] ?? causes.error;+ warnings.push({+ code: 'chart-size',+ message: `${why}, so each chart was drawn by itself, as the first render gave it: a custom tick, label or shape in a chart sees React context defaults, not the values the page provides.`,+ });}for (const sheet of /** @type {string[]} */ (message.skippedCss ?? [])) {warnings.push({@@ -600,7 +616,7 @@ export async function renderPage(entry, options = {}) {'<meta name="color-scheme" content="light dark">' +`<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">` +`<title>${escapeHtml(title)}</title>` +- `<style>${SCHEME_CSS}${css}</style></head><body>${markup}` ++ `<style>${SCHEME_CSS}${markup.includes('class="recharts-responsive-container"') ? CHART_CSS : ''}${css}</style></head><body>${markup}` +`${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;return {html,diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 33148fcfce..e213f9e1ca 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -133,6 +133,7 @@"ignore": "^7.0.5","jiti": "^2.7.0","jscodeshift": "^17.3.0",+ "linkedom": "^0.18.14","node-diff3": "3.2.1","postcss": "^8.5.23","postcss-selector-parser": "^7.1.6",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 359ae95574..7aa8f31a7a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -835,6 +835,9 @@ importers:jscodeshift:specifier: ^17.3.0version: 17.3.0+ linkedom:+ specifier: ^0.18.14+ version: 0.18.14node-diff3:specifier: 3.2.1version: 3.2.1@@ -1259,6 +1262,9 @@ packages:'@acemir/[email protected]':resolution: {integrity: sha512-ZnR3GSaH+/vJ0YlHau21FjfLYjMpYVIzTD8M8vIEQvIGxeOXyXdzCI140rrCY862p/C/BbzWsjc1dgnM9mkoTA==}+ '@acemir/[email protected]':+ resolution: {integrity: sha512-OijrAUu7rrJhSIoHNg6LMPS5e344nwUHA+1EFYYjrh64D+GmytUsfBQjci45TjT+rd5Spsp8B5xsZDT+TgyXXQ==}+'@adobe/[email protected]':resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==}@@ -4347,6 +4353,10 @@ packages:resolution: {integrity: sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==}engines: {node: '>=18'}+ resolution: {integrity: sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==}@@ -4585,10 +4595,18 @@ packages:resolution: {integrity: sha512-COtn4EROW5dBGlE/4PiKnh6rZpAPxDeFLaEEwt4i10jpDMFt2EhQGS79QmmrO+iKCHv0PU/HrOWEhijFd1x99Q==}+ resolution: {integrity: sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}+ resolution: {integrity: sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}@@ -4787,9 +4805,38 @@ packages:resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}+ resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}++ resolution: {integrity: sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==}+ engines: {node: '>=20.19.0'}++ resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}++ resolution: {integrity: sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==}+ engines: {node: '>=20.19.0'}++ resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}+ engines: {node: '>= 4'}++ resolution: {integrity: sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==}+ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}++ resolution: {integrity: sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA==}engines: {node: '>=10'}@@ -4836,6 +4883,10 @@ packages:resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==}engines: {node: '>=8.6'}+ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}+ engines: {node: '>=0.12'}+resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}engines: {node: '>=0.12'}@@ -5268,6 +5319,12 @@ packages:resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}+ resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==}++ resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}+resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}engines: {node: '>= 0.8'}@@ -5683,6 +5740,15 @@ packages:resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}+ resolution: {integrity: sha512-BRUnkOm4YR5vo+qI3j0EbungB0vZPSCue5AdnTQRaxAGSbsOZiBFRO0rh4zlo8qXUhli8pxvnpEXDklMnlq2Rg==}+ engines: {node: '>=16'}+ peerDependencies:+ canvas: '>= 2'+ peerDependenciesMeta:+ canvas:+ optional: true+resolution: {integrity: sha512-B2P/d+jVW0UXOQ0MVMLrB/9ydA1P+zz6jYfdrbbEd9ur3S2rcbduFWKiUCC02Sm5hbC8nrm7y24WuYMG54HfxA==}engines: {node: '>=22.22.1'}@@ -5913,6 +5979,10 @@ packages:resolution: {integrity: sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA==}engines: {node: '>=18'}+ resolution: {integrity: sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==}+ engines: {node: '>=20.19.0'}+resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}engines: {node: '>=0.10.0'}@@ -6837,6 +6907,9 @@ packages:resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==}+ resolution: {integrity: sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==}+resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}@@ -7322,6 +7395,8 @@ snapshots:'@acemir/[email protected]': {}+ '@acemir/[email protected]': {}+'@adobe/[email protected]': {}'@alloc/[email protected]': {}@@ -10333,6 +10408,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+dependencies:balanced-match: 1.0.2@@ -10554,11 +10631,21 @@ snapshots:+ dependencies:+ boolbase: 2.0.0+ css-what: 8.0.0+ domhandler: 6.0.1+ domutils: 4.0.2+ nth-check: 3.0.1+dependencies:mdn-data: 2.27.1source-map-js: 1.2.1+ [email protected]: {}+@@ -10715,10 +10802,46 @@ snapshots:+ dependencies:+ domelementtype: 2.3.0+ domhandler: 5.0.3+ entities: 4.5.0++ dependencies:+ domelementtype: 3.0.0+ domhandler: 6.0.1+ entities: 8.0.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ domelementtype: 2.3.0++ dependencies:+ domelementtype: 3.0.0+optionalDependencies:'@types/trusted-types': 2.0.7+ dependencies:+ dom-serializer: 2.0.0+ domelementtype: 2.3.0+ domhandler: 5.0.3++ dependencies:+ dom-serializer: 3.1.1+ domelementtype: 3.0.0+ domhandler: 6.0.1+dependencies:is-obj: 2.0.0@@ -10757,6 +10880,8 @@ snapshots:ansi-colors: 4.1.3strip-ansi: 6.0.1+ [email protected]: {}+@@ -11344,6 +11469,15 @@ snapshots:+ [email protected]: {}++ dependencies:+ domelementtype: 2.3.0+ domhandler: 5.0.3+ domutils: 3.2.2+ entities: 7.0.1+dependencies:depd: 2.0.0@@ -11688,6 +11822,14 @@ snapshots:+ dependencies:+ '@acemir/cssom': 0.9.32+ css-select: 7.0.0+ html-escaper: 3.0.3+ htmlparser2: 10.1.0+ uhyphen: 0.2.0+dependencies:listr2: 10.2.2@@ -11910,6 +12052,10 @@ snapshots:path-key: 4.0.0unicorn-magic: 0.3.0+ dependencies:+ boolbase: 2.0.0+@@ -12935,6 +13081,8 @@ snapshots:+ [email protected]: {}+