@samizdata/mozaic 0.0.0-stage → 0.3.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 (232) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +44 -2
  3. package/dist/annotations/Arrow.svelte +50 -0
  4. package/dist/annotations/Arrow.svelte.d.ts +18 -0
  5. package/dist/annotations/Callout.svelte +87 -0
  6. package/dist/annotations/Callout.svelte.d.ts +22 -0
  7. package/dist/annotations/Label.svelte +55 -0
  8. package/dist/annotations/Label.svelte.d.ts +19 -0
  9. package/dist/annotations/RefBand.svelte +46 -0
  10. package/dist/annotations/RefBand.svelte.d.ts +18 -0
  11. package/dist/annotations/RefLine.svelte +107 -0
  12. package/dist/annotations/RefLine.svelte.d.ts +27 -0
  13. package/dist/annotations/callout-geometry.d.ts +23 -0
  14. package/dist/annotations/callout-geometry.js +45 -0
  15. package/dist/annotations/index.d.ts +6 -0
  16. package/dist/annotations/index.js +6 -0
  17. package/dist/core/Canvas.svelte +55 -0
  18. package/dist/core/Canvas.svelte.d.ts +19 -0
  19. package/dist/core/Facets.svelte +80 -0
  20. package/dist/core/Facets.svelte.d.ts +49 -0
  21. package/dist/core/Html.svelte +38 -0
  22. package/dist/core/Html.svelte.d.ts +13 -0
  23. package/dist/core/Plot.svelte +202 -0
  24. package/dist/core/Plot.svelte.d.ts +60 -0
  25. package/dist/core/Svg.svelte +58 -0
  26. package/dist/core/Svg.svelte.d.ts +17 -0
  27. package/dist/core/accessor.d.ts +5 -0
  28. package/dist/core/accessor.js +3 -0
  29. package/dist/core/context.d.ts +25 -0
  30. package/dist/core/context.js +69 -0
  31. package/dist/core/index.d.ts +10 -0
  32. package/dist/core/index.js +9 -0
  33. package/dist/core/scales.d.ts +16 -0
  34. package/dist/core/scales.js +32 -0
  35. package/dist/core/types.d.ts +78 -0
  36. package/dist/core/types.js +1 -0
  37. package/dist/core/units.d.ts +6 -0
  38. package/dist/core/units.js +10 -0
  39. package/dist/embed/Embed.svelte +50 -0
  40. package/dist/embed/Embed.svelte.d.ts +14 -0
  41. package/dist/embed/code.d.ts +18 -0
  42. package/dist/embed/code.js +9 -0
  43. package/dist/embed/host.d.ts +6 -0
  44. package/dist/embed/host.js +20 -0
  45. package/dist/embed/index.d.ts +6 -0
  46. package/dist/embed/index.js +5 -0
  47. package/dist/embed/manifest.d.ts +16 -0
  48. package/dist/embed/manifest.js +1 -0
  49. package/dist/embed/params.svelte.d.ts +10 -0
  50. package/dist/embed/params.svelte.js +27 -0
  51. package/dist/embed/resize.d.ts +13 -0
  52. package/dist/embed/resize.js +28 -0
  53. package/dist/export/download.d.ts +13 -0
  54. package/dist/export/download.js +52 -0
  55. package/dist/export/figure-to-svg.d.ts +21 -0
  56. package/dist/export/figure-to-svg.js +187 -0
  57. package/dist/export/fonts.d.ts +26 -0
  58. package/dist/export/fonts.js +112 -0
  59. package/dist/export/index.d.ts +2 -0
  60. package/dist/export/index.js +2 -0
  61. package/dist/frame/Byline.svelte +26 -0
  62. package/dist/frame/Byline.svelte.d.ts +8 -0
  63. package/dist/frame/Chart.svelte +144 -0
  64. package/dist/frame/Chart.svelte.d.ts +37 -0
  65. package/dist/frame/ChartTools.svelte +259 -0
  66. package/dist/frame/ChartTools.svelte.d.ts +17 -0
  67. package/dist/frame/DataDownload.svelte +34 -0
  68. package/dist/frame/DataDownload.svelte.d.ts +34 -0
  69. package/dist/frame/DataTable.svelte +49 -0
  70. package/dist/frame/DataTable.svelte.d.ts +34 -0
  71. package/dist/frame/Footer.svelte +39 -0
  72. package/dist/frame/Footer.svelte.d.ts +10 -0
  73. package/dist/frame/Header.svelte +21 -0
  74. package/dist/frame/Header.svelte.d.ts +9 -0
  75. package/dist/frame/Logo.svelte +57 -0
  76. package/dist/frame/Logo.svelte.d.ts +8 -0
  77. package/dist/frame/Notes.svelte +29 -0
  78. package/dist/frame/Notes.svelte.d.ts +9 -0
  79. package/dist/frame/Source.svelte +29 -0
  80. package/dist/frame/Source.svelte.d.ts +9 -0
  81. package/dist/frame/Subtitle.svelte +22 -0
  82. package/dist/frame/Subtitle.svelte.d.ts +9 -0
  83. package/dist/frame/Title.svelte +31 -0
  84. package/dist/frame/Title.svelte.d.ts +9 -0
  85. package/dist/frame/index.d.ts +12 -0
  86. package/dist/frame/index.js +12 -0
  87. package/dist/guides/AxisX.svelte +101 -0
  88. package/dist/guides/AxisX.svelte.d.ts +22 -0
  89. package/dist/guides/AxisY.svelte +107 -0
  90. package/dist/guides/AxisY.svelte.d.ts +25 -0
  91. package/dist/guides/ColorRamp.svelte +93 -0
  92. package/dist/guides/ColorRamp.svelte.d.ts +25 -0
  93. package/dist/guides/GridX.svelte +35 -0
  94. package/dist/guides/GridX.svelte.d.ts +9 -0
  95. package/dist/guides/GridY.svelte +35 -0
  96. package/dist/guides/GridY.svelte.d.ts +9 -0
  97. package/dist/guides/Key.svelte +48 -0
  98. package/dist/guides/Key.svelte.d.ts +14 -0
  99. package/dist/guides/Legend.svelte +112 -0
  100. package/dist/guides/Legend.svelte.d.ts +26 -0
  101. package/dist/guides/SizeLegend.svelte +62 -0
  102. package/dist/guides/SizeLegend.svelte.d.ts +15 -0
  103. package/dist/guides/index.d.ts +9 -0
  104. package/dist/guides/index.js +9 -0
  105. package/dist/guides/ticks.d.ts +6 -0
  106. package/dist/guides/ticks.js +15 -0
  107. package/dist/index.d.ts +13 -0
  108. package/dist/index.js +14 -0
  109. package/dist/interactive/ButtonGroup.svelte +98 -0
  110. package/dist/interactive/ButtonGroup.svelte.d.ts +42 -0
  111. package/dist/interactive/PointerArea.svelte +49 -0
  112. package/dist/interactive/PointerArea.svelte.d.ts +18 -0
  113. package/dist/interactive/Scroller.svelte +147 -0
  114. package/dist/interactive/Scroller.svelte.d.ts +54 -0
  115. package/dist/interactive/Tooltip.svelte +116 -0
  116. package/dist/interactive/Tooltip.svelte.d.ts +34 -0
  117. package/dist/interactive/index.d.ts +4 -0
  118. package/dist/interactive/index.js +4 -0
  119. package/dist/interactive/tooltip-position.d.ts +12 -0
  120. package/dist/interactive/tooltip-position.js +16 -0
  121. package/dist/locale/definitions.d.ts +145 -0
  122. package/dist/locale/definitions.js +138 -0
  123. package/dist/locale/index.d.ts +23 -0
  124. package/dist/locale/index.js +34 -0
  125. package/dist/marks/Arcs.svelte +93 -0
  126. package/dist/marks/Arcs.svelte.d.ts +47 -0
  127. package/dist/marks/Area.svelte +44 -0
  128. package/dist/marks/Area.svelte.d.ts +43 -0
  129. package/dist/marks/Arrows.svelte +93 -0
  130. package/dist/marks/Arrows.svelte.d.ts +50 -0
  131. package/dist/marks/Bars.svelte +111 -0
  132. package/dist/marks/Bars.svelte.d.ts +61 -0
  133. package/dist/marks/Beeswarm.svelte +84 -0
  134. package/dist/marks/Beeswarm.svelte.d.ts +42 -0
  135. package/dist/marks/Dumbbell.svelte +71 -0
  136. package/dist/marks/Dumbbell.svelte.d.ts +42 -0
  137. package/dist/marks/GeoPath.svelte +56 -0
  138. package/dist/marks/GeoPath.svelte.d.ts +42 -0
  139. package/dist/marks/Hemicycle.svelte +182 -0
  140. package/dist/marks/Hemicycle.svelte.d.ts +78 -0
  141. package/dist/marks/Intervals.svelte +128 -0
  142. package/dist/marks/Intervals.svelte.d.ts +60 -0
  143. package/dist/marks/Line.svelte +64 -0
  144. package/dist/marks/Line.svelte.d.ts +43 -0
  145. package/dist/marks/LineEndLabels.svelte +70 -0
  146. package/dist/marks/LineEndLabels.svelte.d.ts +41 -0
  147. package/dist/marks/Points.svelte +70 -0
  148. package/dist/marks/Points.svelte.d.ts +46 -0
  149. package/dist/marks/Rects.svelte +92 -0
  150. package/dist/marks/Rects.svelte.d.ts +47 -0
  151. package/dist/marks/Rules.svelte +46 -0
  152. package/dist/marks/Rules.svelte.d.ts +15 -0
  153. package/dist/marks/Slope.svelte +112 -0
  154. package/dist/marks/Slope.svelte.d.ts +41 -0
  155. package/dist/marks/Text.svelte +75 -0
  156. package/dist/marks/Text.svelte.d.ts +47 -0
  157. package/dist/marks/Treemap.svelte +89 -0
  158. package/dist/marks/Treemap.svelte.d.ts +45 -0
  159. package/dist/marks/Voronoi.svelte +61 -0
  160. package/dist/marks/Voronoi.svelte.d.ts +39 -0
  161. package/dist/marks/Waffle.svelte +77 -0
  162. package/dist/marks/Waffle.svelte.d.ts +45 -0
  163. package/dist/marks/bar-path.d.ts +5 -0
  164. package/dist/marks/bar-path.js +15 -0
  165. package/dist/marks/index.d.ts +20 -0
  166. package/dist/marks/index.js +20 -0
  167. package/dist/recipes/ArrowChart.svelte +247 -0
  168. package/dist/recipes/ArrowChart.svelte.d.ts +73 -0
  169. package/dist/recipes/BarChart.svelte +122 -0
  170. package/dist/recipes/BarChart.svelte.d.ts +58 -0
  171. package/dist/recipes/BarDotChart.svelte +204 -0
  172. package/dist/recipes/BarDotChart.svelte.d.ts +75 -0
  173. package/dist/recipes/ColumnChart.svelte +119 -0
  174. package/dist/recipes/ColumnChart.svelte.d.ts +56 -0
  175. package/dist/recipes/LineChart.svelte +159 -0
  176. package/dist/recipes/LineChart.svelte.d.ts +61 -0
  177. package/dist/recipes/MosaicChart.svelte +256 -0
  178. package/dist/recipes/MosaicChart.svelte.d.ts +83 -0
  179. package/dist/recipes/ScatterChart.svelte +167 -0
  180. package/dist/recipes/ScatterChart.svelte.d.ts +63 -0
  181. package/dist/recipes/StackedBarChart.svelte +222 -0
  182. package/dist/recipes/StackedBarChart.svelte.d.ts +83 -0
  183. package/dist/recipes/index.d.ts +10 -0
  184. package/dist/recipes/index.js +19 -0
  185. package/dist/styles/base.d.ts +5 -0
  186. package/dist/styles/base.js +102 -0
  187. package/dist/styles/check.d.ts +8 -0
  188. package/dist/styles/check.js +32 -0
  189. package/dist/styles/color.d.ts +11 -0
  190. package/dist/styles/color.js +29 -0
  191. package/dist/styles/index.d.ts +9 -0
  192. package/dist/styles/index.js +17 -0
  193. package/dist/styles/types.d.ts +90 -0
  194. package/dist/styles/types.js +1 -0
  195. package/dist/table/Sparkline.svelte +59 -0
  196. package/dist/table/Sparkline.svelte.d.ts +16 -0
  197. package/dist/table/Table.svelte +287 -0
  198. package/dist/table/Table.svelte.d.ts +44 -0
  199. package/dist/table/csv.d.ts +3 -0
  200. package/dist/table/csv.js +12 -0
  201. package/dist/table/index.d.ts +4 -0
  202. package/dist/table/index.js +3 -0
  203. package/dist/table/types.d.ts +26 -0
  204. package/dist/table/types.js +1 -0
  205. package/dist/transforms/bin.d.ts +15 -0
  206. package/dist/transforms/bin.js +18 -0
  207. package/dist/transforms/dodge.d.ts +10 -0
  208. package/dist/transforms/dodge.js +35 -0
  209. package/dist/transforms/group.d.ts +14 -0
  210. package/dist/transforms/group.js +14 -0
  211. package/dist/transforms/hemicycle.d.ts +30 -0
  212. package/dist/transforms/hemicycle.js +51 -0
  213. package/dist/transforms/index.d.ts +8 -0
  214. package/dist/transforms/index.js +8 -0
  215. package/dist/transforms/labels.d.ts +6 -0
  216. package/dist/transforms/labels.js +20 -0
  217. package/dist/transforms/smooth.d.ts +61 -0
  218. package/dist/transforms/smooth.js +105 -0
  219. package/dist/transforms/stack.d.ts +25 -0
  220. package/dist/transforms/stack.js +61 -0
  221. package/dist/transforms/treemap.d.ts +21 -0
  222. package/dist/transforms/treemap.js +31 -0
  223. package/package.json +152 -3
  224. package/src/lib/recipes/ArrowChart.svelte +247 -0
  225. package/src/lib/recipes/BarChart.svelte +122 -0
  226. package/src/lib/recipes/BarDotChart.svelte +204 -0
  227. package/src/lib/recipes/ColumnChart.svelte +119 -0
  228. package/src/lib/recipes/LineChart.svelte +159 -0
  229. package/src/lib/recipes/MosaicChart.svelte +256 -0
  230. package/src/lib/recipes/ScatterChart.svelte +167 -0
  231. package/src/lib/recipes/StackedBarChart.svelte +222 -0
  232. package/src/lib/recipes/index.ts +20 -0
@@ -0,0 +1,159 @@
1
+ <!--
2
+ @component
3
+ Recipe: a multi-series line chart with a legend, direct end labels and a
4
+ crosshair tooltip. Series colours follow the series order in the theme's
5
+ categorical palette. `mozaic eject LineChart` copies this file into your
6
+ project.
7
+ -->
8
+ <script lang="ts" generics="S, P">
9
+ import type { Snippet } from 'svelte';
10
+ import { scaleLinear, scaleTime } from 'd3-scale';
11
+ import { bisector, extent, max, min } from 'd3-array';
12
+ import { curveMonotoneX } from 'd3-shape';
13
+ import { Chart, Header, Title, Subtitle, Footer, Source, Notes } from '../frame/index.js';
14
+ import type { ChartEmbed } from '../embed/index.js';
15
+ import { Plot, Svg, Html, type PlotContext } from '../core/index.js';
16
+ import { Line, LineEndLabels } from '../marks/index.js';
17
+ import { AxisX, AxisY, GridY, Legend } from '../guides/index.js';
18
+ import { PointerArea, Tooltip } from '../interactive/index.js';
19
+ import { createLocale, type LocaleCode } from '../locale/index.js';
20
+ import { base, type Medium, type Theme } from '../styles/index.js';
21
+
22
+ interface Props {
23
+ series: S[];
24
+ /** Points of one series, sorted by x. */
25
+ points: (s: S) => P[];
26
+ name: (s: S) => string;
27
+ x: (p: P) => Date;
28
+ y: (p: P) => number;
29
+ style?: Theme;
30
+ locale?: LocaleCode;
31
+ medium?: Medium;
32
+ width?: number;
33
+ title?: string;
34
+ subtitle?: string;
35
+ notes?: string;
36
+ source?: string;
37
+ alt?: string;
38
+ /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
39
+ embed?: ChartEmbed;
40
+ format?: (n: number) => string;
41
+ /** Tooltip date format (d3-time-format specifier). */
42
+ dateFormat?: string;
43
+ color?: (s: S, index: number) => string;
44
+ /** Start the y axis at zero. */
45
+ zero?: boolean;
46
+ height?: number;
47
+ annotations?: Snippet<[PlotContext]>;
48
+ }
49
+
50
+ let {
51
+ series,
52
+ points,
53
+ name,
54
+ x: xValue,
55
+ y: yValue,
56
+ style = base,
57
+ locale,
58
+ medium,
59
+ width,
60
+ title,
61
+ subtitle,
62
+ notes,
63
+ source,
64
+ alt,
65
+ embed,
66
+ format,
67
+ dateFormat = '%B %Y',
68
+ color,
69
+ zero = false,
70
+ height,
71
+ annotations
72
+ }: Props = $props();
73
+
74
+ const theme = $derived(style);
75
+ const loc = $derived(createLocale(locale ?? theme.defaultLocale));
76
+ const fmt = $derived(format ?? loc.number);
77
+ const colour = (s: S, i: number) =>
78
+ color?.(s, i) ?? theme.palettes.categorical[i % theme.palettes.categorical.length];
79
+
80
+ const all = $derived(series.flatMap(points));
81
+ const x = $derived(scaleTime().domain(extent(all, xValue) as [Date, Date]));
82
+ const y = $derived(
83
+ scaleLinear()
84
+ .domain([zero ? Math.min(0, min(all, yValue) ?? 0) : (min(all, yValue) ?? 0), max(all, yValue) ?? 1])
85
+ .nice()
86
+ );
87
+ const ends = $derived(series.map((s, i) => ({ s, i, p: points(s)[points(s).length - 1] })).filter((e) => e.p));
88
+ const dates = $derived(points(series[0] ?? ([] as unknown as S)) ?? []);
89
+ const nearest = $derived(bisector<P, Date>(xValue).center);
90
+ let hover = $state<P | null>(null);
91
+ const valueAt = (s: S, date: Date) => points(s).find((p) => +xValue(p) === +date);
92
+ </script>
93
+
94
+ <Chart {style} {locale} {medium} {width} {alt} {embed}>
95
+ <Header>
96
+ {#if title}<Title>{title}</Title>{/if}
97
+ {#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
98
+ {#if series.length > 1}
99
+ <Legend shape="line" items={series.map((s, i) => ({ label: name(s), color: colour(s, i) }))} />
100
+ {/if}
101
+ </Header>
102
+
103
+ <Plot
104
+ {x}
105
+ {y}
106
+ height={height ?? (({ breakpoint }) => (breakpoint === 's' ? 260 : 340))}
107
+ padding={({ breakpoint }) => ({ left: breakpoint === 's' ? 0 : 40, right: 80, top: 16, bottom: 28 })}
108
+ >
109
+ {#snippet children(plot)}
110
+ <Svg>
111
+ <GridY ticks={5} />
112
+ <AxisY ticks={5} format={fmt} inside={plot.breakpoint === 's'} />
113
+ <AxisX ticks={plot.breakpoint === 's' ? 4 : 7} />
114
+ {#if hover}
115
+ <line x1={plot.x(xValue(hover))} x2={plot.x(xValue(hover))} y2={plot.height} stroke="var(--mz-color-axis)" />
116
+ {/if}
117
+ {#each series as s, i}
118
+ <Line data={points(s)} x={xValue} y={yValue} stroke={colour(s, i)} curve={curveMonotoneX} />
119
+ {/each}
120
+ <LineEndLabels
121
+ data={ends}
122
+ x={(e) => xValue(e.p)}
123
+ y={(e) => yValue(e.p)}
124
+ text={(e) => name(e.s)}
125
+ color={(e) => colour(e.s, e.i)}
126
+ />
127
+ {@render annotations?.(plot)}
128
+ <PointerArea
129
+ onmove={({ x: px }) => {
130
+ const date = plot.x.invert?.(px);
131
+ hover = date ? (dates[nearest(dates, date)] ?? null) : null;
132
+ }}
133
+ onleave={() => (hover = null)}
134
+ />
135
+ </Svg>
136
+ <Html>
137
+ {#if hover}
138
+ {@const date = xValue(hover)}
139
+ <Tooltip x={plot.x(date) ?? 0} y={plot.height / 2}>
140
+ <strong>{loc.timeFormat(dateFormat)(date)}</strong>
141
+ {#each series as s, i}
142
+ {@const p = valueAt(s, date)}
143
+ {#if p}
144
+ <div><span style:color={colour(s, i)}>●</span> {name(s)}: <strong>{fmt(yValue(p))}</strong></div>
145
+ {/if}
146
+ {/each}
147
+ </Tooltip>
148
+ {/if}
149
+ </Html>
150
+ {/snippet}
151
+ </Plot>
152
+
153
+ {#if notes || source}
154
+ <Footer>
155
+ {#if notes}<Notes>{notes}</Notes>{/if}
156
+ {#if source}<Source>{source}</Source>{/if}
157
+ </Footer>
158
+ {/if}
159
+ </Chart>
@@ -0,0 +1,61 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { ChartEmbed } from '../embed/index.js';
3
+ import { type PlotContext } from '../core/index.js';
4
+ import { type LocaleCode } from '../locale/index.js';
5
+ import { type Medium, type Theme } from '../styles/index.js';
6
+ declare function $$render<S, P>(): {
7
+ props: {
8
+ series: S[];
9
+ /** Points of one series, sorted by x. */
10
+ points: (s: S) => P[];
11
+ name: (s: S) => string;
12
+ x: (p: P) => Date;
13
+ y: (p: P) => number;
14
+ style?: Theme;
15
+ locale?: LocaleCode;
16
+ medium?: Medium;
17
+ width?: number;
18
+ title?: string;
19
+ subtitle?: string;
20
+ notes?: string;
21
+ source?: string;
22
+ alt?: string;
23
+ /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
24
+ embed?: ChartEmbed;
25
+ format?: (n: number) => string;
26
+ /** Tooltip date format (d3-time-format specifier). */
27
+ dateFormat?: string;
28
+ color?: (s: S, index: number) => string;
29
+ /** Start the y axis at zero. */
30
+ zero?: boolean;
31
+ height?: number;
32
+ annotations?: Snippet<[PlotContext]>;
33
+ };
34
+ exports: {};
35
+ bindings: "";
36
+ slots: {};
37
+ events: {};
38
+ };
39
+ declare class __sveltets_Render<S, P> {
40
+ props(): ReturnType<typeof $$render<S, P>>['props'];
41
+ events(): ReturnType<typeof $$render<S, P>>['events'];
42
+ slots(): ReturnType<typeof $$render<S, P>>['slots'];
43
+ bindings(): "";
44
+ exports(): {};
45
+ }
46
+ interface $$IsomorphicComponent {
47
+ new <S, P>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<S, P>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<S, P>['props']>, ReturnType<__sveltets_Render<S, P>['events']>, ReturnType<__sveltets_Render<S, P>['slots']>> & {
48
+ $$bindings?: ReturnType<__sveltets_Render<S, P>['bindings']>;
49
+ } & ReturnType<__sveltets_Render<S, P>['exports']>;
50
+ <S, P>(internal: unknown, props: ReturnType<__sveltets_Render<S, P>['props']> & {}): ReturnType<__sveltets_Render<S, P>['exports']>;
51
+ z_$$bindings?: ReturnType<__sveltets_Render<any, any>['bindings']>;
52
+ }
53
+ /**
54
+ * Recipe: a multi-series line chart with a legend, direct end labels and a
55
+ * crosshair tooltip. Series colours follow the series order in the theme's
56
+ * categorical palette. `mozaic eject LineChart` copies this file into your
57
+ * project.
58
+ */
59
+ declare const LineChart: $$IsomorphicComponent;
60
+ type LineChart<S, P> = InstanceType<typeof LineChart<S, P>>;
61
+ export default LineChart;
@@ -0,0 +1,256 @@
1
+ <!--
2
+ @component
3
+ Recipe: a mosaic (Marimekko) chart. One 100% stacked bar per row, with each
4
+ row as tall as its weight (by default the sum of its values), so the area of
5
+ every cell is proportional to its value: votes by district, where the
6
+ height shows how many people voted there. Row labels sit at the right, nudged
7
+ apart where rows are thin. Optional: rows sorted by the share of some series,
8
+ a reference line, and series names written once inside their largest cell.
9
+ Use it as is, or run `mozaic eject MosaicChart` to copy this file into your
10
+ project and change anything.
11
+ -->
12
+ <script lang="ts" generics="T">
13
+ import type { Snippet } from 'svelte';
14
+ import { scaleLinear } from 'd3-scale';
15
+ import { group, sum } from 'd3-array';
16
+ import { Chart, Header, Title, Subtitle, Footer, Source, Notes } from '../frame/index.js';
17
+ import type { ChartEmbed } from '../embed/index.js';
18
+ import { Plot, Svg, estimateTextWidth, type PlotContext } from '../core/index.js';
19
+ import { Rects } from '../marks/index.js';
20
+ import { AxisX, Legend } from '../guides/index.js';
21
+ import { RefLine } from '../annotations/index.js';
22
+ import { avoidOverlap } from '../transforms/index.js';
23
+ import { createLocale, type LocaleCode } from '../locale/index.js';
24
+ import { base, contrastRatio, type Breakpoint, type Medium, type Theme } from '../styles/index.js';
25
+
26
+ interface Props {
27
+ /** Long format: one datum per row × series. */
28
+ data: T[];
29
+ row: (d: T) => string;
30
+ series: (d: T) => string;
31
+ value: (d: T) => number;
32
+ /** Row height weight; defaults to the sum of the row's values. */
33
+ weight?: (row: string) => number;
34
+ /** Stacking order, left to right. Defaults to first appearance. */
35
+ seriesOrder?: string[];
36
+ /** Sort rows by the combined share of these series, largest first. Defaults to the order given. */
37
+ sortBy?: string[];
38
+ color?: (series: string) => string;
39
+ seriesLabel?: (series: string) => string;
40
+ /** Legend items; defaults to one per series. Pass [] to hide the legend. */
41
+ legend?: { label: string; color: string }[];
42
+ /** Series named once inside their largest cell, when the name fits. */
43
+ labelSeries?: string[];
44
+ /** Vertical reference line at this share (0–1), e.g. 0.5. */
45
+ reference?: number;
46
+ referenceLabel?: string;
47
+ style?: Theme;
48
+ locale?: LocaleCode;
49
+ medium?: Medium;
50
+ width?: number;
51
+ title?: string;
52
+ subtitle?: string;
53
+ notes?: string;
54
+ source?: string;
55
+ alt?: string;
56
+ /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
57
+ embed?: ChartEmbed;
58
+ /** Share format (0–1) for tooltips; defaults to a locale percentage with one decimal. */
59
+ format?: (share: number) => string;
60
+ /** Plot height in px, or a function of the outer width and breakpoint. Defaults to enough room for every row label, and at least 480 px. */
61
+ height?: number | ((size: { width: number; breakpoint: Breakpoint }) => number);
62
+ /** Extra SVG drawn on top of the cells; receives the plot context. */
63
+ annotations?: Snippet<[PlotContext]>;
64
+ }
65
+
66
+ let {
67
+ data,
68
+ row,
69
+ series,
70
+ value,
71
+ weight,
72
+ seriesOrder,
73
+ sortBy,
74
+ color,
75
+ seriesLabel = (s) => s,
76
+ legend,
77
+ labelSeries = [],
78
+ reference,
79
+ referenceLabel,
80
+ style = base,
81
+ locale,
82
+ medium,
83
+ width,
84
+ title,
85
+ subtitle,
86
+ notes,
87
+ source,
88
+ alt,
89
+ embed,
90
+ format,
91
+ height,
92
+ annotations
93
+ }: Props = $props();
94
+
95
+ const theme = $derived(style);
96
+ const loc = $derived(createLocale(locale ?? theme.defaultLocale));
97
+ const fmt = $derived(format ?? ((s: number) => loc.format('.1%')(s)));
98
+ const fontSize = $derived(theme.plot.fontSize);
99
+ const ink = $derived(theme.tokens['--mz-color-text'] ?? '#000');
100
+ const paper = $derived(theme.tokens['--mz-color-bg'] ?? '#fff');
101
+
102
+ const order = $derived(seriesOrder ?? [...new Set(data.map(series))]);
103
+ const colorOf = $derived(
104
+ (s: string) => color?.(s) ?? theme.palettes.categorical[order.indexOf(s) % theme.palettes.categorical.length]
105
+ );
106
+ const textOn = (fill: string) => (contrastRatio(fill, paper) >= contrastRatio(fill, ink) ? paper : ink);
107
+ const legendItems = $derived(legend ?? order.map((s) => ({ label: seriesLabel(s), color: colorOf(s) })));
108
+
109
+ interface Cell {
110
+ row: string;
111
+ series: string;
112
+ share: number;
113
+ /** Share axis, 0–1. */
114
+ x0: number;
115
+ x1: number;
116
+ /** Cumulative weight axis, top to bottom. */
117
+ y0: number;
118
+ y1: number;
119
+ }
120
+
121
+ const layout = $derived.by(() => {
122
+ const byRow = group(data, row);
123
+ const rows = [...byRow].map(([name, ds]) => {
124
+ const total = sum(ds, value);
125
+ const share = (s: string) =>
126
+ sum(
127
+ ds.filter((d) => series(d) === s),
128
+ value
129
+ ) / (total || 1);
130
+ return { name, total, weight: weight?.(name) ?? total, share };
131
+ });
132
+ if (sortBy) {
133
+ const key = (r: (typeof rows)[number]) => sum(sortBy, r.share);
134
+ rows.sort((a, b) => key(b) - key(a));
135
+ }
136
+ const cells: Cell[] = [];
137
+ const bands: { name: string; y0: number; y1: number }[] = [];
138
+ let y = 0;
139
+ for (const r of rows) {
140
+ let x = 0;
141
+ for (const s of order) {
142
+ const share = r.share(s);
143
+ if (share > 0) cells.push({ row: r.name, series: s, share, x0: x, x1: x + share, y0: y, y1: y + r.weight });
144
+ x += share;
145
+ }
146
+ bands.push({ name: r.name, y0: y, y1: y + r.weight });
147
+ y += r.weight;
148
+ }
149
+ return { cells, bands, total: y };
150
+ });
151
+
152
+ const x = scaleLinear().domain([0, 1]);
153
+ const y = $derived(scaleLinear().domain([0, layout.total]));
154
+ const plotHeight = $derived(
155
+ height ??
156
+ (({ width: w }: { width: number }) =>
157
+ Math.max(480, layout.bands.length * (fontSize + 4) * 1.4, Math.min(900, w * 1.1)))
158
+ );
159
+ const right = $derived(Math.max(...layout.bands.map((b) => estimateTextWidth(b.name, fontSize))) + 18);
160
+
161
+ /** Row labels at the centre of each row, nudged apart; a short tick joins a moved label to its row. */
162
+ function rowLabels(plot: PlotContext) {
163
+ const centres = layout.bands.map((b) => ((plot.y(b.y0) ?? 0) + (plot.y(b.y1) ?? 0)) / 2);
164
+ const placed = avoidOverlap(centres, fontSize + 1, [fontSize / 2, plot.height - fontSize / 2]);
165
+ return layout.bands.map((b, i) => ({ name: b.name, at: centres[i], y: placed[i] }));
166
+ }
167
+
168
+ /** Each labelled series named in its largest cell that holds the name. */
169
+ function seriesLabels(plot: PlotContext) {
170
+ return labelSeries.flatMap((s) => {
171
+ const text = seriesLabel(s);
172
+ const w = estimateTextWidth(text, fontSize) + 12;
173
+ const fits = layout.cells
174
+ .filter((c) => c.series === s)
175
+ .map((c) => ({
176
+ c,
177
+ x0: plot.x(c.x0) ?? 0,
178
+ x1: plot.x(c.x1) ?? 0,
179
+ y0: plot.y(c.y0) ?? 0,
180
+ y1: plot.y(c.y1) ?? 0
181
+ }))
182
+ .filter((r) => r.x1 - r.x0 >= w && r.y1 - r.y0 >= fontSize + 8)
183
+ .sort((a, b) => (b.x1 - b.x0) * (b.y1 - b.y0) - (a.x1 - a.x0) * (a.y1 - a.y0));
184
+ const best = fits[0];
185
+ return best ? [{ text, x: (best.x0 + best.x1) / 2, y: (best.y0 + best.y1) / 2, fill: textOn(colorOf(s)) }] : [];
186
+ });
187
+ }
188
+ </script>
189
+
190
+ <Chart {style} {locale} {medium} {width} {alt} {embed}>
191
+ {#if title || subtitle || legendItems.length > 1}
192
+ <Header>
193
+ {#if title}<Title>{title}</Title>{/if}
194
+ {#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
195
+ {#if legendItems.length > 1}<Legend items={legendItems} />{/if}
196
+ </Header>
197
+ {/if}
198
+
199
+ <Plot {x} {y} yRange={({ height: h }) => [0, h]} height={plotHeight} padding={{ left: 0, right, top: 0, bottom: 24 }}>
200
+ {#snippet children(plot)}
201
+ <Svg>
202
+ <AxisX ticks={4} format={(v) => loc.format('.0%')(v)} />
203
+ <Rects
204
+ data={layout.cells}
205
+ x={(c) => c.x0}
206
+ x2={(c) => c.x1}
207
+ y={(c) => c.y0}
208
+ y2={(c) => c.y1}
209
+ fill={(c) => colorOf(c.series)}
210
+ stroke={paper}
211
+ title={(c) => `${c.row} · ${seriesLabel(c.series)}: ${fmt(c.share)}`}
212
+ />
213
+ {#each seriesLabels(plot) as l (l.text)}
214
+ <text class="mz-mosaic-series" x={l.x} y={l.y} dy="0.35em" text-anchor="middle" fill={l.fill}>{l.text}</text>
215
+ {/each}
216
+ {#if reference !== undefined}
217
+ <RefLine x={reference} label={referenceLabel} />
218
+ {/if}
219
+ {#each rowLabels(plot) as l (l.name)}
220
+ <g class="mz-mosaic-row">
221
+ {#if Math.abs(l.y - l.at) > 2}
222
+ <path d="M{plot.width + 1},{l.at} L{plot.width + 5},{l.y}" />
223
+ {/if}
224
+ <text x={plot.width + 7} y={l.y} dy="0.35em">{l.name}</text>
225
+ </g>
226
+ {/each}
227
+ {@render annotations?.(plot)}
228
+ </Svg>
229
+ {/snippet}
230
+ </Plot>
231
+
232
+ {#if notes || source}
233
+ <Footer>
234
+ {#if notes}<Notes>{notes}</Notes>{/if}
235
+ {#if source}<Source>{source}</Source>{/if}
236
+ </Footer>
237
+ {/if}
238
+ </Chart>
239
+
240
+ <style>
241
+ .mz-mosaic-row text,
242
+ .mz-mosaic-series {
243
+ font-family: var(--mz-font-body);
244
+ font-size: var(--mz-size-axis);
245
+ }
246
+ .mz-mosaic-row text {
247
+ fill: var(--mz-color-text);
248
+ }
249
+ .mz-mosaic-row path {
250
+ fill: none;
251
+ stroke: var(--mz-color-axis);
252
+ }
253
+ .mz-mosaic-series {
254
+ font-weight: var(--mz-weight-strong);
255
+ }
256
+ </style>
@@ -0,0 +1,83 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { ChartEmbed } from '../embed/index.js';
3
+ import { type PlotContext } from '../core/index.js';
4
+ import { type LocaleCode } from '../locale/index.js';
5
+ import { type Breakpoint, type Medium, type Theme } from '../styles/index.js';
6
+ declare function $$render<T>(): {
7
+ props: {
8
+ /** Long format: one datum per row × series. */
9
+ data: T[];
10
+ row: (d: T) => string;
11
+ series: (d: T) => string;
12
+ value: (d: T) => number;
13
+ /** Row height weight; defaults to the sum of the row's values. */
14
+ weight?: (row: string) => number;
15
+ /** Stacking order, left to right. Defaults to first appearance. */
16
+ seriesOrder?: string[];
17
+ /** Sort rows by the combined share of these series, largest first. Defaults to the order given. */
18
+ sortBy?: string[];
19
+ color?: (series: string) => string;
20
+ seriesLabel?: (series: string) => string;
21
+ /** Legend items; defaults to one per series. Pass [] to hide the legend. */
22
+ legend?: {
23
+ label: string;
24
+ color: string;
25
+ }[];
26
+ /** Series named once inside their largest cell, when the name fits. */
27
+ labelSeries?: string[];
28
+ /** Vertical reference line at this share (0–1), e.g. 0.5. */
29
+ reference?: number;
30
+ referenceLabel?: string;
31
+ style?: Theme;
32
+ locale?: LocaleCode;
33
+ medium?: Medium;
34
+ width?: number;
35
+ title?: string;
36
+ subtitle?: string;
37
+ notes?: string;
38
+ source?: string;
39
+ alt?: string;
40
+ /** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
41
+ embed?: ChartEmbed;
42
+ /** Share format (0–1) for tooltips; defaults to a locale percentage with one decimal. */
43
+ format?: (share: number) => string;
44
+ /** Plot height in px, or a function of the outer width and breakpoint. Defaults to enough room for every row label, and at least 480 px. */
45
+ height?: number | ((size: {
46
+ width: number;
47
+ breakpoint: Breakpoint;
48
+ }) => number);
49
+ /** Extra SVG drawn on top of the cells; receives the plot context. */
50
+ annotations?: Snippet<[PlotContext]>;
51
+ };
52
+ exports: {};
53
+ bindings: "";
54
+ slots: {};
55
+ events: {};
56
+ };
57
+ declare class __sveltets_Render<T> {
58
+ props(): ReturnType<typeof $$render<T>>['props'];
59
+ events(): ReturnType<typeof $$render<T>>['events'];
60
+ slots(): ReturnType<typeof $$render<T>>['slots'];
61
+ bindings(): "";
62
+ exports(): {};
63
+ }
64
+ interface $$IsomorphicComponent {
65
+ new <T>(options: import('svelte').ComponentConstructorOptions<ReturnType<__sveltets_Render<T>['props']>>): import('svelte').SvelteComponent<ReturnType<__sveltets_Render<T>['props']>, ReturnType<__sveltets_Render<T>['events']>, ReturnType<__sveltets_Render<T>['slots']>> & {
66
+ $$bindings?: ReturnType<__sveltets_Render<T>['bindings']>;
67
+ } & ReturnType<__sveltets_Render<T>['exports']>;
68
+ <T>(internal: unknown, props: ReturnType<__sveltets_Render<T>['props']> & {}): ReturnType<__sveltets_Render<T>['exports']>;
69
+ z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
70
+ }
71
+ /**
72
+ * Recipe: a mosaic (Marimekko) chart. One 100% stacked bar per row, with each
73
+ * row as tall as its weight (by default the sum of its values), so the area of
74
+ * every cell is proportional to its value: votes by district, where the
75
+ * height shows how many people voted there. Row labels sit at the right, nudged
76
+ * apart where rows are thin. Optional: rows sorted by the share of some series,
77
+ * a reference line, and series names written once inside their largest cell.
78
+ * Use it as is, or run `mozaic eject MosaicChart` to copy this file into your
79
+ * project and change anything.
80
+ */
81
+ declare const MosaicChart: $$IsomorphicComponent;
82
+ type MosaicChart<T> = InstanceType<typeof MosaicChart<T>>;
83
+ export default MosaicChart;