@classic-homes/maps-svelte 0.1.3 → 0.1.5

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,237 @@
1
+ <script lang="ts">
2
+ import { getContext, onDestroy, untrack } 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
+ const registerControl = mapContext?.registerControl;
74
+ if (!containerElement || !registerControl) return;
75
+
76
+ const height = containerElement.offsetHeight;
77
+ untrack(() => {
78
+ customControlOffset = registerControl(switcherId, position, height);
79
+ });
80
+ });
81
+
82
+ // Close on outside click
83
+ $effect(() => {
84
+ if (!isOpen) return;
85
+
86
+ const handleMouseDown = (e: MouseEvent) => {
87
+ if (containerElement && !containerElement.contains(e.target as Node)) {
88
+ isOpen = false;
89
+ }
90
+ };
91
+
92
+ document.addEventListener('mousedown', handleMouseDown);
93
+
94
+ return () => {
95
+ document.removeEventListener('mousedown', handleMouseDown);
96
+ };
97
+ });
98
+
99
+ // Close on Escape
100
+ $effect(() => {
101
+ if (!isOpen) return;
102
+
103
+ const handleKeyDown = (e: KeyboardEvent) => {
104
+ if (e.key === 'Escape') {
105
+ isOpen = false;
106
+ }
107
+ };
108
+
109
+ document.addEventListener('keydown', handleKeyDown);
110
+
111
+ return () => {
112
+ document.removeEventListener('keydown', handleKeyDown);
113
+ };
114
+ });
115
+
116
+ function handleSelect(basemap: BasemapDefinition) {
117
+ const style = resolveBasemapStyle(basemap, apiKeys);
118
+ if (!style) return;
119
+
120
+ if (!activeBasemapId) {
121
+ internalActiveId = basemap.id;
122
+ }
123
+
124
+ mapContext?.setMapStyle?.(style as string | maplibregl.StyleSpecification);
125
+ onBasemapChange?.(basemap);
126
+ isOpen = false;
127
+ }
128
+
129
+ // Cleanup on destroy
130
+ onDestroy(() => {
131
+ mapContext?.unregisterControl?.(switcherId, position);
132
+ });
133
+
134
+ const hasControlsAtPosition = $derived(() => {
135
+ const offset = mapContext?.controlOffsets?.[position] ?? 0;
136
+ return offset > 0;
137
+ });
138
+
139
+ const getPositionClasses = $derived(() => {
140
+ return computePositionClasses(position as ControlPosition, hasControlsAtPosition());
141
+ });
142
+
143
+ const verticalOffsetStyle = $derived(() => {
144
+ const styleObj = computeVerticalOffsetStyle(position as ControlPosition, customControlOffset);
145
+ return Object.entries(styleObj)
146
+ .map(([key, value]) => `${key}: ${value}`)
147
+ .join('; ');
148
+ });
149
+
150
+ const isTop = $derived(position.startsWith('top'));
151
+ const panelWidth = $derived(columns * (thumbnailSize + 12) + 16);
152
+ </script>
153
+
154
+ <div
155
+ bind:this={containerElement}
156
+ class={cn('absolute z-10', getPositionClasses(), className)}
157
+ style={verticalOffsetStyle()}
158
+ >
159
+ <!-- Flyout panel -->
160
+ {#if isOpen}
161
+ <div
162
+ class={cn(
163
+ 'absolute classic-basemap-panel-enter',
164
+ 'bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
165
+ 'p-2',
166
+ isTop ? 'top-full mt-1' : 'bottom-full mb-1',
167
+ position.includes('right') ? 'right-0' : 'left-0'
168
+ )}
169
+ style="width: {panelWidth}px;"
170
+ >
171
+ <div
172
+ role="listbox"
173
+ aria-label="Select basemap"
174
+ class="grid gap-1.5"
175
+ style="grid-template-columns: repeat({columns}, 1fr);"
176
+ >
177
+ {#each availableBasemaps() as basemap (basemap.id)}
178
+ {@const isActive = basemap.id === currentActiveId}
179
+ {@const thumbUrl = resolveBasemapThumbnail(basemap, apiKeys)}
180
+ <button
181
+ type="button"
182
+ role="option"
183
+ aria-selected={isActive}
184
+ class={cn(
185
+ 'flex flex-col items-center gap-1 p-1 rounded cursor-pointer',
186
+ 'hover:bg-muted transition-colors',
187
+ isActive && 'ring-2 ring-primary'
188
+ )}
189
+ onclick={() => handleSelect(basemap)}
190
+ title={basemap.name}
191
+ >
192
+ <img
193
+ src={thumbUrl}
194
+ alt={basemap.name}
195
+ loading="lazy"
196
+ class="rounded object-cover"
197
+ style="width: {thumbnailSize}px; height: {thumbnailSize}px;"
198
+ />
199
+ <span class="text-[10px] text-foreground truncate w-full text-center leading-tight">
200
+ {basemap.label ?? basemap.name}
201
+ </span>
202
+ </button>
203
+ {/each}
204
+ </div>
205
+ </div>
206
+ {/if}
207
+
208
+ <!-- Toggle button -->
209
+ <button
210
+ type="button"
211
+ class={cn(
212
+ 'w-[40px] h-[40px] flex items-center justify-center',
213
+ 'bg-card rounded shadow-lg border border-black dark:border-gray-400',
214
+ 'hover:bg-muted transition-colors cursor-pointer',
215
+ 'text-foreground'
216
+ )}
217
+ onclick={() => (isOpen = !isOpen)}
218
+ aria-label="Switch basemap"
219
+ aria-expanded={isOpen}
220
+ aria-haspopup="true"
221
+ >
222
+ <svg
223
+ width="20"
224
+ height="20"
225
+ viewBox="0 0 24 24"
226
+ fill="none"
227
+ stroke="currentColor"
228
+ stroke-width="2"
229
+ stroke-linecap="round"
230
+ stroke-linejoin="round"
231
+ >
232
+ <path d="M12 2L2 7l10 5 10-5-10-5z" />
233
+ <path d="M2 17l10 5 10-5" />
234
+ <path d="M2 12l10 5 10-5" />
235
+ </svg>
236
+ </button>
237
+ </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,5 +1,5 @@
1
1
  <script lang="ts">
2
- import { getContext, onDestroy } from 'svelte';
2
+ import { getContext, onDestroy, untrack } from 'svelte';
3
3
  import type maplibregl from 'maplibre-gl';
4
4
  import type { CoordinateDisplayProps, LngLat, ControlPosition } from '@classic-homes/maps-core';
5
5
  import {
@@ -56,13 +56,16 @@
56
56
 
57
57
  // Register this control with the map context and get vertical offset
58
58
  $effect(() => {
59
- if (!controlElement || !mapContext?.registerControl) return;
59
+ const registerControl = mapContext?.registerControl;
60
+ if (!controlElement || !registerControl) return;
60
61
 
61
62
  // Get the element's height
62
63
  const height = controlElement.offsetHeight;
63
64
 
64
- // Register and get offset
65
- customControlOffset = mapContext.registerControl(controlId, position, height);
65
+ // Register and get offset - wrap in untrack to prevent infinite loop
66
+ untrack(() => {
67
+ customControlOffset = registerControl(controlId, position, height);
68
+ });
66
69
  });
67
70
 
68
71
  // Cleanup on destroy