@classic-homes/maps-svelte 0.1.3 → 0.1.4

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.
@@ -0,0 +1,234 @@
1
+ <script lang="ts">
2
+ import { getContext, onDestroy } from 'svelte';
3
+ import type {
4
+ BasemapSwitcherProps,
5
+ BasemapDefinition,
6
+ ControlPosition,
7
+ } from '@classic-homes/maps-core';
8
+ import {
9
+ computePositionClasses,
10
+ computeVerticalOffsetStyle,
11
+ FREE_BASEMAPS,
12
+ getAvailableBasemaps,
13
+ resolveBasemapStyle,
14
+ resolveBasemapThumbnail,
15
+ } from '@classic-homes/maps-core';
16
+ import '@classic-homes/maps-core/styles/basemap-switcher.css';
17
+ import { cn } from '../../utils.js';
18
+ import type maplibregl from 'maplibre-gl';
19
+
20
+ interface MapContext {
21
+ readonly controlOffsets?: Record<string, number>;
22
+ registerControl?: (id: string, position: string, height: number) => number;
23
+ unregisterControl?: (id: string, position: string) => void;
24
+ setMapStyle?: (style: string | maplibregl.StyleSpecification) => void;
25
+ }
26
+
27
+ interface Props extends BasemapSwitcherProps {}
28
+
29
+ let {
30
+ basemaps,
31
+ extraBasemaps,
32
+ apiKeys,
33
+ defaultBasemapId,
34
+ activeBasemapId,
35
+ onBasemapChange,
36
+ columns = 3,
37
+ thumbnailSize = 64,
38
+ position = 'bottom-right',
39
+ class: className,
40
+ }: Props = $props();
41
+
42
+ const mapContext = getContext<MapContext>('maplibre-map');
43
+ const switcherId = `basemap-switcher-${Math.random().toString(36).slice(2, 9)}`;
44
+
45
+ let isOpen = $state(false);
46
+ let internalActiveId = $state<string | undefined>(undefined);
47
+ let customControlOffset = $state(0);
48
+
49
+ // Initialize with defaultBasemapId (reactive to prop changes)
50
+ $effect(() => {
51
+ if (defaultBasemapId !== undefined && internalActiveId === undefined) {
52
+ internalActiveId = defaultBasemapId;
53
+ }
54
+ });
55
+ let containerElement: HTMLDivElement;
56
+
57
+ // Compute available basemaps
58
+ const sourceBasemaps = $derived(basemaps ?? FREE_BASEMAPS);
59
+ const availableBasemaps = $derived(() => {
60
+ const available = getAvailableBasemaps(sourceBasemaps, apiKeys);
61
+ if (extraBasemaps?.length) {
62
+ return [...available, ...getAvailableBasemaps(extraBasemaps, apiKeys)];
63
+ }
64
+ return available;
65
+ });
66
+
67
+ const currentActiveId = $derived(
68
+ activeBasemapId ?? internalActiveId ?? availableBasemaps()[0]?.id
69
+ );
70
+
71
+ // Register this control with the map context
72
+ $effect(() => {
73
+ if (!containerElement || !mapContext?.registerControl) return;
74
+
75
+ const height = containerElement.offsetHeight;
76
+ customControlOffset = mapContext.registerControl(switcherId, position, height);
77
+ });
78
+
79
+ // Close on outside click
80
+ $effect(() => {
81
+ if (!isOpen) return;
82
+
83
+ const handleMouseDown = (e: MouseEvent) => {
84
+ if (containerElement && !containerElement.contains(e.target as Node)) {
85
+ isOpen = false;
86
+ }
87
+ };
88
+
89
+ document.addEventListener('mousedown', handleMouseDown);
90
+
91
+ return () => {
92
+ document.removeEventListener('mousedown', handleMouseDown);
93
+ };
94
+ });
95
+
96
+ // Close on Escape
97
+ $effect(() => {
98
+ if (!isOpen) return;
99
+
100
+ const handleKeyDown = (e: KeyboardEvent) => {
101
+ if (e.key === 'Escape') {
102
+ isOpen = false;
103
+ }
104
+ };
105
+
106
+ document.addEventListener('keydown', handleKeyDown);
107
+
108
+ return () => {
109
+ document.removeEventListener('keydown', handleKeyDown);
110
+ };
111
+ });
112
+
113
+ function handleSelect(basemap: BasemapDefinition) {
114
+ const style = resolveBasemapStyle(basemap, apiKeys);
115
+ if (!style) return;
116
+
117
+ if (!activeBasemapId) {
118
+ internalActiveId = basemap.id;
119
+ }
120
+
121
+ mapContext?.setMapStyle?.(style as string | maplibregl.StyleSpecification);
122
+ onBasemapChange?.(basemap);
123
+ isOpen = false;
124
+ }
125
+
126
+ // Cleanup on destroy
127
+ onDestroy(() => {
128
+ mapContext?.unregisterControl?.(switcherId, position);
129
+ });
130
+
131
+ const hasControlsAtPosition = $derived(() => {
132
+ const offset = mapContext?.controlOffsets?.[position] ?? 0;
133
+ return offset > 0;
134
+ });
135
+
136
+ const getPositionClasses = $derived(() => {
137
+ return computePositionClasses(position as ControlPosition, hasControlsAtPosition());
138
+ });
139
+
140
+ const verticalOffsetStyle = $derived(() => {
141
+ const styleObj = computeVerticalOffsetStyle(position as ControlPosition, customControlOffset);
142
+ return Object.entries(styleObj)
143
+ .map(([key, value]) => `${key}: ${value}`)
144
+ .join('; ');
145
+ });
146
+
147
+ const isTop = $derived(position.startsWith('top'));
148
+ const panelWidth = $derived(columns * (thumbnailSize + 12) + 16);
149
+ </script>
150
+
151
+ <div
152
+ bind:this={containerElement}
153
+ class={cn('absolute z-10', getPositionClasses(), className)}
154
+ style={verticalOffsetStyle()}
155
+ >
156
+ <!-- Flyout panel -->
157
+ {#if isOpen}
158
+ <div
159
+ class={cn(
160
+ 'absolute classic-basemap-panel-enter',
161
+ 'bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
162
+ 'p-2',
163
+ isTop ? 'top-full mt-1' : 'bottom-full mb-1',
164
+ position.includes('right') ? 'right-0' : 'left-0'
165
+ )}
166
+ style="width: {panelWidth}px;"
167
+ >
168
+ <div
169
+ role="listbox"
170
+ aria-label="Select basemap"
171
+ class="grid gap-1.5"
172
+ style="grid-template-columns: repeat({columns}, 1fr);"
173
+ >
174
+ {#each availableBasemaps() as basemap (basemap.id)}
175
+ {@const isActive = basemap.id === currentActiveId}
176
+ {@const thumbUrl = resolveBasemapThumbnail(basemap, apiKeys)}
177
+ <button
178
+ type="button"
179
+ role="option"
180
+ aria-selected={isActive}
181
+ class={cn(
182
+ 'flex flex-col items-center gap-1 p-1 rounded cursor-pointer',
183
+ 'hover:bg-muted transition-colors',
184
+ isActive && 'ring-2 ring-primary'
185
+ )}
186
+ onclick={() => handleSelect(basemap)}
187
+ title={basemap.name}
188
+ >
189
+ <img
190
+ src={thumbUrl}
191
+ alt={basemap.name}
192
+ loading="lazy"
193
+ class="rounded object-cover"
194
+ style="width: {thumbnailSize}px; height: {thumbnailSize}px;"
195
+ />
196
+ <span class="text-[10px] text-foreground truncate w-full text-center leading-tight">
197
+ {basemap.label ?? basemap.name}
198
+ </span>
199
+ </button>
200
+ {/each}
201
+ </div>
202
+ </div>
203
+ {/if}
204
+
205
+ <!-- Toggle button -->
206
+ <button
207
+ type="button"
208
+ class={cn(
209
+ 'w-[40px] h-[40px] flex items-center justify-center',
210
+ 'bg-card rounded shadow-lg border border-black dark:border-gray-400',
211
+ 'hover:bg-muted transition-colors cursor-pointer',
212
+ 'text-foreground'
213
+ )}
214
+ onclick={() => (isOpen = !isOpen)}
215
+ aria-label="Switch basemap"
216
+ aria-expanded={isOpen}
217
+ aria-haspopup="true"
218
+ >
219
+ <svg
220
+ width="20"
221
+ height="20"
222
+ viewBox="0 0 24 24"
223
+ fill="none"
224
+ stroke="currentColor"
225
+ stroke-width="2"
226
+ stroke-linecap="round"
227
+ stroke-linejoin="round"
228
+ >
229
+ <path d="M12 2L2 7l10 5 10-5-10-5z" />
230
+ <path d="M2 17l10 5 10-5" />
231
+ <path d="M2 12l10 5 10-5" />
232
+ </svg>
233
+ </button>
234
+ </div>
@@ -0,0 +1,7 @@
1
+ import type { BasemapSwitcherProps } from '@classic-homes/maps-core';
2
+ import '@classic-homes/maps-core/styles/basemap-switcher.css';
3
+ interface Props extends BasemapSwitcherProps {
4
+ }
5
+ declare const BasemapSwitcher: import("svelte").Component<Props, {}, "">;
6
+ type BasemapSwitcher = ReturnType<typeof BasemapSwitcher>;
7
+ export default BasemapSwitcher;
@@ -1,3 +1,4 @@
1
1
  export { default as Legend } from './Legend.svelte';
2
2
  export { default as LegendGroup } from './LegendGroup.svelte';
3
3
  export { default as CoordinateDisplay } from './CoordinateDisplay.svelte';
4
+ export { default as BasemapSwitcher } from './BasemapSwitcher.svelte';
@@ -1,3 +1,4 @@
1
1
  export { default as Legend } from './Legend.svelte';
2
2
  export { default as LegendGroup } from './LegendGroup.svelte';
3
3
  export { default as CoordinateDisplay } from './CoordinateDisplay.svelte';
4
+ export { default as BasemapSwitcher } from './BasemapSwitcher.svelte';
@@ -85,6 +85,13 @@
85
85
  let map: maplibregl.Map | null = $state(null);
86
86
  let mapLoaded = $state(false);
87
87
  let mapError = $state<string | null>(null);
88
+ let styleVersion = $state(0);
89
+ let activeStyleOverride: string | maplibregl.StyleSpecification | null = $state(null);
90
+
91
+ function setMapStyle(style: string | maplibregl.StyleSpecification) {
92
+ activeStyleOverride = style;
93
+ map?.setStyle(style);
94
+ }
88
95
 
89
96
  // Registry for custom controls to coordinate positioning
90
97
  // Each entry tracks controls at a position with their heights
@@ -194,9 +201,13 @@
194
201
  get controlOffsets() {
195
202
  return controlOffsets();
196
203
  },
204
+ get styleVersion() {
205
+ return styleVersion;
206
+ },
197
207
  registerControl,
198
208
  unregisterControl,
199
209
  getCustomControlOffset,
210
+ setMapStyle,
200
211
  });
201
212
 
202
213
  const combinedError = $derived(error || mapError);
@@ -227,6 +238,11 @@
227
238
 
228
239
  map = newMap;
229
240
 
241
+ // Track style changes for layer re-initialization
242
+ newMap.on('style.load', () => {
243
+ styleVersion++;
244
+ });
245
+
230
246
  // Add controls
231
247
  if (navigationControl) {
232
248
  newMap.addControl(
@@ -396,6 +412,9 @@
396
412
  return;
397
413
  }
398
414
 
415
+ // Don't override a programmatic style change (basemap switcher)
416
+ if (activeStyleOverride) return;
417
+
399
418
  // Only update if style actually changed
400
419
  if (styleKey !== lastAppliedStyle) {
401
420
  lastAppliedStyle = styleKey;
@@ -403,6 +422,13 @@
403
422
  }
404
423
  });
405
424
 
425
+ // Clear programmatic override when customStyle prop changes
426
+ $effect(() => {
427
+ if (customStyle) {
428
+ activeStyleOverride = null;
429
+ }
430
+ });
431
+
406
432
  onDestroy(() => {
407
433
  if (map) {
408
434
  map.remove();
@@ -15,6 +15,7 @@
15
15
  interface MapContext {
16
16
  readonly map: maplibregl.Map | null;
17
17
  readonly loaded: boolean;
18
+ readonly styleVersion: number;
18
19
  }
19
20
 
20
21
  /**
@@ -109,6 +110,22 @@
109
110
  let lastDataFingerprint: GeoJSONFingerprint | null = null;
110
111
  let pendingIdleCallback: number | null = null;
111
112
 
113
+ // Track style version for re-initialization after basemap changes
114
+ let lastKnownStyleVersion = -1;
115
+
116
+ $effect(() => {
117
+ const sv = mapContext.styleVersion ?? 0;
118
+ if (lastKnownStyleVersion === -1) {
119
+ lastKnownStyleVersion = sv;
120
+ return;
121
+ }
122
+ if (sv !== lastKnownStyleVersion) {
123
+ lastKnownStyleVersion = sv;
124
+ sourceAdded = false;
125
+ lastDataFingerprint = null;
126
+ }
127
+ });
128
+
112
129
  // Add source effect
113
130
  $effect(() => {
114
131
  const { map, loaded } = mapContext;
@@ -2,4 +2,4 @@ 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
3
  export { FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './layers/index.js';
4
4
  export { DeckOverlay } from './deck/index.js';
5
- export { Legend, LegendGroup, CoordinateDisplay } from './controls/index.js';
5
+ export { Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher } from './controls/index.js';
@@ -7,4 +7,4 @@ export { FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, Hea
7
7
  // Deck.gl components
8
8
  export { DeckOverlay } from './deck/index.js';
9
9
  // Control components
10
- export { Legend, LegendGroup, CoordinateDisplay } from './controls/index.js';
10
+ export { Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher } from './controls/index.js';
@@ -14,6 +14,23 @@ export function useLayer(getOptions) {
14
14
  let lastAppliedVisible = undefined;
15
15
  let lastAppliedPaint = undefined;
16
16
  let lastAppliedFilterSerialized = '';
17
+ // Track style version for re-initialization after basemap changes
18
+ let lastKnownStyleVersion = -1;
19
+ $effect(() => {
20
+ const sv = mapContext.styleVersion ?? 0;
21
+ if (lastKnownStyleVersion === -1) {
22
+ lastKnownStyleVersion = sv;
23
+ return;
24
+ }
25
+ if (sv !== lastKnownStyleVersion) {
26
+ lastKnownStyleVersion = sv;
27
+ layerAdded = false;
28
+ hoveredFeatureId = null;
29
+ lastAppliedVisible = undefined;
30
+ lastAppliedPaint = undefined;
31
+ lastAppliedFilterSerialized = '';
32
+ }
33
+ });
17
34
  const createFeatureParams = (e, options, map) => {
18
35
  const feature = e.features?.[0];
19
36
  if (!feature)
@@ -22,6 +22,10 @@ export interface MapContextValue {
22
22
  unregisterControl?: (id: string, position: string) => void;
23
23
  /** Get the offset for a specific custom control */
24
24
  getCustomControlOffset?: (id: string, position: string) => number;
25
+ /** Counter incremented on each style.load event, used to re-initialize sources/layers */
26
+ readonly styleVersion: number;
27
+ /** Set the map style programmatically (e.g. basemap switching) */
28
+ setMapStyle?: (style: string | maplibregl.StyleSpecification) => void;
25
29
  }
26
30
  /**
27
31
  * Get the map context from a parent Map component
@@ -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, DeckOverlay, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './components/index.js';
6
+ export { MapContainer, MapSkeleton, MapError, MapEmpty, Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter, FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer, Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher, DeckOverlay, type SvelteFeatureClickEventParams, type SvelteFeatureHoverEventParams, } from './components/index.js';
7
7
  export { useMapTheme, useReducedMotion, useMapContext, tryUseMapContext, type MapContextValue, } 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, } from '@classic-homes/maps-core';
10
- 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, } from '@classic-homes/maps-core';
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, } from '@classic-homes/maps-core';
10
+ 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, BUILTIN_BASEMAPS, FREE_BASEMAPS, OSM_STANDARD, resolveBasemapStyle, getAvailableBasemaps, } from '@classic-homes/maps-core';
11
11
  export type { LoadGeoJSONOptions, LoadGeoJSONResult, ValidationResult, ClusterFeatureProperties, ClusterExpandOptions, } from '@classic-homes/maps-core';
12
12
  export { isClusterFeature, getClusterExpansionZoom, getClusterChildren, getClusterLeaves, expandCluster, getClusterBounds, expandClusterToBounds, } from '@classic-homes/maps-core';
package/dist/lib/index.js CHANGED
@@ -12,7 +12,7 @@ Map, Source, Marker, Popup, PopupCard, PopupHeader, PopupContent, PopupFooter,
12
12
  // Layers
13
13
  FillLayer, LineLayer, CircleLayer, SymbolLayer, FillExtrusionLayer, HeatmapLayer,
14
14
  // Controls
15
- Legend, LegendGroup, CoordinateDisplay,
15
+ Legend, LegendGroup, CoordinateDisplay, BasemapSwitcher,
16
16
  // Deck.gl
17
17
  DeckOverlay, } from './components/index.js';
18
18
  // Composables
@@ -24,6 +24,8 @@ export { THEME_LIGHT, THEME_DARK, lightTheme, darkTheme, lightBasicStyle, darkBa
24
24
  // Bounds utilities
25
25
  calculateBounds, extendBounds, combineBounds, isValidBounds,
26
26
  // Data utilities
27
- loadGeoJSON, validateGeoJSON, calculateCentroid, countFeaturesByType, filterByGeometryType, } from '@classic-homes/maps-core';
27
+ loadGeoJSON, validateGeoJSON, calculateCentroid, countFeaturesByType, filterByGeometryType,
28
+ // Basemap utilities
29
+ BUILTIN_BASEMAPS, FREE_BASEMAPS, OSM_STANDARD, resolveBasemapStyle, getAvailableBasemaps, } from '@classic-homes/maps-core';
28
30
  // Re-export cluster utilities from maps-core
29
31
  export { isClusterFeature, getClusterExpansionZoom, getClusterChildren, getClusterLeaves, expandCluster, getClusterBounds, expandClusterToBounds, } 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.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Svelte MapLibre components for Classic Theme",
5
5
  "keywords": [
6
6
  "maps",