@sovereignfs/ui 0.91.0 → 0.96.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/map.d.ts ADDED
@@ -0,0 +1,87 @@
1
+ import * as react from 'react';
2
+
3
+ /**
4
+ * What the `Map` decides without a map: which requests it lets through, the shapes it hands MapLibre, and how markers group when they are close. Pure, so each is tested exactly, and the part
5
+ * that needs WebGL (`Map.tsx`) stays a thin wiring of these.
6
+ */
7
+ interface LatLng {
8
+ readonly lat: number;
9
+ readonly lng: number;
10
+ }
11
+ /**
12
+ * Whether the map may fetch `url`: **only from addresses the app gave**. Its style's own origin and the page's own are allowed (a style's tiles, glyphs and sprite are normally the app's own
13
+ * `/api/map`), and anything listed in `allowedOrigins`; `blob:` and `data:` carry their own bytes. Every other request is refused, so a style that names a third-party tile server, font or
14
+ * sprite makes no request to it, whatever it says.
15
+ */
16
+ declare function isAllowedRequest(url: string, options: {
17
+ base: string;
18
+ allowedOrigins?: readonly string[];
19
+ }): boolean;
20
+
21
+ type MapMarkerTone = 'accent' | 'success' | 'warning' | 'error' | 'neutral';
22
+ interface MapMarkerData {
23
+ /** Stable. */
24
+ id: string;
25
+ lat: number;
26
+ lng: number;
27
+ /** What the marker is, for a screen reader and the tooltip: "Café da Beira". */
28
+ label: string;
29
+ tone?: MapMarkerTone;
30
+ selected?: boolean;
31
+ }
32
+ interface MapPick {
33
+ /** The chosen point, shown with a pin. */
34
+ value?: LatLng | null;
35
+ /** Called with a point chosen by clicking or tapping the map, or by pressing Enter with the map focused (the middle of the map). */
36
+ onPick: (point: LatLng) => void;
37
+ }
38
+ interface MapProps {
39
+ /** The style document's address, from the app's own server. Light or dark is the style's: pass another address, and the map changes. */
40
+ styleUrl: string;
41
+ /** What the map shows, for assistive technology: "Where you have been". */
42
+ ariaLabel: string;
43
+ markers?: readonly MapMarkerData[];
44
+ /** Groups markers that are close together into a count, which zooms in when chosen. */
45
+ cluster?: boolean;
46
+ onMarkerSelect?: (id: string) => void;
47
+ /** A line through these points, in order. */
48
+ line?: readonly LatLng[];
49
+ /** The map is fitted to the markers and the line when this changes (and at the start). Absent, only at the start. */
50
+ fitKey?: string | number;
51
+ /** The view when there is nothing to fit. */
52
+ center?: LatLng;
53
+ zoom?: number;
54
+ /** The person's own position, as a dot. */
55
+ position?: (LatLng & {
56
+ accuracyM?: number;
57
+ }) | null;
58
+ /** Makes the map a place to choose a point. */
59
+ pick?: MapPick;
60
+ /** Attribution the style's sources do not carry, shown with it. */
61
+ attribution?: string | readonly string[];
62
+ /**
63
+ * The address of MapLibre's worker script (`maplibre-gl-worker.mjs`), which the app serves from its own origin so that no `blob:` worker is needed: the app's CSP then says `worker-src 'self'`.
64
+ * Absent, MapLibre makes its own `blob:` worker, which needs `worker-src blob:`.
65
+ */
66
+ workerUrl?: string;
67
+ /** Origins besides the page's and the style's own that the map may fetch from. Normally none: the style's tiles, glyphs and sprite are the app's own. */
68
+ allowedOrigins?: readonly string[];
69
+ /** Called when the map or its style cannot be loaded; the message holds no address. */
70
+ onError?: (message: string) => void;
71
+ className?: string;
72
+ }
73
+ /**
74
+ * A map in the suite's style (`@sovereignfs/ui/map`, its own entry so that an app with no map carries no MapLibre). MapLibre GL JS draws it from **a style the app serves** (`styleUrl`), so the app decides
75
+ * its tiles, glyphs and sprite, and **the map makes no request to any address the app did not give** (`isAllowedRequest`).
76
+ *
77
+ * - **Markers** are real buttons with an accessible label, in token colours, which a keyboard reaches and a screen reader names; with `cluster`, those close together become one button with a count.
78
+ * - **A line** through points, **fit to points**, and **the person's position** as a dot.
79
+ * - **Choosing a point** (`pick`): a click or tap picks that point; with the map focused, the arrow keys move it and Enter picks its middle (MapLibre's own keyboard handling pans and zooms it).
80
+ * - **Attribution** is MapLibre's, from the style's sources, with any `attribution` added.
81
+ *
82
+ * It needs `maplibre-gl` (an optional peer of this package), and the app's CSP needs `worker-src` (see `workerUrl`). Draw a list of the same places beside it: a map is never the only way to reach them.
83
+ */
84
+ declare function Map({ styleUrl, ariaLabel, markers, cluster, onMarkerSelect, line, fitKey, center, zoom, position, pick, attribution, workerUrl, allowedOrigins, onError, className, }: MapProps): react.JSX.Element;
85
+
86
+ export { Map, isAllowedRequest };
87
+ export type { LatLng, MapMarkerData, MapMarkerTone, MapPick, MapProps };
package/dist/map.js ADDED
@@ -0,0 +1,384 @@
1
+ 'use client';
2
+ import {
3
+ usePrefersReducedMotion
4
+ } from "./chunk-E24U223W.js";
5
+
6
+ // src/components/Map/Map.tsx
7
+ import "maplibre-gl/dist/maplibre-gl.css";
8
+ import { useEffect, useRef, useState } from "react";
9
+ import styles from "./Map.module.css";
10
+
11
+ // src/components/Map/mapModel.ts
12
+ var isLatLng = (value) => typeof value === "object" && value !== null && typeof value.lat === "number" && typeof value.lng === "number" && Number.isFinite(value.lat) && Number.isFinite(value.lng) && Math.abs(value.lat) <= 90 && Math.abs(value.lng) <= 180;
13
+ function isAllowedRequest(url, options) {
14
+ if (url.startsWith("blob:") || url.startsWith("data:")) return true;
15
+ let target;
16
+ try {
17
+ target = new URL(url, options.base);
18
+ } catch {
19
+ return false;
20
+ }
21
+ if (target.protocol === "blob:" || target.protocol === "data:") return true;
22
+ const allowed = /* @__PURE__ */ new Set([new URL(options.base).origin, ...options.allowedOrigins ?? []]);
23
+ return allowed.has(target.origin);
24
+ }
25
+ function boundsOf(points) {
26
+ if (points.length === 0) return void 0;
27
+ let west = Infinity;
28
+ let south = Infinity;
29
+ let east = -Infinity;
30
+ let north = -Infinity;
31
+ for (const point of points) {
32
+ west = Math.min(west, point.lng);
33
+ east = Math.max(east, point.lng);
34
+ south = Math.min(south, point.lat);
35
+ north = Math.max(north, point.lat);
36
+ }
37
+ return [
38
+ [west, south],
39
+ [east, north]
40
+ ];
41
+ }
42
+ function lineFeature(points) {
43
+ return {
44
+ type: "Feature",
45
+ properties: {},
46
+ geometry: {
47
+ type: "LineString",
48
+ coordinates: points.map((point) => [point.lng, point.lat])
49
+ }
50
+ };
51
+ }
52
+ function groupMarkers(markers, cellPx = 56) {
53
+ const cells = /* @__PURE__ */ new Map();
54
+ const order = [];
55
+ for (const marker of markers) {
56
+ const key = `${Math.floor(marker.x / cellPx)}:${Math.floor(marker.y / cellPx)}`;
57
+ const cell = cells.get(key);
58
+ if (cell) cell.push(marker);
59
+ else {
60
+ cells.set(key, [marker]);
61
+ order.push(key);
62
+ }
63
+ }
64
+ return order.map((key) => {
65
+ const members = cells.get(key);
66
+ const first = members[0];
67
+ if (members.length === 1) return { kind: "point", id: first.id };
68
+ const ids = members.map((member) => member.id);
69
+ return {
70
+ kind: "cluster",
71
+ key: `c:${ids.join(",")}`,
72
+ ids,
73
+ x: members.reduce((sum, member) => sum + member.x, 0) / members.length,
74
+ y: members.reduce((sum, member) => sum + member.y, 0) / members.length
75
+ };
76
+ });
77
+ }
78
+ var clusterLabel = (count) => `${count} places close together. Press to zoom in.`;
79
+
80
+ // src/components/Map/Map.tsx
81
+ import { jsx } from "react/jsx-runtime";
82
+ var TONE_VAR = {
83
+ accent: "--sv-color-accent",
84
+ success: "--sv-color-success-solid",
85
+ warning: "--sv-color-warning-text",
86
+ error: "--sv-color-error-solid",
87
+ neutral: "--sv-color-text-muted"
88
+ };
89
+ var LINE_SOURCE = "sv-map-line";
90
+ var LINE_LAYER = "sv-map-line-layer";
91
+ var FIT_PADDING = 56;
92
+ var SINGLE_POINT_ZOOM = 14;
93
+ function Map2({
94
+ styleUrl,
95
+ ariaLabel,
96
+ markers = [],
97
+ cluster = false,
98
+ onMarkerSelect,
99
+ line,
100
+ fitKey,
101
+ center,
102
+ zoom,
103
+ position,
104
+ pick,
105
+ attribution,
106
+ workerUrl,
107
+ allowedOrigins,
108
+ onError,
109
+ className
110
+ }) {
111
+ const rootRef = useRef(null);
112
+ const mapRef = useRef(null);
113
+ const libRef = useRef(null);
114
+ const [ready, setReady] = useState(false);
115
+ const [styleVersion, setStyleVersion] = useState(0);
116
+ const reducedMotion = usePrefersReducedMotion();
117
+ const latest = useRef({ onMarkerSelect, pick, onError, reducedMotion, markers, line });
118
+ latest.current = { onMarkerSelect, pick, onError, reducedMotion, markers, line };
119
+ useEffect(() => {
120
+ const root = rootRef.current;
121
+ if (!root) return;
122
+ let cancelled = false;
123
+ let made = null;
124
+ void import("maplibre-gl").then((lib) => {
125
+ if (cancelled) return;
126
+ libRef.current = lib;
127
+ if (workerUrl) lib.setWorkerUrl(workerUrl);
128
+ const base = window.location.href;
129
+ const custom = attribution === void 0 ? void 0 : [attribution].flat();
130
+ made = new lib.Map({
131
+ container: root,
132
+ style: styleUrl,
133
+ center: center ? [center.lng, center.lat] : [0, 20],
134
+ zoom: zoom ?? 1.5,
135
+ attributionControl: {
136
+ compact: true,
137
+ ...custom ? { customAttribution: custom } : {}
138
+ },
139
+ // Only the addresses the app gave: anything else is turned into a request that cannot succeed.
140
+ transformRequest: (url) => isAllowedRequest(url, {
141
+ base: new URL(styleUrl, base).href,
142
+ ...allowedOrigins ? { allowedOrigins } : {}
143
+ }) || isAllowedRequest(url, { base, ...allowedOrigins ? { allowedOrigins } : {} }) ? { url } : { url: "data:," }
144
+ });
145
+ mapRef.current = made;
146
+ made.on("load", () => setReady(true));
147
+ made.on("style.load", () => setStyleVersion((version) => version + 1));
148
+ made.on("error", () => latest.current.onError?.("The map could not be loaded."));
149
+ made.on("click", (event) => {
150
+ const choose = latest.current.pick;
151
+ if (choose) choose.onPick({ lat: event.lngLat.lat, lng: event.lngLat.lng });
152
+ });
153
+ }).catch(() => latest.current.onError?.("The map could not be loaded."));
154
+ return () => {
155
+ cancelled = true;
156
+ made?.remove();
157
+ mapRef.current = null;
158
+ setReady(false);
159
+ };
160
+ }, []);
161
+ const shownStyle = useRef(styleUrl);
162
+ useEffect(() => {
163
+ const map = mapRef.current;
164
+ if (!map || !ready || shownStyle.current === styleUrl) return;
165
+ shownStyle.current = styleUrl;
166
+ map.setStyle(styleUrl);
167
+ }, [styleUrl, ready]);
168
+ useEffect(() => {
169
+ const map = mapRef.current;
170
+ if (!map || !ready) return;
171
+ const points = (line ?? []).filter(isLatLng);
172
+ const existing = map.getSource(LINE_SOURCE);
173
+ if (points.length < 2) {
174
+ if (map.getLayer(LINE_LAYER)) map.removeLayer(LINE_LAYER);
175
+ if (existing) map.removeSource(LINE_SOURCE);
176
+ return;
177
+ }
178
+ const feature = lineFeature(points);
179
+ if (existing) {
180
+ existing.setData(feature);
181
+ return;
182
+ }
183
+ const colour = getComputedStyle(rootRef.current ?? document.body).getPropertyValue("--sv-color-accent").trim() || "#000000";
184
+ map.addSource(LINE_SOURCE, { type: "geojson", data: feature });
185
+ map.addLayer({
186
+ id: LINE_LAYER,
187
+ type: "line",
188
+ source: LINE_SOURCE,
189
+ layout: { "line-join": "round", "line-cap": "round" },
190
+ paint: { "line-color": colour, "line-width": 3, "line-opacity": 0.9 }
191
+ });
192
+ }, [line, ready, styleVersion]);
193
+ const drawn = useRef(new globalThis.Map());
194
+ useEffect(() => {
195
+ const map = mapRef.current;
196
+ const lib = libRef.current;
197
+ if (!map || !lib || !ready) return;
198
+ const valid = markers.filter(isLatLng);
199
+ const byId = {};
200
+ for (const marker of valid) byId[marker.id] = marker;
201
+ const keep = /* @__PURE__ */ new Set();
202
+ const place = (key, make, at) => {
203
+ keep.add(key);
204
+ const existing = drawn.current.get(key);
205
+ if (existing) {
206
+ existing.setLngLat([at.lng, at.lat]);
207
+ return;
208
+ }
209
+ const element = make();
210
+ drawn.current.set(
211
+ key,
212
+ new lib.Marker({ element, anchor: "center" }).setLngLat([at.lng, at.lat]).addTo(map)
213
+ );
214
+ };
215
+ const render = () => {
216
+ keep.clear();
217
+ const groups = cluster ? groupMarkers(
218
+ valid.map((marker) => {
219
+ const point = map.project([marker.lng, marker.lat]);
220
+ return { id: marker.id, x: point.x, y: point.y };
221
+ })
222
+ ) : valid.map((marker) => ({ kind: "point", id: marker.id }));
223
+ for (const group of groups) {
224
+ if (group.kind === "point") {
225
+ const marker = byId[group.id];
226
+ const key = `p:${marker.id}:${marker.tone ?? "accent"}:${marker.selected ? 1 : 0}:${marker.label}`;
227
+ place(
228
+ key,
229
+ () => {
230
+ const button = document.createElement("button");
231
+ button.type = "button";
232
+ button.className = [
233
+ styles.marker,
234
+ styles[marker.tone ?? "accent"],
235
+ marker.selected ? styles.selected : ""
236
+ ].filter(Boolean).join(" ");
237
+ button.setAttribute("aria-label", marker.label);
238
+ button.title = marker.label;
239
+ button.style.setProperty(
240
+ "--marker-colour",
241
+ `var(${TONE_VAR[marker.tone ?? "accent"]})`
242
+ );
243
+ button.addEventListener("click", (event) => {
244
+ event.stopPropagation();
245
+ latest.current.onMarkerSelect?.(marker.id);
246
+ });
247
+ return button;
248
+ },
249
+ marker
250
+ );
251
+ } else {
252
+ const members = group.ids.map((id) => byId[id]);
253
+ const at = map.unproject([group.x, group.y]);
254
+ place(
255
+ group.key,
256
+ () => {
257
+ const button = document.createElement("button");
258
+ button.type = "button";
259
+ button.className = `${styles.marker} ${styles.cluster}`;
260
+ button.textContent = String(members.length);
261
+ button.setAttribute("aria-label", clusterLabel(members.length));
262
+ button.addEventListener("click", (event) => {
263
+ event.stopPropagation();
264
+ const box = boundsOf(members);
265
+ if (box)
266
+ map.fitBounds(box, {
267
+ padding: FIT_PADDING,
268
+ maxZoom: 18,
269
+ animate: !latest.current.reducedMotion
270
+ });
271
+ });
272
+ return button;
273
+ },
274
+ { lat: at.lat, lng: at.lng }
275
+ );
276
+ }
277
+ }
278
+ for (const [key, marker] of drawn.current) {
279
+ if (keep.has(key)) continue;
280
+ marker.remove();
281
+ drawn.current.delete(key);
282
+ }
283
+ };
284
+ render();
285
+ if (cluster) map.on("moveend", render);
286
+ return () => {
287
+ if (cluster) map.off("moveend", render);
288
+ };
289
+ }, [markers, cluster, ready]);
290
+ useEffect(
291
+ () => () => {
292
+ for (const marker of drawn.current.values()) marker.remove();
293
+ drawn.current.clear();
294
+ },
295
+ []
296
+ );
297
+ const dot = useRef(null);
298
+ useEffect(() => {
299
+ const map = mapRef.current;
300
+ const lib = libRef.current;
301
+ if (!map || !lib || !ready) return;
302
+ if (!position || !isLatLng(position)) {
303
+ dot.current?.remove();
304
+ dot.current = null;
305
+ return;
306
+ }
307
+ if (!dot.current) {
308
+ const element = document.createElement("div");
309
+ element.className = styles.position ?? "";
310
+ element.setAttribute("role", "img");
311
+ element.setAttribute("aria-label", "Your position");
312
+ dot.current = new lib.Marker({ element, anchor: "center" }).setLngLat([position.lng, position.lat]).addTo(map);
313
+ } else dot.current.setLngLat([position.lng, position.lat]);
314
+ return void 0;
315
+ }, [position, ready]);
316
+ useEffect(
317
+ () => () => {
318
+ dot.current?.remove();
319
+ },
320
+ []
321
+ );
322
+ const pin = useRef(null);
323
+ const picked = pick?.value;
324
+ useEffect(() => {
325
+ const map = mapRef.current;
326
+ const lib = libRef.current;
327
+ if (!map || !lib || !ready) return;
328
+ if (!picked || !isLatLng(picked)) {
329
+ pin.current?.remove();
330
+ pin.current = null;
331
+ return;
332
+ }
333
+ if (!pin.current) {
334
+ const element = document.createElement("div");
335
+ element.className = styles.pin ?? "";
336
+ element.setAttribute("role", "img");
337
+ element.setAttribute("aria-label", "Chosen point");
338
+ pin.current = new lib.Marker({ element, anchor: "bottom" }).setLngLat([picked.lng, picked.lat]).addTo(map);
339
+ } else pin.current.setLngLat([picked.lng, picked.lat]);
340
+ }, [picked, ready]);
341
+ useEffect(
342
+ () => () => {
343
+ pin.current?.remove();
344
+ },
345
+ []
346
+ );
347
+ useEffect(() => {
348
+ const map = mapRef.current;
349
+ if (!map || !ready) return;
350
+ const points = [...latest.current.markers, ...latest.current.line ?? []].filter(isLatLng);
351
+ const box = boundsOf(points);
352
+ if (!box) return;
353
+ const animate = !latest.current.reducedMotion;
354
+ if (points.length === 1) {
355
+ const only = points[0];
356
+ map.easeTo({ center: [only.lng, only.lat], zoom: SINGLE_POINT_ZOOM, animate });
357
+ } else map.fitBounds(box, { padding: FIT_PADDING, maxZoom: 16, animate });
358
+ }, [fitKey, ready]);
359
+ return (
360
+ // The map is a region; MapLibre makes its canvas focusable, and its own keyboard handling pans and zooms it. With `pick`, Enter on the focused map chooses its middle.
361
+ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- a map is a focusable region with keyboard handling of its own; Enter picks only while choosing a point
362
+ /* @__PURE__ */ jsx(
363
+ "div",
364
+ {
365
+ ref: rootRef,
366
+ role: "region",
367
+ "aria-label": ariaLabel,
368
+ className: [styles.root, pick ? styles.picking : "", className].filter(Boolean).join(" "),
369
+ onKeyDown: (event) => {
370
+ if (!pick || event.key !== "Enter") return;
371
+ if (event.target instanceof HTMLButtonElement) return;
372
+ const middle = mapRef.current?.getCenter();
373
+ if (!middle) return;
374
+ event.preventDefault();
375
+ pick.onPick({ lat: middle.lat, lng: middle.lng });
376
+ }
377
+ }
378
+ )
379
+ );
380
+ }
381
+ export {
382
+ Map2 as Map,
383
+ isAllowedRequest
384
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sovereignfs/ui",
3
- "version": "0.91.0",
3
+ "version": "0.96.1",
4
4
  "type": "module",
5
5
  "description": "Sovereign Design System — design tokens and React components.",
6
6
  "keywords": [
@@ -37,7 +37,11 @@
37
37
  "./tokens.css": "./dist/tokens.css",
38
38
  "./tokens/primitives.css": "./dist/tokens/primitives.css",
39
39
  "./tokens/semantic.css": "./dist/tokens/semantic.css",
40
- "./tokens/theme-presets.css": "./dist/tokens/theme-presets.css"
40
+ "./tokens/theme-presets.css": "./dist/tokens/theme-presets.css",
41
+ "./map": {
42
+ "types": "./dist/map.d.ts",
43
+ "default": "./dist/map.js"
44
+ }
41
45
  },
42
46
  "files": [
43
47
  "dist",
@@ -48,6 +52,7 @@
48
52
  "peerDependencies": {
49
53
  "@dnd-kit/core": "^6.3.1",
50
54
  "@dnd-kit/sortable": "^10.0.0",
55
+ "maplibre-gl": "^6.17.0",
51
56
  "react": "^19.0.0",
52
57
  "react-dom": "^19.0.0"
53
58
  },
@@ -57,6 +62,9 @@
57
62
  },
58
63
  "@dnd-kit/sortable": {
59
64
  "optional": true
65
+ },
66
+ "maplibre-gl": {
67
+ "optional": true
60
68
  }
61
69
  },
62
70
  "devDependencies": {
@@ -72,6 +80,7 @@
72
80
  "@types/node": "^24.19.2",
73
81
  "@types/react": "^19.3.0",
74
82
  "@types/react-dom": "^19.3.0",
83
+ "maplibre-gl": "^6.17.0",
75
84
  "react": "^19.3.1",
76
85
  "react-dom": "^19.3.1",
77
86
  "storybook": "^10.6.0",