@krizaka/ui 3.76.0 → 3.77.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 (52) hide show
  1. package/dist/blocks.css +14 -0
  2. package/dist/chunk-NM2DEHFZ.js +25 -0
  3. package/dist/chunk-NM2DEHFZ.js.map +1 -0
  4. package/dist/document-viewer.d.ts +23 -6
  5. package/dist/document-viewer.js +21 -5
  6. package/dist/document-viewer.js.map +1 -1
  7. package/dist/map/cards.d.ts +145 -0
  8. package/dist/map/cards.js +74 -0
  9. package/dist/map/cards.js.map +1 -0
  10. package/dist/map/pin.d.ts +57 -0
  11. package/dist/map/pin.js +53 -0
  12. package/dist/map/pin.js.map +1 -0
  13. package/dist/map/sheet.d.ts +80 -0
  14. package/dist/map/sheet.js +61 -0
  15. package/dist/map/sheet.js.map +1 -0
  16. package/dist/map.d.ts +41 -14
  17. package/dist/map.js +85 -112
  18. package/dist/map.js.map +1 -1
  19. package/dist/native/map.d.ts +29 -10
  20. package/dist/native/map.js +81 -107
  21. package/dist/native/map.js.map +1 -1
  22. package/dist/shop/services.js +1 -1
  23. package/dist/shop/services.js.map +1 -1
  24. package/dist/shop-composer.js +1 -1
  25. package/dist/shop-composer.js.map +1 -1
  26. package/dist/shop-gallery.js +2 -2
  27. package/dist/shop-gallery.js.map +1 -1
  28. package/dist/wall.d.ts +10 -5
  29. package/dist/wall.js +10 -4
  30. package/dist/wall.js.map +1 -1
  31. package/package.json +53 -8
  32. package/registry/app-frame.json +1 -1
  33. package/registry/document-viewer.json +9 -8
  34. package/registry/examples/document-viewer/highlights.js +2 -1
  35. package/registry/examples/document-viewer/highlights.tsx +3 -0
  36. package/registry/examples/map/pins.d.ts +4 -0
  37. package/registry/examples/map/pins.js +20 -0
  38. package/registry/examples/map/pins.tsx +27 -0
  39. package/registry/examples/map/place-sheet.d.ts +4 -0
  40. package/registry/examples/map/place-sheet.js +34 -0
  41. package/registry/examples/map/place-sheet.tsx +35 -0
  42. package/registry/examples/wall/tidy.d.ts +4 -0
  43. package/registry/examples/wall/tidy.js +27 -0
  44. package/registry/examples/wall/tidy.tsx +19 -0
  45. package/registry/index.json +9 -9
  46. package/registry/map.json +81 -13
  47. package/registry/nav-bar.json +1 -1
  48. package/registry/rail-nav.json +1 -1
  49. package/registry/shop-gallery.json +1 -1
  50. package/registry/shop.json +2 -2
  51. package/registry/site-footer.json +1 -1
  52. package/registry/wall.json +24 -2
package/registry/map.json CHANGED
@@ -42,7 +42,10 @@
42
42
  "Always pass a `fallback` (`StaticMap` with the same centre and places): it shows while the engine loads and for good without WebGL.",
43
43
  "Motion on a map: `Marker drop={index * 90}` drops pins in turn, `Route` draws its line once (and a `courier` makes one trip, `repeatAfter` repeats it while the map is on screen), `Pulse` beats around a hot spot. The drawing is finite — nothing runs afterwards — and everything is in place at once under reduced motion.",
44
44
  "Ask for the position only on a press (`LocationPicker`'s Near me), never on load; every refusal has its words.",
45
+ "`variant` is the look: `plain` (the product register, default), `notebook` (the Cahier — paper and ink, a cluster as a manila tag, a lone place in the margin's red). `scheme=\"auto\"` (default) follows the page; `dark` or `light` pins it. Both come from the tokens — never a hand-written map style.",
46
+ "`MapPin` (from `@krizaka/ui/map/pin`) is the marker's face when the dot is not enough: put it in a `Marker`'s children. Its state is also said by shape (hollow visited, dashed closed, larger selected).",
45
47
  "Keep the attribution visible (OpenStreetMap's licence, the ODbL, asks for it): the components draw it.",
48
+ "Import the place sheet from `@krizaka/ui/map/sheet` (`MapSheet`) and the cards from `@krizaka/ui/map/cards` (`MapInfoCard`, `RouteCard`, `routeLinks`): their own entries, so a page that only draws a map does not pay for them.",
46
49
  "Install the engine only where a map is shown: `maplibre-gl` (web) or `@maplibre/maplibre-react-native` (Expo) — optional peers."
47
50
  ],
48
51
  "accessibility": {
@@ -171,9 +174,9 @@
171
174
  },
172
175
  {
173
176
  "name": "scheme",
174
- "type": "\"light\" | \"dark\"",
177
+ "type": "MapScheme",
175
178
  "default": null,
176
- "description": "The scheme. Default: the page's (`html.light`), followed.",
179
+ "description": "The scheme: `auto` (default) follows the page (`html.light`) as it changes; `dark` or `light` pins it.",
177
180
  "required": false
178
181
  },
179
182
  {
@@ -323,9 +326,16 @@
323
326
  },
324
327
  {
325
328
  "name": "scheme",
326
- "type": "\"light\" | \"dark\"",
329
+ "type": "MapScheme",
330
+ "default": "auto",
331
+ "description": "The scheme: `auto` (default) follows the page (`html.light`) as it changes; `dark` or `light` pins it.",
332
+ "required": false
333
+ },
334
+ {
335
+ "name": "variant",
336
+ "type": "MapVariant",
327
337
  "default": null,
328
- "description": "The scheme. Default: the page's (`html.light`), followed.",
338
+ "description": "The look: `plain` (default), `notebook` (the Cahier: paper and ink, manila tags for clusters).",
329
339
  "required": false
330
340
  },
331
341
  {
@@ -657,6 +667,22 @@
657
667
  "module": "@krizaka/ui/registry/examples/map/route",
658
668
  "code": "\"use client\";\n\nimport { Button } from \"@krizaka/ui/button\";\nimport { Map, Marker, Pulse, Route, StaticMap } from \"@krizaka/ui/map\";\nimport * as React from \"react\";\n\nconst STUDIO = [-73.6005, 45.5229] as const;\nconst HOME = [-73.5695, 45.5268] as const;\nconst PATH = [STUDIO, [-73.5935, 45.5232], [-73.5862, 45.5159], [-73.5753, 45.5171], HOME] as const;\n\n// A delivery in Montréal: the pins drop (staggered), the route draws itself, a courier makes the trip, a demand pulse\n// beats at the destination. Under reduced motion everything is in place at once, the courier at the end.\nexport default function MapRoute() {\n const [run, setRun] = React.useState(0);\n return (\n <div className=\"flex w-full max-w-xl flex-col gap-3\">\n <Map\n key={run}\n label=\"A delivery from the studio to Parc La Fontaine\"\n center={[-73.585, 45.521]}\n zoom={13.2}\n className=\"h-80 w-full\"\n fallback={<StaticMap label=\"A delivery from the studio to Parc La Fontaine\" center={[-73.585, 45.521]} zoom={13.2} places={[{ position: STUDIO, label: \"Studio\" }, { position: HOME, label: \"Parc La Fontaine\" }]} />}\n >\n <Route path={PATH} label=\"Delivery from the studio to Parc La Fontaine, 3 km\" courier tripDuration={3600} />\n <Marker position={STUDIO} label=\"Studio\" drop={0} />\n <Marker position={HOME} label=\"Parc La Fontaine\" drop={260} />\n <Pulse position={HOME} label=\"Orders are picking up around Parc La Fontaine\" size={64} />\n </Map>\n <Button variant=\"secondary\" size=\"sm\" onClick={() => setRun((n) => n + 1)}>\n Replay\n </Button>\n </div>\n );\n}\n"
659
669
  },
670
+ {
671
+ "name": "place-sheet",
672
+ "title": "Place sheet",
673
+ "description": "A non-modal sheet over the map (snap points on a phone, a side card from md): an info card with one action and a route card that opens the person's own navigation app.",
674
+ "path": "examples/map/place-sheet.tsx",
675
+ "module": "@krizaka/ui/registry/examples/map/place-sheet",
676
+ "code": "\"use client\";\n\nimport { Button } from \"@krizaka/ui/button\";\nimport { StaticMap } from \"@krizaka/ui/map\";\nimport { MapInfoCard, RouteCard } from \"@krizaka/ui/map/cards\";\nimport { MapSheet, type MapSheetSnap } from \"@krizaka/ui/map/sheet\";\nimport * as React from \"react\";\n\nconst SHOP = [-73.5673, 45.5017] as const;\nconst ME = [-73.58, 45.51] as const;\n\n// A place on the map: the sheet rises over it WITHOUT blocking it (no scrim, no trap) — three snap points on a phone, a\n// card at the side from md. The info card says what the place is (one action); the route card opens the person's own\n// navigation app. The times are given by the host from a real source — here, demo values.\nexport default function MapPlaceSheet() {\n const [snap, setSnap] = React.useState<MapSheetSnap>(\"half\");\n return (\n <div className=\"relative h-[34rem] w-full max-w-3xl overflow-hidden rounded-xl border border-border-subtle\">\n <StaticMap label=\"Atelier Rose, Montréal\" center={[-73.575, 45.505]} zoom={13} places={[{ position: SHOP, label: \"Atelier Rose\" }]} />\n <MapSheet label=\"Atelier Rose\" handleLabel=\"Resize the panel\" snap={snap} onSnapChange={setSnap}>\n <div className=\"flex flex-col gap-5\">\n <MapInfoCard title=\"Atelier Rose\" meta=\"Hair salon · 1.4 km\" status=\"Open until 18:00\" action={<Button size=\"sm\">See the shop</Button>} />\n <RouteCard\n destination=\"Directions to Atelier Rose\"\n position={SHOP}\n origin={ME}\n directionsLabel=\"Open in\"\n appLabels={{ apple: \"Apple Maps\", google: \"Google Maps\", osm: \"OpenStreetMap\", waze: \"Waze\", transit: \"Transit\" }}\n times={[{ label: \"On foot\", value: \"18 min\" }, { label: \"By bike\", value: \"7 min\" }]}\n />\n </div>\n </MapSheet>\n </div>\n );\n}\n"
677
+ },
678
+ {
679
+ "name": "pins",
680
+ "title": "Pins",
681
+ "description": "MapPin in its three shapes (drop, disc, the Cahier's tag) and four states (default, selected, visited, closed): the state is said by shape as well as colour.",
682
+ "path": "examples/map/pins.tsx",
683
+ "module": "@krizaka/ui/registry/examples/map/pins",
684
+ "code": "import { MapPin, type MapPinShape, type MapPinState } from \"@krizaka/ui/map/pin\";\n\nconst SHAPES: MapPinShape[] = [\"drop\", \"disc\", \"tag\"];\nconst STATES: MapPinState[] = [\"default\", \"selected\", \"visited\", \"closed\"];\n\n// The pins of a map, in their three shapes and four states: the state is said by shape too (hollow = visited,\n// dashed = closed, larger = selected), so it never rests on colour alone.\nexport default function MapPins() {\n return (\n <div className=\"grid w-full max-w-xl grid-cols-[auto_repeat(4,1fr)] items-end gap-x-6 gap-y-5 rounded-xl border border-border-subtle bg-surface-1 p-5 text-xs text-fg-secondary\">\n <span />\n {STATES.map((state) => (\n <span key={state}>{state}</span>\n ))}\n {SHAPES.map((shape) => (\n <div key={shape} className=\"contents\">\n <span>{shape}</span>\n {STATES.map((state) => (\n <span key={state} className=\"flex h-12 items-end\">\n <MapPin shape={shape} state={state} size={26} />\n </span>\n ))}\n </div>\n ))}\n </div>\n );\n}\n"
685
+ },
660
686
  {
661
687
  "name": "static",
662
688
  "title": "Static map",
@@ -986,6 +1012,13 @@
986
1012
  "description": "Styles merged last (its height).",
987
1013
  "required": false
988
1014
  },
1015
+ {
1016
+ "name": "variant",
1017
+ "type": "MapVariant",
1018
+ "default": null,
1019
+ "description": "The look: `plain` (default), or `notebook` (the Cahier). The scheme is the app's (`auto`).",
1020
+ "required": false
1021
+ },
989
1022
  {
990
1023
  "name": "world",
991
1024
  "type": "MapRegion | null",
@@ -1035,13 +1068,25 @@
1035
1068
  "path": "map/assets.ts",
1036
1069
  "content": "// Where the basemap lives: Protomaps PMTiles extracts on the Krizaka CDN (Bunny), uploaded by tools/map-assets.mjs.\n// No API key, no metered service: one file per region, read by HTTP range requests. A new extract is a new file (its\n// build date in the name) and a new default here.\n\nconst CDN = \"https://krizaka-assets.b-cdn.net/maps/v1\";\n\n/** The basemap extracts: OpenStreetMap data built by Protomaps (ODbL). `world` up to zoom 6, `quebec` (Montréal–Québec) up to 14. */\nexport const MAP_TILES = {\n world: `${CDN}/tiles/world-20261012.pmtiles`,\n quebec: `${CDN}/tiles/quebec-20261012.pmtiles`,\n} as const;\n\n/** The glyphs of the labels (Noto Sans, SIL OFL): `{fontstack}` and `{range}` filled by MapLibre. */\nexport const MAP_GLYPHS = `${CDN}/fonts/{fontstack}/{range}.pbf`;\n\n/** The words every map shows, as the licences ask: OpenStreetMap's contributors (ODbL) and Protomaps. */\nexport const MAP_ATTRIBUTION = { osm: \"© OpenStreetMap contributors\", osmUrl: \"https://www.openstreetmap.org/copyright\", protomaps: \"Protomaps\", protomapsUrl: \"https://protomaps.com\" } as const;\n\nlet base: string | null = null;\n\n/**\n * Where the maps read the tiles and the glyphs, when not from the CDN itself: a same-origin path that proxies it\n * (`https://www.krizaka.com/maps/v1`, a rewrite of the site) — no cross-origin request at all. Absolute URL, no trailing slash.\n */\nexport function setMapAssetsBase(url: string | null) {\n base = url ? url.replace(/\\/+$/, \"\") : null;\n}\n\n/** The tiles and glyphs the maps read now: the CDN's, or under the base set by `setMapAssetsBase`. */\nexport function mapAssets() {\n const at = (u: string) => (base ? u.replace(CDN, base) : u);\n return { tiles: { world: at(MAP_TILES.world), quebec: at(MAP_TILES.quebec) }, glyphs: at(MAP_GLYPHS) };\n}\n"
1037
1070
  },
1071
+ {
1072
+ "path": "map/cards/index.ts",
1073
+ "content": "/**\n * @krizaka/ui/map/cards — what a place says under or beside the map: `MapInfoCard` (title, meta, status, one action),\n * `RouteCard` (the person's own navigation apps, optional times) and `routeLinks` (the deep links). Apart from `./map`, so\n * a page that only draws a map does not pay for them. Client (\"use client\").\n */\nexport { mapCard, MapInfoCard, type MapInfoCardProps, RouteCard, type RouteCardProps, type RouteTime } from \"./map-cards\";\nexport { ROUTE_APPS, type RouteApp, type RouteLinks, routeLinks } from \"./route-links\";\n"
1074
+ },
1075
+ {
1076
+ "path": "map/cards/map-cards.tsx",
1077
+ "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { tv } from \"../../tv\";\nimport type { LngLat } from \"../geo\";\nimport { ROUTE_APPS, type RouteApp, routeLinks } from \"./route-links\";\n\nexport const mapCard = tv({\n slots: {\n root: \"flex flex-col gap-2 text-fg\",\n photo: \"aspect-[16/9] w-full overflow-hidden rounded-xl bg-surface-2 [&>img]:h-full [&>img]:w-full [&>img]:object-cover\",\n title: \"text-base font-semibold leading-snug\",\n meta: \"text-sm text-fg-secondary\",\n status: \"w-fit rounded-md bg-surface-2 px-2 py-0.5 text-xs font-medium text-fg-secondary\",\n action: \"mt-1 flex\",\n times: \"grid grid-cols-[repeat(auto-fit,minmax(5.5rem,1fr))] gap-2 text-sm\",\n time: \"flex flex-col rounded-lg bg-surface-2 px-2.5 py-1.5\",\n timeLabel: \"text-xs text-fg-secondary\",\n menu: \"flex flex-wrap gap-2\",\n link: \"rounded-md border border-border-default px-3 py-1.5 text-sm font-medium text-fg hover:bg-surface-2 focus-visible:outline-2 focus-visible:outline-border-focus\",\n },\n});\n\nexport type MapInfoCardProps = Omit<React.ComponentProps<\"article\">, \"title\"> & {\n title: React.ReactNode;\n /** The heading level of the title. Default 3. */\n titleLevel?: 2 | 3 | 4;\n /** A picture (an img or next/image); supply its alt text. Absent: no photo area. */\n photo?: React.ReactNode;\n /** One line under the title: category, distance, hours. */\n meta?: React.ReactNode;\n /** A short honest status (\"Open now\", \"In development\"). */\n status?: React.ReactNode;\n /** The one action (a Button or a link); the card carries no second one. */\n action?: React.ReactNode;\n};\n\n/** What a place says about itself on a map: photo, title, one meta line, a status and ONE action — every field optional. */\nexport function MapInfoCard({ title, titleLevel = 3, photo, meta, status, action, className, ...props }: MapInfoCardProps) {\n const s = mapCard();\n const Heading = `h${titleLevel}` as \"h3\";\n return (\n <article {...props} className={s.root({ className })}>\n {photo ? <div className={s.photo()}>{photo}</div> : null}\n <Heading className={s.title()}>{title}</Heading>\n {meta ? <p className={s.meta()}>{meta}</p> : null}\n {status ? <p className={s.status()}>{status}</p> : null}\n {action ? <div className={s.action()}>{action}</div> : null}\n </article>\n );\n}\n\nexport type RouteTime = { /** \"On foot\", \"By bike\" — translated. */ label: string; /** \"12 min\" — formatted by the host from a real source. */ value: string };\n\nexport type RouteCardProps = Omit<React.ComponentProps<\"section\">, \"title\"> & {\n /** The destination's name. */\n destination: React.ReactNode;\n /** Where it is, for the links. */\n position: LngLat;\n /** Where the person is, when known: the links then start there. */\n origin?: LngLat;\n /** The heading of the links (\"Directions\"). */\n directionsLabel: string;\n /** The apps' names, translated or not (\"Apple Maps\", \"Google Maps\", \"OpenStreetMap\", \"Waze\", \"Transit\"). */\n appLabels: Record<RouteApp, string>;\n /** Honest times, computed by the host from a real source (never invented here). Absent: no row. */\n times?: readonly RouteTime[];\n /** The apps shown, in order. Default all five. */\n apps?: readonly RouteApp[];\n};\n\n/** A destination, the times the host knows, and the « Directions » links to the person's own navigation app. */\nexport function RouteCard({ destination, position, origin, directionsLabel, appLabels, times, apps = ROUTE_APPS, className, ...props }: RouteCardProps) {\n const s = mapCard();\n const links = routeLinks(position, origin);\n const id = React.useId();\n return (\n <section {...props} aria-labelledby={id} className={s.root({ className })}>\n <h3 id={id} className={s.title()}>{destination}</h3>\n {times?.length ? (\n <dl className={s.times()}>\n {times.map((t) => (\n <div key={t.label} className={s.time()}>\n <dt className={s.timeLabel()}>{t.label}</dt>\n <dd>{t.value}</dd>\n </div>\n ))}\n </dl>\n ) : null}\n <nav aria-label={directionsLabel}>\n <ul className={s.menu()}>\n {apps.map((app) => (\n <li key={app}>\n <a className={s.link()} href={links[app]} target=\"_blank\" rel=\"noopener noreferrer\">\n {appLabels[app]}\n </a>\n </li>\n ))}\n </ul>\n </nav>\n </section>\n );\n}\n"
1078
+ },
1079
+ {
1080
+ "path": "map/cards/route-links.ts",
1081
+ "content": "// Server-safe, pure. The links that open a destination in the person's own navigation app: Apple Maps, Google Maps,\n// OpenStreetMap, Waze and public transit. No key, no request: a URL each, opened by the person.\nimport type { LngLat } from \"../geo\";\n\nexport type RouteLinks = {\n apple: string;\n google: string;\n osm: string;\n waze: string;\n /** Google Maps in transit mode: the only one of the five that plans buses and metro without an account. */\n transit: string;\n};\n\nexport type RouteApp = keyof RouteLinks;\n\n/** The apps in the order a menu shows them. */\nexport const ROUTE_APPS: readonly RouteApp[] = [\"apple\", \"google\", \"osm\", \"waze\", \"transit\"];\n\nconst at = ([lng, lat]: LngLat) => `${round(lat)},${round(lng)}`;\nconst round = (n: number) => Math.round(n * 1e6) / 1e6;\n\n/** One URL per navigation app for a trip to `destination` (from `origin` when known, else from where the app finds the person). */\nexport function routeLinks(destination: LngLat, origin?: LngLat): RouteLinks {\n const to = at(destination);\n const from = origin ? at(origin) : undefined;\n const google = (mode: string) => `https://www.google.com/maps/dir/?api=1&destination=${to}${from ? `&origin=${from}` : \"\"}&travelmode=${mode}`;\n return {\n apple: `https://maps.apple.com/?daddr=${to}${from ? `&saddr=${from}` : \"\"}&dirflg=d`,\n google: google(\"driving\"),\n osm: from\n ? `https://www.openstreetmap.org/directions?engine=fossgis_osrm_car&route=${from};${to}`\n : `https://www.openstreetmap.org/?mlat=${round(destination[1])}&mlon=${round(destination[0])}#map=16/${to.replace(\",\", \"/\")}`,\n waze: `https://waze.com/ul?ll=${to}&navigate=yes`,\n transit: google(\"transit\"),\n };\n}\n"
1082
+ },
1038
1083
  {
1039
1084
  "path": "map/geo.ts",
1040
1085
  "content": "/// <reference types=\"geojson\" />\n\n// Plain geometry for the maps, web and native (no DOM, no React): distances, circles, the Web Mercator projection.\n\n/** A position: longitude, latitude (GeoJSON's order, MapLibre's `LngLat`). */\nexport type LngLat = readonly [lng: number, lat: number];\n\nconst R = 6_371_008.8;\nconst rad = (d: number) => (d * Math.PI) / 180;\n\n/** The great-circle distance between two positions, in metres (haversine). */\nexport function distanceMeters(a: LngLat, b: LngLat): number {\n const dLat = rad(b[1] - a[1]);\n const dLng = rad(b[0] - a[0]);\n const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a[1])) * Math.cos(rad(b[1])) * Math.sin(dLng / 2) ** 2;\n return 2 * R * Math.asin(Math.min(1, Math.sqrt(h)));\n}\n\n/** A circle of `radius` metres around `center` as a GeoJSON polygon (`steps` points): a delivery zone, a search radius. */\nexport function circlePolygon(center: LngLat, radius: number, steps = 64): GeoJSON.Feature<GeoJSON.Polygon> {\n const [lng, lat] = center;\n const d = radius / R;\n const ring: [number, number][] = [];\n for (let i = 0; i <= steps; i++) {\n const brg = (2 * Math.PI * i) / steps;\n const lat2 = Math.asin(Math.sin(rad(lat)) * Math.cos(d) + Math.cos(rad(lat)) * Math.sin(d) * Math.cos(brg));\n const lng2 = rad(lng) + Math.atan2(Math.sin(brg) * Math.sin(d) * Math.cos(rad(lat)), Math.cos(d) - Math.sin(rad(lat)) * Math.sin(lat2));\n ring.push([(lng2 * 180) / Math.PI, (lat2 * 180) / Math.PI]);\n }\n return { type: \"Feature\", properties: {}, geometry: { type: \"Polygon\", coordinates: [ring] } };\n}\n\n/** The Web Mercator pixel of a position at a zoom (256-px tiles): what a static map draws without an engine. */\nexport function project([lng, lat]: LngLat, zoom: number): [number, number] {\n const scale = 256 * 2 ** zoom;\n const s = Math.sin(rad(Math.max(-85.0511, Math.min(85.0511, lat))));\n return [((lng + 180) / 360) * scale, (0.5 - Math.log((1 + s) / (1 - s)) / (4 * Math.PI)) * scale];\n}\n\n/** A distance written the locale's way: metres under 1 km, kilometres (one decimal under 10) above. */\nexport function formatDistance(meters: number, locale: string): string {\n if (meters < 1000) return new Intl.NumberFormat(locale, { style: \"unit\", unit: \"meter\", maximumFractionDigits: 0 }).format(Math.round(meters / 10) * 10);\n return new Intl.NumberFormat(locale, { style: \"unit\", unit: \"kilometer\", maximumFractionDigits: meters < 10_000 ? 1 : 0 }).format(meters / 1000);\n}\n\n/** The length of a path of positions, in metres (the sum of its great-circle legs). */\nexport function pathLength(path: readonly LngLat[]): number {\n let total = 0;\n for (let i = 1; i < path.length; i++) total += distanceMeters(path[i - 1]!, path[i]!);\n return total;\n}\n\n/** The position at `fraction` (0–1, clamped) of the path's length, with the heading of the leg it is on (degrees clockwise from north). */\nexport function pointAlong(path: readonly LngLat[], fraction: number): { position: LngLat; heading: number } {\n const first = path[0] ?? [0, 0];\n if (path.length < 2) return { position: first, heading: 0 };\n const target = Math.max(0, Math.min(1, fraction)) * pathLength(path);\n let walked = 0;\n for (let i = 1; i < path.length; i++) {\n const a = path[i - 1]!;\n const b = path[i]!;\n const leg = distanceMeters(a, b);\n if (walked + leg >= target || i === path.length - 1) {\n const t = leg === 0 ? 0 : Math.max(0, Math.min(1, (target - walked) / leg));\n const heading = (Math.atan2(b[0] - a[0], b[1] - a[1]) * 180) / Math.PI;\n return { position: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t], heading: (heading + 360) % 360 };\n }\n walked += leg;\n }\n return { position: first, heading: 0 };\n}\n\n/** The first `fraction` (0–1) of the path, as a GeoJSON line: what a route has drawn so far. */\nexport function sliceLine(path: readonly LngLat[], fraction: number): GeoJSON.Feature<GeoJSON.LineString> {\n const f = Math.max(0, Math.min(1, fraction));\n const total = pathLength(path);\n const coordinates: [number, number][] = [];\n if (path.length) coordinates.push([...path[0]!] as [number, number]);\n let walked = 0;\n for (let i = 1; i < path.length && f > 0; i++) {\n const a = path[i - 1]!;\n const b = path[i]!;\n const leg = distanceMeters(a, b);\n if (walked + leg <= f * total) coordinates.push([...b] as [number, number]);\n else {\n const t = leg === 0 ? 0 : (f * total - walked) / leg;\n coordinates.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);\n break;\n }\n walked += leg;\n }\n if (coordinates.length === 1) coordinates.push([...coordinates[0]!]);\n return { type: \"Feature\", properties: {}, geometry: { type: \"LineString\", coordinates } };\n}\n"
1041
1086
  },
1042
1087
  {
1043
1088
  "path": "map/index.ts",
1044
- "content": "/**\n * @krizaka/ui/map — maps on MapLibre GL JS (open source) over Protomaps tiles on the Krizaka CDN, styled from the\n * tokens: `Map`, `Marker`, `Cluster`, `UserPosition`, `RadiusCircle`, `LocationPicker`, `StaticMap` (the fallback), the\n * style (`mapStyle`, `mapPalette`) and the geometry (`distanceMeters`, `circlePolygon`, `formatDistance`). maplibre-gl\n * and pmtiles are optional peers, loaded when a map is shown. Client (\"use client\").\n */\nexport { MAP_ATTRIBUTION, MAP_GLYPHS, MAP_TILES, mapAssets, setMapAssetsBase } from \"./assets\";\nexport { circlePolygon, distanceMeters, formatDistance, type LngLat, pathLength, pointAlong, project, sliceLine } from \"./geo\";\nexport { LocationPicker, locationPicker, type LocationPickerLabels, locationPickerLabels, type LocationPickerProps } from \"./location-picker\";\nexport {\n Cluster,\n type ClusterPoint,\n type ClusterProps,\n configureMaps,\n Map,\n map,\n type MapLabels,\n mapLabels,\n type MapProps,\n Marker,\n type MarkerProps,\n Pulse,\n type PulseProps,\n RadiusCircle,\n type RadiusCircleProps,\n Route,\n type RouteProps,\n useMap,\n UserPosition,\n type UserPositionProps,\n} from \"./map\";\nexport { StaticMap, staticMap, type StaticMapPlace, type StaticMapProps } from \"./static-map\";\nexport { type MapBrand, mapFlavor, mapPalette, type MapRegion, mapStyle, type MapStyleOptions, mix, REGION_FROM_ZOOM } from \"./style\";\n"
1089
+ "content": "/**\n * @krizaka/ui/map — maps on MapLibre GL JS (open source) over Protomaps tiles on the Krizaka CDN, styled from the\n * tokens: `Map`, `Marker`, `Cluster`, `UserPosition`, `RadiusCircle`, `LocationPicker`, `StaticMap` (the fallback), the\n * style (`mapStyle`, `mapPalette`) and the geometry (`distanceMeters`, `circlePolygon`, `formatDistance`). The pin (`MapPin`) is `@krizaka/ui/map/pin`, the place sheet is\n * `@krizaka/ui/map/sheet` and the cards (`MapInfoCard`, `RouteCard`, `routeLinks`) `@krizaka/ui/map/cards`: a page that only draws a map\n * does not pay for them. maplibre-gl\n * and pmtiles are optional peers, loaded when a map is shown. Client (\"use client\").\n */\nexport { MAP_ATTRIBUTION, MAP_GLYPHS, MAP_TILES, mapAssets, setMapAssetsBase } from \"./assets\";\nexport { circlePolygon, distanceMeters, formatDistance, type LngLat, pathLength, pointAlong, project, sliceLine } from \"./geo\";\nexport { LocationPicker, locationPicker, type LocationPickerLabels, locationPickerLabels, type LocationPickerProps } from \"./location-picker\";\nexport {\n Cluster,\n type ClusterPoint,\n type ClusterProps,\n configureMaps,\n Map,\n map,\n type MapLabels,\n mapLabels,\n type MapProps,\n Marker,\n type MarkerProps,\n Pulse,\n type PulseProps,\n RadiusCircle,\n type RadiusCircleProps,\n Route,\n type RouteProps,\n useMap,\n UserPosition,\n type UserPositionProps,\n} from \"./map\";\nexport { StaticMap, staticMap, type StaticMapPlace, type StaticMapProps } from \"./static-map\";\nexport { type MapBrand, mapFlavor, mapPalette, type MapRegion, type MapScheme, mapStyle, type MapStyleOptions, type MapVariant, mix, REGION_FROM_ZOOM } from \"./style\";\n"
1045
1090
  },
1046
1091
  {
1047
1092
  "path": "map/location-picker.tsx",
@@ -1049,11 +1094,27 @@
1049
1094
  },
1050
1095
  {
1051
1096
  "path": "map/map.tsx",
1052
- "content": "// Client. A map of the Krizaka family on MapLibre GL JS (open source) over Protomaps tiles on our CDN — no API key, no\n// metered service. MapLibre and PMTiles are optional peers, loaded when a map is shown (a dynamic import: a page without\n// a map never pays for them). The style comes from the tokens (`mapStyle`), in the page's scheme, and follows it.\n//\n// What every map does: the canvas is decorative for assistive technologies — the map is a region named by `label`, its\n// places a list read in order (the text alternative, `MapPlaces`), each marker a button when it does something; the\n// attribution of OpenStreetMap (ODbL) and Protomaps is always shown; under reduced motion the camera jumps, never flies;\n// without WebGL (or while the engine loads) `fallback` stands in its place.\n/// <reference types=\"geojson\" />\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\n\nimport { usePrefersReducedMotion } from \"../media\";\nimport { tv } from \"../tv\";\nimport { MAP_ATTRIBUTION, setMapAssetsBase } from \"./assets\";\nimport { circlePolygon, type LngLat, pointAlong, sliceLine } from \"./geo\";\nimport { type MapBrand, mapPalette, type MapRegion, mapStyle } from \"./style\";\n\ntype MapLibre = typeof import(\"maplibre-gl\");\ntype MapInstance = import(\"maplibre-gl\").Map;\n\nexport const map = tv({\n slots: {\n root: \"relative isolate overflow-hidden rounded-2xl border border-border-default bg-surface-2 shadow-raised\",\n canvas: \"absolute inset-0 [&_.maplibregl-canvas]:outline-hidden\",\n fallback: \"absolute inset-0\",\n controls: \"absolute right-3 top-3 z-10 flex flex-col overflow-hidden rounded-xl border border-border-default bg-surface-1 shadow-floating\",\n control:\n \"inline-flex h-10 w-10 items-center justify-center text-lg font-semibold text-fg-secondary transition-colors hover:bg-surface-3 hover:text-fg \" +\n \"focus-visible:outline-hidden focus-visible:focus-ring-inset disabled:opacity-40 [&+&]:border-t [&+&]:border-border-subtle\",\n attribution:\n \"absolute bottom-1.5 right-1.5 z-10 rounded-md bg-surface-1 px-1.5 py-0.5 text-[10px] text-fg-secondary [&_a]:underline-offset-2 hover:[&_a]:underline\",\n places: \"sr-only\",\n marker:\n \"group relative flex -translate-y-1/2 cursor-pointer items-center justify-center rounded-full border-2 border-on-accent bg-accent shadow-floating outline-hidden \" +\n \"transition-transform hover:scale-110 focus-visible:focus-ring motion-reduce:transition-none motion-reduce:hover:scale-100 data-[selected]:scale-125\",\n markerLabel:\n \"pointer-events-none absolute bottom-full mb-2 whitespace-nowrap rounded-lg border border-border-default bg-surface-1 px-2 py-1 text-xs font-semibold text-fg shadow-floating\",\n },\n});\n\ntype Registry = { add: (id: string, text: string) => void; remove: (id: string) => void };\ntype Ctx = { map: MapInstance | null; lib: MapLibre | null; ready: boolean; reduce: boolean; places: Registry };\nconst MapContext = React.createContext<Ctx | null>(null);\n\n/** The map a child is drawn on (`Marker`, `RadiusCircle`, `Cluster`…): the MapLibre instance once it is ready. */\nexport function useMap(): Ctx {\n const ctx = React.useContext(MapContext);\n if (!ctx) throw new Error(\"useMap: inside a <Map> only\");\n return ctx;\n}\n\n/** The scheme of the page (`html.light`), followed as it changes. */\nfunction usePageScheme(): \"dark\" | \"light\" {\n const read = () => (typeof document !== \"undefined\" && document.documentElement.classList.contains(\"light\") ? \"light\" : \"dark\");\n const [scheme, setScheme] = React.useState<\"dark\" | \"light\">(read);\n React.useEffect(() => {\n const observer = new MutationObserver(() => setScheme(read()));\n observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\"] });\n return () => observer.disconnect();\n }, []);\n return scheme;\n}\n\nlet protocolAdded = false;\nlet workerUrl: string | null = null;\n\n/**\n * Where MapLibre's worker comes from. A bundler (Next.js, Vite) renames MapLibre's module and leaves its worker behind:\n * by default the worker of the very version the app installed is imported from jsDelivr (free, open source, no key)\n * through a module worker of the page's own origin. An app with a strict CSP serves it itself —\n * `configureMaps({ workerUrl: \"/maplibre-gl-worker.mjs\" })` (with `maplibre-gl-shared.mjs` beside it), once, before a map.\n * `assetsBase` reads the tiles and glyphs through a same-origin proxy of the CDN (`setMapAssetsBase`).\n */\nexport function configureMaps(options: { workerUrl?: string; assetsBase?: string }) {\n if (options.workerUrl) workerUrl = options.workerUrl;\n if (options.assetsBase) setMapAssetsBase(options.assetsBase);\n}\n\n/** MapLibre, its worker and the PMTiles protocol, loaded once for the page. */\nasync function loadEngine(): Promise<MapLibre> {\n const [lib, pmtiles] = await Promise.all([import(\"maplibre-gl\"), import(\"pmtiles\")]);\n const ml = ((lib as unknown as { default?: MapLibre }).default ?? lib) as MapLibre;\n if (!protocolAdded) {\n protocolAdded = true;\n const remote = `https://cdn.jsdelivr.net/npm/maplibre-gl@${ml.getVersion()}/dist/maplibre-gl-worker.mjs`;\n ml.setWorkerUrl(workerUrl ?? URL.createObjectURL(new Blob([`import ${JSON.stringify(remote)};`], { type: \"text/javascript\" })));\n ml.addProtocol(\"pmtiles\", new pmtiles.Protocol().tile);\n }\n return ml;\n}\n\nconst hasWebGL = () => {\n try {\n const canvas = document.createElement(\"canvas\");\n return Boolean(canvas.getContext(\"webgl2\") ?? canvas.getContext(\"webgl\"));\n } catch {\n return false;\n }\n};\n\nexport type MapLabels = {\n /** The zoom-in button (\"Zoom in\"). */\n zoomIn: string;\n /** The zoom-out button (\"Zoom out\"). */\n zoomOut: string;\n /** Before the list of places read in place of the map (\"Places on the map\"). */\n places: string;\n};\n\nexport const mapLabels: MapLabels = { zoomIn: \"Zoom in\", zoomOut: \"Zoom out\", places: \"Places on the map\" };\n\nexport type MapProps = {\n /** The map's accessible name (\"Pick-up points near you\"), passed translated. */\n label: string;\n /** Where the map looks at first: longitude, latitude. */\n center: LngLat;\n /** The zoom at first (0 the world, 12 a city, 16 a street). Default 12. */\n zoom?: number;\n /** The camera follows `center` and `zoom` when they change (flies, or jumps under reduced motion). */\n controlled?: boolean;\n /** The scheme. Default: the page's (`html.light`), followed. */\n scheme?: \"dark\" | \"light\";\n /** The product whose accent the map carries. Default `krizaka`. */\n brand?: MapBrand;\n /** The language of the labels (`fr`, `en`). Default `en`. */\n lang?: string;\n /** The detailed region (PMTiles) drawn from zoom 6.5. Default: our Montréal–Québec extract (to zoom 14). */\n region?: MapRegion | null;\n /** The world's low zooms (PMTiles). Default: our world extract (to zoom 6). */\n world?: MapRegion | null;\n /** The zoom buttons (default) — the keyboard also zooms with + and − on the focused map. */\n controls?: boolean;\n /** Moves with the hand (default); `false` makes a still picture of a place. */\n interactive?: boolean;\n /** Shown in place of the map while its engine loads, and for good without WebGL: a `StaticMap`, a picture. */\n fallback?: React.ReactNode;\n /** Called when the camera rests: its centre and zoom. */\n onMoveEnd?: (view: { center: LngLat; zoom: number }) => void;\n /** Called with the position pressed on the map (not on a marker). */\n onPress?: (position: LngLat) => void;\n /** Markers, circles, clusters, the user's position — and anything drawn over the map. */\n children?: React.ReactNode;\n /** The words, passed translated; English by default. */\n labels?: Partial<MapLabels>;\n /** Classes merged on the root (its height: `h-80`, `aspect-video`). */\n className?: string;\n};\n\n/** A map: MapLibre over our Protomaps tiles, styled from the tokens, with its places as a list for screen readers. */\nfunction MapRoot({\n label,\n center,\n zoom = 12,\n controlled,\n scheme: schemeProp,\n brand,\n lang,\n region,\n world,\n controls = true,\n interactive = true,\n fallback,\n onMoveEnd,\n onPress,\n children,\n labels: given,\n className,\n}: MapProps) {\n const labels = { ...mapLabels, ...given };\n const s = map();\n const pageScheme = usePageScheme();\n const scheme = schemeProp ?? pageScheme;\n const reduce = usePrefersReducedMotion();\n const host = React.useRef<HTMLDivElement>(null);\n const [instance, setInstance] = React.useState<MapInstance | null>(null);\n const [lib, setLib] = React.useState<MapLibre | null>(null);\n const [ready, setReady] = React.useState(false);\n const [failed, setFailed] = React.useState(false);\n const [places, setPlaces] = React.useState<Record<string, string>>({});\n const registry = React.useMemo<Registry>(\n () => ({\n add: (id, text) => setPlaces((p) => (p[id] === text ? p : { ...p, [id]: text })),\n remove: (id) =>\n setPlaces((p) => {\n const { [id]: _gone, ...rest } = p;\n return rest;\n }),\n }),\n [],\n );\n const latest = React.useRef({ onMoveEnd, onPress });\n React.useEffect(() => {\n latest.current = { onMoveEnd, onPress };\n });\n const styleOf = React.useCallback((sc: \"dark\" | \"light\") => mapStyle({ scheme: sc, brand, lang, ...(region !== undefined ? { region } : {}), ...(world !== undefined ? { world } : {}) }), [brand, lang, region, world]);\n\n // The style the map wears now: the engine loads asynchronously, so the scheme it is created with is read when it is ready\n // (the page's theme may have flipped since the first render), and the effect below applies whatever differs.\n const wanted = React.useRef({ scheme, styleOf });\n React.useEffect(() => {\n wanted.current = { scheme, styleOf };\n });\n const applied = React.useRef<{ scheme: \"dark\" | \"light\"; styleOf: typeof styleOf } | null>(null);\n\n // The engine and the map, once (the style follows the scheme below).\n React.useEffect(() => {\n if (!host.current) return;\n let alive = true;\n let created: MapInstance | null = null;\n (hasWebGL() ? loadEngine() : Promise.reject(new Error(\"no WebGL\")))\n .then((ml) => {\n if (!alive || !host.current) return;\n applied.current = wanted.current;\n created = new ml.Map({\n container: host.current,\n style: wanted.current.styleOf(wanted.current.scheme) as never,\n center: [...center] as [number, number],\n zoom,\n interactive,\n attributionControl: false,\n fadeDuration: reduce ? 0 : 300,\n cooperativeGestures: false,\n });\n created.getCanvas().setAttribute(\"aria-hidden\", \"true\");\n created.getCanvas().setAttribute(\"tabindex\", \"-1\");\n created.on(\"load\", () => alive && setReady(true));\n // The basemap cannot be read (offline, a blocked request): the fallback comes back rather than an empty map.\n created.on(\"error\", (e) => {\n const source = (e as { sourceId?: string }).sourceId;\n if (alive && (source === \"world\" || source === \"region\")) setFailed(true);\n });\n created.on(\"moveend\", () => {\n const c = created!.getCenter();\n latest.current.onMoveEnd?.({ center: [c.lng, c.lat], zoom: created!.getZoom() });\n });\n created.on(\"click\", (e) => {\n if ((e.originalEvent.target as Element | null)?.closest?.(\"[data-kz-marker]\")) return;\n latest.current.onPress?.([e.lngLat.lng, e.lngLat.lat]);\n });\n setLib(ml);\n setInstance(created);\n })\n .catch(() => alive && setFailed(true));\n return () => {\n alive = false;\n created?.remove();\n };\n // Created once: the props that change afterwards are followed by the effects below.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // The scheme (and the brand, the language) change the style, not the map.\n React.useEffect(() => {\n if (!instance) return;\n if (applied.current?.scheme === scheme && applied.current.styleOf === styleOf) return;\n applied.current = { scheme, styleOf };\n instance.setStyle(styleOf(scheme) as never);\n }, [instance, scheme, styleOf]);\n\n // A controlled camera: it flies (or jumps) to the new view.\n React.useEffect(() => {\n if (!instance || !controlled) return;\n const view = { center: [...center] as [number, number], zoom };\n if (reduce) instance.jumpTo(view);\n else instance.flyTo({ ...view, speed: 1.4 });\n }, [instance, controlled, center[0], center[1], zoom, reduce]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const zoomBy = (by: number) => instance && (reduce ? instance.setZoom(instance.getZoom() + by) : instance.zoomTo(instance.getZoom() + by, { duration: 250 }));\n const ctx = React.useMemo<Ctx>(() => ({ map: instance, lib, ready, reduce, places: registry }), [instance, lib, ready, reduce, registry]);\n const listed = Object.entries(places);\n return (\n <MapContext.Provider value={ctx}>\n <section\n aria-label={label}\n className={s.root({ className })}\n data-ready={ready ? \"\" : undefined}\n tabIndex={interactive ? 0 : undefined}\n onKeyDown={(e) => {\n if (e.target !== e.currentTarget || !instance) return;\n if (e.key === \"+\" || e.key === \"=\") zoomBy(1);\n else if (e.key === \"-\") zoomBy(-1);\n else if (e.key.startsWith(\"Arrow\")) {\n e.preventDefault();\n const step = 80;\n const by: Record<string, [number, number]> = { ArrowUp: [0, -step], ArrowDown: [0, step], ArrowLeft: [-step, 0], ArrowRight: [step, 0] };\n instance.panBy(by[e.key]!, { duration: reduce ? 0 : 200 });\n }\n }}\n >\n {!ready || failed ? <div className={s.fallback()}>{fallback}</div> : null}\n <div ref={host} className={s.canvas()} style={{ position: \"absolute\", inset: 0, visibility: failed ? \"hidden\" : undefined }} />\n {controls && interactive && !failed ? (\n <div className={s.controls()}>\n <button type=\"button\" className={s.control()} aria-label={labels.zoomIn} disabled={!instance} onClick={() => zoomBy(1)}>\n +\n </button>\n <button type=\"button\" className={s.control()} aria-label={labels.zoomOut} disabled={!instance} onClick={() => zoomBy(-1)}>\n −\n </button>\n </div>\n ) : null}\n <p className={s.attribution()}>\n <a href={MAP_ATTRIBUTION.protomapsUrl} target=\"_blank\" rel=\"noreferrer\">\n {MAP_ATTRIBUTION.protomaps}\n </a>\n {\" · \"}\n <a href={MAP_ATTRIBUTION.osmUrl} target=\"_blank\" rel=\"noreferrer\">\n {MAP_ATTRIBUTION.osm}\n </a>\n </p>\n {listed.length ? (\n <div className={s.places()}>\n <p>{labels.places}</p>\n <ul>\n {listed.map(([id, text]) => (\n <li key={id}>{text}</li>\n ))}\n </ul>\n </div>\n ) : null}\n {children}\n </section>\n </MapContext.Provider>\n );\n}\n\nexport type MarkerProps = {\n /** Where it stands. */\n position: LngLat;\n /** Its words: the place's name, read in the list of places and as the button's name (\"Café Olimpico, 350 m\"). */\n label: string;\n /** Pressing it (details in a panel, a sheet): the marker becomes a button. */\n onPress?: () => void;\n /** The chosen one: larger, its label shown above it. */\n selected?: boolean;\n /** Its size in pixels. Default 18. */\n size?: number;\n /** What it draws instead of the accent dot (an avatar, an icon). */\n children?: React.ReactNode;\n /** Drops onto its place once, after this many milliseconds (stagger several: `index * 90`). Still under reduced motion. */\n drop?: number;\n};\n\nconst noSubscription = () => () => undefined;\n\n/** A place on the map: an accent dot (or your content) that is a button when it does something. */\nexport function Marker({ position, label, onPress, selected, size = 18, children, drop }: MarkerProps) {\n const { map: m, lib, places } = useMap();\n const s = map();\n const id = React.useId();\n // The marker's host element exists only in a browser: the server and the hydration pass render nothing for it, then the\n // client swaps in the element — `useSyncExternalStore`'s server snapshot, so hydration never sees a difference.\n const host = React.useRef<HTMLElement | null>(null);\n const el = React.useSyncExternalStore(\n noSubscription,\n () => (host.current ??= document.createElement(\"div\")),\n () => null,\n );\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n React.useEffect(() => {\n if (!m || !lib || !el) return;\n el.setAttribute(\"data-kz-marker\", \"\");\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...position] as [number, number]).addTo(m);\n return () => void marker.remove();\n }, [m, lib, el, position[0], position[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n if (!el) return null;\n const Tag = onPress ? \"button\" : \"span\";\n return createPortal(\n <Tag\n type={onPress ? \"button\" : undefined}\n aria-label={onPress ? label : undefined}\n aria-hidden={onPress ? undefined : true}\n aria-pressed={onPress && selected !== undefined ? selected : undefined}\n data-selected={selected ? \"\" : undefined}\n data-drop={drop === undefined ? undefined : \"\"}\n className={s.marker()}\n style={{ ...(children ? null : { width: size, height: size }), ...(drop === undefined ? null : ({ \"--kz-map-drop-delay\": `${drop}ms` } as React.CSSProperties)) }}\n onClick={onPress}\n >\n {children}\n {selected ? <span className={s.markerLabel()}>{label}</span> : null}\n </Tag>,\n el,\n );\n}\n\nexport type UserPositionProps = {\n /** Where the person is. */\n position: LngLat;\n /** Its words (\"You are here\"), read in the list of places. */\n label: string;\n /** The accuracy in metres: a soft disc around the dot. */\n accuracy?: number;\n};\n\n/** The person's position: a dot that pulses (still under reduced motion), its accuracy as a soft disc. */\nexport function UserPosition({ position, label, accuracy }: UserPositionProps) {\n const { map: m, lib, places } = useMap();\n const id = React.useId();\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n React.useEffect(() => {\n if (!m || !lib) return;\n const el = document.createElement(\"div\");\n el.className = \"kz-map-user\";\n el.setAttribute(\"aria-hidden\", \"true\");\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...position] as [number, number]).addTo(m);\n return () => void marker.remove();\n }, [m, lib, position[0], position[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n return accuracy ? <RadiusCircle center={position} radius={accuracy} tone=\"soft\" /> : null;\n}\n\nexport type PulseProps = {\n /** Where it beats. */\n position: LngLat;\n /** Its words (\"High demand in Mile End\"), read in the list of places. */\n label: string;\n /** The rings' reach in pixels. Default 56. */\n size?: number;\n /** `accent` (a zone that matters) or `soft`. Default `accent`. */\n tone?: \"accent\" | \"soft\";\n};\n\n/** A heat pulse: rings that swell and fade around a place (a hot spot, a demand peak). Still rings under reduced motion. */\nexport function Pulse({ position, label, size = 56, tone = \"accent\" }: PulseProps) {\n const { map: m, lib, places } = useMap();\n const id = React.useId();\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n React.useEffect(() => {\n if (!m || !lib) return;\n const el = document.createElement(\"div\");\n el.className = \"kz-map-pulse\";\n el.setAttribute(\"data-tone\", tone);\n el.setAttribute(\"aria-hidden\", \"true\");\n el.style.setProperty(\"--kz-map-pulse-size\", `${size}px`);\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...position] as [number, number]).addTo(m);\n return () => void marker.remove();\n }, [m, lib, tone, size, position[0], position[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n return null;\n}\n\nexport type RouteProps = {\n /** The path, as positions in order (a polyline: a delivery, a walk, a flight). */\n path: readonly LngLat[];\n /** Its words (\"Delivery from the studio to Mile End, 2.4 km\"), read in the list of places. */\n label: string;\n /** The line draws itself once, from its start, when the map is on screen; `false` shows it whole. Default `true`. */\n draw?: boolean;\n /** How long the drawing lasts, in milliseconds. Default 1400. */\n duration?: number;\n /** A dot that travels the route once drawn (`true`, or your own content: an avatar, an icon). */\n courier?: boolean | React.ReactNode;\n /** How long a trip takes, in milliseconds. Default 3200. */\n tripDuration?: number;\n /** Start the trips again after a pause (milliseconds), only while the map is on screen. Without it the courier makes one trip. */\n repeatAfter?: number;\n /** Changing it replays the drawing and the trip. */\n replayKey?: string | number;\n /** `accent` or `soft`. Default `accent`. */\n tone?: \"accent\" | \"soft\";\n /** The timing function of the drawing and of the trips: `ease-out`, `linear`, `ease-in-out`. Default: out for the drawing, in-out for a trip. */\n easing?: \"ease-out\" | \"linear\" | \"ease-in-out\";\n /** Holds the drawing and the trips where they are (a controlled pause, on top of the off-screen one). */\n paused?: boolean;\n};\n\nconst ROUTE_CURVES = {\n linear: (t: number) => t,\n \"ease-out\": (t: number) => 1 - (1 - t) ** 3,\n \"ease-in-out\": (t: number) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2),\n} as const;\n\ntype RouteSource = { setData?: (d: GeoJSON.GeoJSON) => void };\n\n/** A route on the map: a line that draws itself, and a courier that travels it. Under reduced motion the line is whole and the courier rests at the end. */\nexport function Route({ path, label, draw = true, duration = 1400, courier, tripDuration = 3200, repeatAfter, replayKey, tone = \"accent\", easing, paused = false }: RouteProps) {\n const { map: m, lib, ready, reduce, places } = useMap();\n const id = `kz-route-${React.useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n const animated = draw && !reduce;\n // The drawing is done for this `replayKey` (a new key draws again); without animation the line is whole at once.\n const token = replayKey ?? 0;\n const [doneFor, setDoneFor] = React.useState<string | number | null>(null);\n const drawn = !animated || doneFor === token;\n const whole = React.useMemo(() => sliceLine(path, 1), [path]);\n const start = React.useMemo(() => sliceLine(path, 0), [path]);\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n useGeoLayer(id, drawn ? whole : start, (c) => [\n { id: `${id}-casing`, type: \"line\", source: id, layout: { \"line-cap\": \"round\", \"line-join\": \"round\" }, paint: { \"line-color\": c.accent, \"line-width\": 9, \"line-opacity\": tone === \"soft\" ? 0.08 : 0.16, \"line-blur\": 3 } },\n { id: `${id}-line`, type: \"line\", source: id, layout: { \"line-cap\": \"round\", \"line-join\": \"round\" }, paint: { \"line-color\": c.accent, \"line-width\": tone === \"soft\" ? 2 : 3.5, \"line-opacity\": tone === \"soft\" ? 0.6 : 1 } },\n ]);\n // Is the map on screen? The drawing waits for it, and a repeating trip does not start while it is not.\n const [seen, setSeen] = React.useState(() => typeof IntersectionObserver === \"undefined\");\n const visible = seen && !paused;\n React.useEffect(() => {\n const el = m?.getContainer?.();\n if (!el || typeof IntersectionObserver === \"undefined\") return;\n const io = new IntersectionObserver(([entry]) => setSeen(!!entry?.isIntersecting), { threshold: 0.25 });\n io.observe(el);\n return () => io.disconnect();\n }, [m]);\n // The drawing: a finite animation, one frame per paint for `duration` ms — no loop, nothing runs afterwards.\n React.useEffect(() => {\n if (!m || !ready || !animated || drawn || !visible) return;\n const source = m.getSource(id) as RouteSource | undefined;\n let frame = 0;\n const began = performance.now();\n const step = (now: number) => {\n const t = Math.min(1, (now - began) / Math.max(1, duration));\n source?.setData?.(sliceLine(path, ROUTE_CURVES[easing ?? \"ease-out\"](t)));\n if (t < 1) frame = requestAnimationFrame(step);\n else setDoneFor(token);\n };\n frame = requestAnimationFrame(step);\n return () => cancelAnimationFrame(frame);\n }, [m, ready, animated, drawn, visible, id, path, duration, token, easing]);\n // The courier: one trip once the line is drawn (finite frames), again after `repeatAfter` while on screen.\n const [trip, setTrip] = React.useState(0);\n React.useEffect(() => {\n if (!courier || !m || !lib || !ready || !drawn) return;\n const el = document.createElement(\"div\");\n el.className = \"kz-map-courier\";\n el.setAttribute(\"aria-hidden\", \"true\");\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...(path[reduce ? path.length - 1 : 0] ?? [0, 0])] as [number, number]).addTo(m);\n let frame = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (!reduce && visible) {\n const began = performance.now();\n const step = (now: number) => {\n const t = Math.min(1, (now - began) / Math.max(1, tripDuration));\n const eased = ROUTE_CURVES[easing ?? \"ease-in-out\"](t);\n marker.setLngLat([...pointAlong(path, eased).position] as [number, number]);\n if (t < 1) frame = requestAnimationFrame(step);\n else if (repeatAfter !== undefined) timer = setTimeout(() => setTrip((n) => n + 1), repeatAfter);\n };\n frame = requestAnimationFrame(step);\n } else if (!reduce) marker.setLngLat([...(path[path.length - 1] ?? [0, 0])] as [number, number]);\n return () => {\n cancelAnimationFrame(frame);\n clearTimeout(timer);\n marker.remove();\n };\n }, [courier, m, lib, ready, drawn, visible, reduce, path, tripDuration, repeatAfter, trip, token, easing]);\n return null;\n}\n\n/** Adds a GeoJSON source and its layers while the map has a style (again after a change of scheme). */\nfunction useGeoLayer(id: string, data: GeoJSON.GeoJSON, layers: (palette: ReturnType<typeof mapPalette>) => object[], source: object = {}) {\n const { map: m, ready } = useMap();\n const dataRef = React.useRef(data);\n React.useEffect(() => {\n dataRef.current = data;\n const src = m?.getSource(id) as { setData?: (d: GeoJSON.GeoJSON) => void } | undefined;\n src?.setData?.(data);\n }, [m, id, data]);\n React.useEffect(() => {\n if (!m || !ready) return;\n const add = () => {\n if (m.getSource(id)) return;\n const scheme = document.documentElement.classList.contains(\"light\") ? \"light\" : \"dark\";\n m.addSource(id, { type: \"geojson\", data: dataRef.current, ...source } as never);\n for (const layer of layers(mapPalette(scheme))) m.addLayer(layer as never);\n };\n add();\n m.on(\"styledata\", add);\n return () => {\n m.off(\"styledata\", add);\n if (!m.getStyle()) return;\n for (const layer of m.getStyle().layers.filter((l) => \"source\" in l && l.source === id)) m.removeLayer(layer.id);\n if (m.getSource(id)) m.removeSource(id);\n };\n }, [m, ready, id]); // eslint-disable-line react-hooks/exhaustive-deps\n}\n\nexport type RadiusCircleProps = {\n /** Its centre. */\n center: LngLat;\n /** Its radius in metres. */\n radius: number;\n /** `accent` (a zone that matters: a delivery area, a search radius) or `soft` (an accuracy). */\n tone?: \"accent\" | \"soft\";\n};\n\n/** A circle on the ground: a delivery zone, a search radius — filled with the accent, its edge drawn. */\nexport function RadiusCircle({ center, radius, tone = \"accent\" }: RadiusCircleProps) {\n const id = `kz-circle-${React.useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n const data = React.useMemo(() => circlePolygon(center, radius), [center[0], center[1], radius]); // eslint-disable-line react-hooks/exhaustive-deps\n useGeoLayer(id, data, (c) => [\n { id: `${id}-fill`, type: \"fill\", source: id, paint: { \"fill-color\": c.accent, \"fill-opacity\": tone === \"soft\" ? 0.1 : 0.14 } },\n { id: `${id}-line`, type: \"line\", source: id, paint: { \"line-color\": c.accent, \"line-width\": tone === \"soft\" ? 1 : 2, \"line-opacity\": tone === \"soft\" ? 0.4 : 0.9, ...(tone === \"accent\" ? { \"line-dasharray\": [2, 1.5] } : {}) } },\n ]);\n return null;\n}\n\nexport type ClusterPoint = { id: string; position: LngLat; label: string };\n\nexport type ClusterProps = {\n /** The points: many of them (creators, pick-up points, events). */\n points: readonly ClusterPoint[];\n /** Pressing a single point. A group zooms in to open itself. */\n onPointPress?: (point: ClusterPoint) => void;\n /** The radius, in pixels, within which points group. Default 48. */\n radius?: number;\n};\n\n/** Many points grouped while they are close: a disc with the count, opened by zooming in; each point is listed for screen readers. */\nexport function Cluster({ points, onPointPress, radius = 48 }: ClusterProps) {\n const { map: m, ready, reduce, places } = useMap();\n const id = `kz-cluster-${React.useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n const data = React.useMemo<GeoJSON.FeatureCollection>(\n () => ({ type: \"FeatureCollection\", features: points.map((p) => ({ type: \"Feature\", properties: { id: p.id, label: p.label }, geometry: { type: \"Point\", coordinates: [...p.position] } })) }),\n [points],\n );\n React.useEffect(() => {\n for (const p of points) places.add(`${id}-${p.id}`, p.label);\n return () => points.forEach((p) => places.remove(`${id}-${p.id}`));\n }, [points, places, id]);\n useGeoLayer(\n id,\n data,\n (c) => [\n { id: `${id}-groups`, type: \"circle\", source: id, filter: [\"has\", \"point_count\"], paint: { \"circle-color\": c.accent, \"circle-opacity\": 0.92, \"circle-radius\": [\"step\", [\"get\", \"point_count\"], 16, 10, 20, 50, 26], \"circle-stroke-width\": 3, \"circle-stroke-color\": c.halo } },\n { id: `${id}-count`, type: \"symbol\", source: id, filter: [\"has\", \"point_count\"], layout: { \"text-field\": [\"get\", \"point_count_abbreviated\"], \"text-font\": [\"Noto Sans Medium\"], \"text-size\": 13 }, paint: { \"text-color\": c.onAccent } },\n { id: `${id}-points`, type: \"circle\", source: id, filter: [\"!\", [\"has\", \"point_count\"]], paint: { \"circle-color\": c.accent, \"circle-radius\": 7, \"circle-stroke-width\": 2.5, \"circle-stroke-color\": c.halo } },\n ],\n { cluster: true, clusterRadius: radius, clusterMaxZoom: 15 },\n );\n React.useEffect(() => {\n if (!m || !ready) return;\n const openGroup = async (e: { features?: { properties: Record<string, unknown>; geometry: GeoJSON.Geometry }[] }) => {\n const f = e.features?.[0];\n if (!f) return;\n const src = m.getSource(id) as unknown as { getClusterExpansionZoom: (id: number) => Promise<number> };\n const z = await src.getClusterExpansionZoom(f.properties.cluster_id as number);\n const center = (f.geometry as GeoJSON.Point).coordinates as [number, number];\n if (reduce) m.jumpTo({ center, zoom: z });\n else m.easeTo({ center, zoom: z });\n };\n const pressPoint = (e: { features?: { properties: Record<string, unknown> }[] }) => {\n const pid = e.features?.[0]?.properties.id;\n const point = points.find((p) => p.id === pid);\n if (point) onPointPress?.(point);\n };\n m.on(\"click\", `${id}-groups`, openGroup as never);\n m.on(\"click\", `${id}-points`, pressPoint as never);\n return () => {\n m.off(\"click\", `${id}-groups`, openGroup as never);\n m.off(\"click\", `${id}-points`, pressPoint as never);\n };\n }, [m, ready, id, points, onPointPress, reduce]);\n return null;\n}\n\nexport { MapRoot as Map };\n"
1097
+ "content": "// Client. A map of the Krizaka family on MapLibre GL JS (open source) over Protomaps tiles on our CDN — no API key, no\n// metered service. MapLibre and PMTiles are optional peers, loaded when a map is shown (a dynamic import: a page without\n// a map never pays for them). The style comes from the tokens (`mapStyle`), in the page's scheme, and follows it.\n//\n// What every map does: the canvas is decorative for assistive technologies — the map is a region named by `label`, its\n// places a list read in order (the text alternative, `MapPlaces`), each marker a button when it does something; the\n// attribution of OpenStreetMap (ODbL) and Protomaps is always shown; under reduced motion the camera jumps, never flies;\n// without WebGL (or while the engine loads) `fallback` stands in its place.\n/// <reference types=\"geojson\" />\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\n\nimport { usePrefersReducedMotion } from \"../media\";\nimport { tv } from \"../tv\";\nimport { MAP_ATTRIBUTION, setMapAssetsBase } from \"./assets\";\nimport { circlePolygon, type LngLat, pointAlong, sliceLine } from \"./geo\";\nimport { type MapBrand, mapPalette, type MapRegion, type MapScheme, mapStyle, type MapVariant } from \"./style\";\n\ntype MapLibre = typeof import(\"maplibre-gl\");\ntype MapInstance = import(\"maplibre-gl\").Map;\n\nexport const map = tv({\n slots: {\n root: \"relative isolate overflow-hidden rounded-2xl border border-border-default bg-surface-2 shadow-raised\",\n canvas: \"absolute inset-0 [&_.maplibregl-canvas]:outline-hidden\",\n fallback: \"absolute inset-0\",\n controls: \"absolute right-3 top-3 z-10 flex flex-col overflow-hidden rounded-xl border border-border-default bg-surface-1 shadow-floating\",\n control:\n \"inline-flex h-10 w-10 items-center justify-center text-lg font-semibold text-fg-secondary transition-colors hover:bg-surface-3 hover:text-fg \" +\n \"focus-visible:outline-hidden focus-visible:focus-ring-inset disabled:opacity-40 [&+&]:border-t [&+&]:border-border-subtle\",\n attribution:\n \"absolute bottom-1.5 right-1.5 z-10 rounded-md bg-surface-1 px-1.5 py-0.5 text-[10px] text-fg-secondary [&_a]:underline-offset-2 hover:[&_a]:underline\",\n places: \"sr-only\",\n marker:\n \"group relative flex -translate-y-1/2 cursor-pointer items-center justify-center rounded-full border-2 border-on-accent bg-accent shadow-floating outline-hidden \" +\n \"transition-transform hover:scale-110 focus-visible:focus-ring motion-reduce:transition-none motion-reduce:hover:scale-100 data-[selected]:scale-125\",\n markerLabel:\n \"pointer-events-none absolute bottom-full mb-2 whitespace-nowrap rounded-lg border border-border-default bg-surface-1 px-2 py-1 text-xs font-semibold text-fg shadow-floating\",\n },\n});\n\ntype Registry = { add: (id: string, text: string) => void; remove: (id: string) => void };\ntype Look = { scheme: \"dark\" | \"light\"; brand?: MapBrand; variant?: MapVariant };\ntype Ctx = { map: MapInstance | null; lib: MapLibre | null; ready: boolean; reduce: boolean; places: Registry; look: Look };\nconst MapContext = React.createContext<Ctx | null>(null);\n\n/** The map a child is drawn on (`Marker`, `RadiusCircle`, `Cluster`…): the MapLibre instance once it is ready. */\nexport function useMap(): Ctx {\n const ctx = React.useContext(MapContext);\n if (!ctx) throw new Error(\"useMap: inside a <Map> only\");\n return ctx;\n}\n\n/** The scheme of the page (`html.light`), followed as it changes. */\nfunction usePageScheme(): \"dark\" | \"light\" {\n const read = () => (typeof document !== \"undefined\" && document.documentElement.classList.contains(\"light\") ? \"light\" : \"dark\");\n const [scheme, setScheme] = React.useState<\"dark\" | \"light\">(read);\n React.useEffect(() => {\n const observer = new MutationObserver(() => setScheme(read()));\n observer.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\"] });\n return () => observer.disconnect();\n }, []);\n return scheme;\n}\n\nlet protocolAdded = false;\nlet workerUrl: string | null = null;\n\n/**\n * Where MapLibre's worker comes from. A bundler (Next.js, Vite) renames MapLibre's module and leaves its worker behind:\n * by default the worker of the very version the app installed is imported from jsDelivr (free, open source, no key)\n * through a module worker of the page's own origin. An app with a strict CSP serves it itself —\n * `configureMaps({ workerUrl: \"/maplibre-gl-worker.mjs\" })` (with `maplibre-gl-shared.mjs` beside it), once, before a map.\n * `assetsBase` reads the tiles and glyphs through a same-origin proxy of the CDN (`setMapAssetsBase`).\n */\nexport function configureMaps(options: { workerUrl?: string; assetsBase?: string }) {\n if (options.workerUrl) workerUrl = options.workerUrl;\n if (options.assetsBase) setMapAssetsBase(options.assetsBase);\n}\n\n/** MapLibre, its worker and the PMTiles protocol, loaded once for the page. */\nasync function loadEngine(): Promise<MapLibre> {\n const [lib, pmtiles] = await Promise.all([import(\"maplibre-gl\"), import(\"pmtiles\")]);\n const ml = ((lib as unknown as { default?: MapLibre }).default ?? lib) as MapLibre;\n if (!protocolAdded) {\n protocolAdded = true;\n const remote = `https://cdn.jsdelivr.net/npm/maplibre-gl@${ml.getVersion()}/dist/maplibre-gl-worker.mjs`;\n ml.setWorkerUrl(workerUrl ?? URL.createObjectURL(new Blob([`import ${JSON.stringify(remote)};`], { type: \"text/javascript\" })));\n ml.addProtocol(\"pmtiles\", new pmtiles.Protocol().tile);\n }\n return ml;\n}\n\nconst hasWebGL = () => {\n try {\n const canvas = document.createElement(\"canvas\");\n return Boolean(canvas.getContext(\"webgl2\") ?? canvas.getContext(\"webgl\"));\n } catch {\n return false;\n }\n};\n\nexport type MapLabels = {\n /** The zoom-in button (\"Zoom in\"). */\n zoomIn: string;\n /** The zoom-out button (\"Zoom out\"). */\n zoomOut: string;\n /** Before the list of places read in place of the map (\"Places on the map\"). */\n places: string;\n};\n\nexport const mapLabels: MapLabels = { zoomIn: \"Zoom in\", zoomOut: \"Zoom out\", places: \"Places on the map\" };\n\nexport type MapProps = {\n /** The map's accessible name (\"Pick-up points near you\"), passed translated. */\n label: string;\n /** Where the map looks at first: longitude, latitude. */\n center: LngLat;\n /** The zoom at first (0 the world, 12 a city, 16 a street). Default 12. */\n zoom?: number;\n /** The camera follows `center` and `zoom` when they change (flies, or jumps under reduced motion). */\n controlled?: boolean;\n /** The scheme: `auto` (default) follows the page (`html.light`) as it changes; `dark` or `light` pins it. */\n scheme?: MapScheme;\n /** The look: `plain` (default), `notebook` (the Cahier: paper and ink, manila tags for clusters). */\n variant?: MapVariant;\n /** The product whose accent the map carries. Default `krizaka`. */\n brand?: MapBrand;\n /** The language of the labels (`fr`, `en`). Default `en`. */\n lang?: string;\n /** The detailed region (PMTiles) drawn from zoom 6.5. Default: our Montréal–Québec extract (to zoom 14). */\n region?: MapRegion | null;\n /** The world's low zooms (PMTiles). Default: our world extract (to zoom 6). */\n world?: MapRegion | null;\n /** The zoom buttons (default) — the keyboard also zooms with + and − on the focused map. */\n controls?: boolean;\n /** Moves with the hand (default); `false` makes a still picture of a place. */\n interactive?: boolean;\n /** Shown in place of the map while its engine loads, and for good without WebGL: a `StaticMap`, a picture. */\n fallback?: React.ReactNode;\n /** Called when the camera rests: its centre and zoom. */\n onMoveEnd?: (view: { center: LngLat; zoom: number }) => void;\n /** Called with the position pressed on the map (not on a marker). */\n onPress?: (position: LngLat) => void;\n /** Markers, circles, clusters, the user's position — and anything drawn over the map. */\n children?: React.ReactNode;\n /** The words, passed translated; English by default. */\n labels?: Partial<MapLabels>;\n /** Classes merged on the root (its height: `h-80`, `aspect-video`). */\n className?: string;\n};\n\n/** A map: MapLibre over our Protomaps tiles, styled from the tokens, with its places as a list for screen readers. */\nfunction MapRoot({\n label,\n center,\n zoom = 12,\n controlled,\n scheme: schemeProp = \"auto\",\n variant,\n brand,\n lang,\n region,\n world,\n controls = true,\n interactive = true,\n fallback,\n onMoveEnd,\n onPress,\n children,\n labels: given,\n className,\n}: MapProps) {\n const labels = { ...mapLabels, ...given };\n const s = map();\n const pageScheme = usePageScheme();\n const scheme = schemeProp === \"auto\" ? pageScheme : schemeProp;\n const reduce = usePrefersReducedMotion();\n const host = React.useRef<HTMLDivElement>(null);\n const [instance, setInstance] = React.useState<MapInstance | null>(null);\n const [lib, setLib] = React.useState<MapLibre | null>(null);\n const [ready, setReady] = React.useState(false);\n const [failed, setFailed] = React.useState(false);\n const [places, setPlaces] = React.useState<Record<string, string>>({});\n const registry = React.useMemo<Registry>(\n () => ({\n add: (id, text) => setPlaces((p) => (p[id] === text ? p : { ...p, [id]: text })),\n remove: (id) =>\n setPlaces((p) => {\n const { [id]: _gone, ...rest } = p;\n return rest;\n }),\n }),\n [],\n );\n const latest = React.useRef({ onMoveEnd, onPress });\n React.useEffect(() => {\n latest.current = { onMoveEnd, onPress };\n });\n const styleOf = React.useCallback((sc: \"dark\" | \"light\") => mapStyle({ scheme: sc, brand, variant, lang, ...(region !== undefined ? { region } : {}), ...(world !== undefined ? { world } : {}) }), [brand, variant, lang, region, world]);\n\n // The style the map wears now: the engine loads asynchronously, so the scheme it is created with is read when it is ready\n // (the page's theme may have flipped since the first render), and the effect below applies whatever differs.\n const wanted = React.useRef({ scheme, styleOf });\n React.useEffect(() => {\n wanted.current = { scheme, styleOf };\n });\n const applied = React.useRef<{ scheme: \"dark\" | \"light\"; styleOf: typeof styleOf } | null>(null);\n\n // The engine and the map, once (the style follows the scheme below).\n React.useEffect(() => {\n if (!host.current) return;\n let alive = true;\n let created: MapInstance | null = null;\n (hasWebGL() ? loadEngine() : Promise.reject(new Error(\"no WebGL\")))\n .then((ml) => {\n if (!alive || !host.current) return;\n applied.current = wanted.current;\n created = new ml.Map({\n container: host.current,\n style: wanted.current.styleOf(wanted.current.scheme) as never,\n center: [...center] as [number, number],\n zoom,\n interactive,\n attributionControl: false,\n fadeDuration: reduce ? 0 : 300,\n cooperativeGestures: false,\n });\n created.getCanvas().setAttribute(\"aria-hidden\", \"true\");\n created.getCanvas().setAttribute(\"tabindex\", \"-1\");\n created.on(\"load\", () => alive && setReady(true));\n // The basemap cannot be read (offline, a blocked request): the fallback comes back rather than an empty map.\n created.on(\"error\", (e) => {\n const source = (e as { sourceId?: string }).sourceId;\n if (alive && (source === \"world\" || source === \"region\")) setFailed(true);\n });\n created.on(\"moveend\", () => {\n const c = created!.getCenter();\n latest.current.onMoveEnd?.({ center: [c.lng, c.lat], zoom: created!.getZoom() });\n });\n created.on(\"click\", (e) => {\n if ((e.originalEvent.target as Element | null)?.closest?.(\"[data-kz-marker]\")) return;\n latest.current.onPress?.([e.lngLat.lng, e.lngLat.lat]);\n });\n setLib(ml);\n setInstance(created);\n })\n .catch(() => alive && setFailed(true));\n return () => {\n alive = false;\n created?.remove();\n };\n // Created once: the props that change afterwards are followed by the effects below.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // The scheme (and the brand, the language) change the style, not the map.\n React.useEffect(() => {\n if (!instance) return;\n if (applied.current?.scheme === scheme && applied.current.styleOf === styleOf) return;\n applied.current = { scheme, styleOf };\n instance.setStyle(styleOf(scheme) as never);\n }, [instance, scheme, styleOf]);\n\n // A controlled camera: it flies (or jumps) to the new view.\n React.useEffect(() => {\n if (!instance || !controlled) return;\n const view = { center: [...center] as [number, number], zoom };\n if (reduce) instance.jumpTo(view);\n else instance.flyTo({ ...view, speed: 1.4 });\n }, [instance, controlled, center[0], center[1], zoom, reduce]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const zoomBy = (by: number) => instance && (reduce ? instance.setZoom(instance.getZoom() + by) : instance.zoomTo(instance.getZoom() + by, { duration: 250 }));\n const ctx = React.useMemo<Ctx>(() => ({ map: instance, lib, ready, reduce, places: registry, look: { scheme, brand, variant } }), [instance, lib, ready, reduce, registry, scheme, brand, variant]);\n const listed = Object.entries(places);\n return (\n <MapContext.Provider value={ctx}>\n <section\n aria-label={label}\n className={s.root({ className })}\n data-ready={ready ? \"\" : undefined}\n tabIndex={interactive ? 0 : undefined}\n onKeyDown={(e) => {\n if (e.target !== e.currentTarget || !instance) return;\n if (e.key === \"+\" || e.key === \"=\") zoomBy(1);\n else if (e.key === \"-\") zoomBy(-1);\n else if (e.key.startsWith(\"Arrow\")) {\n e.preventDefault();\n const step = 80;\n const by: Record<string, [number, number]> = { ArrowUp: [0, -step], ArrowDown: [0, step], ArrowLeft: [-step, 0], ArrowRight: [step, 0] };\n instance.panBy(by[e.key]!, { duration: reduce ? 0 : 200 });\n }\n }}\n >\n {!ready || failed ? <div className={s.fallback()}>{fallback}</div> : null}\n <div ref={host} className={s.canvas()} style={{ position: \"absolute\", inset: 0, visibility: failed ? \"hidden\" : undefined }} />\n {controls && interactive && !failed ? (\n <div className={s.controls()}>\n <button type=\"button\" className={s.control()} aria-label={labels.zoomIn} disabled={!instance} onClick={() => zoomBy(1)}>\n +\n </button>\n <button type=\"button\" className={s.control()} aria-label={labels.zoomOut} disabled={!instance} onClick={() => zoomBy(-1)}>\n −\n </button>\n </div>\n ) : null}\n <p className={s.attribution()}>\n <a href={MAP_ATTRIBUTION.protomapsUrl} target=\"_blank\" rel=\"noreferrer\">\n {MAP_ATTRIBUTION.protomaps}\n </a>\n {\" · \"}\n <a href={MAP_ATTRIBUTION.osmUrl} target=\"_blank\" rel=\"noreferrer\">\n {MAP_ATTRIBUTION.osm}\n </a>\n </p>\n {listed.length ? (\n <div className={s.places()}>\n <p>{labels.places}</p>\n <ul>\n {listed.map(([id, text]) => (\n <li key={id}>{text}</li>\n ))}\n </ul>\n </div>\n ) : null}\n {children}\n </section>\n </MapContext.Provider>\n );\n}\n\nexport type MarkerProps = {\n /** Where it stands. */\n position: LngLat;\n /** Its words: the place's name, read in the list of places and as the button's name (\"Café Olimpico, 350 m\"). */\n label: string;\n /** Pressing it (details in a panel, a sheet): the marker becomes a button. */\n onPress?: () => void;\n /** The chosen one: larger, its label shown above it. */\n selected?: boolean;\n /** Its size in pixels. Default 18. */\n size?: number;\n /** What it draws instead of the accent dot (an avatar, an icon). */\n children?: React.ReactNode;\n /** Drops onto its place once, after this many milliseconds (stagger several: `index * 90`). Still under reduced motion. */\n drop?: number;\n};\n\nconst noSubscription = () => () => undefined;\n\n/** A place on the map: an accent dot (or your content) that is a button when it does something. */\nexport function Marker({ position, label, onPress, selected, size = 18, children, drop }: MarkerProps) {\n const { map: m, lib, places } = useMap();\n const s = map();\n const id = React.useId();\n // The marker's host element exists only in a browser: the server and the hydration pass render nothing for it, then the\n // client swaps in the element — `useSyncExternalStore`'s server snapshot, so hydration never sees a difference.\n const host = React.useRef<HTMLElement | null>(null);\n const el = React.useSyncExternalStore(\n noSubscription,\n () => (host.current ??= document.createElement(\"div\")),\n () => null,\n );\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n React.useEffect(() => {\n if (!m || !lib || !el) return;\n el.setAttribute(\"data-kz-marker\", \"\");\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...position] as [number, number]).addTo(m);\n return () => void marker.remove();\n }, [m, lib, el, position[0], position[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n if (!el) return null;\n const Tag = onPress ? \"button\" : \"span\";\n return createPortal(\n <Tag\n type={onPress ? \"button\" : undefined}\n aria-label={onPress ? label : undefined}\n aria-hidden={onPress ? undefined : true}\n aria-pressed={onPress && selected !== undefined ? selected : undefined}\n data-selected={selected ? \"\" : undefined}\n data-drop={drop === undefined ? undefined : \"\"}\n className={s.marker()}\n style={{ ...(children ? null : { width: size, height: size }), ...(drop === undefined ? null : ({ \"--kz-map-drop-delay\": `${drop}ms` } as React.CSSProperties)) }}\n onClick={onPress}\n >\n {children}\n {selected ? <span className={s.markerLabel()}>{label}</span> : null}\n </Tag>,\n el,\n );\n}\n\nexport type UserPositionProps = {\n /** Where the person is. */\n position: LngLat;\n /** Its words (\"You are here\"), read in the list of places. */\n label: string;\n /** The accuracy in metres: a soft disc around the dot. */\n accuracy?: number;\n};\n\n/** The person's position: a dot that pulses (still under reduced motion), its accuracy as a soft disc. */\nexport function UserPosition({ position, label, accuracy }: UserPositionProps) {\n const { map: m, lib, places } = useMap();\n const id = React.useId();\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n React.useEffect(() => {\n if (!m || !lib) return;\n const el = document.createElement(\"div\");\n el.className = \"kz-map-user\";\n el.setAttribute(\"aria-hidden\", \"true\");\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...position] as [number, number]).addTo(m);\n return () => void marker.remove();\n }, [m, lib, position[0], position[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n return accuracy ? <RadiusCircle center={position} radius={accuracy} tone=\"soft\" /> : null;\n}\n\nexport type PulseProps = {\n /** Where it beats. */\n position: LngLat;\n /** Its words (\"High demand in Mile End\"), read in the list of places. */\n label: string;\n /** The rings' reach in pixels. Default 56. */\n size?: number;\n /** `accent` (a zone that matters) or `soft`. Default `accent`. */\n tone?: \"accent\" | \"soft\";\n};\n\n/** A heat pulse: rings that swell and fade around a place (a hot spot, a demand peak). Still rings under reduced motion. */\nexport function Pulse({ position, label, size = 56, tone = \"accent\" }: PulseProps) {\n const { map: m, lib, places } = useMap();\n const id = React.useId();\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n React.useEffect(() => {\n if (!m || !lib) return;\n const el = document.createElement(\"div\");\n el.className = \"kz-map-pulse\";\n el.setAttribute(\"data-tone\", tone);\n el.setAttribute(\"aria-hidden\", \"true\");\n el.style.setProperty(\"--kz-map-pulse-size\", `${size}px`);\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...position] as [number, number]).addTo(m);\n return () => void marker.remove();\n }, [m, lib, tone, size, position[0], position[1]]); // eslint-disable-line react-hooks/exhaustive-deps\n return null;\n}\n\nexport type RouteProps = {\n /** The path, as positions in order (a polyline: a delivery, a walk, a flight). */\n path: readonly LngLat[];\n /** Its words (\"Delivery from the studio to Mile End, 2.4 km\"), read in the list of places. */\n label: string;\n /** The line draws itself once, from its start, when the map is on screen; `false` shows it whole. Default `true`. */\n draw?: boolean;\n /** How long the drawing lasts, in milliseconds. Default 1400. */\n duration?: number;\n /** A dot that travels the route once drawn (`true`, or your own content: an avatar, an icon). */\n courier?: boolean | React.ReactNode;\n /** How long a trip takes, in milliseconds. Default 3200. */\n tripDuration?: number;\n /** Start the trips again after a pause (milliseconds), only while the map is on screen. Without it the courier makes one trip. */\n repeatAfter?: number;\n /** Changing it replays the drawing and the trip. */\n replayKey?: string | number;\n /** `accent` or `soft`. Default `accent`. */\n tone?: \"accent\" | \"soft\";\n /** The timing function of the drawing and of the trips: `ease-out`, `linear`, `ease-in-out`. Default: out for the drawing, in-out for a trip. */\n easing?: \"ease-out\" | \"linear\" | \"ease-in-out\";\n /** Holds the drawing and the trips where they are (a controlled pause, on top of the off-screen one). */\n paused?: boolean;\n};\n\nconst ROUTE_CURVES = {\n linear: (t: number) => t,\n \"ease-out\": (t: number) => 1 - (1 - t) ** 3,\n \"ease-in-out\": (t: number) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2),\n} as const;\n\ntype RouteSource = { setData?: (d: GeoJSON.GeoJSON) => void };\n\n/** A route on the map: a line that draws itself, and a courier that travels it. Under reduced motion the line is whole and the courier rests at the end. */\nexport function Route({ path, label, draw = true, duration = 1400, courier, tripDuration = 3200, repeatAfter, replayKey, tone = \"accent\", easing, paused = false }: RouteProps) {\n const { map: m, lib, ready, reduce, places } = useMap();\n const id = `kz-route-${React.useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n const animated = draw && !reduce;\n // The drawing is done for this `replayKey` (a new key draws again); without animation the line is whole at once.\n const token = replayKey ?? 0;\n const [doneFor, setDoneFor] = React.useState<string | number | null>(null);\n const drawn = !animated || doneFor === token;\n const whole = React.useMemo(() => sliceLine(path, 1), [path]);\n const start = React.useMemo(() => sliceLine(path, 0), [path]);\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\n useGeoLayer(id, drawn ? whole : start, (c) => [\n { id: `${id}-casing`, type: \"line\", source: id, layout: { \"line-cap\": \"round\", \"line-join\": \"round\" }, paint: { \"line-color\": c.accent, \"line-width\": 9, \"line-opacity\": tone === \"soft\" ? 0.08 : 0.16, \"line-blur\": 3 } },\n { id: `${id}-line`, type: \"line\", source: id, layout: { \"line-cap\": \"round\", \"line-join\": \"round\" }, paint: { \"line-color\": c.accent, \"line-width\": tone === \"soft\" ? 2 : 3.5, \"line-opacity\": tone === \"soft\" ? 0.6 : 1 } },\n ]);\n // Is the map on screen? The drawing waits for it, and a repeating trip does not start while it is not.\n const [seen, setSeen] = React.useState(() => typeof IntersectionObserver === \"undefined\");\n const visible = seen && !paused;\n React.useEffect(() => {\n const el = m?.getContainer?.();\n if (!el || typeof IntersectionObserver === \"undefined\") return;\n const io = new IntersectionObserver(([entry]) => setSeen(!!entry?.isIntersecting), { threshold: 0.25 });\n io.observe(el);\n return () => io.disconnect();\n }, [m]);\n // The drawing: a finite animation, one frame per paint for `duration` ms — no loop, nothing runs afterwards.\n React.useEffect(() => {\n if (!m || !ready || !animated || drawn || !visible) return;\n const source = m.getSource(id) as RouteSource | undefined;\n let frame = 0;\n const began = performance.now();\n const step = (now: number) => {\n const t = Math.min(1, (now - began) / Math.max(1, duration));\n source?.setData?.(sliceLine(path, ROUTE_CURVES[easing ?? \"ease-out\"](t)));\n if (t < 1) frame = requestAnimationFrame(step);\n else setDoneFor(token);\n };\n frame = requestAnimationFrame(step);\n return () => cancelAnimationFrame(frame);\n }, [m, ready, animated, drawn, visible, id, path, duration, token, easing]);\n // The courier: one trip once the line is drawn (finite frames), again after `repeatAfter` while on screen.\n const [trip, setTrip] = React.useState(0);\n React.useEffect(() => {\n if (!courier || !m || !lib || !ready || !drawn) return;\n const el = document.createElement(\"div\");\n el.className = \"kz-map-courier\";\n el.setAttribute(\"aria-hidden\", \"true\");\n const marker = new lib.Marker({ element: el, anchor: \"center\" }).setLngLat([...(path[reduce ? path.length - 1 : 0] ?? [0, 0])] as [number, number]).addTo(m);\n let frame = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n if (!reduce && visible) {\n const began = performance.now();\n const step = (now: number) => {\n const t = Math.min(1, (now - began) / Math.max(1, tripDuration));\n const eased = ROUTE_CURVES[easing ?? \"ease-in-out\"](t);\n marker.setLngLat([...pointAlong(path, eased).position] as [number, number]);\n if (t < 1) frame = requestAnimationFrame(step);\n else if (repeatAfter !== undefined) timer = setTimeout(() => setTrip((n) => n + 1), repeatAfter);\n };\n frame = requestAnimationFrame(step);\n } else if (!reduce) marker.setLngLat([...(path[path.length - 1] ?? [0, 0])] as [number, number]);\n return () => {\n cancelAnimationFrame(frame);\n clearTimeout(timer);\n marker.remove();\n };\n }, [courier, m, lib, ready, drawn, visible, reduce, path, tripDuration, repeatAfter, trip, token, easing]);\n return null;\n}\n\n/** Adds a GeoJSON source and its layers while the map has a style (again after a change of scheme). */\nfunction useGeoLayer(id: string, data: GeoJSON.GeoJSON, layers: (palette: ReturnType<typeof mapPalette>) => object[], source: object = {}) {\n const { map: m, ready, look: { scheme, brand, variant } } = useMap();\n const dataRef = React.useRef(data);\n React.useEffect(() => {\n dataRef.current = data;\n const src = m?.getSource(id) as { setData?: (d: GeoJSON.GeoJSON) => void } | undefined;\n src?.setData?.(data);\n }, [m, id, data]);\n React.useEffect(() => {\n if (!m || !ready) return;\n const add = () => {\n if (m.getSource(id)) return;\n m.addSource(id, { type: \"geojson\", data: dataRef.current, ...source } as never);\n for (const layer of layers(mapPalette(scheme, brand, variant))) m.addLayer(layer as never);\n };\n add();\n m.on(\"styledata\", add);\n return () => {\n m.off(\"styledata\", add);\n if (!m.getStyle()) return;\n for (const layer of m.getStyle().layers.filter((l) => \"source\" in l && l.source === id)) m.removeLayer(layer.id);\n if (m.getSource(id)) m.removeSource(id);\n };\n }, [m, ready, id, scheme, brand, variant]); // eslint-disable-line react-hooks/exhaustive-deps\n}\n\nexport type RadiusCircleProps = {\n /** Its centre. */\n center: LngLat;\n /** Its radius in metres. */\n radius: number;\n /** `accent` (a zone that matters: a delivery area, a search radius) or `soft` (an accuracy). */\n tone?: \"accent\" | \"soft\";\n};\n\n/** A circle on the ground: a delivery zone, a search radius — filled with the accent, its edge drawn. */\nexport function RadiusCircle({ center, radius, tone = \"accent\" }: RadiusCircleProps) {\n const id = `kz-circle-${React.useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n const data = React.useMemo(() => circlePolygon(center, radius), [center[0], center[1], radius]); // eslint-disable-line react-hooks/exhaustive-deps\n useGeoLayer(id, data, (c) => [\n { id: `${id}-fill`, type: \"fill\", source: id, paint: { \"fill-color\": c.accent, \"fill-opacity\": tone === \"soft\" ? 0.1 : 0.14 } },\n { id: `${id}-line`, type: \"line\", source: id, paint: { \"line-color\": c.accent, \"line-width\": tone === \"soft\" ? 1 : 2, \"line-opacity\": tone === \"soft\" ? 0.4 : 0.9, ...(tone === \"accent\" ? { \"line-dasharray\": [2, 1.5] } : {}) } },\n ]);\n return null;\n}\n\nexport type ClusterPoint = { id: string; position: LngLat; label: string };\n\nexport type ClusterProps = {\n /** The points: many of them (creators, pick-up points, events). */\n points: readonly ClusterPoint[];\n /** Pressing a single point. A group zooms in to open itself. */\n onPointPress?: (point: ClusterPoint) => void;\n /** The radius, in pixels, within which points group. Default 48. */\n radius?: number;\n};\n\n/** Many points grouped while they are close: a disc with the count, opened by zooming in; each point is listed for screen readers. */\nexport function Cluster({ points, onPointPress, radius = 48 }: ClusterProps) {\n const { map: m, ready, reduce, places } = useMap();\n const id = `kz-cluster-${React.useId().replace(/[^a-zA-Z0-9]/g, \"\")}`;\n const data = React.useMemo<GeoJSON.FeatureCollection>(\n () => ({ type: \"FeatureCollection\", features: points.map((p) => ({ type: \"Feature\", properties: { id: p.id, label: p.label }, geometry: { type: \"Point\", coordinates: [...p.position] } })) }),\n [points],\n );\n React.useEffect(() => {\n for (const p of points) places.add(`${id}-${p.id}`, p.label);\n return () => points.forEach((p) => places.remove(`${id}-${p.id}`));\n }, [points, places, id]);\n useGeoLayer(\n id,\n data,\n (c) => [\n { id: `${id}-groups`, type: \"circle\", source: id, filter: [\"has\", \"point_count\"], paint: { \"circle-color\": c.cluster.fill, \"circle-opacity\": 0.95, \"circle-radius\": [\"step\", [\"get\", \"point_count\"], 16, 10, 20, 50, 26], \"circle-stroke-width\": 3, \"circle-stroke-color\": c.cluster.stroke } },\n { id: `${id}-count`, type: \"symbol\", source: id, filter: [\"has\", \"point_count\"], layout: { \"text-field\": [\"get\", \"point_count_abbreviated\"], \"text-font\": [\"Noto Sans Medium\"], \"text-size\": 13 }, paint: { \"text-color\": c.cluster.text } },\n { id: `${id}-points`, type: \"circle\", source: id, filter: [\"!\", [\"has\", \"point_count\"]], paint: { \"circle-color\": c.point.fill, \"circle-radius\": 7, \"circle-stroke-width\": 2.5, \"circle-stroke-color\": c.point.stroke } },\n ],\n { cluster: true, clusterRadius: radius, clusterMaxZoom: 15 },\n );\n React.useEffect(() => {\n if (!m || !ready) return;\n const openGroup = async (e: { features?: { properties: Record<string, unknown>; geometry: GeoJSON.Geometry }[] }) => {\n const f = e.features?.[0];\n if (!f) return;\n const src = m.getSource(id) as unknown as { getClusterExpansionZoom: (id: number) => Promise<number> };\n const z = await src.getClusterExpansionZoom(f.properties.cluster_id as number);\n const center = (f.geometry as GeoJSON.Point).coordinates as [number, number];\n if (reduce) m.jumpTo({ center, zoom: z });\n else m.easeTo({ center, zoom: z });\n };\n const pressPoint = (e: { features?: { properties: Record<string, unknown> }[] }) => {\n const pid = e.features?.[0]?.properties.id;\n const point = points.find((p) => p.id === pid);\n if (point) onPointPress?.(point);\n };\n m.on(\"click\", `${id}-groups`, openGroup as never);\n m.on(\"click\", `${id}-points`, pressPoint as never);\n return () => {\n m.off(\"click\", `${id}-groups`, openGroup as never);\n m.off(\"click\", `${id}-points`, pressPoint as never);\n };\n }, [m, ready, id, points, onPointPress, reduce]);\n return null;\n}\n\nexport { MapRoot as Map };\n"
1053
1098
  },
1054
1099
  {
1055
1100
  "path": "map/meta.ts",
1056
- "content": "import type { ComponentMeta } from \"../meta\";\n\nexport const meta = {\n title: \"Map\",\n summary:\n \"Maps that cost nothing per view — MapLibre (open source) over Protomaps tiles on the Krizaka CDN, painted from the tokens in dark or light and in the product's accent — with markers, clusters, the person's position, a radius and a location picker.\",\n status: \"beta\",\n category: \"data-display\",\n domain: \"maps\",\n platforms: \"both\",\n parity: { desktop: \"web\" },\n whenToUse: [\n \"To show where things are: pick-up points, creators near you, an event's venue.\",\n \"`Cluster` for many points (dozens to thousands): they group while close and open by zooming in.\",\n \"`LocationPicker` to choose a place: a meeting point, a delivery address, the centre of a search with its radius.\",\n \"`StaticMap` where a live map is too much (a card, a list, an e-mail) and as the `fallback` of every `Map`.\",\n ],\n whenNotToUse: [\n { when: \"For an address typed or searched: a text field (geocoding is a server's job — Nominatim or Photon self-hosted later), the map only confirms it.\", use: \"field\" },\n { when: \"For figures by country or region (a choropleth): a chart.\", use: \"stat\" },\n ],\n bestPractices: [\n \"Give every map a `label` and every marker a `label`: they are read as the list of places in place of the map.\",\n \"Always pass a `fallback` (`StaticMap` with the same centre and places): it shows while the engine loads and for good without WebGL.\",\n \"Motion on a map: `Marker drop={index * 90}` drops pins in turn, `Route` draws its line once (and a `courier` makes one trip, `repeatAfter` repeats it while the map is on screen), `Pulse` beats around a hot spot. The drawing is finite — nothing runs afterwards — and everything is in place at once under reduced motion.\",\n \"Ask for the position only on a press (`LocationPicker`'s Near me), never on load; every refusal has its words.\",\n \"Keep the attribution visible (OpenStreetMap's licence, the ODbL, asks for it): the components draw it.\",\n \"Install the engine only where a map is shown: `maplibre-gl` (web) or `@maplibre/maplibre-react-native` (Expo) — optional peers.\",\n ],\n accessibility: {\n keyboard: [\n { keys: \"Tab\", action: \"The map (a region named by `label`), then its buttons: zoom, the markers that do something, Near me.\" },\n { keys: \"Arrow keys\", action: \"Pan the focused map.\" },\n { keys: \"+ / −\", action: \"Zoom the focused map in or out.\" },\n ],\n notes: [\n \"The canvas is hidden from assistive technologies: the places are read as a list (each `Marker`, `Cluster` point and the person's position by its `label`).\",\n \"A marker with `onPress` is a button named by its label (`aria-pressed` when it can be chosen); the chosen one shows its name above it.\",\n \"Under reduced motion the camera jumps instead of flying and the position's pulse stands still.\",\n \"Colours come from the tokens: the water is the accent softened, roads and labels the text roles — readable in both schemes.\",\n ],\n },\n related: [\"dialog\", \"search-field\", \"chip\"],\n web: {\n imports: [\"Map\", \"Marker\", \"Cluster\", \"UserPosition\", \"RadiusCircle\", \"Route\", \"Pulse\", \"LocationPicker\", \"StaticMap\", \"mapStyle\", \"distanceMeters\", \"formatDistance\", \"pathLength\", \"pointAlong\", \"sliceLine\"],\n examples: [\n { name: \"places\", title: \"Places\", description: \"Pick-up points in Montréal: markers are buttons, the chosen one shows its name.\" },\n { name: \"cluster\", title: \"Cluster\", description: \"Sixty creators grouped while they are close; a group opens by zooming in.\" },\n { name: \"location-picker\", title: \"Location picker\", description: \"A meeting point under the pin, its distance from the person, a 1-km zone and Near me.\" },\n { name: \"route\", title: \"Route\", description: \"A delivery: pins that drop, a route that draws itself, a courier that travels it, a demand pulse — still under reduced motion.\" },\n { name: \"static\", title: \"Static map\", description: \"The places on the map's paper, without an engine: a card, a list item, a fallback.\" },\n ],\n },\n native: {\n entry: \"@krizaka/ui/native/map\",\n imports: [\"Map\", \"Marker\", \"Cluster\", \"UserPosition\", \"RadiusCircle\", \"LocationPicker\"],\n differences: [\n \"MapLibre Native (`@maplibre/maplibre-react-native`, an optional peer, with its Expo config plugin): the same style and tiles as the web — it reads `pmtiles://` itself.\",\n \"A marker's details open in a `Sheet` (`@krizaka/ui/native`); markers and Near me play a haptic.\",\n \"Near me asks the system's permission through MapLibre's `LocationManager` when pressed; the app declares the location usage in its config.\",\n \"The map's name lists its places for VoiceOver and TalkBack; the screenshots of these stories are drawn by a stand-in (the markers placed, not the tiles).\",\n ],\n examples: [\n { name: \"places\", title: \"Places\", description: \"Pick-up points: a marker pressed opens its details in a bottom sheet.\" },\n { name: \"location-picker\", title: \"Location picker\", description: \"A meeting point under the pin; Near me on request.\" },\n ],\n },\n} satisfies ComponentMeta;\n"
1101
+ "content": "import type { ComponentMeta } from \"../meta\";\n\nexport const meta = {\n title: \"Map\",\n summary:\n \"Maps that cost nothing per view — MapLibre (open source) over Protomaps tiles on the Krizaka CDN, painted from the tokens in dark or light and in the product's accent — with markers, clusters, the person's position, a radius and a location picker.\",\n status: \"beta\",\n category: \"data-display\",\n domain: \"maps\",\n platforms: \"both\",\n parity: { desktop: \"web\" },\n whenToUse: [\n \"To show where things are: pick-up points, creators near you, an event's venue.\",\n \"`Cluster` for many points (dozens to thousands): they group while close and open by zooming in.\",\n \"`LocationPicker` to choose a place: a meeting point, a delivery address, the centre of a search with its radius.\",\n \"`StaticMap` where a live map is too much (a card, a list, an e-mail) and as the `fallback` of every `Map`.\",\n ],\n whenNotToUse: [\n { when: \"For an address typed or searched: a text field (geocoding is a server's job — Nominatim or Photon self-hosted later), the map only confirms it.\", use: \"field\" },\n { when: \"For figures by country or region (a choropleth): a chart.\", use: \"stat\" },\n ],\n bestPractices: [\n \"Give every map a `label` and every marker a `label`: they are read as the list of places in place of the map.\",\n \"Always pass a `fallback` (`StaticMap` with the same centre and places): it shows while the engine loads and for good without WebGL.\",\n \"Motion on a map: `Marker drop={index * 90}` drops pins in turn, `Route` draws its line once (and a `courier` makes one trip, `repeatAfter` repeats it while the map is on screen), `Pulse` beats around a hot spot. The drawing is finite — nothing runs afterwards — and everything is in place at once under reduced motion.\",\n \"Ask for the position only on a press (`LocationPicker`'s Near me), never on load; every refusal has its words.\",\n \"`variant` is the look: `plain` (the product register, default), `notebook` (the Cahier — paper and ink, a cluster as a manila tag, a lone place in the margin's red). `scheme=\\\"auto\\\"` (default) follows the page; `dark` or `light` pins it. Both come from the tokens — never a hand-written map style.\",\n \"`MapPin` (from `@krizaka/ui/map/pin`) is the marker's face when the dot is not enough: put it in a `Marker`'s children. Its state is also said by shape (hollow visited, dashed closed, larger selected).\",\n \"Keep the attribution visible (OpenStreetMap's licence, the ODbL, asks for it): the components draw it.\",\n \"Import the place sheet from `@krizaka/ui/map/sheet` (`MapSheet`) and the cards from `@krizaka/ui/map/cards` (`MapInfoCard`, `RouteCard`, `routeLinks`): their own entries, so a page that only draws a map does not pay for them.\",\n \"Install the engine only where a map is shown: `maplibre-gl` (web) or `@maplibre/maplibre-react-native` (Expo) — optional peers.\",\n ],\n accessibility: {\n keyboard: [\n { keys: \"Tab\", action: \"The map (a region named by `label`), then its buttons: zoom, the markers that do something, Near me.\" },\n { keys: \"Arrow keys\", action: \"Pan the focused map.\" },\n { keys: \"+ / −\", action: \"Zoom the focused map in or out.\" },\n ],\n notes: [\n \"The canvas is hidden from assistive technologies: the places are read as a list (each `Marker`, `Cluster` point and the person's position by its `label`).\",\n \"A marker with `onPress` is a button named by its label (`aria-pressed` when it can be chosen); the chosen one shows its name above it.\",\n \"Under reduced motion the camera jumps instead of flying and the position's pulse stands still.\",\n \"Colours come from the tokens: the water is the accent softened, roads and labels the text roles — readable in both schemes.\",\n ],\n },\n related: [\"dialog\", \"search-field\", \"chip\"],\n web: {\n imports: [\"Map\", \"Marker\", \"Cluster\", \"UserPosition\", \"RadiusCircle\", \"Route\", \"Pulse\", \"LocationPicker\", \"StaticMap\", \"mapStyle\", \"distanceMeters\", \"formatDistance\", \"pathLength\", \"pointAlong\", \"sliceLine\"],\n examples: [\n { name: \"places\", title: \"Places\", description: \"Pick-up points in Montréal: markers are buttons, the chosen one shows its name.\" },\n { name: \"cluster\", title: \"Cluster\", description: \"Sixty creators grouped while they are close; a group opens by zooming in.\" },\n { name: \"location-picker\", title: \"Location picker\", description: \"A meeting point under the pin, its distance from the person, a 1-km zone and Near me.\" },\n { name: \"route\", title: \"Route\", description: \"A delivery: pins that drop, a route that draws itself, a courier that travels it, a demand pulse — still under reduced motion.\" },\n { name: \"place-sheet\", title: \"Place sheet\", description: \"A non-modal sheet over the map (snap points on a phone, a side card from md): an info card with one action and a route card that opens the person's own navigation app.\" },\n { name: \"pins\", title: \"Pins\", description: \"MapPin in its three shapes (drop, disc, the Cahier's tag) and four states (default, selected, visited, closed): the state is said by shape as well as colour.\" },\n { name: \"static\", title: \"Static map\", description: \"The places on the map's paper, without an engine: a card, a list item, a fallback.\" },\n ],\n },\n native: {\n entry: \"@krizaka/ui/native/map\",\n imports: [\"Map\", \"Marker\", \"Cluster\", \"UserPosition\", \"RadiusCircle\", \"LocationPicker\"],\n differences: [\n \"MapLibre Native (`@maplibre/maplibre-react-native`, an optional peer, with its Expo config plugin): the same style and tiles as the web — it reads `pmtiles://` itself.\",\n \"A marker's details open in a `Sheet` (`@krizaka/ui/native`); markers and Near me play a haptic.\",\n \"Near me asks the system's permission through MapLibre's `LocationManager` when pressed; the app declares the location usage in its config.\",\n \"The map's name lists its places for VoiceOver and TalkBack; the screenshots of these stories are drawn by a stand-in (the markers placed, not the tiles).\",\n ],\n examples: [\n { name: \"places\", title: \"Places\", description: \"Pick-up points: a marker pressed opens its details in a bottom sheet.\" },\n { name: \"location-picker\", title: \"Location picker\", description: \"A meeting point under the pin; Near me on request.\" },\n ],\n },\n} satisfies ComponentMeta;\n"
1102
+ },
1103
+ {
1104
+ "path": "map/pin/index.ts",
1105
+ "content": "/**\n * @krizaka/ui/map/pin — `MapPin`, the marker's face when a dot is not enough (drop, disc, the Cahier's tag × default,\n * selected, visited, closed). Apart from `./map`, so a page that only draws a map does not pay for it. Put it in a `Marker`'s children.\n */\nexport { MapPin, mapPin, type MapPinProps, type MapPinShape, type MapPinState } from \"./map-pin\";\n"
1106
+ },
1107
+ {
1108
+ "path": "map/pin/map-pin.tsx",
1109
+ "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { tv } from \"../../tv\";\n\nexport const mapPin = tv({\n slots: {\n root: \"relative inline-flex items-center justify-center text-on-accent transition-transform motion-reduce:transition-none\",\n shape: \"block h-full w-full overflow-visible drop-shadow-md\",\n glyph: \"absolute inset-0 flex items-center justify-center text-[0.55em] font-semibold leading-none [&>svg]:h-[55%] [&>svg]:w-[55%]\",\n },\n variants: {\n selected: {\n true: { root: \"scale-125\" },\n },\n },\n});\n\nexport type MapPinShape = \"drop\" | \"disc\" | \"tag\";\nexport type MapPinState = \"default\" | \"selected\" | \"visited\" | \"closed\";\n\nexport type MapPinProps = {\n /** `drop` (a pin, its tip on the place), `disc` (a dot with a ring) or `tag` (the Cahier's manila tag with its eyelet). Default `drop`. */\n shape?: MapPinShape;\n /** `default`; `selected` (larger, the ring doubled); `visited` (hollow: seen already); `closed` (greyed: not available now). */\n state?: MapPinState;\n /** `accent` (the product's colour) or `margin` (the notebook's red). Default `accent`. */\n tone?: \"accent\" | \"margin\";\n /** Its size in pixels (the width). Default 28. */\n size?: number;\n /** A short mark or an icon in the head of the pin (\"3\", an icon). */\n children?: React.ReactNode;\n className?: string;\n};\n\nconst PATHS: Record<MapPinShape, { d: string; viewBox: string; height: number; head: [number, number] }> = {\n drop: { d: \"M12 1C6.2 1 1.5 5.6 1.5 11.3 1.5 18.6 12 31 12 31s10.5-12.4 10.5-19.7C22.5 5.6 17.8 1 12 1Z\", viewBox: \"0 0 24 32\", height: 32 / 24, head: [12, 11.5] },\n disc: { d: \"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Z\", viewBox: \"0 0 24 24\", height: 1, head: [12, 12] },\n tag: { d: \"M5 2h14a2 2 0 0 1 2 2v12l-9 7.5L3 16V4a2 2 0 0 1 2-2Z\", viewBox: \"0 0 24 26\", height: 26 / 24, head: [12, 10] },\n};\n\ntype PinColours = { edge: string; fill: string; stroke: string; glyph: string; headFill: string };\n\n/** The colours a pin wears for its shape, state and tone: the state is also said by shape (hollow, struck), never by colour alone. */\nfunction pinColours(shape: MapPinShape, state: MapPinState, tone: \"accent\" | \"margin\"): PinColours {\n const tag = shape === \"tag\";\n const base = tag ? \"var(--kz-paper-tag)\" : `var(--kz-${tone === \"margin\" ? \"paper-rule-margin\" : \"accent\"})`;\n const edge = tag ? \"var(--kz-paper-tag-edge)\" : \"var(--kz-on-accent)\";\n const muted = \"var(--kz-text-muted)\";\n if (state === \"closed\") return { edge, fill: \"var(--kz-surface-3)\", stroke: muted, glyph: muted, headFill: \"none\" };\n if (state === \"visited\") return { edge, fill: \"var(--kz-surface-1)\", stroke: base, glyph: base, headFill: base };\n return { edge, fill: base, stroke: edge, glyph: tag ? \"var(--kz-paper-tag-ink)\" : edge, headFill: \"var(--kz-surface-0)\" };\n}\n\nconst GLYPH_TOP: Record<MapPinShape, string | number> = { drop: \"-8%\", tag: \"6%\", disc: 0 };\n\n/**\n * A pin for a `Marker`'s children: three shapes, four states, drawn from the tokens (both themes). Decorative by itself —\n * the `Marker` carries the label — and the state is also said by shape (hollow, struck), never by colour alone.\n */\nexport function MapPin({ shape = \"drop\", state = \"default\", tone = \"accent\", size = 28, children, className }: Readonly<MapPinProps>) {\n const s = mapPin({ selected: state === \"selected\" });\n const p = PATHS[shape];\n const c = pinColours(shape, state, tone);\n const closed = state === \"closed\";\n return (\n <span className={s.root({ className })} style={{ width: size, height: size * p.height }} data-shape={shape} data-state={state} aria-hidden=\"true\">\n <svg className={s.shape()} viewBox={p.viewBox} focusable=\"false\">\n <path d={p.d} fill={c.fill} stroke={c.stroke} strokeWidth={state === \"selected\" ? 2.5 : 1.75} strokeDasharray={closed ? \"3 2\" : undefined} />\n {shape === \"tag\" ? <circle cx={12} cy={5.5} r={1.6} fill=\"var(--kz-surface-0)\" stroke={c.edge} strokeWidth={1} /> : null}\n {children ? null : <circle cx={p.head[0]} cy={p.head[1]} r={shape === \"disc\" ? 3 : 3.2} fill={c.headFill} opacity={closed ? 0 : 1} />}\n </svg>\n {children ? (\n <span className={s.glyph()} style={{ color: c.glyph, top: GLYPH_TOP[shape] }}>\n {children}\n </span>\n ) : null}\n </span>\n );\n}\n"
1110
+ },
1111
+ {
1112
+ "path": "map/sheet/index.ts",
1113
+ "content": "/**\n * @krizaka/ui/map/sheet — `MapSheet`, the non-modal sheet over a map (snap points on a phone, a side card from md). Apart\n * from `./map`, so a page that only draws a map does not pay for it. Client (\"use client\").\n */\nexport { MAP_SHEET_SNAPS, MapSheet, mapSheet, type MapSheetProps, type MapSheetSnap } from \"./map-sheet\";\n"
1114
+ },
1115
+ {
1116
+ "path": "map/sheet/map-sheet.tsx",
1117
+ "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { tv } from \"../../tv\";\n\nexport const mapSheet = tv({\n slots: {\n root: \"absolute inset-x-0 bottom-0 z-10 flex max-h-full flex-col rounded-t-2xl border border-border-subtle bg-surface-1 text-fg shadow-lg transition-[height] duration-200 motion-reduce:transition-none md:inset-y-3 md:left-3 md:right-auto md:max-h-none md:w-[22rem] md:rounded-2xl\",\n handle: \"flex h-6 w-full shrink-0 items-center justify-center md:hidden focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-border-focus\",\n grip: \"h-1 w-10 rounded-full bg-border-default\",\n body: \"min-h-0 flex-1 overflow-y-auto px-4 pb-4 md:pt-4\",\n },\n variants: {\n snap: {\n peek: { root: \"h-24 md:h-auto\" },\n half: { root: \"h-1/2 md:h-auto\" },\n full: { root: \"h-[92%] md:h-auto\" },\n },\n },\n defaultVariants: { snap: \"peek\" },\n});\n\nexport type MapSheetSnap = \"peek\" | \"half\" | \"full\";\nexport const MAP_SHEET_SNAPS: readonly MapSheetSnap[] = [\"peek\", \"half\", \"full\"];\n\nexport type MapSheetProps = Omit<React.ComponentProps<\"section\">, \"children\"> & {\n /** What the sheet is, passed translated: its accessible name (\"Place details\"). */\n label: string;\n /** The content: an info card, a route card, a list. */\n children: React.ReactNode;\n /** The snap point, when controlled. */\n snap?: MapSheetSnap;\n /** The snap point at the start, when not controlled. Default \"peek\". */\n defaultSnap?: MapSheetSnap;\n /** Called with the new snap point (the handle: a press cycles, ArrowUp / ArrowDown step, Home / End jump). */\n onSnapChange?: (snap: MapSheetSnap) => void;\n /** The handle's name, translated (\"Resize the panel\"). */\n handleLabel: string;\n};\n\n/**\n * A NON-modal sheet over a map: the map stays alive and reachable behind it (no scrim, no focus trap, nothing made\n * inert). On a phone it rises from the bottom with three snap points; from the `md` breakpoint it is a card at the\n * side and the handle disappears. Place it in the map's positioned container.\n */\nexport function MapSheet({ label, children, snap, defaultSnap = \"peek\", onSnapChange, handleLabel, className, ...props }: MapSheetProps) {\n const [inner, setInner] = React.useState<MapSheetSnap>(defaultSnap);\n const current = snap ?? inner;\n const set = (next: MapSheetSnap) => {\n if (snap === undefined) setInner(next);\n onSnapChange?.(next);\n };\n const step = (by: number) => set(MAP_SHEET_SNAPS[Math.min(MAP_SHEET_SNAPS.length - 1, Math.max(0, MAP_SHEET_SNAPS.indexOf(current) + by))]!);\n const s = mapSheet({ snap: current });\n return (\n <section {...props} aria-label={label} data-snap={current} className={s.root({ className })}>\n <button\n type=\"button\"\n className={s.handle()}\n aria-label={handleLabel}\n aria-expanded={current !== \"peek\"}\n onClick={() => set(MAP_SHEET_SNAPS[(MAP_SHEET_SNAPS.indexOf(current) + 1) % MAP_SHEET_SNAPS.length]!)}\n onKeyDown={(e) => {\n const move = { ArrowUp: () => step(1), ArrowDown: () => step(-1), Home: () => set(\"peek\"), End: () => set(\"full\") }[e.key];\n if (!move) return;\n e.preventDefault();\n move();\n }}\n >\n <span className={s.grip()} aria-hidden />\n </button>\n <div className={s.body()}>{children}</div>\n </section>\n );\n}\n"
1057
1118
  },
1058
1119
  {
1059
1120
  "path": "map/static-map.tsx",
@@ -1061,7 +1122,7 @@
1061
1122
  },
1062
1123
  {
1063
1124
  "path": "map/style.ts",
1064
- "content": "// The Krizaka map style, generated from the tokens (no hand-written colour): Protomaps' basemap layers\n// (@protomaps/basemaps) painted with a flavour drawn from `@krizaka/tokens` — the surfaces for the land, the accent\n// softened for the water, the text roles for the labels — in dark or light, the product's accent where a brand asks.\n// Platform-neutral: the web `Map` and the native `Map` both read it.\nimport { brands, themes } from \"@krizaka/tokens/native\";\nimport { type Flavor, layers, namedFlavor } from \"@protomaps/basemaps\";\n\nimport { MAP_ATTRIBUTION, mapAssets } from \"./assets\";\n\n/** A product of the family: its accent paints the map. */\nexport type MapBrand = keyof typeof brands;\n\n/** A colour mixed into another (`#rrggbb` only): `t` = 0 gives `a`, 1 gives `b`. */\nexport function mix(a: string, b: string, t: number): string {\n const p = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));\n const [x, y] = [p(a), p(b)];\n return `#${x.map((v, i) => Math.round(v + (y[i]! - v) * t).toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/** The colours of the map in a scheme (and a brand): what the style, the markers and the static map share. */\nexport function mapPalette(scheme: \"dark\" | \"light\", brand: MapBrand = \"krizaka\") {\n const t = { ...themes[scheme], ...(brands as Record<string, Partial<Record<\"dark\" | \"light\", Partial<typeof themes.dark>>>>)[brand]?.[scheme] };\n const dark = scheme === \"dark\";\n const land = dark ? t.surface1 : t.surface0;\n return {\n land,\n background: dark ? t.surface0 : t.surface2,\n water: mix(land, t.accent, dark ? 0.18 : 0.14),\n park: mix(land, t.success, dark ? 0.1 : 0.12),\n road: dark ? mix(land, t.textPrimary, 0.12) : \"#ffffff\",\n roadMajor: dark ? mix(land, t.textPrimary, 0.2) : mix(land, t.textPrimary, 0.06),\n casing: mix(land, t.textPrimary, dark ? 0.05 : 0.12),\n building: mix(land, t.textPrimary, dark ? 0.06 : 0.07),\n boundary: mix(land, t.textPrimary, 0.3),\n label: t.textSecondary,\n labelStrong: t.textPrimary,\n halo: land,\n accent: t.accent,\n onAccent: t.onAccent,\n };\n}\n\n/** The basemap flavour of a palette: every role of Protomaps' layers filled from the tokens. */\nexport function mapFlavor(scheme: \"dark\" | \"light\", brand?: MapBrand): Flavor {\n const c = mapPalette(scheme, brand);\n const base = namedFlavor(scheme);\n return {\n ...base,\n background: c.background,\n earth: c.land,\n park_a: c.park,\n park_b: c.park,\n wood_a: c.park,\n wood_b: c.park,\n scrub_a: c.park,\n scrub_b: c.park,\n glacier: c.land,\n sand: c.land,\n beach: c.land,\n zoo: c.park,\n hospital: c.land,\n industrial: c.land,\n school: c.land,\n military: c.land,\n aerodrome: c.land,\n pedestrian: c.land,\n runway: c.building,\n water: c.water,\n buildings: c.building,\n pier: c.building,\n boundaries: c.boundary,\n railway: c.casing,\n other: c.road,\n minor_service: c.road,\n minor_a: c.road,\n minor_b: c.road,\n link: c.road,\n major: c.roadMajor,\n highway: c.roadMajor,\n bridges_other: c.road,\n bridges_minor: c.road,\n bridges_link: c.road,\n bridges_major: c.roadMajor,\n bridges_highway: c.roadMajor,\n tunnel_other: c.road,\n tunnel_minor: c.road,\n tunnel_link: c.road,\n tunnel_major: c.roadMajor,\n tunnel_highway: c.roadMajor,\n minor_service_casing: c.casing,\n minor_casing: c.casing,\n link_casing: c.casing,\n major_casing_late: c.casing,\n major_casing_early: c.casing,\n highway_casing_late: c.casing,\n highway_casing_early: c.casing,\n bridges_other_casing: c.casing,\n bridges_minor_casing: c.casing,\n bridges_link_casing: c.casing,\n bridges_major_casing: c.casing,\n bridges_highway_casing: c.casing,\n tunnel_other_casing: c.casing,\n tunnel_minor_casing: c.casing,\n tunnel_link_casing: c.casing,\n tunnel_major_casing: c.casing,\n tunnel_highway_casing: c.casing,\n roads_label_minor: c.label,\n roads_label_minor_halo: c.halo,\n roads_label_major: c.label,\n roads_label_major_halo: c.halo,\n ocean_label: c.label,\n subplace_label: c.label,\n subplace_label_halo: c.halo,\n city_label: c.labelStrong,\n city_label_halo: c.halo,\n state_label: c.label,\n state_label_halo: c.halo,\n country_label: c.label,\n address_label: c.label,\n address_label_halo: c.halo,\n regular: \"Noto Sans Regular\",\n bold: \"Noto Sans Medium\",\n italic: \"Noto Sans Italic\",\n // No point-of-interest icons (no sprite to host): the app's own markers carry the places that matter.\n pois: undefined,\n landcover: undefined,\n };\n}\n\n/** A region of the basemap: its PMTiles file and the zoom up to which it has tiles. */\nexport type MapRegion = { url: string; maxzoom: number };\n\nexport type MapStyleOptions = {\n /** `dark` or `light`: the scheme of the page or the app. */\n scheme: \"dark\" | \"light\";\n /** The product whose accent the map carries (its markers, its water's tint). Default `krizaka`. */\n brand?: MapBrand;\n /** The language of the labels (`fr`, `en`): the place names in it where OpenStreetMap has them. Default `en`. */\n lang?: string;\n /** The low zooms of the whole world. Default: our world extract (zoom 0–6). */\n world?: MapRegion | null;\n /** The detailed region drawn from zoom 7. Default: Montréal–Québec (up to 14, overzoomed beyond). */\n region?: MapRegion | null;\n /** The glyphs' URL template. Default: our Noto Sans on the CDN. */\n glyphs?: string;\n};\n\n/** The zoom where the detailed region takes over from the world. */\nexport const REGION_FROM_ZOOM = 6.5;\n\n/**\n * The MapLibre style of a Krizaka map (a `StyleSpecification`): the world's low zooms, then the detailed region,\n * painted from the tokens. The `pmtiles://` sources need the PMTiles protocol (the web `Map` registers it; MapLibre\n * Native reads it as it is).\n */\nexport function mapStyle({ scheme, brand, lang = \"en\", world = { url: mapAssets().tiles.world, maxzoom: 6 }, region = { url: mapAssets().tiles.quebec, maxzoom: 14 }, glyphs = mapAssets().glyphs }: MapStyleOptions) {\n const flavor = mapFlavor(scheme, brand);\n const attribution = `<a href=\"${MAP_ATTRIBUTION.protomapsUrl}\">${MAP_ATTRIBUTION.protomaps}</a> · <a href=\"${MAP_ATTRIBUTION.osmUrl}\">${MAP_ATTRIBUTION.osm}</a>`;\n const sources: Record<string, unknown> = {};\n const all: { id: string; minzoom?: number; maxzoom?: number; [k: string]: unknown }[] = [];\n if (world) {\n sources.world = { type: \"vector\", url: `pmtiles://${world.url}`, attribution };\n for (const l of layers(\"world\", flavor, { lang }) as typeof all) {\n if (l.id === \"background\") all.push(l);\n else all.push({ ...l, id: `world-${l.id}`, maxzoom: region ? Math.min(l.maxzoom ?? 24, REGION_FROM_ZOOM) : l.maxzoom });\n }\n }\n if (region) {\n sources.region = { type: \"vector\", url: `pmtiles://${region.url}`, attribution };\n for (const l of layers(\"region\", flavor, { lang }) as typeof all) {\n if (l.id === \"background\") {\n if (!world) all.push(l);\n continue;\n }\n all.push({ ...l, id: `region-${l.id}`, minzoom: world ? Math.max(l.minzoom ?? 0, REGION_FROM_ZOOM) : l.minzoom });\n }\n }\n // No sprite is hosted: a layer that needs an icon (points of interest) is left out — the app's markers carry the places.\n const drawn = all.filter((l) => !(l.layout as Record<string, unknown> | undefined)?.[\"icon-image\"]);\n return { version: 8 as const, glyphs, sources, layers: drawn.map((l) => (l.maxzoom === undefined ? withoutKey(l, \"maxzoom\") : l)) };\n}\n\nconst withoutKey = <T extends Record<string, unknown>>(o: T, key: string) => Object.fromEntries(Object.entries(o).filter(([k]) => k !== key)) as T;\n"
1125
+ "content": "// The Krizaka map style, generated from the tokens (no hand-written colour): Protomaps' basemap layers\n// (@protomaps/basemaps) painted with a flavour drawn from `@krizaka/tokens` — the surfaces for the land, the accent\n// softened for the water, the text roles for the labels — in dark or light, the product's accent where a brand asks.\n// Platform-neutral: the web `Map` and the native `Map` both read it.\nimport { brands, themes } from \"@krizaka/tokens/native\";\nimport { type Flavor, layers, namedFlavor } from \"@protomaps/basemaps\";\n\nimport { MAP_ATTRIBUTION, mapAssets } from \"./assets\";\n\n/** A product of the family: its accent paints the map. */\nexport type MapBrand = keyof typeof brands;\n\n/** A colour mixed into another (`#rrggbb` only): `t` = 0 gives `a`, 1 gives `b`. */\nexport function mix(a: string, b: string, t: number): string {\n const p = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));\n const [x, y] = [p(a), p(b)];\n return `#${x.map((v, i) => Math.round(v + (y[i]! - v) * t).toString(16).padStart(2, \"0\")).join(\"\")}`;\n}\n\n/**\n * The look of the map: `plain` (the product register) or `notebook` (the Cahier: ink lines on the paper in light, chalk on\n * the slate in dark, the margin's red for the main roads).\n */\nexport type MapVariant = \"plain\" | \"notebook\";\n\n/** The scheme a map is asked for: `auto` follows the page (web) or the app (native). */\nexport type MapScheme = \"dark\" | \"light\" | \"auto\";\n\ntype Tokens = Record<string, string>;\n\n/** A colour mixed into a base, by `d` in dark or `l` in light. */\nconst tint = (base: string, dark: boolean) => (colour: string, d: number, l: number) => mix(base, colour, dark ? d : l);\n\n/** The product register: the page's surfaces, the accent softened for the water, the roads in white (light) or a lift of the land (dark). */\nfunction plainPalette(t: Tokens, dark: boolean) {\n const land = dark ? t.surface1! : t.surface0!;\n const on = tint(land, dark);\n const text = t.textPrimary!;\n return {\n land,\n background: dark ? t.surface0! : t.surface2!,\n water: on(t.accent!, 0.18, 0.14),\n park: on(t.success!, 0.1, 0.12),\n road: dark ? on(text, 0.12, 0) : \"#ffffff\",\n roadMajor: on(text, 0.2, 0.06),\n casing: on(text, 0.05, 0.12),\n building: on(text, 0.06, 0.07),\n boundary: on(text, 0.3, 0.3),\n label: t.textSecondary!,\n labelStrong: text,\n halo: land,\n accent: t.accent!,\n onAccent: t.onAccent!,\n // The clusters and the pins' ring: a disc of the accent in the product register.\n cluster: { fill: t.accent!, stroke: land, text: t.onAccent! },\n point: { fill: t.accent!, stroke: land },\n };\n}\n\ntype Palette = ReturnType<typeof plainPalette>;\n\n/** `notebook`: the paper is the page's surface; the lines are the ink, drawn without casings, as with a pen. */\nfunction notebookPalette(plain: Palette, t: Tokens, dark: boolean): Palette {\n const paper = t.surface0!;\n const margin = t.paperRuleMargin!;\n const on = tint(paper, dark);\n const ink = t.textPrimary!;\n return {\n ...plain,\n land: paper,\n background: paper,\n water: on(t.accent!, 0.26, 0.2),\n park: on(t.paperTag!, 0.7, 0.55),\n road: on(ink, 0.32, 0.28),\n roadMajor: on(margin, 0.75, 0.7),\n casing: paper,\n halo: paper,\n // A cluster is a manila tag with its eyelet edge; a single point is the margin's red.\n cluster: { fill: t.paperTag!, stroke: t.paperTagEdge!, text: t.paperTagInk! },\n point: { fill: margin, stroke: paper },\n };\n}\n\n/** The colours of the map in a scheme (and a brand, a variant): what the style, the markers, the clusters and the static map share. */\nexport function mapPalette(scheme: \"dark\" | \"light\", brand: MapBrand = \"krizaka\", variant: MapVariant = \"plain\") {\n const t = { ...themes[scheme], ...(brands as Record<string, Partial<Record<\"dark\" | \"light\", Partial<typeof themes.dark>>>>)[brand]?.[scheme] } as unknown as Tokens;\n const dark = scheme === \"dark\";\n const plain = plainPalette(t, dark);\n if (variant === \"notebook\") return notebookPalette(plain, t, dark);\n return plain;\n}\n\n/** Which colour of the palette paints each role of the basemap flavour (the first pattern that matches the role's name; the land otherwise). */\nconst FLAVOR_ROLES: [RegExp, string][] = [\n [/halo/, \"halo\"],\n [/city_label/, \"labelStrong\"],\n [/label/, \"label\"],\n [/casing|railway/, \"casing\"],\n [/major|highway/, \"roadMajor\"],\n [/^(other|minor|link|bridges|tunnel)/, \"road\"],\n [/park|wood|scrub|zoo/, \"park\"],\n [/runway|buildings|pier/, \"building\"],\n [/water/, \"water\"],\n [/boundaries/, \"boundary\"],\n [/background/, \"background\"],\n];\n\n/** The basemap flavour of a palette: every role of Protomaps' layers filled from the tokens. */\nexport function mapFlavor(scheme: \"dark\" | \"light\", brand?: MapBrand, variant?: MapVariant): Flavor {\n const c = mapPalette(scheme, brand, variant) as unknown as Record<string, string>;\n const base = namedFlavor(scheme);\n return {\n ...base,\n ...Object.fromEntries(Object.keys(base).map((role) => [role, c[FLAVOR_ROLES.find(([re]) => re.test(role))?.[1] ?? \"land\"]])),\n regular: \"Noto Sans Regular\",\n bold: \"Noto Sans Medium\",\n italic: \"Noto Sans Italic\",\n // No point-of-interest icons (no sprite to host): the app's own markers carry the places that matter.\n pois: undefined,\n landcover: undefined,\n };\n}\n\n/** A region of the basemap: its PMTiles file and the zoom up to which it has tiles. */\nexport type MapRegion = { url: string; maxzoom: number };\n\nexport type MapStyleOptions = {\n /** `dark` or `light`: the scheme of the page or the app. */\n scheme: \"dark\" | \"light\";\n /** The product whose accent the map carries (its markers, its water's tint). Default `krizaka`. */\n brand?: MapBrand;\n /** The look: `plain` (default), or `notebook` (the Cahier's paper and ink). */\n variant?: MapVariant;\n /** The language of the labels (`fr`, `en`): the place names in it where OpenStreetMap has them. Default `en`. */\n lang?: string;\n /** The low zooms of the whole world. Default: our world extract (zoom 0–6). */\n world?: MapRegion | null;\n /** The detailed region drawn from zoom 7. Default: Montréal–Québec (up to 14, overzoomed beyond). */\n region?: MapRegion | null;\n /** The glyphs' URL template. Default: our Noto Sans on the CDN. */\n glyphs?: string;\n};\n\n/** The zoom where the detailed region takes over from the world. */\nexport const REGION_FROM_ZOOM = 6.5;\n\ntype StyleLayer = { id: string; minzoom?: number; maxzoom?: number; [k: string]: unknown };\n\n/** The world's layers: the background once, the others under `world-` and cut where the region takes over. */\nfunction worldLayers(layerList: StyleLayer[], hasRegion: boolean): StyleLayer[] {\n return layerList.map((l) => {\n if (l.id === \"background\") return l;\n const maxzoom = hasRegion ? Math.min(l.maxzoom ?? 24, REGION_FROM_ZOOM) : l.maxzoom;\n return { ...l, id: `world-${l.id}`, ...(maxzoom === undefined ? {} : { maxzoom }) };\n });\n}\n\n/** The region's layers under `region-`, from the zoom where it takes over; its background only when there is no world. */\nfunction regionLayers(layerList: StyleLayer[], hasWorld: boolean): StyleLayer[] {\n return layerList\n .filter((l) => l.id !== \"background\" || !hasWorld)\n .map((l) => (l.id === \"background\" ? l : { ...l, id: `region-${l.id}`, minzoom: hasWorld ? Math.max(l.minzoom ?? 0, REGION_FROM_ZOOM) : l.minzoom }));\n}\n\n/**\n * The MapLibre style of a Krizaka map (a `StyleSpecification`): the world's low zooms, then the detailed region,\n * painted from the tokens. The `pmtiles://` sources need the PMTiles protocol (the web `Map` registers it; MapLibre\n * Native reads it as it is).\n */\nexport function mapStyle({ scheme, brand, variant, lang = \"en\", world = { url: mapAssets().tiles.world, maxzoom: 6 }, region = { url: mapAssets().tiles.quebec, maxzoom: 14 }, glyphs = mapAssets().glyphs }: MapStyleOptions) {\n const flavor = mapFlavor(scheme, brand, variant);\n const attribution = `<a href=\"${MAP_ATTRIBUTION.protomapsUrl}\">${MAP_ATTRIBUTION.protomaps}</a> · <a href=\"${MAP_ATTRIBUTION.osmUrl}\">${MAP_ATTRIBUTION.osm}</a>`;\n const sources: Record<string, unknown> = {};\n const all: StyleLayer[] = [];\n if (world) {\n sources.world = { type: \"vector\", url: `pmtiles://${world.url}`, attribution };\n all.push(...worldLayers(layers(\"world\", flavor, { lang }) as StyleLayer[], Boolean(region)));\n }\n if (region) {\n sources.region = { type: \"vector\", url: `pmtiles://${region.url}`, attribution };\n all.push(...regionLayers(layers(\"region\", flavor, { lang }) as StyleLayer[], Boolean(world)));\n }\n // No sprite is hosted: a layer that needs an icon (points of interest) is left out — the app's markers carry the places.\n const drawn = all.filter((l) => !(l.layout as Record<string, unknown> | undefined)?.[\"icon-image\"]);\n return { version: 8 as const, glyphs, sources, layers: drawn };\n}\n"
1065
1126
  },
1066
1127
  {
1067
1128
  "path": "media.ts",
@@ -1077,7 +1138,7 @@
1077
1138
  }
1078
1139
  ],
1079
1140
  "dependencies": [
1080
- "@krizaka/tokens@^3.76.0",
1141
+ "@krizaka/tokens@^3.77.0",
1081
1142
  "@protomaps/basemaps@5.7.2",
1082
1143
  "tailwind-variants@^3.3.1"
1083
1144
  ],
@@ -1184,9 +1245,9 @@
1184
1245
  },
1185
1246
  {
1186
1247
  "name": "scheme",
1187
- "type": "\"light\" | \"dark\"",
1248
+ "type": "MapScheme",
1188
1249
  "default": null,
1189
- "description": "The scheme. Default: the page's (`html.light`), followed.",
1250
+ "description": "The scheme: `auto` (default) follows the page (`html.light`) as it changes; `dark` or `light` pins it.",
1190
1251
  "required": false
1191
1252
  },
1192
1253
  {
@@ -1336,9 +1397,16 @@
1336
1397
  },
1337
1398
  {
1338
1399
  "name": "scheme",
1339
- "type": "\"light\" | \"dark\"",
1400
+ "type": "MapScheme",
1401
+ "default": "auto",
1402
+ "description": "The scheme: `auto` (default) follows the page (`html.light`) as it changes; `dark` or `light` pins it.",
1403
+ "required": false
1404
+ },
1405
+ {
1406
+ "name": "variant",
1407
+ "type": "MapVariant",
1340
1408
  "default": null,
1341
- "description": "The scheme. Default: the page's (`html.light`), followed.",
1409
+ "description": "The look: `plain` (default), `notebook` (the Cahier: paper and ink, manila tags for clusters).",
1342
1410
  "required": false
1343
1411
  },
1344
1412
  {
@@ -711,7 +711,7 @@
711
711
  }
712
712
  ],
713
713
  "dependencies": [
714
- "@krizaka/tokens@^3.76.0",
714
+ "@krizaka/tokens@^3.77.0",
715
715
  "radix-ui@^1.8.1",
716
716
  "tailwind-variants@^3.3.1"
717
717
  ],
@@ -336,7 +336,7 @@
336
336
  }
337
337
  ],
338
338
  "dependencies": [
339
- "@krizaka/tokens@^3.76.0",
339
+ "@krizaka/tokens@^3.77.0",
340
340
  "radix-ui@^1.8.1",
341
341
  "tailwind-variants@^3.3.1"
342
342
  ],
@@ -154,7 +154,7 @@
154
154
  },
155
155
  {
156
156
  "path": "shop-gallery/shop-gallery.tsx",
157
- "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"../cn\";\nimport { type ShopGalleryLabels, shopGalleryLabels } from \"./labels\";\n\n// The lightbox is a lazy chunk: nothing of it is loaded until a photo is opened.\nconst Lightbox = React.lazy(() => import(\"./lightbox\"));\n\nexport type ShopGalleryPhoto = {\n id: string;\n /** The tile's image. */\n src: string;\n /** What it shows, in words: the tile's name and the lightbox's caption. */\n alt: string;\n /** The widths the product holds (`/a-400.avif 400w, /a-800.avif 800w, /a-1200.avif 1200w`). */\n srcSet?: string;\n /** The lightbox's image at full resolution (default: `src`). */\n fullSrc?: string;\n fullSrcSet?: string;\n};\n\nexport type ShopGalleryProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n /** The shop's photos, in order, already unique. */\n photos: readonly ShopGalleryPhoto[];\n /** The gallery's accessible name (`Photos of the salon`). */\n label: string;\n /** The tiles' `sizes` (default: the bento's share of a 72 rem page on a desktop, 78 vw on a phone). */\n sizes?: string;\n /** Translated texts; `shopGalleryLabelsFr` for French. */\n labels?: Partial<ShopGalleryLabels>;\n};\n\nconst BENTO = 5;\n\nconst styles = `\n.kz-sg{position:relative}\n.kz-sg-list{margin:0;padding:0;list-style:none;display:grid;grid-template-columns:repeat(2,1fr);gap:.5rem}\n.kz-sg-tile{position:relative;display:block;width:100%;height:100%;padding:0;overflow:hidden;cursor:zoom-in;border:1px solid var(--kz-border-subtle);border-radius:var(--kz-shop-photo-radius,.75rem);background:var(--kz-surface-2);color:var(--kz-text-on-media)}\n.kz-sg-tile img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}\n.kz-sg-tile:focus-visible{outline:2px solid var(--kz-ring);outline-offset:2px}\n.kz-sg-list>li{aspect-ratio:1/1;min-width:0}\n.kz-sg-list>li:first-child:nth-last-child(odd){grid-column:span 2;aspect-ratio:16/10}\n.kz-sg-more,.kz-sg-count{display:none}\n.kz-sg[data-strip=true] .kz-sg-list{display:flex;gap:.75rem;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:none;margin-inline:-1rem;padding-inline:1rem;scroll-padding-inline:1rem;-webkit-mask-image:linear-gradient(to right,transparent,currentcolor 1.25rem,currentcolor calc(100% - 1.25rem),transparent);mask-image:linear-gradient(to right,transparent,currentcolor 1.25rem,currentcolor calc(100% - 1.25rem),transparent)}\n.kz-sg[data-strip=true] .kz-sg-list::-webkit-scrollbar{display:none}\n.kz-sg[data-strip=true] .kz-sg-list>li{flex:0 0 78%;aspect-ratio:4/5;scroll-snap-align:start}\n.kz-sg[data-strip=true] .kz-sg-list>li:first-child:nth-last-child(odd){grid-column:auto;aspect-ratio:4/5}\n.kz-sg[data-strip=true] .kz-sg-count{display:block;margin:.5rem 0 0;text-align:end;font:600 .75rem/1 var(--kz-font-mono,monospace);color:var(--kz-text-secondary)}\n@media (prefers-reduced-motion:no-preference){.kz-sg[data-strip=true] .kz-sg-list{scroll-behavior:smooth}.kz-sg-tile img{transition:transform .35s ease}.kz-sg-tile:hover img{transform:scale(1.03)}}\n@media (min-width:40rem){\n.kz-sg-list{gap:.75rem}\n.kz-sg[data-strip=true] .kz-sg-list{display:grid;overflow:visible;margin-inline:0;padding-inline:0;-webkit-mask-image:none;mask-image:none}\n.kz-sg[data-strip=true] .kz-sg-count{display:none}\n.kz-sg[data-count=\"1\"] .kz-sg-list{grid-template-columns:1fr}\n.kz-sg[data-count=\"1\"] .kz-sg-list>li{aspect-ratio:16/9}\n.kz-sg[data-count=\"2\"] .kz-sg-list>li,.kz-sg[data-count=\"2\"] .kz-sg-list>li:first-child:nth-last-child(odd){aspect-ratio:4/3;grid-column:auto}\n.kz-sg:not([data-count=\"1\"]):not([data-count=\"2\"]) .kz-sg-list{grid-template-columns:repeat(4,1fr);grid-template-rows:repeat(2,1fr);aspect-ratio:2/1}\n.kz-sg:not([data-count=\"1\"]):not([data-count=\"2\"]) .kz-sg-list>li,.kz-sg[data-strip=true] .kz-sg-list>li{aspect-ratio:auto;flex:none}\n.kz-sg:not([data-count=\"1\"]):not([data-count=\"2\"]) .kz-sg-list>li:first-child{grid-column:1/3;grid-row:1/3}\n.kz-sg[data-count=\"3\"] .kz-sg-list>li:nth-child(n+2){grid-column:3/5}\n.kz-sg[data-count=\"4\"] .kz-sg-list>li:nth-child(2){grid-column:3/5}\n.kz-sg[data-strip=true] .kz-sg-list>li:nth-child(n+6){display:none}\n.kz-sg[data-more=true] .kz-sg-list>li:nth-child(5) .kz-sg-more{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--kz-scrim-strong) 62%,transparent);font:700 1.125rem/1.2 var(--kz-font-sans,system-ui);text-align:center}\n}\n`;\n\n/** A shop's photos: a bento mosaic (one 2×2 lead and four tiles, the last one « + N photos »), a snap strip on a phone, and a lightbox. */\nexport function ShopGallery({ photos, label, sizes, labels: given, className, ...props }: ShopGalleryProps) {\n const labels = { ...shopGalleryLabels, ...given };\n const total = photos.length;\n const strip = total >= BENTO;\n const [open, setOpen] = React.useState<number | null>(null);\n const [current, setCurrent] = React.useState(1);\n const tiles = React.useRef<(HTMLButtonElement | null)[]>([]);\n const opener = React.useRef<number>(0);\n if (total === 0) return null;\n\n const tileSizes = sizes ?? (strip ? \"(min-width: 40rem) 36rem, 78vw\" : \"(min-width: 40rem) 36rem, 50vw\");\n const onScroll = (event: React.UIEvent<HTMLUListElement>) => {\n const list = event.currentTarget;\n const first = list.children[0] as HTMLElement | undefined;\n const step = first ? first.offsetWidth + 12 : 0;\n if (step > 0) setCurrent(Math.min(total, Math.max(1, Math.round(list.scrollLeft / step) + 1)));\n };\n return (\n <div className={cn(\"kz-sg\", className)} data-count={total} data-strip={strip || undefined} data-more={total > BENTO || undefined} role=\"group\" aria-label={label} {...props}>\n <style>{styles}</style>\n <ul className=\"kz-sg-list\" onScroll={strip ? onScroll : undefined}>\n {photos.map((photo, i) => (\n <li key={photo.id}>\n <button\n type=\"button\"\n ref={(node) => {\n tiles.current[i] = node;\n }}\n className=\"kz-sg-tile\"\n aria-label={i === BENTO - 1 && total > BENTO ? `${labels.more(total - BENTO + 1)}: ${labels.open(photo.alt, i + 1, total)}` : labels.open(photo.alt, i + 1, total)}\n onClick={() => {\n opener.current = i;\n setOpen(i);\n }}\n >\n <img src={photo.src} srcSet={photo.srcSet} sizes={photo.srcSet ? tileSizes : undefined} alt=\"\" loading=\"lazy\" decoding=\"async\" />\n {i === BENTO - 1 && total > BENTO && <span className=\"kz-sg-more\" aria-hidden>{labels.more(total - BENTO + 1)}</span>}\n </button>\n </li>\n ))}\n </ul>\n {strip && <p className=\"kz-sg-count\" aria-hidden>{labels.counter(current, total)}</p>}\n {open !== null && (\n <React.Suspense fallback={null}>\n <Lightbox\n photos={photos}\n index={open}\n onIndexChange={setOpen}\n onClose={() => setOpen(null)}\n label={label}\n labels={labels}\n returnFocus={() => tiles.current[opener.current] ?? null}\n />\n </React.Suspense>\n )}\n </div>\n );\n}\n"
157
+ "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"../cn\";\nimport { type ShopGalleryLabels, shopGalleryLabels } from \"./labels\";\n\n// The lightbox is a lazy chunk: nothing of it is loaded until a photo is opened.\nconst Lightbox = React.lazy(() => import(\"./lightbox\"));\n\nexport type ShopGalleryPhoto = {\n id: string;\n /** The tile's image. */\n src: string;\n /** What it shows, in words: the tile's name and the lightbox's caption. */\n alt: string;\n /** The widths the product holds (`/a-400.avif 400w, /a-800.avif 800w, /a-1200.avif 1200w`). */\n srcSet?: string;\n /** The lightbox's image at full resolution (default: `src`). */\n fullSrc?: string;\n fullSrcSet?: string;\n};\n\nexport type ShopGalleryProps = Omit<React.ComponentProps<\"div\">, \"children\"> & {\n /** The shop's photos, in order, already unique. */\n photos: readonly ShopGalleryPhoto[];\n /** The gallery's accessible name (`Photos of the salon`). */\n label: string;\n /** The tiles' `sizes` (default: the bento's share of a 72 rem page on a desktop, 78 vw on a phone). */\n sizes?: string;\n /** Translated texts; `shopGalleryLabelsFr` for French. */\n labels?: Partial<ShopGalleryLabels>;\n};\n\nconst BENTO = 5;\n\nconst styles = `\n.kz-sg{position:relative}\n.kz-sg-list{margin:0;padding:0;list-style:none;display:grid;grid-template-columns:repeat(2,1fr);gap:.5rem}\n.kz-sg-tile{position:relative;display:block;width:100%;height:100%;padding:0;overflow:hidden;cursor:zoom-in;border:1px solid var(--kz-border-subtle);border-radius:var(--kz-shop-photo-radius,.75rem);background:var(--kz-surface-2);color:var(--kz-text-on-media)}\n.kz-sg-tile img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}\n.kz-sg-tile:focus-visible{outline:2px solid var(--kz-ring);outline-offset:2px}\n.kz-sg-list>li{aspect-ratio:1/1;min-width:0}\n.kz-sg-list>li:first-child:nth-last-child(odd){grid-column:span 2;aspect-ratio:16/10}\n.kz-sg-more,.kz-sg-count{display:none}\n.kz-sg[data-strip=true] .kz-sg-list{display:flex;gap:.75rem;overflow-x:auto;scroll-snap-type:x mandatory;scrollbar-width:none;margin-inline:-1rem;padding-inline:1rem;scroll-padding-inline:1rem;-webkit-mask-image:linear-gradient(to right,transparent,currentcolor 1.25rem,currentcolor calc(100% - 1.25rem),transparent);mask-image:linear-gradient(to right,transparent,currentcolor 1.25rem,currentcolor calc(100% - 1.25rem),transparent)}\n.kz-sg[data-strip=true] .kz-sg-list::-webkit-scrollbar{display:none}\n.kz-sg[data-strip=true] .kz-sg-list>li{flex:0 0 78%;aspect-ratio:4/5;scroll-snap-align:start}\n.kz-sg[data-strip=true] .kz-sg-list>li:first-child:nth-last-child(odd){grid-column:auto;aspect-ratio:4/5}\n.kz-sg[data-strip=true] .kz-sg-count{display:block;margin:.5rem 0 0;text-align:end;font:600 .75rem/1 var(--kz-font-mono,monospace);color:var(--kz-text-secondary)}\n@media (prefers-reduced-motion:no-preference){.kz-sg[data-strip=true] .kz-sg-list{scroll-behavior:smooth}.kz-sg-tile img{transition:transform .35s ease}.kz-sg-tile:hover img{transform:scale(1.03)}}\n@media (min-width:40rem){\n.kz-sg-list{gap:.75rem}\n.kz-sg[data-strip=true] .kz-sg-list{display:grid;overflow:visible;margin-inline:0;padding-inline:0;-webkit-mask-image:none;mask-image:none}\n.kz-sg[data-strip=true] .kz-sg-count{display:none}\n.kz-sg[data-count=\"1\"] .kz-sg-list{grid-template-columns:1fr}\n.kz-sg[data-count=\"1\"] .kz-sg-list>li{aspect-ratio:16/9}\n.kz-sg[data-count=\"2\"] .kz-sg-list>li,.kz-sg[data-count=\"2\"] .kz-sg-list>li:first-child:nth-last-child(odd){aspect-ratio:4/3;grid-column:auto}\n.kz-sg:not([data-count=\"1\"]):not([data-count=\"2\"]) .kz-sg-list{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:repeat(2,minmax(0,1fr));aspect-ratio:2/1}\n.kz-sg:not([data-count=\"1\"]):not([data-count=\"2\"]) .kz-sg-list>li,.kz-sg[data-strip=true] .kz-sg-list>li{aspect-ratio:auto;flex:none}\n.kz-sg:not([data-count=\"1\"]):not([data-count=\"2\"]) .kz-sg-list>li:first-child{grid-column:1/3;grid-row:1/3;aspect-ratio:auto}\n.kz-sg[data-count=\"3\"] .kz-sg-list>li:nth-child(n+2){grid-column:3/5}\n.kz-sg[data-count=\"4\"] .kz-sg-list>li:nth-child(2){grid-column:3/5}\n.kz-sg[data-strip=true] .kz-sg-list>li:nth-child(n+6){display:none}\n.kz-sg[data-more=true] .kz-sg-list>li:nth-child(5) .kz-sg-more{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--kz-scrim-strong) 62%,transparent);font:700 1.125rem/1.2 var(--kz-font-sans,system-ui);text-align:center}\n}\n`;\n\n/** A shop's photos: a bento mosaic (one 2×2 lead and four tiles, the last one « + N photos »), a snap strip on a phone, and a lightbox. */\nexport function ShopGallery({ photos, label, sizes, labels: given, className, ...props }: ShopGalleryProps) {\n const labels = { ...shopGalleryLabels, ...given };\n const total = photos.length;\n const strip = total >= BENTO;\n const [open, setOpen] = React.useState<number | null>(null);\n const [current, setCurrent] = React.useState(1);\n const tiles = React.useRef<(HTMLButtonElement | null)[]>([]);\n const opener = React.useRef<number>(0);\n if (total === 0) return null;\n\n const tileSizes = sizes ?? (strip ? \"(min-width: 40rem) 36rem, 78vw\" : \"(min-width: 40rem) 36rem, 50vw\");\n const onScroll = (event: React.UIEvent<HTMLUListElement>) => {\n const list = event.currentTarget;\n const first = list.children[0] as HTMLElement | undefined;\n const step = first ? first.offsetWidth + 12 : 0;\n if (step > 0) setCurrent(Math.min(total, Math.max(1, Math.round(list.scrollLeft / step) + 1)));\n };\n return (\n <div className={cn(\"kz-sg\", className)} data-count={total} data-strip={strip || undefined} data-more={total > BENTO || undefined} role=\"group\" aria-label={label} {...props}>\n <style>{styles}</style>\n <ul className=\"kz-sg-list\" onScroll={strip ? onScroll : undefined}>\n {photos.map((photo, i) => (\n <li key={photo.id}>\n <button\n type=\"button\"\n ref={(node) => {\n tiles.current[i] = node;\n }}\n className=\"kz-sg-tile\"\n aria-label={i === BENTO - 1 && total > BENTO ? `${labels.more(total - BENTO + 1)}: ${labels.open(photo.alt, i + 1, total)}` : labels.open(photo.alt, i + 1, total)}\n onClick={() => {\n opener.current = i;\n setOpen(i);\n }}\n >\n <img src={photo.src} srcSet={photo.srcSet} sizes={photo.srcSet ? tileSizes : undefined} alt=\"\" loading=\"lazy\" decoding=\"async\" />\n {i === BENTO - 1 && total > BENTO && <span className=\"kz-sg-more\" aria-hidden>{labels.more(total - BENTO + 1)}</span>}\n </button>\n </li>\n ))}\n </ul>\n {strip && <p className=\"kz-sg-count\" aria-hidden>{labels.counter(current, total)}</p>}\n {open !== null && (\n <React.Suspense fallback={null}>\n <Lightbox\n photos={photos}\n index={open}\n onIndexChange={setOpen}\n onClose={() => setOpen(null)}\n label={label}\n labels={labels}\n returnFocus={() => tiles.current[opener.current] ?? null}\n />\n </React.Suspense>\n )}\n </div>\n );\n}\n"
158
158
  }
159
159
  ],
160
160
  "dependencies": [],