@samizdata/mozaic 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/recipes/FootprintMap.svelte +368 -0
- package/dist/recipes/FootprintMap.svelte.d.ts +116 -0
- package/dist/recipes/index.d.ts +3 -1
- package/dist/recipes/index.js +3 -1
- package/dist/transforms/contour.d.ts +42 -0
- package/dist/transforms/contour.js +112 -0
- package/dist/transforms/index.d.ts +1 -0
- package/dist/transforms/index.js +1 -0
- package/package.json +3 -1
- package/src/lib/recipes/FootprintMap.svelte +368 -0
- package/src/lib/recipes/index.ts +4 -1
package/README.md
CHANGED
|
@@ -40,7 +40,7 @@ pnpm add @samizdata/mozaic d3-scale d3-array d3-shape
|
|
|
40
40
|
| `@samizdata/mozaic/locale` | `createLocale` (`en`, `ro`, `ru`) |
|
|
41
41
|
| `@samizdata/mozaic/embed` | `Embed`, `useEmbedParams`, `embedCode`, `hostScript`, `observeHeight` |
|
|
42
42
|
| `@samizdata/mozaic/export` | `figureToSvg`, `downloadSvg`, `downloadPng`, `figureToPng` |
|
|
43
|
-
| `@samizdata/mozaic/recipes` | `BarChart`, `ColumnChart`, `LineChart`, `ScatterChart`, `ArrowChart`, `BarDotChart`, `StackedBarChart`, `MosaicChart`, `PercentileChart`, `StripChart`
|
|
43
|
+
| `@samizdata/mozaic/recipes` | `BarChart`, `ColumnChart`, `LineChart`, `ScatterChart`, `ArrowChart`, `BarDotChart`, `StackedBarChart`, `MosaicChart`, `PercentileChart`, `StripChart`, `FootprintMap` |
|
|
44
44
|
|
|
45
45
|
## CLI
|
|
46
46
|
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
Recipe: the footprints of several events on one map (the area each earthquake shook hard, each
|
|
4
|
+
flood covered or each fire burnt), stacked from the oldest, faintest, to the newest, strongest,
|
|
5
|
+
in one colour. Each footprint is outlined and labelled where you place its label; at narrow
|
|
6
|
+
widths, or for footprints without a label position, a key lists them instead. Pointing at the
|
|
7
|
+
map lists the footprints that cover that spot. Build footprints from point measurements with
|
|
8
|
+
`contourPoints` from `@samizdata/mozaic/transforms`. Use it as is, or run
|
|
9
|
+
`mozaic eject FootprintMap` to copy this file into your project and change anything.
|
|
10
|
+
-->
|
|
11
|
+
<script lang="ts" module>
|
|
12
|
+
/** A labelled point on the map: a town, an epicentre, a country name. */
|
|
13
|
+
export interface FootprintPlace {
|
|
14
|
+
name: string;
|
|
15
|
+
lon: number;
|
|
16
|
+
lat: number;
|
|
17
|
+
/** Draw a dot at the point (towns); without it the name is centred on the point (regions). */
|
|
18
|
+
dot?: boolean;
|
|
19
|
+
/** Grey text, for context such as country names. */
|
|
20
|
+
muted?: boolean;
|
|
21
|
+
/** Text anchor for names beside a dot; defaults to `start` (to the right). */
|
|
22
|
+
anchor?: 'start' | 'middle' | 'end';
|
|
23
|
+
/** Hide at narrow widths. */
|
|
24
|
+
hideSmall?: boolean;
|
|
25
|
+
}
|
|
26
|
+
</script>
|
|
27
|
+
|
|
28
|
+
<script lang="ts" generics="T">
|
|
29
|
+
import type { Snippet } from 'svelte';
|
|
30
|
+
import { geoContains, type GeoPermissibleObjects, type GeoProjection } from 'd3-geo';
|
|
31
|
+
import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
|
|
32
|
+
import type { ChartEmbed } from '../embed/index.js';
|
|
33
|
+
import { Plot, Svg, Html, type PlotContext } from '../core/index.js';
|
|
34
|
+
import { Text } from '../marks/index.js';
|
|
35
|
+
import { Legend } from '../guides/index.js';
|
|
36
|
+
import { PointerArea, Tooltip } from '../interactive/index.js';
|
|
37
|
+
import type { LocaleCode } from '../locale/index.js';
|
|
38
|
+
import { base, readableColor, type Breakpoint, type Medium, type Theme } from '../styles/index.js';
|
|
39
|
+
|
|
40
|
+
interface Props {
|
|
41
|
+
/** One row per footprint. */
|
|
42
|
+
data: T[];
|
|
43
|
+
/** The footprint's area, e.g. a GeoJSON feature. */
|
|
44
|
+
geometry: (d: T) => GeoPermissibleObjects;
|
|
45
|
+
/** Name of the footprint, e.g. the year. */
|
|
46
|
+
label: (d: T) => string;
|
|
47
|
+
/** What decides the fading: lowest is drawn first and faintest. Defaults to data order (oldest first). */
|
|
48
|
+
order?: (d: T) => number | Date;
|
|
49
|
+
/**
|
|
50
|
+
* Where to write the footprint's name, as [longitude, latitude]: inside it, near its edge, or
|
|
51
|
+
* outside it, in empty space, where a leader line joins it to the nearest point of the edge.
|
|
52
|
+
* Footprints without one go in the key.
|
|
53
|
+
*/
|
|
54
|
+
labelAt?: (d: T) => [number, number] | null | undefined;
|
|
55
|
+
/** Text anchor of each label; defaults to `middle`. */
|
|
56
|
+
labelAnchor?: (d: T) => 'start' | 'middle' | 'end';
|
|
57
|
+
/**
|
|
58
|
+
* Keep the labels on the map at narrow widths (and in narrow print sizes) as well as listing
|
|
59
|
+
* the footprints in the key. Without it, narrow maps rely on the key and the tooltip, which
|
|
60
|
+
* print doesn't have. Defaults to true.
|
|
61
|
+
*/
|
|
62
|
+
labelSmall?: boolean;
|
|
63
|
+
/** Land for context, drawn in grey under the footprints (countries, regions). */
|
|
64
|
+
basemap?: GeoPermissibleObjects[];
|
|
65
|
+
/** Areas the chart is about, outlined on top of the footprints (e.g. the country). */
|
|
66
|
+
focus?: GeoPermissibleObjects[];
|
|
67
|
+
/** Towns, epicentres and region names. */
|
|
68
|
+
places?: FootprintPlace[];
|
|
69
|
+
/** A d3-geo projection; it is fitted to `fit`. */
|
|
70
|
+
projection: GeoProjection;
|
|
71
|
+
/** The area to show; footprints beyond it are cut off. */
|
|
72
|
+
fit: GeoPermissibleObjects;
|
|
73
|
+
/** Width ÷ height of the map. Defaults to 1.1. */
|
|
74
|
+
aspectRatio?: number;
|
|
75
|
+
/** Map height in px, or a function of the width and breakpoint; overrides `aspectRatio`. */
|
|
76
|
+
height?: number | ((size: { width: number; breakpoint: Breakpoint }) => number);
|
|
77
|
+
/** Colour of every footprint; defaults to the first categorical colour. */
|
|
78
|
+
color?: string;
|
|
79
|
+
/** Fill opacity of the oldest and the newest footprint. Defaults to [0.12, 0.4]. */
|
|
80
|
+
opacity?: [number, number];
|
|
81
|
+
/** Tooltip heading over the footprints under the pointer, e.g. "Shaken at intensity VII or more in". */
|
|
82
|
+
tooltipTitle?: string;
|
|
83
|
+
/** Tooltip text where no footprint covers the pointer; with none, no tooltip shows there. */
|
|
84
|
+
tooltipNone?: string;
|
|
85
|
+
style?: Theme;
|
|
86
|
+
locale?: LocaleCode;
|
|
87
|
+
medium?: Medium;
|
|
88
|
+
width?: number;
|
|
89
|
+
title?: string;
|
|
90
|
+
subtitle?: string;
|
|
91
|
+
notes?: string;
|
|
92
|
+
/** Plain text, or sources with optional links (see `<Source>`). */
|
|
93
|
+
source?: string | SourceItem[];
|
|
94
|
+
alt?: string;
|
|
95
|
+
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
96
|
+
embed?: ChartEmbed;
|
|
97
|
+
/** Extra SVG drawn on top (annotations); receives the plot context. */
|
|
98
|
+
annotations?: Snippet<[PlotContext]>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let {
|
|
102
|
+
data,
|
|
103
|
+
geometry,
|
|
104
|
+
label,
|
|
105
|
+
order,
|
|
106
|
+
labelAt,
|
|
107
|
+
labelAnchor,
|
|
108
|
+
labelSmall = true,
|
|
109
|
+
basemap = [],
|
|
110
|
+
focus = [],
|
|
111
|
+
places = [],
|
|
112
|
+
projection,
|
|
113
|
+
fit,
|
|
114
|
+
aspectRatio = 1.1,
|
|
115
|
+
height,
|
|
116
|
+
color,
|
|
117
|
+
opacity = [0.12, 0.4],
|
|
118
|
+
tooltipTitle,
|
|
119
|
+
tooltipNone,
|
|
120
|
+
style = base,
|
|
121
|
+
locale,
|
|
122
|
+
medium,
|
|
123
|
+
width,
|
|
124
|
+
title,
|
|
125
|
+
subtitle,
|
|
126
|
+
notes,
|
|
127
|
+
source,
|
|
128
|
+
alt,
|
|
129
|
+
embed,
|
|
130
|
+
annotations
|
|
131
|
+
}: Props = $props();
|
|
132
|
+
|
|
133
|
+
const uid = $props.id();
|
|
134
|
+
const theme = $derived(style);
|
|
135
|
+
const bg = $derived(theme.tokens['--mz-color-bg'] ?? '#ffffff');
|
|
136
|
+
const hue = $derived(color ?? theme.palettes.categorical[0]);
|
|
137
|
+
const ink = $derived(readableColor(hue, bg));
|
|
138
|
+
|
|
139
|
+
/** Oldest first, so the newest is drawn on top. */
|
|
140
|
+
const layers = $derived.by(() => {
|
|
141
|
+
const rows = order ? data.toSorted((a, b) => +order(a) - +order(b)) : [...data];
|
|
142
|
+
const n = rows.length;
|
|
143
|
+
return rows.map((d, i) => {
|
|
144
|
+
const t = n > 1 ? i / (n - 1) : 1;
|
|
145
|
+
const fill = opacity[0] + t * (opacity[1] - opacity[0]);
|
|
146
|
+
return { d, geo: geometry(d), name: label(d), fill, stroke: 0.5 + 0.5 * t, at: labelAt?.(d) ?? null };
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
/** Every vertex of a GeoJSON object. */
|
|
151
|
+
function vertices(g: unknown, out: [number, number][] = []): [number, number][] {
|
|
152
|
+
if (!g || typeof g !== 'object') return out;
|
|
153
|
+
const o = g as {
|
|
154
|
+
type?: string;
|
|
155
|
+
coordinates?: unknown;
|
|
156
|
+
geometry?: unknown;
|
|
157
|
+
features?: unknown[];
|
|
158
|
+
geometries?: unknown[];
|
|
159
|
+
};
|
|
160
|
+
if (o.type === 'Feature') return vertices(o.geometry, out);
|
|
161
|
+
if (o.type === 'FeatureCollection') o.features?.forEach((f) => vertices(f, out));
|
|
162
|
+
else if (o.type === 'GeometryCollection') o.geometries?.forEach((f) => vertices(f, out));
|
|
163
|
+
else if (o.coordinates) {
|
|
164
|
+
const walk = (c: unknown) => {
|
|
165
|
+
if (Array.isArray(c) && typeof c[0] === 'number') out.push([c[0], c[1] as number]);
|
|
166
|
+
else if (Array.isArray(c)) c.forEach(walk);
|
|
167
|
+
};
|
|
168
|
+
walk(o.coordinates);
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A label placed outside its footprint gets a leader line to the nearest visible point of the
|
|
175
|
+
* footprint's edge, so labels can sit in empty space when footprints overlap.
|
|
176
|
+
*/
|
|
177
|
+
function leader(l: (typeof layers)[number], plot: PlotContext): [number, number, number, number] | null {
|
|
178
|
+
if (!l.at || !plot.projection || geoContains(l.geo, l.at)) return null;
|
|
179
|
+
const from = plot.projection(l.at);
|
|
180
|
+
if (!from) return null;
|
|
181
|
+
let best: [number, number] | null = null;
|
|
182
|
+
let dist = Infinity;
|
|
183
|
+
for (const v of vertices(l.geo)) {
|
|
184
|
+
const p = plot.projection(v);
|
|
185
|
+
if (!p || p[0] < 0 || p[1] < 0 || p[0] > plot.width || p[1] > plot.height) continue;
|
|
186
|
+
const dd = (p[0] - from[0]) ** 2 + (p[1] - from[1]) ** 2;
|
|
187
|
+
if (dd < dist) {
|
|
188
|
+
dist = dd;
|
|
189
|
+
best = [p[0], p[1]];
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return best ? [from[0], from[1], best[0], best[1]] : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The colour a footprint's fill shows over the background, for the key and tooltip swatches. */
|
|
196
|
+
function over(alpha: number): string {
|
|
197
|
+
const rgb = (h: string) => {
|
|
198
|
+
const s = h.replace('#', '');
|
|
199
|
+
const f = s.length === 3 ? s.replace(/./g, '$&$&') : s.slice(0, 6);
|
|
200
|
+
return [0, 2, 4].map((i) => parseInt(f.slice(i, i + 2), 16));
|
|
201
|
+
};
|
|
202
|
+
const [a, b] = [rgb(hue), rgb(bg)];
|
|
203
|
+
// Swatches are small, so show them a little stronger than the fill.
|
|
204
|
+
const k = Math.min(1, alpha * 1.6);
|
|
205
|
+
return `#${a
|
|
206
|
+
.map((v, i) =>
|
|
207
|
+
Math.round(k * v + (1 - k) * b[i])
|
|
208
|
+
.toString(16)
|
|
209
|
+
.padStart(2, '0')
|
|
210
|
+
)
|
|
211
|
+
.join('')}`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const newestFirst = $derived(layers.toReversed());
|
|
215
|
+
const unlabelled = $derived(layers.some((l) => !l.at));
|
|
216
|
+
|
|
217
|
+
let hover = $state<{ x: number; y: number; covered: typeof layers } | null>(null);
|
|
218
|
+
function onmove(px: number, py: number, plot: PlotContext) {
|
|
219
|
+
const lonlat = plot.projection?.invert?.([px, py]);
|
|
220
|
+
if (!lonlat) return (hover = null);
|
|
221
|
+
hover = { x: px, y: py, covered: newestFirst.filter((l) => geoContains(l.geo, lonlat)) };
|
|
222
|
+
}
|
|
223
|
+
const isHovered = (l: (typeof layers)[number]) => !!hover?.covered.includes(l);
|
|
224
|
+
</script>
|
|
225
|
+
|
|
226
|
+
<Chart {style} {locale} {medium} {width} {alt} {embed}>
|
|
227
|
+
<Header>
|
|
228
|
+
{#if title}<Title>{title}</Title>{/if}
|
|
229
|
+
{#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
|
|
230
|
+
<!-- The key shows when a footprint has no label on the map, and at narrow widths, where it explains the fading. -->
|
|
231
|
+
<div class="mz-footprint-key" class:mz-footprint-key-always={unlabelled}>
|
|
232
|
+
<Legend items={newestFirst.map((l) => ({ label: l.name, color: over(l.fill) }))} />
|
|
233
|
+
</div>
|
|
234
|
+
</Header>
|
|
235
|
+
|
|
236
|
+
<Plot {projection} {fit} {aspectRatio} {height} padding={{ top: 0, right: 0, bottom: 0, left: 0 }}>
|
|
237
|
+
{#snippet children(plot)}
|
|
238
|
+
<Svg>
|
|
239
|
+
{#snippet defs()}
|
|
240
|
+
<clipPath id="mz-footprint-clip-{uid}">
|
|
241
|
+
<rect x={0} y={0} width={plot.width} height={plot.height} />
|
|
242
|
+
</clipPath>
|
|
243
|
+
{/snippet}
|
|
244
|
+
<g class="mz-footprint-map" clip-path="url(#mz-footprint-clip-{uid})">
|
|
245
|
+
{#each basemap as g, i (i)}
|
|
246
|
+
<path
|
|
247
|
+
class="mz-footprint-base"
|
|
248
|
+
d={plot.path?.(g) ?? ''}
|
|
249
|
+
fill="var(--mz-color-grid)"
|
|
250
|
+
fill-opacity="0.45"
|
|
251
|
+
stroke="var(--mz-color-axis)"
|
|
252
|
+
stroke-width="0.5"
|
|
253
|
+
stroke-linejoin="round"
|
|
254
|
+
/>
|
|
255
|
+
{/each}
|
|
256
|
+
{#each layers as l, i (i)}
|
|
257
|
+
<path
|
|
258
|
+
class="mz-footprint"
|
|
259
|
+
d={plot.path?.(l.geo) ?? ''}
|
|
260
|
+
fill={hue}
|
|
261
|
+
fill-opacity={l.fill}
|
|
262
|
+
stroke={hue}
|
|
263
|
+
stroke-opacity={isHovered(l) ? 1 : l.stroke}
|
|
264
|
+
stroke-width={isHovered(l) ? 2.5 : 1.25}
|
|
265
|
+
stroke-linejoin="round"
|
|
266
|
+
/>
|
|
267
|
+
{/each}
|
|
268
|
+
{#each focus as g, i (i)}
|
|
269
|
+
<path
|
|
270
|
+
class="mz-footprint-focus"
|
|
271
|
+
d={plot.path?.(g) ?? ''}
|
|
272
|
+
fill="none"
|
|
273
|
+
stroke="var(--mz-color-text)"
|
|
274
|
+
stroke-width="1.25"
|
|
275
|
+
stroke-linejoin="round"
|
|
276
|
+
/>
|
|
277
|
+
{/each}
|
|
278
|
+
</g>
|
|
279
|
+
{#each places.filter((p) => p.dot && !(p.hideSmall && plot.breakpoint === 's')) as p, i (i)}
|
|
280
|
+
{@const xy = plot.projection?.([p.lon, p.lat])}
|
|
281
|
+
{#if xy}
|
|
282
|
+
<circle
|
|
283
|
+
class="mz-footprint-dot"
|
|
284
|
+
cx={xy[0]}
|
|
285
|
+
cy={xy[1]}
|
|
286
|
+
r={2.5}
|
|
287
|
+
fill={p.muted ? 'var(--mz-color-muted)' : 'var(--mz-color-text)'}
|
|
288
|
+
stroke="var(--mz-color-bg)"
|
|
289
|
+
stroke-width="1"
|
|
290
|
+
/>
|
|
291
|
+
{/if}
|
|
292
|
+
{/each}
|
|
293
|
+
{#each places.filter((p) => !(p.hideSmall && plot.breakpoint === 's')) as p, i (i)}
|
|
294
|
+
{@const anchor = p.dot ? (p.anchor ?? 'start') : 'middle'}
|
|
295
|
+
<Text
|
|
296
|
+
data={[p]}
|
|
297
|
+
x={(d) => d.lon}
|
|
298
|
+
y={(d) => d.lat}
|
|
299
|
+
text={(d) => d.name}
|
|
300
|
+
dx={p.dot ? (anchor === 'start' ? 5 : anchor === 'end' ? -5 : 0) : 0}
|
|
301
|
+
dy={p.dot && anchor === 'middle' ? -9 : 0}
|
|
302
|
+
{anchor}
|
|
303
|
+
fill={p.muted ? 'var(--mz-color-muted)' : 'var(--mz-color-text)'}
|
|
304
|
+
fontWeight={p.dot ? 400 : 600}
|
|
305
|
+
halo
|
|
306
|
+
/>
|
|
307
|
+
{/each}
|
|
308
|
+
{#if plot.breakpoint !== 's' || labelSmall}
|
|
309
|
+
{#each layers.filter((l) => l.at) as l, i (i)}
|
|
310
|
+
{@const line = leader(l, plot)}
|
|
311
|
+
{#if line}
|
|
312
|
+
<g class="mz-footprint-leader">
|
|
313
|
+
<line x1={line[0]} y1={line[1]} x2={line[2]} y2={line[3]} stroke={ink} stroke-width="1" />
|
|
314
|
+
<circle cx={line[2]} cy={line[3]} r="2" fill={ink} />
|
|
315
|
+
</g>
|
|
316
|
+
{/if}
|
|
317
|
+
{/each}
|
|
318
|
+
{#each layers.filter((l) => l.at) as l, i (i)}
|
|
319
|
+
<Text
|
|
320
|
+
data={[l]}
|
|
321
|
+
x={(d) => d.at![0]}
|
|
322
|
+
y={(d) => d.at![1]}
|
|
323
|
+
text={(d) => d.name}
|
|
324
|
+
anchor={labelAnchor?.(l.d) ?? 'middle'}
|
|
325
|
+
fill={ink}
|
|
326
|
+
fontWeight={700}
|
|
327
|
+
halo
|
|
328
|
+
/>
|
|
329
|
+
{/each}
|
|
330
|
+
{/if}
|
|
331
|
+
{@render annotations?.(plot)}
|
|
332
|
+
{#if tooltipTitle}
|
|
333
|
+
<PointerArea onmove={({ x, y }) => onmove(x, y, plot)} onleave={() => (hover = null)} />
|
|
334
|
+
{/if}
|
|
335
|
+
</Svg>
|
|
336
|
+
<Html>
|
|
337
|
+
{#if hover && tooltipTitle && (hover.covered.length || tooltipNone)}
|
|
338
|
+
<Tooltip
|
|
339
|
+
x={hover.x}
|
|
340
|
+
y={hover.y}
|
|
341
|
+
title={tooltipTitle}
|
|
342
|
+
items={hover.covered.length
|
|
343
|
+
? hover.covered.map((l) => ({ label: l.name, value: '', color: over(l.fill), shape: 'square' as const }))
|
|
344
|
+
: [{ label: tooltipNone ?? '', value: '', color: 'transparent', shape: 'square' as const }]}
|
|
345
|
+
/>
|
|
346
|
+
{/if}
|
|
347
|
+
</Html>
|
|
348
|
+
{/snippet}
|
|
349
|
+
</Plot>
|
|
350
|
+
|
|
351
|
+
{#if notes || source}
|
|
352
|
+
<Footer>
|
|
353
|
+
{#if notes}<Notes>{notes}</Notes>{/if}
|
|
354
|
+
{#if source}<Source sources={source} />{/if}
|
|
355
|
+
</Footer>
|
|
356
|
+
{/if}
|
|
357
|
+
</Chart>
|
|
358
|
+
|
|
359
|
+
<style>
|
|
360
|
+
.mz-footprint-key {
|
|
361
|
+
display: none;
|
|
362
|
+
margin-top: 0.25rem;
|
|
363
|
+
}
|
|
364
|
+
.mz-footprint-key-always,
|
|
365
|
+
:global([data-mz-breakpoint='s']) .mz-footprint-key {
|
|
366
|
+
display: block;
|
|
367
|
+
}
|
|
368
|
+
</style>
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/** A labelled point on the map: a town, an epicentre, a country name. */
|
|
2
|
+
export interface FootprintPlace {
|
|
3
|
+
name: string;
|
|
4
|
+
lon: number;
|
|
5
|
+
lat: number;
|
|
6
|
+
/** Draw a dot at the point (towns); without it the name is centred on the point (regions). */
|
|
7
|
+
dot?: boolean;
|
|
8
|
+
/** Grey text, for context such as country names. */
|
|
9
|
+
muted?: boolean;
|
|
10
|
+
/** Text anchor for names beside a dot; defaults to `start` (to the right). */
|
|
11
|
+
anchor?: 'start' | 'middle' | 'end';
|
|
12
|
+
/** Hide at narrow widths. */
|
|
13
|
+
hideSmall?: boolean;
|
|
14
|
+
}
|
|
15
|
+
import type { Snippet } from 'svelte';
|
|
16
|
+
import { type GeoPermissibleObjects, type GeoProjection } from 'd3-geo';
|
|
17
|
+
import { type SourceItem } from '../frame/index.js';
|
|
18
|
+
import type { ChartEmbed } from '../embed/index.js';
|
|
19
|
+
import { type PlotContext } from '../core/index.js';
|
|
20
|
+
import type { LocaleCode } from '../locale/index.js';
|
|
21
|
+
import { type Breakpoint, type Medium, type Theme } from '../styles/index.js';
|
|
22
|
+
declare function $$render<T>(): {
|
|
23
|
+
props: {
|
|
24
|
+
/** One row per footprint. */
|
|
25
|
+
data: T[];
|
|
26
|
+
/** The footprint's area, e.g. a GeoJSON feature. */
|
|
27
|
+
geometry: (d: T) => GeoPermissibleObjects;
|
|
28
|
+
/** Name of the footprint, e.g. the year. */
|
|
29
|
+
label: (d: T) => string;
|
|
30
|
+
/** What decides the fading: lowest is drawn first and faintest. Defaults to data order (oldest first). */
|
|
31
|
+
order?: (d: T) => number | Date;
|
|
32
|
+
/**
|
|
33
|
+
* Where to write the footprint's name, as [longitude, latitude]: inside it, near its edge, or
|
|
34
|
+
* outside it, in empty space, where a leader line joins it to the nearest point of the edge.
|
|
35
|
+
* Footprints without one go in the key.
|
|
36
|
+
*/
|
|
37
|
+
labelAt?: (d: T) => [number, number] | null | undefined;
|
|
38
|
+
/** Text anchor of each label; defaults to `middle`. */
|
|
39
|
+
labelAnchor?: (d: T) => "start" | "middle" | "end";
|
|
40
|
+
/**
|
|
41
|
+
* Keep the labels on the map at narrow widths (and in narrow print sizes) as well as listing
|
|
42
|
+
* the footprints in the key. Without it, narrow maps rely on the key and the tooltip, which
|
|
43
|
+
* print doesn't have. Defaults to true.
|
|
44
|
+
*/
|
|
45
|
+
labelSmall?: boolean;
|
|
46
|
+
/** Land for context, drawn in grey under the footprints (countries, regions). */
|
|
47
|
+
basemap?: GeoPermissibleObjects[];
|
|
48
|
+
/** Areas the chart is about, outlined on top of the footprints (e.g. the country). */
|
|
49
|
+
focus?: GeoPermissibleObjects[];
|
|
50
|
+
/** Towns, epicentres and region names. */
|
|
51
|
+
places?: FootprintPlace[];
|
|
52
|
+
/** A d3-geo projection; it is fitted to `fit`. */
|
|
53
|
+
projection: GeoProjection;
|
|
54
|
+
/** The area to show; footprints beyond it are cut off. */
|
|
55
|
+
fit: GeoPermissibleObjects;
|
|
56
|
+
/** Width ÷ height of the map. Defaults to 1.1. */
|
|
57
|
+
aspectRatio?: number;
|
|
58
|
+
/** Map height in px, or a function of the width and breakpoint; overrides `aspectRatio`. */
|
|
59
|
+
height?: number | ((size: {
|
|
60
|
+
width: number;
|
|
61
|
+
breakpoint: Breakpoint;
|
|
62
|
+
}) => number);
|
|
63
|
+
/** Colour of every footprint; defaults to the first categorical colour. */
|
|
64
|
+
color?: string;
|
|
65
|
+
/** Fill opacity of the oldest and the newest footprint. Defaults to [0.12, 0.4]. */
|
|
66
|
+
opacity?: [number, number];
|
|
67
|
+
/** Tooltip heading over the footprints under the pointer, e.g. "Shaken at intensity VII or more in". */
|
|
68
|
+
tooltipTitle?: string;
|
|
69
|
+
/** Tooltip text where no footprint covers the pointer; with none, no tooltip shows there. */
|
|
70
|
+
tooltipNone?: string;
|
|
71
|
+
style?: Theme;
|
|
72
|
+
locale?: LocaleCode;
|
|
73
|
+
medium?: Medium;
|
|
74
|
+
width?: number;
|
|
75
|
+
title?: string;
|
|
76
|
+
subtitle?: string;
|
|
77
|
+
notes?: string;
|
|
78
|
+
/** Plain text, or sources with optional links (see `<Source>`). */
|
|
79
|
+
source?: string | SourceItem[];
|
|
80
|
+
alt?: string;
|
|
81
|
+
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
82
|
+
embed?: ChartEmbed;
|
|
83
|
+
/** Extra SVG drawn on top (annotations); receives the plot context. */
|
|
84
|
+
annotations?: Snippet<[PlotContext]>;
|
|
85
|
+
};
|
|
86
|
+
exports: {};
|
|
87
|
+
bindings: "";
|
|
88
|
+
slots: {};
|
|
89
|
+
events: {};
|
|
90
|
+
};
|
|
91
|
+
declare class __sveltets_Render<T> {
|
|
92
|
+
props(): ReturnType<typeof $$render<T>>['props'];
|
|
93
|
+
events(): ReturnType<typeof $$render<T>>['events'];
|
|
94
|
+
slots(): ReturnType<typeof $$render<T>>['slots'];
|
|
95
|
+
bindings(): "";
|
|
96
|
+
exports(): {};
|
|
97
|
+
}
|
|
98
|
+
interface $$IsomorphicComponent {
|
|
99
|
+
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']>> & {
|
|
100
|
+
$$bindings?: ReturnType<__sveltets_Render<T>['bindings']>;
|
|
101
|
+
} & ReturnType<__sveltets_Render<T>['exports']>;
|
|
102
|
+
<T>(internal: unknown, props: ReturnType<__sveltets_Render<T>['props']> & {}): ReturnType<__sveltets_Render<T>['exports']>;
|
|
103
|
+
z_$$bindings?: ReturnType<__sveltets_Render<any>['bindings']>;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Recipe: the footprints of several events on one map (the area each earthquake shook hard, each
|
|
107
|
+
* flood covered or each fire burnt), stacked from the oldest, faintest, to the newest, strongest,
|
|
108
|
+
* in one colour. Each footprint is outlined and labelled where you place its label; at narrow
|
|
109
|
+
* widths, or for footprints without a label position, a key lists them instead. Pointing at the
|
|
110
|
+
* map lists the footprints that cover that spot. Build footprints from point measurements with
|
|
111
|
+
* `contourPoints` from `@samizdata/mozaic/transforms`. Use it as is, or run
|
|
112
|
+
* `mozaic eject FootprintMap` to copy this file into your project and change anything.
|
|
113
|
+
*/
|
|
114
|
+
declare const FootprintMap: $$IsomorphicComponent;
|
|
115
|
+
type FootprintMap<T> = InstanceType<typeof FootprintMap<T>>;
|
|
116
|
+
export default FootprintMap;
|
package/dist/recipes/index.d.ts
CHANGED
|
@@ -8,5 +8,7 @@ export { default as StackedBarChart } from './StackedBarChart.svelte';
|
|
|
8
8
|
export { default as MosaicChart } from './MosaicChart.svelte';
|
|
9
9
|
export { default as PercentileChart } from './PercentileChart.svelte';
|
|
10
10
|
export { default as StripChart } from './StripChart.svelte';
|
|
11
|
+
export { default as FootprintMap } from './FootprintMap.svelte';
|
|
12
|
+
export type { FootprintPlace } from './FootprintMap.svelte';
|
|
11
13
|
/** Recipe names accepted by `mozaic eject`. */
|
|
12
|
-
export declare const recipes: readonly ["BarChart", "ColumnChart", "LineChart", "ScatterChart", "ArrowChart", "BarDotChart", "StackedBarChart", "MosaicChart", "PercentileChart", "StripChart"];
|
|
14
|
+
export declare const recipes: readonly ["BarChart", "ColumnChart", "LineChart", "ScatterChart", "ArrowChart", "BarDotChart", "StackedBarChart", "MosaicChart", "PercentileChart", "StripChart", "FootprintMap"];
|
package/dist/recipes/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export { default as StackedBarChart } from './StackedBarChart.svelte';
|
|
|
8
8
|
export { default as MosaicChart } from './MosaicChart.svelte';
|
|
9
9
|
export { default as PercentileChart } from './PercentileChart.svelte';
|
|
10
10
|
export { default as StripChart } from './StripChart.svelte';
|
|
11
|
+
export { default as FootprintMap } from './FootprintMap.svelte';
|
|
11
12
|
/** Recipe names accepted by `mozaic eject`. */
|
|
12
13
|
export const recipes = [
|
|
13
14
|
'BarChart',
|
|
@@ -19,5 +20,6 @@ export const recipes = [
|
|
|
19
20
|
'StackedBarChart',
|
|
20
21
|
'MosaicChart',
|
|
21
22
|
'PercentileChart',
|
|
22
|
-
'StripChart'
|
|
23
|
+
'StripChart',
|
|
24
|
+
'FootprintMap'
|
|
23
25
|
];
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Feature, MultiPolygon } from 'geojson';
|
|
2
|
+
export interface ContourPointsOptions<T> {
|
|
3
|
+
/** Longitude of each observation. */
|
|
4
|
+
x: (d: T) => number;
|
|
5
|
+
/** Latitude of each observation. */
|
|
6
|
+
y: (d: T) => number;
|
|
7
|
+
/** The measured value. Missing values (null, undefined, NaN) are skipped. */
|
|
8
|
+
value: (d: T) => number | null | undefined;
|
|
9
|
+
/** Draw the area where the smoothed value is at least each of these. */
|
|
10
|
+
thresholds: number[];
|
|
11
|
+
/** Smoothing radius in kilometres: the standard deviation of the Gaussian kernel. */
|
|
12
|
+
bandwidth: number;
|
|
13
|
+
/** Grid cell size in kilometres. Defaults to a quarter of the bandwidth. */
|
|
14
|
+
cellSize?: number;
|
|
15
|
+
/** Area to grid, as [[west, south], [east, north]]. Defaults to the data's bounds plus two bandwidths. */
|
|
16
|
+
extent?: [[number, number], [number, number]];
|
|
17
|
+
/**
|
|
18
|
+
* Where the kernel weights of the observations near a cell add up to less than this, the cell's
|
|
19
|
+
* value fades towards `background` in proportion, so the areas stop where the data stops (not in
|
|
20
|
+
* the sea or empty country) with smooth edges. Above it, the value is the plain weighted mean.
|
|
21
|
+
* One observation one bandwidth away weighs 0.61. Defaults to 0.5.
|
|
22
|
+
*/
|
|
23
|
+
minWeight?: number;
|
|
24
|
+
/** The value where there is no data. Defaults to the smallest observed value. */
|
|
25
|
+
background?: number;
|
|
26
|
+
/** Extra weight per observation. */
|
|
27
|
+
weight?: (d: T) => number;
|
|
28
|
+
}
|
|
29
|
+
/** The area where the smoothed value is at least `value`, in longitude and latitude. */
|
|
30
|
+
export type ContourArea = Feature<MultiPolygon, {
|
|
31
|
+
value: number;
|
|
32
|
+
}>;
|
|
33
|
+
/**
|
|
34
|
+
* Contours of scattered measurements on a map, such as earthquake intensities reported by place,
|
|
35
|
+
* felt reports or sensor readings: the areas where the smoothed value is at least each threshold.
|
|
36
|
+
* Each grid cell takes the Gaussian-weighted mean of the observations within three bandwidths
|
|
37
|
+
* (Nadaraya–Watson); at the edges of the data it fades to a background value. Returns one
|
|
38
|
+
* GeoJSON feature per threshold, wound for d3-geo, ready for `<GeoPath>`. For whole-number scales (intensity, ratings),
|
|
39
|
+
* a threshold half a step below a value (6.5 for VII) draws the line where the smoothed value
|
|
40
|
+
* rounds to it.
|
|
41
|
+
*/
|
|
42
|
+
export declare function contourPoints<T>(data: Iterable<T>, options: ContourPointsOptions<T>): ContourArea[];
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { contours } from 'd3-contour';
|
|
2
|
+
import { geoArea } from 'd3-geo';
|
|
3
|
+
const KM_PER_DEGREE = 111.32;
|
|
4
|
+
/**
|
|
5
|
+
* Contours of scattered measurements on a map, such as earthquake intensities reported by place,
|
|
6
|
+
* felt reports or sensor readings: the areas where the smoothed value is at least each threshold.
|
|
7
|
+
* Each grid cell takes the Gaussian-weighted mean of the observations within three bandwidths
|
|
8
|
+
* (Nadaraya–Watson); at the edges of the data it fades to a background value. Returns one
|
|
9
|
+
* GeoJSON feature per threshold, wound for d3-geo, ready for `<GeoPath>`. For whole-number scales (intensity, ratings),
|
|
10
|
+
* a threshold half a step below a value (6.5 for VII) draws the line where the smoothed value
|
|
11
|
+
* rounds to it.
|
|
12
|
+
*/
|
|
13
|
+
export function contourPoints(data, options) {
|
|
14
|
+
const { x, y, value, thresholds, bandwidth, weight, minWeight = 0.5 } = options;
|
|
15
|
+
const cellKm = options.cellSize ?? bandwidth / 4;
|
|
16
|
+
const points = [];
|
|
17
|
+
for (const d of data) {
|
|
18
|
+
const v = value(d);
|
|
19
|
+
const lon = x(d);
|
|
20
|
+
const lat = y(d);
|
|
21
|
+
if (v == null || !Number.isFinite(v) || !Number.isFinite(lon) || !Number.isFinite(lat))
|
|
22
|
+
continue;
|
|
23
|
+
points.push({ lon, lat, v, w: weight ? weight(d) : 1 });
|
|
24
|
+
}
|
|
25
|
+
if (!points.length || !thresholds.length)
|
|
26
|
+
return thresholds.map((t) => empty(t));
|
|
27
|
+
const background = options.background ?? Math.min(...points.map((p) => p.v));
|
|
28
|
+
const pad = (2 * bandwidth) / KM_PER_DEGREE;
|
|
29
|
+
const [[west, south], [east, north]] = options.extent ?? [
|
|
30
|
+
[
|
|
31
|
+
Math.min(...points.map((p) => p.lon)) - pad / Math.cos(rad(mean(points.map((p) => p.lat)))),
|
|
32
|
+
Math.min(...points.map((p) => p.lat)) - pad
|
|
33
|
+
],
|
|
34
|
+
[
|
|
35
|
+
Math.max(...points.map((p) => p.lon)) + pad / Math.cos(rad(mean(points.map((p) => p.lat)))),
|
|
36
|
+
Math.max(...points.map((p) => p.lat)) + pad
|
|
37
|
+
]
|
|
38
|
+
];
|
|
39
|
+
const kmX = KM_PER_DEGREE * Math.cos(rad((south + north) / 2));
|
|
40
|
+
const dLon = cellKm / kmX;
|
|
41
|
+
const dLat = cellKm / KM_PER_DEGREE;
|
|
42
|
+
const nx = Math.max(2, Math.ceil((east - west) / dLon) + 1);
|
|
43
|
+
const ny = Math.max(2, Math.ceil((north - south) / dLat) + 1);
|
|
44
|
+
// Bucket the observations by cut-off radius so each cell only looks at its neighbours. Buckets
|
|
45
|
+
// are as wide in degrees as the cut-off is at the edge furthest from the equator.
|
|
46
|
+
const cutoff = 3 * bandwidth;
|
|
47
|
+
const bucketLon = cutoff / (KM_PER_DEGREE * Math.cos(rad(Math.min(89, Math.max(Math.abs(south), Math.abs(north))))));
|
|
48
|
+
const bucketLat = cutoff / KM_PER_DEGREE;
|
|
49
|
+
const buckets = new Map();
|
|
50
|
+
const key = (bx, by) => `${bx},${by}`;
|
|
51
|
+
for (const p of points) {
|
|
52
|
+
const k = key(Math.floor((p.lon - west) / bucketLon), Math.floor((p.lat - south) / bucketLat));
|
|
53
|
+
const b = buckets.get(k);
|
|
54
|
+
if (b)
|
|
55
|
+
b.push(p);
|
|
56
|
+
else
|
|
57
|
+
buckets.set(k, [p]);
|
|
58
|
+
}
|
|
59
|
+
// Row 0 is the north edge, so the grid reads like the map and rings keep their orientation.
|
|
60
|
+
const values = new Float64Array(nx * ny);
|
|
61
|
+
const twoSigma2 = 2 * bandwidth * bandwidth;
|
|
62
|
+
for (let j = 0; j < ny; j++) {
|
|
63
|
+
const lat = north - j * dLat;
|
|
64
|
+
const kx = KM_PER_DEGREE * Math.cos(rad(lat));
|
|
65
|
+
const by = Math.floor((lat - south) / bucketLat);
|
|
66
|
+
for (let i = 0; i < nx; i++) {
|
|
67
|
+
const lon = west + i * dLon;
|
|
68
|
+
const bx = Math.floor((lon - west) / bucketLon);
|
|
69
|
+
let sw = 0;
|
|
70
|
+
let swv = 0;
|
|
71
|
+
for (let ox = -1; ox <= 1; ox++) {
|
|
72
|
+
for (let oy = -1; oy <= 1; oy++) {
|
|
73
|
+
const b = buckets.get(key(bx + ox, by + oy));
|
|
74
|
+
if (!b)
|
|
75
|
+
continue;
|
|
76
|
+
for (const p of b) {
|
|
77
|
+
const ex = (p.lon - lon) * kx;
|
|
78
|
+
const ey = (p.lat - lat) * KM_PER_DEGREE;
|
|
79
|
+
const d2 = ex * ex + ey * ey;
|
|
80
|
+
if (d2 > cutoff * cutoff)
|
|
81
|
+
continue;
|
|
82
|
+
const w = p.w * Math.exp(-d2 / twoSigma2);
|
|
83
|
+
sw += w;
|
|
84
|
+
swv += w * p.v;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const fade = minWeight > 0 ? Math.min(1, sw / minWeight) : 1;
|
|
89
|
+
values[j * nx + i] = sw > 0 ? background + fade * (swv / sw - background) : background;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const toGeo = (pt) => [west + (pt[0] - 0.5) * dLon, north - (pt[1] - 0.5) * dLat];
|
|
93
|
+
return contours()
|
|
94
|
+
.size([nx, ny])
|
|
95
|
+
.thresholds(thresholds)(Array.from(values))
|
|
96
|
+
.map((c) => {
|
|
97
|
+
const coordinates = c.coordinates
|
|
98
|
+
.map((polygon) => polygon.map((ring) => ring.map(toGeo)))
|
|
99
|
+
.map((polygon) => wind(polygon));
|
|
100
|
+
return { type: 'Feature', properties: { value: c.value }, geometry: { type: 'MultiPolygon', coordinates } };
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** d3-geo reads a polygon wound the wrong way as the whole globe minus the shape: flip it. */
|
|
104
|
+
function wind(polygon) {
|
|
105
|
+
const area = geoArea({ type: 'Polygon', coordinates: polygon });
|
|
106
|
+
return area > 2 * Math.PI ? polygon.map((ring) => [...ring].reverse()) : polygon;
|
|
107
|
+
}
|
|
108
|
+
function empty(value) {
|
|
109
|
+
return { type: 'Feature', properties: { value }, geometry: { type: 'MultiPolygon', coordinates: [] } };
|
|
110
|
+
}
|
|
111
|
+
const rad = (deg) => (deg * Math.PI) / 180;
|
|
112
|
+
const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
|
|
@@ -7,3 +7,4 @@ export { treemapLayout, type TreemapCell } from './treemap.js';
|
|
|
7
7
|
export { hemicycleLayout, type HemicycleLayout, type HemicycleOptions, type Seat } from './hemicycle.js';
|
|
8
8
|
export { kernelSmooth, loess, type Kernel, type KernelSmoothOptions, type LoessOptions, type Smoothed } from './smooth.js';
|
|
9
9
|
export { percentileRank, type PercentilePoint, type PercentileRank } from './percentile.js';
|
|
10
|
+
export { contourPoints, type ContourArea, type ContourPointsOptions } from './contour.js';
|
package/dist/transforms/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@samizdata/mozaic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"description": "Chart components for the web and print, built on Svelte 5 and d3, and the mozaic CLI (export embeds to SVG, PDF and PNG; eject recipes).",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"author": "Nicu Calcea",
|
|
@@ -115,6 +115,7 @@
|
|
|
115
115
|
},
|
|
116
116
|
"dependencies": {
|
|
117
117
|
"d3-array": "^3.2.4",
|
|
118
|
+
"d3-contour": "^4.0.3",
|
|
118
119
|
"d3-delaunay": "^6.0.4",
|
|
119
120
|
"d3-format": "^3.1.0",
|
|
120
121
|
"d3-geo": "^3.1.1",
|
|
@@ -130,6 +131,7 @@
|
|
|
130
131
|
"@sveltejs/package": "^3.0.1",
|
|
131
132
|
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
|
132
133
|
"@types/d3-array": "^3.2.1",
|
|
134
|
+
"@types/d3-contour": "^3.0.6",
|
|
133
135
|
"@types/d3-delaunay": "^6.0.4",
|
|
134
136
|
"@types/d3-format": "^3.0.4",
|
|
135
137
|
"@types/d3-geo": "^3.1.0",
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
@component
|
|
3
|
+
Recipe: the footprints of several events on one map (the area each earthquake shook hard, each
|
|
4
|
+
flood covered or each fire burnt), stacked from the oldest, faintest, to the newest, strongest,
|
|
5
|
+
in one colour. Each footprint is outlined and labelled where you place its label; at narrow
|
|
6
|
+
widths, or for footprints without a label position, a key lists them instead. Pointing at the
|
|
7
|
+
map lists the footprints that cover that spot. Build footprints from point measurements with
|
|
8
|
+
`contourPoints` from `@samizdata/mozaic/transforms`. Use it as is, or run
|
|
9
|
+
`mozaic eject FootprintMap` to copy this file into your project and change anything.
|
|
10
|
+
-->
|
|
11
|
+
<script lang="ts" module>
|
|
12
|
+
/** A labelled point on the map: a town, an epicentre, a country name. */
|
|
13
|
+
export interface FootprintPlace {
|
|
14
|
+
name: string;
|
|
15
|
+
lon: number;
|
|
16
|
+
lat: number;
|
|
17
|
+
/** Draw a dot at the point (towns); without it the name is centred on the point (regions). */
|
|
18
|
+
dot?: boolean;
|
|
19
|
+
/** Grey text, for context such as country names. */
|
|
20
|
+
muted?: boolean;
|
|
21
|
+
/** Text anchor for names beside a dot; defaults to `start` (to the right). */
|
|
22
|
+
anchor?: 'start' | 'middle' | 'end';
|
|
23
|
+
/** Hide at narrow widths. */
|
|
24
|
+
hideSmall?: boolean;
|
|
25
|
+
}
|
|
26
|
+
</script>
|
|
27
|
+
|
|
28
|
+
<script lang="ts" generics="T">
|
|
29
|
+
import type { Snippet } from 'svelte';
|
|
30
|
+
import { geoContains, type GeoPermissibleObjects, type GeoProjection } from 'd3-geo';
|
|
31
|
+
import { Chart, Header, Title, Subtitle, Footer, Source, Notes, type SourceItem } from '../frame/index.js';
|
|
32
|
+
import type { ChartEmbed } from '../embed/index.js';
|
|
33
|
+
import { Plot, Svg, Html, type PlotContext } from '../core/index.js';
|
|
34
|
+
import { Text } from '../marks/index.js';
|
|
35
|
+
import { Legend } from '../guides/index.js';
|
|
36
|
+
import { PointerArea, Tooltip } from '../interactive/index.js';
|
|
37
|
+
import type { LocaleCode } from '../locale/index.js';
|
|
38
|
+
import { base, readableColor, type Breakpoint, type Medium, type Theme } from '../styles/index.js';
|
|
39
|
+
|
|
40
|
+
interface Props {
|
|
41
|
+
/** One row per footprint. */
|
|
42
|
+
data: T[];
|
|
43
|
+
/** The footprint's area, e.g. a GeoJSON feature. */
|
|
44
|
+
geometry: (d: T) => GeoPermissibleObjects;
|
|
45
|
+
/** Name of the footprint, e.g. the year. */
|
|
46
|
+
label: (d: T) => string;
|
|
47
|
+
/** What decides the fading: lowest is drawn first and faintest. Defaults to data order (oldest first). */
|
|
48
|
+
order?: (d: T) => number | Date;
|
|
49
|
+
/**
|
|
50
|
+
* Where to write the footprint's name, as [longitude, latitude]: inside it, near its edge, or
|
|
51
|
+
* outside it, in empty space, where a leader line joins it to the nearest point of the edge.
|
|
52
|
+
* Footprints without one go in the key.
|
|
53
|
+
*/
|
|
54
|
+
labelAt?: (d: T) => [number, number] | null | undefined;
|
|
55
|
+
/** Text anchor of each label; defaults to `middle`. */
|
|
56
|
+
labelAnchor?: (d: T) => 'start' | 'middle' | 'end';
|
|
57
|
+
/**
|
|
58
|
+
* Keep the labels on the map at narrow widths (and in narrow print sizes) as well as listing
|
|
59
|
+
* the footprints in the key. Without it, narrow maps rely on the key and the tooltip, which
|
|
60
|
+
* print doesn't have. Defaults to true.
|
|
61
|
+
*/
|
|
62
|
+
labelSmall?: boolean;
|
|
63
|
+
/** Land for context, drawn in grey under the footprints (countries, regions). */
|
|
64
|
+
basemap?: GeoPermissibleObjects[];
|
|
65
|
+
/** Areas the chart is about, outlined on top of the footprints (e.g. the country). */
|
|
66
|
+
focus?: GeoPermissibleObjects[];
|
|
67
|
+
/** Towns, epicentres and region names. */
|
|
68
|
+
places?: FootprintPlace[];
|
|
69
|
+
/** A d3-geo projection; it is fitted to `fit`. */
|
|
70
|
+
projection: GeoProjection;
|
|
71
|
+
/** The area to show; footprints beyond it are cut off. */
|
|
72
|
+
fit: GeoPermissibleObjects;
|
|
73
|
+
/** Width ÷ height of the map. Defaults to 1.1. */
|
|
74
|
+
aspectRatio?: number;
|
|
75
|
+
/** Map height in px, or a function of the width and breakpoint; overrides `aspectRatio`. */
|
|
76
|
+
height?: number | ((size: { width: number; breakpoint: Breakpoint }) => number);
|
|
77
|
+
/** Colour of every footprint; defaults to the first categorical colour. */
|
|
78
|
+
color?: string;
|
|
79
|
+
/** Fill opacity of the oldest and the newest footprint. Defaults to [0.12, 0.4]. */
|
|
80
|
+
opacity?: [number, number];
|
|
81
|
+
/** Tooltip heading over the footprints under the pointer, e.g. "Shaken at intensity VII or more in". */
|
|
82
|
+
tooltipTitle?: string;
|
|
83
|
+
/** Tooltip text where no footprint covers the pointer; with none, no tooltip shows there. */
|
|
84
|
+
tooltipNone?: string;
|
|
85
|
+
style?: Theme;
|
|
86
|
+
locale?: LocaleCode;
|
|
87
|
+
medium?: Medium;
|
|
88
|
+
width?: number;
|
|
89
|
+
title?: string;
|
|
90
|
+
subtitle?: string;
|
|
91
|
+
notes?: string;
|
|
92
|
+
/** Plain text, or sources with optional links (see `<Source>`). */
|
|
93
|
+
source?: string | SourceItem[];
|
|
94
|
+
alt?: string;
|
|
95
|
+
/** The chart's embed page, for the embed code under the chart (see `<Chart embed>`). */
|
|
96
|
+
embed?: ChartEmbed;
|
|
97
|
+
/** Extra SVG drawn on top (annotations); receives the plot context. */
|
|
98
|
+
annotations?: Snippet<[PlotContext]>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
let {
|
|
102
|
+
data,
|
|
103
|
+
geometry,
|
|
104
|
+
label,
|
|
105
|
+
order,
|
|
106
|
+
labelAt,
|
|
107
|
+
labelAnchor,
|
|
108
|
+
labelSmall = true,
|
|
109
|
+
basemap = [],
|
|
110
|
+
focus = [],
|
|
111
|
+
places = [],
|
|
112
|
+
projection,
|
|
113
|
+
fit,
|
|
114
|
+
aspectRatio = 1.1,
|
|
115
|
+
height,
|
|
116
|
+
color,
|
|
117
|
+
opacity = [0.12, 0.4],
|
|
118
|
+
tooltipTitle,
|
|
119
|
+
tooltipNone,
|
|
120
|
+
style = base,
|
|
121
|
+
locale,
|
|
122
|
+
medium,
|
|
123
|
+
width,
|
|
124
|
+
title,
|
|
125
|
+
subtitle,
|
|
126
|
+
notes,
|
|
127
|
+
source,
|
|
128
|
+
alt,
|
|
129
|
+
embed,
|
|
130
|
+
annotations
|
|
131
|
+
}: Props = $props();
|
|
132
|
+
|
|
133
|
+
const uid = $props.id();
|
|
134
|
+
const theme = $derived(style);
|
|
135
|
+
const bg = $derived(theme.tokens['--mz-color-bg'] ?? '#ffffff');
|
|
136
|
+
const hue = $derived(color ?? theme.palettes.categorical[0]);
|
|
137
|
+
const ink = $derived(readableColor(hue, bg));
|
|
138
|
+
|
|
139
|
+
/** Oldest first, so the newest is drawn on top. */
|
|
140
|
+
const layers = $derived.by(() => {
|
|
141
|
+
const rows = order ? data.toSorted((a, b) => +order(a) - +order(b)) : [...data];
|
|
142
|
+
const n = rows.length;
|
|
143
|
+
return rows.map((d, i) => {
|
|
144
|
+
const t = n > 1 ? i / (n - 1) : 1;
|
|
145
|
+
const fill = opacity[0] + t * (opacity[1] - opacity[0]);
|
|
146
|
+
return { d, geo: geometry(d), name: label(d), fill, stroke: 0.5 + 0.5 * t, at: labelAt?.(d) ?? null };
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
/** Every vertex of a GeoJSON object. */
|
|
151
|
+
function vertices(g: unknown, out: [number, number][] = []): [number, number][] {
|
|
152
|
+
if (!g || typeof g !== 'object') return out;
|
|
153
|
+
const o = g as {
|
|
154
|
+
type?: string;
|
|
155
|
+
coordinates?: unknown;
|
|
156
|
+
geometry?: unknown;
|
|
157
|
+
features?: unknown[];
|
|
158
|
+
geometries?: unknown[];
|
|
159
|
+
};
|
|
160
|
+
if (o.type === 'Feature') return vertices(o.geometry, out);
|
|
161
|
+
if (o.type === 'FeatureCollection') o.features?.forEach((f) => vertices(f, out));
|
|
162
|
+
else if (o.type === 'GeometryCollection') o.geometries?.forEach((f) => vertices(f, out));
|
|
163
|
+
else if (o.coordinates) {
|
|
164
|
+
const walk = (c: unknown) => {
|
|
165
|
+
if (Array.isArray(c) && typeof c[0] === 'number') out.push([c[0], c[1] as number]);
|
|
166
|
+
else if (Array.isArray(c)) c.forEach(walk);
|
|
167
|
+
};
|
|
168
|
+
walk(o.coordinates);
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A label placed outside its footprint gets a leader line to the nearest visible point of the
|
|
175
|
+
* footprint's edge, so labels can sit in empty space when footprints overlap.
|
|
176
|
+
*/
|
|
177
|
+
function leader(l: (typeof layers)[number], plot: PlotContext): [number, number, number, number] | null {
|
|
178
|
+
if (!l.at || !plot.projection || geoContains(l.geo, l.at)) return null;
|
|
179
|
+
const from = plot.projection(l.at);
|
|
180
|
+
if (!from) return null;
|
|
181
|
+
let best: [number, number] | null = null;
|
|
182
|
+
let dist = Infinity;
|
|
183
|
+
for (const v of vertices(l.geo)) {
|
|
184
|
+
const p = plot.projection(v);
|
|
185
|
+
if (!p || p[0] < 0 || p[1] < 0 || p[0] > plot.width || p[1] > plot.height) continue;
|
|
186
|
+
const dd = (p[0] - from[0]) ** 2 + (p[1] - from[1]) ** 2;
|
|
187
|
+
if (dd < dist) {
|
|
188
|
+
dist = dd;
|
|
189
|
+
best = [p[0], p[1]];
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return best ? [from[0], from[1], best[0], best[1]] : null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The colour a footprint's fill shows over the background, for the key and tooltip swatches. */
|
|
196
|
+
function over(alpha: number): string {
|
|
197
|
+
const rgb = (h: string) => {
|
|
198
|
+
const s = h.replace('#', '');
|
|
199
|
+
const f = s.length === 3 ? s.replace(/./g, '$&$&') : s.slice(0, 6);
|
|
200
|
+
return [0, 2, 4].map((i) => parseInt(f.slice(i, i + 2), 16));
|
|
201
|
+
};
|
|
202
|
+
const [a, b] = [rgb(hue), rgb(bg)];
|
|
203
|
+
// Swatches are small, so show them a little stronger than the fill.
|
|
204
|
+
const k = Math.min(1, alpha * 1.6);
|
|
205
|
+
return `#${a
|
|
206
|
+
.map((v, i) =>
|
|
207
|
+
Math.round(k * v + (1 - k) * b[i])
|
|
208
|
+
.toString(16)
|
|
209
|
+
.padStart(2, '0')
|
|
210
|
+
)
|
|
211
|
+
.join('')}`;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const newestFirst = $derived(layers.toReversed());
|
|
215
|
+
const unlabelled = $derived(layers.some((l) => !l.at));
|
|
216
|
+
|
|
217
|
+
let hover = $state<{ x: number; y: number; covered: typeof layers } | null>(null);
|
|
218
|
+
function onmove(px: number, py: number, plot: PlotContext) {
|
|
219
|
+
const lonlat = plot.projection?.invert?.([px, py]);
|
|
220
|
+
if (!lonlat) return (hover = null);
|
|
221
|
+
hover = { x: px, y: py, covered: newestFirst.filter((l) => geoContains(l.geo, lonlat)) };
|
|
222
|
+
}
|
|
223
|
+
const isHovered = (l: (typeof layers)[number]) => !!hover?.covered.includes(l);
|
|
224
|
+
</script>
|
|
225
|
+
|
|
226
|
+
<Chart {style} {locale} {medium} {width} {alt} {embed}>
|
|
227
|
+
<Header>
|
|
228
|
+
{#if title}<Title>{title}</Title>{/if}
|
|
229
|
+
{#if subtitle}<Subtitle>{subtitle}</Subtitle>{/if}
|
|
230
|
+
<!-- The key shows when a footprint has no label on the map, and at narrow widths, where it explains the fading. -->
|
|
231
|
+
<div class="mz-footprint-key" class:mz-footprint-key-always={unlabelled}>
|
|
232
|
+
<Legend items={newestFirst.map((l) => ({ label: l.name, color: over(l.fill) }))} />
|
|
233
|
+
</div>
|
|
234
|
+
</Header>
|
|
235
|
+
|
|
236
|
+
<Plot {projection} {fit} {aspectRatio} {height} padding={{ top: 0, right: 0, bottom: 0, left: 0 }}>
|
|
237
|
+
{#snippet children(plot)}
|
|
238
|
+
<Svg>
|
|
239
|
+
{#snippet defs()}
|
|
240
|
+
<clipPath id="mz-footprint-clip-{uid}">
|
|
241
|
+
<rect x={0} y={0} width={plot.width} height={plot.height} />
|
|
242
|
+
</clipPath>
|
|
243
|
+
{/snippet}
|
|
244
|
+
<g class="mz-footprint-map" clip-path="url(#mz-footprint-clip-{uid})">
|
|
245
|
+
{#each basemap as g, i (i)}
|
|
246
|
+
<path
|
|
247
|
+
class="mz-footprint-base"
|
|
248
|
+
d={plot.path?.(g) ?? ''}
|
|
249
|
+
fill="var(--mz-color-grid)"
|
|
250
|
+
fill-opacity="0.45"
|
|
251
|
+
stroke="var(--mz-color-axis)"
|
|
252
|
+
stroke-width="0.5"
|
|
253
|
+
stroke-linejoin="round"
|
|
254
|
+
/>
|
|
255
|
+
{/each}
|
|
256
|
+
{#each layers as l, i (i)}
|
|
257
|
+
<path
|
|
258
|
+
class="mz-footprint"
|
|
259
|
+
d={plot.path?.(l.geo) ?? ''}
|
|
260
|
+
fill={hue}
|
|
261
|
+
fill-opacity={l.fill}
|
|
262
|
+
stroke={hue}
|
|
263
|
+
stroke-opacity={isHovered(l) ? 1 : l.stroke}
|
|
264
|
+
stroke-width={isHovered(l) ? 2.5 : 1.25}
|
|
265
|
+
stroke-linejoin="round"
|
|
266
|
+
/>
|
|
267
|
+
{/each}
|
|
268
|
+
{#each focus as g, i (i)}
|
|
269
|
+
<path
|
|
270
|
+
class="mz-footprint-focus"
|
|
271
|
+
d={plot.path?.(g) ?? ''}
|
|
272
|
+
fill="none"
|
|
273
|
+
stroke="var(--mz-color-text)"
|
|
274
|
+
stroke-width="1.25"
|
|
275
|
+
stroke-linejoin="round"
|
|
276
|
+
/>
|
|
277
|
+
{/each}
|
|
278
|
+
</g>
|
|
279
|
+
{#each places.filter((p) => p.dot && !(p.hideSmall && plot.breakpoint === 's')) as p, i (i)}
|
|
280
|
+
{@const xy = plot.projection?.([p.lon, p.lat])}
|
|
281
|
+
{#if xy}
|
|
282
|
+
<circle
|
|
283
|
+
class="mz-footprint-dot"
|
|
284
|
+
cx={xy[0]}
|
|
285
|
+
cy={xy[1]}
|
|
286
|
+
r={2.5}
|
|
287
|
+
fill={p.muted ? 'var(--mz-color-muted)' : 'var(--mz-color-text)'}
|
|
288
|
+
stroke="var(--mz-color-bg)"
|
|
289
|
+
stroke-width="1"
|
|
290
|
+
/>
|
|
291
|
+
{/if}
|
|
292
|
+
{/each}
|
|
293
|
+
{#each places.filter((p) => !(p.hideSmall && plot.breakpoint === 's')) as p, i (i)}
|
|
294
|
+
{@const anchor = p.dot ? (p.anchor ?? 'start') : 'middle'}
|
|
295
|
+
<Text
|
|
296
|
+
data={[p]}
|
|
297
|
+
x={(d) => d.lon}
|
|
298
|
+
y={(d) => d.lat}
|
|
299
|
+
text={(d) => d.name}
|
|
300
|
+
dx={p.dot ? (anchor === 'start' ? 5 : anchor === 'end' ? -5 : 0) : 0}
|
|
301
|
+
dy={p.dot && anchor === 'middle' ? -9 : 0}
|
|
302
|
+
{anchor}
|
|
303
|
+
fill={p.muted ? 'var(--mz-color-muted)' : 'var(--mz-color-text)'}
|
|
304
|
+
fontWeight={p.dot ? 400 : 600}
|
|
305
|
+
halo
|
|
306
|
+
/>
|
|
307
|
+
{/each}
|
|
308
|
+
{#if plot.breakpoint !== 's' || labelSmall}
|
|
309
|
+
{#each layers.filter((l) => l.at) as l, i (i)}
|
|
310
|
+
{@const line = leader(l, plot)}
|
|
311
|
+
{#if line}
|
|
312
|
+
<g class="mz-footprint-leader">
|
|
313
|
+
<line x1={line[0]} y1={line[1]} x2={line[2]} y2={line[3]} stroke={ink} stroke-width="1" />
|
|
314
|
+
<circle cx={line[2]} cy={line[3]} r="2" fill={ink} />
|
|
315
|
+
</g>
|
|
316
|
+
{/if}
|
|
317
|
+
{/each}
|
|
318
|
+
{#each layers.filter((l) => l.at) as l, i (i)}
|
|
319
|
+
<Text
|
|
320
|
+
data={[l]}
|
|
321
|
+
x={(d) => d.at![0]}
|
|
322
|
+
y={(d) => d.at![1]}
|
|
323
|
+
text={(d) => d.name}
|
|
324
|
+
anchor={labelAnchor?.(l.d) ?? 'middle'}
|
|
325
|
+
fill={ink}
|
|
326
|
+
fontWeight={700}
|
|
327
|
+
halo
|
|
328
|
+
/>
|
|
329
|
+
{/each}
|
|
330
|
+
{/if}
|
|
331
|
+
{@render annotations?.(plot)}
|
|
332
|
+
{#if tooltipTitle}
|
|
333
|
+
<PointerArea onmove={({ x, y }) => onmove(x, y, plot)} onleave={() => (hover = null)} />
|
|
334
|
+
{/if}
|
|
335
|
+
</Svg>
|
|
336
|
+
<Html>
|
|
337
|
+
{#if hover && tooltipTitle && (hover.covered.length || tooltipNone)}
|
|
338
|
+
<Tooltip
|
|
339
|
+
x={hover.x}
|
|
340
|
+
y={hover.y}
|
|
341
|
+
title={tooltipTitle}
|
|
342
|
+
items={hover.covered.length
|
|
343
|
+
? hover.covered.map((l) => ({ label: l.name, value: '', color: over(l.fill), shape: 'square' as const }))
|
|
344
|
+
: [{ label: tooltipNone ?? '', value: '', color: 'transparent', shape: 'square' as const }]}
|
|
345
|
+
/>
|
|
346
|
+
{/if}
|
|
347
|
+
</Html>
|
|
348
|
+
{/snippet}
|
|
349
|
+
</Plot>
|
|
350
|
+
|
|
351
|
+
{#if notes || source}
|
|
352
|
+
<Footer>
|
|
353
|
+
{#if notes}<Notes>{notes}</Notes>{/if}
|
|
354
|
+
{#if source}<Source sources={source} />{/if}
|
|
355
|
+
</Footer>
|
|
356
|
+
{/if}
|
|
357
|
+
</Chart>
|
|
358
|
+
|
|
359
|
+
<style>
|
|
360
|
+
.mz-footprint-key {
|
|
361
|
+
display: none;
|
|
362
|
+
margin-top: 0.25rem;
|
|
363
|
+
}
|
|
364
|
+
.mz-footprint-key-always,
|
|
365
|
+
:global([data-mz-breakpoint='s']) .mz-footprint-key {
|
|
366
|
+
display: block;
|
|
367
|
+
}
|
|
368
|
+
</style>
|
package/src/lib/recipes/index.ts
CHANGED
|
@@ -8,6 +8,8 @@ export { default as StackedBarChart } from './StackedBarChart.svelte';
|
|
|
8
8
|
export { default as MosaicChart } from './MosaicChart.svelte';
|
|
9
9
|
export { default as PercentileChart } from './PercentileChart.svelte';
|
|
10
10
|
export { default as StripChart } from './StripChart.svelte';
|
|
11
|
+
export { default as FootprintMap } from './FootprintMap.svelte';
|
|
12
|
+
export type { FootprintPlace } from './FootprintMap.svelte';
|
|
11
13
|
|
|
12
14
|
/** Recipe names accepted by `mozaic eject`. */
|
|
13
15
|
export const recipes = [
|
|
@@ -20,5 +22,6 @@ export const recipes = [
|
|
|
20
22
|
'StackedBarChart',
|
|
21
23
|
'MosaicChart',
|
|
22
24
|
'PercentileChart',
|
|
23
|
-
'StripChart'
|
|
25
|
+
'StripChart',
|
|
26
|
+
'FootprintMap'
|
|
24
27
|
] as const;
|