@classic-homes/maps-svelte 0.2.7 → 0.2.8

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.
@@ -25,6 +25,7 @@
25
25
  defaultBasemapId,
26
26
  activeBasemapId,
27
27
  onBasemapChange,
28
+ onStyleError,
28
29
  columns = 3,
29
30
  thumbnailSize = 64,
30
31
  position = 'bottom-right',
@@ -38,15 +39,18 @@
38
39
  let internalActiveId = $state<string | undefined>(undefined);
39
40
  let containerElement: HTMLDivElement;
40
41
 
41
- // Use positioning coordinator
42
- const controlPosition = useControlPosition(() => containerElement, {
43
- id: switcherId,
44
- type: 'basemap-switcher',
45
- position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
46
- priority: 'normal',
47
- zLayer: 'interactive',
48
- hasExpandedState: true,
49
- });
42
+ // Use positioning coordinator with getter for reactive position updates
43
+ const controlPosition = useControlPosition(
44
+ () => containerElement,
45
+ () => ({
46
+ id: switcherId,
47
+ type: 'basemap-switcher',
48
+ position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
49
+ priority: 'normal',
50
+ zLayer: 'interactive',
51
+ hasExpandedState: true,
52
+ })
53
+ );
50
54
 
51
55
  // Initialize with defaultBasemapId (reactive to prop changes)
52
56
  $effect(() => {
@@ -107,7 +111,14 @@
107
111
 
108
112
  function handleSelect(basemap: BasemapDefinition) {
109
113
  const resolvedStyle = resolveBasemapStyle(basemap, apiKeys);
110
- if (!resolvedStyle) return;
114
+ if (!resolvedStyle) {
115
+ const reason = basemap.requiresApiKey
116
+ ? `Basemap "${basemap.name}" requires an API key that was not provided`
117
+ : `Failed to resolve style for basemap "${basemap.name}"`;
118
+ console.warn(`[maps-svelte] BasemapSwitcher: ${reason}`);
119
+ onStyleError?.({ basemap, reason });
120
+ return;
121
+ }
111
122
 
112
123
  if (!activeBasemapId) {
113
124
  internalActiveId = basemap.id;
@@ -39,13 +39,17 @@
39
39
  let controlElement: HTMLDivElement;
40
40
 
41
41
  // Use positioning coordinator with 'critical' priority to be at the edge
42
- const controlPosition = useControlPosition(() => controlElement, {
43
- id: controlId,
44
- type: 'coordinate-display',
45
- position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
46
- priority: 'critical',
47
- zLayer: 'base',
48
- });
42
+ // Use getter for reactive position updates
43
+ const controlPosition = useControlPosition(
44
+ () => controlElement,
45
+ () => ({
46
+ id: controlId,
47
+ type: 'coordinate-display',
48
+ position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
49
+ priority: 'critical',
50
+ zLayer: 'base',
51
+ })
52
+ );
49
53
 
50
54
  // Adjust style based on position
51
55
  const ATTRIBUTION_HEIGHT = 32;
@@ -47,18 +47,24 @@
47
47
  children,
48
48
  }: Props = $props();
49
49
 
50
+ // Generate stable ID at mount time
51
+ // svelte-ignore state_referenced_locally
50
52
  const controlId = id ?? `custom-control-${Math.random().toString(36).slice(2, 9)}`;
51
53
  let controlElement: HTMLDivElement;
52
54
 
53
- const controlPosition = useControlPosition(() => controlElement, {
54
- id: controlId,
55
- type: 'custom',
56
- position,
57
- fallbacks,
58
- priority,
59
- zLayer,
60
- hasExpandedState,
61
- });
55
+ // Use positioning coordinator with getter for reactive position updates
56
+ const controlPosition = useControlPosition(
57
+ () => controlElement,
58
+ () => ({
59
+ id: controlId,
60
+ type: 'custom',
61
+ position,
62
+ fallbacks,
63
+ priority,
64
+ zLayer,
65
+ hasExpandedState,
66
+ })
67
+ );
62
68
 
63
69
  const mergedStyle = $derived(
64
70
  userStyle ? `${controlPosition.style}; ${userStyle}` : controlPosition.style
@@ -49,6 +49,7 @@
49
49
  let isOpen = $state(false);
50
50
 
51
51
  // Capture initialActiveLayers at mount time (non-reactive)
52
+ // svelte-ignore state_referenced_locally
52
53
  const initialActiveLayersSet = new Set(initialActiveLayers ?? []);
53
54
 
54
55
  // Store layer states as stable $state - NOT derived
@@ -125,15 +126,18 @@
125
126
  let dragOver = $state<{ id: string; position: 'above' | 'below' } | null>(null);
126
127
  let containerElement: HTMLDivElement;
127
128
 
128
- // Use positioning coordinator
129
- const controlPosition = useControlPosition(() => containerElement, {
130
- id: managerId,
131
- type: 'layer-manager',
132
- position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
133
- priority: 'high',
134
- zLayer: 'interactive',
135
- hasExpandedState: true,
136
- });
129
+ // Use positioning coordinator with getter for reactive position updates
130
+ const controlPosition = useControlPosition(
131
+ () => containerElement,
132
+ () => ({
133
+ id: managerId,
134
+ type: 'layer-manager',
135
+ position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
136
+ priority: 'high',
137
+ zLayer: 'interactive',
138
+ hasExpandedState: true,
139
+ })
140
+ );
137
141
 
138
142
  // Track style version for re-initialization after basemap changes
139
143
  let lastKnownStyleVersion = -1;
@@ -27,15 +27,18 @@
27
27
  let localCollapsed = $state(false);
28
28
  let legendElement: HTMLDivElement;
29
29
 
30
- // Use positioning coordinator
31
- const controlPosition = useControlPosition(() => legendElement, {
32
- id: legendId,
33
- type: 'legend',
34
- position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
35
- priority: 'normal',
36
- zLayer: 'interactive',
37
- hasExpandedState: collapsible,
38
- });
30
+ // Use positioning coordinator with getter for reactive position updates
31
+ const controlPosition = useControlPosition(
32
+ () => legendElement,
33
+ () => ({
34
+ id: legendId,
35
+ type: 'legend',
36
+ position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
37
+ priority: 'normal',
38
+ zLayer: 'interactive',
39
+ hasExpandedState: collapsible,
40
+ })
41
+ );
39
42
 
40
43
  // Determine effective collapsed state - user toggle takes precedence
41
44
  const isCollapsed = $derived(userToggled ? localCollapsed : collapsed);
@@ -28,15 +28,18 @@
28
28
  let internalExpanded = $state<string | null>(getInitialExpanded());
29
29
  let containerElement: HTMLDivElement;
30
30
 
31
- // Use positioning coordinator
32
- const controlPosition = useControlPosition(() => containerElement, {
33
- id: groupId,
34
- type: 'legend-group',
35
- position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
36
- priority: 'normal',
37
- zLayer: 'interactive',
38
- hasExpandedState: true,
39
- });
31
+ // Use positioning coordinator with getter for reactive position updates
32
+ const controlPosition = useControlPosition(
33
+ () => containerElement,
34
+ () => ({
35
+ id: groupId,
36
+ type: 'legend-group',
37
+ position: position as 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right',
38
+ priority: 'normal',
39
+ zLayer: 'interactive',
40
+ hasExpandedState: true,
41
+ })
42
+ );
40
43
 
41
44
  // Use controlled or internal state
42
45
  const expandedId = $derived(
@@ -91,13 +91,23 @@
91
91
  let mapError = $state<string | null>(null);
92
92
  let styleVersion = $state(0);
93
93
  let activeStyleOverride: string | maplibregl.StyleSpecification | null = $state(null);
94
+ let styleLoadHandler: (() => void) | null = null;
95
+ let initTimeoutId: ReturnType<typeof setTimeout> | null = null;
94
96
 
95
97
  // Create positioning coordinator instance
96
98
  const positioningCoordinator: PositioningCoordinator = createPositioningCoordinator();
97
99
 
98
100
  function setMapStyle(style: string | maplibregl.StyleSpecification) {
99
101
  activeStyleOverride = style;
100
- map?.setStyle(style);
102
+ if (map) {
103
+ map.setStyle(style);
104
+ // style.load doesn't reliably fire after setStyle() in newer MapLibre versions,
105
+ // so we manually trigger a style version bump after the map becomes idle
106
+ // See: https://github.com/maplibre/maplibre-gl-js/discussions/2716
107
+ map.once('idle', () => {
108
+ styleVersion++;
109
+ });
110
+ }
101
111
  }
102
112
 
103
113
  const reducedMotion = useReducedMotion();
@@ -159,14 +169,23 @@
159
169
  map = newMap;
160
170
 
161
171
  // Track style changes for layer re-initialization
162
- // Note: Using 'data' event with dataType check instead of 'style.load'
163
- // because style.load doesn't reliably fire after setStyle() in newer MapLibre versions
164
- // See: https://github.com/maplibre/maplibre-gl-js/discussions/2716
165
- newMap.on('data', (e) => {
166
- if (e.dataType === 'style') {
167
- styleVersion++;
172
+ styleLoadHandler = () => {
173
+ styleVersion++;
174
+ };
175
+ newMap.on('style.load', styleLoadHandler);
176
+
177
+ // Map initialization timeout (30 seconds)
178
+ initTimeoutId = setTimeout(() => {
179
+ if (!map?.loaded()) {
180
+ const errorMessage = 'Map initialization timeout - style may be unreachable';
181
+ mapError = errorMessage;
182
+ onError?.({
183
+ type: 'error',
184
+ message: errorMessage,
185
+ error: new Error(errorMessage),
186
+ });
168
187
  }
169
- });
188
+ }, 30000);
170
189
 
171
190
  // Add controls and register with positioning coordinator
172
191
  if (navigationControl) {
@@ -264,6 +283,10 @@
264
283
 
265
284
  // Map load handler
266
285
  newMap.on('load', () => {
286
+ if (initTimeoutId) {
287
+ clearTimeout(initTimeoutId);
288
+ initTimeoutId = null;
289
+ }
267
290
  mapLoaded = true;
268
291
 
269
292
  if (bounds) {
@@ -279,6 +302,10 @@
279
302
  // Error handler
280
303
  newMap.on('error', (e) => {
281
304
  const errorMessage = e.error?.message || 'Map error';
305
+ if (initTimeoutId) {
306
+ clearTimeout(initTimeoutId);
307
+ initTimeoutId = null;
308
+ }
282
309
  mapError = errorMessage;
283
310
  onError?.({ type: 'error', message: errorMessage, error: e.error });
284
311
  });
@@ -447,6 +474,16 @@
447
474
  });
448
475
 
449
476
  onDestroy(() => {
477
+ // Clear initialization timeout
478
+ if (initTimeoutId) {
479
+ clearTimeout(initTimeoutId);
480
+ initTimeoutId = null;
481
+ }
482
+ // Remove style.load listener before destroying map
483
+ if (map && styleLoadHandler) {
484
+ map.off('style.load', styleLoadHandler);
485
+ styleLoadHandler = null;
486
+ }
450
487
  if (map) {
451
488
  map.remove();
452
489
  map = null;
@@ -8,6 +8,7 @@
8
8
  applyMarkerChildProtection,
9
9
  removeMarkerProtection,
10
10
  } from '@classic-homes/maps-core';
11
+ import type { MapContextValue } from '../../composables/useMapContext.svelte';
11
12
 
12
13
  type Anchor =
13
14
  | 'center'
@@ -20,11 +21,6 @@
20
21
  | 'bottom-left'
21
22
  | 'bottom-right';
22
23
 
23
- interface MapContext {
24
- readonly map: maplibregl.Map | null;
25
- readonly loaded: boolean;
26
- }
27
-
28
24
  interface Props extends MarkerProps {
29
25
  /** Custom marker content */
30
26
  children?: Snippet;
@@ -45,7 +41,7 @@
45
41
  children,
46
42
  }: Props = $props();
47
43
 
48
- const mapContext = getContext<MapContext>('maplibre-map');
44
+ const mapContext = getContext<MapContextValue>('maplibre-map');
49
45
 
50
46
  let marker: maplibregl.Marker | null = $state(null);
51
47
  let markerElement: HTMLDivElement | null = $state(null);
@@ -100,22 +96,6 @@
100
96
 
101
97
  marker = newMarker;
102
98
 
103
- // Click handler
104
- if (onClick) {
105
- const element = newMarker.getElement();
106
- clickHandler = (e: MouseEvent) => {
107
- e.stopPropagation();
108
- const lngLat = newMarker.getLngLat();
109
- onClick({
110
- type: 'click',
111
- markerId: id || '',
112
- lngLat: [lngLat.lng, lngLat.lat] as LngLat,
113
- originalEvent: e,
114
- });
115
- };
116
- element.addEventListener('click', clickHandler);
117
- }
118
-
119
99
  // Drag handlers
120
100
  if (draggable) {
121
101
  newMarker.on('dragstart', () => {
@@ -149,6 +129,44 @@
149
129
  }
150
130
  });
151
131
 
132
+ // Handle click handler - separate effect to properly update when onClick prop changes
133
+ $effect(() => {
134
+ if (!marker) return;
135
+
136
+ const element = marker.getElement();
137
+ const currentMarker = marker;
138
+ const currentId = id;
139
+
140
+ // Clean up existing handler
141
+ if (clickHandler) {
142
+ element.removeEventListener('click', clickHandler);
143
+ clickHandler = null;
144
+ }
145
+
146
+ // Attach new handler if onClick exists
147
+ if (onClick) {
148
+ const currentOnClick = onClick;
149
+ clickHandler = (e: MouseEvent) => {
150
+ e.stopPropagation();
151
+ const lngLat = currentMarker.getLngLat();
152
+ currentOnClick({
153
+ type: 'click',
154
+ markerId: currentId || '',
155
+ lngLat: [lngLat.lng, lngLat.lat] as LngLat,
156
+ originalEvent: e,
157
+ });
158
+ };
159
+ element.addEventListener('click', clickHandler);
160
+ }
161
+
162
+ return () => {
163
+ if (clickHandler && currentMarker) {
164
+ currentMarker.getElement().removeEventListener('click', clickHandler);
165
+ clickHandler = null;
166
+ }
167
+ };
168
+ });
169
+
152
170
  // Update position when coordinates change
153
171
  $effect(() => {
154
172
  if (marker && coordinates) {
@@ -181,11 +199,6 @@
181
199
  // Cleanup on destroy
182
200
  onDestroy(() => {
183
201
  if (marker) {
184
- // Remove click handler to prevent memory leaks
185
- if (clickHandler) {
186
- marker.getElement().removeEventListener('click', clickHandler);
187
- clickHandler = null;
188
- }
189
202
  // Clean up marker protection observer
190
203
  removeMarkerProtection(marker.getElement());
191
204
  marker.remove();
@@ -11,12 +11,7 @@
11
11
  createGeoJSONFingerprint,
12
12
  fingerprintEqual,
13
13
  } from '@classic-homes/maps-core';
14
-
15
- interface MapContext {
16
- readonly map: maplibregl.Map | null;
17
- readonly loaded: boolean;
18
- readonly styleVersion: number;
19
- }
14
+ import type { MapContextValue } from '../../composables/useMapContext.svelte';
20
15
 
21
16
  /**
22
17
  * Source component props - extends MapLibre source specifications
@@ -102,7 +97,7 @@
102
97
  fitBoundsAnimate = true,
103
98
  }: Props = $props();
104
99
 
105
- const mapContext = getContext<MapContext>('maplibre-map');
100
+ const mapContext = getContext<MapContextValue>('maplibre-map');
106
101
  let sourceAdded = $state(false);
107
102
  let initialFitDone = $state(false);
108
103
 
@@ -10,6 +10,8 @@ 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
15
  // Track last applied values to prevent redundant MapLibre API calls
14
16
  let lastAppliedVisible = undefined;
15
17
  let lastAppliedPaint = undefined;
@@ -24,6 +26,11 @@ export function useLayer(getOptions) {
24
26
  }
25
27
  if (sv !== lastKnownStyleVersion) {
26
28
  lastKnownStyleVersion = sv;
29
+ // Clean up old event handlers before re-initializing
30
+ if (eventHandlerCleanup) {
31
+ eventHandlerCleanup();
32
+ eventHandlerCleanup = null;
33
+ }
27
34
  layerAdded = false;
28
35
  hoveredFeatureId = null;
29
36
  lastAppliedVisible = undefined;
@@ -110,8 +117,8 @@ export function useLayer(getOptions) {
110
117
  }
111
118
  map.addLayer(layerConfig, beforeId);
112
119
  layerAdded = true;
113
- // Set up event handlers
114
- setupEventHandlers(map, id, source, sourceLayer, onClick, onHover);
120
+ // Set up event handlers and store cleanup function
121
+ eventHandlerCleanup = setupEventHandlers(map, id, source, sourceLayer, onClick, onHover);
115
122
  }
116
123
  catch (err) {
117
124
  console.error(`[maps-svelte] Failed to add layer "${id}":`, err);
@@ -187,7 +194,12 @@ export function useLayer(getOptions) {
187
194
  const handleClick = (e) => {
188
195
  const params = createFeatureParams(e, getOptions(), map);
189
196
  if (params) {
190
- onClick?.({ type: 'click', ...params });
197
+ try {
198
+ onClick?.({ type: 'click', ...params });
199
+ }
200
+ catch (err) {
201
+ console.error(`[maps-svelte] Layer "${id}" click handler error:`, err);
202
+ }
191
203
  }
192
204
  };
193
205
  // Hover handlers
@@ -209,7 +221,12 @@ export function useLayer(getOptions) {
209
221
  }
210
222
  const params = createFeatureParams(e, getOptions(), map);
211
223
  if (params) {
212
- onHover?.({ type: 'mouseenter', ...params });
224
+ try {
225
+ onHover?.({ type: 'mouseenter', ...params });
226
+ }
227
+ catch (err) {
228
+ console.error(`[maps-svelte] Layer "${id}" hover handler error:`, err);
229
+ }
213
230
  }
214
231
  };
215
232
  // Mouse move handler for feature-to-feature transitions
@@ -239,7 +256,12 @@ export function useLayer(getOptions) {
239
256
  lastHoverCallTime = now;
240
257
  const params = createFeatureParams(e, options, map);
241
258
  if (params) {
242
- onHover?.({ type: 'mousemove', ...params });
259
+ try {
260
+ onHover?.({ type: 'mousemove', ...params });
261
+ }
262
+ catch (err) {
263
+ console.error(`[maps-svelte] Layer "${id}" hover handler error:`, err);
264
+ }
243
265
  }
244
266
  }
245
267
  }
@@ -256,15 +278,20 @@ export function useLayer(getOptions) {
256
278
  }
257
279
  // Use last known position for mouseleave event (more meaningful than [0, 0])
258
280
  const lastPos = lastMousePosition;
259
- onHover?.({
260
- type: 'mouseleave',
261
- feature: null,
262
- layerId: id,
263
- sourceId: source,
264
- lngLat: lastPos?.lngLat ?? [0, 0],
265
- point: lastPos?.point ?? [0, 0],
266
- map,
267
- });
281
+ try {
282
+ onHover?.({
283
+ type: 'mouseleave',
284
+ feature: null,
285
+ layerId: id,
286
+ sourceId: source,
287
+ lngLat: lastPos?.lngLat ?? [0, 0],
288
+ point: lastPos?.point ?? [0, 0],
289
+ map,
290
+ });
291
+ }
292
+ catch (err) {
293
+ console.error(`[maps-svelte] Layer "${id}" hover handler error:`, err);
294
+ }
268
295
  lastMousePosition = null;
269
296
  };
270
297
  // Attach handlers
@@ -276,11 +303,27 @@ export function useLayer(getOptions) {
276
303
  map.on('mousemove', id, handleMouseMove);
277
304
  map.on('mouseleave', id, handleMouseLeave);
278
305
  }
306
+ // Return cleanup function to remove all handlers
307
+ return () => {
308
+ if (onClick) {
309
+ map.off('click', id, handleClick);
310
+ }
311
+ if (onHover) {
312
+ map.off('mouseenter', id, handleMouseEnter);
313
+ map.off('mousemove', id, handleMouseMove);
314
+ map.off('mouseleave', id, handleMouseLeave);
315
+ }
316
+ };
279
317
  }
280
318
  // Cleanup on destroy
281
319
  onDestroy(() => {
282
320
  const { map } = mapContext;
283
321
  const options = getOptions();
322
+ // Remove event handlers first (before removing the layer)
323
+ if (eventHandlerCleanup) {
324
+ eventHandlerCleanup();
325
+ eventHandlerCleanup = null;
326
+ }
284
327
  if (sourceDataHandler && map) {
285
328
  map.off('sourcedata', sourceDataHandler);
286
329
  }
@@ -1,4 +1,4 @@
1
1
  export { useMapTheme } from './useMapTheme.svelte.js';
2
2
  export { useReducedMotion } from './useReducedMotion.svelte.js';
3
- export { useMapContext, tryUseMapContext, type MapContextValue } from './useMapContext.svelte.js';
3
+ export { useMapContext, tryUseMapContext, useMapInstance, type MapContextValue, } from './useMapContext.svelte.js';
4
4
  export { useControlPosition, type UseControlPositionOptions, type UseControlPositionResult, } from './useControlPosition.svelte.js';
@@ -1,4 +1,4 @@
1
1
  export { useMapTheme } from './useMapTheme.svelte.js';
2
2
  export { useReducedMotion } from './useReducedMotion.svelte.js';
3
- export { useMapContext, tryUseMapContext } from './useMapContext.svelte.js';
3
+ export { useMapContext, tryUseMapContext, useMapInstance, } from './useMapContext.svelte.js';
4
4
  export { useControlPosition, } from './useControlPosition.svelte.js';
@@ -45,7 +45,7 @@ export interface UseControlPositionResult {
45
45
  * Create a control position manager using the positioning coordinator
46
46
  *
47
47
  * @param getElement - Function that returns the control element (use a getter for reactivity)
48
- * @param options - Control registration options
48
+ * @param options - Control registration options (can be an object or a getter function for reactivity)
49
49
  * @returns Position offset, visibility, and style to apply
50
50
  *
51
51
  * @example
@@ -56,6 +56,7 @@ export interface UseControlPositionResult {
56
56
  * let legendElement: HTMLDivElement;
57
57
  * const legendId = `legend-${Math.random().toString(36).slice(2, 9)}`;
58
58
  *
59
+ * // For static options:
59
60
  * const controlPosition = useControlPosition(
60
61
  * () => legendElement,
61
62
  * {
@@ -65,6 +66,17 @@ export interface UseControlPositionResult {
65
66
  * priority: 'normal',
66
67
  * }
67
68
  * );
69
+ *
70
+ * // For reactive options (e.g., position can change):
71
+ * const controlPosition = useControlPosition(
72
+ * () => legendElement,
73
+ * () => ({
74
+ * id: legendId,
75
+ * type: 'legend',
76
+ * position: position, // reactive prop
77
+ * priority: 'normal',
78
+ * })
79
+ * );
68
80
  * </script>
69
81
  *
70
82
  * <div bind:this={legendElement} style={controlPosition.style} hidden={!controlPosition.visible}>
@@ -72,4 +84,4 @@ export interface UseControlPositionResult {
72
84
  * </div>
73
85
  * ```
74
86
  */
75
- export declare function useControlPosition(getElement: () => HTMLElement | undefined, options: UseControlPositionOptions): UseControlPositionResult;
87
+ export declare function useControlPosition(getElement: () => HTMLElement | undefined, options: UseControlPositionOptions | (() => UseControlPositionOptions)): UseControlPositionResult;
@@ -10,7 +10,7 @@ import { tryUseMapContext } from './useMapContext.svelte.js';
10
10
  * Create a control position manager using the positioning coordinator
11
11
  *
12
12
  * @param getElement - Function that returns the control element (use a getter for reactivity)
13
- * @param options - Control registration options
13
+ * @param options - Control registration options (can be an object or a getter function for reactivity)
14
14
  * @returns Position offset, visibility, and style to apply
15
15
  *
16
16
  * @example
@@ -21,6 +21,7 @@ import { tryUseMapContext } from './useMapContext.svelte.js';
21
21
  * let legendElement: HTMLDivElement;
22
22
  * const legendId = `legend-${Math.random().toString(36).slice(2, 9)}`;
23
23
  *
24
+ * // For static options:
24
25
  * const controlPosition = useControlPosition(
25
26
  * () => legendElement,
26
27
  * {
@@ -30,6 +31,17 @@ import { tryUseMapContext } from './useMapContext.svelte.js';
30
31
  * priority: 'normal',
31
32
  * }
32
33
  * );
34
+ *
35
+ * // For reactive options (e.g., position can change):
36
+ * const controlPosition = useControlPosition(
37
+ * () => legendElement,
38
+ * () => ({
39
+ * id: legendId,
40
+ * type: 'legend',
41
+ * position: position, // reactive prop
42
+ * priority: 'normal',
43
+ * })
44
+ * );
33
45
  * </script>
34
46
  *
35
47
  * <div bind:this={legendElement} style={controlPosition.style} hidden={!controlPosition.visible}>
@@ -38,7 +50,11 @@ import { tryUseMapContext } from './useMapContext.svelte.js';
38
50
  * ```
39
51
  */
40
52
  export function useControlPosition(getElement, options) {
41
- const { id, type, position, fallbacks, priority = 'normal', zLayer = 'interactive', hasExpandedState = false, isBuiltIn = false, } = options;
53
+ // Support both static options and getter function for reactivity
54
+ const getOptions = typeof options === 'function' ? options : () => options;
55
+ // Get initial values for registration (these are used once at mount)
56
+ const initialOptions = getOptions();
57
+ const { id, type, hasExpandedState = false, isBuiltIn = false } = initialOptions;
42
58
  const mapContext = tryUseMapContext();
43
59
  const coordinator = mapContext
44
60
  ?.positioningCoordinator;
@@ -87,6 +103,7 @@ export function useControlPosition(getElement, options) {
87
103
  // Initial registration
88
104
  if (!registered) {
89
105
  untrack(() => {
106
+ const opts = getOptions();
90
107
  const initialOffset = coordinator.register({
91
108
  id,
92
109
  type,
@@ -96,11 +113,11 @@ export function useControlPosition(getElement, options) {
96
113
  height: element.offsetHeight || 100,
97
114
  },
98
115
  position: {
99
- primary: position,
100
- fallbacks,
116
+ primary: opts.position,
117
+ fallbacks: opts.fallbacks,
101
118
  },
102
- priority,
103
- zLayer,
119
+ priority: opts.priority ?? 'normal',
120
+ zLayer: opts.zLayer ?? 'interactive',
104
121
  hasExpandedState,
105
122
  isExpanded: false,
106
123
  });
@@ -133,11 +150,13 @@ export function useControlPosition(getElement, options) {
133
150
  $effect(() => {
134
151
  if (!coordinator || !registered)
135
152
  return;
153
+ // Get current options (this creates reactivity when using a getter function)
154
+ const opts = getOptions();
136
155
  // Track these values to trigger the effect when they change
137
- const _position = position;
138
- const _fallbacks = fallbacks;
139
- const _priority = priority;
140
- const _zLayer = zLayer;
156
+ const _position = opts.position;
157
+ const _fallbacks = opts.fallbacks;
158
+ const _priority = opts.priority ?? 'normal';
159
+ const _zLayer = opts.zLayer ?? 'interactive';
141
160
  untrack(() => {
142
161
  coordinator.update(id, {
143
162
  position: {
@@ -15,7 +15,7 @@ export interface MapContextValue {
15
15
  readonly map: maplibregl.Map | null;
16
16
  /** Whether the map has finished loading */
17
17
  readonly loaded: boolean;
18
- /** Counter incremented on each style change (via data event), used to re-initialize sources/layers */
18
+ /** Counter incremented on style changes, used to re-initialize sources/layers */
19
19
  readonly styleVersion: number;
20
20
  /** Set the map style programmatically (e.g. basemap switching) */
21
21
  setMapStyle?: (style: string | maplibregl.StyleSpecification) => void;
@@ -59,3 +59,29 @@ export declare function useMapContext(): MapContextValue;
59
59
  * @returns The map context or null if not within a Map component
60
60
  */
61
61
  export declare function tryUseMapContext(): MapContextValue | null;
62
+ /**
63
+ * Get the map instance only when loaded
64
+ *
65
+ * This is a convenience composable that returns the map instance
66
+ * only when it's fully loaded. Returns null if map is not yet available.
67
+ *
68
+ * @returns The map instance or null if not loaded
69
+ * @throws Error if used outside of a Map component
70
+ *
71
+ * @example
72
+ * ```svelte
73
+ * <script lang="ts">
74
+ * import { useMapInstance } from '@classic-homes/maps-svelte';
75
+ *
76
+ * const map = useMapInstance();
77
+ *
78
+ * $effect(() => {
79
+ * if (map) {
80
+ * // Map is ready to use
81
+ * map.flyTo({ center: [0, 0], zoom: 5 });
82
+ * }
83
+ * });
84
+ * </script>
85
+ * ```
86
+ */
87
+ export declare function useMapInstance(): maplibregl.Map | null;
@@ -56,3 +56,33 @@ export function useMapContext() {
56
56
  export function tryUseMapContext() {
57
57
  return getContext(MAP_CONTEXT_KEY) ?? null;
58
58
  }
59
+ /**
60
+ * Get the map instance only when loaded
61
+ *
62
+ * This is a convenience composable that returns the map instance
63
+ * only when it's fully loaded. Returns null if map is not yet available.
64
+ *
65
+ * @returns The map instance or null if not loaded
66
+ * @throws Error if used outside of a Map component
67
+ *
68
+ * @example
69
+ * ```svelte
70
+ * <script lang="ts">
71
+ * import { useMapInstance } from '@classic-homes/maps-svelte';
72
+ *
73
+ * const map = useMapInstance();
74
+ *
75
+ * $effect(() => {
76
+ * if (map) {
77
+ * // Map is ready to use
78
+ * map.flyTo({ center: [0, 0], zoom: 5 });
79
+ * }
80
+ * });
81
+ * </script>
82
+ * ```
83
+ */
84
+ export function useMapInstance() {
85
+ const context = useMapContext();
86
+ // Use $derived-like pattern to reactively return map only when loaded
87
+ return context.loaded ? context.map : null;
88
+ }
@@ -4,10 +4,11 @@
4
4
  * Svelte MapLibre components for the Classic Theme design system
5
5
  */
6
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';
7
- export { useMapTheme, useReducedMotion, useMapContext, tryUseMapContext, useControlPosition, type MapContextValue, type UseControlPositionOptions, type UseControlPositionResult, } from './composables/index.js';
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
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';
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';
13
- export { isClusterFeature, getClusterExpansionZoom, getClusterChildren, getClusterLeaves, expandCluster, getClusterBounds, expandClusterToBounds, } from '@classic-homes/maps-core';
13
+ export { isClusterFeature, getClusterExpansionZoom, getClusterChildren, getClusterLeaves, expandCluster, getClusterBounds, expandClusterToBounds, createClusterStyles, createClusterCirclePaint, createClusterTextLayout, } from '@classic-homes/maps-core';
14
+ export type { ClusterCircleStyleOptions, ClusterTextStyleOptions, UnclusteredPointStyleOptions, ClusterLayerStyles, } from '@classic-homes/maps-core';
package/dist/lib/index.js CHANGED
@@ -16,7 +16,7 @@ Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher, LayerManager, CustomCon
16
16
  // Deck.gl
17
17
  DeckOverlay, } from './components/index.js';
18
18
  // Composables
19
- export { useMapTheme, useReducedMotion, useMapContext, tryUseMapContext, useControlPosition, } from './composables/index.js';
19
+ export { useMapTheme, useReducedMotion, useMapContext, tryUseMapContext, useMapInstance, useControlPosition, } from './composables/index.js';
20
20
  // Utils
21
21
  export { cn } from './utils.js';
22
22
  // Re-export layer presets and utilities from maps-core
@@ -30,4 +30,6 @@ loadGeoJSON, validateGeoJSON, calculateCentroid, countFeaturesByType, filterByGe
30
30
  // Basemap utilities
31
31
  DEFAULT_BASEMAP, SATELLITE_BASEMAP, TOPO_BASEMAP, PRIMARY_BASEMAPS, BUILTIN_BASEMAPS, FREE_BASEMAPS, OSM_STANDARD, resolveBasemapStyle, getAvailableBasemaps, } from '@classic-homes/maps-core';
32
32
  // Re-export cluster utilities from maps-core
33
- export { isClusterFeature, getClusterExpansionZoom, getClusterChildren, getClusterLeaves, expandCluster, getClusterBounds, expandClusterToBounds, } from '@classic-homes/maps-core';
33
+ export { isClusterFeature, getClusterExpansionZoom, getClusterChildren, getClusterLeaves, expandCluster, getClusterBounds, expandClusterToBounds,
34
+ // Cluster rendering helpers
35
+ createClusterStyles, createClusterCirclePaint, createClusterTextLayout, } from '@classic-homes/maps-core';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/maps-svelte",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "description": "Svelte MapLibre components for Classic Theme",
5
5
  "keywords": [
6
6
  "maps",