@classic-homes/maps-svelte 0.5.1 → 0.6.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.
@@ -47,7 +47,7 @@
47
47
  {#if onRetry}
48
48
  <button
49
49
  onclick={onRetry}
50
- class="mt-2 rounded-md border border-input bg-background px-4 py-2 text-sm font-medium shadow-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
50
+ class="mt-2 rounded-md border border-input bg-background px-4 py-2 text-sm font-medium shadow-sm hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
51
51
  >
52
52
  Retry
53
53
  </button>
@@ -1,9 +1,10 @@
1
1
  <script lang="ts">
2
- import { getContext, untrack } from 'svelte';
2
+ import { getContext, tick, untrack } from 'svelte';
3
3
  import type { BasemapSwitcherProps, BasemapDefinition } from '@classic-homes/maps-core';
4
4
  import {
5
5
  FREE_BASEMAPS,
6
6
  getAvailableBasemaps,
7
+ getGridNavigationIndex,
7
8
  resolveBasemapStyle,
8
9
  resolveBasemapThumbnail,
9
10
  } from '@classic-homes/maps-core';
@@ -40,6 +41,9 @@
40
41
  let internalActiveId = $state<string | undefined>(undefined);
41
42
  let containerElement: HTMLDivElement;
42
43
  let toggleButton: HTMLButtonElement;
44
+ const optionButtons: (HTMLButtonElement | null)[] = $state([]);
45
+ // Roving tab stop: the one option in the radiogroup that Tab reaches
46
+ let tabStopIndex = $state(0);
43
47
  let panelStyle = $state('');
44
48
  let panelColumns = $state(1);
45
49
  let compactPanel = $state(false);
@@ -110,6 +114,39 @@
110
114
  const currentActiveId = $derived(
111
115
  activeBasemapId ?? internalActiveId ?? availableBasemaps()[0]?.id
112
116
  );
117
+ const activeIndex = $derived(
118
+ Math.max(
119
+ 0,
120
+ availableBasemaps().findIndex((basemap) => basemap.id === currentActiveId)
121
+ )
122
+ );
123
+
124
+ // On open, the checked option takes the tab stop and focus. Only isOpen is
125
+ // tracked: re-focusing whenever the active basemap changes would pull focus
126
+ // around while the panel is in use.
127
+ $effect(() => {
128
+ if (!isOpen) return;
129
+ const index = untrack(() => activeIndex);
130
+ tabStopIndex = index;
131
+ // The options render with this same update; focus once they are in the DOM
132
+ tick().then(() => optionButtons[index]?.focus());
133
+ });
134
+
135
+ // Arrow keys move focus between options; Enter/Space selects. Selecting on
136
+ // arrow (the automatic radiogroup variant) would swap the map style and close
137
+ // the panel on the first key press.
138
+ function handleOptionsKeyDown(e: KeyboardEvent) {
139
+ const next = getGridNavigationIndex(
140
+ e.key,
141
+ tabStopIndex,
142
+ availableBasemaps().length,
143
+ panelColumns
144
+ );
145
+ if (next === null) return;
146
+ e.preventDefault();
147
+ tabStopIndex = next;
148
+ optionButtons[next]?.focus();
149
+ }
113
150
 
114
151
  // Close on outside click
115
152
  $effect(() => {
@@ -195,22 +232,28 @@
195
232
  style={panelStyle}
196
233
  >
197
234
  <div
198
- role="group"
235
+ role="radiogroup"
199
236
  aria-label="Select basemap"
237
+ tabindex="-1"
200
238
  class="grid gap-1.5"
201
239
  style="grid-template-columns: repeat({panelColumns}, minmax(0, 1fr));"
240
+ onkeydown={handleOptionsKeyDown}
202
241
  >
203
- {#each availableBasemaps() as basemap (basemap.id)}
242
+ {#each availableBasemaps() as basemap, index (basemap.id)}
204
243
  {@const isActive = basemap.id === currentActiveId}
205
244
  {@const thumbUrl = resolveBasemapThumbnail(basemap, apiKeys)}
206
245
  <button
246
+ bind:this={optionButtons[index]}
207
247
  type="button"
208
- aria-pressed={isActive}
248
+ role="radio"
249
+ aria-checked={isActive}
250
+ tabindex={index === tabStopIndex ? 0 : -1}
209
251
  class={cn(
210
252
  'flex min-h-[44px] min-w-0 flex-col items-center gap-1 p-1 rounded cursor-pointer',
211
- 'hover:bg-muted transition-colors',
253
+ 'hover:bg-muted',
212
254
  isActive && 'ring-2 ring-primary'
213
255
  )}
256
+ onfocus={() => (tabStopIndex = index)}
214
257
  onclick={() => handleSelect(basemap)}
215
258
  title={basemap.name}
216
259
  >
@@ -239,7 +282,7 @@
239
282
  class={cn(
240
283
  'w-[44px] h-[44px] flex items-center justify-center',
241
284
  'bg-card rounded shadow-lg border border-black dark:border-gray-400',
242
- 'hover:bg-muted transition-colors cursor-pointer',
285
+ 'hover:bg-muted cursor-pointer',
243
286
  'text-foreground'
244
287
  )}
245
288
  onclick={handleToggle}
@@ -219,17 +219,26 @@
219
219
  lastKnownStyleVersion = sv;
220
220
  addedSources.clear();
221
221
  addedLayers.clear();
222
+ layerThemes.clear();
222
223
  }
223
224
  });
224
225
 
225
226
  // Track pending map update
226
227
  let mapUpdateTimeout: ReturnType<typeof setTimeout> | null = null;
228
+ // Theme each added layer's paint was last applied for
229
+ const layerThemes = new Map<string, 'light' | 'dark'>();
227
230
 
228
231
  // Manage sources and layers on the map
229
232
  // Use setTimeout to debounce updates and break reactive chains
230
233
  $effect(() => {
231
234
  // Read visibleLayerStates to establish dependency
232
235
  const states = visibleLayerStates;
236
+ // Also re-sync after a style reload (setStyle drops our sources/layers),
237
+ // once the map loads, and when the theme changes. These must be read here,
238
+ // synchronously: reads inside the setTimeout below are not tracked.
239
+ void mapContext.styleVersion;
240
+ void mapContext.loaded;
241
+ const theme = isDark ? 'dark' : 'light';
233
242
 
234
243
  // Cancel any pending update
235
244
  if (mapUpdateTimeout) {
@@ -244,7 +253,6 @@
244
253
  const { map, loaded } = mapContext;
245
254
  if (!map || !loaded) return;
246
255
 
247
- const theme = isDark ? 'dark' : 'light';
248
256
  const currentVisibleIds = new Set(states.map((s) => s.id));
249
257
 
250
258
  // Add/update visible layers
@@ -318,11 +326,24 @@
318
326
 
319
327
  map.addLayer(layerConfig);
320
328
  addedLayers.add(layerId);
329
+ layerThemes.set(layerId, theme);
321
330
  } catch (err) {
322
331
  console.error(`[maps-svelte] LayerManager: Failed to add layer "${layerId}":`, err);
323
332
  }
324
333
  }
325
334
 
335
+ // Restyle an existing layer when the theme changed since it was styled
336
+ if (map.getLayer(layerId) && layerThemes.get(layerId) !== theme) {
337
+ for (const [prop, value] of Object.entries(paint)) {
338
+ try {
339
+ map.setPaintProperty(layerId, prop, value);
340
+ } catch {
341
+ // Ignore
342
+ }
343
+ }
344
+ layerThemes.set(layerId, theme);
345
+ }
346
+
326
347
  // Update opacity if layer exists
327
348
  // Multiply base opacity from style with state opacity so the slider acts as a multiplier
328
349
  if (map.getLayer(layerId)) {
@@ -548,6 +569,12 @@
548
569
 
549
570
  // Cleanup on destroy
550
571
  onDestroy(() => {
572
+ // A pending debounced update would otherwise add sources/layers after cleanup
573
+ if (mapUpdateTimeout) {
574
+ clearTimeout(mapUpdateTimeout);
575
+ mapUpdateTimeout = null;
576
+ }
577
+
551
578
  const { map } = mapContext;
552
579
  if (!map) return;
553
580
 
@@ -746,7 +773,8 @@
746
773
  class="text-muted-foreground hover:text-foreground p-1"
747
774
  onclick={() =>
748
775
  (expandedOpacity = expandedOpacity === layer.id ? null : layer.id)}
749
- aria-label="Adjust opacity"
776
+ aria-label={`Adjust ${layer.name} opacity`}
777
+ aria-expanded={expandedOpacity === layer.id}
750
778
  >
751
779
  <svg
752
780
  width="14"
@@ -772,6 +800,8 @@
772
800
  min="0"
773
801
  max="100"
774
802
  value={state.opacity * 100}
803
+ aria-label={`${layer.name} opacity`}
804
+ aria-valuetext={`${Math.round(state.opacity * 100)}%`}
775
805
  oninput={(e) =>
776
806
  handleOpacityChange(
777
807
  layer.id,
@@ -865,7 +895,8 @@
865
895
  class="text-muted-foreground hover:text-foreground p-1"
866
896
  onclick={() =>
867
897
  (expandedOpacity = expandedOpacity === layer.id ? null : layer.id)}
868
- aria-label="Adjust opacity"
898
+ aria-label={`Adjust ${layer.name} opacity`}
899
+ aria-expanded={expandedOpacity === layer.id}
869
900
  >
870
901
  <svg
871
902
  width="14"
@@ -891,6 +922,8 @@
891
922
  min="0"
892
923
  max="100"
893
924
  value={state.opacity * 100}
925
+ aria-label={`${layer.name} opacity`}
926
+ aria-valuetext={`${Math.round(state.opacity * 100)}%`}
894
927
  oninput={(e) =>
895
928
  handleOpacityChange(
896
929
  layer.id,
@@ -921,7 +954,7 @@
921
954
  class={cn(
922
955
  'w-[40px] h-[40px] flex items-center justify-center',
923
956
  'bg-card rounded shadow-lg border border-black dark:border-gray-400',
924
- 'hover:bg-muted transition-colors cursor-pointer',
957
+ 'hover:bg-muted cursor-pointer',
925
958
  'text-foreground'
926
959
  )}
927
960
  onclick={handleToggle}
@@ -104,7 +104,7 @@
104
104
  type="button"
105
105
  class={cn(
106
106
  'w-full flex items-center justify-between px-3 py-2 font-medium text-card-foreground',
107
- 'cursor-pointer hover:bg-muted transition-colors',
107
+ 'cursor-pointer hover:bg-muted',
108
108
  isFirst && 'rounded-t-lg',
109
109
  isLast && !isExpanded && 'rounded-b-lg'
110
110
  )}
@@ -196,6 +196,17 @@
196
196
  keyboard,
197
197
  cooperativeGestures,
198
198
  attributionControl: attributionControl ? { customAttribution } : false,
199
+ // Frame the bounds from the first frame (as React's Map does); `center`
200
+ // /`zoom` alone put the map at its defaults until the load handler's
201
+ // fitBounds, which then flew in from the other side of the world.
202
+ ...(bounds
203
+ ? {
204
+ bounds: bounds as [[number, number], [number, number]],
205
+ fitBoundsOptions: {
206
+ padding: boundsPadding as number | maplibregl.PaddingOptions | undefined,
207
+ },
208
+ }
209
+ : {}),
199
210
  });
200
211
 
201
212
  map = newMap;
@@ -380,78 +391,74 @@
380
391
  };
381
392
  };
382
393
 
383
- // Click handlers
384
- if (onClick) {
385
- newMap.on('click', (e) => {
386
- onClick({
387
- type: 'click',
388
- ...createEventParams(e),
389
- features: newMap.queryRenderedFeatures(
390
- e.point
391
- ) as unknown as MapClickEventParams['features'],
392
- });
394
+ // Handlers are always attached and read the callback props when the
395
+ // event fires: a callback passed after mount still gets wired, and one
396
+ // removed later is skipped instead of throwing on every event. Each one
397
+ // returns early when no callback is set, so an unused mousemove or move does
398
+ // not query features or bounds on every frame.
399
+ newMap.on('click', (e) => {
400
+ if (!onClick) return;
401
+ onClick({
402
+ type: 'click',
403
+ ...createEventParams(e),
404
+ features: newMap.queryRenderedFeatures(
405
+ e.point
406
+ ) as unknown as MapClickEventParams['features'],
393
407
  });
394
- }
408
+ });
395
409
 
396
- if (onDblClick) {
397
- newMap.on('dblclick', (e) => {
398
- onDblClick({
399
- type: 'dblclick',
400
- ...createEventParams(e),
401
- features: newMap.queryRenderedFeatures(
402
- e.point
403
- ) as unknown as MapClickEventParams['features'],
404
- });
410
+ newMap.on('dblclick', (e) => {
411
+ if (!onDblClick) return;
412
+ onDblClick({
413
+ type: 'dblclick',
414
+ ...createEventParams(e),
415
+ features: newMap.queryRenderedFeatures(
416
+ e.point
417
+ ) as unknown as MapClickEventParams['features'],
405
418
  });
406
- }
419
+ });
407
420
 
408
- if (onContextMenu) {
409
- newMap.on('contextmenu', (e) => {
410
- onContextMenu({
411
- type: 'contextmenu',
412
- ...createEventParams(e),
413
- features: newMap.queryRenderedFeatures(
414
- e.point
415
- ) as unknown as MapClickEventParams['features'],
416
- });
421
+ newMap.on('contextmenu', (e) => {
422
+ if (!onContextMenu) return;
423
+ onContextMenu({
424
+ type: 'contextmenu',
425
+ ...createEventParams(e),
426
+ features: newMap.queryRenderedFeatures(
427
+ e.point
428
+ ) as unknown as MapClickEventParams['features'],
417
429
  });
418
- }
430
+ });
419
431
 
420
- if (onMouseMove) {
421
- newMap.on('mousemove', (e) => {
422
- onMouseMove({
423
- type: 'mousemove',
424
- ...createEventParams(e),
425
- features: newMap.queryRenderedFeatures(
426
- e.point
427
- ) as unknown as MapHoverEventParams['features'],
428
- });
432
+ newMap.on('mousemove', (e) => {
433
+ if (!onMouseMove) return;
434
+ onMouseMove({
435
+ type: 'mousemove',
436
+ ...createEventParams(e),
437
+ features: newMap.queryRenderedFeatures(
438
+ e.point
439
+ ) as unknown as MapHoverEventParams['features'],
429
440
  });
430
- }
441
+ });
431
442
 
432
- if (onMove) {
433
- newMap.on('move', () => {
434
- onMove({ type: 'move', ...createMoveParams() } as MapMoveEventParams);
435
- });
436
- }
443
+ newMap.on('move', () => {
444
+ if (!onMove) return;
445
+ onMove({ type: 'move', ...createMoveParams() } as MapMoveEventParams);
446
+ });
437
447
 
438
- if (onMoveStart) {
439
- newMap.on('movestart', () => {
440
- onMoveStart({ type: 'movestart', ...createMoveParams() } as MapMoveEventParams);
441
- });
442
- }
448
+ newMap.on('movestart', () => {
449
+ if (!onMoveStart) return;
450
+ onMoveStart({ type: 'movestart', ...createMoveParams() } as MapMoveEventParams);
451
+ });
443
452
 
444
- if (onMoveEnd) {
445
- newMap.on('moveend', () => {
446
- onMoveEnd({ type: 'moveend', ...createMoveParams() } as MapMoveEventParams);
447
- });
448
- }
453
+ newMap.on('moveend', () => {
454
+ if (!onMoveEnd) return;
455
+ onMoveEnd({ type: 'moveend', ...createMoveParams() } as MapMoveEventParams);
456
+ });
449
457
 
450
- if (onZoom) {
451
- newMap.on('zoom', () => {
452
- onZoom({ type: 'zoom', ...createMoveParams() } as MapMoveEventParams);
453
- });
454
- }
458
+ newMap.on('zoom', () => {
459
+ if (!onZoom) return;
460
+ onZoom({ type: 'zoom', ...createMoveParams() } as MapMoveEventParams);
461
+ });
455
462
  } catch (err) {
456
463
  const errorMessage = err instanceof Error ? err.message : 'Failed to initialize map';
457
464
  mapError = errorMessage;
@@ -9,6 +9,7 @@
9
9
  removeMarkerProtection,
10
10
  } from '@classic-homes/maps-core';
11
11
  import type { MapContextValue } from '../../composables/useMapContext.svelte';
12
+ import { colors } from '@classic-homes/theme-tokens';
12
13
 
13
14
  type Anchor =
14
15
  | 'center'
@@ -29,7 +30,7 @@
29
30
  let {
30
31
  id,
31
32
  coordinates,
32
- color = '#3ba4a7',
33
+ color = colors.teal[500],
33
34
  anchor = 'bottom',
34
35
  offset,
35
36
  rotation,
@@ -96,37 +97,36 @@
96
97
 
97
98
  marker = newMarker;
98
99
 
99
- // Drag handlers
100
- if (draggable) {
101
- newMarker.on('dragstart', () => {
100
+ // Drag handlers — always registered (they no-op without callbacks) so
101
+ // they still fire when `draggable` is switched on after creation
102
+ newMarker.on('dragstart', () => {
103
+ const lngLat = newMarker.getLngLat();
104
+ originalLngLat = [lngLat.lng, lngLat.lat] as LngLat;
105
+ });
106
+
107
+ newMarker.on('drag', () => {
108
+ if (onDrag) {
102
109
  const lngLat = newMarker.getLngLat();
103
- originalLngLat = [lngLat.lng, lngLat.lat] as LngLat;
104
- });
105
-
106
- newMarker.on('drag', () => {
107
- if (onDrag) {
108
- const lngLat = newMarker.getLngLat();
109
- onDrag({
110
- type: 'drag',
111
- markerId: id || '',
112
- lngLat: [lngLat.lng, lngLat.lat] as LngLat,
113
- originalLngLat,
114
- });
115
- }
116
- });
117
-
118
- newMarker.on('dragend', () => {
119
- if (onDragEnd) {
120
- const lngLat = newMarker.getLngLat();
121
- onDragEnd({
122
- type: 'dragend',
123
- markerId: id || '',
124
- lngLat: [lngLat.lng, lngLat.lat] as LngLat,
125
- originalLngLat,
126
- });
127
- }
128
- });
129
- }
110
+ onDrag({
111
+ type: 'drag',
112
+ markerId: id || '',
113
+ lngLat: [lngLat.lng, lngLat.lat] as LngLat,
114
+ originalLngLat,
115
+ });
116
+ }
117
+ });
118
+
119
+ newMarker.on('dragend', () => {
120
+ if (onDragEnd) {
121
+ const lngLat = newMarker.getLngLat();
122
+ onDragEnd({
123
+ type: 'dragend',
124
+ markerId: id || '',
125
+ lngLat: [lngLat.lng, lngLat.lat] as LngLat,
126
+ originalLngLat,
127
+ });
128
+ }
129
+ });
130
130
  });
131
131
 
132
132
  // Handle click handler - separate effect to properly update when onClick prop changes
@@ -188,6 +188,13 @@
188
188
  }
189
189
  });
190
190
 
191
+ // Update offset (matches maps-react: an unset offset keeps MapLibre's default)
192
+ $effect(() => {
193
+ if (marker && offset) {
194
+ marker.setOffset(offset as maplibregl.PointLike);
195
+ }
196
+ });
197
+
191
198
  // Move rendered children content into markerElement for MapLibre
192
199
  $effect(() => {
193
200
  if (contentRef && markerElement && children) {
@@ -108,6 +108,64 @@
108
108
  // Track style version for re-initialization after basemap changes
109
109
  let lastKnownStyleVersion = -1;
110
110
 
111
+ // The id and configuration of the source this component put on the map.
112
+ // MapLibre cannot change a source's id, type, tiles or cluster options in
113
+ // place, so a change to any of them replaces the source.
114
+ let addedSourceId: string | null = null;
115
+ let addedConfigKey: string | null = null;
116
+
117
+ /** Every prop that shapes the source, except `data` (updated via setData) */
118
+ function getConfigKey(): string {
119
+ return JSON.stringify([
120
+ id,
121
+ type,
122
+ url ?? null,
123
+ tiles ?? null,
124
+ tileSize ?? null,
125
+ minzoom ?? null,
126
+ maxzoom ?? null,
127
+ attribution ?? null,
128
+ bounds ?? null,
129
+ scheme ?? null,
130
+ promoteId ?? null,
131
+ generateId ?? null,
132
+ cluster ?? null,
133
+ clusterRadius ?? null,
134
+ clusterMaxZoom ?? null,
135
+ clusterMinPoints ?? null,
136
+ clusterProperties ?? null,
137
+ lineMetrics ?? null,
138
+ tolerance ?? null,
139
+ buffer ?? null,
140
+ ]);
141
+ }
142
+
143
+ type LayerSnapshot = { spec: maplibregl.LayerSpecification; beforeId?: string };
144
+
145
+ /**
146
+ * Remove a source and the layers drawn from it. Returns those layers with
147
+ * the layer each sat below, so they can be put back on a replacement.
148
+ */
149
+ function removeSourceAndLayers(map: maplibregl.Map, sourceId: string): LayerSnapshot[] {
150
+ const removed: LayerSnapshot[] = [];
151
+ try {
152
+ const styleLayers = map.getStyle()?.layers ?? [];
153
+ const uses = (layer: maplibregl.LayerSpecification) =>
154
+ 'source' in layer && layer.source === sourceId;
155
+ styleLayers.forEach((layer, index) => {
156
+ if (!uses(layer)) return;
157
+ // The next layer that stays on the map keeps the original order
158
+ const below = styleLayers.slice(index + 1).find((l) => !uses(l));
159
+ removed.push({ spec: layer, beforeId: below?.id });
160
+ if (map.getLayer(layer.id)) map.removeLayer(layer.id);
161
+ });
162
+ if (map.getSource(sourceId)) map.removeSource(sourceId);
163
+ } catch {
164
+ // Ignore cleanup errors
165
+ }
166
+ return removed;
167
+ }
168
+
111
169
  $effect(() => {
112
170
  const sv = mapContext.styleVersion ?? 0;
113
171
  if (lastKnownStyleVersion === -1) {
@@ -124,9 +182,27 @@
124
182
  // Add source effect
125
183
  $effect(() => {
126
184
  const { map, loaded } = mapContext;
185
+ const configKey = getConfigKey();
186
+
187
+ if (!map || !loaded) return;
188
+
189
+ // A changed configuration replaces the source. Its layers are put back on
190
+ // the new one, since their hooks still consider them added; on an id
191
+ // change they stay off, and layers re-pointed at the new id add themselves.
192
+ let layersToRestore: LayerSnapshot[] = [];
193
+ if (sourceAdded && addedSourceId !== null && addedConfigKey !== configKey) {
194
+ const removed = removeSourceAndLayers(map, addedSourceId);
195
+ if (addedSourceId === id) layersToRestore = removed;
196
+ addedSourceId = null;
197
+ addedConfigKey = null;
198
+ lastDataFingerprint = null;
199
+ sourceAdded = false;
200
+ }
127
201
 
128
- if (!map || !loaded || sourceAdded) return;
202
+ if (sourceAdded) return;
129
203
  if (map.getSource(id)) {
204
+ addedSourceId = id;
205
+ addedConfigKey = configKey;
130
206
  sourceAdded = true;
131
207
  return;
132
208
  }
@@ -164,6 +240,9 @@
164
240
  if (attribution !== undefined) sourceConfig.attribution = attribution;
165
241
 
166
242
  map.addSource(id, sourceConfig);
243
+ // The source now holds `data`; record it so the data effect does not
244
+ // immediately re-send the same dataset (a full worker re-parse)
245
+ lastDataFingerprint = data ? createGeoJSONFingerprint(data) : null;
167
246
  } else if (type === 'vector') {
168
247
  const sourceConfig: maplibregl.VectorSourceSpecification = {
169
248
  type: 'vector',
@@ -194,9 +273,38 @@
194
273
  if (scheme !== undefined) sourceConfig.scheme = scheme;
195
274
 
196
275
  map.addSource(id, sourceConfig);
276
+ } else if (type === 'raster-dem') {
277
+ const sourceConfig: maplibregl.RasterDEMSourceSpecification = {
278
+ type: 'raster-dem',
279
+ };
280
+
281
+ if (url) sourceConfig.url = url;
282
+ if (tiles) sourceConfig.tiles = tiles;
283
+ if (tileSize !== undefined) sourceConfig.tileSize = tileSize;
284
+ if (minzoom !== undefined) sourceConfig.minzoom = minzoom;
285
+ if (maxzoom !== undefined) sourceConfig.maxzoom = maxzoom;
286
+ if (attribution !== undefined) sourceConfig.attribution = attribution;
287
+ if (bounds !== undefined) sourceConfig.bounds = bounds as [number, number, number, number];
288
+
289
+ map.addSource(id, sourceConfig);
290
+ } else {
291
+ // Nothing was added: do not report the source as ready, or dependent
292
+ // layers would wait on it forever without a clue why
293
+ console.warn(`[maps-svelte] Source "${id}": type "${type}" is not supported.`);
294
+ return;
197
295
  }
198
296
 
297
+ addedSourceId = id;
298
+ addedConfigKey = configKey;
199
299
  sourceAdded = true;
300
+
301
+ for (const { spec, beforeId } of layersToRestore) {
302
+ try {
303
+ map.addLayer(spec, beforeId && map.getLayer(beforeId) ? beforeId : undefined);
304
+ } catch (err) {
305
+ console.error(`[maps-svelte] Failed to restore layer "${spec.id}" on "${id}":`, err);
306
+ }
307
+ }
200
308
  } catch (err) {
201
309
  console.error(`[maps-svelte] Failed to add source "${id}":`, err);
202
310
  }
@@ -315,24 +423,9 @@
315
423
 
316
424
  const { map } = mapContext;
317
425
 
318
- if (map && sourceAdded) {
319
- try {
320
- // Remove all layers using this source first
321
- const style = map.getStyle();
322
- if (style?.layers) {
323
- style.layers.forEach((layer) => {
324
- if ('source' in layer && layer.source === id) {
325
- map.removeLayer(layer.id);
326
- }
327
- });
328
- }
329
-
330
- if (map.getSource(id)) {
331
- map.removeSource(id);
332
- }
333
- } catch (err) {
334
- // Ignore cleanup errors
335
- }
426
+ // The id this component added, which can trail the prop by one update
427
+ if (map && sourceAdded && addedSourceId !== null) {
428
+ removeSourceAndLayers(map, addedSourceId);
336
429
  }
337
430
  });
338
431
  </script>
@@ -56,18 +56,24 @@
56
56
  let overlayRef = $state<maplibregl.IControl | null>(null);
57
57
  let MapboxOverlayClass = $state<MapboxOverlayClass | null>(null);
58
58
  let initialized = $state(false);
59
+ // Plain (non-reactive) guards for the async import below
60
+ let initializing = false;
61
+ let destroyed = false;
59
62
 
60
63
  // Initialize Deck.gl overlay
61
64
  $effect(() => {
62
65
  const { map, loaded } = mapContext;
63
66
 
64
- if (!map || !loaded || initialized) return;
67
+ if (!map || !loaded || initialized || initializing) return;
68
+ initializing = true;
65
69
 
66
70
  const initOverlay = async () => {
67
71
  try {
68
72
  // Dynamic import to make Deck.gl optional
69
- // @ts-ignore - deck.gl types are optional peer dependencies
70
73
  const deckMapbox = await import('@deck.gl/mapbox');
74
+ // Destroyed while the chunk loaded: onDestroy has already run, so an
75
+ // overlay added now would never be removed
76
+ if (destroyed) return;
71
77
  MapboxOverlayClass = deckMapbox.MapboxOverlay as unknown as MapboxOverlayClass;
72
78
 
73
79
  const overlay = new MapboxOverlayClass({
@@ -85,6 +91,7 @@
85
91
  overlayRef = overlay;
86
92
  initialized = true;
87
93
  } catch (err) {
94
+ initializing = false;
88
95
  console.warn(
89
96
  '[maps-svelte] Deck.gl is not available. Install @deck.gl/core, @deck.gl/layers, and @deck.gl/mapbox to use DeckOverlay.',
90
97
  err
@@ -122,6 +129,7 @@
122
129
 
123
130
  // Cleanup on destroy
124
131
  onDestroy(() => {
132
+ destroyed = true;
125
133
  const { map } = mapContext;
126
134
 
127
135
  if (overlayRef && map) {
@@ -1,5 +1,5 @@
1
1
  export { MapContainer, MapSkeleton, MapError, MapEmpty } from './base/index.js';
2
2
  export { Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter, } from './core/index.js';
3
- export { FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './layers/index.js';
3
+ export { FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, useLayer, type UseLayerOptions, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './layers/index.js';
4
4
  export { DeckOverlay } from './deck/index.js';
5
5
  export { Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher, LayerManager, CustomControl, type CustomControlProps, } from './controls/index.js';
@@ -3,7 +3,7 @@ export { MapContainer, MapSkeleton, MapError, MapEmpty } from './base/index.js';
3
3
  // Core components
4
4
  export { Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter, } from './core/index.js';
5
5
  // Layer components
6
- export { FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, } from './layers/index.js';
6
+ export { FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, useLayer, } from './layers/index.js';
7
7
  // Deck.gl components
8
8
  export { DeckOverlay } from './deck/index.js';
9
9
  // Control components
@@ -4,4 +4,5 @@ export { default as CircleLayer } from './CircleLayer.svelte';
4
4
  export { default as SymbolLayer } from './SymbolLayer.svelte';
5
5
  export { default as FillExtrusionLayer } from './FillExtrusionLayer.svelte';
6
6
  export { default as HeatmapLayer } from './HeatmapLayer.svelte';
7
- export type { SvelteFeatureClickEventParams, SvelteFeatureHoverEventParams, } from './useLayer.svelte.js';
7
+ export { useLayer } from './useLayer.svelte.js';
8
+ export type { UseLayerOptions, SvelteFeatureClickEventParams, SvelteFeatureHoverEventParams, } from './useLayer.svelte.js';
@@ -4,3 +4,4 @@ export { default as CircleLayer } from './CircleLayer.svelte';
4
4
  export { default as SymbolLayer } from './SymbolLayer.svelte';
5
5
  export { default as FillExtrusionLayer } from './FillExtrusionLayer.svelte';
6
6
  export { default as HeatmapLayer } from './HeatmapLayer.svelte';
7
+ export { useLayer } from './useLayer.svelte.js';
@@ -10,12 +10,16 @@ export function useLayer(getOptions) {
10
10
  let sourceDataHandler = null;
11
11
  let lastHoverCallTime = 0;
12
12
  let lastMousePosition = null;
13
- // Store event handler references for cleanup
14
- let eventHandlerCleanup = null;
13
+ // The layer this hook put on the map (or adopted), and the structural options
14
+ // it was built from. Plain variables: they are bookkeeping, not reactive state.
15
+ let addedLayerId = null;
16
+ let addedLayerKey = null;
15
17
  // Track last applied values to prevent redundant MapLibre API calls
16
18
  let lastAppliedVisible = undefined;
17
19
  let lastAppliedPaint = undefined;
18
20
  let lastAppliedFilterSerialized = '';
21
+ let lastAppliedLayout = undefined;
22
+ let lastAppliedZoomRange = undefined;
19
23
  // Track style version for re-initialization after basemap changes
20
24
  let lastKnownStyleVersion = -1;
21
25
  $effect(() => {
@@ -26,18 +30,35 @@ export function useLayer(getOptions) {
26
30
  }
27
31
  if (sv !== lastKnownStyleVersion) {
28
32
  lastKnownStyleVersion = sv;
29
- // Clean up old event handlers before re-initializing
30
- if (eventHandlerCleanup) {
31
- eventHandlerCleanup();
32
- eventHandlerCleanup = null;
33
- }
33
+ // Re-initialize: the handler effect drops its handlers when layerAdded
34
+ // goes false and re-attaches once the add effect sets it again
34
35
  layerAdded = false;
35
- hoveredFeatureId = null;
36
- lastAppliedVisible = undefined;
37
- lastAppliedPaint = undefined;
38
- lastAppliedFilterSerialized = '';
36
+ resetAppliedState();
39
37
  }
40
38
  });
39
+ function resetAppliedState() {
40
+ hoveredFeatureId = null;
41
+ lastAppliedVisible = undefined;
42
+ lastAppliedPaint = undefined;
43
+ lastAppliedFilterSerialized = '';
44
+ lastAppliedLayout = undefined;
45
+ lastAppliedZoomRange = undefined;
46
+ }
47
+ /** Remove the layer this hook added, if it is still on the map */
48
+ function removeAddedLayer(map) {
49
+ if (addedLayerId === null)
50
+ return;
51
+ try {
52
+ if (map.getLayer(addedLayerId)) {
53
+ map.removeLayer(addedLayerId);
54
+ }
55
+ }
56
+ catch {
57
+ // Ignore cleanup errors
58
+ }
59
+ addedLayerId = null;
60
+ addedLayerKey = null;
61
+ }
41
62
  const createFeatureParams = (e, options, map) => {
42
63
  const feature = e.features?.[0];
43
64
  if (!feature)
@@ -59,7 +80,17 @@ export function useLayer(getOptions) {
59
80
  const { map, loaded } = mapContext;
60
81
  if (!map || !loaded)
61
82
  return;
62
- const { id, source, sourceLayer, type, visible = true, minZoom, maxZoom, filter, beforeId, paint = {}, layout = {}, onClick, onHover, } = options;
83
+ const { id, source, sourceLayer, type, visible = true, minZoom, maxZoom, filter, beforeId, paint = {}, layout = {}, } = options;
84
+ // id, source, sourceLayer, type and beforeId cannot be changed in place:
85
+ // when one changes, the old layer comes off and a new one is added. Without
86
+ // this, an id change left the old layer on the map for good (unmount only
87
+ // removed the current id) and a new source or beforeId was ignored.
88
+ const layerKey = JSON.stringify([id, source, sourceLayer ?? null, type, beforeId ?? null]);
89
+ if (addedLayerKey !== null && addedLayerKey !== layerKey) {
90
+ removeAddedLayer(map);
91
+ layerAdded = false;
92
+ resetAppliedState();
93
+ }
63
94
  // Check if source is available
64
95
  if (!map.getSource(source)) {
65
96
  let timeoutId = null;
@@ -97,15 +128,12 @@ export function useLayer(getOptions) {
97
128
  addLayer();
98
129
  function addLayer() {
99
130
  if (layerAdded || map.getLayer(id)) {
131
+ // Already on the map: a styleVersion bump can land after the layer
132
+ // survived the style swap, or a second bump after the first re-added
133
+ // it. Adopt it; setting layerAdded re-attaches the handlers.
134
+ addedLayerId = id;
135
+ addedLayerKey = layerKey;
100
136
  layerAdded = true;
101
- // The layer is on the map but this hook may not own its events: a
102
- // styleVersion bump drops the handlers and marks the layer as not added,
103
- // and if the layer survived (or a second bump lands after the first one
104
- // re-added it) this branch is the only path back. Without the re-attach,
105
- // the layer renders but every onClick/onHover is silently dead.
106
- if (!eventHandlerCleanup) {
107
- eventHandlerCleanup = setupEventHandlers(map, id, source, sourceLayer, onClick, onHover);
108
- }
109
137
  return;
110
138
  }
111
139
  try {
@@ -132,15 +160,29 @@ export function useLayer(getOptions) {
132
160
  layerConfig.filter = filter;
133
161
  }
134
162
  map.addLayer(layerConfig, beforeId);
163
+ addedLayerId = id;
164
+ addedLayerKey = layerKey;
135
165
  layerAdded = true;
136
- // Set up event handlers and store cleanup function
137
- eventHandlerCleanup = setupEventHandlers(map, id, source, sourceLayer, onClick, onHover);
138
166
  }
139
167
  catch (err) {
140
168
  console.error(`[maps-svelte] Failed to add layer "${id}":`, err);
141
169
  }
142
170
  }
143
171
  });
172
+ // Event handlers. Their own effect, so an onClick/onHover passed (or changed)
173
+ // after the layer was added is wired up too; they used to be bound once, in
174
+ // the add path. The deriveds keep paint or filter updates from re-binding.
175
+ const handlerLayerId = $derived(getOptions().id);
176
+ const handlerSource = $derived(getOptions().source);
177
+ const handlerSourceLayer = $derived(getOptions().sourceLayer);
178
+ const handlerOnClick = $derived(getOptions().onClick);
179
+ const handlerOnHover = $derived(getOptions().onHover);
180
+ $effect(() => {
181
+ const { map } = mapContext;
182
+ if (!map || !layerAdded)
183
+ return;
184
+ return setupEventHandlers(map, handlerLayerId, handlerSource, handlerSourceLayer, handlerOnClick, handlerOnHover);
185
+ });
144
186
  // Update visibility (only when changed)
145
187
  $effect(() => {
146
188
  const options = getOptions();
@@ -205,6 +247,50 @@ export function useLayer(getOptions) {
205
247
  // Layer might not exist yet
206
248
  }
207
249
  });
250
+ // Update layout properties (except visibility, handled above; only changed
251
+ // properties). The add effect only applies layout once.
252
+ $effect(() => {
253
+ const options = getOptions();
254
+ const { map, loaded } = mapContext;
255
+ if (!map || !loaded || !layerAdded)
256
+ return;
257
+ const next = { ...(options.layout ?? {}) };
258
+ delete next.visibility;
259
+ const diff = getChangedPaintProps(lastAppliedLayout, next);
260
+ if (!diff.hasChanges)
261
+ return;
262
+ try {
263
+ for (const [key, value] of Object.entries(diff.changed)) {
264
+ map.setLayoutProperty(options.id, key, value);
265
+ }
266
+ for (const key of diff.removed) {
267
+ map.setLayoutProperty(options.id, key, undefined);
268
+ }
269
+ lastAppliedLayout = next;
270
+ }
271
+ catch {
272
+ // Layer might not exist yet
273
+ }
274
+ });
275
+ // Update zoom range (only when changed)
276
+ $effect(() => {
277
+ const options = getOptions();
278
+ const { map, loaded } = mapContext;
279
+ if (!map || !loaded || !layerAdded)
280
+ return;
281
+ const minZoom = options.minZoom ?? 0;
282
+ const maxZoom = options.maxZoom ?? 24;
283
+ const key = `${minZoom}:${maxZoom}`;
284
+ if (lastAppliedZoomRange === key)
285
+ return;
286
+ try {
287
+ map.setLayerZoomRange(options.id, minZoom, maxZoom);
288
+ lastAppliedZoomRange = key;
289
+ }
290
+ catch {
291
+ // Layer might not exist yet
292
+ }
293
+ });
208
294
  function setupEventHandlers(map, id, source, sourceLayer, onClick, onHover) {
209
295
  // Click handler
210
296
  const handleClick = (e) => {
@@ -331,28 +417,16 @@ export function useLayer(getOptions) {
331
417
  }
332
418
  };
333
419
  }
334
- // Cleanup on destroy
420
+ // Cleanup on destroy (the handler effect detaches its handlers itself)
335
421
  onDestroy(() => {
336
422
  const { map } = mapContext;
337
- const options = getOptions();
338
- // Remove event handlers first (before removing the layer)
339
- if (eventHandlerCleanup) {
340
- eventHandlerCleanup();
341
- eventHandlerCleanup = null;
342
- }
343
423
  if (sourceDataHandler && map) {
344
424
  map.off('sourcedata', sourceDataHandler);
345
425
  }
346
- if (map && layerAdded) {
347
- try {
348
- if (map.getLayer(options.id)) {
349
- map.removeLayer(options.id);
350
- }
351
- }
352
- catch {
353
- // Ignore cleanup errors
354
- }
355
- }
426
+ // The id this hook added, not the current prop: they differ when the add
427
+ // effect has not yet re-run after an id change
428
+ if (map)
429
+ removeAddedLayer(map);
356
430
  });
357
431
  return {
358
432
  get layerAdded() {
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Svelte MapLibre components for the Classic Theme design system
5
5
  */
6
- export { MapContainer, MapSkeleton, MapError, MapEmpty, Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter, FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher, LayerManager, CustomControl, type CustomControlProps, DeckOverlay, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './components/index.js';
6
+ export { MapContainer, MapSkeleton, MapError, MapEmpty, Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter, useLayer, type UseLayerOptions, FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher, LayerManager, CustomControl, type CustomControlProps, DeckOverlay, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './components/index.js';
7
7
  export { useMapTheme, useReducedMotion, useMapContext, tryUseMapContext, useMapInstance, useControlPosition, type MapContextValue, type UseControlPositionOptions, type UseControlPositionResult, } from './composables/index.js';
8
8
  export { cn } from './utils.js';
9
- export type { LngLat, MapBounds, BoundsArray, MapViewport, GeoJSONFeature, GeoJSONFeatureCollection, MarkerData, MapClickEventParams, MapHoverEventParams, FeatureClickEventParams, FeatureHoverEventParams, MarkerClickEventParams, MapMoveEventParams, BaseMapProps, MapProps, SourceProps, FillLayerProps, LineLayerProps, CircleLayerProps, SymbolLayerProps, FillExtrusionLayerProps, HeatmapLayerProps, MarkerProps, PopupProps, LegendItem, GradientStop, LegendProps, CoordinateDisplayProps, LegendConfig, LegendGroupProps, BasemapProvider, BasemapCategory, BasemapDefinition, BasemapApiKeys, BasemapSwitcherProps, OverlayLayerCategory, OverlayLayerDefinition, OverlayLayerState, OverlayApiKeys, LayerManagerProps, ExtendedControlPosition, ControlPriority, ZIndexLayer, ControlType, ControlOffset, } from '@classic-homes/maps-core';
9
+ export type { LngLat, MapBounds, BoundsArray, MapViewport, GeoJSONFeature, GeoJSONFeatureCollection, MarkerData, MapClickEventParams, MapHoverEventParams, FeatureClickEventParams, FeatureHoverEventParams, MarkerClickEventParams, MarkerDragEventParams, MapMoveEventParams, BaseMapProps, MapProps, SourceProps, FillLayerProps, LineLayerProps, CircleLayerProps, SymbolLayerProps, FillExtrusionLayerProps, HeatmapLayerProps, MarkerProps, PopupProps, LegendItem, GradientStop, LegendProps, CoordinateDisplayProps, LegendConfig, LegendGroupProps, BasemapProvider, BasemapCategory, BasemapDefinition, BasemapApiKeys, BasemapSwitcherProps, OverlayLayerCategory, OverlayLayerDefinition, OverlayLayerState, OverlayApiKeys, LayerManagerProps, ExtendedControlPosition, ControlPriority, ZIndexLayer, ControlType, ControlOffset, } from '@classic-homes/maps-core';
10
10
  export { CATEGORY_META, SCHOOL_DISTRICTS, CITY_LIMITS, ZONING_DISTRICTS, PARKS, TRAILS, SPORTS_FACILITIES, TRANSIT_ROUTES, BIKE_LANES, FLOOD_ZONES, WATERSHEDS, BUILTIN_OVERLAY_LAYERS, resolveLayerSourceUrl, getLayerStyleForTheme, searchLayers, getLayersByCategory, groupLayersByCategory, getLayerCategories, createInitialLayerStates, toggleLayerVisibility, setLayerOpacity, } from '@classic-homes/maps-core';
11
11
  export { THEME_LIGHT, THEME_DARK, lightTheme, darkTheme, lightBasicStyle, darkBasicStyle, generateMapDescription, formatCoordinates, formatDistance, formatArea, createHoverExpression, createSelectionExpression, getHighlightStyle, getSelectionStyle, calculateBounds, extendBounds, combineBounds, isValidBounds, loadGeoJSON, validateGeoJSON, calculateCentroid, countFeaturesByType, filterByGeometryType, DEFAULT_BASEMAP, SATELLITE_BASEMAP, TOPO_BASEMAP, PRIMARY_BASEMAPS, BUILTIN_BASEMAPS, FREE_BASEMAPS, OSM_STANDARD, resolveBasemapStyle, getAvailableBasemaps, } from '@classic-homes/maps-core';
12
12
  export type { LoadGeoJSONOptions, LoadGeoJSONResult, ValidationResult, ClusterFeatureProperties, ClusterExpandOptions, } from '@classic-homes/maps-core';
package/dist/lib/index.js CHANGED
@@ -10,7 +10,7 @@ MapContainer, MapSkeleton, MapError, MapEmpty,
10
10
  // Core
11
11
  Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter,
12
12
  // Layers
13
- FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer,
13
+ useLayer, FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer,
14
14
  // Controls
15
15
  Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher, LayerManager, CustomControl,
16
16
  // Deck.gl
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/maps-svelte",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Svelte MapLibre components for Classic Theme",
5
5
  "keywords": [
6
6
  "maps",
@@ -67,10 +67,12 @@
67
67
  "@deck.gl/mapbox": "^9.0.0",
68
68
  "@sveltejs/package": "^2.3.0",
69
69
  "@sveltejs/vite-plugin-svelte": "^7.0.0",
70
+ "jsdom": "^28.1.0",
70
71
  "maplibre-gl": "^5.0.0",
71
72
  "svelte": "^5.0.0",
72
73
  "svelte-check": "^4.0.0",
73
- "typescript": "^5.3.0"
74
+ "typescript": "^5.3.0",
75
+ "vitest": "^4.1.10"
74
76
  },
75
77
  "publishConfig": {
76
78
  "access": "public"