@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,966 @@
1
+ <script lang="ts">
2
+ import { getContext, onDestroy, untrack } from 'svelte';
3
+ import type {
4
+ LayerManagerProps,
5
+ OverlayLayerDefinition,
6
+ OverlayLayerState,
7
+ OverlayLayerCategory,
8
+ ControlPosition,
9
+ } from '@classic-homes/maps-core';
10
+ import {
11
+ computePositionClasses,
12
+ computeVerticalOffsetStyle,
13
+ CATEGORY_META,
14
+ getLayerStyleForTheme,
15
+ searchLayers,
16
+ getLayerCategories,
17
+ groupLayersByCategory,
18
+ createInitialLayerStates,
19
+ toggleLayerVisibility,
20
+ setLayerOpacity,
21
+ reorderLayers,
22
+ getLayerStatesArray,
23
+ resolveLayerSourceUrl,
24
+ } from '@classic-homes/maps-core';
25
+ import '@classic-homes/maps-core/styles/layer-manager.css';
26
+ import { Switch } from '@classic-homes/theme-svelte';
27
+ import { cn } from '../../utils.js';
28
+ import type maplibregl from 'maplibre-gl';
29
+
30
+ interface MapContext {
31
+ readonly map: maplibregl.Map | null;
32
+ readonly loaded: boolean;
33
+ readonly styleVersion: number;
34
+ readonly controlOffsets?: Record<string, number>;
35
+ registerControl?: (id: string, position: string, height: number) => number;
36
+ unregisterControl?: (id: string, position: string) => void;
37
+ }
38
+
39
+ interface Props extends LayerManagerProps {}
40
+
41
+ let {
42
+ layers,
43
+ apiKeys,
44
+ initialActiveLayers,
45
+ position = 'top-right',
46
+ showSearch = false,
47
+ showCategories = false,
48
+ allowReorder = false,
49
+ showOpacity = false,
50
+ collapsible = true,
51
+ onLayerChange,
52
+ class: className,
53
+ }: Props = $props();
54
+
55
+ const mapContext = getContext<MapContext>('maplibre-map');
56
+ const managerId = `layer-manager-${Math.random().toString(36).slice(2, 9)}`;
57
+
58
+ let isOpen = $state(false);
59
+
60
+ // Capture initialActiveLayers at mount time (non-reactive)
61
+ const initialActiveLayersSet = new Set(initialActiveLayers ?? []);
62
+
63
+ // Store layer states as stable $state - NOT derived
64
+ // This prevents object identity changes from causing infinite loops
65
+ let layerStates = $state<Map<string, OverlayLayerState>>(new Map());
66
+
67
+ // Version counter to force derived recalculations when layerStates Map contents change
68
+ // Svelte 5 doesn't deeply track Map mutations, so we use this to trigger updates
69
+ let stateVersion = $state(0);
70
+
71
+ // Track which layer IDs we've seen (non-reactive, plain object)
72
+ let knownLayerIds: Set<string> = new Set();
73
+
74
+ // Sync layer states when layers prop changes
75
+ // IMPORTANT: All reads of layerStates must be inside untrack() to avoid dependency cycle
76
+ $effect(() => {
77
+ // Read layers prop to establish dependency (this is the ONLY reactive dependency)
78
+ const currentLayers = layers;
79
+ if (!currentLayers || currentLayers.length === 0) return;
80
+
81
+ // Build set of current layer IDs
82
+ const currentIds = new Set(currentLayers.map((l) => l.id));
83
+
84
+ // Check if we have any new layers or removed layers
85
+ const hasNew = currentLayers.some((l) => !knownLayerIds.has(l.id));
86
+ const hasRemoved = [...knownLayerIds].some((id) => !currentIds.has(id));
87
+
88
+ // ALL reads of layerStates must be inside untrack to prevent dependency cycle
89
+ untrack(() => {
90
+ // Check if we actually need to update
91
+ if (!hasNew && !hasRemoved && layerStates.size > 0) {
92
+ // No structural changes - just update tracking
93
+ knownLayerIds = currentIds;
94
+ return;
95
+ }
96
+
97
+ const newStates = new Map(layerStates);
98
+ let changed = false;
99
+
100
+ // Add new layers
101
+ currentLayers.forEach((layer, index) => {
102
+ if (!newStates.has(layer.id)) {
103
+ newStates.set(layer.id, {
104
+ id: layer.id,
105
+ visible: initialActiveLayersSet.has(layer.id),
106
+ opacity: 1,
107
+ loading: false,
108
+ error: null,
109
+ order: newStates.size + index,
110
+ });
111
+ changed = true;
112
+ }
113
+ });
114
+
115
+ // Remove states for removed layers
116
+ for (const id of knownLayerIds) {
117
+ if (!currentIds.has(id)) {
118
+ newStates.delete(id);
119
+ changed = true;
120
+ }
121
+ }
122
+
123
+ if (changed) {
124
+ layerStates = newStates;
125
+ }
126
+ knownLayerIds = currentIds;
127
+ });
128
+ });
129
+
130
+ let searchQuery = $state('');
131
+ let activeCategory = $state<OverlayLayerCategory | 'all'>('all');
132
+ let customControlOffset = $state(0);
133
+ let expandedOpacity = $state<string | null>(null);
134
+ let draggedId = $state<string | null>(null);
135
+ let dragOver = $state<{ id: string; position: 'above' | 'below' } | null>(null);
136
+ let containerElement: HTMLDivElement;
137
+
138
+ // Track style version for re-initialization after basemap changes
139
+ let lastKnownStyleVersion = -1;
140
+ let addedSources = new Set<string>();
141
+ let addedLayers = new Set<string>();
142
+
143
+ // Detect theme from document
144
+ let isDark = $state(false);
145
+
146
+ $effect(() => {
147
+ if (typeof document !== 'undefined') {
148
+ isDark = document.documentElement.classList.contains('dark');
149
+
150
+ // Watch for dark mode class changes
151
+ const observer = new MutationObserver((mutations) => {
152
+ mutations.forEach((mutation) => {
153
+ if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
154
+ isDark = document.documentElement.classList.contains('dark');
155
+ }
156
+ });
157
+ });
158
+
159
+ observer.observe(document.documentElement, {
160
+ attributes: true,
161
+ attributeFilter: ['class'],
162
+ });
163
+
164
+ return () => observer.disconnect();
165
+ }
166
+ });
167
+
168
+ // Get available categories
169
+ const categories = $derived(getLayerCategories(layers));
170
+
171
+ // Filter layers by search and category, then sort by state order
172
+ // We depend on stateVersion to recalculate when order changes (after drag-drop)
173
+ const filteredLayers = $derived.by(() => {
174
+ // Force recalculation when layerStates contents change
175
+ void stateVersion;
176
+
177
+ let result = layers;
178
+
179
+ if (searchQuery) {
180
+ result = searchLayers(result, searchQuery);
181
+ }
182
+
183
+ if (activeCategory !== 'all') {
184
+ result = result.filter((l) => l.category === activeCategory);
185
+ }
186
+
187
+ // Sort by state order for drag-to-reorder support
188
+ return [...result].sort((a, b) => {
189
+ const orderA = layerStates.get(a.id)?.order ?? 0;
190
+ const orderB = layerStates.get(b.id)?.order ?? 0;
191
+ return orderA - orderB;
192
+ });
193
+ });
194
+
195
+ // Group layers by category for display
196
+ const layerGroups = $derived.by(() =>
197
+ showCategories ? groupLayersByCategory(filteredLayers) : null
198
+ );
199
+
200
+ // Get visible layer states
201
+ // Depend on stateVersion to recalculate when visibility or opacity changes
202
+ const visibleLayerStates = $derived.by(() => {
203
+ void stateVersion;
204
+ return getLayerStatesArray(layerStates).filter((s) => s.visible);
205
+ });
206
+
207
+ // Register this control with the map context
208
+ $effect(() => {
209
+ const registerControl = mapContext?.registerControl;
210
+ if (!containerElement || !registerControl) return;
211
+
212
+ const height = containerElement.offsetHeight;
213
+ untrack(() => {
214
+ customControlOffset = registerControl(managerId, position, height);
215
+ });
216
+ });
217
+
218
+ // Reset on style version change
219
+ $effect(() => {
220
+ const sv = mapContext.styleVersion ?? 0;
221
+ if (lastKnownStyleVersion === -1) {
222
+ lastKnownStyleVersion = sv;
223
+ return;
224
+ }
225
+ if (sv !== lastKnownStyleVersion) {
226
+ lastKnownStyleVersion = sv;
227
+ addedSources.clear();
228
+ addedLayers.clear();
229
+ }
230
+ });
231
+
232
+ // Track pending map update
233
+ let mapUpdateTimeout: ReturnType<typeof setTimeout> | null = null;
234
+
235
+ // Manage sources and layers on the map
236
+ // Use setTimeout to debounce updates and break reactive chains
237
+ $effect(() => {
238
+ // Read visibleLayerStates to establish dependency
239
+ const states = visibleLayerStates;
240
+
241
+ // Cancel any pending update
242
+ if (mapUpdateTimeout) {
243
+ clearTimeout(mapUpdateTimeout);
244
+ }
245
+
246
+ // Schedule map update after a microtask to break reactive chain
247
+ mapUpdateTimeout = setTimeout(() => {
248
+ mapUpdateTimeout = null;
249
+
250
+ // All reads are now outside the reactive context
251
+ const { map, loaded } = mapContext;
252
+ if (!map || !loaded) return;
253
+
254
+ const theme = isDark ? 'dark' : 'light';
255
+ const currentVisibleIds = new Set(states.map((s) => s.id));
256
+
257
+ // Add/update visible layers
258
+ // Use untrack to read layers without creating a dependency
259
+ // This prevents the effect from re-running when layers changes
260
+ // (we already react to layer changes via visibleLayerStates)
261
+ for (const state of states) {
262
+ const layer = untrack(() => layers.find((l) => l.id === state.id));
263
+ if (!layer) continue;
264
+
265
+ const sourceId = `lm-source-${layer.id}`;
266
+ const layerId = `lm-layer-${layer.id}`;
267
+ const paint = getLayerStyleForTheme(layer, theme);
268
+ const sourceUrl = untrack(() => resolveLayerSourceUrl(layer, apiKeys));
269
+
270
+ // Add source if not added
271
+ if (!addedSources.has(sourceId) && !map.getSource(sourceId)) {
272
+ try {
273
+ if (layer.source.type === 'geojson-inline' && layer.source.data) {
274
+ map.addSource(sourceId, {
275
+ type: 'geojson',
276
+ data: layer.source.data as GeoJSON.GeoJSON,
277
+ attribution: layer.source.attribution,
278
+ });
279
+ addedSources.add(sourceId);
280
+ } else if (layer.source.type === 'geojson-url' && sourceUrl) {
281
+ map.addSource(sourceId, {
282
+ type: 'geojson',
283
+ data: sourceUrl,
284
+ attribution: layer.source.attribution,
285
+ });
286
+ addedSources.add(sourceId);
287
+ } else if (layer.source.type === 'vector-tiles' && sourceUrl) {
288
+ map.addSource(sourceId, {
289
+ type: 'vector',
290
+ tiles: [sourceUrl],
291
+ attribution: layer.source.attribution,
292
+ });
293
+ addedSources.add(sourceId);
294
+ }
295
+ } catch (err) {
296
+ console.error(`[maps-svelte] LayerManager: Failed to add source "${sourceId}":`, err);
297
+ }
298
+ }
299
+
300
+ // Add layer if not added and source exists
301
+ if (!addedLayers.has(layerId) && !map.getLayer(layerId) && map.getSource(sourceId)) {
302
+ try {
303
+ const layerConfig: maplibregl.LayerSpecification = {
304
+ id: layerId,
305
+ type: layer.style.renderType as 'fill',
306
+ source: sourceId,
307
+ paint: paint as maplibregl.FillLayerSpecification['paint'],
308
+ layout: {
309
+ visibility: 'visible',
310
+ },
311
+ };
312
+
313
+ if (layer.source.sourceLayer) {
314
+ (layerConfig as maplibregl.FillLayerSpecification)['source-layer'] =
315
+ layer.source.sourceLayer;
316
+ }
317
+
318
+ if (layer.style.minZoom !== undefined) {
319
+ layerConfig.minzoom = layer.style.minZoom;
320
+ }
321
+
322
+ if (layer.style.maxZoom !== undefined) {
323
+ layerConfig.maxzoom = layer.style.maxZoom;
324
+ }
325
+
326
+ map.addLayer(layerConfig);
327
+ addedLayers.add(layerId);
328
+ } catch (err) {
329
+ console.error(`[maps-svelte] LayerManager: Failed to add layer "${layerId}":`, err);
330
+ }
331
+ }
332
+
333
+ // Update opacity if layer exists
334
+ // Multiply base opacity from style with state opacity so the slider acts as a multiplier
335
+ if (map.getLayer(layerId)) {
336
+ try {
337
+ const opacityProp = getOpacityProperty(layer.style.renderType);
338
+ if (opacityProp) {
339
+ const baseOpacity = getBaseOpacity(layer, theme);
340
+ map.setPaintProperty(layerId, opacityProp, baseOpacity * state.opacity);
341
+ }
342
+ } catch {
343
+ // Ignore
344
+ }
345
+ }
346
+ }
347
+
348
+ // Hide layers that are no longer visible
349
+ for (const layerId of addedLayers) {
350
+ const originalId = layerId.replace('lm-layer-', '');
351
+ if (!currentVisibleIds.has(originalId)) {
352
+ try {
353
+ if (map.getLayer(layerId)) {
354
+ map.setLayoutProperty(layerId, 'visibility', 'none');
355
+ }
356
+ } catch {
357
+ // Ignore
358
+ }
359
+ } else {
360
+ try {
361
+ if (map.getLayer(layerId)) {
362
+ map.setLayoutProperty(layerId, 'visibility', 'visible');
363
+ }
364
+ } catch {
365
+ // Ignore
366
+ }
367
+ }
368
+ }
369
+ }, 0); // End of setTimeout callback
370
+ });
371
+
372
+ function getOpacityProperty(renderType: string): string | null {
373
+ switch (renderType) {
374
+ case 'fill':
375
+ return 'fill-opacity';
376
+ case 'line':
377
+ return 'line-opacity';
378
+ case 'circle':
379
+ return 'circle-opacity';
380
+ case 'symbol':
381
+ return 'icon-opacity';
382
+ default:
383
+ return null;
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Get the base opacity from the layer style definition for the current theme.
389
+ * This is used to multiply with state.opacity so the slider acts as a multiplier.
390
+ */
391
+ function getBaseOpacity(layer: OverlayLayerDefinition, theme: 'light' | 'dark'): number {
392
+ const paint = getLayerStyleForTheme(layer, theme);
393
+ const opacityProp = getOpacityProperty(layer.style.renderType);
394
+ if (!opacityProp) return 1;
395
+ return (paint[opacityProp] as number | undefined) ?? 1;
396
+ }
397
+
398
+ // Close on outside click
399
+ $effect(() => {
400
+ if (!isOpen) return;
401
+
402
+ const handleMouseDown = (e: MouseEvent) => {
403
+ if (containerElement && !containerElement.contains(e.target as Node)) {
404
+ isOpen = false;
405
+ }
406
+ };
407
+
408
+ document.addEventListener('mousedown', handleMouseDown);
409
+
410
+ return () => {
411
+ document.removeEventListener('mousedown', handleMouseDown);
412
+ };
413
+ });
414
+
415
+ // Close on Escape
416
+ $effect(() => {
417
+ if (!isOpen) return;
418
+
419
+ const handleKeyDown = (e: KeyboardEvent) => {
420
+ if (e.key === 'Escape') {
421
+ isOpen = false;
422
+ }
423
+ };
424
+
425
+ document.addEventListener('keydown', handleKeyDown);
426
+
427
+ return () => {
428
+ document.removeEventListener('keydown', handleKeyDown);
429
+ };
430
+ });
431
+
432
+ function handleToggleLayer(layerId: string) {
433
+ const currentState = layerStates.get(layerId);
434
+ if (!currentState) return;
435
+
436
+ const newVisible = !currentState.visible;
437
+
438
+ // Directly update the state map
439
+ const newStates = new Map(layerStates);
440
+ newStates.set(layerId, { ...currentState, visible: newVisible });
441
+ layerStates = newStates;
442
+ stateVersion++; // Trigger derived recalculations
443
+
444
+ if (onLayerChange) {
445
+ onLayerChange(layerId, { ...currentState, visible: newVisible });
446
+ }
447
+ }
448
+
449
+ function handleOpacityChange(layerId: string, opacity: number) {
450
+ const currentState = layerStates.get(layerId);
451
+ if (!currentState) return;
452
+
453
+ // Directly update the state map
454
+ const newStates = new Map(layerStates);
455
+ newStates.set(layerId, { ...currentState, opacity });
456
+ layerStates = newStates;
457
+ stateVersion++; // Trigger derived recalculations
458
+
459
+ if (onLayerChange) {
460
+ onLayerChange(layerId, { ...currentState, opacity });
461
+ }
462
+ }
463
+
464
+ // Drag handlers for reordering
465
+ function handleDragStart(e: DragEvent, layerId: string) {
466
+ draggedId = layerId;
467
+ if (e.dataTransfer) {
468
+ e.dataTransfer.effectAllowed = 'move';
469
+ e.dataTransfer.setData('text/plain', layerId);
470
+ }
471
+ }
472
+
473
+ function handleDragOver(e: DragEvent, layerId: string) {
474
+ e.preventDefault();
475
+ if (e.dataTransfer) {
476
+ e.dataTransfer.dropEffect = 'move';
477
+ }
478
+ if (layerId !== draggedId) {
479
+ // Calculate if mouse is in top or bottom portion of the element
480
+ // Use a dead zone in the middle (30-70%) to prevent flickering
481
+ const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
482
+ const relativeY = (e.clientY - rect.top) / rect.height;
483
+
484
+ let position: 'above' | 'below';
485
+ if (relativeY < 0.3) {
486
+ position = 'above';
487
+ } else if (relativeY > 0.7) {
488
+ position = 'below';
489
+ } else {
490
+ // In the middle - keep current position or default to 'below'
491
+ position = dragOver?.id === layerId ? dragOver.position : 'below';
492
+ }
493
+
494
+ dragOver = { id: layerId, position };
495
+ }
496
+ }
497
+
498
+ function handleDragLeave() {
499
+ dragOver = null;
500
+ }
501
+
502
+ function handleDragEnd() {
503
+ draggedId = null;
504
+ dragOver = null;
505
+ }
506
+
507
+ function handleDrop(e: DragEvent, targetLayerId: string) {
508
+ e.preventDefault();
509
+ const sourceLayerId = e.dataTransfer?.getData('text/plain');
510
+
511
+ if (sourceLayerId && sourceLayerId !== targetLayerId) {
512
+ // Get the target index, adjusting for drop position
513
+ const sortedStates = getLayerStatesArray(layerStates);
514
+ const sourceIndex = sortedStates.findIndex((s) => s.id === sourceLayerId);
515
+ let targetIndex = sortedStates.findIndex((s) => s.id === targetLayerId);
516
+
517
+ if (targetIndex !== -1) {
518
+ // If dropping below and source is above target, increment target index
519
+ if (dragOver?.position === 'below') {
520
+ targetIndex += 1;
521
+ }
522
+ // Adjust if source was before target (removal shifts indices)
523
+ if (sourceIndex < targetIndex) {
524
+ targetIndex -= 1;
525
+ }
526
+
527
+ // Recompute orders for all layers
528
+ const newStates = new Map(layerStates);
529
+ const statesArray = [...sortedStates];
530
+ const [removed] = statesArray.splice(sourceIndex, 1);
531
+ statesArray.splice(targetIndex, 0, removed);
532
+
533
+ statesArray.forEach((state, index) => {
534
+ const current = newStates.get(state.id);
535
+ if (current) {
536
+ newStates.set(state.id, { ...current, order: index });
537
+ }
538
+ });
539
+
540
+ layerStates = newStates;
541
+ stateVersion++; // Trigger derived recalculations for reorder
542
+
543
+ const state = layerStates.get(sourceLayerId);
544
+ if (state && onLayerChange) {
545
+ onLayerChange(sourceLayerId, { ...state, order: targetIndex });
546
+ }
547
+ }
548
+ }
549
+
550
+ draggedId = null;
551
+ dragOver = null;
552
+ }
553
+
554
+ // Cleanup on destroy
555
+ onDestroy(() => {
556
+ mapContext?.unregisterControl?.(managerId, position);
557
+
558
+ const { map } = mapContext;
559
+ if (!map) return;
560
+
561
+ // Remove all added layers and sources
562
+ for (const layerId of addedLayers) {
563
+ try {
564
+ if (map.getLayer(layerId)) {
565
+ map.removeLayer(layerId);
566
+ }
567
+ } catch {
568
+ // Ignore
569
+ }
570
+ }
571
+
572
+ for (const sourceId of addedSources) {
573
+ try {
574
+ if (map.getSource(sourceId)) {
575
+ map.removeSource(sourceId);
576
+ }
577
+ } catch {
578
+ // Ignore
579
+ }
580
+ }
581
+ });
582
+
583
+ const hasControlsAtPosition = $derived.by(() => {
584
+ const offset = mapContext?.controlOffsets?.[position] ?? 0;
585
+ return offset > 0;
586
+ });
587
+
588
+ const getPositionClasses = $derived.by(() => {
589
+ return computePositionClasses(position as ControlPosition, hasControlsAtPosition);
590
+ });
591
+
592
+ const verticalOffsetStyle = $derived.by(() => {
593
+ const styleObj = computeVerticalOffsetStyle(position as ControlPosition, customControlOffset);
594
+ return Object.entries(styleObj)
595
+ .map(([key, value]) => `${key}: ${value}`)
596
+ .join('; ');
597
+ });
598
+
599
+ const isTop = $derived(position.startsWith('top'));
600
+ </script>
601
+
602
+ <div
603
+ bind:this={containerElement}
604
+ class={cn('absolute z-10', getPositionClasses, className)}
605
+ style={verticalOffsetStyle}
606
+ >
607
+ <!-- Flyout panel -->
608
+ {#if isOpen}
609
+ <div
610
+ class={cn(
611
+ 'absolute classic-layer-panel-enter',
612
+ 'bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
613
+ 'w-64',
614
+ isTop ? 'top-full mt-1' : 'bottom-full mb-1',
615
+ position.includes('right') ? 'right-0' : 'left-0'
616
+ )}
617
+ >
618
+ <!-- Header -->
619
+ <div class="flex items-center justify-between p-3 border-b border-border">
620
+ <span class="text-sm font-medium text-foreground">Layers</span>
621
+ {#if collapsible}
622
+ <button
623
+ type="button"
624
+ class="text-muted-foreground hover:text-foreground"
625
+ onclick={() => (isOpen = false)}
626
+ aria-label="Close layer manager"
627
+ >
628
+ <svg
629
+ width="16"
630
+ height="16"
631
+ viewBox="0 0 24 24"
632
+ fill="none"
633
+ stroke="currentColor"
634
+ stroke-width="2"
635
+ >
636
+ <path d="M18 6L6 18M6 6l12 12" />
637
+ </svg>
638
+ </button>
639
+ {/if}
640
+ </div>
641
+
642
+ <!-- Search -->
643
+ {#if showSearch}
644
+ <div class="p-2 border-b border-border">
645
+ <input
646
+ type="text"
647
+ placeholder="Search layers..."
648
+ bind:value={searchQuery}
649
+ class="classic-layer-search"
650
+ />
651
+ </div>
652
+ {/if}
653
+
654
+ <!-- Category tabs -->
655
+ {#if showCategories && categories.length > 1}
656
+ <div class="p-2 border-b border-border">
657
+ <div class="classic-layer-tabs">
658
+ <button
659
+ type="button"
660
+ class="classic-layer-tab"
661
+ data-active={activeCategory === 'all'}
662
+ onclick={() => (activeCategory = 'all')}
663
+ >
664
+ All
665
+ </button>
666
+ {#each categories as cat (cat)}
667
+ <button
668
+ type="button"
669
+ class="classic-layer-tab"
670
+ data-active={activeCategory === cat}
671
+ onclick={() => (activeCategory = cat)}
672
+ >
673
+ {CATEGORY_META[cat].label}
674
+ </button>
675
+ {/each}
676
+ </div>
677
+ </div>
678
+ {/if}
679
+
680
+ <!-- Layer list -->
681
+ <div class="max-h-64 overflow-y-auto">
682
+ {#if showCategories && layerGroups && activeCategory === 'all'}
683
+ <!-- Grouped by category -->
684
+ {#each categories as cat (cat)}
685
+ {@const catLayers = layerGroups![cat]}
686
+ {#if catLayers.length > 0}
687
+ <div>
688
+ <div
689
+ class="px-3 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wider"
690
+ >
691
+ {CATEGORY_META[cat].label}
692
+ </div>
693
+ {#each catLayers as layer (layer.id)}
694
+ {@const state = layerStates.get(layer.id)}
695
+ {#if state}
696
+ <div
697
+ class="classic-layer-item"
698
+ role={allowReorder ? 'listitem' : undefined}
699
+ draggable={allowReorder}
700
+ ondragstart={allowReorder
701
+ ? (e: DragEvent) => handleDragStart(e, layer.id)
702
+ : undefined}
703
+ ondragover={allowReorder
704
+ ? (e: DragEvent) => handleDragOver(e, layer.id)
705
+ : undefined}
706
+ ondragleave={allowReorder ? handleDragLeave : undefined}
707
+ ondragend={allowReorder ? handleDragEnd : undefined}
708
+ ondrop={allowReorder ? (e: DragEvent) => handleDrop(e, layer.id) : undefined}
709
+ data-dragging={draggedId === layer.id || undefined}
710
+ data-drag-over={dragOver?.id === layer.id ? dragOver.position : undefined}
711
+ >
712
+ {#if allowReorder}
713
+ <span class="classic-layer-drag-handle text-muted-foreground">
714
+ <svg
715
+ width="12"
716
+ height="12"
717
+ viewBox="0 0 24 24"
718
+ fill="none"
719
+ stroke="currentColor"
720
+ stroke-width="2"
721
+ >
722
+ <circle cx="9" cy="6" r="1" fill="currentColor" />
723
+ <circle cx="15" cy="6" r="1" fill="currentColor" />
724
+ <circle cx="9" cy="12" r="1" fill="currentColor" />
725
+ <circle cx="15" cy="12" r="1" fill="currentColor" />
726
+ <circle cx="9" cy="18" r="1" fill="currentColor" />
727
+ <circle cx="15" cy="18" r="1" fill="currentColor" />
728
+ </svg>
729
+ </span>
730
+ {/if}
731
+
732
+ <Switch
733
+ checked={state.visible}
734
+ onchange={() => handleToggleLayer(layer.id)}
735
+ class="scale-75"
736
+ />
737
+
738
+ <div class="flex-1 min-w-0">
739
+ <div class="flex items-center gap-1">
740
+ <span class="text-sm text-foreground truncate">{layer.name}</span>
741
+ {#if state.loading}
742
+ <svg
743
+ class="classic-layer-loading w-3 h-3 text-muted-foreground"
744
+ viewBox="0 0 24 24"
745
+ fill="none"
746
+ stroke="currentColor"
747
+ stroke-width="2"
748
+ >
749
+ <path
750
+ d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"
751
+ />
752
+ </svg>
753
+ {/if}
754
+ </div>
755
+ {#if state.error}
756
+ <span class="classic-layer-error">{state.error}</span>
757
+ {/if}
758
+ </div>
759
+
760
+ {#if showOpacity && state.visible}
761
+ <button
762
+ type="button"
763
+ class="text-muted-foreground hover:text-foreground p-1"
764
+ onclick={() =>
765
+ (expandedOpacity = expandedOpacity === layer.id ? null : layer.id)}
766
+ aria-label="Adjust opacity"
767
+ >
768
+ <svg
769
+ width="14"
770
+ height="14"
771
+ viewBox="0 0 24 24"
772
+ fill="none"
773
+ stroke="currentColor"
774
+ stroke-width="2"
775
+ >
776
+ <circle cx="12" cy="12" r="10" />
777
+ <path d="M12 2a10 10 0 0 1 0 20" fill="currentColor" opacity="0.3" />
778
+ </svg>
779
+ </button>
780
+ {/if}
781
+ </div>
782
+
783
+ {#if expandedOpacity === layer.id}
784
+ <div class="px-3 pb-2">
785
+ <div class="flex items-center gap-2">
786
+ <span class="text-xs text-muted-foreground w-12">Opacity</span>
787
+ <input
788
+ type="range"
789
+ min="0"
790
+ max="100"
791
+ value={state.opacity * 100}
792
+ oninput={(e) =>
793
+ handleOpacityChange(
794
+ layer.id,
795
+ Number((e.target as HTMLInputElement).value) / 100
796
+ )}
797
+ class="classic-layer-opacity-slider flex-1"
798
+ />
799
+ <span class="text-xs text-muted-foreground w-8 text-right">
800
+ {Math.round(state.opacity * 100)}%
801
+ </span>
802
+ </div>
803
+ </div>
804
+ {/if}
805
+ {/if}
806
+ {/each}
807
+ </div>
808
+ {/if}
809
+ {/each}
810
+ {:else}
811
+ <!-- Flat list -->
812
+ {#each filteredLayers as layer (layer.id)}
813
+ {@const state = layerStates.get(layer.id)}
814
+ {#if state}
815
+ <div
816
+ class="classic-layer-item"
817
+ role={allowReorder ? 'listitem' : undefined}
818
+ draggable={allowReorder}
819
+ ondragstart={allowReorder
820
+ ? (e: DragEvent) => handleDragStart(e, layer.id)
821
+ : undefined}
822
+ ondragover={allowReorder
823
+ ? (e: DragEvent) => handleDragOver(e, layer.id)
824
+ : undefined}
825
+ ondragleave={allowReorder ? handleDragLeave : undefined}
826
+ ondragend={allowReorder ? handleDragEnd : undefined}
827
+ ondrop={allowReorder ? (e: DragEvent) => handleDrop(e, layer.id) : undefined}
828
+ data-dragging={draggedId === layer.id || undefined}
829
+ data-drag-over={dragOver?.id === layer.id ? dragOver.position : undefined}
830
+ >
831
+ {#if allowReorder}
832
+ <span class="classic-layer-drag-handle text-muted-foreground">
833
+ <svg
834
+ width="12"
835
+ height="12"
836
+ viewBox="0 0 24 24"
837
+ fill="none"
838
+ stroke="currentColor"
839
+ stroke-width="2"
840
+ >
841
+ <circle cx="9" cy="6" r="1" fill="currentColor" />
842
+ <circle cx="15" cy="6" r="1" fill="currentColor" />
843
+ <circle cx="9" cy="12" r="1" fill="currentColor" />
844
+ <circle cx="15" cy="12" r="1" fill="currentColor" />
845
+ <circle cx="9" cy="18" r="1" fill="currentColor" />
846
+ <circle cx="15" cy="18" r="1" fill="currentColor" />
847
+ </svg>
848
+ </span>
849
+ {/if}
850
+
851
+ <Switch
852
+ checked={state.visible}
853
+ onchange={() => handleToggleLayer(layer.id)}
854
+ class="scale-75"
855
+ />
856
+
857
+ <div class="flex-1 min-w-0">
858
+ <div class="flex items-center gap-1">
859
+ <span class="text-sm text-foreground truncate">{layer.name}</span>
860
+ {#if state.loading}
861
+ <svg
862
+ class="classic-layer-loading w-3 h-3 text-muted-foreground"
863
+ viewBox="0 0 24 24"
864
+ fill="none"
865
+ stroke="currentColor"
866
+ stroke-width="2"
867
+ >
868
+ <path
869
+ d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"
870
+ />
871
+ </svg>
872
+ {/if}
873
+ </div>
874
+ {#if state.error}
875
+ <span class="classic-layer-error">{state.error}</span>
876
+ {/if}
877
+ </div>
878
+
879
+ {#if showOpacity && state.visible}
880
+ <button
881
+ type="button"
882
+ class="text-muted-foreground hover:text-foreground p-1"
883
+ onclick={() =>
884
+ (expandedOpacity = expandedOpacity === layer.id ? null : layer.id)}
885
+ aria-label="Adjust opacity"
886
+ >
887
+ <svg
888
+ width="14"
889
+ height="14"
890
+ viewBox="0 0 24 24"
891
+ fill="none"
892
+ stroke="currentColor"
893
+ stroke-width="2"
894
+ >
895
+ <circle cx="12" cy="12" r="10" />
896
+ <path d="M12 2a10 10 0 0 1 0 20" fill="currentColor" opacity="0.3" />
897
+ </svg>
898
+ </button>
899
+ {/if}
900
+ </div>
901
+
902
+ {#if expandedOpacity === layer.id}
903
+ <div class="px-3 pb-2">
904
+ <div class="flex items-center gap-2">
905
+ <span class="text-xs text-muted-foreground w-12">Opacity</span>
906
+ <input
907
+ type="range"
908
+ min="0"
909
+ max="100"
910
+ value={state.opacity * 100}
911
+ oninput={(e) =>
912
+ handleOpacityChange(
913
+ layer.id,
914
+ Number((e.target as HTMLInputElement).value) / 100
915
+ )}
916
+ class="classic-layer-opacity-slider flex-1"
917
+ />
918
+ <span class="text-xs text-muted-foreground w-8 text-right">
919
+ {Math.round(state.opacity * 100)}%
920
+ </span>
921
+ </div>
922
+ </div>
923
+ {/if}
924
+ {/if}
925
+ {/each}
926
+
927
+ {#if filteredLayers.length === 0}
928
+ <div class="p-4 text-center text-sm text-muted-foreground">No layers found</div>
929
+ {/if}
930
+ {/if}
931
+ </div>
932
+ </div>
933
+ {/if}
934
+
935
+ <!-- Toggle button -->
936
+ <button
937
+ type="button"
938
+ class={cn(
939
+ 'w-[40px] h-[40px] flex items-center justify-center',
940
+ 'bg-card rounded shadow-lg border border-black dark:border-gray-400',
941
+ 'hover:bg-muted transition-colors cursor-pointer',
942
+ 'text-foreground'
943
+ )}
944
+ onclick={() => (isOpen = !isOpen)}
945
+ aria-label="Toggle layer manager"
946
+ aria-expanded={isOpen}
947
+ aria-haspopup="true"
948
+ >
949
+ <svg
950
+ width="20"
951
+ height="20"
952
+ viewBox="0 0 24 24"
953
+ fill="none"
954
+ stroke="currentColor"
955
+ stroke-width="2"
956
+ stroke-linecap="round"
957
+ stroke-linejoin="round"
958
+ >
959
+ <path
960
+ d="M12.89 1.45l8 4A2 2 0 0 1 22 7.24v9.53a2 2 0 0 1-1.11 1.79l-8 4a2 2 0 0 1-1.78 0l-8-4a2 2 0 0 1-1.11-1.8V7.24a2 2 0 0 1 1.11-1.79l8-4a2 2 0 0 1 1.78 0z"
961
+ />
962
+ <polyline points="2.32 6.16 12 11 21.68 6.16" />
963
+ <line x1="12" y1="22.76" x2="12" y2="11" />
964
+ </svg>
965
+ </button>
966
+ </div>