maplibrex-svelte 0.1.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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +300 -0
  3. package/dist/components/MapLibre.svelte +258 -0
  4. package/dist/components/MapLibre.svelte.d.ts +42 -0
  5. package/dist/components/controls/AttributionControl.svelte +21 -0
  6. package/dist/components/controls/AttributionControl.svelte.d.ts +11 -0
  7. package/dist/components/controls/Control.svelte +58 -0
  8. package/dist/components/controls/Control.svelte.d.ts +33 -0
  9. package/dist/components/controls/CustomControl.svelte +46 -0
  10. package/dist/components/controls/CustomControl.svelte.d.ts +13 -0
  11. package/dist/components/controls/FullscreenControl.svelte +32 -0
  12. package/dist/components/controls/FullscreenControl.svelte.d.ts +12 -0
  13. package/dist/components/controls/GeolocateControl.svelte +32 -0
  14. package/dist/components/controls/GeolocateControl.svelte.d.ts +12 -0
  15. package/dist/components/controls/GlobeControl.svelte +16 -0
  16. package/dist/components/controls/GlobeControl.svelte.d.ts +11 -0
  17. package/dist/components/controls/LogoControl.svelte +21 -0
  18. package/dist/components/controls/LogoControl.svelte.d.ts +11 -0
  19. package/dist/components/controls/NavigationControl.svelte +21 -0
  20. package/dist/components/controls/NavigationControl.svelte.d.ts +11 -0
  21. package/dist/components/controls/ScaleControl.svelte +21 -0
  22. package/dist/components/controls/ScaleControl.svelte.d.ts +11 -0
  23. package/dist/components/controls/TerrainControl.svelte +21 -0
  24. package/dist/components/controls/TerrainControl.svelte.d.ts +11 -0
  25. package/dist/components/data/FeatureState.svelte +56 -0
  26. package/dist/components/data/FeatureState.svelte.d.ts +13 -0
  27. package/dist/components/data/Protocol.svelte +24 -0
  28. package/dist/components/data/Protocol.svelte.d.ts +9 -0
  29. package/dist/components/layers/BackgroundLayer.svelte +21 -0
  30. package/dist/components/layers/BackgroundLayer.svelte.d.ts +17 -0
  31. package/dist/components/layers/CircleLayer.svelte +25 -0
  32. package/dist/components/layers/CircleLayer.svelte.d.ts +21 -0
  33. package/dist/components/layers/ColorReliefLayer.svelte +25 -0
  34. package/dist/components/layers/ColorReliefLayer.svelte.d.ts +21 -0
  35. package/dist/components/layers/CustomLayer.svelte +35 -0
  36. package/dist/components/layers/CustomLayer.svelte.d.ts +13 -0
  37. package/dist/components/layers/FillExtrusionLayer.svelte +25 -0
  38. package/dist/components/layers/FillExtrusionLayer.svelte.d.ts +21 -0
  39. package/dist/components/layers/FillLayer.svelte +25 -0
  40. package/dist/components/layers/FillLayer.svelte.d.ts +21 -0
  41. package/dist/components/layers/HeatmapLayer.svelte +25 -0
  42. package/dist/components/layers/HeatmapLayer.svelte.d.ts +21 -0
  43. package/dist/components/layers/HillshadeLayer.svelte +25 -0
  44. package/dist/components/layers/HillshadeLayer.svelte.d.ts +21 -0
  45. package/dist/components/layers/Layer.svelte +204 -0
  46. package/dist/components/layers/Layer.svelte.d.ts +29 -0
  47. package/dist/components/layers/LineLayer.svelte +25 -0
  48. package/dist/components/layers/LineLayer.svelte.d.ts +21 -0
  49. package/dist/components/layers/RasterLayer.svelte +25 -0
  50. package/dist/components/layers/RasterLayer.svelte.d.ts +21 -0
  51. package/dist/components/layers/SymbolLayer.svelte +25 -0
  52. package/dist/components/layers/SymbolLayer.svelte.d.ts +21 -0
  53. package/dist/components/overlays/Marker.svelte +204 -0
  54. package/dist/components/overlays/Marker.svelte.d.ts +27 -0
  55. package/dist/components/overlays/Popup.svelte +184 -0
  56. package/dist/components/overlays/Popup.svelte.d.ts +24 -0
  57. package/dist/components/sources/CanvasSource.svelte +16 -0
  58. package/dist/components/sources/CanvasSource.svelte.d.ts +13 -0
  59. package/dist/components/sources/GeoJSONSource.svelte +16 -0
  60. package/dist/components/sources/GeoJSONSource.svelte.d.ts +13 -0
  61. package/dist/components/sources/ImageSource.svelte +16 -0
  62. package/dist/components/sources/ImageSource.svelte.d.ts +13 -0
  63. package/dist/components/sources/RasterDEMSource.svelte +16 -0
  64. package/dist/components/sources/RasterDEMSource.svelte.d.ts +13 -0
  65. package/dist/components/sources/RasterSource.svelte +16 -0
  66. package/dist/components/sources/RasterSource.svelte.d.ts +13 -0
  67. package/dist/components/sources/Source.svelte +88 -0
  68. package/dist/components/sources/Source.svelte.d.ts +14 -0
  69. package/dist/components/sources/VectorSource.svelte +16 -0
  70. package/dist/components/sources/VectorSource.svelte.d.ts +13 -0
  71. package/dist/components/sources/VideoSource.svelte +16 -0
  72. package/dist/components/sources/VideoSource.svelte.d.ts +13 -0
  73. package/dist/components/style/GlobalState.svelte +67 -0
  74. package/dist/components/style/GlobalState.svelte.d.ts +8 -0
  75. package/dist/components/style/Image.svelte +92 -0
  76. package/dist/components/style/Image.svelte.d.ts +14 -0
  77. package/dist/components/style/Light.svelte +31 -0
  78. package/dist/components/style/Light.svelte.d.ts +4 -0
  79. package/dist/components/style/Projection.svelte +31 -0
  80. package/dist/components/style/Projection.svelte.d.ts +4 -0
  81. package/dist/components/style/Sky.svelte +31 -0
  82. package/dist/components/style/Sky.svelte.d.ts +4 -0
  83. package/dist/components/style/Terrain.svelte +50 -0
  84. package/dist/components/style/Terrain.svelte.d.ts +9 -0
  85. package/dist/context.d.ts +41 -0
  86. package/dist/context.js +31 -0
  87. package/dist/index.d.ts +57 -0
  88. package/dist/index.js +48 -0
  89. package/dist/internal/bind-events.svelte.d.ts +26 -0
  90. package/dist/internal/bind-events.svelte.js +49 -0
  91. package/dist/internal/camera.d.ts +15 -0
  92. package/dist/internal/camera.js +33 -0
  93. package/dist/internal/deep-equal.d.ts +6 -0
  94. package/dist/internal/deep-equal.js +25 -0
  95. package/dist/internal/diff.d.ts +15 -0
  96. package/dist/internal/diff.js +29 -0
  97. package/dist/internal/events.d.ts +22 -0
  98. package/dist/internal/events.js +40 -0
  99. package/dist/internal/interactions.d.ts +22 -0
  100. package/dist/internal/interactions.js +36 -0
  101. package/dist/internal/source.d.ts +25 -0
  102. package/dist/internal/source.js +25 -0
  103. package/dist/internal/stable-key.d.ts +9 -0
  104. package/dist/internal/stable-key.js +17 -0
  105. package/dist/internal/style-ops.d.ts +26 -0
  106. package/dist/internal/style-ops.js +56 -0
  107. package/dist/types.d.ts +21 -0
  108. package/dist/types.js +1 -0
  109. package/package.json +92 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yendris Rogelio Cruz Mendoza
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,300 @@
1
+ # maplibrex-svelte
2
+
3
+ Component-oriented [MapLibre GL JS](https://maplibre.org/) bindings for Svelte 5, written in TypeScript.
4
+
5
+ You describe the map as a component tree. The library keeps that tree and the imperative MapLibre instance in sync — adding, updating in place, and tearing down in the right order.
6
+
7
+ ```svelte
8
+ <script lang="ts">
9
+ import 'maplibre-gl/dist/maplibre-gl.css';
10
+ import { MapLibre, NavigationControl, GeoJSONSource, CircleLayer } from 'maplibrex-svelte';
11
+
12
+ let zoom = $state(4);
13
+ </script>
14
+
15
+ <div style="height: 400px">
16
+ <MapLibre mapStyle="https://demotiles.maplibre.org/style.json" center={[2.17, 41.38]} bind:zoom>
17
+ <NavigationControl />
18
+
19
+ <GeoJSONSource id="cities" data={cities}>
20
+ <CircleLayer id="cities-dots" paint={{ 'circle-radius': 6, 'circle-color': '#0f766e' }} />
21
+ </GeoJSONSource>
22
+ </MapLibre>
23
+ </div>
24
+ ```
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm install maplibrex-svelte maplibre-gl
30
+ ```
31
+
32
+ `maplibre-gl` and `svelte` are peer dependencies. MapLibre is the thing being wrapped, so the consumer owns its version: two copies in one bundle would mean two WebGL contexts and two style stores.
33
+
34
+ Import the upstream stylesheet once in your app — controls, markers, and popups are unstyled without it:
35
+
36
+ ```ts
37
+ import 'maplibre-gl/dist/maplibre-gl.css';
38
+ ```
39
+
40
+ ## Should you use this?
41
+
42
+ Two other libraries cover the same ground, both mature and both published this month:
43
+
44
+ | | maplibre-gl | Svelte | Runtime dependencies |
45
+ | ------------------------------------------------------------------------ | ------------------------------------- | ------------- | ------------------------------------- |
46
+ | [`svelte-maplibre`](https://www.npmjs.com/package/svelte-maplibre) | bundled as a direct dependency (`^6`) | 5 | d3-geo, dequal, just-compare, pmtiles |
47
+ | [`svelte-maplibre-gl`](https://www.npmjs.com/package/svelte-maplibre-gl) | peer (`^5.19 \|\| ^6`) | ≥5 | — |
48
+ | this one | peer (`^6`) | 5, runes only | none |
49
+
50
+ **If you want something proven, use one of those two.** They have real users, real issues filed, and a track record this package does not have yet. This one is at `0.1.0`, and the API has already moved once during its first week.
51
+
52
+ It exists for a narrower set of preferences: no runtime dependencies at all, MapLibre 6 and Svelte 5 runes only, event props derived from MapLibre's own event maps rather than enumerated by hand, and updates that are surgical by default — a paint change calls one setter, and recreation happens only where MapLibre exposes no alternative.
53
+
54
+ ## One Vite step you cannot skip
55
+
56
+ MapLibre v6 loads its web worker from a URL it builds at runtime:
57
+
58
+ ```js
59
+ new URL(`./${workerFileName}`, import.meta.url);
60
+ ```
61
+
62
+ The template is dynamic, so no bundler can trace it. Vite never copies the worker beside the bundled chunk, and in a **production build** the request 404s. The failure is quiet and easy to misdiagnose: the map loads, the canvas appears, controls work — and every source renders as empty background, because nothing parses tiles or GeoJSON.
63
+
64
+ Copy both worker files somewhere your app serves, keeping them **in the same directory** (the worker imports its sibling shared chunk by relative path), then point MapLibre at the copy before the first map is constructed:
65
+
66
+ ```ts
67
+ import { setWorkerUrl } from 'maplibre-gl';
68
+
69
+ setWorkerUrl('/maplibre/maplibre-gl-worker.mjs');
70
+ ```
71
+
72
+ This repository does it with a small Vite plugin in `vite-plugins/maplibre-worker.ts` that reads both files out of `node_modules` at build time, so they cannot drift from the installed version. Copy it if you want the same behaviour.
73
+
74
+ Two things that look like fixes but are not: emitting only the worker with a `?url` import leaves its shared chunk missing, and a bare side-effect import of your setup module is legal to tree-shake under a narrow `sideEffects` list — export a function and call it instead.
75
+
76
+ ## Requirements
77
+
78
+ | | |
79
+ | -------------- | -------------------------------------------- |
80
+ | Svelte | 5 (runes) |
81
+ | MapLibre GL JS | 6 |
82
+ | TypeScript | optional, but every component is fully typed |
83
+
84
+ ## Design
85
+
86
+ Four decisions shape the whole API.
87
+
88
+ **The component tree is the style tree.** A `<Layer>` nested inside a source component inherits its source id. Nesting is not decoration — it is what wires the two together, and it is what makes teardown order correct: Svelte destroys children before parents, which is exactly the order MapLibre requires when removing a layer that references a source.
89
+
90
+ **Updates are surgical, never destructive.** Changing one paint property calls `setPaintProperty` for that key alone; recreating the layer would drop its tiles and restart every transition. Changing GeoJSON data calls `setData`; recreating the source would take every dependent layer down with it. Recreation happens only where MapLibre exposes no setter — and where that is the case, it is documented on the prop.
91
+
92
+ **Every MapLibre event is a typed callback prop.** The props are derived from MapLibre's own event maps, so `onmoveend` gets a `MapLibreEvent`, `onclick` on a layer gets a `MapLayerMouseEvent`, and a new upstream event is available without a release here.
93
+
94
+ **Server rendering is safe.** Importing the library on the server is harmless; the map is only constructed inside `$effect`, which never runs there. The container renders on the server, the map attaches on the client.
95
+
96
+ ## Components
97
+
98
+ ### Root
99
+
100
+ | Component | Notes |
101
+ | ------------ | ------------------------------------------------------------------------------------------------------------------------- |
102
+ | `<MapLibre>` | Creates the map and provides context. `bind:map`, `bind:ready`, `bind:center`, `bind:zoom`, `bind:bearing`, `bind:pitch`. |
103
+
104
+ Changing `mapStyle` swaps the style in place rather than recreating the map; descendants re-add themselves once the new style has loaded.
105
+
106
+ `padding` insets the viewport, which moves the vanishing point off centre. `interactions` enables and disables gesture handlers at runtime; an omitted key is left alone, so you toggle only what you name:
107
+
108
+ ```svelte
109
+ <MapLibre mapStyle={style} interactions={{ scrollZoom: false, dragRotate: allowRotation }} />
110
+ ```
111
+
112
+ ### Controls
113
+
114
+ `<NavigationControl>`, `<ScaleControl>`, `<GeolocateControl>`, `<FullscreenControl>`, `<AttributionControl>`, `<GlobeControl>`, `<TerrainControl>`, `<LogoControl>`.
115
+
116
+ Each takes its native options as props plus `position`, and exposes `bind:control` for imperative calls such as `control.trigger()`.
117
+
118
+ `<CustomControl>` puts your own markup in a control slot:
119
+
120
+ ```svelte
121
+ <CustomControl position="top-left">
122
+ <button type="button" onclick={() => (zoom = 4)}>Reset zoom</button>
123
+ </CustomControl>
124
+ ```
125
+
126
+ `<Control>` is the generic escape hatch for any third-party `IControl`.
127
+
128
+ ### Sources
129
+
130
+ `<GeoJSONSource>`, `<VectorSource>`, `<RasterSource>`, `<RasterDEMSource>`, `<ImageSource>`, `<VideoSource>`, `<CanvasSource>`, and the generic `<Source>` which takes a raw `SourceSpecification`.
131
+
132
+ ### Layers
133
+
134
+ `<FillLayer>`, `<LineLayer>`, `<SymbolLayer>`, `<CircleLayer>`, `<HeatmapLayer>`, `<FillExtrusionLayer>`, `<RasterLayer>`, `<HillshadeLayer>`, `<ColorReliefLayer>`, `<BackgroundLayer>`, and the generic `<Layer>`.
135
+
136
+ `<CustomLayer>` mounts your own WebGL layer — three.js, babylon.js, or raw GL — through MapLibre's `CustomLayerInterface`.
137
+
138
+ Common props: `id`, `source` (defaults to the enclosing source), `sourceLayer`, `paint`, `layout`, `filter`, `minzoom`, `maxzoom`, `beforeId`, and `visible` as sugar over `layout.visibility`.
139
+
140
+ Layer-scoped events are typed:
141
+
142
+ ```svelte
143
+ <CircleLayer
144
+ id="cities-dots"
145
+ paint={{ 'circle-radius': 6 }}
146
+ onclick={(event) => console.log(event.features?.[0]?.properties)}
147
+ onmouseenter={() => (cursor = 'pointer')}
148
+ />
149
+ ```
150
+
151
+ ### Overlays
152
+
153
+ `<Marker>` renders the default pin. A `content` snippet replaces it with your own markup; anything else nested — a `<Popup>`, for instance — attaches to the marker and leaves the pin alone. With `draggable`, `bind:lngLat` reflects the drag.
154
+
155
+ ```svelte
156
+ <Marker lngLat={position}>
157
+ {#snippet content()}
158
+ <div class="chip">Custom</div>
159
+ {/snippet}
160
+ </Marker>
161
+ ```
162
+
163
+ `<Popup>` works standalone with `lngLat` and `bind:open`, or nested inside a `<Marker>`, where the marker owns the open/close behaviour:
164
+
165
+ ```svelte
166
+ <Marker bind:lngLat={position} draggable>
167
+ <Popup>
168
+ <strong>Drag me</strong>
169
+ </Popup>
170
+ </Marker>
171
+ ```
172
+
173
+ ### Style state
174
+
175
+ Terrain, sky, light and projection are properties of the style rather than entries in it. These components apply them on mount and **put back what the style declared** on unmount, so mounting one inside an `{#if}` is a safe way to turn an effect on and off.
176
+
177
+ ```svelte
178
+ <RasterDEMSource id="dem" tiles={[demUrl]} encoding="terrarium">
179
+ <Terrain exaggeration={1.5} />
180
+ </RasterDEMSource>
181
+
182
+ <Sky sky-color="#001133" horizon-color="#8899aa" fog-color="#ffffff" />
183
+ <Light anchor="map" intensity={0.4} />
184
+ <Projection type="globe" />
185
+ ```
186
+
187
+ `<Terrain>` inherits its source id from an enclosing `<RasterDEMSource>`, the same way layers do.
188
+
189
+ `<Image>` registers an icon for `icon-image` to reference, from a URL or from pixels you already have, and re-registers it after a style swap:
190
+
191
+ ```svelte
192
+ <Image id="cat" url="/cat.png" />
193
+ <Image id="pulse" image={generatedPixels} pixelRatio={2} sdf />
194
+ <Image id="popup-bg" url="/popup.png" stretchX={[[25, 55]]} content={[25, 25, 115, 100]} />
195
+ ```
196
+
197
+ `<GlobalState>` turns every prop into a global state property, readable from style expressions through `["global-state", "name"]`:
198
+
199
+ ```svelte
200
+ <GlobalState labelSize={14} showBuildings={true} />
201
+ ```
202
+
203
+ ### Data
204
+
205
+ `<FeatureState>` makes hover and selection declarative. Mount it while a feature is active; unmounting clears the state, so there is no `setFeatureState` left without its matching `removeFeatureState`:
206
+
207
+ ```svelte
208
+ <GeoJSONSource id="counties" data={counties}>
209
+ {#if hoveredId !== null}
210
+ <FeatureState id={hoveredId} state={{ hover: true }} />
211
+ {/if}
212
+
213
+ <FillLayer
214
+ id="counties-fill"
215
+ paint={{ 'fill-opacity': ['case', ['boolean', ['feature-state', 'hover'], false], 1, 0.4] }}
216
+ onmousemove={(event) => (hoveredId = event.features?.[0]?.id ?? null)}
217
+ onmouseleave={() => (hoveredId = null)}
218
+ />
219
+ </GeoJSONSource>
220
+ ```
221
+
222
+ `<Protocol>` registers a custom URL scheme — PMTiles, or a transform over an existing endpoint. MapLibre keeps protocols in a global registry, not on the map, so **place it above `<MapLibre>`**: sibling effects run in document order, and the scheme must exist before the map requests anything through it.
223
+
224
+ ```svelte
225
+ <Protocol name="pmtiles" handler={pmtilesProtocol.tile} />
226
+
227
+ <MapLibre mapStyle={style}>
228
+ <VectorSource id="tiles" url="pmtiles://https://example.com/tiles.pmtiles" />
229
+ </MapLibre>
230
+ ```
231
+
232
+ ## Two-way camera binding
233
+
234
+ `bind:center`, `bind:zoom`, `bind:bearing`, and `bind:pitch` are genuinely bidirectional. Panning writes back to your state; assigning to your state moves the map. The loop is broken by comparison, not by a mutex: an update that matches where the map already is does nothing. `cameraMode` picks how prop-driven moves animate — `'jump'`, `'ease'` (default), or `'fly'`.
235
+
236
+ ## Escape hatches
237
+
238
+ Nothing here is a wall. `bind:map` gives you the raw `Map`; `getMapContext()` gives it to any descendant component; `<Source>`, `<Layer>`, and `<Control>` take raw MapLibre specifications and instances.
239
+
240
+ ```svelte
241
+ <script lang="ts">
242
+ import { getMapContext } from 'maplibrex-svelte';
243
+
244
+ const context = getMapContext();
245
+
246
+ $effect(() => {
247
+ if (!context.ready) return;
248
+ context.map?.setProjection({ type: 'globe' });
249
+ });
250
+ </script>
251
+ ```
252
+
253
+ ## Provenance
254
+
255
+ The component surface is derived from the [official MapLibre GL JS examples](https://maplibre.org/maplibre-gl-js/docs/examples/) rather than invented. Each component exists because real examples need it:
256
+
257
+ | Component | Examples it covers |
258
+ | ---------------- | -------------------------------------------------------------------------------------- |
259
+ | `<Terrain>` | 3D Terrain; quantized-mesh terrain; hybrid satellite with elevation; Sky, Fog, Terrain |
260
+ | `<Sky>` | Sky, Fog, Terrain; globe with an atmosphere |
261
+ | `<Projection>` | the globe family — vector globe, custom layers on a globe, fill extrusion on a globe |
262
+ | `<Light>` | display buildings in 3D |
263
+ | `<Image>` | add an icon; generated icon; stretchable image; remote SVG symbol; fallback image |
264
+ | `<CanvasSource>` | add a canvas source |
265
+ | `<CustomLayer>` | custom style layer; three.js and babylon.js models; custom layers on a globe |
266
+ | `<FeatureState>` | create a hover effect; get features under the mouse pointer |
267
+ | `<Protocol>` | PMTiles source and protocol; addProtocol to transform feature properties |
268
+ | `<GlobalState>` | filter layer symbols using global state |
269
+ | `padding` | offset the vanishing point using padding |
270
+ | `interactions` | toggle interactions; disable rotation; disable scroll zoom |
271
+
272
+ ## Documentation site
273
+
274
+ `npm run dev` serves a documentation site alongside the library: a page per component, generated from a single registry so a component cannot ship with a page that disagrees with it, plus nine live demos and a playground.
275
+
276
+ | Route | What it is |
277
+ | ------------------- | ------------------------------------------------------------------------------- |
278
+ | `/` | Overview, install, and the design decisions |
279
+ | `/docs` | Every component, grouped by what it does |
280
+ | `/docs/<component>` | Live demo, usage, props, gotchas, and the official examples it covers |
281
+ | `/playground` | One map wired to a source, layers, feature state, overlays and controls at once |
282
+
283
+ The site lives outside `src/lib`, so none of it reaches the published package.
284
+
285
+ ## Development
286
+
287
+ ```sh
288
+ npm install
289
+ npm run dev # demo app in src/routes
290
+ npm run check # svelte-check
291
+ npm run test # unit tests plus real-WebGL component tests
292
+ npm run lint
293
+ npm run prepack # build the distributable and validate it with publint
294
+ ```
295
+
296
+ Component tests run in headless Chromium against a real map with an inline, empty style — no mocks and no network.
297
+
298
+ ## License
299
+
300
+ MIT
@@ -0,0 +1,258 @@
1
+ <script lang="ts">
2
+ import { Map as MapLibreMap } from 'maplibre-gl';
3
+ import type {
4
+ LngLatBoundsLike,
5
+ LngLatLike,
6
+ MapOptions,
7
+ PaddingOptions,
8
+ StyleSpecification
9
+ } from 'maplibre-gl';
10
+ import { untrack, type Snippet } from 'svelte';
11
+ import { setMapContext } from '../context.js';
12
+ import { sameLngLat, sameNumber } from '../internal/camera.js';
13
+ import { bindEvents } from '../internal/bind-events.svelte.js';
14
+ import {
15
+ planInteractionChanges,
16
+ readInteractionState,
17
+ type InteractionRequest
18
+ } from '../internal/interactions.js';
19
+ import type { CameraMode, MapEventProps } from '../types.js';
20
+
21
+ type Props = MapEventProps & {
22
+ /**
23
+ * A style URL or an inline style specification. Changing it swaps the
24
+ * style in place instead of recreating the map.
25
+ */
26
+ mapStyle: StyleSpecification | string;
27
+ /** Two-way. Written back as a `[lng, lat]` tuple as the user pans. */
28
+ center?: LngLatLike;
29
+ /** Two-way. */
30
+ zoom?: number;
31
+ /** Two-way. */
32
+ bearing?: number;
33
+ /** Two-way. */
34
+ pitch?: number;
35
+ /** Applied once on creation; use `map.fitBounds` afterwards. */
36
+ bounds?: LngLatBoundsLike;
37
+ /** Insets the viewport, which moves the vanishing point off centre. */
38
+ padding?: PaddingOptions;
39
+ /** Enables or disables gesture handlers at runtime. Omitted keys are left alone. */
40
+ interactions?: InteractionRequest;
41
+ /** How camera prop changes are applied. @defaultValue 'ease' */
42
+ cameraMode?: CameraMode;
43
+ /** Escape hatch for any `MapOptions` this component does not surface. */
44
+ options?: Partial<Omit<MapOptions, 'container' | 'style'>>;
45
+ /** Read-only binding to the underlying instance. */
46
+ map?: MapLibreMap | null;
47
+ /** Read-only binding: `true` once the style is loaded. */
48
+ ready?: boolean;
49
+ class?: string;
50
+ style?: string;
51
+ children?: Snippet<[{ map: MapLibreMap }]>;
52
+ };
53
+
54
+ let {
55
+ mapStyle,
56
+ center = $bindable(),
57
+ zoom = $bindable(),
58
+ bearing = $bindable(),
59
+ pitch = $bindable(),
60
+ bounds,
61
+ padding,
62
+ interactions,
63
+ cameraMode = 'ease',
64
+ options,
65
+ map = $bindable(null),
66
+ ready = $bindable(false),
67
+ class: className,
68
+ style: containerStyle,
69
+ children,
70
+ ...events
71
+ }: Props = $props();
72
+
73
+ let container = $state<HTMLDivElement | null>(null);
74
+ let styleEpoch = $state(0);
75
+
76
+ setMapContext({
77
+ get map() {
78
+ return map;
79
+ },
80
+ get ready() {
81
+ return ready;
82
+ },
83
+ get styleEpoch() {
84
+ return styleEpoch;
85
+ }
86
+ });
87
+
88
+ // Creation depends on the container element alone. Every other prop is read
89
+ // untracked so that a zoom change never tears the WebGL context down.
90
+ $effect(() => {
91
+ const element = container;
92
+ if (!element) return;
93
+
94
+ return untrack(() => {
95
+ const instance = new MapLibreMap({
96
+ ...options,
97
+ container: element,
98
+ style: mapStyle,
99
+ ...(center !== undefined && { center }),
100
+ ...(zoom !== undefined && { zoom }),
101
+ ...(bearing !== undefined && { bearing }),
102
+ ...(pitch !== undefined && { pitch }),
103
+ ...(bounds !== undefined && { bounds })
104
+ });
105
+
106
+ map = instance;
107
+
108
+ const loaded = instance.on('load', () => {
109
+ ready = true;
110
+ styleEpoch += 1;
111
+ });
112
+
113
+ return () => {
114
+ loaded.unsubscribe();
115
+ ready = false;
116
+ map = null;
117
+ instance.remove();
118
+ };
119
+ });
120
+ });
121
+
122
+ // Style swaps wipe user-added sources and layers, so descendants are told to
123
+ // re-add themselves only once the replacement style has finished loading.
124
+ let appliedStyle = $state<StyleSpecification | string | undefined>();
125
+
126
+ $effect(() => {
127
+ const instance = map;
128
+ const nextStyle = mapStyle;
129
+ if (!instance || !ready) return;
130
+
131
+ if (untrack(() => appliedStyle) === undefined) {
132
+ appliedStyle = nextStyle;
133
+ return;
134
+ }
135
+ if (untrack(() => appliedStyle) === nextStyle) return;
136
+
137
+ appliedStyle = nextStyle;
138
+ instance.setStyle(nextStyle);
139
+
140
+ let cancelled = false;
141
+ void instance.once('styledata').then(() => {
142
+ if (!cancelled) styleEpoch += 1;
143
+ });
144
+
145
+ return () => {
146
+ cancelled = true;
147
+ };
148
+ });
149
+
150
+ // Map -> props. Guarded by value comparison rather than a mutex flag, which
151
+ // also absorbs the write the opposite effect is about to make.
152
+ $effect(() => {
153
+ const instance = map;
154
+ if (!instance) return;
155
+
156
+ const sync = () => {
157
+ const nextCenter = instance.getCenter();
158
+ if (!sameLngLat(center, nextCenter)) center = [nextCenter.lng, nextCenter.lat];
159
+ if (!sameNumber(zoom, instance.getZoom())) zoom = instance.getZoom();
160
+ if (!sameNumber(bearing, instance.getBearing())) bearing = instance.getBearing();
161
+ if (!sameNumber(pitch, instance.getPitch())) pitch = instance.getPitch();
162
+ };
163
+
164
+ const subscriptions = [
165
+ instance.on('move', sync),
166
+ instance.on('rotate', sync),
167
+ instance.on('pitch', sync)
168
+ ];
169
+
170
+ return () => {
171
+ for (const subscription of subscriptions) subscription.unsubscribe();
172
+ };
173
+ });
174
+
175
+ // Props -> map. A no-op when the map is already where the props say it is,
176
+ // which is what stops the two directions from feeding each other.
177
+ $effect(() => {
178
+ const instance = map;
179
+ const target = { center, zoom, bearing, pitch };
180
+ if (!instance) return;
181
+
182
+ const moved =
183
+ (target.center !== undefined && !sameLngLat(target.center, instance.getCenter())) ||
184
+ (target.zoom !== undefined && !sameNumber(target.zoom, instance.getZoom())) ||
185
+ (target.bearing !== undefined && !sameNumber(target.bearing, instance.getBearing())) ||
186
+ (target.pitch !== undefined && !sameNumber(target.pitch, instance.getPitch()));
187
+
188
+ if (!moved) return;
189
+
190
+ const cameraOptions = {
191
+ ...(target.center !== undefined && { center: target.center }),
192
+ ...(target.zoom !== undefined && { zoom: target.zoom }),
193
+ ...(target.bearing !== undefined && { bearing: target.bearing }),
194
+ ...(target.pitch !== undefined && { pitch: target.pitch })
195
+ };
196
+
197
+ untrack(() => {
198
+ if (cameraMode === 'jump') instance.jumpTo(cameraOptions);
199
+ else if (cameraMode === 'fly') instance.flyTo(cameraOptions);
200
+ else instance.easeTo(cameraOptions);
201
+ });
202
+ });
203
+
204
+ $effect(() => {
205
+ const instance = map;
206
+ const next = padding;
207
+ if (!instance || next === undefined) return;
208
+
209
+ untrack(() => instance.setPadding(next));
210
+ });
211
+
212
+ // Gesture handlers are imperative objects rather than style state, so they
213
+ // are compared against their live enabled flag instead of a shadow copy.
214
+ $effect(() => {
215
+ const instance = map;
216
+ const requested = interactions;
217
+ if (!instance || !requested) return;
218
+
219
+ const changes = planInteractionChanges(readInteractionState(instance), requested);
220
+ if (changes.length === 0) return;
221
+
222
+ untrack(() => {
223
+ for (const [name, enabled] of changes) {
224
+ // The handlers share `enable`/`disable` but not their option types,
225
+ // so the union is widened at this single call site.
226
+ const handler = instance[name] as { enable(): void; disable(): void };
227
+ if (enabled) handler.enable();
228
+ else handler.disable();
229
+ }
230
+ });
231
+ });
232
+
233
+ bindEvents(
234
+ () => map,
235
+ () => events
236
+ );
237
+ </script>
238
+
239
+ <div
240
+ bind:this={container}
241
+ class={['maplibrex-map', className]}
242
+ style={containerStyle}
243
+ data-maplibrex="map"
244
+ ></div>
245
+
246
+ {#if map}
247
+ {@render children?.({ map })}
248
+ {/if}
249
+
250
+ <style>
251
+ /* Fills its parent by default: a map with no height renders nothing, and
252
+ that is the single most common first-run surprise. */
253
+ .maplibrex-map {
254
+ position: relative;
255
+ width: 100%;
256
+ height: 100%;
257
+ }
258
+ </style>
@@ -0,0 +1,42 @@
1
+ import { Map as MapLibreMap } from 'maplibre-gl';
2
+ import type { LngLatBoundsLike, LngLatLike, MapOptions, PaddingOptions, StyleSpecification } from 'maplibre-gl';
3
+ import { type Snippet } from 'svelte';
4
+ import { type InteractionRequest } from '../internal/interactions.js';
5
+ import type { CameraMode, MapEventProps } from '../types.js';
6
+ type Props = MapEventProps & {
7
+ /**
8
+ * A style URL or an inline style specification. Changing it swaps the
9
+ * style in place instead of recreating the map.
10
+ */
11
+ mapStyle: StyleSpecification | string;
12
+ /** Two-way. Written back as a `[lng, lat]` tuple as the user pans. */
13
+ center?: LngLatLike;
14
+ /** Two-way. */
15
+ zoom?: number;
16
+ /** Two-way. */
17
+ bearing?: number;
18
+ /** Two-way. */
19
+ pitch?: number;
20
+ /** Applied once on creation; use `map.fitBounds` afterwards. */
21
+ bounds?: LngLatBoundsLike;
22
+ /** Insets the viewport, which moves the vanishing point off centre. */
23
+ padding?: PaddingOptions;
24
+ /** Enables or disables gesture handlers at runtime. Omitted keys are left alone. */
25
+ interactions?: InteractionRequest;
26
+ /** How camera prop changes are applied. @defaultValue 'ease' */
27
+ cameraMode?: CameraMode;
28
+ /** Escape hatch for any `MapOptions` this component does not surface. */
29
+ options?: Partial<Omit<MapOptions, 'container' | 'style'>>;
30
+ /** Read-only binding to the underlying instance. */
31
+ map?: MapLibreMap | null;
32
+ /** Read-only binding: `true` once the style is loaded. */
33
+ ready?: boolean;
34
+ class?: string;
35
+ style?: string;
36
+ children?: Snippet<[{
37
+ map: MapLibreMap;
38
+ }]>;
39
+ };
40
+ declare const MapLibre: import("svelte").Component<Props, {}, "center" | "zoom" | "bearing" | "pitch" | "map" | "ready">;
41
+ type MapLibre = ReturnType<typeof MapLibre>;
42
+ export default MapLibre;
@@ -0,0 +1,21 @@
1
+ <script lang="ts">
2
+ import { AttributionControl as MapLibreAttributionControl } from 'maplibre-gl';
3
+ import type { ControlPosition, AttributionControlOptions } from 'maplibre-gl';
4
+ import Control from './Control.svelte';
5
+
6
+ type Props = AttributionControlOptions & {
7
+ /** @defaultValue 'top-right' */
8
+ position?: ControlPosition;
9
+ /** Read-only binding to the underlying control, for imperative calls. */
10
+ control?: MapLibreAttributionControl | null;
11
+ };
12
+
13
+ let { position = 'top-right', control = $bindable(null), ...options }: Props = $props();
14
+ </script>
15
+
16
+ <Control
17
+ factory={(resolved: AttributionControlOptions) => new MapLibreAttributionControl(resolved)}
18
+ {options}
19
+ {position}
20
+ bind:control
21
+ />
@@ -0,0 +1,11 @@
1
+ import { AttributionControl as MapLibreAttributionControl } from 'maplibre-gl';
2
+ import type { ControlPosition, AttributionControlOptions } from 'maplibre-gl';
3
+ type Props = AttributionControlOptions & {
4
+ /** @defaultValue 'top-right' */
5
+ position?: ControlPosition;
6
+ /** Read-only binding to the underlying control, for imperative calls. */
7
+ control?: MapLibreAttributionControl | null;
8
+ };
9
+ declare const AttributionControl: import("svelte").Component<Props, {}, "control">;
10
+ type AttributionControl = ReturnType<typeof AttributionControl>;
11
+ export default AttributionControl;