@krizaka/ui 3.83.0 → 3.85.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 (76) hide show
  1. package/dist/app-header/search.js +1 -1
  2. package/dist/app-shell.js +16 -25
  3. package/dist/app-shell.js.map +1 -1
  4. package/dist/bird-plate.js +1 -1
  5. package/dist/card-grid.js +1 -1
  6. package/dist/{chunk-DJ5ZPPWL.js → chunk-7P7I5OQV.js} +2 -2
  7. package/dist/{chunk-27AWSJTK.js → chunk-EDQLPCM4.js} +2 -2
  8. package/dist/chunk-FYPYJ6MW.js +60 -0
  9. package/dist/chunk-FYPYJ6MW.js.map +1 -0
  10. package/dist/chunk-QHVV2JGF.js +144 -0
  11. package/dist/chunk-QHVV2JGF.js.map +1 -0
  12. package/dist/chunk-S2O4NSN5.js +72 -0
  13. package/dist/{chunk-GFRUTPGG.js.map → chunk-S2O4NSN5.js.map} +1 -1
  14. package/dist/chunk-TN5JJ6JI.js +60 -0
  15. package/dist/chunk-TN5JJ6JI.js.map +1 -0
  16. package/dist/{chunk-XVXFMVG3.js → chunk-TVLRE7S3.js} +2 -2
  17. package/dist/chunk-VYZFQE3P.js +518 -0
  18. package/dist/chunk-VYZFQE3P.js.map +1 -0
  19. package/dist/{chunk-7MQNG35Q.js → chunk-ZKKMYIDN.js} +3 -2
  20. package/dist/chunk-ZKKMYIDN.js.map +1 -0
  21. package/dist/code-block.js +2 -2
  22. package/dist/cover-hero.js +3 -3
  23. package/dist/filter-bar.d.ts +3 -3
  24. package/dist/flock.js +1 -1
  25. package/dist/grade-stamp.js +2 -2
  26. package/dist/map.d.ts +16 -2
  27. package/dist/map.js +20 -18
  28. package/dist/map.js.map +1 -1
  29. package/dist/mascot-quote.js +1 -1
  30. package/dist/media-carousel.d.ts +113 -0
  31. package/dist/media-carousel.js +122 -0
  32. package/dist/media-carousel.js.map +1 -0
  33. package/dist/media-player.d.ts +177 -0
  34. package/dist/media-player.js +14 -0
  35. package/dist/media-player.js.map +1 -0
  36. package/dist/motion.css +7 -0
  37. package/dist/player-lightbox-ETBQWDOT.js +148 -0
  38. package/dist/player-lightbox-ETBQWDOT.js.map +1 -0
  39. package/dist/rail-nav.js +3 -3
  40. package/dist/retro-tv-playlist.d.ts +2 -0
  41. package/dist/retro-tv.js +1 -1
  42. package/dist/{schema-CL7t7xqb.d.ts → schema-DgjBz7-8.d.ts} +1 -1
  43. package/dist/shop.d.ts +2 -2
  44. package/dist/site-cahier.js +4 -4
  45. package/dist/taped-photo.js +2 -2
  46. package/dist/toc.js +1 -1
  47. package/dist/versus-card.js +1 -1
  48. package/dist/video-player.d.ts +3 -1
  49. package/dist/video-player.js +1 -1
  50. package/dist/virtual.d.ts +3 -3
  51. package/dist/wall.js +2 -2
  52. package/package.json +32 -4
  53. package/registry/app-frame.json +1 -1
  54. package/registry/examples/map/full-screen.d.ts +4 -0
  55. package/registry/examples/map/full-screen.js +26 -0
  56. package/registry/examples/map/full-screen.tsx +27 -0
  57. package/registry/examples/media-gallery/carousel.d.ts +4 -0
  58. package/registry/examples/media-gallery/carousel.js +22 -0
  59. package/registry/examples/media-gallery/carousel.tsx +20 -0
  60. package/registry/examples/media-gallery/player.d.ts +4 -0
  61. package/registry/examples/media-gallery/player.js +15 -0
  62. package/registry/examples/media-gallery/player.tsx +13 -0
  63. package/registry/index.json +16 -12
  64. package/registry/map.json +31 -4
  65. package/registry/media-gallery.json +57 -6
  66. package/registry/nav-bar.json +1 -1
  67. package/registry/rail-nav.json +1 -1
  68. package/registry/retro-tv.json +14 -0
  69. package/registry/shop.json +1 -1
  70. package/registry/site-footer.json +1 -1
  71. package/registry/video-player.json +15 -1
  72. package/dist/chunk-7MQNG35Q.js.map +0 -1
  73. package/dist/chunk-GFRUTPGG.js +0 -43
  74. /package/dist/{chunk-DJ5ZPPWL.js.map → chunk-7P7I5OQV.js.map} +0 -0
  75. /package/dist/{chunk-27AWSJTK.js.map → chunk-EDQLPCM4.js.map} +0 -0
  76. /package/dist/{chunk-XVXFMVG3.js.map → chunk-TVLRE7S3.js.map} +0 -0
package/registry/map.json CHANGED
@@ -44,6 +44,7 @@
44
44
  "Ask for the position only on a press (`LocationPicker`'s Near me), never on load; every refusal has its words.",
45
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
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).",
47
+ "In a page the wheel scrolls the page, not the map (`gestures=\"page\"`, the default): the map zooms with Ctrl/⌘ + wheel, two fingers on a phone and its + / − buttons, and the engine's overlay says so in the map's words (`labels.gestureHelp`: MapLibre's `CooperativeGesturesHandler.*HelpText` keys). A map that IS the screen (an explorer, full height) opts in with `gestures=\"map\"`.",
47
48
  "Keep the attribution visible (OpenStreetMap's licence, the ODbL, asks for it): the components draw it.",
48
49
  "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.",
49
50
  "Install the engine only where a map is shown: `maplibre-gl` (web) or `@maplibre/maplibre-react-native` (Expo) — optional peers."
@@ -58,6 +59,10 @@
58
59
  "keys": "Arrow keys",
59
60
  "action": "Pan the focused map."
60
61
  },
62
+ {
63
+ "keys": "Ctrl / ⌘ + wheel",
64
+ "action": "Zoom the map; a plain wheel scrolls the page (unless `gestures=\"map\"`)."
65
+ },
61
66
  {
62
67
  "keys": "+ / −",
63
68
  "action": "Zoom the focused map in or out."
@@ -282,6 +287,13 @@
282
287
  "description": "Shown in place of the map while its engine loads, and for good without WebGL: a `StaticMap`, a picture.",
283
288
  "required": false
284
289
  },
290
+ {
291
+ "name": "gestures",
292
+ "type": "MapGestures",
293
+ "default": "page",
294
+ "description": "Who owns the wheel and the fingers. `page` (default): the wheel and one finger scroll the page past the map; the map zooms\nwith Ctrl/⌘ + wheel, two fingers and the buttons, and a short hint says so. `map`: the map is the screen (full height) and\ntakes every gesture.",
295
+ "required": false
296
+ },
285
297
  {
286
298
  "name": "interactive",
287
299
  "type": "boolean",
@@ -659,6 +671,14 @@
659
671
  "module": "@krizaka/ui/registry/examples/map/location-picker",
660
672
  "code": "\"use client\";\n\nimport { type LngLat, LocationPicker, StaticMap } from \"@krizaka/ui/map\";\nimport * as React from \"react\";\n\n// A meeting point picked by moving the map under the pin: its distance from the person, a 1-km zone, \"Near me\" on request.\nexport default function MapLocationPicker() {\n const [point, setPoint] = React.useState<LngLat>([-73.5673, 45.5017]);\n return (\n <div className=\"w-full max-w-xl\">\n <LocationPicker\n label=\"Meeting point\"\n locale=\"en-CA\"\n value={point}\n onValueChange={setPoint}\n origin={[-73.5794, 45.5048]}\n radius={1000}\n fallback={<StaticMap label=\"Meeting point\" center={point} zoom={14} places={[{ position: point, label: \"Meeting point\" }]} />}\n />\n </div>\n );\n}\n"
661
673
  },
674
+ {
675
+ "name": "full-screen",
676
+ "title": "Full-screen map",
677
+ "description": "A map that is the whole screen takes the wheel and one finger with `gestures=\"map\"`; in a page the default leaves them to the page.",
678
+ "path": "examples/map/full-screen.tsx",
679
+ "module": "@krizaka/ui/registry/examples/map/full-screen",
680
+ "code": "\"use client\";\n\nimport { Map, Marker, StaticMap } from \"@krizaka/ui/map\";\n\nconst SPOTS = [\n { id: \"olimpico\", label: \"Café Olimpico, Mile End\", position: [-73.6005, 45.5229] as const },\n { id: \"parc\", label: \"Parc La Fontaine\", position: [-73.5695, 45.5268] as const },\n];\n\n// A map that IS the screen (an explorer, full height): `gestures=\"map\"` gives it the wheel and one finger. In a page, leave the\n// default (`page`): the wheel scrolls the page past the map, and Ctrl/⌘ + wheel or two fingers zoom it.\nexport default function MapFullScreen() {\n return (\n <Map\n label=\"Explore the neighbourhood\"\n gestures=\"map\"\n center={[-73.59, 45.525]}\n zoom={12.5}\n className=\"h-96 w-full max-w-xl\"\n fallback={<StaticMap label=\"Explore the neighbourhood\" center={[-73.59, 45.525]} zoom={12.5} places={SPOTS} />}\n >\n {SPOTS.map((s) => (\n <Marker key={s.id} position={s.position} label={s.label} />\n ))}\n </Map>\n );\n}\n"
681
+ },
662
682
  {
663
683
  "name": "route",
664
684
  "title": "Route",
@@ -1086,7 +1106,7 @@
1086
1106
  },
1087
1107
  {
1088
1108
  "path": "map/index.ts",
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"
1109
+ "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 MapGestures,\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"
1090
1110
  },
1091
1111
  {
1092
1112
  "path": "map/location-picker.tsx",
@@ -1094,11 +1114,11 @@
1094
1114
  },
1095
1115
  {
1096
1116
  "path": "map/map.tsx",
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"
1117
+ "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 * The words of the engine's overlay when the wheel turns over a map in a page (the page scrolls; the map zooms with Ctrl or ⌘,\n * or two fingers): MapLibre's `locale` keys `CooperativeGesturesHandler.WindowsHelpText`, `.MacHelpText` and `.MobileHelpText`.\n * Missing: the engine's English.\n */\n gestureHelp?: Partial<Record<`CooperativeGesturesHandler.${\"Windows\" | \"Mac\" | \"Mobile\"}HelpText`, string>>;\n};\n\nexport const mapLabels: MapLabels = {\n zoomIn: \"Zoom in\",\n zoomOut: \"Zoom out\",\n places: \"Places on the map\",\n};\n\n/** Who owns the gestures: `page` (default) lets the wheel and one finger scroll the page; `map` is for a map that is the screen. */\nexport type MapGestures = \"page\" | \"map\";\n\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 /**\n * Who owns the wheel and the fingers. `page` (default): the wheel and one finger scroll the page past the map; the map zooms\n * with Ctrl/⌘ + wheel, two fingers and the buttons, and a short hint says so. `map`: the map is the screen (full height) and\n * takes every gesture.\n */\n gestures?: MapGestures;\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 gestures = \"page\",\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: gestures === \"page\",\n // The engine's own overlay (styled in motion.css) says it in the words given; its English is the default.\n locale: labels.gestureHelp,\n // The engine's own overlay (styled in motion.css) says it in the words given; its English is the default.\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\n/** Lists a place for screen readers while the component stands. */\nfunction usePlace(id: string, label: string, places: Registry) {\n React.useEffect(() => {\n places.add(id, label);\n return () => places.remove(id);\n }, [id, label, places]);\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 usePlace(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 usePlace(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 usePlace(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 usePlace(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"
1098
1118
  },
1099
1119
  {
1100
1120
  "path": "map/meta.ts",
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"
1121
+ "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 \"In a page the wheel scrolls the page, not the map (`gestures=\\\"page\\\"`, the default): the map zooms with Ctrl/⌘ + wheel, two fingers on a phone and its + / − buttons, and the engine's overlay says so in the map's words (`labels.gestureHelp`: MapLibre's `CooperativeGesturesHandler.*HelpText` keys). A map that IS the screen (an explorer, full height) opts in with `gestures=\\\"map\\\"`.\",\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: \"Ctrl / ⌘ + wheel\", action: \"Zoom the map; a plain wheel scrolls the page (unless `gestures=\\\"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: \"full-screen\", title: \"Full-screen map\", description: \"A map that is the whole screen takes the wheel and one finger with `gestures=\\\"map\\\"`; in a page the default leaves them to the page.\" },\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
1122
  },
1103
1123
  {
1104
1124
  "path": "map/pin/index.ts",
@@ -1138,7 +1158,7 @@
1138
1158
  }
1139
1159
  ],
1140
1160
  "dependencies": [
1141
- "@krizaka/tokens@^3.83.0",
1161
+ "@krizaka/tokens@^3.85.0",
1142
1162
  "@protomaps/basemaps@5.7.2",
1143
1163
  "tailwind-variants@^3.3.1"
1144
1164
  ],
@@ -1353,6 +1373,13 @@
1353
1373
  "description": "Shown in place of the map while its engine loads, and for good without WebGL: a `StaticMap`, a picture.",
1354
1374
  "required": false
1355
1375
  },
1376
+ {
1377
+ "name": "gestures",
1378
+ "type": "MapGestures",
1379
+ "default": "page",
1380
+ "description": "Who owns the wheel and the fingers. `page` (default): the wheel and one finger scroll the page past the map; the map zooms\nwith Ctrl/⌘ + wheel, two fingers and the buttons, and a short hint says so. `map`: the map is the screen (full height) and\ntakes every gesture.",
1381
+ "required": false
1382
+ },
1356
1383
  {
1357
1384
  "name": "interactive",
1358
1385
  "type": "boolean",
@@ -2,8 +2,8 @@
2
2
  "name": "media-gallery",
3
3
  "type": "primitive",
4
4
  "title": "Media gallery",
5
- "summary": "A shop's own photos and loops in tiles — the first featured, loops playing muted while their tile is on screen (a still under reduced motion), a caption on the foot of a tile.",
6
- "description": "A shop's own photos and loops in tiles — the first featured, loops playing muted while their tile is on screen (a still under reduced motion), a caption on the foot of a tile.",
5
+ "summary": "Also `MediaCarousel` (3 to 4 realisations, one at a time) and `MediaPlayer` (the one video frame: inline, lightbox, 9:16). A shop's own photos and loops in tiles — the first featured, loops playing muted while their tile is on screen (a still under reduced motion), a caption on the foot of a tile.",
6
+ "description": "Also `MediaCarousel` (3 to 4 realisations, one at a time) and `MediaPlayer` (the one video frame: inline, lightbox, 9:16). A shop's own photos and loops in tiles — the first featured, loops playing muted while their tile is on screen (a still under reduced motion), a caption on the foot of a tile.",
7
7
  "status": "beta",
8
8
  "deprecated": null,
9
9
  "category": "media",
@@ -39,6 +39,9 @@
39
39
  "keyboard": [],
40
40
  "notes": [
41
41
  "A list named by `label`; each tile is a figure with the photo's `alt` and its caption.",
42
+ "`MediaCarousel` is a `carousel` region named by `label`; each slide is a numbered group, only the one in view is exposed (`inert` on the others); previous / next are buttons in a `toolbar` that also takes ← / → (at an end the focus moves to the other button), a swipe turns one slide, the track has no scroll of its own to reach, the count is polite.",
43
+ "`MediaPlayer` in a lightbox: one button named `playLabel` opens a modal dialog (focus trapped, Escape closes, focus returns) holding the VideoPlayer; the press starts it with sound.",
44
+ "Nothing moves under the pointer and nothing advances by itself; a loop plays only on the slide in view, never under reduced motion (the still shows, the buttons stay).",
42
45
  "A loop is decorative (`aria-hidden`), starts only while its tile is on screen and never under reduced motion."
43
46
  ]
44
47
  },
@@ -47,7 +50,7 @@
47
50
  ],
48
51
  "web": {
49
52
  "entry": "@krizaka/ui/media-gallery",
50
- "import": "import { MediaGallery } from \"@krizaka/ui/media-gallery\";",
53
+ "import": "import { MediaGallery, MediaCarousel, MediaPlayer } from \"@krizaka/ui/media-gallery\";",
51
54
  "props": [
52
55
  {
53
56
  "component": "MediaGallery",
@@ -78,22 +81,66 @@
78
81
  "path": "examples/media-gallery/shop.tsx",
79
82
  "module": "@krizaka/ui/registry/examples/media-gallery/shop",
80
83
  "code": "import { MediaGallery } from \"@krizaka/ui/media-gallery\";\n\n// Drawn pictures (data URIs, no network); a shop passes its own photos.\nconst PIC = (a: string, b: string) => `data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 800 600'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='${a}'/><stop offset='1' stop-color='${b}'/></linearGradient></defs><rect width='800' height='600' fill='url(#g)'/></svg>`)}`;\n\n// A shop's own photos: the first is featured, a loop plays while its tile is on screen.\nexport default function MediaGalleryShop() {\n return (\n <MediaGallery\n label=\"Photos of the shop\"\n items={[\n { id: \"a\", src: PIC(\"#1d4d3a\", \"#c87a3a\"), alt: \"First snow on the street\", caption: \"First snow\", shape: \"wide\" },\n { id: \"b\", src: PIC(\"#33523f\", \"#8a5a2b\"), alt: \"Pouring tea\", shape: \"wide\" },\n { id: \"c\", src: PIC(\"#27483a\", \"#d99a56\"), alt: \"A camp at blue hour\", shape: \"wide\" },\n ]}\n />\n );\n}\n"
84
+ },
85
+ {
86
+ "name": "carousel",
87
+ "title": "Carousel",
88
+ "description": "Three realisations one at a time, the first opens its film; buttons (and ← / → on them), swipe, nothing advances by itself.",
89
+ "path": "examples/media-gallery/carousel.tsx",
90
+ "module": "@krizaka/ui/registry/examples/media-gallery/carousel",
91
+ "code": "import { MediaCarousel } from \"@krizaka/ui/media-carousel\";\n\n// Drawn pictures (data URIs, no network); a page passes its own realisations.\nconst PIC = (a: string, b: string) => `data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 800 500'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='${a}'/><stop offset='1' stop-color='${b}'/></linearGradient></defs><rect width='800' height='500' fill='url(#g)'/></svg>`)}`;\n\n// Three realisations, one at a time; the first opens its film in a lightbox. Nothing advances by itself.\nexport default function MediaCarouselExample() {\n return (\n <div className=\"max-w-xl\">\n <MediaCarousel\n label=\"Realisations\"\n slides={[\n { id: \"a\", src: PIC(\"#1d3f6b\", \"#4d7fb8\"), alt: \"The brand film\", caption: \"Fig. 1a\", film: { src: \"https://krizaka-assets.b-cdn.net/org/v1/films/film/le-monde-de-krizaka-16x9.b1c7c4ee51.mp4\", title: \"Film: the world of Krizaka\", playLabel: \"Play the film\" } },\n { id: \"b\", src: PIC(\"#23496f\", \"#6b9bc9\"), alt: \"A lease read in a minute\", caption: \"Fig. 1b\" },\n { id: \"c\", src: PIC(\"#2a3f5c\", \"#7aa5d6\"), alt: \"A return prepared, never filed\", caption: \"Fig. 1c\" },\n ]}\n />\n </div>\n );\n}\n"
92
+ },
93
+ {
94
+ "name": "player",
95
+ "title": "Player",
96
+ "description": "The one video frame: a poster that opens a lightbox started by the press (with sound), 16:9 and vertical 9:16.",
97
+ "path": "examples/media-gallery/player.tsx",
98
+ "module": "@krizaka/ui/registry/examples/media-gallery/player",
99
+ "code": "import { MediaPlayer } from \"@krizaka/ui/media-player\";\n\nconst POSTER = `data:image/svg+xml,${encodeURIComponent(\"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 800 450'><rect width='800' height='450' fill='#1d3f6b'/></svg>\")}`;\n\n// One player, three ways: a lightbox (a press opens it, with sound), inline, and vertical 9:16 in a lightbox.\nexport default function MediaPlayerExample() {\n return (\n <div className=\"grid max-w-2xl grid-cols-[2fr_1fr] items-start gap-3\">\n <MediaPlayer mode=\"lightbox\" src=\"https://krizaka-assets.b-cdn.net/org/v1/films/film/le-monde-de-krizaka-16x9.b1c7c4ee51.mp4\" poster={POSTER} title=\"Film: the world of Krizaka\" playLabel=\"Play the film\" caption=\"Fig. 1\" />\n <MediaPlayer mode=\"lightbox\" vertical src=\"https://krizaka-assets.b-cdn.net/org/v1/films/film/le-monde-de-krizaka-9x16.aa28980db3.mp4\" poster={POSTER} title=\"Film: the world of Krizaka, vertical\" playLabel=\"Play the vertical film\" />\n </div>\n );\n}\n"
81
100
  }
82
101
  ]
83
102
  },
84
103
  "native": null,
85
104
  "files": [
105
+ {
106
+ "path": "glyphs.tsx",
107
+ "content": "// The small line glyphs the data and media primitives draw (play, volume, search, chevrons…): decorative, 24-unit\n// box, `currentColor`, sized by the caller's class. Shared by the entries that need them; never exported on its own —\n// a product draws its own icons with @krizaka/icons.\nimport type * as React from \"react\";\n\ntype GlyphProps = { className?: string };\n\nfunction Glyph({ className = \"h-4 w-4\", fill, children }: GlyphProps & { fill?: boolean; children: React.ReactNode }) {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n className={className}\n fill={fill ? \"currentColor\" : \"none\"}\n stroke={fill ? \"none\" : \"currentColor\"}\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden\n focusable=\"false\"\n >\n {children}\n </svg>\n );\n}\n\nexport const PlayGlyph = (p: GlyphProps) => (\n <Glyph {...p} fill>\n <path d=\"M8 5.5v13a1 1 0 0 0 1.5.86l10.4-6.5a1 1 0 0 0 0-1.72L9.5 4.64A1 1 0 0 0 8 5.5Z\" />\n </Glyph>\n);\nexport const PauseGlyph = (p: GlyphProps) => (\n <Glyph {...p} fill>\n <rect x=\"6\" y=\"5\" width=\"4\" height=\"14\" rx=\"1\" />\n <rect x=\"14\" y=\"5\" width=\"4\" height=\"14\" rx=\"1\" />\n </Glyph>\n);\nexport const VolumeGlyph = ({ muted, ...p }: GlyphProps & { muted?: boolean }) => (\n <Glyph {...p}>\n <path d=\"M11 5 6 9H3v6h3l5 4V5Z\" />\n {muted ? <path d=\"m22 9-6 6m0-6 6 6\" /> : <path d=\"M15.5 8.5a5 5 0 0 1 0 7M18.5 5.5a9 9 0 0 1 0 13\" />}\n </Glyph>\n);\nexport const FullscreenGlyph = ({ exit, ...p }: GlyphProps & { exit?: boolean }) => (\n <Glyph {...p}>\n {exit ? <path d=\"M9 4v5H4m11-5v5h5M9 20v-5H4m11 5v-5h5\" /> : <path d=\"M4 9V4h5m6 0h5v5M4 15v5h5m11-5v5h-5\" />}\n </Glyph>\n);\nexport const CaptionsGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\" />\n <path d=\"M10 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3\" />\n </Glyph>\n);\nexport const PipGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <rect x=\"3\" y=\"5\" width=\"18\" height=\"14\" rx=\"2\" />\n <rect x=\"12\" y=\"12\" width=\"6\" height=\"4\" rx=\"1\" />\n </Glyph>\n);\nexport const SearchGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <circle cx=\"11\" cy=\"11\" r=\"7\" />\n <path d=\"m20 20-3.5-3.5\" />\n </Glyph>\n);\nexport const CloseGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M18 6 6 18M6 6l12 12\" />\n </Glyph>\n);\nexport const ChevronGlyph = ({ direction = \"down\", ...p }: GlyphProps & { direction?: \"left\" | \"right\" | \"up\" | \"down\" }) => (\n <Glyph {...p}>\n <path d={{ left: \"m15 6-6 6 6 6\", right: \"m9 6 6 6-6 6\", up: \"m6 15 6-6 6 6\", down: \"m6 9 6 6 6-6\" }[direction]} />\n </Glyph>\n);\nexport const CheckGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M20 6 9 17l-5-5\" />\n </Glyph>\n);\nexport const PlusGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M12 5v14M5 12h14\" />\n </Glyph>\n);\nexport const CalendarGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <rect x=\"3\" y=\"5\" width=\"18\" height=\"16\" rx=\"2\" />\n <path d=\"M3 10h18M8 3v4M16 3v4\" />\n </Glyph>\n);\nexport const UploadGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M12 16V4m0 0L7 9m5-5 5 5\" />\n <path d=\"M4 16v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2\" />\n </Glyph>\n);\nexport const FileGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z\" />\n <path d=\"M14 3v5h5\" />\n </Glyph>\n);\nexport const CameraGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M4 8h3l2-3h6l2 3h3a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1Z\" />\n <circle cx=\"12\" cy=\"13.5\" r=\"3.5\" />\n </Glyph>\n);\nexport const FlipGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M4 12a8 8 0 0 1 14-5.3M20 12a8 8 0 0 1-14 5.3\" />\n <path d=\"M18 3v4h-4M6 21v-4h4\" />\n </Glyph>\n);\nexport const RetryGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M4 12a8 8 0 1 0 2.3-5.7L4 8.5\" />\n <path d=\"M4 4v4.5h4.5\" />\n </Glyph>\n);\nexport const SortGlyph = ({ direction, ...p }: GlyphProps & { direction?: \"ascending\" | \"descending\" }) => (\n <Glyph {...p}>\n {direction === \"ascending\" ? <path d=\"m7 14 5-5 5 5\" /> : direction === \"descending\" ? <path d=\"m7 10 5 5 5-5\" /> : <path d=\"m8 9 4-4 4 4M8 15l4 4 4-4\" />}\n </Glyph>\n);\nexport const ArrowGlyph = ({ direction = \"right\", ...p }: GlyphProps & { direction?: \"left\" | \"right\" }) => (\n <Glyph {...p}>\n <path d={direction === \"left\" ? \"M19 12H5m0 0 6-6m-6 6 6 6\" : \"M5 12h14m0 0-6-6m6 6-6 6\"} />\n </Glyph>\n);\nexport const ExternalGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M14 4h6v6M20 4l-9 9\" />\n <path d=\"M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4\" />\n </Glyph>\n);\nexport const WarningGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M12 4 2.5 20h19L12 4Z\" />\n <path d=\"M12 10v4M12 17.2v.1\" />\n </Glyph>\n);\nexport const CopyGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <rect x=\"9\" y=\"9\" width=\"11\" height=\"11\" rx=\"2\" />\n <path d=\"M15 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h3\" />\n </Glyph>\n);\nexport const PencilGlyph = (p: GlyphProps) => (\n <Glyph {...p}>\n <path d=\"M4 20h4L19 9a2.8 2.8 0 0 0-4-4L4 16v4zM13.5 6.5l4 4\" />\n </Glyph>\n);\n"
108
+ },
109
+ {
110
+ "path": "media-gallery/carousel-index.ts",
111
+ "content": "/** @krizaka/ui/media-carousel — `MediaCarousel` (`slides`, `label`): 3–4 realisations one at a time, a slide may open its film. Client. */\nexport { type CarouselSlide, MediaCarousel, mediaCarousel, type MediaCarouselLabels, mediaCarouselLabels, type MediaCarouselProps } from \"./media-carousel\";\n"
112
+ },
86
113
  {
87
114
  "path": "media-gallery/index.ts",
88
- "content": "/** @krizaka/ui/media-gallery — `MediaGallery` (`items`, `label`), `mediaGallery`: a shop's photos and loops in tiles, the first featured. Client. */\nexport { type GalleryMedia, MediaGallery, mediaGallery, type MediaGalleryProps } from \"./media-gallery\";\n"
115
+ "content": "/** @krizaka/ui/media-gallery — `MediaGallery` (`items`, `label`), `mediaGallery`: a shop's photos and loops in tiles, the first featured. Client. `MediaCarousel` is `@krizaka/ui/media-carousel` and `MediaPlayer` is `@krizaka/ui/media-player`: their own entries, so the tiles stay light. */\nexport { type GalleryMedia, MediaGallery, mediaGallery, type MediaGalleryProps } from \"./media-gallery\";\n"
116
+ },
117
+ {
118
+ "path": "media-gallery/media-carousel.tsx",
119
+ "content": "// Client (the slide in view, the reader's motion preference). A few realisations in one frame: a scroll-snap track moved by\n// a swipe, previous / next buttons in a toolbar that also takes the arrow keys, a « n / N » count. Nothing advances by itself and nothing moves under the pointer; a loop plays only on the\n// slide in view (a still under reduced motion); a slide with a film opens it in the MediaPlayer lightbox.\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { IconButton } from \"../button/button\";\nimport { ChevronGlyph } from \"../glyphs\";\nimport { usePrefersReducedMotion } from \"../media\";\nimport { MediaPlayer, type MediaPlayerProps } from \"./media-player\";\n\nexport const mediaCarousel = tv({\n slots: {\n root: \"relative isolate w-full\",\n track: \"m-0 flex list-none snap-x snap-mandatory gap-3 overflow-hidden p-0 touch-pan-y\",\n slide: \"relative m-0 w-full shrink-0 snap-center overflow-hidden rounded-xl border border-border-default bg-media\",\n media: \"absolute inset-0 h-full w-full object-cover\",\n caption: \"absolute inset-x-0 bottom-0 bg-linear-to-t from-scrim-strong to-transparent p-3 pt-8 text-xs font-semibold text-fg-on-media\",\n bar: \"mt-3 flex items-center justify-between gap-3\",\n count: \"text-xs tabular-nums text-fg-secondary\",\n buttons: \"flex gap-2\",\n },\n});\nconst s = mediaCarousel();\n\nexport type CarouselSlide = {\n /** A stable id. */\n id: string;\n /** The still, or the poster of a loop or a film. */\n src: string;\n /** What it shows, in words. */\n alt: string;\n /** « Fig. 1a »: one line over the foot of the slide. */\n caption?: string;\n /** A muted loop playing while the slide is the one in view. */\n video?: { webm?: string; mp4?: string };\n /** A film opened by a press, with sound, in the lightbox of the MediaPlayer. */\n film?: Pick<MediaPlayerProps, \"src\" | \"title\" | \"tracks\" | \"loadHls\"> & { playLabel: string; vertical?: boolean };\n};\n\nexport type MediaCarouselLabels = { previous: string; next: string; close: string; slide: string };\nexport const mediaCarouselLabels: MediaCarouselLabels = { previous: \"Previous\", next: \"Next\", close: \"Close\", slide: \"{n} of {total}\" };\n\nexport type MediaCarouselProps = Omit<React.ComponentProps<\"section\">, \"children\"> & {\n /** The slides, in order: 3 to 4 realisations. */\n slides: readonly CarouselSlide[];\n /** The carousel's accessible name, passed translated. */\n label: string;\n /** The frame ratio of every slide (width / height). Default `16 / 10`. */\n ratio?: string;\n /** The words, passed translated; English by default. `slide` takes `{n}` and `{total}`. */\n labels?: Partial<MediaCarouselLabels>;\n};\n\n/** How far a swipe travels, in CSS pixels, before it turns the slide. */\nconst SWIPE_DISTANCE = 40;\n\n/** The slide in view and the one way to change it: the track scrolls only from here, so it holds no scroll of its own to reach. */\nfunction useActiveSlide(track: React.RefObject<HTMLUListElement | null>, count: number) {\n const [active, setActive] = React.useState(0);\n const reduce = usePrefersReducedMotion();\n const go = (to: number) => {\n const el = track.current;\n if (!el) return active;\n const next = Math.min(count - 1, Math.max(0, to));\n el.scrollTo({ left: next * (el.scrollWidth / count), behavior: reduce ? \"auto\" : \"smooth\" });\n setActive(next);\n return next;\n };\n return { active, go, reduce };\n}\n\n/** A horizontal swipe on the track turns one slide; a vertical one stays the page's scroll (`touch-action: pan-y`). */\nfunction useSwipe(turn: (delta: 1 | -1) => void) {\n const from = React.useRef<number | null>(null);\n return {\n onPointerDown: (event: React.PointerEvent) => {\n from.current = event.clientX;\n },\n onPointerUp: (event: React.PointerEvent) => {\n const start = from.current;\n from.current = null;\n if (start === null) return;\n const distance = event.clientX - start;\n if (Math.abs(distance) >= SWIPE_DISTANCE) turn(distance < 0 ? 1 : -1);\n },\n onPointerCancel: () => {\n from.current = null;\n },\n };\n}\n\n/** At an end the button just used is disabled: the focus moves to the other one, never to the page. */\nfunction keepFocus(toolbar: HTMLElement | null, at: number, count: number) {\n if (!toolbar?.contains(document.activeElement) || count < 2) return;\n const [previous, next] = toolbar.querySelectorAll(\"button\");\n if (at === 0) next?.focus();\n if (at === count - 1) previous?.focus();\n}\n\n/** The arrow keys of the toolbar: right turns forward, left back. */\nconst ARROWS: Partial<Record<string, 1 | -1>> = { ArrowRight: 1, ArrowLeft: -1 };\n\nfunction SlideMedia({ slide, playing, ratio, closeLabel }: Readonly<{ slide: CarouselSlide; playing: boolean; ratio: string; closeLabel: string }>) {\n if (slide.film) {\n const { playLabel, vertical, ...film } = slide.film;\n return <MediaPlayer {...film} mode=\"lightbox\" poster={slide.src} posterAlt={slide.alt} playLabel={playLabel} vertical={vertical} caption={slide.caption} closeLabel={closeLabel} className=\"h-full rounded-none border-0\" />;\n }\n return (\n <>\n <img src={slide.src} alt={slide.alt} loading=\"lazy\" decoding=\"async\" draggable={false} className={s.media()} style={{ aspectRatio: ratio }} />\n {playing && slide.video && (\n <video className={s.media()} poster={slide.src} autoPlay muted loop playsInline aria-hidden tabIndex={-1}>\n {slide.video.webm && <source src={slide.video.webm} type=\"video/webm\" />}\n {slide.video.mp4 && <source src={slide.video.mp4} type=\"video/mp4\" />}\n </video>\n )}\n {slide.caption && <figcaption className={s.caption()}>{slide.caption}</figcaption>}\n </>\n );\n}\n\n/** A few realisations in one frame, one at a time: swipe, buttons or arrow keys on them; nothing advances by itself. */\nexport function MediaCarousel({ slides, label, ratio = \"16 / 10\", labels: given, className, ...props }: Readonly<MediaCarouselProps>) {\n const labels = { ...mediaCarouselLabels, ...given };\n const track = React.useRef<HTMLUListElement>(null);\n const toolbar = React.useRef<HTMLDivElement>(null);\n const { active, go, reduce } = useActiveSlide(track, slides.length);\n const turn = (delta: 1 | -1) => keepFocus(toolbar.current, go(active + delta), slides.length);\n const swipe = useSwipe(turn);\n const keys = (event: React.KeyboardEvent<HTMLDivElement>) => {\n const delta = ARROWS[event.key];\n if (!delta) return;\n event.preventDefault();\n turn(delta);\n };\n const name = (i: number) => labels.slide.replace(\"{n}\", String(i + 1)).replace(\"{total}\", String(slides.length));\n return (\n <section aria-roledescription=\"carousel\" aria-label={label} className={s.root({ className })} {...props}>\n <ul ref={track} className={s.track()} {...swipe}>\n {slides.map((slide, i) => (\n <li key={slide.id} aria-roledescription=\"slide\" aria-label={name(i)} className={s.slide()} style={{ aspectRatio: ratio }} aria-hidden={i === active ? undefined : true} inert={i === active ? undefined : true}>\n <figure className=\"m-0 h-full w-full\">\n <SlideMedia slide={slide} playing={i === active && !reduce} ratio={ratio} closeLabel={labels.close} />\n </figure>\n </li>\n ))}\n </ul>\n <div className={s.bar()}>\n <span className={s.count()} aria-live=\"polite\">{active + 1} / {slides.length}</span>\n <div ref={toolbar} role=\"toolbar\" aria-orientation=\"horizontal\" className={s.buttons()} onKeyDown={keys}>\n <IconButton variant=\"secondary\" label={labels.previous} disabled={active === 0} onClick={() => turn(-1)}>\n <ChevronGlyph direction=\"left\" className=\"h-5 w-5\" />\n </IconButton>\n <IconButton variant=\"secondary\" label={labels.next} disabled={active === slides.length - 1} onClick={() => turn(1)}>\n <ChevronGlyph direction=\"right\" className=\"h-5 w-5\" />\n </IconButton>\n </div>\n </div>\n </section>\n );\n}\n"
89
120
  },
90
121
  {
91
122
  "path": "media-gallery/media-gallery.tsx",
92
123
  "content": "// Client (the reader's motion preference). A shop's photos and loops in tiles: the first is the featured one, loops play\n// muted while their tile is on screen (a still under reduced motion), a caption rides the foot of a tile.\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nexport const mediaGallery = tv({\n slots: {\n root: \"m-0 grid list-none grid-cols-2 gap-2 p-0 sm:gap-3 md:grid-cols-4\",\n tile:\n \"group relative isolate m-0 aspect-[3/4] overflow-hidden rounded-xl border border-border-default bg-media data-[shape=wide]:aspect-[4/3] \" +\n // The featured tile takes two columns; from md up it has no ratio of its own and stretches to the height of the row its neighbours set.\n \"data-[featured]:col-span-2 data-[featured]:aspect-[4/3] md:data-[featured]:aspect-auto\",\n media: \"absolute inset-0 h-full w-full object-cover\",\n caption: \"pointer-events-none absolute inset-x-0 bottom-0 bg-linear-to-t from-scrim-strong to-transparent p-3 pt-8 text-xs font-semibold text-fg-on-media\",\n },\n});\nconst s = mediaGallery();\n\nexport type GalleryMedia = {\n /** A stable id. */\n id: string;\n /** The still: a photo, or the poster of a loop. */\n src: string;\n /** What it shows, in words. */\n alt: string;\n /** A muted loop: WebM first, MP4 for Safari. */\n video?: { webm?: string; mp4?: string };\n /** One line over the foot of the tile. */\n caption?: string;\n /** `wide` for a landscape source (4:3 tile); the default tile is a 3:4 portrait. */\n shape?: \"portrait\" | \"wide\";\n};\n\nexport type MediaGalleryProps = Omit<React.ComponentProps<\"ul\">, \"children\"> & {\n /** The photos and loops, the featured one first. */\n items: readonly GalleryMedia[];\n /** The gallery's accessible name, passed translated. */\n label: string;\n};\n\nfunction Tile({ item, featured }: { item: GalleryMedia; featured: boolean }) {\n const ref = React.useRef<HTMLLIElement>(null);\n const [play, setPlay] = React.useState(false);\n React.useEffect(() => {\n const node = ref.current;\n if (!item.video || !node || window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return;\n const io = new IntersectionObserver(([entry]) => setPlay(Boolean(entry?.isIntersecting)), { rootMargin: \"120px\" });\n io.observe(node);\n return () => io.disconnect();\n }, [item.video]);\n return (\n <li ref={ref} className={s.tile()} data-featured={featured ? \"\" : undefined} data-shape={item.shape ?? \"portrait\"}>\n <figure className=\"m-0 h-full w-full\">\n <img src={item.src} alt={item.alt} loading=\"lazy\" decoding=\"async\" className={s.media()} />\n {play && item.video && (\n <video className={s.media()} poster={item.src} autoPlay muted loop playsInline preload=\"none\" aria-hidden tabIndex={-1}>\n {item.video.webm && <source src={item.video.webm} type=\"video/webm\" />}\n {item.video.mp4 && <source src={item.video.mp4} type=\"video/mp4\" />}\n </video>\n )}\n {item.caption && <figcaption className={s.caption()}>{item.caption}</figcaption>}\n </figure>\n </li>\n );\n}\n\n/** Photos and loops in tiles, the first featured; loops play while seen. */\nexport function MediaGallery({ items, label, className, ...props }: MediaGalleryProps) {\n return (\n <ul aria-label={label} className={s.root({ className })} {...props}>\n {items.map((item, i) => (\n <Tile key={item.id} item={item} featured={i === 0 && items.length > 2} />\n ))}\n </ul>\n );\n}\n"
93
124
  },
125
+ {
126
+ "path": "media-gallery/media-player.tsx",
127
+ "content": "// Client (a dialog, the video player). ONE designed media player: the same frame inline, in a lightbox, or vertical (9:16).\n// Inline it is the VideoPlayer of `@krizaka/ui/video-player`; as a lightbox a poster with a play button opens the player in a\n// dialog, started by that press, with sound. Nothing moves under the pointer: the poster's hover is a colour.\nimport * as React from \"react\";\nimport { tv } from \"tailwind-variants\";\n\nimport { PlayGlyph } from \"../glyphs\";\nimport { VideoPlayer, type VideoPlayerProps } from \"../video-player\";\n\n// The dialog and the player of the lightbox load when the poster is pressed, not with the page.\nconst PlayerLightbox = React.lazy(() => import(\"./player-lightbox\"));\n\nexport const mediaPlayer = tv({\n slots: {\n poster:\n \"group relative isolate block w-full overflow-hidden rounded-xl border border-border-default bg-media p-0 text-fg-on-media \" +\n \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring\",\n image: \"absolute inset-0 h-full w-full object-cover\",\n play:\n \"absolute left-1/2 top-1/2 flex h-14 w-14 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full \" +\n \"bg-scrim-strong text-fg-on-media transition-colors group-hover:bg-scrim\",\n caption: \"pointer-events-none absolute inset-x-0 bottom-0 bg-linear-to-t from-scrim-strong to-transparent p-3 pt-8 text-left text-xs font-semibold\",\n },\n});\nconst s = mediaPlayer();\n\nexport type MediaPlayerProps = Pick<\n VideoPlayerProps,\n \"src\" | \"poster\" | \"title\" | \"tracks\" | \"loadHls\" | \"labels\" | \"onPlay\" | \"onPause\" | \"onEnded\" | \"onError\"\n> & {\n /** `inline`: the player itself. `lightbox`: a poster that opens it in a dialog. Default `inline`. */\n mode?: \"inline\" | \"lightbox\";\n /** `9 / 16` frame for a vertical film; default `16 / 9`. */\n vertical?: boolean;\n /** The poster's words in the lightbox (\"Play the film\"), passed translated. Required for `lightbox`. */\n playLabel?: string;\n /** The close button's words, passed translated. Default `Close`. */\n closeLabel?: string;\n /** What the poster shows, in words (the `alt` of its image); default is empty (decorative: `playLabel` names the button). */\n posterAlt?: string;\n /** A line over the foot of the poster (« Fig. 1a »). */\n caption?: string;\n /** Called when the lightbox opens or closes. */\n onOpenChange?: (open: boolean) => void;\n /** Classes merged on the player or the poster. */\n className?: string;\n};\n\n/** A video in one frame: inline, in a lightbox (a press opens it with sound), 16:9 or vertical. */\nexport function MediaPlayer({\n mode = \"inline\",\n vertical = false,\n playLabel,\n closeLabel = \"Close\",\n posterAlt = \"\",\n caption,\n onOpenChange,\n className,\n ...player\n}: MediaPlayerProps) {\n const ratio = vertical ? \"9 / 16\" : \"16 / 9\";\n const [open, setOpen] = React.useState(false);\n const poster = React.useRef<HTMLButtonElement>(null);\n const toggle = React.useCallback(\n (next: boolean) => {\n setOpen(next);\n onOpenChange?.(next);\n if (!next) poster.current?.focus();\n },\n [onOpenChange],\n );\n if (mode === \"inline\") return <VideoPlayer {...player} aspectRatio={ratio} className={className} />;\n return (\n <>\n <button ref={poster} type=\"button\" className={s.poster({ className })} style={{ aspectRatio: ratio }} aria-label={caption ? `${caption}. ${playLabel ?? player.title}` : (playLabel ?? player.title)} onClick={() => toggle(true)}>\n {player.poster && <img src={player.poster} alt={posterAlt} loading=\"lazy\" decoding=\"async\" className={s.image()} />}\n <span className={s.play()} aria-hidden>\n <PlayGlyph className=\"ml-1 h-6 w-6\" />\n </span>\n {caption && <span className={s.caption()}>{caption}</span>}\n </button>\n {open && (\n <React.Suspense fallback={null}>\n <PlayerLightbox player={player} ratio={ratio} vertical={vertical} closeLabel={closeLabel} onClose={() => toggle(false)} />\n </React.Suspense>\n )}\n </>\n );\n}\n"
128
+ },
94
129
  {
95
130
  "path": "media-gallery/meta.ts",
96
- "content": "import type { ComponentMeta } from \"../meta\";\n\nexport const meta = {\n title: \"Media gallery\",\n summary: \"A shop's own photos and loops in tiles — the first featured, loops playing muted while their tile is on screen (a still under reduced motion), a caption on the foot of a tile.\",\n status: \"beta\",\n category: \"media\",\n domain: \"media\",\n platforms: \"web\",\n parity: { native: { status: \"n/a\", reason: \"A shop's public storefront is a web page.\" }, desktop: \"web\" },\n whenToUse: [\"The « look inside » of a business page: its real photos and short clips.\"],\n whenNotToUse: [\n { when: \"A demo gallery with titles and captions per piece.\" },\n ],\n bestPractices: [\n \"Real photos only; every tile has `alt` text that says what it shows.\",\n \"Give a landscape source `shape=\\\"wide\\\"` so it is not cropped to a portrait.\",\n \"Keep loops short and few: one or two per gallery.\",\n ],\n accessibility: {\n keyboard: [],\n notes: [\n \"A list named by `label`; each tile is a figure with the photo's `alt` and its caption.\",\n \"A loop is decorative (`aria-hidden`), starts only while its tile is on screen and never under reduced motion.\",\n ],\n },\n related: [\"cover-hero\"],\n web: {\n imports: [\"MediaGallery\"],\n examples: [{ name: \"shop\", title: \"Shop\", description: \"Three photos, the first featured, one with a caption.\" }],\n },\n} satisfies ComponentMeta;\n"
131
+ "content": "import type { ComponentMeta } from \"../meta\";\n\nexport const meta = {\n title: \"Media gallery\",\n summary: \"Also `MediaCarousel` (3 to 4 realisations, one at a time) and `MediaPlayer` (the one video frame: inline, lightbox, 9:16). A shop's own photos and loops in tiles — the first featured, loops playing muted while their tile is on screen (a still under reduced motion), a caption on the foot of a tile.\",\n status: \"beta\",\n category: \"media\",\n domain: \"media\",\n platforms: \"web\",\n parity: { native: { status: \"n/a\", reason: \"A shop's public storefront is a web page.\" }, desktop: \"web\" },\n whenToUse: [\"The « look inside » of a business page: its real photos and short clips.\"],\n whenNotToUse: [\n { when: \"A demo gallery with titles and captions per piece.\" },\n ],\n bestPractices: [\n \"Real photos only; every tile has `alt` text that says what it shows.\",\n \"Give a landscape source `shape=\\\"wide\\\"` so it is not cropped to a portrait.\",\n \"Keep loops short and few: one or two per gallery.\",\n ],\n accessibility: {\n keyboard: [],\n notes: [\n \"A list named by `label`; each tile is a figure with the photo's `alt` and its caption.\",\n \"`MediaCarousel` is a `carousel` region named by `label`; each slide is a numbered group, only the one in view is exposed (`inert` on the others); previous / next are buttons in a `toolbar` that also takes ← / → (at an end the focus moves to the other button), a swipe turns one slide, the track has no scroll of its own to reach, the count is polite.\",\n \"`MediaPlayer` in a lightbox: one button named `playLabel` opens a modal dialog (focus trapped, Escape closes, focus returns) holding the VideoPlayer; the press starts it with sound.\",\n \"Nothing moves under the pointer and nothing advances by itself; a loop plays only on the slide in view, never under reduced motion (the still shows, the buttons stay).\",\n \"A loop is decorative (`aria-hidden`), starts only while its tile is on screen and never under reduced motion.\",\n ],\n },\n related: [\"cover-hero\"],\n web: {\n imports: [\"MediaGallery\", \"MediaCarousel\", \"MediaPlayer\"],\n examples: [\n { name: \"shop\", title: \"Shop\", description: \"Three photos, the first featured, one with a caption.\" },\n { name: \"carousel\", title: \"Carousel\", description: \"Three realisations one at a time, the first opens its film; buttons (and ← / → on them), swipe, nothing advances by itself.\" },\n { name: \"player\", title: \"Player\", description: \"The one video frame: a poster that opens a lightbox started by the press (with sound), 16:9 and vertical 9:16.\" },\n ],\n },\n} satisfies ComponentMeta;\n"
132
+ },
133
+ {
134
+ "path": "media-gallery/player-index.ts",
135
+ "content": "/** @krizaka/ui/media-player — `MediaPlayer` (`src`, `mode`, `playLabel`): the one video frame, inline, in a lightbox (the dialog loads when it opens) or 9:16. Client. */\nexport { MediaPlayer, mediaPlayer, type MediaPlayerProps } from \"./media-player\";\n"
136
+ },
137
+ {
138
+ "path": "media-gallery/player-lightbox.tsx",
139
+ "content": "// Client. The lightbox's dialog and its player: loaded by `MediaPlayer` only when the poster is pressed.\nimport * as React from \"react\";\n\nimport { Dialog } from \"../dialog\";\nimport { VideoPlayer, type VideoPlayerProps } from \"../video-player\";\n\nexport type PlayerLightboxProps = {\n player: Omit<VideoPlayerProps, \"aspectRatio\" | \"className\">;\n ratio: string;\n vertical: boolean;\n closeLabel: string;\n onClose: () => void;\n};\n\n/** The open dialog holding the player, started by the press that opened it. */\nexport default function PlayerLightbox({ player, ratio, vertical, closeLabel, onClose }: Readonly<PlayerLightboxProps>) {\n return (\n <Dialog.Root open onOpenChange={(open) => !open && onClose()}>\n <Dialog.Content size={vertical ? \"sm\" : \"lg\"} closeLabel={closeLabel} className=\"bg-media p-0\">\n <Dialog.Title className=\"sr-only\">{player.title}</Dialog.Title>\n <VideoPlayer {...player} aspectRatio={ratio} playOnMount pauseWhenHidden={false} />\n </Dialog.Content>\n </Dialog.Root>\n );\n}\n"
140
+ },
141
+ {
142
+ "path": "media.ts",
143
+ "content": "// Shared by the data and media primitives (client): the clock format, the reduced-motion preference, the\n// in-view observer, a debounced callback. Never an entry of its own.\nimport * as React from \"react\";\n\n/** Seconds as a clock: `75` → `1:15`, `3725` → `1:02:05`. Negative or unknown values read `0:00`. */\nexport function formatClock(seconds: number): string {\n const s = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;\n const h = Math.floor(s / 3600);\n const m = Math.floor((s % 3600) / 60);\n const rest = String(s % 60).padStart(2, \"0\");\n return h > 0 ? `${h}:${String(m).padStart(2, \"0\")}:${rest}` : `${m}:${rest}`;\n}\n\n/** Clamps `value` between `min` and `max`. */\nexport const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));\n\nconst REDUCE = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduce = (notify: () => void) => {\n if (typeof window === \"undefined\" || !window.matchMedia) return () => undefined;\n const query = window.matchMedia(REDUCE);\n query.addEventListener?.(\"change\", notify);\n return () => query.removeEventListener?.(\"change\", notify);\n};\n\n/** `true` when the person asked for less motion (`prefers-reduced-motion: reduce`); follows a change of the setting. */\nexport function usePrefersReducedMotion(): boolean {\n return React.useSyncExternalStore(\n subscribeReduce,\n () => (typeof window !== \"undefined\" && window.matchMedia ? window.matchMedia(REDUCE).matches : false),\n () => false,\n );\n}\n\n/** The latest value of a callback, for an effect or an event that must not re-subscribe when it changes. */\nexport function useLatest<T>(value: T) {\n const ref = React.useRef(value);\n React.useLayoutEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n\n/** Calls `onChange(visible)` when at least `threshold` of the element enters or leaves the viewport. */\nexport function useInView(ref: React.RefObject<Element | null>, onChange: (visible: boolean) => void, enabled = true, threshold = 0.25) {\n const latest = useLatest(onChange);\n React.useEffect(() => {\n const element = ref.current;\n if (!enabled || !element || typeof IntersectionObserver === \"undefined\") return;\n const observer = new IntersectionObserver(([entry]) => entry && latest.current(entry.isIntersecting), { threshold });\n observer.observe(element);\n return () => observer.disconnect();\n }, [ref, enabled, threshold, latest]);\n}\n\n/** A value controlled by a prop when it is given, held inside otherwise; `set` calls `onChange` either way. */\nexport function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (next: T) => void) {\n const [inner, setInner] = React.useState(defaultValue);\n const controlled = value !== undefined;\n const current = controlled ? value : inner;\n const set = React.useCallback(\n (next: T) => {\n if (!controlled) setInner(next);\n onChange?.(next);\n },\n [controlled, onChange],\n );\n return [current, set] as const;\n}\n\n/** Starts a media element without an unhandled rejection (autoplay refused, the source replaced meanwhile). */\nexport function playSafely(media: HTMLMediaElement | null | undefined) {\n try {\n const started = media?.play() as Promise<void> | undefined;\n started?.catch?.(() => undefined);\n } catch {\n // Not playable here (no media support): the controls stay as they are.\n }\n}\n"
97
144
  },
98
145
  {
99
146
  "path": "meta.ts",
@@ -103,7 +150,11 @@
103
150
  "dependencies": [
104
151
  "tailwind-variants@^3.3.1"
105
152
  ],
106
- "registryDependencies": [],
153
+ "registryDependencies": [
154
+ "button",
155
+ "dialog",
156
+ "video-player"
157
+ ],
107
158
  "demo": {
108
159
  "path": "examples/media-gallery/shop.tsx",
109
160
  "content": "import { MediaGallery } from \"@krizaka/ui/media-gallery\";\n\n// Drawn pictures (data URIs, no network); a shop passes its own photos.\nconst PIC = (a: string, b: string) => `data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 800 600'><defs><linearGradient id='g' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='${a}'/><stop offset='1' stop-color='${b}'/></linearGradient></defs><rect width='800' height='600' fill='url(#g)'/></svg>`)}`;\n\n// A shop's own photos: the first is featured, a loop plays while its tile is on screen.\nexport default function MediaGalleryShop() {\n return (\n <MediaGallery\n label=\"Photos of the shop\"\n items={[\n { id: \"a\", src: PIC(\"#1d4d3a\", \"#c87a3a\"), alt: \"First snow on the street\", caption: \"First snow\", shape: \"wide\" },\n { id: \"b\", src: PIC(\"#33523f\", \"#8a5a2b\"), alt: \"Pouring tea\", shape: \"wide\" },\n { id: \"c\", src: PIC(\"#27483a\", \"#d99a56\"), alt: \"A camp at blue hour\", shape: \"wide\" },\n ]}\n />\n );\n}\n"
@@ -715,7 +715,7 @@
715
715
  }
716
716
  ],
717
717
  "dependencies": [
718
- "@krizaka/tokens@^3.83.0",
718
+ "@krizaka/tokens@^3.85.0",
719
719
  "radix-ui@^1.8.1",
720
720
  "tailwind-variants@^3.3.1"
721
721
  ],
@@ -340,7 +340,7 @@
340
340
  }
341
341
  ],
342
342
  "dependencies": [
343
- "@krizaka/tokens@^3.83.0",
343
+ "@krizaka/tokens@^3.85.0",
344
344
  "radix-ui@^1.8.1",
345
345
  "tailwind-variants@^3.3.1"
346
346
  ],
@@ -241,6 +241,13 @@
241
241
  "description": "Programmes played in order, then again from the first. Replaces `src` and `children`.",
242
242
  "required": false
243
243
  },
244
+ {
245
+ "name": "playOnMount",
246
+ "type": "boolean",
247
+ "default": null,
248
+ "description": "Starts playing as soon as it mounts, with sound: for a player opened by a press (a lightbox), never for one that was already on the page.",
249
+ "required": false
250
+ },
244
251
  {
245
252
  "name": "poster",
246
253
  "type": "string",
@@ -549,6 +556,13 @@
549
556
  "description": "Programmes played in order, then again from the first. Replaces `src` and `children`.",
550
557
  "required": false
551
558
  },
559
+ {
560
+ "name": "playOnMount",
561
+ "type": "boolean",
562
+ "default": null,
563
+ "description": "Starts playing as soon as it mounts, with sound: for a player opened by a press (a lightbox), never for one that was already on the page.",
564
+ "required": false
565
+ },
552
566
  {
553
567
  "name": "poster",
554
568
  "type": "string",
@@ -700,7 +700,7 @@
700
700
  }
701
701
  ],
702
702
  "dependencies": [
703
- "@krizaka/tokens@^3.83.0",
703
+ "@krizaka/tokens@^3.85.0",
704
704
  "zod@^4.6.7"
705
705
  ],
706
706
  "registryDependencies": [
@@ -366,7 +366,7 @@
366
366
  }
367
367
  ],
368
368
  "dependencies": [
369
- "@krizaka/tokens@^3.83.0",
369
+ "@krizaka/tokens@^3.85.0",
370
370
  "radix-ui@^1.8.1",
371
371
  "tailwind-variants@^3.3.1"
372
372
  ],