@classic-homes/maps-svelte 0.2.3 → 0.2.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.
@@ -1,13 +1,7 @@
1
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';
2
+ import { getContext } from 'svelte';
3
+ import type { BasemapSwitcherProps, BasemapDefinition } from '@classic-homes/maps-core';
8
4
  import {
9
- computePositionClasses,
10
- computeVerticalOffsetStyle,
11
5
  FREE_BASEMAPS,
12
6
  getAvailableBasemaps,
13
7
  resolveBasemapStyle,
@@ -16,11 +10,9 @@
16
10
  import '@classic-homes/maps-core/styles/basemap-switcher.css';
17
11
  import { cn } from '../../utils.js';
18
12
  import type maplibregl from 'maplibre-gl';
13
+ import { useControlPosition } from '../../composables/useControlPosition.svelte.js';
19
14
 
20
15
  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
16
  setMapStyle?: (style: string | maplibregl.StyleSpecification) => void;
25
17
  }
26
18
 
@@ -44,7 +36,17 @@
44
36
 
45
37
  let isOpen = $state(false);
46
38
  let internalActiveId = $state<string | undefined>(undefined);
47
- let customControlOffset = $state(0);
39
+ let containerElement: HTMLDivElement;
40
+
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
+ });
48
50
 
49
51
  // Initialize with defaultBasemapId (reactive to prop changes)
50
52
  $effect(() => {
@@ -52,7 +54,6 @@
52
54
  internalActiveId = defaultBasemapId;
53
55
  }
54
56
  });
55
- let containerElement: HTMLDivElement;
56
57
 
57
58
  // Compute available basemaps
58
59
  const sourceBasemaps = $derived(basemaps ?? FREE_BASEMAPS);
@@ -68,17 +69,6 @@
68
69
  activeBasemapId ?? internalActiveId ?? availableBasemaps()[0]?.id
69
70
  );
70
71
 
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
72
  // Close on outside click
83
73
  $effect(() => {
84
74
  if (!isOpen) return;
@@ -86,6 +76,7 @@
86
76
  const handleMouseDown = (e: MouseEvent) => {
87
77
  if (containerElement && !containerElement.contains(e.target as Node)) {
88
78
  isOpen = false;
79
+ controlPosition.setExpanded(false);
89
80
  }
90
81
  };
91
82
 
@@ -103,6 +94,7 @@
103
94
  const handleKeyDown = (e: KeyboardEvent) => {
104
95
  if (e.key === 'Escape') {
105
96
  isOpen = false;
97
+ controlPosition.setExpanded(false);
106
98
  }
107
99
  };
108
100
 
@@ -114,38 +106,24 @@
114
106
  });
115
107
 
116
108
  function handleSelect(basemap: BasemapDefinition) {
117
- const style = resolveBasemapStyle(basemap, apiKeys);
118
- if (!style) return;
109
+ const resolvedStyle = resolveBasemapStyle(basemap, apiKeys);
110
+ if (!resolvedStyle) return;
119
111
 
120
112
  if (!activeBasemapId) {
121
113
  internalActiveId = basemap.id;
122
114
  }
123
115
 
124
- mapContext?.setMapStyle?.(style as string | maplibregl.StyleSpecification);
116
+ mapContext?.setMapStyle?.(resolvedStyle as string | maplibregl.StyleSpecification);
125
117
  onBasemapChange?.(basemap);
126
118
  isOpen = false;
119
+ controlPosition.setExpanded(false);
127
120
  }
128
121
 
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
- });
122
+ function handleToggle() {
123
+ const newState = !isOpen;
124
+ isOpen = newState;
125
+ controlPosition.setExpanded(newState);
126
+ }
149
127
 
150
128
  const isTop = $derived(position.startsWith('top'));
151
129
  const panelWidth = $derived(columns * (thumbnailSize + 12) + 16);
@@ -153,8 +131,8 @@
153
131
 
154
132
  <div
155
133
  bind:this={containerElement}
156
- class={cn('absolute z-10', getPositionClasses(), className)}
157
- style={verticalOffsetStyle()}
134
+ class={cn('absolute', !controlPosition.visible && 'invisible', className)}
135
+ style={controlPosition.style}
158
136
  >
159
137
  <!-- Flyout panel -->
160
138
  {#if isOpen}
@@ -214,7 +192,7 @@
214
192
  'hover:bg-muted transition-colors cursor-pointer',
215
193
  'text-foreground'
216
194
  )}
217
- onclick={() => (isOpen = !isOpen)}
195
+ onclick={handleToggle}
218
196
  aria-label="Switch basemap"
219
197
  aria-expanded={isOpen}
220
198
  aria-haspopup="true"
@@ -1,21 +1,14 @@
1
1
  <script lang="ts">
2
- import { getContext, onDestroy, untrack } from 'svelte';
2
+ import { getContext } from 'svelte';
3
3
  import type maplibregl from 'maplibre-gl';
4
- import type { CoordinateDisplayProps, LngLat, ControlPosition } from '@classic-homes/maps-core';
5
- import {
6
- formatCoordinates,
7
- computePositionClasses,
8
- computeVerticalOffsetStyle,
9
- } from '@classic-homes/maps-core';
4
+ import type { CoordinateDisplayProps, LngLat } from '@classic-homes/maps-core';
5
+ import { formatCoordinates, EDGE_MARGIN, STACK_GAP } from '@classic-homes/maps-core';
10
6
  import { cn } from '../../utils.js';
7
+ import { useControlPosition } from '../../composables/useControlPosition.svelte.js';
11
8
 
12
9
  interface MapContext {
13
10
  readonly map: maplibregl.Map | null;
14
11
  readonly loaded: boolean;
15
- readonly controlOffsets?: Record<string, number>;
16
- registerControl?: (id: string, position: string, height: number) => number;
17
- unregisterControl?: (id: string, position: string) => void;
18
- getCustomControlOffset?: (id: string, position: string) => number;
19
12
  }
20
13
 
21
14
  interface Props extends CoordinateDisplayProps {}
@@ -34,6 +27,9 @@
34
27
  // Generate unique ID for this control instance
35
28
  const controlId = `coord-display-${Math.random().toString(36).slice(2, 9)}`;
36
29
 
30
+ // Native control dimensions for offset calculations
31
+ const NAV_CONTROL_WIDTH = 29;
32
+
37
33
  let cursorLngLat: LngLat | null = $state(null);
38
34
  let currentZoom = $state(0);
39
35
  let currentBearing = $state(0);
@@ -41,45 +37,33 @@
41
37
  let zoomHandler: (() => void) | null = null;
42
38
  let rotateHandler: (() => void) | null = null;
43
39
  let controlElement: HTMLDivElement;
44
- let customControlOffset = $state(0);
45
-
46
- // Check if controls exist at this position - if so, offset horizontally toward center
47
- const hasControlsAtPosition = $derived(() => {
48
- const offset = mapContext?.controlOffsets?.[position] ?? 0;
49
- return offset > 0;
50
- });
51
40
 
52
- // Get combined position classes using shared utility
53
- const getPositionClasses = $derived(() => {
54
- return computePositionClasses(position as ControlPosition, hasControlsAtPosition());
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',
55
48
  });
56
49
 
57
- // Register this control with the map context and get vertical offset
58
- $effect(() => {
59
- const registerControl = mapContext?.registerControl;
60
- if (!controlElement || !registerControl) return;
50
+ // Adjust style based on position
51
+ const ATTRIBUTION_HEIGHT = 32;
61
52
 
62
- // Get the element's height
63
- const height = controlElement.offsetHeight;
53
+ const adjustedStyle = $derived(() => {
54
+ if (position === 'top-right') {
55
+ // Position horizontally to the left of native controls
56
+ const rightOffset = NAV_CONTROL_WIDTH + STACK_GAP + EDGE_MARGIN;
57
+ return `position: absolute; top: ${EDGE_MARGIN}px; right: ${rightOffset}px; z-index: 10;`;
58
+ }
64
59
 
65
- // Register and get offset - wrap in untrack to prevent infinite loop
66
- untrack(() => {
67
- customControlOffset = registerControl(controlId, position, height);
68
- });
69
- });
70
-
71
- // Cleanup on destroy
72
- onDestroy(() => {
73
- mapContext?.unregisterControl?.(controlId, position);
74
- });
60
+ if (position === 'bottom-right') {
61
+ // Add extra offset to not cover the MapLibre attribution
62
+ const bottomOffset = EDGE_MARGIN + ATTRIBUTION_HEIGHT;
63
+ return `position: absolute; bottom: ${bottomOffset}px; right: ${EDGE_MARGIN}px; z-index: 10;`;
64
+ }
75
65
 
76
- // Calculate vertical offset style for stacking with other custom controls
77
- // Uses top/bottom properties instead of margins for correct absolute positioning
78
- const verticalOffsetStyle = $derived(() => {
79
- const styleObj = computeVerticalOffsetStyle(position as ControlPosition, customControlOffset);
80
- return Object.entries(styleObj)
81
- .map(([key, value]) => `${key}: ${value}`)
82
- .join('; ');
66
+ return controlPosition.style;
83
67
  });
84
68
 
85
69
  // Format the coordinate based on settings
@@ -139,14 +123,14 @@
139
123
  <div
140
124
  bind:this={controlElement}
141
125
  class={cn(
142
- 'absolute z-10 bg-card rounded px-2 py-1',
126
+ 'absolute bg-card rounded px-2 py-1',
143
127
  'text-xs font-mono text-muted-foreground',
144
128
  'border border-black dark:border-gray-400 shadow-sm',
145
129
  'flex items-center gap-3',
146
- getPositionClasses(),
130
+ !controlPosition.visible && 'invisible',
147
131
  className
148
132
  )}
149
- style={verticalOffsetStyle()}
133
+ style={adjustedStyle()}
150
134
  >
151
135
  {#if cursorLngLat}
152
136
  <span title="Cursor coordinates">{formatCoord(cursorLngLat)}</span>
@@ -5,20 +5,13 @@
5
5
  OverlayLayerDefinition,
6
6
  OverlayLayerState,
7
7
  OverlayLayerCategory,
8
- ControlPosition,
9
8
  } from '@classic-homes/maps-core';
10
9
  import {
11
- computePositionClasses,
12
- computeVerticalOffsetStyle,
13
10
  CATEGORY_META,
14
11
  getLayerStyleForTheme,
15
12
  searchLayers,
16
13
  getLayerCategories,
17
14
  groupLayersByCategory,
18
- createInitialLayerStates,
19
- toggleLayerVisibility,
20
- setLayerOpacity,
21
- reorderLayers,
22
15
  getLayerStatesArray,
23
16
  resolveLayerSourceUrl,
24
17
  } from '@classic-homes/maps-core';
@@ -26,14 +19,12 @@
26
19
  import { Switch } from '@classic-homes/theme-svelte';
27
20
  import { cn } from '../../utils.js';
28
21
  import type maplibregl from 'maplibre-gl';
22
+ import { useControlPosition } from '../../composables/useControlPosition.svelte.js';
29
23
 
30
24
  interface MapContext {
31
25
  readonly map: maplibregl.Map | null;
32
26
  readonly loaded: boolean;
33
27
  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
28
  }
38
29
 
39
30
  interface Props extends LayerManagerProps {}
@@ -129,12 +120,21 @@
129
120
 
130
121
  let searchQuery = $state('');
131
122
  let activeCategory = $state<OverlayLayerCategory | 'all'>('all');
132
- let customControlOffset = $state(0);
133
123
  let expandedOpacity = $state<string | null>(null);
134
124
  let draggedId = $state<string | null>(null);
135
125
  let dragOver = $state<{ id: string; position: 'above' | 'below' } | null>(null);
136
126
  let containerElement: HTMLDivElement;
137
127
 
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
+ });
137
+
138
138
  // Track style version for re-initialization after basemap changes
139
139
  let lastKnownStyleVersion = -1;
140
140
  let addedSources = new Set<string>();
@@ -204,17 +204,6 @@
204
204
  return getLayerStatesArray(layerStates).filter((s) => s.visible);
205
205
  });
206
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
207
  // Reset on style version change
219
208
  $effect(() => {
220
209
  const sv = mapContext.styleVersion ?? 0;
@@ -402,6 +391,7 @@
402
391
  const handleMouseDown = (e: MouseEvent) => {
403
392
  if (containerElement && !containerElement.contains(e.target as Node)) {
404
393
  isOpen = false;
394
+ controlPosition.setExpanded(false);
405
395
  }
406
396
  };
407
397
 
@@ -419,6 +409,7 @@
419
409
  const handleKeyDown = (e: KeyboardEvent) => {
420
410
  if (e.key === 'Escape') {
421
411
  isOpen = false;
412
+ controlPosition.setExpanded(false);
422
413
  }
423
414
  };
424
415
 
@@ -553,8 +544,6 @@
553
544
 
554
545
  // Cleanup on destroy
555
546
  onDestroy(() => {
556
- mapContext?.unregisterControl?.(managerId, position);
557
-
558
547
  const { map } = mapContext;
559
548
  if (!map) return;
560
549
 
@@ -580,29 +569,19 @@
580
569
  }
581
570
  });
582
571
 
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
- });
572
+ function handleToggle() {
573
+ const newState = !isOpen;
574
+ isOpen = newState;
575
+ controlPosition.setExpanded(newState);
576
+ }
598
577
 
599
578
  const isTop = $derived(position.startsWith('top'));
600
579
  </script>
601
580
 
602
581
  <div
603
582
  bind:this={containerElement}
604
- class={cn('absolute z-10', getPositionClasses, className)}
605
- style={verticalOffsetStyle}
583
+ class={cn('absolute', !controlPosition.visible && 'invisible', className)}
584
+ style={controlPosition.style}
606
585
  >
607
586
  <!-- Flyout panel -->
608
587
  {#if isOpen}
@@ -941,7 +920,7 @@
941
920
  'hover:bg-muted transition-colors cursor-pointer',
942
921
  'text-foreground'
943
922
  )}
944
- onclick={() => (isOpen = !isOpen)}
923
+ onclick={handleToggle}
945
924
  aria-label="Toggle layer manager"
946
925
  aria-expanded={isOpen}
947
926
  aria-haspopup="true"
@@ -1,15 +1,7 @@
1
1
  <script lang="ts">
2
- import { getContext, onDestroy, untrack } from 'svelte';
3
- import type { LegendProps, LegendItem, ControlPosition } from '@classic-homes/maps-core';
4
- import { computePositionClasses, computeVerticalOffsetStyle } from '@classic-homes/maps-core';
2
+ import type { LegendProps, LegendItem } from '@classic-homes/maps-core';
5
3
  import { cn } from '../../utils.js';
6
-
7
- interface MapContext {
8
- readonly controlOffsets?: Record<string, number>;
9
- registerControl?: (id: string, position: string, height: number) => number;
10
- unregisterControl?: (id: string, position: string) => void;
11
- getCustomControlOffset?: (id: string, position: string) => number;
12
- }
4
+ import { useControlPosition } from '../../composables/useControlPosition.svelte.js';
13
5
 
14
6
  interface Props extends LegendProps {}
15
7
 
@@ -27,8 +19,6 @@
27
19
  onItemClick,
28
20
  }: Props = $props();
29
21
 
30
- const mapContext = getContext<MapContext>('maplibre-map');
31
-
32
22
  // Generate unique ID for this legend instance
33
23
  const legendId = `legend-${Math.random().toString(36).slice(2, 9)}`;
34
24
 
@@ -36,49 +26,19 @@
36
26
  let userToggled = $state(false);
37
27
  let localCollapsed = $state(false);
38
28
  let legendElement: HTMLDivElement;
39
- let customControlOffset = $state(0);
40
29
 
41
- // Determine effective collapsed state - user toggle takes precedence
42
- const isCollapsed = $derived(userToggled ? localCollapsed : collapsed);
43
-
44
- // Register this control with the map context and get vertical offset
45
- $effect(() => {
46
- const registerControl = mapContext?.registerControl;
47
- if (!legendElement || !registerControl) return;
48
-
49
- // Get the element's height
50
- const height = legendElement.offsetHeight;
51
-
52
- // Register and get offset - wrap in untrack to prevent infinite loop
53
- untrack(() => {
54
- customControlOffset = registerControl(legendId, position, height);
55
- });
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,
56
38
  });
57
39
 
58
- // Cleanup on destroy
59
- onDestroy(() => {
60
- mapContext?.unregisterControl?.(legendId, position);
61
- });
62
-
63
- // Check if controls exist at this position - if so, offset horizontally toward center
64
- const hasControlsAtPosition = $derived(() => {
65
- const offset = mapContext?.controlOffsets?.[position] ?? 0;
66
- return offset > 0;
67
- });
68
-
69
- // Get combined position classes using shared utility
70
- const getPositionClasses = $derived(() => {
71
- return computePositionClasses(position as ControlPosition, hasControlsAtPosition());
72
- });
73
-
74
- // Calculate vertical offset style for stacking with other custom controls
75
- // Uses top/bottom properties instead of margins for correct absolute positioning
76
- const verticalOffsetStyle = $derived(() => {
77
- const styleObj = computeVerticalOffsetStyle(position as ControlPosition, customControlOffset);
78
- return Object.entries(styleObj)
79
- .map(([key, value]) => `${key}: ${value}`)
80
- .join('; ');
81
- });
40
+ // Determine effective collapsed state - user toggle takes precedence
41
+ const isCollapsed = $derived(userToggled ? localCollapsed : collapsed);
82
42
 
83
43
  function handleItemClick(item: LegendItem, index: number) {
84
44
  if (onItemClick) {
@@ -104,19 +64,20 @@
104
64
  <div
105
65
  bind:this={legendElement}
106
66
  class={cn(
107
- 'absolute z-10 bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
67
+ 'absolute bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
108
68
  'text-sm min-w-[140px] max-w-[280px]',
109
- getPositionClasses(),
69
+ !controlPosition.visible && 'invisible',
110
70
  className
111
71
  )}
112
- style={verticalOffsetStyle()}
72
+ style={controlPosition.style}
113
73
  >
114
74
  {#if title || collapsible}
115
75
  <button
116
76
  type="button"
117
77
  class={cn(
118
78
  'w-full flex items-center justify-between px-3 py-2 font-medium text-card-foreground',
119
- collapsible && 'cursor-pointer hover:bg-muted rounded-t-lg',
79
+ collapsible && 'cursor-pointer hover:bg-muted',
80
+ collapsible && (isCollapsed ? 'rounded-lg' : 'rounded-t-lg'),
120
81
  !collapsible && 'cursor-default'
121
82
  )}
122
83
  onclick={toggleCollapse}
@@ -1,20 +1,7 @@
1
1
  <script lang="ts">
2
- import { getContext, onDestroy, untrack } from 'svelte';
3
- import type {
4
- LegendGroupProps,
5
- LegendConfig,
6
- LegendItem,
7
- ControlPosition,
8
- } from '@classic-homes/maps-core';
9
- import { computePositionClasses, computeVerticalOffsetStyle } from '@classic-homes/maps-core';
2
+ import type { LegendGroupProps, LegendConfig, LegendItem } from '@classic-homes/maps-core';
10
3
  import { cn } from '../../utils.js';
11
-
12
- interface MapContext {
13
- readonly controlOffsets?: Record<string, number>;
14
- registerControl?: (id: string, position: string, height: number) => number;
15
- unregisterControl?: (id: string, position: string) => void;
16
- getCustomControlOffset?: (id: string, position: string) => number;
17
- }
4
+ import { useControlPosition } from '../../composables/useControlPosition.svelte.js';
18
5
 
19
6
  interface Props extends LegendGroupProps {}
20
7
 
@@ -28,8 +15,6 @@
28
15
  class: className,
29
16
  }: Props = $props();
30
17
 
31
- const mapContext = getContext<MapContext>('maplibre-map');
32
-
33
18
  // Generate unique ID for this legend group instance
34
19
  const groupId = `legend-group-${Math.random().toString(36).slice(2, 9)}`;
35
20
 
@@ -42,7 +27,16 @@
42
27
 
43
28
  let internalExpanded = $state<string | null>(getInitialExpanded());
44
29
  let containerElement: HTMLDivElement;
45
- let customControlOffset = $state(0);
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
+ });
46
40
 
47
41
  // Use controlled or internal state
48
42
  const expandedId = $derived(
@@ -57,6 +51,9 @@
57
51
  internalExpanded = newExpanded;
58
52
  }
59
53
 
54
+ // Notify coordinator of expanded state change
55
+ controlPosition.setExpanded(newExpanded !== null);
56
+
60
57
  onExpandedChange?.(newExpanded);
61
58
  }
62
59
 
@@ -67,44 +64,6 @@
67
64
  }
68
65
  });
69
66
 
70
- // Register this control with the map context and get vertical offset
71
- $effect(() => {
72
- const registerControl = mapContext?.registerControl;
73
- if (!containerElement || !registerControl) return;
74
-
75
- // Get the element's height
76
- const height = containerElement.offsetHeight;
77
-
78
- // Register and get offset - wrap in untrack to prevent infinite loop
79
- untrack(() => {
80
- customControlOffset = registerControl(groupId, position, height);
81
- });
82
- });
83
-
84
- // Cleanup on destroy
85
- onDestroy(() => {
86
- mapContext?.unregisterControl?.(groupId, position);
87
- });
88
-
89
- // Check if controls exist at this position
90
- const hasControlsAtPosition = $derived(() => {
91
- const offset = mapContext?.controlOffsets?.[position] ?? 0;
92
- return offset > 0;
93
- });
94
-
95
- // Get combined position classes using shared utility
96
- const getPositionClasses = $derived(() => {
97
- return computePositionClasses(position as ControlPosition, hasControlsAtPosition());
98
- });
99
-
100
- // Calculate vertical offset style for stacking with other custom controls
101
- const verticalOffsetStyle = $derived(() => {
102
- const styleObj = computeVerticalOffsetStyle(position as ControlPosition, customControlOffset);
103
- return Object.entries(styleObj)
104
- .map(([key, value]) => `${key}: ${value}`)
105
- .join('; ');
106
- });
107
-
108
67
  // Generate gradient CSS
109
68
  function getGradientStyle(legend: LegendConfig): string {
110
69
  if (legend.type !== 'gradient' || !legend.gradient?.length) return '';
@@ -120,12 +79,12 @@
120
79
  <div
121
80
  bind:this={containerElement}
122
81
  class={cn(
123
- 'absolute z-10 bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
82
+ 'absolute bg-card rounded-lg shadow-lg border border-black dark:border-gray-400',
124
83
  'text-sm min-w-[160px] max-w-[280px]',
125
- getPositionClasses(),
84
+ !controlPosition.visible && 'invisible',
126
85
  className
127
86
  )}
128
- style={verticalOffsetStyle()}
87
+ style={controlPosition.style}
129
88
  >
130
89
  {#each legends as legend, legendIndex}
131
90
  {@const isExpanded = expandedId === legend.id}
@@ -13,7 +13,11 @@
13
13
  MapMoveEventParams,
14
14
  LngLat,
15
15
  } from '@classic-homes/maps-core';
16
- import { generateMapDescription } from '@classic-homes/maps-core';
16
+ import {
17
+ generateMapDescription,
18
+ createPositioningCoordinator,
19
+ type PositioningCoordinator,
20
+ } from '@classic-homes/maps-core';
17
21
 
18
22
  import { cn } from '../../utils.js';
19
23
  import { useMapTheme } from '../../composables/useMapTheme.svelte.js';
@@ -88,69 +92,14 @@
88
92
  let styleVersion = $state(0);
89
93
  let activeStyleOverride: string | maplibregl.StyleSpecification | null = $state(null);
90
94
 
95
+ // Create positioning coordinator instance
96
+ const positioningCoordinator: PositioningCoordinator = createPositioningCoordinator();
97
+
91
98
  function setMapStyle(style: string | maplibregl.StyleSpecification) {
92
99
  activeStyleOverride = style;
93
100
  map?.setStyle(style);
94
101
  }
95
102
 
96
- // Non-reactive registry for custom controls to coordinate positioning (like React's useRef pattern)
97
- // Each entry tracks controls at a position with their heights
98
- type ControlEntry = { id: string; height: number };
99
- const customControlRegistryRef: Record<string, ControlEntry[]> = {
100
- 'top-left': [],
101
- 'top-right': [],
102
- 'bottom-left': [],
103
- 'bottom-right': [],
104
- };
105
-
106
- // Only trigger re-render when registry structure changes (new controls added/removed)
107
- let controlRegistryVersion = $state(0);
108
-
109
- // Register a custom control and return its vertical offset
110
- function registerControl(id: string, position: string, height: number): number {
111
- const positionControls = customControlRegistryRef[position] || [];
112
-
113
- const existingIndex = positionControls.findIndex((c) => c.id === id);
114
- if (existingIndex >= 0) {
115
- // Just update height - no reactivity trigger needed
116
- positionControls[existingIndex].height = height;
117
- } else {
118
- // New control - add and trigger update
119
- positionControls.push({ id, height });
120
- customControlRegistryRef[position] = positionControls;
121
- controlRegistryVersion++;
122
- }
123
-
124
- // Calculate offset (sum of heights of controls before this one)
125
- let offset = 0;
126
- for (const control of positionControls) {
127
- if (control.id === id) break;
128
- offset += control.height + 8; // 8px gap between controls
129
- }
130
- return offset;
131
- }
132
-
133
- // Unregister a custom control
134
- function unregisterControl(id: string, position: string): void {
135
- const positionControls = customControlRegistryRef[position] || [];
136
- const filtered = positionControls.filter((c) => c.id !== id);
137
- if (filtered.length !== positionControls.length) {
138
- customControlRegistryRef[position] = filtered;
139
- controlRegistryVersion++;
140
- }
141
- }
142
-
143
- // Get offset for a control at a position
144
- function getCustomControlOffset(id: string, position: string): number {
145
- const positionControls = customControlRegistryRef[position] || [];
146
- let offset = 0;
147
- for (const control of positionControls) {
148
- if (control.id === id) break;
149
- offset += control.height + 8;
150
- }
151
- return offset;
152
- }
153
-
154
103
  const reducedMotion = useReducedMotion();
155
104
  const themeState = useMapTheme(() => themePref);
156
105
 
@@ -166,39 +115,6 @@
166
115
  })
167
116
  );
168
117
 
169
- // Calculate control offsets for each position
170
- // MapLibre controls are ~29px per button with ~5px margin
171
- const controlOffsets = $derived(() => {
172
- const offsets: Record<string, number> = {
173
- 'top-left': 0,
174
- 'top-right': 0,
175
- 'bottom-left': 0,
176
- 'bottom-right': 0,
177
- };
178
-
179
- // Navigation control is ~91px (3 buttons)
180
- if (navigationControl) {
181
- offsets[navigationControlPosition] += 100;
182
- }
183
-
184
- // Scale control is ~28px
185
- if (scaleControl) {
186
- offsets[scaleControlPosition] += 28;
187
- }
188
-
189
- // Fullscreen control is ~29px
190
- if (fullscreenControl) {
191
- offsets[fullscreenControlPosition] += 38;
192
- }
193
-
194
- // Geolocate control is ~29px
195
- if (geolocateControl) {
196
- offsets[geolocateControlPosition] += 38;
197
- }
198
-
199
- return offsets;
200
- });
201
-
202
118
  // Set context for child components
203
119
  setContext('maplibre-map', {
204
120
  get map() {
@@ -207,16 +123,11 @@
207
123
  get loaded() {
208
124
  return mapLoaded;
209
125
  },
210
- get controlOffsets() {
211
- return controlOffsets();
212
- },
213
126
  get styleVersion() {
214
127
  return styleVersion;
215
128
  },
216
- registerControl,
217
- unregisterControl,
218
- getCustomControlOffset,
219
129
  setMapStyle,
130
+ positioningCoordinator,
220
131
  });
221
132
 
222
133
  const combinedError = $derived(error || mapError);
@@ -252,7 +163,7 @@
252
163
  styleVersion++;
253
164
  });
254
165
 
255
- // Add controls
166
+ // Add controls and register with positioning coordinator
256
167
  if (navigationControl) {
257
168
  newMap.addControl(
258
169
  new maplibregl.NavigationControl({
@@ -262,14 +173,62 @@
262
173
  }),
263
174
  navigationControlPosition
264
175
  );
176
+ // Register with coordinator - NavigationControl is ~29x91px with visualizePitch
177
+ positioningCoordinator.register({
178
+ id: 'maplibre-navigation-control',
179
+ type: 'navigation',
180
+ isBuiltIn: true,
181
+ dimensions: { width: 29, height: 91 },
182
+ position: {
183
+ primary: navigationControlPosition as
184
+ | 'top-left'
185
+ | 'top-right'
186
+ | 'bottom-left'
187
+ | 'bottom-right',
188
+ },
189
+ priority: 'critical',
190
+ zLayer: 'base',
191
+ });
265
192
  }
266
193
 
267
194
  if (scaleControl) {
268
195
  newMap.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), scaleControlPosition);
196
+ // Register with coordinator - ScaleControl is ~100x20px
197
+ positioningCoordinator.register({
198
+ id: 'maplibre-scale-control',
199
+ type: 'scale',
200
+ isBuiltIn: true,
201
+ dimensions: { width: 100, height: 20 },
202
+ position: {
203
+ primary: scaleControlPosition as
204
+ | 'top-left'
205
+ | 'top-right'
206
+ | 'bottom-left'
207
+ | 'bottom-right',
208
+ },
209
+ priority: 'critical',
210
+ zLayer: 'base',
211
+ });
269
212
  }
270
213
 
271
214
  if (fullscreenControl) {
272
215
  newMap.addControl(new maplibregl.FullscreenControl(), fullscreenControlPosition);
216
+ // Register with coordinator - FullscreenControl is ~29x29px
217
+ positioningCoordinator.register({
218
+ id: 'maplibre-fullscreen-control',
219
+ type: 'custom',
220
+ isBuiltIn: true,
221
+ dimensions: { width: 29, height: 29 },
222
+ position: {
223
+ primary: fullscreenControlPosition as
224
+ | 'top-left'
225
+ | 'top-right'
226
+ | 'bottom-left'
227
+ | 'bottom-right',
228
+ },
229
+ priority: 'critical',
230
+ zLayer: 'base',
231
+ });
273
232
  }
274
233
 
275
234
  if (geolocateControl) {
@@ -280,6 +239,22 @@
280
239
  }),
281
240
  geolocateControlPosition
282
241
  );
242
+ // Register with coordinator - GeolocateControl is ~29x29px
243
+ positioningCoordinator.register({
244
+ id: 'maplibre-geolocate-control',
245
+ type: 'custom',
246
+ isBuiltIn: true,
247
+ dimensions: { width: 29, height: 29 },
248
+ position: {
249
+ primary: geolocateControlPosition as
250
+ | 'top-left'
251
+ | 'top-right'
252
+ | 'bottom-left'
253
+ | 'bottom-right',
254
+ },
255
+ priority: 'critical',
256
+ zLayer: 'base',
257
+ });
283
258
  }
284
259
 
285
260
  // Map load handler
@@ -439,12 +414,41 @@
439
414
  }
440
415
  });
441
416
 
417
+ // Update positioning coordinator when container resizes
418
+ let containerResizeObserver: ResizeObserver | null = null;
419
+
420
+ $effect(() => {
421
+ if (!containerElement) return;
422
+
423
+ const updateDimensions = () => {
424
+ if (!containerElement) return;
425
+ positioningCoordinator.setMapDimensions({
426
+ width: containerElement.offsetWidth,
427
+ height: containerElement.offsetHeight,
428
+ });
429
+ };
430
+
431
+ // Initial update
432
+ updateDimensions();
433
+
434
+ // Observe container size changes
435
+ containerResizeObserver = new ResizeObserver(updateDimensions);
436
+ containerResizeObserver.observe(containerElement);
437
+
438
+ return () => {
439
+ containerResizeObserver?.disconnect();
440
+ containerResizeObserver = null;
441
+ };
442
+ });
443
+
442
444
  onDestroy(() => {
443
445
  if (map) {
444
446
  map.remove();
445
447
  map = null;
446
448
  mapLoaded = false;
447
449
  }
450
+ containerResizeObserver?.disconnect();
451
+ positioningCoordinator.destroy();
448
452
  });
449
453
  </script>
450
454
 
@@ -1,3 +1,4 @@
1
1
  export { useMapTheme } from './useMapTheme.svelte.js';
2
2
  export { useReducedMotion } from './useReducedMotion.svelte.js';
3
3
  export { useMapContext, tryUseMapContext, type MapContextValue } from './useMapContext.svelte.js';
4
+ export { useControlPosition, type UseControlPositionOptions, type UseControlPositionResult, } from './useControlPosition.svelte.js';
@@ -1,3 +1,4 @@
1
1
  export { useMapTheme } from './useMapTheme.svelte.js';
2
2
  export { useReducedMotion } from './useReducedMotion.svelte.js';
3
3
  export { useMapContext, tryUseMapContext } from './useMapContext.svelte.js';
4
+ export { useControlPosition, } from './useControlPosition.svelte.js';
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Composable for registering a control with the positioning coordinator
3
+ *
4
+ * This composable handles auto-registration on mount, dimension updates
5
+ * via ResizeObserver, and cleanup on unmount.
6
+ */
7
+ import type { ControlOffset, ControlPriority, ControlType, ExtendedControlPosition, ZIndexLayer } from '@classic-homes/maps-core';
8
+ /**
9
+ * Options for useControlPosition composable
10
+ */
11
+ export interface UseControlPositionOptions {
12
+ /** Unique identifier for the control instance */
13
+ id: string;
14
+ /** Type of control */
15
+ type: ControlType;
16
+ /** Primary position for the control */
17
+ position: ExtendedControlPosition;
18
+ /** Fallback positions to try if primary is occupied */
19
+ fallbacks?: ExtendedControlPosition[];
20
+ /** Priority level for collision resolution (default: 'normal') */
21
+ priority?: ControlPriority;
22
+ /** Z-index layer (default: 'interactive') */
23
+ zLayer?: ZIndexLayer;
24
+ /** Whether the control has an expanded state */
25
+ hasExpandedState?: boolean;
26
+ /** Whether the control is a built-in MapLibre control */
27
+ isBuiltIn?: boolean;
28
+ }
29
+ /**
30
+ * Return value from useControlPosition composable
31
+ */
32
+ export interface UseControlPositionResult {
33
+ /** Current computed offset and position (reactive) */
34
+ readonly offset: ControlOffset | null;
35
+ /** Update the expanded state */
36
+ setExpanded: (isExpanded: boolean) => void;
37
+ /** CSS style string to apply to the control */
38
+ readonly style: string;
39
+ /** Whether the control should be visible */
40
+ readonly visible: boolean;
41
+ /** Whether the coordinator is available */
42
+ readonly hasCoordinator: boolean;
43
+ }
44
+ /**
45
+ * Create a control position manager using the positioning coordinator
46
+ *
47
+ * @param getElement - Function that returns the control element (use a getter for reactivity)
48
+ * @param options - Control registration options
49
+ * @returns Position offset, visibility, and style to apply
50
+ *
51
+ * @example
52
+ * ```svelte
53
+ * <script lang="ts">
54
+ * import { useControlPosition } from '../composables/useControlPosition.svelte.js';
55
+ *
56
+ * let legendElement: HTMLDivElement;
57
+ * const legendId = `legend-${Math.random().toString(36).slice(2, 9)}`;
58
+ *
59
+ * const controlPosition = useControlPosition(
60
+ * () => legendElement,
61
+ * {
62
+ * id: legendId,
63
+ * type: 'legend',
64
+ * position: 'bottom-left',
65
+ * priority: 'normal',
66
+ * }
67
+ * );
68
+ * </script>
69
+ *
70
+ * <div bind:this={legendElement} style={controlPosition.style} hidden={!controlPosition.visible}>
71
+ * ...
72
+ * </div>
73
+ * ```
74
+ */
75
+ export declare function useControlPosition(getElement: () => HTMLElement | undefined, options: UseControlPositionOptions): UseControlPositionResult;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Composable for registering a control with the positioning coordinator
3
+ *
4
+ * This composable handles auto-registration on mount, dimension updates
5
+ * via ResizeObserver, and cleanup on unmount.
6
+ */
7
+ import { onDestroy, untrack } from 'svelte';
8
+ import { tryUseMapContext } from './useMapContext.svelte.js';
9
+ /**
10
+ * Create a control position manager using the positioning coordinator
11
+ *
12
+ * @param getElement - Function that returns the control element (use a getter for reactivity)
13
+ * @param options - Control registration options
14
+ * @returns Position offset, visibility, and style to apply
15
+ *
16
+ * @example
17
+ * ```svelte
18
+ * <script lang="ts">
19
+ * import { useControlPosition } from '../composables/useControlPosition.svelte.js';
20
+ *
21
+ * let legendElement: HTMLDivElement;
22
+ * const legendId = `legend-${Math.random().toString(36).slice(2, 9)}`;
23
+ *
24
+ * const controlPosition = useControlPosition(
25
+ * () => legendElement,
26
+ * {
27
+ * id: legendId,
28
+ * type: 'legend',
29
+ * position: 'bottom-left',
30
+ * priority: 'normal',
31
+ * }
32
+ * );
33
+ * </script>
34
+ *
35
+ * <div bind:this={legendElement} style={controlPosition.style} hidden={!controlPosition.visible}>
36
+ * ...
37
+ * </div>
38
+ * ```
39
+ */
40
+ export function useControlPosition(getElement, options) {
41
+ const { id, type, position, fallbacks, priority = 'normal', zLayer = 'interactive', hasExpandedState = false, isBuiltIn = false, } = options;
42
+ const mapContext = tryUseMapContext();
43
+ const coordinator = mapContext
44
+ ?.positioningCoordinator;
45
+ // Reactive state
46
+ let offset = $state(null);
47
+ let registered = $state(false);
48
+ let resizeObserver = null;
49
+ let unsubscribe = null;
50
+ // Compute style from offset
51
+ const style = $derived(() => {
52
+ if (!offset) {
53
+ return 'position: absolute; visibility: hidden;';
54
+ }
55
+ const resolvedPosition = offset.position;
56
+ const isLeftPosition = resolvedPosition.includes('left') || resolvedPosition.includes('center');
57
+ const isCenterHorizontal = resolvedPosition.includes('center');
58
+ const styles = ['position: absolute', `z-index: ${offset.zIndex}`];
59
+ // Apply horizontal positioning
60
+ if (isCenterHorizontal) {
61
+ styles.push(`left: ${offset.x}px`);
62
+ }
63
+ else if (isLeftPosition) {
64
+ styles.push(`left: ${offset.x}px`);
65
+ }
66
+ else {
67
+ styles.push(`right: ${offset.x}px`);
68
+ }
69
+ // Apply vertical positioning
70
+ if (resolvedPosition.startsWith('bottom')) {
71
+ styles.push(`bottom: ${offset.y}px`);
72
+ }
73
+ else {
74
+ styles.push(`top: ${offset.y}px`);
75
+ }
76
+ return styles.join('; ');
77
+ });
78
+ const visible = $derived(offset?.visible ?? false);
79
+ const hasCoordinator = !!coordinator;
80
+ // Register with coordinator
81
+ $effect(() => {
82
+ if (!coordinator)
83
+ return;
84
+ const element = getElement();
85
+ if (!element)
86
+ return;
87
+ // Initial registration
88
+ if (!registered) {
89
+ untrack(() => {
90
+ const initialOffset = coordinator.register({
91
+ id,
92
+ type,
93
+ isBuiltIn,
94
+ dimensions: {
95
+ width: element.offsetWidth || 200,
96
+ height: element.offsetHeight || 100,
97
+ },
98
+ position: {
99
+ primary: position,
100
+ fallbacks,
101
+ },
102
+ priority,
103
+ zLayer,
104
+ hasExpandedState,
105
+ isExpanded: false,
106
+ });
107
+ offset = initialOffset;
108
+ registered = true;
109
+ });
110
+ // Subscribe to coordinator events
111
+ unsubscribe = coordinator.subscribe((event) => {
112
+ const newOffset = event.offsets.get(id);
113
+ if (newOffset) {
114
+ offset = newOffset;
115
+ }
116
+ });
117
+ // Observe dimension changes
118
+ resizeObserver = new ResizeObserver(() => {
119
+ const el = getElement();
120
+ if (!el)
121
+ return;
122
+ coordinator.update(id, {
123
+ dimensions: {
124
+ width: el.offsetWidth,
125
+ height: el.offsetHeight,
126
+ },
127
+ });
128
+ });
129
+ resizeObserver.observe(element);
130
+ }
131
+ });
132
+ // Update position configuration when options change
133
+ $effect(() => {
134
+ if (!coordinator || !registered)
135
+ return;
136
+ // 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;
141
+ untrack(() => {
142
+ coordinator.update(id, {
143
+ position: {
144
+ primary: _position,
145
+ fallbacks: _fallbacks,
146
+ },
147
+ priority: _priority,
148
+ zLayer: _zLayer,
149
+ });
150
+ });
151
+ });
152
+ // Setter for expanded state
153
+ function setExpanded(isExpanded) {
154
+ if (coordinator) {
155
+ coordinator.setExpanded(id, isExpanded);
156
+ }
157
+ }
158
+ // Cleanup on destroy
159
+ onDestroy(() => {
160
+ resizeObserver?.disconnect();
161
+ unsubscribe?.();
162
+ if (coordinator && registered) {
163
+ coordinator.unregister(id);
164
+ }
165
+ });
166
+ return {
167
+ get offset() {
168
+ return offset;
169
+ },
170
+ setExpanded,
171
+ get style() {
172
+ return style();
173
+ },
174
+ get visible() {
175
+ return visible;
176
+ },
177
+ hasCoordinator,
178
+ };
179
+ }
@@ -6,6 +6,7 @@
6
6
  * advanced operations like cluster expansion.
7
7
  */
8
8
  import type maplibregl from 'maplibre-gl';
9
+ import type { PositioningCoordinator } from '@classic-homes/maps-core';
9
10
  /**
10
11
  * Map context interface provided by the Map component
11
12
  */
@@ -14,18 +15,12 @@ export interface MapContextValue {
14
15
  readonly map: maplibregl.Map | null;
15
16
  /** Whether the map has finished loading */
16
17
  readonly loaded: boolean;
17
- /** Computed control offsets for positioning custom controls */
18
- readonly controlOffsets?: Record<string, number>;
19
- /** Register a custom control for offset coordination */
20
- registerControl?: (id: string, position: string, height: number) => number;
21
- /** Unregister a custom control */
22
- unregisterControl?: (id: string, position: string) => void;
23
- /** Get the offset for a specific custom control */
24
- getCustomControlOffset?: (id: string, position: string) => number;
25
18
  /** Counter incremented on each style.load event, used to re-initialize sources/layers */
26
19
  readonly styleVersion: number;
27
20
  /** Set the map style programmatically (e.g. basemap switching) */
28
21
  setMapStyle?: (style: string | maplibregl.StyleSpecification) => void;
22
+ /** Positioning coordinator for centralized control positioning */
23
+ positioningCoordinator: PositioningCoordinator;
29
24
  }
30
25
  /**
31
26
  * Get the map context from a parent Map component
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/maps-svelte",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Svelte MapLibre components for Classic Theme",
5
5
  "keywords": [
6
6
  "maps",