@samizdata/mozaic 0.11.0 → 0.12.1

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 (43) hide show
  1. package/README.md +1 -1
  2. package/dist/flags/index.d.ts +16 -0
  3. package/dist/flags/index.js +16 -0
  4. package/dist/flags/svgs.d.ts +261 -0
  5. package/dist/flags/svgs.js +265 -0
  6. package/dist/guides/AxisX.svelte +18 -3
  7. package/dist/guides/AxisX.svelte.d.ts +4 -0
  8. package/dist/interactive/Tooltip.svelte +10 -3
  9. package/dist/locale/index.d.ts +8 -0
  10. package/dist/locale/index.js +10 -0
  11. package/dist/marks/Beeswarm.svelte +31 -12
  12. package/dist/marks/Beeswarm.svelte.d.ts +3 -0
  13. package/dist/marks/Flag.svelte +65 -0
  14. package/dist/marks/Flag.svelte.d.ts +27 -0
  15. package/dist/marks/Flags.svelte +69 -0
  16. package/dist/marks/Flags.svelte.d.ts +45 -0
  17. package/dist/marks/index.d.ts +2 -0
  18. package/dist/marks/index.js +2 -0
  19. package/dist/recipes/ArrowChart.svelte +4 -1
  20. package/dist/recipes/ArrowChart.svelte.d.ts +2 -0
  21. package/dist/recipes/BarChart.svelte +103 -18
  22. package/dist/recipes/BarChart.svelte.d.ts +20 -2
  23. package/dist/recipes/BarDotChart.svelte +4 -1
  24. package/dist/recipes/BarDotChart.svelte.d.ts +2 -0
  25. package/dist/recipes/ColumnChart.svelte +7 -3
  26. package/dist/recipes/ColumnChart.svelte.d.ts +2 -0
  27. package/dist/recipes/LineChart.svelte +8 -2
  28. package/dist/recipes/LineChart.svelte.d.ts +2 -0
  29. package/dist/recipes/ScatterChart.svelte +179 -18
  30. package/dist/recipes/ScatterChart.svelte.d.ts +40 -1
  31. package/dist/recipes/StripChart.svelte +301 -0
  32. package/dist/recipes/StripChart.svelte.d.ts +89 -0
  33. package/dist/recipes/index.d.ts +2 -1
  34. package/dist/recipes/index.js +3 -1
  35. package/package.json +174 -170
  36. package/src/lib/recipes/ArrowChart.svelte +4 -1
  37. package/src/lib/recipes/BarChart.svelte +103 -18
  38. package/src/lib/recipes/BarDotChart.svelte +4 -1
  39. package/src/lib/recipes/ColumnChart.svelte +7 -3
  40. package/src/lib/recipes/LineChart.svelte +8 -2
  41. package/src/lib/recipes/ScatterChart.svelte +179 -18
  42. package/src/lib/recipes/StripChart.svelte +301 -0
  43. package/src/lib/recipes/index.ts +3 -1
@@ -1,7 +1,12 @@
1
1
  <!--
2
2
  @component
3
3
  Recipe: a sorted horizontal bar chart with value labels, hover tooltip and
4
- the full frame. Use it as is, or run `mozaic eject BarChart` to copy this
4
+ the full frame. Rows known only as a range (`range`) get a solid bar to the
5
+ low end, a lighter one to the high end and a "low–high" label. Value labels
6
+ sit inside the end of each bar where they fit (in white or the text colour,
7
+ whichever reads on the bar) and just past it otherwise, and the bars run to the
8
+ largest value, so there is no empty space on the right. Pass `flag`
9
+ to put a circular flag between each label and its bar. Use it as is, or run `mozaic eject BarChart` to copy this
5
10
  file into your project and change anything.
6
11
  -->
7
12
  <script lang="ts" generics="T">
@@ -11,11 +16,11 @@ file into your project and change anything.
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
18
  import { Plot, Svg, Html, estimateTextWidth, useTextWidth, scaled, type PlotContext } from '../core/index.js';
14
- import { Bars, Rules, Text } from '../marks/index.js';
19
+ import { Bars, Flag, Rules, Text } from '../marks/index.js';
15
20
  import { AxisY } from '../guides/index.js';
16
21
  import { Tooltip } from '../interactive/index.js';
17
22
  import { createLocale, type LocaleCode } from '../locale/index.js';
18
- import { base, type Medium, type Theme } from '../styles/index.js';
23
+ import { base, contrastRatio, type Medium, type Theme } from '../styles/index.js';
19
24
 
20
25
  interface Props {
21
26
  data: T[];
@@ -33,10 +38,23 @@ file into your project and change anything.
33
38
  alt?: string;
34
39
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
35
40
  embed?: ChartEmbed;
36
- /** Value label format; defaults to locale numbers. */
41
+ /** Value label format; defaults to locale numbers. Use the locale's `money` for prices. */
37
42
  format?: (n: number) => string;
43
+ /** Unit after the value in the tooltip, e.g. "lei/m³" (bar charts have no value axis). */
44
+ unit?: string;
38
45
  /** Bar colour; defaults to the first categorical colour. */
39
46
  color?: (d: T) => string;
47
+ /**
48
+ * Low and high ends for rows known only as a range (several suppliers,
49
+ * regions or estimates). The bar is solid to the low end and lighter to
50
+ * the high end, and the label reads "low–high". Return `null` for rows
51
+ * with a single value; `value` still sets the sort order.
52
+ */
53
+ range?: (d: T) => [number, number] | null | undefined;
54
+ /** The row's flag from `@samizdata/mozaic/flags`, drawn between its label and its bar. */
55
+ flag?: (d: T) => string | null | undefined;
56
+ /** Put value labels inside the bars where they fit (default true); otherwise always after them. */
57
+ labelsInside?: boolean;
40
58
  /** Sort largest first (default) or keep data order. */
41
59
  sort?: boolean;
42
60
  rowHeight?: number;
@@ -59,7 +77,11 @@ file into your project and change anything.
59
77
  alt,
60
78
  embed,
61
79
  format,
80
+ unit,
62
81
  color,
82
+ range,
83
+ flag,
84
+ labelsInside = true,
63
85
  sort = true,
64
86
  rowHeight = 28,
65
87
  annotations
@@ -71,15 +93,47 @@ file into your project and change anything.
71
93
  const labelWidth = (s: string) => measure(s, theme.plot.fontSize, theme.tokens['--mz-font-body']);
72
94
  const fmt = $derived(format ?? createLocale(locale ?? theme.defaultLocale).number);
73
95
  const rows = $derived(sort ? data.toSorted((a, b) => value(b) - value(a)) : data);
74
- const x = $derived(
75
- scaleLinear()
76
- .domain([Math.min(0, min(rows, value) ?? 0), Math.max(0, max(rows, value) ?? 1)])
77
- .nice()
78
- );
96
+ const span = (d: T) => range?.(d) ?? null;
97
+ /** Where the solid bar ends: the value, or the low end of a range. */
98
+ const low = (d: T) => span(d)?.[0] ?? value(d);
99
+ /** Where the bar and its label end: the value, or the high end of a range. */
100
+ const high = (d: T) => span(d)?.[1] ?? value(d);
101
+ const ranged = $derived(rows.filter((d) => span(d)));
102
+ const valueLabel = (d: T) => {
103
+ const r = span(d);
104
+ return r ? `${fmt(r[0])}–${fmt(r[1])}` : fmt(value(d));
105
+ };
106
+ // No value axis is drawn, so the scale runs exactly to the data: rounding it up would only leave space.
107
+ const x = $derived(scaleLinear().domain([Math.min(0, min(rows, low) ?? 0), Math.max(0, max(rows, high) ?? 1)]));
79
108
  const y = $derived(scaleBand<string>().domain(rows.map(label)).paddingInner(0.25).paddingOuter(0.1));
80
- const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12);
81
- const right = $derived(Math.max(...rows.map((d) => estimateTextWidth(fmt(value(d)), theme.plot.fontSize)), 0) + 12);
82
- let hovered = $state<T | null>(null);
109
+ /** Flag radius and the room the flags take between the labels and the bars. */
110
+ const flagR = $derived(Math.round(theme.plot.fontSize * 0.6));
111
+ const flagGap = 4;
112
+ const flagRoom = $derived(flag && rows.some((d) => flag(d)) ? flagR * 2 + flagGap : 0);
113
+ const left = $derived(Math.max(...rows.map((d) => labelWidth(label(d))), 0) + 12 + flagRoom);
114
+ const textWidth = (d: T) => estimateTextWidth(valueLabel(d), theme.plot.fontSize);
115
+ /** Labels that fit inside their solid bar, for a plot area `w` px wide. Ranges keep theirs outside. */
116
+ const insideFor = (w: number) => {
117
+ const scale = x.copy().range([0, w]);
118
+ return (d: T) => labelsInside && !span(d) && low(d) > 0 && textWidth(d) + 12 <= scale(low(d)) - scale(0);
119
+ };
120
+ /** Room on the right for the labels that stay outside, for a plot area `w` px wide. */
121
+ const rightFor = (w: number) => {
122
+ const scale = x.copy().range([0, w]);
123
+ const inside = insideFor(w);
124
+ return Math.max(0, ...rows.filter((d) => !inside(d)).map((d) => scale(high(d)) + 4 + textWidth(d) - w)) + 4;
125
+ };
126
+ // The room changes the bar lengths, which changes which labels fit: two passes settle it.
127
+ const padding = (size: { width: number }) => {
128
+ const w = size.width - left;
129
+ const first = rightFor(w);
130
+ return { left, right: Math.max(first, rightFor(w - first)), top: 0, bottom: 0 };
131
+ };
132
+ const barColor = (d: T) => color?.(d) ?? theme.palettes.categorical[0];
133
+ /** White on dark bars, the text colour on light ones. */
134
+ const inkOn = (d: T) => (contrastRatio(barColor(d), '#ffffff') >= 4.5 ? '#ffffff' : 'var(--mz-color-text)');
135
+ // Raw, not a proxy: marks compare the hovered row with each datum by identity.
136
+ let hovered = $state.raw<T | null>(null);
83
137
  </script>
84
138
 
85
139
  <Chart {style} {locale} {medium} {width} {alt} {embed}>
@@ -90,13 +144,34 @@ file into your project and change anything.
90
144
  </Header>
91
145
  {/if}
92
146
 
93
- <Plot {x} {y} height={rows.length * rowHeight} padding={{ left, right, top: 0, bottom: 0 }}>
147
+ <Plot {x} {y} height={rows.length * rowHeight} {padding}>
94
148
  {#snippet children(plot)}
149
+ {@const inside = insideFor(plot.width)}
95
150
  <Svg>
96
- <AxisY />
151
+ <AxisY tickPadding={flagRoom ? theme.plot.tickPadding + flagRoom : undefined} />
152
+ {#if flagRoom}
153
+ {#each rows as d, i (i)}
154
+ {@const svg = flag?.(d)}
155
+ {#if svg}
156
+ <Flag {svg} cx={-(flagR + flagGap)} cy={scaled(plot.y, label(d))} r={flagR} />
157
+ {/if}
158
+ {/each}
159
+ {/if}
160
+ {#if ranged.length}
161
+ <Bars
162
+ class="mz-bars-range"
163
+ data={ranged}
164
+ x={high}
165
+ y={label}
166
+ fill={color}
167
+ opacity={(d) => (hovered && hovered !== d ? 0.2 : 0.4)}
168
+ onpointerenter={(d) => (hovered = d)}
169
+ onpointerleave={() => (hovered = null)}
170
+ />
171
+ {/if}
97
172
  <Bars
98
173
  data={rows}
99
- x={value}
174
+ x={low}
100
175
  y={label}
101
176
  fill={color}
102
177
  opacity={(d) => (hovered && hovered !== d ? 0.5 : 1)}
@@ -104,13 +179,23 @@ file into your project and change anything.
104
179
  onpointerleave={() => (hovered = null)}
105
180
  />
106
181
  <Rules x={[0]} />
107
- <Text data={rows} x={value} y={label} text={(d) => fmt(value(d))} dx={4} />
182
+ <Text data={rows.filter((d) => !inside(d))} x={high} y={label} text={valueLabel} dx={4} />
183
+ <Text
184
+ class="mz-bar-value-inside"
185
+ data={rows.filter(inside)}
186
+ x={low}
187
+ y={label}
188
+ text={valueLabel}
189
+ dx={-6}
190
+ anchor="end"
191
+ fill={inkOn}
192
+ />
108
193
  {@render annotations?.(plot)}
109
194
  </Svg>
110
195
  <Html>
111
196
  {#if hovered}
112
- <Tooltip x={plot.x(value(hovered)) ?? 0} y={scaled(plot.y, label(hovered))}>
113
- <strong>{label(hovered)}</strong><br />{fmt(value(hovered))}
197
+ <Tooltip x={plot.x(high(hovered)) ?? 0} y={scaled(plot.y, label(hovered))}>
198
+ <strong>{label(hovered)}</strong><br />{valueLabel(hovered)}{unit ? ` ${unit}` : ''}
114
199
  </Tooltip>
115
200
  {/if}
116
201
  </Html>
@@ -21,10 +21,23 @@ declare function $$render<T>(): {
21
21
  alt?: string;
22
22
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
23
23
  embed?: ChartEmbed;
24
- /** Value label format; defaults to locale numbers. */
24
+ /** Value label format; defaults to locale numbers. Use the locale's `money` for prices. */
25
25
  format?: (n: number) => string;
26
+ /** Unit after the value in the tooltip, e.g. "lei/m³" (bar charts have no value axis). */
27
+ unit?: string;
26
28
  /** Bar colour; defaults to the first categorical colour. */
27
29
  color?: (d: T) => string;
30
+ /**
31
+ * Low and high ends for rows known only as a range (several suppliers,
32
+ * regions or estimates). The bar is solid to the low end and lighter to
33
+ * the high end, and the label reads "low–high". Return `null` for rows
34
+ * with a single value; `value` still sets the sort order.
35
+ */
36
+ range?: (d: T) => [number, number] | null | undefined;
37
+ /** The row's flag from `@samizdata/mozaic/flags`, drawn between its label and its bar. */
38
+ flag?: (d: T) => string | null | undefined;
39
+ /** Put value labels inside the bars where they fit (default true); otherwise always after them. */
40
+ labelsInside?: boolean;
28
41
  /** Sort largest first (default) or keep data order. */
29
42
  sort?: boolean;
30
43
  rowHeight?: number;
@@ -52,7 +65,12 @@ interface $$IsomorphicComponent {
52
65
  }
53
66
  /**
54
67
  * Recipe: a sorted horizontal bar chart with value labels, hover tooltip and
55
- * the full frame. Use it as is, or run `mozaic eject BarChart` to copy this
68
+ * the full frame. Rows known only as a range (`range`) get a solid bar to the
69
+ * low end, a lighter one to the high end and a "low–high" label. Value labels
70
+ * sit inside the end of each bar where they fit (in white or the text colour,
71
+ * whichever reads on the bar) and just past it otherwise, and the bars run to the
72
+ * largest value, so there is no empty space on the right. Pass `flag`
73
+ * to put a circular flag between each label and its bar. Use it as is, or run `mozaic eject BarChart` to copy this
56
74
  * file into your project and change anything.
57
75
  */
58
76
  declare const BarChart: $$IsomorphicComponent;
@@ -44,6 +44,8 @@ anything.
44
44
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
45
45
  embed?: ChartEmbed;
46
46
  /** Value label format; defaults to locale numbers. */
47
+ /** Unit after the last value-axis tick label and the tooltip values, e.g. "lei/m³". */
48
+ unit?: string;
47
49
  format?: (n: number) => string;
48
50
  /** Change label format; defaults to one decimal with a sign. */
49
51
  formatChange?: (n: number) => string;
@@ -79,6 +81,7 @@ anything.
79
81
  source,
80
82
  alt,
81
83
  embed,
84
+ unit,
82
85
  format,
83
86
  formatChange,
84
87
  tickFormat,
@@ -148,7 +151,7 @@ anything.
148
151
  {#snippet children(plot)}
149
152
  <Svg>
150
153
  <GridX ticks={4} />
151
- <AxisX ticks={4} format={tickFormat ?? fmt} />
154
+ <AxisX ticks={4} format={tickFormat ?? fmt} {unit} />
152
155
  <AxisY />
153
156
  <Bars
154
157
  data={rows.filter((d) => has(value(d)))}
@@ -28,6 +28,8 @@ declare function $$render<T>(): {
28
28
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
29
29
  embed?: ChartEmbed;
30
30
  /** Value label format; defaults to locale numbers. */
31
+ /** Unit after the last value-axis tick label and the tooltip values, e.g. "lei/m³". */
32
+ unit?: string;
31
33
  format?: (n: number) => string;
32
34
  /** Change label format; defaults to one decimal with a sign. */
33
35
  formatChange?: (n: number) => string;
@@ -34,6 +34,8 @@ copies this file into your project.
34
34
  alt?: string;
35
35
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
36
36
  embed?: ChartEmbed;
37
+ /** Unit after the last value-axis tick label and the tooltip values, e.g. "lei/m³". */
38
+ unit?: string;
37
39
  format?: (n: number) => string;
38
40
  color?: (d: T) => string;
39
41
  height?: number;
@@ -56,6 +58,7 @@ copies this file into your project.
56
58
  source,
57
59
  alt,
58
60
  embed,
61
+ unit,
59
62
  format,
60
63
  color,
61
64
  height = 280,
@@ -71,7 +74,8 @@ copies this file into your project.
71
74
  .domain([Math.min(0, min(data, value) ?? 0), Math.max(0, max(data, value) ?? 1)])
72
75
  .nice()
73
76
  );
74
- let hovered = $state<T | null>(null);
77
+ // Raw, not a proxy: marks compare the hovered row with each datum by identity.
78
+ let hovered = $state.raw<T | null>(null);
75
79
  </script>
76
80
 
77
81
  <Chart {style} {locale} {medium} {width} {alt} {embed}>
@@ -87,7 +91,7 @@ copies this file into your project.
87
91
  {@const every = labelEvery ?? Math.max(1, Math.ceil((data.length * 36) / Math.max(1, plot.width)))}
88
92
  <Svg>
89
93
  <GridY ticks={5} />
90
- <AxisY ticks={5} format={fmt} />
94
+ <AxisY ticks={5} format={fmt} {unit} />
91
95
  <AxisX tickValues={data.map(label).filter((_, i) => i % every === 0)} />
92
96
  <Bars
93
97
  {data}
@@ -104,7 +108,7 @@ copies this file into your project.
104
108
  <Html>
105
109
  {#if hovered}
106
110
  <Tooltip x={scaled(plot.x, label(hovered))} y={plot.y(value(hovered)) ?? 0}>
107
- <strong>{label(hovered)}</strong><br />{fmt(value(hovered))}
111
+ <strong>{label(hovered)}</strong><br />{fmt(value(hovered))}{unit ? ` ${unit}` : ''}
108
112
  </Tooltip>
109
113
  {/if}
110
114
  </Html>
@@ -22,6 +22,8 @@ declare function $$render<T>(): {
22
22
  alt?: string;
23
23
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
24
24
  embed?: ChartEmbed;
25
+ /** Unit after the last value-axis tick label and the tooltip values, e.g. "lei/m³". */
26
+ unit?: string;
25
27
  format?: (n: number) => string;
26
28
  color?: (d: T) => string;
27
29
  height?: number;
@@ -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>
@@ -24,6 +24,8 @@ declare function $$render<S, P>(): {
24
24
  alt?: string;
25
25
  /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
26
26
  embed?: ChartEmbed;
27
+ /** Unit after the last value-axis tick label and the tooltip values, e.g. "lei/m³". */
28
+ unit?: string;
27
29
  format?: (n: number) => string;
28
30
  /** Tooltip date format (d3-time-format specifier). */
29
31
  dateFormat?: string;
@@ -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,12 +142,53 @@ 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];
103
- let hovered = $state<T | null>(null);
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);
190
+ // Raw, not a proxy: marks compare the hovered row with each datum by identity.
191
+ let hovered = $state.raw<T | null>(null);
104
192
  </script>
105
193
 
106
194
  <Chart {style} {locale} {medium} {width} {alt} {embed}>
@@ -118,24 +206,80 @@ copies this file into your project.
118
206
  {/if}
119
207
  </Header>
120
208
 
121
- <Plot {x} {y} {height} padding={{ left: 44, right: 16, top: 16, bottom: 36 }}>
209
+ <Plot {x} {y} {height} {padding}>
122
210
  {#snippet children(plot)}
211
+ {@const layout = cornerLayout(plot.width)}
212
+ {@const arrows = showDirections(plot.width)}
123
213
  <Svg>
124
214
  <GridX ticks={5} />
125
215
  <GridY ticks={5} />
126
- <AxisX ticks={5} format={xFormat} label={xLabel} />
127
- <AxisY ticks={5} format={yFormat} label={yLabel} />
216
+ <AxisX ticks={5} format={xFormat} label={xLabel} unit={xUnit} />
217
+ <AxisY ticks={5} format={yFormat} label={yLabel} unit={yUnit} />
218
+ {#if arrows && directions?.x}
219
+ {@const dy = plot.height + 36 + lineHeight}
220
+ {@const [low, high] = directions.x}
221
+ {@const both =
222
+ estimateTextWidth(`← ${low}`, theme.plot.fontSize) +
223
+ estimateTextWidth(`${high} →`, theme.plot.fontSize) +
224
+ 24 <
225
+ plot.width}
226
+ {#if low && (both || !high)}
227
+ <text class="mz-direction" x={0} y={dy} font-size={theme.plot.fontSize}>← {low}</text>
228
+ {/if}
229
+ {#if high}
230
+ <text class="mz-direction" x={plot.width} y={dy} text-anchor="end" font-size={theme.plot.fontSize}
231
+ >{high} →</text
232
+ >
233
+ {/if}
234
+ {/if}
235
+ {#if arrows && directions?.y}
236
+ {#if directions.y[1]}
237
+ <text class="mz-direction" x={6} y={6 + theme.plot.fontSize} font-size={theme.plot.fontSize}
238
+ >↑ {directions.y[1]}</text
239
+ >
240
+ {/if}
241
+ {#if directions.y[0]}
242
+ <text class="mz-direction" x={6} y={plot.height - 6} font-size={theme.plot.fontSize}
243
+ >↓ {directions.y[0]}</text
244
+ >
245
+ {/if}
246
+ {/if}
247
+ {#if quadrants}
248
+ <RefLine x={quadrants.x} label={quadrants.xLabel} labelY={4} />
249
+ <RefLine y={quadrants.y} label={quadrants.yLabel} />
250
+ {#if layout.fits}
251
+ {#each layout.items as c (c.key)}
252
+ {@const cx = c.anchor === 'start' ? 6 : plot.width - 6}
253
+ {@const top =
254
+ c.edge === 'top' ? 6 + theme.plot.fontSize : plot.height - 6 - (c.lines.length - 1) * lineHeight}
255
+ <text class="mz-quadrant" x={cx} y={top} text-anchor={c.anchor} font-size={theme.plot.fontSize}>
256
+ {#each c.lines as line, k (k)}<tspan x={cx} dy={k ? lineHeight : 0}>{line}</tspan>{/each}
257
+ </text>
258
+ {/each}
259
+ {/if}
260
+ {/if}
128
261
  <Points
129
- {data}
262
+ data={flag ? data.filter((d) => !flag(d)) : data}
130
263
  x={xValue}
131
264
  y={yValue}
132
- r={(d) => (size ? r(size(d)) : 5)}
265
+ r={radius}
133
266
  fill={colour}
134
267
  opacity={(d) => (hovered && hovered !== d ? 0.35 : size ? 0.75 : 0.9)}
135
268
  />
269
+ {#if flag}
270
+ <Flags
271
+ {data}
272
+ x={xValue}
273
+ y={yValue}
274
+ {flag}
275
+ r={radius}
276
+ title={name}
277
+ opacity={(d) => (hovered && hovered !== d ? 0.5 : 1)}
278
+ />
279
+ {/if}
136
280
  {#if labelled}
137
281
  {#each data.filter(labelled) as d}
138
- <Label x={xValue(d)} y={yValue(d)} label={name(d)} dx={(size ? r(size(d)) : 5) + 4} />
282
+ <Label x={xValue(d)} y={yValue(d)} label={name(d)} dx={radius(d) + 4} bold={emphasize?.(d) ?? false} />
139
283
  {/each}
140
284
  {/if}
141
285
  {@render annotations?.(plot)}
@@ -149,11 +293,15 @@ copies this file into your project.
149
293
  </Svg>
150
294
  <Html>
151
295
  {#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>
296
+ <Tooltip
297
+ x={plot.x(xValue(hovered)) ?? 0}
298
+ y={plot.y(yValue(hovered)) ?? 0}
299
+ title={name(hovered)}
300
+ items={[
301
+ { label: xLabel ?? 'x', value: withUnit((xFormat ?? loc.number)(xValue(hovered)), xUnit) },
302
+ { label: yLabel ?? 'y', value: withUnit((yFormat ?? loc.number)(yValue(hovered)), yUnit) }
303
+ ]}
304
+ />
157
305
  {/if}
158
306
  </Html>
159
307
  {/snippet}
@@ -166,3 +314,16 @@ copies this file into your project.
166
314
  </Footer>
167
315
  {/if}
168
316
  </Chart>
317
+
318
+ <style>
319
+ .mz-quadrant,
320
+ .mz-direction {
321
+ fill: var(--mz-color-muted);
322
+ font-family: var(--mz-font-body);
323
+ font-style: italic;
324
+ paint-order: stroke;
325
+ stroke: var(--mz-color-bg);
326
+ stroke-width: 3px;
327
+ stroke-linejoin: round;
328
+ }
329
+ </style>