@samizdata/mozaic 0.9.0 → 0.11.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
  }
@@ -0,0 +1,10 @@
1
+ import type { Browser } from 'playwright-core';
2
+
3
+ /** Chromium executables to try, in order: `explicit`, $MOZAIC_BROWSER, Playwright's, the system's. */
4
+ export function browserCandidates(explicit?: string): string[];
5
+ /** The first Chromium found, or `undefined`. */
6
+ export function findBrowser(explicit?: string): string | undefined;
7
+ /** Launch the first Chromium that starts; with `explicit`, only that one. */
8
+ export function launchBrowser(explicit?: string): Promise<Browser>;
9
+ /** Serve a static folder on 127.0.0.1 at a random port; directories get their index.html. */
10
+ export function serveStatic(dir: string): Promise<{ url: string; close: () => Promise<void> }>;
@@ -0,0 +1,4 @@
1
+ // The CLI's building blocks, for scripts that render charts their own way (images for social media, say):
2
+ // `import { launchBrowser, serveStatic } from '@samizdata/mozaic/cli'`.
3
+ export { browserCandidates, findBrowser, launchBrowser } from './browser.js';
4
+ export { serveStatic } from './serve.js';
@@ -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
+ }
@@ -1,12 +1,14 @@
1
1
  <!--
2
2
  @component
3
3
  Horizontal axis for the plot's x scale. Tick labels use the chart's locale
4
- unless you pass `format`.
4
+ unless you pass `format`. On a continuous scale, labels that would overlap are
5
+ thinned to every other tick (or every third, and so on); the tick marks stay.
5
6
  -->
6
7
  <script lang="ts">
7
8
  import { useChart, usePlot } from '../core/context.js';
8
9
  import { estimateTextWidth, scaled } from '../core/scales.js';
9
- import { defaultTickFormat, tickValues } from './ticks.js';
10
+ import { useTextWidth } from '../core/text.svelte.js';
11
+ import { defaultTickFormat, tickStride, tickValues } from './ticks.js';
10
12
 
11
13
  interface Props {
12
14
  /** Approximate number of ticks for continuous scales. */
@@ -46,6 +48,17 @@ unless you pass `format`.
46
48
  const values = $derived(tickValues(plot.x, ticks ?? chart.theme.plot.ticks, explicitValues));
47
49
  const fmt = $derived(format ?? defaultTickFormat(values, chart.locale));
48
50
  const dir = $derived(position === 'bottom' ? 1 : -1);
51
+ const measure = useTextWidth();
52
+ const items = $derived(values.map((value, i) => ({ value, px: scaled(plot.x, value), label: fmt(value, i) })));
53
+ // Band and point scales name every category, so only continuous scales are thinned.
54
+ const stride = $derived(
55
+ plot.x.bandwidth
56
+ ? 1
57
+ : tickStride(
58
+ items.map((t) => t.px),
59
+ items.map((t) => measure(t.label, chart.theme.plot.fontSize, chart.theme.tokens['--mz-font-body']))
60
+ )
61
+ );
49
62
 
50
63
  // Labels that would spill past the chart edge are anchored inwards instead of centred.
51
64
  function anchor(px: number, label: string): 'start' | 'middle' | 'end' {
@@ -58,18 +71,18 @@ unless you pass `format`.
58
71
 
59
72
  <g class="mz-axis mz-axis-x {className}" transform="translate(0,{position === 'bottom' ? plot.height : 0})">
60
73
  {#if baseline}<line class="mz-axis-line" x2={plot.width} />{/if}
61
- {#each values as value, i (value)}
62
- {@const px = scaled(plot.x, value)}
63
- {@const label = fmt(value, i)}
74
+ {#each items as { value, px, label }, i (value)}
64
75
  <g class="mz-tick" transform="translate({px},0)">
65
76
  {#if tickSize > 0}<line y2={dir * tickSize} />{/if}
66
- <text
67
- y={dir * (tickSize + tickPadding)}
68
- dy={position === 'bottom' ? '0.71em' : '0'}
69
- text-anchor={anchor(px, label)}
70
- >
71
- {label}
72
- </text>
77
+ {#if i % stride === 0}
78
+ <text
79
+ y={dir * (tickSize + tickPadding)}
80
+ dy={position === 'bottom' ? '0.71em' : '0'}
81
+ text-anchor={anchor(px, label)}
82
+ >
83
+ {label}
84
+ </text>
85
+ {/if}
73
86
  </g>
74
87
  {/each}
75
88
  {#if label}
@@ -15,7 +15,8 @@ interface Props {
15
15
  }
16
16
  /**
17
17
  * Horizontal axis for the plot's x scale. Tick labels use the chart's locale
18
- * unless you pass `format`.
18
+ * unless you pass `format`. On a continuous scale, labels that would overlap are
19
+ * thinned to every other tick (or every third, and so on); the tick marks stay.
19
20
  */
20
21
  declare const AxisX: import("svelte").Component<Props, {}, "">;
21
22
  type AxisX = ReturnType<typeof AxisX>;
@@ -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>;
@@ -4,3 +4,8 @@ import type { PositionScale } from '../core/types.js';
4
4
  export declare function tickValues(scale: PositionScale, count: number, explicit?: unknown[]): unknown[];
5
5
  /** Locale-aware default label: dates by multiTimeFormat, numbers with grouping, anything else as text. */
6
6
  export declare function defaultTickFormat(values: unknown[], locale: Locale): (value: any) => string;
7
+ /**
8
+ * Every how many ticks to label so that no two labels overlap: 1 when all fit, 2 for every other one,
9
+ * and so on. `positions` are the ticks' centres in px (in order), `widths` their labels' widths.
10
+ */
11
+ export declare function tickStride(positions: number[], widths: number[], gap?: number): number;
@@ -13,3 +13,19 @@ export function defaultTickFormat(values, locale) {
13
13
  return locale.number;
14
14
  return (value) => String(value);
15
15
  }
16
+ /**
17
+ * Every how many ticks to label so that no two labels overlap: 1 when all fit, 2 for every other one,
18
+ * and so on. `positions` are the ticks' centres in px (in order), `widths` their labels' widths.
19
+ */
20
+ export function tickStride(positions, widths, gap = 8) {
21
+ for (let stride = 1; stride < positions.length; stride++) {
22
+ let fits = true;
23
+ for (let i = stride; i < positions.length && fits; i += stride) {
24
+ const room = Math.abs(positions[i] - positions[i - stride]);
25
+ fits = room >= (widths[i] + widths[i - stride]) / 2 + gap;
26
+ }
27
+ if (fits)
28
+ return stride;
29
+ }
30
+ return Math.max(1, positions.length);
31
+ }
@@ -3,13 +3,15 @@
3
3
  Direct labels at the end of lines: a dot in the series colour on the last
4
4
  point, and the label beside it, in the text colour or (with `colorText`) in
5
5
  the series colour so the labels double as the legend. Labels are nudged apart
6
- so they never overlap; a short leader joins a nudged label to its dot.
6
+ so they never overlap; a short leader joins a nudged label to its dot. A label
7
+ too long for the room right of the plot breaks onto two or more lines.
7
8
  -->
8
9
  <script lang="ts" generics="T">
9
10
  import { useChart, usePlot } from '../core/context.js';
10
11
  import { scaled } from '../core/scales.js';
12
+ import { useTextWidth } from '../core/text.svelte.js';
11
13
  import { readableColor } from '../styles/color.js';
12
- import { avoidOverlap } from '../transforms/labels.js';
14
+ import { avoidOverlap, wrapLabel } from '../transforms/labels.js';
13
15
 
14
16
  interface Props {
15
17
  /** One item per series, describing its last point. */
@@ -27,21 +29,47 @@ so they never overlap; a short leader joins a nudged label to its dot.
27
29
  * backgrounds) where needed to reach 4.5:1 against the background.
28
30
  */
29
31
  colorText?: boolean;
32
+ /** Draw the dot on the last point; turn it off when the point has a mark of its own. */
33
+ dot?: boolean;
30
34
  class?: string;
31
35
  }
32
36
 
33
- let { data, x, y, text, color, dx = 10, minGap = 14, colorText = false, class: className = '' }: Props = $props();
37
+ let {
38
+ data,
39
+ x,
40
+ y,
41
+ text,
42
+ color,
43
+ dx = 10,
44
+ minGap = 14,
45
+ colorText = false,
46
+ dot = true,
47
+ class: className = ''
48
+ }: Props = $props();
34
49
 
35
50
  const chart = useChart();
36
51
  const plot = usePlot();
37
52
  const background = $derived(chart.theme.tokens['--mz-color-bg']);
38
53
 
54
+ const measure = useTextWidth();
55
+ /** Line height of a wrapped label, in em. */
56
+ const leading = 1.15;
57
+
39
58
  const labels = $derived.by(() => {
40
- const points = data.map((d) => ({ d, px: scaled(plot.x, x(d)), py: scaled(plot.y, y(d)) }));
59
+ const size = chart.theme.plot.fontSize;
60
+ const width = (s: string) => measure(s, size, chart.theme.tokens['--mz-font-body']);
61
+ const points = data.map((d) => {
62
+ const px = scaled(plot.x, x(d));
63
+ // Room from the label's start to the chart's right edge, less a pixel or two for the halo.
64
+ const room = plot.width + plot.padding.right - (px + dx) - 2;
65
+ return { d, px, py: scaled(plot.y, y(d)), lines: wrapLabel(text(d), room, width) };
66
+ });
67
+ const lineGap = (size * leading) / minGap;
41
68
  const placed = avoidOverlap(
42
69
  points.map((p) => p.py),
43
70
  minGap,
44
- [0, plot.height]
71
+ [0, plot.height],
72
+ points.map((p) => 1 + (p.lines.length - 1) * lineGap)
45
73
  );
46
74
  return points.map((p, i) => ({ ...p, ly: placed[i] }));
47
75
  });
@@ -52,12 +80,16 @@ so they never overlap; a short leader joins a nudged label to its dot.
52
80
  {#if Math.abs(label.ly - label.py) > 2}
53
81
  <path class="mz-leader" d="M{label.px + 5},{label.py}L{label.px + dx - 3},{label.ly}" />
54
82
  {/if}
55
- <circle cx={label.px} cy={label.py} r={4} fill={color(label.d)} />
83
+ {#if dot}<circle cx={label.px} cy={label.py} r={4} fill={color(label.d)} />{/if}
56
84
  <text
57
85
  x={label.px + dx}
58
86
  y={label.ly}
59
- dy="0.32em"
60
- style:fill={colorText ? readableColor(color(label.d), background) : undefined}>{text(label.d)}</text
87
+ dy={label.lines.length === 1 ? '0.32em' : undefined}
88
+ style:fill={colorText ? readableColor(color(label.d), background) : undefined}
89
+ >{#if label.lines.length === 1}{label.lines[0]}{:else}{#each label.lines as line, i (i)}<tspan
90
+ x={label.px + dx}
91
+ dy={i === 0 ? `${0.32 - ((label.lines.length - 1) * leading) / 2}em` : `${leading}em`}>{line}</tspan
92
+ >{/each}{/if}</text
61
93
  >
62
94
  {/each}
63
95
  </g>
@@ -15,6 +15,8 @@ declare function $$render<T>(): {
15
15
  * backgrounds) where needed to reach 4.5:1 against the background.
16
16
  */
17
17
  colorText?: boolean;
18
+ /** Draw the dot on the last point; turn it off when the point has a mark of its own. */
19
+ dot?: boolean;
18
20
  class?: string;
19
21
  };
20
22
  exports: {};
@@ -40,7 +42,8 @@ interface $$IsomorphicComponent {
40
42
  * Direct labels at the end of lines: a dot in the series colour on the last
41
43
  * point, and the label beside it, in the text colour or (with `colorText`) in
42
44
  * the series colour so the labels double as the legend. Labels are nudged apart
43
- * so they never overlap; a short leader joins a nudged label to its dot.
45
+ * so they never overlap; a short leader joins a nudged label to its dot. A label
46
+ * too long for the room right of the plot breaks onto two or more lines.
44
47
  */
45
48
  declare const LineEndLabels: $$IsomorphicComponent;
46
49
  type LineEndLabels<T> = InstanceType<typeof LineEndLabels<T>>;
@@ -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. */
@@ -1,4 +1,4 @@
1
- export { avoidOverlap } from './labels.js';
1
+ export { avoidOverlap, wrapLabel } from './labels.js';
2
2
  export { stack, type StackedRow, type StackOptions } from './stack.js';
3
3
  export { bin, type Bin } from './bin.js';
4
4
  export { groupBy, indexTo, rollup } from './group.js';
@@ -1,4 +1,4 @@
1
- export { avoidOverlap } from './labels.js';
1
+ export { avoidOverlap, wrapLabel } from './labels.js';
2
2
  export { stack } from './stack.js';
3
3
  export { bin } from './bin.js';
4
4
  export { groupBy, indexTo, rollup } from './group.js';
@@ -1,6 +1,12 @@
1
1
  /**
2
2
  * Nudge 1-D label positions apart so neighbours are at least `gap` px apart,
3
3
  * keeping them inside [min, max] where possible. Returns positions in the
4
- * original order. Used for direct line labels.
4
+ * original order. Used for direct line labels. `sizes` gives labels of
5
+ * several lines their room: a label of size 2 needs twice the gap.
5
6
  */
6
- export declare function avoidOverlap(positions: number[], gap: number, [min, max]?: [number, number]): number[];
7
+ export declare function avoidOverlap(positions: number[], gap: number, [min, max]?: [number, number], sizes?: number[]): number[];
8
+ /**
9
+ * Break `text` at spaces into lines no wider than `maxWidth` (by `measure`), for a label that would
10
+ * otherwise run off the chart. A word wider than `maxWidth` stays whole on its own line.
11
+ */
12
+ export declare function wrapLabel(text: string, maxWidth: number, measure: (text: string) => number): string[];
@@ -1,20 +1,48 @@
1
1
  /**
2
2
  * Nudge 1-D label positions apart so neighbours are at least `gap` px apart,
3
3
  * keeping them inside [min, max] where possible. Returns positions in the
4
- * original order. Used for direct line labels.
4
+ * original order. Used for direct line labels. `sizes` gives labels of
5
+ * several lines their room: a label of size 2 needs twice the gap.
5
6
  */
6
- export function avoidOverlap(positions, gap, [min, max] = [-Infinity, Infinity]) {
7
+ export function avoidOverlap(positions, gap, [min, max] = [-Infinity, Infinity], sizes) {
7
8
  const order = positions.map((p, i) => ({ p, i })).sort((a, b) => a.p - b.p);
8
9
  const placed = order.map((o) => Math.min(max, Math.max(min, o.p)));
10
+ // With `sizes` (each label's height, in multiples of `gap`), neighbours are kept half of each apart.
11
+ const size = (k) => sizes?.[order[k].i] ?? 1;
12
+ const apart = (k) => (gap * (size(k - 1) + size(k))) / 2;
13
+ const edge = (k) => (gap * (size(k) - 1)) / 2;
9
14
  // Push down from the top, then back up from the bottom if we ran past `max`.
10
15
  for (let k = 1; k < placed.length; k++)
11
- placed[k] = Math.max(placed[k], placed[k - 1] + gap);
12
- if (placed.length && placed[placed.length - 1] > max) {
13
- placed[placed.length - 1] = max;
14
- for (let k = placed.length - 2; k >= 0; k--)
15
- placed[k] = Math.min(placed[k], placed[k + 1] - gap);
16
+ placed[k] = Math.max(placed[k], placed[k - 1] + apart(k));
17
+ const last = placed.length - 1;
18
+ if (placed.length && placed[last] > max - edge(last)) {
19
+ placed[last] = max - edge(last);
20
+ for (let k = last - 1; k >= 0; k--)
21
+ placed[k] = Math.min(placed[k], placed[k + 1] - apart(k + 1));
16
22
  }
17
23
  const result = new Array(positions.length);
18
24
  order.forEach((o, k) => (result[o.i] = placed[k]));
19
25
  return result;
20
26
  }
27
+ /**
28
+ * Break `text` at spaces into lines no wider than `maxWidth` (by `measure`), for a label that would
29
+ * otherwise run off the chart. A word wider than `maxWidth` stays whole on its own line.
30
+ */
31
+ export function wrapLabel(text, maxWidth, measure) {
32
+ if (measure(text) <= maxWidth)
33
+ return [text];
34
+ const lines = [];
35
+ let line = '';
36
+ for (const word of text.split(' ')) {
37
+ const next = line ? `${line} ${word}` : word;
38
+ if (line && measure(next) > maxWidth) {
39
+ lines.push(line);
40
+ line = word;
41
+ }
42
+ else
43
+ line = next;
44
+ }
45
+ if (line)
46
+ lines.push(line);
47
+ return lines;
48
+ }
package/package.json CHANGED
@@ -1,165 +1,171 @@
1
1
  {
2
- "name": "@samizdata/mozaic",
3
- "version": "0.9.0",
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
- "license": "GPL-3.0-or-later",
6
- "author": "Nicu Calcea",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/samizdata-co/mozaic.git",
10
- "directory": "packages/mozaic"
11
- },
12
- "homepage": "https://github.com/samizdata-co/mozaic#readme",
13
- "bugs": "https://github.com/samizdata-co/mozaic/issues",
14
- "type": "module",
15
- "bin": {
16
- "mozaic": "./cli/bin/mozaic.js"
17
- },
18
- "files": [
19
- "dist",
20
- "src/lib/recipes",
21
- "cli/bin",
22
- "cli/src",
23
- "!dist/**/*.test.*",
24
- "!dist/**/*.spec.*"
25
- ],
26
- "sideEffects": [
27
- "**/*.css"
28
- ],
29
- "svelte": "./dist/index.js",
30
- "types": "./dist/index.d.ts",
31
- "exports": {
32
- ".": {
33
- "mozaic-dev": "./src/lib/index.ts",
34
- "types": "./dist/index.d.ts",
35
- "svelte": "./dist/index.js"
36
- },
37
- "./core": {
38
- "mozaic-dev": "./src/lib/core/index.ts",
39
- "types": "./dist/core/index.d.ts",
40
- "svelte": "./dist/core/index.js"
41
- },
42
- "./marks": {
43
- "mozaic-dev": "./src/lib/marks/index.ts",
44
- "types": "./dist/marks/index.d.ts",
45
- "svelte": "./dist/marks/index.js"
46
- },
47
- "./guides": {
48
- "mozaic-dev": "./src/lib/guides/index.ts",
49
- "types": "./dist/guides/index.d.ts",
50
- "svelte": "./dist/guides/index.js"
51
- },
52
- "./annotations": {
53
- "mozaic-dev": "./src/lib/annotations/index.ts",
54
- "types": "./dist/annotations/index.d.ts",
55
- "svelte": "./dist/annotations/index.js"
56
- },
57
- "./interactive": {
58
- "mozaic-dev": "./src/lib/interactive/index.ts",
59
- "types": "./dist/interactive/index.d.ts",
60
- "svelte": "./dist/interactive/index.js"
61
- },
62
- "./frame": {
63
- "mozaic-dev": "./src/lib/frame/index.ts",
64
- "types": "./dist/frame/index.d.ts",
65
- "svelte": "./dist/frame/index.js"
66
- },
67
- "./table": {
68
- "mozaic-dev": "./src/lib/table/index.ts",
69
- "types": "./dist/table/index.d.ts",
70
- "svelte": "./dist/table/index.js"
71
- },
72
- "./embed": {
73
- "mozaic-dev": "./src/lib/embed/index.ts",
74
- "types": "./dist/embed/index.d.ts",
75
- "svelte": "./dist/embed/index.js"
76
- },
77
- "./export": {
78
- "mozaic-dev": "./src/lib/export/index.ts",
79
- "types": "./dist/export/index.d.ts",
80
- "svelte": "./dist/export/index.js"
81
- },
82
- "./recipes": {
83
- "mozaic-dev": "./src/lib/recipes/index.ts",
84
- "types": "./dist/recipes/index.d.ts",
85
- "svelte": "./dist/recipes/index.js"
86
- },
87
- "./styles": {
88
- "mozaic-dev": "./src/lib/styles/index.ts",
89
- "types": "./dist/styles/index.d.ts",
90
- "default": "./dist/styles/index.js"
91
- },
92
- "./locale": {
93
- "mozaic-dev": "./src/lib/locale/index.ts",
94
- "types": "./dist/locale/index.d.ts",
95
- "default": "./dist/locale/index.js"
96
- },
97
- "./transforms": {
98
- "mozaic-dev": "./src/lib/transforms/index.ts",
99
- "types": "./dist/transforms/index.d.ts",
100
- "default": "./dist/transforms/index.js"
101
- },
102
- "./package.json": "./package.json"
103
- },
104
- "peerDependencies": {
105
- "svelte": "^5.57.0"
106
- },
107
- "dependencies": {
108
- "d3-array": "^3.2.4",
109
- "d3-delaunay": "^6.0.4",
110
- "d3-format": "^3.1.0",
111
- "d3-geo": "^3.1.1",
112
- "d3-hierarchy": "^3.1.2",
113
- "d3-scale": "^4.0.2",
114
- "d3-shape": "^3.2.0",
115
- "d3-time-format": "^4.1.0",
116
- "playwright-core": "1.64.1"
117
- },
118
- "devDependencies": {
119
- "@sveltejs/adapter-auto": "^8.0.0",
120
- "@sveltejs/kit": "^3.1.0",
121
- "@sveltejs/package": "^3.0.1",
122
- "@sveltejs/vite-plugin-svelte": "^7.3.1",
123
- "@types/d3-array": "^3.2.1",
124
- "@types/d3-delaunay": "^6.0.4",
125
- "@types/d3-format": "^3.0.4",
126
- "@types/d3-geo": "^3.1.0",
127
- "@types/d3-hierarchy": "^3.1.7",
128
- "@types/d3-scale": "^4.0.8",
129
- "@types/d3-scale-chromatic": "^3.1.0",
130
- "@types/d3-shape": "^3.1.6",
131
- "@types/d3-time-format": "^4.0.3",
132
- "@types/geojson": "^7946.0.14",
133
- "@types/node": "^24.0.0",
134
- "@vitest/coverage-v8": "^4.1.12",
135
- "d3-scale-chromatic": "^3.1.0",
136
- "linkedom": "^0.18.14",
137
- "publint": "^0.3.21",
138
- "svelte": "^5.57.2",
139
- "svelte-check": "^4.6.0",
140
- "typescript": "^6.0.3",
141
- "vite": "^8.3.5",
142
- "vitest": "^4.1.8"
143
- },
144
- "keywords": [
145
- "svelte",
146
- "charts",
147
- "dataviz",
148
- "d3"
149
- ],
150
- "imports": {
151
- "#lib": "./src/lib/index.js",
152
- "#lib/*": "./src/lib/*"
153
- },
154
- "engines": {
155
- "node": ">=22.17"
156
- },
157
- "scripts": {
158
- "dev": "vite dev",
159
- "package": "svelte-kit sync && svelte-package && publint",
160
- "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && tsc -p cli/jsconfig.json",
161
- "test:unit": "vitest",
162
- "test": "vitest --run",
163
- "test:coverage": "vitest --run --coverage"
164
- }
165
- }
2
+ "name": "@samizdata/mozaic",
3
+ "version": "0.11.0",
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
+ "license": "GPL-3.0-or-later",
6
+ "author": "Nicu Calcea",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/samizdata-co/mozaic.git",
10
+ "directory": "packages/mozaic"
11
+ },
12
+ "homepage": "https://github.com/samizdata-co/mozaic#readme",
13
+ "bugs": "https://github.com/samizdata-co/mozaic/issues",
14
+ "type": "module",
15
+ "scripts": {
16
+ "dev": "vite dev",
17
+ "package": "svelte-kit sync && svelte-package && publint",
18
+ "prepare": "svelte-kit sync || echo ''",
19
+ "prepack": "pnpm package",
20
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && tsc -p cli/jsconfig.json",
21
+ "test:unit": "vitest",
22
+ "test": "vitest --run",
23
+ "test:coverage": "vitest --run --coverage"
24
+ },
25
+ "bin": {
26
+ "mozaic": "./cli/bin/mozaic.js"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "src/lib/recipes",
31
+ "cli/bin",
32
+ "cli/src",
33
+ "!dist/**/*.test.*",
34
+ "!dist/**/*.spec.*"
35
+ ],
36
+ "sideEffects": [
37
+ "**/*.css"
38
+ ],
39
+ "svelte": "./dist/index.js",
40
+ "types": "./dist/index.d.ts",
41
+ "exports": {
42
+ ".": {
43
+ "mozaic-dev": "./src/lib/index.ts",
44
+ "types": "./dist/index.d.ts",
45
+ "svelte": "./dist/index.js"
46
+ },
47
+ "./core": {
48
+ "mozaic-dev": "./src/lib/core/index.ts",
49
+ "types": "./dist/core/index.d.ts",
50
+ "svelte": "./dist/core/index.js"
51
+ },
52
+ "./marks": {
53
+ "mozaic-dev": "./src/lib/marks/index.ts",
54
+ "types": "./dist/marks/index.d.ts",
55
+ "svelte": "./dist/marks/index.js"
56
+ },
57
+ "./guides": {
58
+ "mozaic-dev": "./src/lib/guides/index.ts",
59
+ "types": "./dist/guides/index.d.ts",
60
+ "svelte": "./dist/guides/index.js"
61
+ },
62
+ "./annotations": {
63
+ "mozaic-dev": "./src/lib/annotations/index.ts",
64
+ "types": "./dist/annotations/index.d.ts",
65
+ "svelte": "./dist/annotations/index.js"
66
+ },
67
+ "./interactive": {
68
+ "mozaic-dev": "./src/lib/interactive/index.ts",
69
+ "types": "./dist/interactive/index.d.ts",
70
+ "svelte": "./dist/interactive/index.js"
71
+ },
72
+ "./frame": {
73
+ "mozaic-dev": "./src/lib/frame/index.ts",
74
+ "types": "./dist/frame/index.d.ts",
75
+ "svelte": "./dist/frame/index.js"
76
+ },
77
+ "./table": {
78
+ "mozaic-dev": "./src/lib/table/index.ts",
79
+ "types": "./dist/table/index.d.ts",
80
+ "svelte": "./dist/table/index.js"
81
+ },
82
+ "./embed": {
83
+ "mozaic-dev": "./src/lib/embed/index.ts",
84
+ "types": "./dist/embed/index.d.ts",
85
+ "svelte": "./dist/embed/index.js"
86
+ },
87
+ "./export": {
88
+ "mozaic-dev": "./src/lib/export/index.ts",
89
+ "types": "./dist/export/index.d.ts",
90
+ "svelte": "./dist/export/index.js"
91
+ },
92
+ "./recipes": {
93
+ "mozaic-dev": "./src/lib/recipes/index.ts",
94
+ "types": "./dist/recipes/index.d.ts",
95
+ "svelte": "./dist/recipes/index.js"
96
+ },
97
+ "./styles": {
98
+ "mozaic-dev": "./src/lib/styles/index.ts",
99
+ "types": "./dist/styles/index.d.ts",
100
+ "default": "./dist/styles/index.js"
101
+ },
102
+ "./locale": {
103
+ "mozaic-dev": "./src/lib/locale/index.ts",
104
+ "types": "./dist/locale/index.d.ts",
105
+ "default": "./dist/locale/index.js"
106
+ },
107
+ "./transforms": {
108
+ "mozaic-dev": "./src/lib/transforms/index.ts",
109
+ "types": "./dist/transforms/index.d.ts",
110
+ "default": "./dist/transforms/index.js"
111
+ },
112
+ "./cli": {
113
+ "types": "./cli/src/index.d.ts",
114
+ "default": "./cli/src/index.js"
115
+ },
116
+ "./package.json": "./package.json"
117
+ },
118
+ "peerDependencies": {
119
+ "svelte": "^5.57.0"
120
+ },
121
+ "dependencies": {
122
+ "d3-array": "^3.2.4",
123
+ "d3-delaunay": "^6.0.4",
124
+ "d3-format": "^3.1.0",
125
+ "d3-geo": "^3.1.1",
126
+ "d3-hierarchy": "^3.1.2",
127
+ "d3-scale": "^4.0.2",
128
+ "d3-shape": "^3.2.0",
129
+ "d3-time-format": "^4.1.0",
130
+ "playwright-core": "1.64.1"
131
+ },
132
+ "devDependencies": {
133
+ "@sveltejs/adapter-auto": "^8.0.0",
134
+ "@sveltejs/kit": "^3.1.0",
135
+ "@sveltejs/package": "^3.0.1",
136
+ "@sveltejs/vite-plugin-svelte": "^7.3.1",
137
+ "@types/d3-array": "^3.2.1",
138
+ "@types/d3-delaunay": "^6.0.4",
139
+ "@types/d3-format": "^3.0.4",
140
+ "@types/d3-geo": "^3.1.0",
141
+ "@types/d3-hierarchy": "^3.1.7",
142
+ "@types/d3-scale": "^4.0.8",
143
+ "@types/d3-scale-chromatic": "^3.1.0",
144
+ "@types/d3-shape": "^3.1.6",
145
+ "@types/d3-time-format": "^4.0.3",
146
+ "@types/geojson": "^7946.0.14",
147
+ "@types/node": "^24.0.0",
148
+ "@vitest/coverage-v8": "^4.1.12",
149
+ "d3-scale-chromatic": "^3.1.0",
150
+ "linkedom": "^0.18.14",
151
+ "publint": "^0.3.21",
152
+ "svelte": "^5.57.2",
153
+ "svelte-check": "^4.6.0",
154
+ "typescript": "^6.0.3",
155
+ "vite": "^8.3.5",
156
+ "vitest": "^4.1.8"
157
+ },
158
+ "keywords": [
159
+ "svelte",
160
+ "charts",
161
+ "dataviz",
162
+ "d3"
163
+ ],
164
+ "imports": {
165
+ "#lib": "./src/lib/index.js",
166
+ "#lib/*": "./src/lib/*"
167
+ },
168
+ "engines": {
169
+ "node": ">=22.17"
170
+ }
171
+ }
@@ -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. */