@samizdata/mozaic 0.9.0 → 0.10.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/README.md CHANGED
@@ -59,6 +59,6 @@ mozaic --help
59
59
 
60
60
  Options: `--out <dir>` (default `exports`), `--only <slug,…>`, `--formats svg,pdf,png`, `--web-width <px>`, `--browser <path>`.
61
61
 
62
- Chromium lookup: `--browser`, `$MOZAIC_BROWSER`, Playwright's download (`npx playwright install chromium`), any Chromium in Playwright's cache, then common system locations. Each is tried until one starts.
62
+ Chromium lookup: `--browser`, `$MOZAIC_BROWSER`, Playwright's download (`pnpm dlx playwright install chromium`), any Chromium in Playwright's cache, then common system locations. Each is tried until one starts.
63
63
 
64
64
  Requires Svelte 5.57+. The full guides, API reference and gallery are in the repository's docs site.
@@ -75,7 +75,7 @@ export async function launchBrowser(explicit) {
75
75
  const candidates = explicit ? [explicit] : browserCandidates(undefined);
76
76
  if (!candidates.length) {
77
77
  throw new Error(
78
- 'No Chromium found. Install one with `npx playwright install chromium`, or pass --browser /path/to/chrome.'
78
+ 'No Chromium found. Install one with `pnpm dlx playwright install chromium`, or pass --browser /path/to/chrome.'
79
79
  );
80
80
  }
81
81
  /** @type {string[]} */
@@ -88,6 +88,6 @@ export async function launchBrowser(explicit) {
88
88
  }
89
89
  }
90
90
  throw new Error(
91
- `Could not start Chromium. Tried:\n${failures.join('\n')}\nInstall one with \`npx playwright install chromium\` or pass --browser.`
91
+ `Could not start Chromium. Tried:\n${failures.join('\n')}\nInstall one with \`pnpm dlx playwright install chromium\` or pass --browser.`
92
92
  );
93
93
  }
@@ -5,6 +5,7 @@ export { default as Canvas } from './Canvas.svelte';
5
5
  export { default as Facets } from './Facets.svelte';
6
6
  export { setChartContext, setDownloads, setInitialWidth, setPlotContext, useChart, useDownloads, useInitialWidth, useLocale, usePlot, useTheme } from './context.js';
7
7
  export { estimateTextWidth, isOrdinal, isScale, position, scaled } from './scales.js';
8
+ export { measureTextWidth, useTextWidth } from './text.svelte.js';
8
9
  export { mm, pt, PX_PER_MM } from './units.js';
9
10
  export { access, type Accessor, type Value } from './accessor.js';
10
11
  export type { Breakpoint, ChartContext, Dimensions, Medium, Padding, PlotContext, PositionScale, ProjectionInput, RangeInput, ScaleInput } from './types.js';
@@ -5,5 +5,6 @@ export { default as Canvas } from './Canvas.svelte';
5
5
  export { default as Facets } from './Facets.svelte';
6
6
  export { setChartContext, setDownloads, setInitialWidth, setPlotContext, useChart, useDownloads, useInitialWidth, useLocale, usePlot, useTheme } from './context.js';
7
7
  export { estimateTextWidth, isOrdinal, isScale, position, scaled } from './scales.js';
8
+ export { measureTextWidth, useTextWidth } from './text.svelte.js';
8
9
  export { mm, pt, PX_PER_MM } from './units.js';
9
10
  export { access } from './accessor.js';
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Width in pixels of one line of `text` in a CSS `font` (`'12px "Source Sans 3", sans-serif'`),
3
+ * measured with a canvas. `undefined` where there is no canvas (server rendering) or the font
4
+ * can't be parsed (a `var()` in it, say).
5
+ */
6
+ export declare function measureTextWidth(text: string, font: string): number | undefined;
7
+ /**
8
+ * Text widths for laying out a chart, such as the gutter for row labels. Call it while a
9
+ * component initialises; it returns `(text, fontSize, family?) => width`, the widest line
10
+ * for text broken with `\n`. Until the component
11
+ * mounts (and in server rendering) the width is `estimateTextWidth`'s, so hydration matches the
12
+ * server's markup; then it is measured in `family`, and measured again when web fonts finish
13
+ * loading. Use it inside `$derived` so layouts follow.
14
+ */
15
+ export declare function useTextWidth(): (text: string, fontSize: number, family?: string) => number;
@@ -0,0 +1,52 @@
1
+ import { estimateTextWidth } from './scales.js';
2
+ let context;
3
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity -- a plain cache; `generation` in useTextWidth carries the reactivity
4
+ const cache = new Map();
5
+ /**
6
+ * Width in pixels of one line of `text` in a CSS `font` (`'12px "Source Sans 3", sans-serif'`),
7
+ * measured with a canvas. `undefined` where there is no canvas (server rendering) or the font
8
+ * can't be parsed (a `var()` in it, say).
9
+ */
10
+ export function measureTextWidth(text, font) {
11
+ if (typeof document === 'undefined' || font.includes('var('))
12
+ return undefined;
13
+ context ??= document.createElement('canvas').getContext('2d');
14
+ if (!context)
15
+ return undefined;
16
+ const key = `${font}\n${text}`;
17
+ let width = cache.get(key);
18
+ if (width === undefined) {
19
+ context.font = font;
20
+ width = context.measureText(text).width;
21
+ cache.set(key, width);
22
+ }
23
+ return width;
24
+ }
25
+ /**
26
+ * Text widths for laying out a chart, such as the gutter for row labels. Call it while a
27
+ * component initialises; it returns `(text, fontSize, family?) => width`, the widest line
28
+ * for text broken with `\n`. Until the component
29
+ * mounts (and in server rendering) the width is `estimateTextWidth`'s, so hydration matches the
30
+ * server's markup; then it is measured in `family`, and measured again when web fonts finish
31
+ * loading. Use it inside `$derived` so layouts follow.
32
+ */
33
+ export function useTextWidth() {
34
+ const widest = (text, width) => Math.max(...text.split('\n').map(width));
35
+ let generation = $state(0);
36
+ $effect(() => {
37
+ generation = 1;
38
+ const fonts = typeof document === 'undefined' ? undefined : document.fonts;
39
+ if (!fonts)
40
+ return;
41
+ const remeasure = () => {
42
+ cache.clear();
43
+ generation += 1;
44
+ };
45
+ fonts.addEventListener('loadingdone', remeasure);
46
+ void fonts.ready.then(remeasure);
47
+ return () => fonts.removeEventListener('loadingdone', remeasure);
48
+ });
49
+ return (text, fontSize, family = 'sans-serif') => widest(text, (line) => generation === 0
50
+ ? estimateTextWidth(line, fontSize)
51
+ : (measureTextWidth(line, `${fontSize}px ${family}`) ?? estimateTextWidth(line, fontSize)));
52
+ }
@@ -3,7 +3,8 @@
3
3
  Vertical axis for the plot's y scale. With `inside`, labels sit just above
4
4
  the gridlines inside the plot area, which saves left padding on small screens.
5
5
  `unit` names the unit once, after the top tick label ("50 lei/m³"); on a
6
- left axis it runs into the plot, so it needs no extra padding.
6
+ left axis it runs into the plot, so it needs no extra padding. A `\n` in a
7
+ label (from `format` or a band domain) breaks it into lines, centred on the tick.
7
8
  -->
8
9
  <script lang="ts">
9
10
  import { useChart, usePlot } from '../core/context.js';
@@ -60,8 +61,19 @@ left axis it runs into the plot, so it needs no extra padding.
60
61
  );
61
62
  // Outside a left axis, the unit starts where the numbers end and runs into the plot.
62
63
  const unitApart = $derived(position === 'left' && !inside);
64
+ /** Line height of a label broken with `\n`, in em. */
65
+ const LINE = 1.15;
63
66
  </script>
64
67
 
68
+ <!-- One `<text>` per label; extra lines are tspans, the first raised so the block centres on `dy`. -->
69
+ {#snippet lines(text: string, x: number, dy: number)}
70
+ {@const parts = text.split('\n')}
71
+ {@const first = dy - (inside ? parts.length - 1 : (parts.length - 1) / 2) * LINE}
72
+ <text {x} dy="{first}em" text-anchor={anchor}
73
+ >{#each parts as part, j (j)}{#if j === 0}{part}{:else}<tspan {x} dy="{LINE}em">{part}</tspan>{/if}{/each}</text
74
+ >
75
+ {/snippet}
76
+
65
77
  <g class="mz-axis mz-axis-y {className}" transform="translate({position === 'left' ? 0 : plot.width},0)">
66
78
  {#if baseline}<line class="mz-axis-line" y2={plot.height} />{/if}
67
79
  {#each values as value, i (value)}
@@ -69,9 +81,9 @@ left axis it runs into the plot, so it needs no extra padding.
69
81
  <g class="mz-tick" transform="translate(0,{scaled(plot.y, value)})">
70
82
  {#if tickSize > 0 && !inside}<line x2={dir * tickSize} />{/if}
71
83
  {#if inside}
72
- <text x={0} dy="-0.35em" text-anchor={anchor}>{withUnit}</text>
84
+ {@render lines(withUnit, 0, -0.35)}
73
85
  {:else}
74
- <text x={dir * (tickSize + tickPadding)} dy="0.32em" text-anchor={anchor}>{withUnit}</text>
86
+ {@render lines(withUnit, dir * (tickSize + tickPadding), 0.32)}
75
87
  {/if}
76
88
  {#if unit && value === top && unitApart}
77
89
  <text class="mz-axis-unit" x={-(tickSize + tickPadding) + 4} dy="0.32em" text-anchor="start">{unit}</text>
@@ -18,7 +18,8 @@ interface Props {
18
18
  * Vertical axis for the plot's y scale. With `inside`, labels sit just above
19
19
  * the gridlines inside the plot area, which saves left padding on small screens.
20
20
  * `unit` names the unit once, after the top tick label ("50 lei/m³"); on a
21
- * left axis it runs into the plot, so it needs no extra padding.
21
+ * left axis it runs into the plot, so it needs no extra padding. A `\n` in a
22
+ * label (from `format` or a band domain) breaks it into lines, centred on the tick.
22
23
  */
23
24
  declare const AxisY: import("svelte").Component<Props, {}, "">;
24
25
  type AxisY = ReturnType<typeof AxisY>;
@@ -13,7 +13,7 @@ project and change anything.
13
13
  import { max, min } from 'd3-array';
14
14
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
15
15
  import type { ChartEmbed } from '../embed/index.js';
16
- import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
16
+ import { Plot, Svg, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
17
17
  import { Arrows } from '../marks/index.js';
18
18
  import { AxisX, AxisY, GridX } from '../guides/index.js';
19
19
  import { createLocale, type LocaleCode } from '../locale/index.js';
@@ -88,6 +88,9 @@ project and change anything.
88
88
  }: Props = $props();
89
89
 
90
90
  const theme = $derived(style);
91
+ const measure = useTextWidth();
92
+ /** Width of a row label in the axis font, measured once mounted. */
93
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
91
94
  const fmt = $derived(format ?? createLocale(locale ?? theme.defaultLocale).number);
92
95
  const fontSize = $derived(theme.plot.fontSize);
93
96
  const has = (v: Maybe): v is number => v !== null && v !== undefined && Number.isFinite(v);
@@ -111,7 +114,7 @@ project and change anything.
111
114
  );
112
115
  const y = $derived(scaleBand<string>().domain(rows.map(label)).paddingInner(0.25).paddingOuter(0.1));
113
116
  const textWidth = (s: string) => estimateTextWidth(s, fontSize);
114
- const left = $derived(Math.max(...rows.map((d) => textWidth(label(d))), 0) + 12);
117
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
115
118
  const right = $derived(Math.max(...all.map((v) => textWidth(fmt(v))), 0) + 12);
116
119
  const labelled = $derived(Boolean(startLabel || endLabel) && both.length > 0);
117
120
 
@@ -10,7 +10,7 @@ file into your project and change anything.
10
10
  import { max, min } from 'd3-array';
11
11
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
12
12
  import type { ChartEmbed } from '../embed/index.js';
13
- import { Plot, Svg, Html, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
13
+ import { Plot, Svg, Html, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
14
14
  import { Bars, Rules, Text } from '../marks/index.js';
15
15
  import { AxisY } from '../guides/index.js';
16
16
  import { Tooltip } from '../interactive/index.js';
@@ -66,6 +66,9 @@ file into your project and change anything.
66
66
  }: Props = $props();
67
67
 
68
68
  const theme = $derived(style);
69
+ const measure = useTextWidth();
70
+ /** Width of a row label in the axis font, measured once mounted. */
71
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
69
72
  const fmt = $derived(format ?? createLocale(locale ?? theme.defaultLocale).number);
70
73
  const rows = $derived(sort ? data.toSorted((a, b) => value(b) - value(a)) : data);
71
74
  const x = $derived(
@@ -74,7 +77,7 @@ file into your project and change anything.
74
77
  .nice()
75
78
  );
76
79
  const y = $derived(scaleBand<string>().domain(rows.map(label)).paddingInner(0.25).paddingOuter(0.1));
77
- const left = $derived(Math.max(...rows.map((d) => estimateTextWidth(label(d), theme.plot.fontSize)), 0) + 12);
80
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
78
81
  const right = $derived(Math.max(...rows.map((d) => estimateTextWidth(fmt(value(d)), theme.plot.fontSize)), 0) + 12);
79
82
  let hovered = $state<T | null>(null);
80
83
  </script>
@@ -13,7 +13,7 @@ anything.
13
13
  import { max, min } from 'd3-array';
14
14
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
15
15
  import type { ChartEmbed } from '../embed/index.js';
16
- import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
16
+ import { Plot, Svg, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
17
17
  import { Bars, Points } from '../marks/index.js';
18
18
  import { AxisX, AxisY, GridX, Legend } from '../guides/index.js';
19
19
  import { createLocale, type LocaleCode } from '../locale/index.js';
@@ -91,6 +91,9 @@ anything.
91
91
  }: Props = $props();
92
92
 
93
93
  const theme = $derived(style);
94
+ const measure = useTextWidth();
95
+ /** Width of a row label in the axis font, measured once mounted. */
96
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
94
97
  const numbers = $derived(createLocale(locale ?? theme.defaultLocale));
95
98
  const fmt = $derived(format ?? numbers.number);
96
99
  const signed = $derived(
@@ -115,7 +118,7 @@ anything.
115
118
  const p = previous(d);
116
119
  return { value: has(v) ? fmt(v) : '–', change: has(v) && has(p) ? signed(v - p) : '' };
117
120
  };
118
- const left = $derived(Math.max(...rows.map((d) => estimateTextWidth(label(d), fontSize)), 0) + 12);
121
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
119
122
  const right = $derived(
120
123
  Math.max(
121
124
  ...rows.map((d) => {
@@ -15,7 +15,7 @@ project and change anything.
15
15
  import { group, sum } from 'd3-array';
16
16
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
17
17
  import type { ChartEmbed } from '../embed/index.js';
18
- import { Plot, Svg, estimateTextWidth, type PlotContext } from '../core/index.js';
18
+ import { Plot, Svg, estimateTextWidth, useTextWidth, type PlotContext } from '../core/index.js';
19
19
  import { Rects } from '../marks/index.js';
20
20
  import { AxisX, Legend } from '../guides/index.js';
21
21
  import { RefLine } from '../annotations/index.js';
@@ -94,6 +94,9 @@ project and change anything.
94
94
  }: Props = $props();
95
95
 
96
96
  const theme = $derived(style);
97
+ const measure = useTextWidth();
98
+ /** Width of a row label in the axis font, measured once mounted. */
99
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
97
100
  const loc = $derived(createLocale(locale ?? theme.defaultLocale));
98
101
  const fmt = $derived(format ?? ((s: number) => loc.format('.1%')(s)));
99
102
  const fontSize = $derived(theme.plot.fontSize);
@@ -157,7 +160,7 @@ project and change anything.
157
160
  (({ width: w }: { width: number }) =>
158
161
  Math.max(480, layout.bands.length * (fontSize + 4) * 1.4, Math.min(900, w * 1.1)))
159
162
  );
160
- const right = $derived(Math.max(...layout.bands.map((b) => estimateTextWidth(b.name, fontSize))) + 18);
163
+ const right = $derived(Math.max(...layout.bands.map((b) => labelWidth(b.name))) + 18);
161
164
 
162
165
  /** Row labels at the centre of each row, nudged apart; a short tick joins a moved label to its row. */
163
166
  function rowLabels(plot: PlotContext) {
@@ -15,7 +15,7 @@ your project and change anything.
15
15
  import { scaleBand, scaleLinear } from 'd3-scale';
16
16
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
17
17
  import type { ChartEmbed } from '../embed/index.js';
18
- import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
18
+ import { Plot, Svg, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
19
19
  import { Rects } from '../marks/index.js';
20
20
  import { AxisX, AxisY, Legend } from '../guides/index.js';
21
21
  import { RefLine } from '../annotations/index.js';
@@ -103,6 +103,9 @@ your project and change anything.
103
103
  }: Props = $props();
104
104
 
105
105
  const theme = $derived(style);
106
+ const measure = useTextWidth();
107
+ /** Width of a row label in the axis font, measured once mounted. */
108
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
106
109
  const loc = $derived(createLocale(locale ?? theme.defaultLocale));
107
110
  const fmt = $derived(format ?? ((s: number) => loc.format('.1%')(s)));
108
111
  const fontSize = $derived(theme.plot.fontSize);
@@ -133,7 +136,7 @@ your project and change anything.
133
136
  const single = $derived(rows.length === 1);
134
137
  const x = scaleLinear().domain([0, 1]);
135
138
  const y = $derived(scaleBand<string>().domain(rows).paddingInner(0.25));
136
- const left = $derived(single ? 0 : Math.max(...rows.map((r) => estimateTextWidth(r, fontSize))) + 12);
139
+ const left = $derived(single ? 0 : Math.max(...rows.map((r) => labelWidth(r))) + 12);
137
140
  const bracketSpace = $derived(groups.length ? fontSize + 14 : 0);
138
141
 
139
142
  /** Segment labels: name over value, when both lines fit the segment. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samizdata/mozaic",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Chart components for the web and print, built on Svelte 5 and d3, and the mozaic CLI (export embeds to SVG, PDF and PNG; eject recipes).",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "author": "Nicu Calcea",
@@ -13,7 +13,7 @@ project and change anything.
13
13
  import { max, min } from 'd3-array';
14
14
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
15
15
  import type { ChartEmbed } from '../embed/index.js';
16
- import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
16
+ import { Plot, Svg, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
17
17
  import { Arrows } from '../marks/index.js';
18
18
  import { AxisX, AxisY, GridX } from '../guides/index.js';
19
19
  import { createLocale, type LocaleCode } from '../locale/index.js';
@@ -88,6 +88,9 @@ project and change anything.
88
88
  }: Props = $props();
89
89
 
90
90
  const theme = $derived(style);
91
+ const measure = useTextWidth();
92
+ /** Width of a row label in the axis font, measured once mounted. */
93
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
91
94
  const fmt = $derived(format ?? createLocale(locale ?? theme.defaultLocale).number);
92
95
  const fontSize = $derived(theme.plot.fontSize);
93
96
  const has = (v: Maybe): v is number => v !== null && v !== undefined && Number.isFinite(v);
@@ -111,7 +114,7 @@ project and change anything.
111
114
  );
112
115
  const y = $derived(scaleBand<string>().domain(rows.map(label)).paddingInner(0.25).paddingOuter(0.1));
113
116
  const textWidth = (s: string) => estimateTextWidth(s, fontSize);
114
- const left = $derived(Math.max(...rows.map((d) => textWidth(label(d))), 0) + 12);
117
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
115
118
  const right = $derived(Math.max(...all.map((v) => textWidth(fmt(v))), 0) + 12);
116
119
  const labelled = $derived(Boolean(startLabel || endLabel) && both.length > 0);
117
120
 
@@ -10,7 +10,7 @@ file into your project and change anything.
10
10
  import { max, min } from 'd3-array';
11
11
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
12
12
  import type { ChartEmbed } from '../embed/index.js';
13
- import { Plot, Svg, Html, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
13
+ import { Plot, Svg, Html, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
14
14
  import { Bars, Rules, Text } from '../marks/index.js';
15
15
  import { AxisY } from '../guides/index.js';
16
16
  import { Tooltip } from '../interactive/index.js';
@@ -66,6 +66,9 @@ file into your project and change anything.
66
66
  }: Props = $props();
67
67
 
68
68
  const theme = $derived(style);
69
+ const measure = useTextWidth();
70
+ /** Width of a row label in the axis font, measured once mounted. */
71
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
69
72
  const fmt = $derived(format ?? createLocale(locale ?? theme.defaultLocale).number);
70
73
  const rows = $derived(sort ? data.toSorted((a, b) => value(b) - value(a)) : data);
71
74
  const x = $derived(
@@ -74,7 +77,7 @@ file into your project and change anything.
74
77
  .nice()
75
78
  );
76
79
  const y = $derived(scaleBand<string>().domain(rows.map(label)).paddingInner(0.25).paddingOuter(0.1));
77
- const left = $derived(Math.max(...rows.map((d) => estimateTextWidth(label(d), theme.plot.fontSize)), 0) + 12);
80
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
78
81
  const right = $derived(Math.max(...rows.map((d) => estimateTextWidth(fmt(value(d)), theme.plot.fontSize)), 0) + 12);
79
82
  let hovered = $state<T | null>(null);
80
83
  </script>
@@ -13,7 +13,7 @@ anything.
13
13
  import { max, min } from 'd3-array';
14
14
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
15
15
  import type { ChartEmbed } from '../embed/index.js';
16
- import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
16
+ import { Plot, Svg, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
17
17
  import { Bars, Points } from '../marks/index.js';
18
18
  import { AxisX, AxisY, GridX, Legend } from '../guides/index.js';
19
19
  import { createLocale, type LocaleCode } from '../locale/index.js';
@@ -91,6 +91,9 @@ anything.
91
91
  }: Props = $props();
92
92
 
93
93
  const theme = $derived(style);
94
+ const measure = useTextWidth();
95
+ /** Width of a row label in the axis font, measured once mounted. */
96
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
94
97
  const numbers = $derived(createLocale(locale ?? theme.defaultLocale));
95
98
  const fmt = $derived(format ?? numbers.number);
96
99
  const signed = $derived(
@@ -115,7 +118,7 @@ anything.
115
118
  const p = previous(d);
116
119
  return { value: has(v) ? fmt(v) : '–', change: has(v) && has(p) ? signed(v - p) : '' };
117
120
  };
118
- const left = $derived(Math.max(...rows.map((d) => estimateTextWidth(label(d), fontSize)), 0) + 12);
121
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
119
122
  const right = $derived(
120
123
  Math.max(
121
124
  ...rows.map((d) => {
@@ -15,7 +15,7 @@ project and change anything.
15
15
  import { group, sum } from 'd3-array';
16
16
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
17
17
  import type { ChartEmbed } from '../embed/index.js';
18
- import { Plot, Svg, estimateTextWidth, type PlotContext } from '../core/index.js';
18
+ import { Plot, Svg, estimateTextWidth, useTextWidth, type PlotContext } from '../core/index.js';
19
19
  import { Rects } from '../marks/index.js';
20
20
  import { AxisX, Legend } from '../guides/index.js';
21
21
  import { RefLine } from '../annotations/index.js';
@@ -94,6 +94,9 @@ project and change anything.
94
94
  }: Props = $props();
95
95
 
96
96
  const theme = $derived(style);
97
+ const measure = useTextWidth();
98
+ /** Width of a row label in the axis font, measured once mounted. */
99
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
97
100
  const loc = $derived(createLocale(locale ?? theme.defaultLocale));
98
101
  const fmt = $derived(format ?? ((s: number) => loc.format('.1%')(s)));
99
102
  const fontSize = $derived(theme.plot.fontSize);
@@ -157,7 +160,7 @@ project and change anything.
157
160
  (({ width: w }: { width: number }) =>
158
161
  Math.max(480, layout.bands.length * (fontSize + 4) * 1.4, Math.min(900, w * 1.1)))
159
162
  );
160
- const right = $derived(Math.max(...layout.bands.map((b) => estimateTextWidth(b.name, fontSize))) + 18);
163
+ const right = $derived(Math.max(...layout.bands.map((b) => labelWidth(b.name))) + 18);
161
164
 
162
165
  /** Row labels at the centre of each row, nudged apart; a short tick joins a moved label to its row. */
163
166
  function rowLabels(plot: PlotContext) {
@@ -15,7 +15,7 @@ your project and change anything.
15
15
  import { scaleBand, scaleLinear } from 'd3-scale';
16
16
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
17
17
  import type { ChartEmbed } from '../embed/index.js';
18
- import { Plot, Svg, estimateTextWidth, scaled, type PlotContext } from '../core/index.js';
18
+ import { Plot, Svg, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
19
19
  import { Rects } from '../marks/index.js';
20
20
  import { AxisX, AxisY, Legend } from '../guides/index.js';
21
21
  import { RefLine } from '../annotations/index.js';
@@ -103,6 +103,9 @@ your project and change anything.
103
103
  }: Props = $props();
104
104
 
105
105
  const theme = $derived(style);
106
+ const measure = useTextWidth();
107
+ /** Width of a row label in the axis font, measured once mounted. */
108
+ const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
106
109
  const loc = $derived(createLocale(locale ?? theme.defaultLocale));
107
110
  const fmt = $derived(format ?? ((s: number) => loc.format('.1%')(s)));
108
111
  const fontSize = $derived(theme.plot.fontSize);
@@ -133,7 +136,7 @@ your project and change anything.
133
136
  const single = $derived(rows.length === 1);
134
137
  const x = scaleLinear().domain([0, 1]);
135
138
  const y = $derived(scaleBand<string>().domain(rows).paddingInner(0.25));
136
- const left = $derived(single ? 0 : Math.max(...rows.map((r) => estimateTextWidth(r, fontSize))) + 12);
139
+ const left = $derived(single ? 0 : Math.max(...rows.map((r) => labelWidth(r))) + 12);
137
140
  const bracketSpace = $derived(groups.length ? fontSize + 14 : 0);
138
141
 
139
142
  /** Segment labels: name over value, when both lines fit the segment. */