@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,32 @@
1
+ export function isScale(value) {
2
+ return typeof value === 'function' && typeof value.domain === 'function';
3
+ }
4
+ /** True for band and point scales (they have a bandwidth). */
5
+ export function isOrdinal(scale) {
6
+ return isScale(scale) && typeof scale.bandwidth === 'function';
7
+ }
8
+ /**
9
+ * Pixel position of a value. For band scales, returns the point at `align`
10
+ * across the band (0.5 = centre), so marks can treat all scales alike.
11
+ */
12
+ export function scaled(scale, value, align = 0.5) {
13
+ const px = scale(value);
14
+ if (px == null || Number.isNaN(px))
15
+ return NaN;
16
+ return scale.bandwidth ? px + scale.bandwidth() * align : px;
17
+ }
18
+ /** Rough text width for layout decisions (padding for long labels). Deterministic on server and client. */
19
+ export function estimateTextWidth(text, fontSize, averageCharWidth = 0.56) {
20
+ return text.length * fontSize * averageCharWidth;
21
+ }
22
+ /**
23
+ * Pixel position of a data point. With a projection on the plot, `x`/`y` are
24
+ * longitude/latitude; otherwise they go through the x and y scales.
25
+ */
26
+ export function position(plot, x, y) {
27
+ if (plot.projection) {
28
+ const p = plot.projection([Number(x), Number(y)]);
29
+ return p ? [p[0], p[1]] : [NaN, NaN];
30
+ }
31
+ return [scaled(plot.x, x), scaled(plot.y, y)];
32
+ }
@@ -0,0 +1,78 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { GeoPath, GeoPermissibleObjects, GeoProjection } from 'd3-geo';
3
+ import type { Locale } from '../locale/index.js';
4
+ import type { Breakpoint, Medium, Padding, Theme } from '../styles/types.js';
5
+ export type { Breakpoint, Medium, Padding };
6
+ /**
7
+ * Any d3 scale that maps a data value to a pixel position:
8
+ * linear, log, sqrt, symlog, time, utc, band, point, identity, …
9
+ */
10
+ export interface PositionScale {
11
+ (value: any): number | undefined;
12
+ domain(): any[];
13
+ range(): number[];
14
+ range(range: Iterable<number>): this;
15
+ copy(): this;
16
+ bandwidth?(): number;
17
+ invert?(value: number): any;
18
+ ticks?(count?: number): any[];
19
+ }
20
+ /** Sizes passed to scale, range and projection factories. */
21
+ export interface Dimensions {
22
+ /** Plot-area width (inside the padding). */
23
+ width: number;
24
+ /** Plot-area height (inside the padding). */
25
+ height: number;
26
+ padding: Padding;
27
+ fullWidth: number;
28
+ fullHeight: number;
29
+ breakpoint: Breakpoint;
30
+ }
31
+ /** A d3 scale (Plot sets its range), or a factory that returns a fully configured scale. */
32
+ export type ScaleInput = PositionScale | ((dims: Dimensions) => PositionScale);
33
+ export type RangeInput = [number, number] | ((dims: Dimensions) => [number, number]);
34
+ /** A d3 projection, or a factory that returns a fitted projection. */
35
+ export type ProjectionInput = GeoProjection | ((dims: Dimensions) => GeoProjection);
36
+ /** What `usePlot()` returns. All values are reactive. */
37
+ export interface PlotContext {
38
+ readonly width: number;
39
+ readonly height: number;
40
+ readonly padding: Padding;
41
+ readonly fullWidth: number;
42
+ readonly fullHeight: number;
43
+ /** False during server rendering, before the container has been measured. */
44
+ readonly measured: boolean;
45
+ readonly breakpoint: Breakpoint;
46
+ readonly medium: Medium;
47
+ /** Position scales with ranges set. Identity scales (pixels) when none were given. */
48
+ readonly x: PositionScale;
49
+ readonly y: PositionScale;
50
+ /** Extra named scales (colour, radius, …). */
51
+ readonly scales: Record<string, any>;
52
+ readonly projection: GeoProjection | undefined;
53
+ /** `geoPath` bound to the projection; undefined when there is no projection. */
54
+ readonly path: GeoPath<any, GeoPermissibleObjects> | undefined;
55
+ }
56
+ /** What `useChart()` returns. All values are reactive. */
57
+ export interface ChartContext {
58
+ readonly theme: Theme;
59
+ readonly locale: Locale;
60
+ readonly medium: Medium;
61
+ readonly breakpoint: Breakpoint;
62
+ /** Chart width in px (initial width until measured). */
63
+ readonly width: number;
64
+ readonly measured: boolean;
65
+ /** Element ids used for ARIA wiring. */
66
+ readonly ids: {
67
+ title: string;
68
+ desc: string;
69
+ /** Set by `<Title>` as it renders, so the SVG is only labelled by a title that exists. */
70
+ hasTitle?: boolean;
71
+ /** Whether the chart has alt text (rendered with the `desc` id). */
72
+ readonly hasDesc?: boolean;
73
+ };
74
+ /** What the buttons under the chart open besides embed and download: `<DataTable>` puts its table here. */
75
+ readonly tools?: {
76
+ table: Snippet | null;
77
+ };
78
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ /** CSS pixels per millimetre (96 dpi). */
2
+ export declare const PX_PER_MM: number;
3
+ /** Millimetres → CSS pixels, for print widths: `<Chart medium="print" width={mm(55)}>`. */
4
+ export declare function mm(value: number): number;
5
+ /** Points → CSS pixels. */
6
+ export declare function pt(value: number): number;
@@ -0,0 +1,10 @@
1
+ /** CSS pixels per millimetre (96 dpi). */
2
+ export const PX_PER_MM = 96 / 25.4;
3
+ /** Millimetres → CSS pixels, for print widths: `<Chart medium="print" width={mm(55)}>`. */
4
+ export function mm(value) {
5
+ return value * PX_PER_MM;
6
+ }
7
+ /** Points → CSS pixels. */
8
+ export function pt(value) {
9
+ return (value * 96) / 72;
10
+ }
@@ -0,0 +1,50 @@
1
+ <!--
2
+ @component
3
+ Wraps the chart on an embed page. It reports its height to the host page
4
+ (see `embed.js`), removes page margins, hides the chart's embed code, and exposes `window.__mozaic` so
5
+ `mozaic export` can render SVG from the live chart.
6
+ -->
7
+ <script lang="ts">
8
+ import type { Snippet } from 'svelte';
9
+ import { observeHeight } from './resize.js';
10
+ import { figureToSvg } from '../export/figure-to-svg.js';
11
+ import { setEmbedded } from '../core/context.js';
12
+
13
+ interface Props {
14
+ /** Identifies this embed in resize messages; defaults to the URL path. */
15
+ id?: string;
16
+ children?: Snippet;
17
+ }
18
+
19
+ let { id, children }: Props = $props();
20
+
21
+ let container = $state<HTMLDivElement>();
22
+ setEmbedded();
23
+
24
+ $effect(() => {
25
+ if (!container) return;
26
+ const el = container;
27
+ const stop = observeHeight(el, id ?? location.pathname);
28
+ (window as unknown as { __mozaic: unknown }).__mozaic = {
29
+ ready: true,
30
+ toSvg: () => figureToSvg((el.querySelector('.mz-chart') as HTMLElement | null) ?? el)
31
+ };
32
+ return stop;
33
+ });
34
+ </script>
35
+
36
+ <div class="mz-embed" bind:this={container}>
37
+ {@render children?.()}
38
+ </div>
39
+
40
+ <style>
41
+ :global(html),
42
+ :global(body) {
43
+ margin: 0;
44
+ padding: 0;
45
+ background: transparent;
46
+ }
47
+ .mz-embed {
48
+ display: flow-root;
49
+ }
50
+ </style>
@@ -0,0 +1,14 @@
1
+ import type { Snippet } from 'svelte';
2
+ interface Props {
3
+ /** Identifies this embed in resize messages; defaults to the URL path. */
4
+ id?: string;
5
+ children?: Snippet;
6
+ }
7
+ /**
8
+ * Wraps the chart on an embed page. It reports its height to the host page
9
+ * (see `embed.js`), removes page margins, hides the chart's embed code, and exposes `window.__mozaic` so
10
+ * `mozaic export` can render SVG from the live chart.
11
+ */
12
+ declare const Embed: import("svelte").Component<Props, {}, "">;
13
+ type Embed = ReturnType<typeof Embed>;
14
+ export default Embed;
@@ -0,0 +1,18 @@
1
+ /** The HTML snippet to paste into a CMS to embed a chart. */
2
+ export declare function embedCode(options: {
3
+ src: string;
4
+ title: string;
5
+ height?: number;
6
+ scriptSrc?: string;
7
+ }): string;
8
+ /** Where a chart's embed page is, for the embed code shown under the chart (`<Chart embed>`). */
9
+ export interface ChartEmbed {
10
+ /** The chart's embed page. A path is resolved against the page the chart is on. */
11
+ src: string;
12
+ /** The host-page script that resizes the iframe (`embed.js`), resolved the same way. */
13
+ scriptSrc?: string;
14
+ /** The iframe's title; defaults to the chart's title. */
15
+ title?: string;
16
+ /** The iframe's height before the script resizes it; defaults to the chart's height where it is shown. */
17
+ height?: number;
18
+ }
@@ -0,0 +1,9 @@
1
+ function attr(value) {
2
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
3
+ }
4
+ /** The HTML snippet to paste into a CMS to embed a chart. */
5
+ export function embedCode(options) {
6
+ const { src, title, height = 480, scriptSrc } = options;
7
+ const iframe = `<iframe src="${attr(src)}" title="${attr(title)}" data-mozaic-embed scrolling="no" loading="lazy" height="${height}" style="width:100%;border:0;"></iframe>`;
8
+ return scriptSrc ? `${iframe}\n<script src="${attr(scriptSrc)}" async></script>` : iframe;
9
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The host-page script (`embed.js`). It resizes every mozaic iframe on the
3
+ * page to the height its chart reports. Serve it as a static file and
4
+ * include it once per page; including it twice is harmless.
5
+ */
6
+ export declare const hostScript = "(function () {\n\tif (window.__mozaicHost) return;\n\twindow.__mozaicHost = true;\n\twindow.addEventListener('message', function (event) {\n\t\tvar data = event.data;\n\t\tif (!data || data.type !== 'mozaic:resize' || typeof data.height !== 'number') return;\n\t\tvar frames = document.getElementsByTagName('iframe');\n\t\tfor (var i = 0; i < frames.length; i++) {\n\t\t\tif (frames[i].contentWindow === event.source) {\n\t\t\t\tframes[i].style.height = Math.ceil(data.height) + 'px';\n\t\t\t}\n\t\t}\n\t});\n})();\n";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The host-page script (`embed.js`). It resizes every mozaic iframe on the
3
+ * page to the height its chart reports. Serve it as a static file and
4
+ * include it once per page; including it twice is harmless.
5
+ */
6
+ export const hostScript = `(function () {
7
+ if (window.__mozaicHost) return;
8
+ window.__mozaicHost = true;
9
+ window.addEventListener('message', function (event) {
10
+ var data = event.data;
11
+ if (!data || data.type !== 'mozaic:resize' || typeof data.height !== 'number') return;
12
+ var frames = document.getElementsByTagName('iframe');
13
+ for (var i = 0; i < frames.length; i++) {
14
+ if (frames[i].contentWindow === event.source) {
15
+ frames[i].style.height = Math.ceil(data.height) + 'px';
16
+ }
17
+ }
18
+ });
19
+ })();
20
+ `;
@@ -0,0 +1,6 @@
1
+ export { default as Embed } from './Embed.svelte';
2
+ export { observeHeight, postHeight, type ResizeMessage } from './resize.js';
3
+ export { hostScript } from './host.js';
4
+ export { embedCode, type ChartEmbed } from './code.js';
5
+ export { useEmbedParams } from './params.svelte.js';
6
+ export type { EmbedEntry, EmbedManifest } from './manifest.js';
@@ -0,0 +1,5 @@
1
+ export { default as Embed } from './Embed.svelte';
2
+ export { observeHeight, postHeight } from './resize.js';
3
+ export { hostScript } from './host.js';
4
+ export { embedCode } from './code.js';
5
+ export { useEmbedParams } from './params.svelte.js';
@@ -0,0 +1,16 @@
1
+ /** One prerendered embed page: a chart in one style and language. */
2
+ export interface EmbedEntry {
3
+ slug: string;
4
+ style: string;
5
+ locale: string;
6
+ title: string;
7
+ /** Path relative to the site root, with a trailing slash, e.g. `embed/budget/ro/`. */
8
+ path: string;
9
+ /** Print widths to export, name → millimetres. */
10
+ print: Record<string, number>;
11
+ }
12
+ /** Written to `embed/manifest.json` at build time; read by `mozaic export`. */
13
+ export interface EmbedManifest {
14
+ project: string;
15
+ embeds: EmbedEntry[];
16
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { Medium } from '../styles/types.js';
2
+ /**
3
+ * Query parameters an embed page understands, read in the browser after
4
+ * hydration (prerendered pages cannot read the query string):
5
+ * `?medium=print&width=208` (width in px).
6
+ */
7
+ export declare function useEmbedParams(): {
8
+ readonly medium: Medium;
9
+ readonly width: number | undefined;
10
+ };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Query parameters an embed page understands, read in the browser after
3
+ * hydration (prerendered pages cannot read the query string):
4
+ * `?medium=print&width=208` (width in px).
5
+ */
6
+ export function useEmbedParams() {
7
+ let medium = $state('web');
8
+ let width = $state();
9
+ $effect(() => {
10
+ // Read once; nothing needs to react to this object.
11
+ // eslint-disable-next-line svelte/prefer-svelte-reactivity
12
+ const params = new URLSearchParams(window.location.search);
13
+ if (params.get('medium') === 'print')
14
+ medium = 'print';
15
+ const w = Number(params.get('width'));
16
+ if (w > 0)
17
+ width = w;
18
+ });
19
+ return {
20
+ get medium() {
21
+ return medium;
22
+ },
23
+ get width() {
24
+ return width;
25
+ }
26
+ };
27
+ }
@@ -0,0 +1,13 @@
1
+ /** Message an embedded chart posts to its parent page whenever its height changes. */
2
+ export interface ResizeMessage {
3
+ type: 'mozaic:resize';
4
+ /** Identifies the embed; defaults to its URL path. */
5
+ id: string;
6
+ height: number;
7
+ }
8
+ export declare function postHeight(height: number, id: string): void;
9
+ /**
10
+ * Post the element's height to the parent page now and whenever it changes.
11
+ * Returns a function that stops observing. Does nothing outside an iframe.
12
+ */
13
+ export declare function observeHeight(element: HTMLElement, id?: string): () => void;
@@ -0,0 +1,28 @@
1
+ export function postHeight(height, id) {
2
+ if (typeof window === 'undefined' || window.parent === window)
3
+ return;
4
+ const message = { type: 'mozaic:resize', id, height };
5
+ window.parent.postMessage(message, '*');
6
+ // Also speak Datawrapper's protocol, so hosts that already run its listener resize our embeds too.
7
+ window.parent.postMessage({ 'datawrapper-height': { [id]: height } }, '*');
8
+ }
9
+ /**
10
+ * Post the element's height to the parent page now and whenever it changes.
11
+ * Returns a function that stops observing. Does nothing outside an iframe.
12
+ */
13
+ export function observeHeight(element, id = location.pathname) {
14
+ if (window.parent === window)
15
+ return () => { };
16
+ let last = 0;
17
+ const send = () => {
18
+ const height = Math.ceil(element.getBoundingClientRect().height);
19
+ if (height !== last) {
20
+ last = height;
21
+ postHeight(height, id);
22
+ }
23
+ };
24
+ const observer = new ResizeObserver(send);
25
+ observer.observe(element);
26
+ send();
27
+ return () => observer.disconnect();
28
+ }
@@ -0,0 +1,13 @@
1
+ /** Space around a downloaded chart, in px, so its text does not touch the edge of the image. */
2
+ export declare const DOWNLOAD_PADDING = 20;
3
+ /** Download a rendered chart as SVG, with `padding` px around it. */
4
+ export declare function downloadSvg(figure: HTMLElement, filename?: string, padding?: number): void;
5
+ /**
6
+ * Render a chart to a PNG blob at `scale` × its on-screen size, with `padding` px around it. The page's web
7
+ * fonts are embedded in the SVG it is drawn from, so the text looks as it does on the page.
8
+ */
9
+ export declare function figureToPng(figure: HTMLElement, scale?: number, padding?: number): Promise<Blob>;
10
+ /** Download a rendered chart as PNG, with `padding` px around it. */
11
+ export declare function downloadPng(figure: HTMLElement, filename?: string, scale?: number, padding?: number): Promise<void>;
12
+ /** A file name (without extension) from a chart's title: lower case, no diacritics, words joined by hyphens. */
13
+ export declare function fileName(title: string, fallback?: string): string;
@@ -0,0 +1,52 @@
1
+ import { figureToSvg, isExcluded } from './figure-to-svg.js';
2
+ import { embeddedFontStyle, usedFonts } from './fonts.js';
3
+ /** Space around a downloaded chart, in px, so its text does not touch the edge of the image. */
4
+ export const DOWNLOAD_PADDING = 20;
5
+ function save(blob, filename) {
6
+ const url = URL.createObjectURL(blob);
7
+ const a = document.createElement('a');
8
+ a.href = url;
9
+ a.download = filename;
10
+ a.click();
11
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
12
+ }
13
+ /** Download a rendered chart as SVG, with `padding` px around it. */
14
+ export function downloadSvg(figure, filename = 'chart.svg', padding = DOWNLOAD_PADDING) {
15
+ save(new Blob([figureToSvg(figure, { padding })], { type: 'image/svg+xml' }), filename);
16
+ }
17
+ /**
18
+ * Render a chart to a PNG blob at `scale` × its on-screen size, with `padding` px around it. The page's web
19
+ * fonts are embedded in the SVG it is drawn from, so the text looks as it does on the page.
20
+ */
21
+ export async function figureToPng(figure, scale = 2, padding = 0) {
22
+ const fonts = await embeddedFontStyle(usedFonts(figure, isExcluded)).catch(() => '');
23
+ const svg = figureToSvg(figure, { padding }).replace(/^(<svg[^>]*>)/, `$1${fonts ? `<defs>${fonts}</defs>` : ''}`);
24
+ const image = new Image();
25
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
26
+ await image.decode();
27
+ const canvas = document.createElement('canvas');
28
+ canvas.width = Math.ceil(image.width * scale);
29
+ canvas.height = Math.ceil(image.height * scale);
30
+ const ctx = canvas.getContext('2d');
31
+ if (!ctx)
32
+ throw new Error('Canvas 2D is not available.');
33
+ ctx.scale(scale, scale);
34
+ ctx.drawImage(image, 0, 0);
35
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error('PNG encoding failed.'))), 'image/png'));
36
+ }
37
+ /** Download a rendered chart as PNG, with `padding` px around it. */
38
+ export async function downloadPng(figure, filename = 'chart.png', scale = 2, padding = DOWNLOAD_PADDING) {
39
+ save(await figureToPng(figure, scale, padding), filename);
40
+ }
41
+ /** A file name (without extension) from a chart's title: lower case, no diacritics, words joined by hyphens. */
42
+ export function fileName(title, fallback = 'chart') {
43
+ const name = title
44
+ .normalize('NFD')
45
+ .replace(/[\u0300-\u036f]/g, '')
46
+ .toLowerCase()
47
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
48
+ .replace(/^-+|-+$/g, '')
49
+ .slice(0, 80)
50
+ .replace(/-+$/, '');
51
+ return name || fallback;
52
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Convert a rendered chart (`<figure class="mz-chart">`, HTML header and
3
+ * footer included) into one standalone SVG. Runs in the browser: it reads
4
+ * layout and computed styles from the live DOM.
5
+ *
6
+ * - SVG layers are copied with computed styles inlined (no CSS needed).
7
+ * - HTML text becomes SVG `<text>`, one element per rendered line, so it
8
+ * stays editable in Illustrator or Inkscape.
9
+ * - Elements with a background colour (legend swatches) become rectangles.
10
+ * - Interactive-only parts (tooltips, buttons, data tables) are left out, and the image ends above the
11
+ * controls under the chart.
12
+ */
13
+ /** Whether an element is left out of exports: interactive-only parts and the controls under the chart. */
14
+ export declare function isExcluded(el: Element): boolean;
15
+ export interface SvgOptions {
16
+ /** Fill the image with the chart's background colour (default true). */
17
+ background?: boolean;
18
+ /** Space around the chart, in px (default 0). */
19
+ padding?: number;
20
+ }
21
+ export declare function figureToSvg(figure: HTMLElement, options?: SvgOptions): string;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Convert a rendered chart (`<figure class="mz-chart">`, HTML header and
3
+ * footer included) into one standalone SVG. Runs in the browser: it reads
4
+ * layout and computed styles from the live DOM.
5
+ *
6
+ * - SVG layers are copied with computed styles inlined (no CSS needed).
7
+ * - HTML text becomes SVG `<text>`, one element per rendered line, so it
8
+ * stays editable in Illustrator or Inkscape.
9
+ * - Elements with a background colour (legend swatches) become rectangles.
10
+ * - Interactive-only parts (tooltips, buttons, data tables) are left out, and the image ends above the
11
+ * controls under the chart.
12
+ */
13
+ const SVG_NS = 'http://www.w3.org/2000/svg';
14
+ const SVG_STYLE_PROPS = [
15
+ 'fill',
16
+ 'fill-opacity',
17
+ 'stroke',
18
+ 'stroke-width',
19
+ 'stroke-opacity',
20
+ 'stroke-dasharray',
21
+ 'stroke-linejoin',
22
+ 'stroke-linecap',
23
+ 'paint-order',
24
+ 'opacity',
25
+ 'font-family',
26
+ 'font-size',
27
+ 'font-weight',
28
+ 'font-style',
29
+ 'letter-spacing',
30
+ 'text-anchor',
31
+ 'dominant-baseline',
32
+ 'shape-rendering',
33
+ 'visibility'
34
+ ];
35
+ const EXCLUDE = [
36
+ '.mz-html',
37
+ '.mz-visually-hidden',
38
+ '.mz-button-group',
39
+ '.mz-data-table',
40
+ '.mz-data-download',
41
+ '.mz-chart-tools',
42
+ '.mz-table-search',
43
+ '.mz-table-more',
44
+ '.mz-tooltip',
45
+ '[data-mz-export="exclude"]',
46
+ 'script',
47
+ 'style',
48
+ 'button',
49
+ 'input',
50
+ 'select',
51
+ 'textarea'
52
+ ].join(',');
53
+ function escapeXml(text) {
54
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
55
+ }
56
+ function transparent(color) {
57
+ return !color || color === 'transparent' || /rgba\([^)]*,\s*0\)$/.test(color);
58
+ }
59
+ /** Whether an element is left out of exports: interactive-only parts and the controls under the chart. */
60
+ export function isExcluded(el) {
61
+ return el.closest(EXCLUDE) !== null;
62
+ }
63
+ function hidden(el) {
64
+ if (isExcluded(el))
65
+ return true;
66
+ const cs = getComputedStyle(el);
67
+ return cs.display === 'none' || cs.visibility === 'hidden' || Number(cs.opacity) === 0;
68
+ }
69
+ function inlineSvg(svg, x, y, width, height) {
70
+ const clone = svg.cloneNode(true);
71
+ const source = [svg, ...svg.querySelectorAll('*')];
72
+ const target = [clone, ...clone.querySelectorAll('*')];
73
+ source.forEach((el, i) => {
74
+ const out = target[i];
75
+ const cs = getComputedStyle(el);
76
+ const style = SVG_STYLE_PROPS.map((p) => `${p}:${cs.getPropertyValue(p)}`)
77
+ .filter((s) => !s.endsWith(':'))
78
+ .join(';');
79
+ out.setAttribute('style', style);
80
+ out.removeAttribute('class');
81
+ out.removeAttribute('role');
82
+ out.removeAttribute('aria-labelledby');
83
+ out.removeAttribute('aria-describedby');
84
+ });
85
+ // Interactive-only SVG parts (matched on the source, which still has its classes).
86
+ source.forEach((el, i) => {
87
+ if (el.matches?.('.mz-pointer-area, .mz-voronoi'))
88
+ target[i].remove();
89
+ });
90
+ clone.setAttribute('x', String(x));
91
+ clone.setAttribute('y', String(y));
92
+ clone.setAttribute('width', String(width));
93
+ clone.setAttribute('height', String(height));
94
+ clone.removeAttribute('style');
95
+ clone.setAttribute('overflow', 'visible');
96
+ return new XMLSerializer().serializeToString(clone);
97
+ }
98
+ function textLines(node, origin) {
99
+ const parent = node.parentElement;
100
+ if (!parent || !node.data.trim())
101
+ return [];
102
+ const cs = getComputedStyle(parent);
103
+ const fontSize = parseFloat(cs.fontSize);
104
+ const transform = cs.textTransform;
105
+ const range = document.createRange();
106
+ const lines = new Map();
107
+ const re = /\S+/g;
108
+ let match;
109
+ while ((match = re.exec(node.data))) {
110
+ range.setStart(node, match.index);
111
+ range.setEnd(node, match.index + match[0].length);
112
+ const rect = range.getClientRects()[0];
113
+ if (!rect || rect.width === 0)
114
+ continue;
115
+ const key = Math.round(rect.top);
116
+ const line = lines.get(key) ?? { top: rect.top, bottom: rect.bottom, words: [] };
117
+ let text = match[0];
118
+ if (transform === 'uppercase')
119
+ text = text.toUpperCase();
120
+ else if (transform === 'lowercase')
121
+ text = text.toLowerCase();
122
+ line.words.push({ x: rect.left - origin.left, text });
123
+ lines.set(key, line);
124
+ }
125
+ const attrs = [
126
+ `font-family="${escapeXml(cs.fontFamily)}"`,
127
+ `font-size="${fontSize}"`,
128
+ `font-weight="${cs.fontWeight}"`,
129
+ cs.fontStyle !== 'normal' ? `font-style="${cs.fontStyle}"` : '',
130
+ cs.letterSpacing !== 'normal' ? `letter-spacing="${cs.letterSpacing}"` : '',
131
+ `fill="${cs.color}"`
132
+ ]
133
+ .filter(Boolean)
134
+ .join(' ');
135
+ return [...lines.values()].map((line) => {
136
+ // Baseline from the line box: centred glyphs, ~0.2em descent.
137
+ const baseline = line.bottom - (line.bottom - line.top - fontSize) / 2 - fontSize * 0.2 - origin.top;
138
+ const spans = line.words
139
+ .map((w) => `<tspan x="${w.x.toFixed(2)}" y="${baseline.toFixed(2)}">${escapeXml(w.text)}</tspan>`)
140
+ .join('');
141
+ return `<text ${attrs} xml:space="preserve">${spans}</text>`;
142
+ });
143
+ }
144
+ export function figureToSvg(figure, options = {}) {
145
+ const pad = options.padding ?? 0;
146
+ const origin = figure.getBoundingClientRect();
147
+ const width = Math.ceil(origin.width);
148
+ // End at the last part that is exported, not at the controls under it (embed, download, data table).
149
+ const bottom = Math.max(...[...figure.children].filter((el) => !hidden(el)).map((el) => el.getBoundingClientRect().bottom));
150
+ const height = Math.ceil(Number.isFinite(bottom) ? bottom - origin.top : origin.height);
151
+ const parts = [];
152
+ const bg = getComputedStyle(figure).backgroundColor;
153
+ const fill = options.background !== false && !transparent(bg)
154
+ ? `<rect width="${width + 2 * pad}" height="${height + 2 * pad}" fill="${bg}"/>`
155
+ : '';
156
+ // Boxes with a background colour (legend swatches, keys, table bars).
157
+ for (const el of figure.querySelectorAll('*')) {
158
+ if (el.closest('svg') || hidden(el))
159
+ continue;
160
+ const cs = getComputedStyle(el);
161
+ if (transparent(cs.backgroundColor))
162
+ continue;
163
+ const r = el.getBoundingClientRect();
164
+ if (r.width === 0 || r.height === 0)
165
+ continue;
166
+ const radius = parseFloat(cs.borderTopLeftRadius) || 0;
167
+ parts.push(`<rect x="${(r.left - origin.left).toFixed(2)}" y="${(r.top - origin.top).toFixed(2)}" width="${r.width.toFixed(2)}" height="${r.height.toFixed(2)}" rx="${Math.min(radius, r.width / 2, r.height / 2)}" fill="${cs.backgroundColor}"${cs.opacity !== '1' ? ` fill-opacity="${cs.opacity}"` : ''}/>`);
168
+ }
169
+ // SVG layers and SVG guides (outermost <svg> elements only).
170
+ for (const svg of figure.querySelectorAll('svg')) {
171
+ if (svg.parentElement?.closest('svg') || hidden(svg))
172
+ continue;
173
+ const r = svg.getBoundingClientRect();
174
+ parts.push(inlineSvg(svg, r.left - origin.left, r.top - origin.top, r.width, r.height));
175
+ }
176
+ // HTML text.
177
+ const walker = document.createTreeWalker(figure, NodeFilter.SHOW_TEXT);
178
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
179
+ const parent = node.parentElement;
180
+ if (!parent || parent.closest('svg') || hidden(parent))
181
+ continue;
182
+ parts.push(...textLines(node, origin));
183
+ }
184
+ const [w, h] = [width + 2 * pad, height + 2 * pad];
185
+ const body = pad ? `<g transform="translate(${pad} ${pad})">${parts.join('')}</g>` : parts.join('');
186
+ return `<svg xmlns="${SVG_NS}" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}">${fill}${body}</svg>`;
187
+ }