@samizdata/mozaic 0.11.0 → 0.12.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.
Files changed (42) hide show
  1. package/dist/flags/index.d.ts +16 -0
  2. package/dist/flags/index.js +16 -0
  3. package/dist/flags/svgs.d.ts +261 -0
  4. package/dist/flags/svgs.js +265 -0
  5. package/dist/guides/AxisX.svelte +18 -3
  6. package/dist/guides/AxisX.svelte.d.ts +4 -0
  7. package/dist/interactive/Tooltip.svelte +10 -3
  8. package/dist/locale/index.d.ts +8 -0
  9. package/dist/locale/index.js +10 -0
  10. package/dist/marks/Beeswarm.svelte +31 -12
  11. package/dist/marks/Beeswarm.svelte.d.ts +3 -0
  12. package/dist/marks/Flag.svelte +65 -0
  13. package/dist/marks/Flag.svelte.d.ts +27 -0
  14. package/dist/marks/Flags.svelte +69 -0
  15. package/dist/marks/Flags.svelte.d.ts +45 -0
  16. package/dist/marks/index.d.ts +2 -0
  17. package/dist/marks/index.js +2 -0
  18. package/dist/recipes/ArrowChart.svelte +4 -1
  19. package/dist/recipes/ArrowChart.svelte.d.ts +2 -0
  20. package/dist/recipes/BarChart.svelte +101 -17
  21. package/dist/recipes/BarChart.svelte.d.ts +20 -2
  22. package/dist/recipes/BarDotChart.svelte +4 -1
  23. package/dist/recipes/BarDotChart.svelte.d.ts +2 -0
  24. package/dist/recipes/ColumnChart.svelte +5 -2
  25. package/dist/recipes/ColumnChart.svelte.d.ts +2 -0
  26. package/dist/recipes/LineChart.svelte +8 -2
  27. package/dist/recipes/LineChart.svelte.d.ts +2 -0
  28. package/dist/recipes/ScatterChart.svelte +177 -17
  29. package/dist/recipes/ScatterChart.svelte.d.ts +40 -1
  30. package/dist/recipes/StripChart.svelte +301 -0
  31. package/dist/recipes/StripChart.svelte.d.ts +89 -0
  32. package/dist/recipes/index.d.ts +2 -1
  33. package/dist/recipes/index.js +3 -1
  34. package/package.json +174 -170
  35. package/src/lib/recipes/ArrowChart.svelte +4 -1
  36. package/src/lib/recipes/BarChart.svelte +101 -17
  37. package/src/lib/recipes/BarDotChart.svelte +4 -1
  38. package/src/lib/recipes/ColumnChart.svelte +5 -2
  39. package/src/lib/recipes/LineChart.svelte +8 -2
  40. package/src/lib/recipes/ScatterChart.svelte +177 -17
  41. package/src/lib/recipes/StripChart.svelte +301 -0
  42. package/src/lib/recipes/index.ts +3 -1
@@ -38,6 +38,8 @@ project.
38
38
  alt?: string;
39
39
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
40
40
  embed?: ChartEmbed;
41
+ /** Unit after the last value-axis tick label and the tooltip values, e.g. "lei/m³". */
42
+ unit?: string;
41
43
  format?: (n: number) => string;
42
44
  /** Tooltip date format (d3-time-format specifier). */
43
45
  dateFormat?: string;
@@ -64,6 +66,7 @@ project.
64
66
  source,
65
67
  alt,
66
68
  embed,
69
+ unit,
67
70
  format,
68
71
  dateFormat = '%B %Y',
69
72
  color,
@@ -110,7 +113,7 @@ project.
110
113
  {#snippet children(plot)}
111
114
  <Svg>
112
115
  <GridY ticks={5} />
113
- <AxisY ticks={5} format={fmt} inside={plot.breakpoint === 's'} />
116
+ <AxisY ticks={5} format={fmt} inside={plot.breakpoint === 's'} {unit} />
114
117
  <AxisX ticks={plot.breakpoint === 's' ? 4 : 7} />
115
118
  {#if hover}
116
119
  <line x1={plot.x(xValue(hover))} x2={plot.x(xValue(hover))} y2={plot.height} stroke="var(--mz-color-axis)" />
@@ -142,7 +145,10 @@ project.
142
145
  {#each series as s, i}
143
146
  {@const p = valueAt(s, date)}
144
147
  {#if p}
145
- <div><span style:color={colour(s, i)}>●</span> {name(s)}: <strong>{fmt(yValue(p))}</strong></div>
148
+ <div>
149
+ <span style:color={colour(s, i)}>●</span>
150
+ {name(s)}: <strong>{fmt(yValue(p))}{unit ? ` ${unit}` : ''}</strong>
151
+ </div>
146
152
  {/if}
147
153
  {/each}
148
154
  </Tooltip>
@@ -1,7 +1,12 @@
1
1
  <!--
2
2
  @component
3
3
  Recipe: a scatter plot with optional bubble sizes, colour groups, labels for
4
- selected points and a nearest-point tooltip. `mozaic eject ScatterChart`
4
+ selected points and a nearest-point tooltip. Pass `flag` to draw countries as
5
+ circular flags, as in ggflags. `quadrants` splits the plot at two reference
6
+ values (an average, a target) with dashed lines and says in each corner what
7
+ that quarter means, so readers know where "good" and "bad" are. `directions`
8
+ puts arrows on the axes ("Richer →"); with quadrants they replace the quarter
9
+ labels on charts too narrow for them. `mozaic eject ScatterChart`
5
10
  copies this file into your project.
6
11
  -->
7
12
  <script lang="ts" generics="T">
@@ -10,14 +15,29 @@ copies this file into your project.
10
15
  import { extent, max } from 'd3-array';
11
16
  import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
12
17
  import type { ChartEmbed } from '../embed/index.js';
13
- import { Plot, Svg, Html, type PlotContext } from '../core/index.js';
14
- import { Points, Voronoi } from '../marks/index.js';
18
+ import { Plot, Svg, Html, estimateTextWidth, type PlotContext } from '../core/index.js';
19
+ import { wrapLabel } from '../transforms/index.js';
20
+ import { Flags, Points, Voronoi } from '../marks/index.js';
15
21
  import { AxisX, AxisY, GridX, GridY, Legend } from '../guides/index.js';
16
- import { Label } from '../annotations/index.js';
22
+ import { Label, RefLine } from '../annotations/index.js';
17
23
  import { Tooltip } from '../interactive/index.js';
18
24
  import { createLocale, type LocaleCode } from '../locale/index.js';
19
25
  import { base, type Medium, type Theme } from '../styles/index.js';
20
26
 
27
+ interface Quadrants {
28
+ /** Where the vertical and horizontal dividing lines cross, in data units. */
29
+ x: number;
30
+ y: number;
31
+ /** Labels for the dividing lines, e.g. "EU average". */
32
+ xLabel?: string;
33
+ yLabel?: string;
34
+ /** What each quarter means, written in its outer corner. Newlines split a label; long lines wrap to fit the quarter. */
35
+ topLeft?: string;
36
+ topRight?: string;
37
+ bottomLeft?: string;
38
+ bottomRight?: string;
39
+ }
40
+
21
41
  interface Props {
22
42
  data: T[];
23
43
  x: (d: T) => number;
@@ -28,6 +48,10 @@ copies this file into your project.
28
48
  size?: (d: T) => number;
29
49
  /** Optional colour group. */
30
50
  group?: (d: T) => string;
51
+ /** The point's flag from `@samizdata/mozaic/flags`, drawn instead of a dot (rows without one keep their dot). */
52
+ flag?: (d: T) => string | null | undefined;
53
+ /** Labels to set in bold, e.g. the story's own country. */
54
+ emphasize?: (d: T) => boolean;
31
55
  /** Points to label permanently. */
32
56
  labelled?: (d: T) => boolean;
33
57
  style?: Theme;
@@ -46,6 +70,21 @@ copies this file into your project.
46
70
  yLabel?: string;
47
71
  xFormat?: (n: number) => string;
48
72
  yFormat?: (n: number) => string;
73
+ /** Units after the last tick label of each axis and the tooltip values, e.g. "euro a year". */
74
+ xUnit?: string;
75
+ yUnit?: string;
76
+ /** Axis domains; default to the data's extent, rounded. Start at zero to leave room in the corners. */
77
+ xDomain?: [number, number];
78
+ yDomain?: [number, number];
79
+ /** Dashed dividing lines and a label for each quarter (see `Quadrants`). */
80
+ quadrants?: Quadrants;
81
+ /**
82
+ * What the low and high ends of each axis mean, e.g. `{ x: ['Poorer', 'Richer'] }`: "← Poorer"
83
+ * and "Richer →" under the x axis, "↑ …" and "↓ …" inside the top and bottom left corners.
84
+ * With `quadrants`, drawn only when the quarter labels don't fit (narrow charts). Leave an end
85
+ * empty (`['', 'Richer']`) for a single arrow; the low end is dropped when both don't fit.
86
+ */
87
+ directions?: { x?: [string, string]; y?: [string, string] };
49
88
  height?: number;
50
89
  annotations?: Snippet<[PlotContext]>;
51
90
  }
@@ -57,7 +96,9 @@ copies this file into your project.
57
96
  name,
58
97
  size,
59
98
  group,
99
+ flag,
60
100
  labelled,
101
+ emphasize,
61
102
  style = base,
62
103
  locale,
63
104
  medium,
@@ -72,6 +113,12 @@ copies this file into your project.
72
113
  yLabel,
73
114
  xFormat,
74
115
  yFormat,
116
+ xUnit,
117
+ yUnit,
118
+ xDomain,
119
+ yDomain,
120
+ quadrants,
121
+ directions,
75
122
  height = 360,
76
123
  annotations
77
124
  }: Props = $props();
@@ -80,12 +127,12 @@ copies this file into your project.
80
127
  const loc = $derived(createLocale(locale ?? theme.defaultLocale));
81
128
  const x = $derived(
82
129
  scaleLinear()
83
- .domain(extent(data, xValue) as [number, number])
130
+ .domain(xDomain ?? (extent(data, xValue) as [number, number]))
84
131
  .nice()
85
132
  );
86
133
  const y = $derived(
87
134
  scaleLinear()
88
- .domain(extent(data, yValue) as [number, number])
135
+ .domain(yDomain ?? (extent(data, yValue) as [number, number]))
89
136
  .nice()
90
137
  );
91
138
  const r = $derived(
@@ -95,11 +142,51 @@ copies this file into your project.
95
142
  .range([0, 18])
96
143
  : () => 5
97
144
  );
145
+ /** Radius of a point: its bubble size, or larger for flags so they stay recognisable. */
146
+ const radius = (d: T) => (size ? r(size(d)) : flag?.(d) ? Math.round(theme.plot.fontSize * 0.75) : 5);
98
147
  const groups = $derived(group ? [...new Set(data.map(group))] : []);
99
148
  const colour = (d: T) =>
100
149
  group
101
150
  ? theme.palettes.categorical[groups.indexOf(group(d)) % theme.palettes.categorical.length]
102
151
  : theme.palettes.categorical[0];
152
+ const corners = $derived(
153
+ quadrants
154
+ ? (
155
+ [
156
+ ['topLeft', 'start', 'top'],
157
+ ['topRight', 'end', 'top'],
158
+ ['bottomLeft', 'start', 'bottom'],
159
+ ['bottomRight', 'end', 'bottom']
160
+ ] as const
161
+ ).flatMap(([key, anchor, edge]) => {
162
+ const text = quadrants[key];
163
+ return text ? [{ key, text, anchor, edge }] : [];
164
+ })
165
+ : []
166
+ );
167
+ const basePadding = { left: 44, right: 16, top: 16, bottom: 36 };
168
+ const lineHeight = $derived(Math.round(theme.plot.fontSize * 1.25));
169
+ /** Quarter labels laid out for a plot area `w` px wide, and whether they fit without extra lines. */
170
+ function cornerLayout(w: number) {
171
+ if (!quadrants) return { items: [], fits: false };
172
+ const split = x.copy().range([0, w])(quadrants.x);
173
+ const items = corners.map((c) => {
174
+ const room = Math.max(40, (c.anchor === 'start' ? split : w - split) - 18);
175
+ const given = c.text.split('\n');
176
+ const lines = given.flatMap((t) => wrapLabel(t, room, (s) => estimateTextWidth(s, theme.plot.fontSize)));
177
+ return { ...c, lines, fits: lines.length <= Math.max(2, given.length) };
178
+ });
179
+ return { items, fits: items.every((c) => c.fits) };
180
+ }
181
+ /** Arrows on the axes: always without quadrants, otherwise only in place of quarter labels that don't fit. */
182
+ const showDirections = (w: number) => !!directions && (!quadrants || !cornerLayout(w).fits);
183
+ const padding = (size: { width: number }) => {
184
+ const w = size.width - basePadding.left - basePadding.right;
185
+ return showDirections(w) && directions?.x
186
+ ? { ...basePadding, bottom: basePadding.bottom + lineHeight + 6 }
187
+ : basePadding;
188
+ };
189
+ const withUnit = (s: string, unit?: string) => (unit ? `${s} ${unit}` : s);
103
190
  let hovered = $state<T | null>(null);
104
191
  </script>
105
192
 
@@ -118,24 +205,80 @@ copies this file into your project.
118
205
  {/if}
119
206
  </Header>
120
207
 
121
- <Plot {x} {y} {height} padding={{ left: 44, right: 16, top: 16, bottom: 36 }}>
208
+ <Plot {x} {y} {height} {padding}>
122
209
  {#snippet children(plot)}
210
+ {@const layout = cornerLayout(plot.width)}
211
+ {@const arrows = showDirections(plot.width)}
123
212
  <Svg>
124
213
  <GridX ticks={5} />
125
214
  <GridY ticks={5} />
126
- <AxisX ticks={5} format={xFormat} label={xLabel} />
127
- <AxisY ticks={5} format={yFormat} label={yLabel} />
215
+ <AxisX ticks={5} format={xFormat} label={xLabel} unit={xUnit} />
216
+ <AxisY ticks={5} format={yFormat} label={yLabel} unit={yUnit} />
217
+ {#if arrows && directions?.x}
218
+ {@const dy = plot.height + 36 + lineHeight}
219
+ {@const [low, high] = directions.x}
220
+ {@const both =
221
+ estimateTextWidth(`← ${low}`, theme.plot.fontSize) +
222
+ estimateTextWidth(`${high} →`, theme.plot.fontSize) +
223
+ 24 <
224
+ plot.width}
225
+ {#if low && (both || !high)}
226
+ <text class="mz-direction" x={0} y={dy} font-size={theme.plot.fontSize}>← {low}</text>
227
+ {/if}
228
+ {#if high}
229
+ <text class="mz-direction" x={plot.width} y={dy} text-anchor="end" font-size={theme.plot.fontSize}
230
+ >{high} →</text
231
+ >
232
+ {/if}
233
+ {/if}
234
+ {#if arrows && directions?.y}
235
+ {#if directions.y[1]}
236
+ <text class="mz-direction" x={6} y={6 + theme.plot.fontSize} font-size={theme.plot.fontSize}
237
+ >↑ {directions.y[1]}</text
238
+ >
239
+ {/if}
240
+ {#if directions.y[0]}
241
+ <text class="mz-direction" x={6} y={plot.height - 6} font-size={theme.plot.fontSize}
242
+ >↓ {directions.y[0]}</text
243
+ >
244
+ {/if}
245
+ {/if}
246
+ {#if quadrants}
247
+ <RefLine x={quadrants.x} label={quadrants.xLabel} labelY={4} />
248
+ <RefLine y={quadrants.y} label={quadrants.yLabel} />
249
+ {#if layout.fits}
250
+ {#each layout.items as c (c.key)}
251
+ {@const cx = c.anchor === 'start' ? 6 : plot.width - 6}
252
+ {@const top =
253
+ c.edge === 'top' ? 6 + theme.plot.fontSize : plot.height - 6 - (c.lines.length - 1) * lineHeight}
254
+ <text class="mz-quadrant" x={cx} y={top} text-anchor={c.anchor} font-size={theme.plot.fontSize}>
255
+ {#each c.lines as line, k (k)}<tspan x={cx} dy={k ? lineHeight : 0}>{line}</tspan>{/each}
256
+ </text>
257
+ {/each}
258
+ {/if}
259
+ {/if}
128
260
  <Points
129
- {data}
261
+ data={flag ? data.filter((d) => !flag(d)) : data}
130
262
  x={xValue}
131
263
  y={yValue}
132
- r={(d) => (size ? r(size(d)) : 5)}
264
+ r={radius}
133
265
  fill={colour}
134
266
  opacity={(d) => (hovered && hovered !== d ? 0.35 : size ? 0.75 : 0.9)}
135
267
  />
268
+ {#if flag}
269
+ <Flags
270
+ {data}
271
+ x={xValue}
272
+ y={yValue}
273
+ {flag}
274
+ r={radius}
275
+ title={name}
276
+ opacity={(d) => (hovered && hovered !== d ? 0.5 : 1)}
277
+ />
278
+ {/if}
136
279
  {#if labelled}
137
280
  {#each data.filter(labelled) as d}
138
- <Label x={xValue(d)} y={yValue(d)} label={name(d)} dx={(size ? r(size(d)) : 5) + 4} />
281
+ <Label x={xValue(d)} y={yValue(d)} label={name(d)} dx={radius(d) + 4} bold={emphasize?.(d) ?? false} />
139
282
  {/each}
140
283
  {/if}
141
284
  {@render annotations?.(plot)}
@@ -149,11 +292,15 @@ copies this file into your project.
149
292
  </Svg>
150
293
  <Html>
151
294
  {#if hovered}
152
- <Tooltip x={plot.x(xValue(hovered)) ?? 0} y={plot.y(yValue(hovered)) ?? 0}>
153
- <strong>{name(hovered)}</strong><br />
154
- {xLabel ?? 'x'}: {(xFormat ?? loc.number)(xValue(hovered))}<br />
155
- {yLabel ?? 'y'}: {(yFormat ?? loc.number)(yValue(hovered))}
156
- </Tooltip>
295
+ <Tooltip
296
+ x={plot.x(xValue(hovered)) ?? 0}
297
+ y={plot.y(yValue(hovered)) ?? 0}
298
+ title={name(hovered)}
299
+ items={[
300
+ { label: xLabel ?? 'x', value: withUnit((xFormat ?? loc.number)(xValue(hovered)), xUnit) },
301
+ { label: yLabel ?? 'y', value: withUnit((yFormat ?? loc.number)(yValue(hovered)), yUnit) }
302
+ ]}
303
+ />
157
304
  {/if}
158
305
  </Html>
159
306
  {/snippet}
@@ -166,3 +313,16 @@ copies this file into your project.
166
313
  </Footer>
167
314
  {/if}
168
315
  </Chart>
316
+
317
+ <style>
318
+ .mz-quadrant,
319
+ .mz-direction {
320
+ fill: var(--mz-color-muted);
321
+ font-family: var(--mz-font-body);
322
+ font-style: italic;
323
+ paint-order: stroke;
324
+ stroke: var(--mz-color-bg);
325
+ stroke-width: 3px;
326
+ stroke-linejoin: round;
327
+ }
328
+ </style>
@@ -0,0 +1,301 @@
1
+ <!--
2
+ @component
3
+ Recipe: a strip (one-axis dot plot) for comparing many items on one value,
4
+ such as a price across countries. Items sit along the x axis, nudged up and
5
+ down so they do not overlap (a beeswarm), as dots or as circular flags
6
+ (`flag`, as in ggflags). Highlighted items get a label with a leader line
7
+ above the strip; reference values (an average) get a dashed line labelled
8
+ below it. Arrows under the axis (`directions`) say what each end means, and
9
+ very soft gridlines help read values off the axis. Much shorter than a bar chart of the same items, so use it when the
10
+ reader needs the overall spread and a few named items, not every value.
11
+ `mozaic eject StripChart` copies this file into your project.
12
+ -->
13
+ <script lang="ts" generics="T">
14
+ import { scaleLinear } from 'd3-scale';
15
+ import { max, min } from 'd3-array';
16
+ import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
17
+ import type { ChartEmbed } from '../embed/index.js';
18
+ import { Plot, Svg, Html, estimateTextWidth } from '../core/index.js';
19
+ import { Flag } from '../marks/index.js';
20
+ import { AxisX } from '../guides/index.js';
21
+ import { Tooltip } from '../interactive/index.js';
22
+ import { createLocale, type LocaleCode } from '../locale/index.js';
23
+ import { base, readableColor, type Medium, type Theme } from '../styles/index.js';
24
+ import { dodge } from '../transforms/index.js';
25
+
26
+ interface Reference {
27
+ value: number;
28
+ label: string;
29
+ }
30
+
31
+ interface Props {
32
+ data: T[];
33
+ value: (d: T) => number;
34
+ /** Name shown in the tooltip and in highlighted labels. */
35
+ label: (d: T) => string;
36
+ /** The item's flag from `@samizdata/mozaic/flags`, drawn instead of a dot. */
37
+ flag?: (d: T) => string | null | undefined;
38
+ /** Items to label above the strip. */
39
+ highlight?: (d: T) => boolean;
40
+ /** Text of a highlighted label; defaults to the name and value. */
41
+ labelText?: (d: T) => string;
42
+ /** Highlighted labels to set in bold, e.g. the story's own country; the rest are regular. */
43
+ emphasize?: (d: T) => boolean;
44
+ /** Dot colour, and the colour of the item's label (darkened to 4.5:1 where needed). */
45
+ color?: (d: T) => string | undefined;
46
+ /** Dashed vertical lines with a label under the strip, e.g. an average. */
47
+ references?: Reference[];
48
+ /** Value axis domain; defaults to zero to the largest value. */
49
+ domain?: [number, number];
50
+ /** Unit after the last axis tick label and the tooltip value, e.g. "c/kWh". */
51
+ unit?: string;
52
+ /** Axis title at the end of the value axis. Leave it out when the subtitle gives the unit. */
53
+ axisLabel?: string;
54
+ /**
55
+ * What the low and high ends of the axis mean, e.g. `["Cheaper", "More expensive"]`,
56
+ * drawn under the axis as "← Cheaper" and "More expensive →". Leave an end empty for a single
57
+ * arrow; the low end is dropped when both do not fit.
58
+ */
59
+ directions?: [string, string];
60
+ /** Very soft vertical gridlines at the ticks (default true). */
61
+ grid?: boolean;
62
+ /** Dot or flag radius in px; defaults to a size that keeps flags recognisable. */
63
+ r?: number;
64
+ style?: Theme;
65
+ locale?: LocaleCode;
66
+ medium?: Medium;
67
+ width?: number;
68
+ title?: string;
69
+ subtitle?: string;
70
+ notes?: string;
71
+ /** Plain text, or sources with optional links (see `<Source>`). */
72
+ source?: string | SourceItem[];
73
+ alt?: string;
74
+ /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
75
+ embed?: ChartEmbed;
76
+ /** Value format for labels, tooltips and references; defaults to locale numbers. */
77
+ format?: (n: number) => string;
78
+ }
79
+
80
+ let {
81
+ data,
82
+ value,
83
+ label,
84
+ flag,
85
+ highlight,
86
+ labelText,
87
+ emphasize,
88
+ color,
89
+ references = [],
90
+ domain,
91
+ unit,
92
+ axisLabel,
93
+ directions,
94
+ grid = true,
95
+ r: radius,
96
+ style = base,
97
+ locale,
98
+ medium,
99
+ width,
100
+ title,
101
+ subtitle,
102
+ notes,
103
+ source,
104
+ alt,
105
+ embed,
106
+ format
107
+ }: Props = $props();
108
+
109
+ const theme = $derived(style);
110
+ const fmt = $derived(format ?? createLocale(locale ?? theme.defaultLocale).number);
111
+ const fontSize = $derived(theme.plot.fontSize);
112
+ const lineHeight = $derived(Math.round(fontSize * 1.35));
113
+ const r = $derived(radius ?? Math.round(fontSize * 0.7));
114
+ const padding = $derived({ left: 8, right: 8, top: 0, bottom: directions ? 28 + lineHeight + 6 : 28 });
115
+ const ticks = 5;
116
+ const leader = 8;
117
+ const x = $derived(
118
+ scaleLinear()
119
+ .domain(domain ?? [Math.min(0, min(data, value) ?? 0), max(data, value) ?? 1])
120
+ .nice()
121
+ );
122
+ const textOf = (d: T) => labelText?.(d) ?? `${label(d)} ${fmt(value(d))}`;
123
+ const labelled = $derived(highlight ? data.filter(highlight) : []);
124
+
125
+ /** Positions of the items and labels for a plot area `w` px wide. Pure, so the height can be worked out before the plot is drawn. */
126
+ function layout(w: number) {
127
+ const scale = x.copy().range([0, w]);
128
+ const xs = data.map((d) => scale(value(d)));
129
+ const offsets = dodge(xs, r, { padding: 1 });
130
+ const half = Math.max(0, ...offsets.map(Math.abs)) + r;
131
+ // Labels go in rows above the strip, each in the lowest row where it fits.
132
+ const rows: [number, number][][] = [];
133
+ const labels = labelled
134
+ .map((d) => ({ d, text: textOf(d), cx: scale(value(d)) }))
135
+ .sort((a, b) => a.cx - b.cx)
136
+ .map((l) => {
137
+ const wl = estimateTextWidth(l.text, fontSize);
138
+ const left = Math.max(0, Math.min(w - wl, l.cx - wl / 2));
139
+ let row = rows.findIndex((spans) => spans.every(([a, b]) => left > b + 8 || left + wl < a - 8));
140
+ if (row < 0) row = rows.push([]) - 1;
141
+ rows[row].push([left, left + wl]);
142
+ return { ...l, tx: left + wl / 2, row };
143
+ });
144
+ const band = rows.length ? rows.length * lineHeight + leader : 0;
145
+ const centre = band + half;
146
+ const below = references.length ? lineHeight + 4 : 0;
147
+ return { scale, xs, offsets, half, labels, band, centre, height: band + half * 2 + below };
148
+ }
149
+
150
+ const plotHeight = (size: { width: number }) => layout(size.width - padding.left - padding.right).height;
151
+ const ink = (d: T) => {
152
+ const c = color?.(d);
153
+ return c ? readableColor(c, theme.tokens['--mz-color-bg']) : 'var(--mz-color-text)';
154
+ };
155
+ let hovered = $state<number | null>(null);
156
+ </script>
157
+
158
+ <Chart {style} {locale} {medium} {width} {alt} {embed}>
159
+ {#if title || subtitle}
160
+ <Header>
161
+ {#if title}<Title>{title}</Title>{/if}
162
+ {#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
163
+ </Header>
164
+ {/if}
165
+
166
+ <Plot {x} height={plotHeight} {padding}>
167
+ {#snippet children(plot)}
168
+ {@const L = layout(plot.width)}
169
+ <Svg>
170
+ {#if grid}
171
+ {#each x.ticks(ticks) as tick (tick)}
172
+ {@const gx = L.scale(tick)}
173
+ <line class="mz-strip-grid" x1={gx} x2={gx} y1={L.band} y2={plot.height} />
174
+ {/each}
175
+ {/if}
176
+ <AxisX {ticks} label={axisLabel} {unit} />
177
+ {#if directions}
178
+ {@const dy = plot.height + 28 + lineHeight}
179
+ {@const [low, high] = directions}
180
+ {@const both =
181
+ estimateTextWidth(`← ${low}`, fontSize) + estimateTextWidth(`${high} →`, fontSize) + 24 < plot.width}
182
+ {#if low && (both || !high)}
183
+ <text class="mz-strip-direction" x={0} y={dy} font-size={fontSize}>← {low}</text>
184
+ {/if}
185
+ {#if high}
186
+ <text class="mz-strip-direction" x={plot.width} y={dy} text-anchor="end" font-size={fontSize}>{high} →</text
187
+ >
188
+ {/if}
189
+ {/if}
190
+ {#each references as ref (ref.label)}
191
+ {@const rx = L.scale(ref.value)}
192
+ <line
193
+ class="mz-strip-ref"
194
+ x1={rx}
195
+ x2={rx}
196
+ y1={L.band}
197
+ y2={L.centre + L.half}
198
+ stroke="var(--mz-color-muted)"
199
+ stroke-dasharray="3 3"
200
+ />
201
+ <text
202
+ class="mz-strip-ref-label"
203
+ x={rx}
204
+ y={L.centre + L.half + lineHeight}
205
+ text-anchor="middle"
206
+ font-size={fontSize}>{ref.label}</text
207
+ >
208
+ {/each}
209
+ {#each data as d, i (i)}
210
+ {@const cx = L.xs[i]}
211
+ {@const cy = L.centre + L.offsets[i]}
212
+ {@const svg = flag?.(d)}
213
+ {@const on = highlight?.(d) ?? false}
214
+ {#if svg}
215
+ <Flag
216
+ {svg}
217
+ {cx}
218
+ {cy}
219
+ {r}
220
+ stroke={on ? 'var(--mz-color-text)' : undefined}
221
+ strokeWidth={on ? 1.5 : 1}
222
+ title={label(d)}
223
+ opacity={hovered != null && hovered !== i ? 0.5 : 1}
224
+ onpointerenter={() => (hovered = i)}
225
+ onpointerleave={() => (hovered = null)}
226
+ />
227
+ {:else}
228
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
229
+ <circle
230
+ {cx}
231
+ {cy}
232
+ {r}
233
+ fill={color?.(d) ?? theme.palettes.categorical[0]}
234
+ stroke="var(--mz-color-bg)"
235
+ opacity={hovered != null && hovered !== i ? 0.5 : 1}
236
+ onpointerenter={() => (hovered = i)}
237
+ onpointerleave={() => (hovered = null)}><title>{label(d)}</title></circle
238
+ >
239
+ {/if}
240
+ {/each}
241
+ {#each L.labels as l (l.text)}
242
+ {@const i = data.indexOf(l.d)}
243
+ {@const ty = L.band - leader - l.row * lineHeight}
244
+ <line
245
+ class="mz-strip-leader"
246
+ x1={l.cx}
247
+ x2={l.cx}
248
+ y1={ty + 3}
249
+ y2={L.centre + L.offsets[i] - r}
250
+ stroke="var(--mz-color-muted)"
251
+ stroke-width="0.75"
252
+ />
253
+ <text
254
+ class="mz-strip-label"
255
+ x={l.tx}
256
+ y={ty}
257
+ text-anchor="middle"
258
+ font-size={fontSize}
259
+ style:font-weight={emphasize?.(l.d) ? 'var(--mz-weight-strong)' : undefined}
260
+ fill={ink(l.d)}>{l.text}</text
261
+ >
262
+ {/each}
263
+ </Svg>
264
+ <Html>
265
+ {#if hovered != null}
266
+ <Tooltip x={L.xs[hovered]} y={L.centre + L.offsets[hovered]}>
267
+ <strong>{label(data[hovered])}</strong><br />{fmt(value(data[hovered]))}{unit ? ` ${unit}` : ''}
268
+ </Tooltip>
269
+ {/if}
270
+ </Html>
271
+ {/snippet}
272
+ </Plot>
273
+
274
+ {#if notes || source}
275
+ <Footer>
276
+ {#if notes}<Notes>{notes}</Notes>{/if}
277
+ {#if source}<Source sources={source} />{/if}
278
+ </Footer>
279
+ {/if}
280
+ </Chart>
281
+
282
+ <style>
283
+ .mz-strip-grid {
284
+ stroke: var(--mz-color-grid);
285
+ stroke-width: 1;
286
+ opacity: 0.5;
287
+ shape-rendering: crispEdges;
288
+ }
289
+ .mz-strip-direction {
290
+ fill: var(--mz-color-muted);
291
+ font-family: var(--mz-font-body);
292
+ font-style: italic;
293
+ }
294
+ .mz-strip-ref-label {
295
+ fill: var(--mz-color-muted);
296
+ font-family: var(--mz-font-body);
297
+ }
298
+ .mz-strip-label {
299
+ font-family: var(--mz-font-body);
300
+ }
301
+ </style>
@@ -7,6 +7,7 @@ export { default as BarDotChart } from './BarDotChart.svelte';
7
7
  export { default as StackedBarChart } from './StackedBarChart.svelte';
8
8
  export { default as MosaicChart } from './MosaicChart.svelte';
9
9
  export { default as PercentileChart } from './PercentileChart.svelte';
10
+ export { default as StripChart } from './StripChart.svelte';
10
11
 
11
12
  /** Recipe names accepted by `mozaic eject`. */
12
13
  export const recipes = [
@@ -18,5 +19,6 @@ export const recipes = [
18
19
  'BarDotChart',
19
20
  'StackedBarChart',
20
21
  'MosaicChart',
21
- 'PercentileChart'
22
+ 'PercentileChart',
23
+ 'StripChart'
22
24
  ] as const;