maplibre-gl-layer-control 0.18.3 → 0.19.1
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.
- package/README.md +21 -0
- package/dist/{LayerControl-BVcYNnJ3.cjs → LayerControl-2Gi-t4dS.cjs} +165 -7
- package/dist/LayerControl-2Gi-t4dS.cjs.map +1 -0
- package/dist/{LayerControl-dS3dARlw.js → LayerControl-Ccyj0y-D.js} +165 -7
- package/dist/LayerControl-Ccyj0y-D.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/react.cjs +1 -1
- package/dist/react.mjs +1 -1
- package/dist/types/index.d.ts +78 -4
- package/dist/types/react.d.ts +9 -0
- package/package.json +1 -1
- package/dist/LayerControl-BVcYNnJ3.cjs.map +0 -1
- package/dist/LayerControl-dS3dARlw.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"LayerControl-Ccyj0y-D.js","sources":["../src/lib/core/CustomLayerRegistry.ts","../src/lib/utils/layerUtils.ts","../src/lib/utils/styleCache.ts","../node_modules/colord/index.mjs","../node_modules/colord/plugins/names.mjs","../src/lib/utils/colorUtils.ts","../src/lib/utils/formatters.ts","../src/lib/utils/styleProperties.ts","../src/lib/utils/symbolUtils.ts","../src/lib/core/LayerControl.ts"],"sourcesContent":["import type { CustomLayerAdapter, LayerGroupState, LayerState } from './types';\n\n/**\n * Registry for managing custom layer adapters.\n * Routes layer operations to the appropriate adapter based on layer ID.\n */\nexport class CustomLayerRegistry {\n private adapters: Map<string, CustomLayerAdapter> = new Map();\n private changeListeners: Array<(event: 'add' | 'remove', layerId: string) => void> = [];\n private unsubscribers: Map<string, () => void> = new Map();\n\n /**\n * Register a custom layer adapter.\n * @param adapter The adapter to register\n */\n register(adapter: CustomLayerAdapter): void {\n this.adapters.set(adapter.type, adapter);\n\n // Subscribe to adapter's layer changes if supported\n if (adapter.onLayerChange) {\n const unsubscribe = adapter.onLayerChange((event, layerId) => {\n this.notifyChange(event, layerId);\n });\n this.unsubscribers.set(adapter.type, unsubscribe);\n }\n }\n\n /**\n * Unregister an adapter by type.\n * @param type The adapter type to unregister\n */\n unregister(type: string): void {\n // Clean up the subscription for this adapter\n const unsubscribe = this.unsubscribers.get(type);\n if (unsubscribe) {\n unsubscribe();\n this.unsubscribers.delete(type);\n }\n this.adapters.delete(type);\n }\n\n /**\n * Get all custom layer IDs across all adapters.\n * @returns Array of layer IDs\n */\n getAllLayerIds(): string[] {\n const ids: string[] = [];\n this.adapters.forEach(adapter => {\n ids.push(...adapter.getLayerIds());\n });\n return ids;\n }\n\n /**\n * Get each adapter's layer IDs as a separate list, in adapter order.\n * @returns One array of layer IDs per registered adapter\n */\n getLayerIdGroups(): string[][] {\n return Array.from(this.adapters.values(), (adapter) => adapter.getLayerIds());\n }\n\n /**\n * Check if a layer ID is managed by any adapter.\n * @param layerId The layer ID to check\n * @returns true if the layer is managed by an adapter\n */\n hasLayer(layerId: string): boolean {\n for (const adapter of this.adapters.values()) {\n if (adapter.getLayerIds().includes(layerId)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the adapter responsible for a specific layer.\n * @param layerId The layer ID\n * @returns The adapter or null if not found\n */\n getAdapterForLayer(layerId: string): CustomLayerAdapter | null {\n for (const adapter of this.adapters.values()) {\n if (adapter.getLayerIds().includes(layerId)) {\n return adapter;\n }\n }\n return null;\n }\n\n /**\n * Get the state of a custom layer.\n * @param layerId The layer ID\n * @returns The layer state or null if not found\n */\n getLayerState(layerId: string): LayerState | null {\n const adapter = this.getAdapterForLayer(layerId);\n return adapter ? adapter.getLayerState(layerId) : null;\n }\n\n /**\n * Set visibility of a custom layer.\n * @param layerId The layer ID\n * @param visible Whether the layer should be visible\n * @returns true if the operation was handled by an adapter\n */\n setVisibility(layerId: string, visible: boolean): boolean {\n const adapter = this.getAdapterForLayer(layerId);\n if (adapter) {\n adapter.setVisibility(layerId, visible);\n return true;\n }\n return false;\n }\n\n /**\n * Set opacity of a custom layer.\n * @param layerId The layer ID\n * @param opacity The opacity value (0-1)\n * @returns true if the operation was handled by an adapter\n */\n setOpacity(layerId: string, opacity: number): boolean {\n const adapter = this.getAdapterForLayer(layerId);\n if (adapter) {\n adapter.setOpacity(layerId, opacity);\n return true;\n }\n return false;\n }\n\n /**\n * Get the symbol type for a custom layer (for UI display).\n * @param layerId The layer ID\n * @returns The symbol type or null if not available\n */\n getSymbolType(layerId: string): string | null {\n const adapter = this.getAdapterForLayer(layerId);\n if (adapter && adapter.getSymbolType) {\n return adapter.getSymbolType(layerId);\n }\n return null;\n }\n\n /**\n * Get the bounds of a custom layer (for zoom-to-layer).\n * @param layerId The layer ID\n * @returns The bounds [west, south, east, north] or null if not available\n */\n getBounds(layerId: string): [number, number, number, number] | null {\n const adapter = this.getAdapterForLayer(layerId);\n if (adapter && adapter.getBounds) {\n return adapter.getBounds(layerId);\n }\n return null;\n }\n\n /**\n * Get native MapLibre layer IDs for a custom layer.\n * @param layerId The custom layer ID\n * @returns Array of native layer IDs, or null if not available\n */\n getNativeLayerIds(layerId: string): string[] | null {\n const adapter = this.getAdapterForLayer(layerId);\n if (adapter && adapter.getNativeLayerIds) {\n return adapter.getNativeLayerIds(layerId);\n }\n return null;\n }\n\n /**\n * Remove a custom layer through its adapter.\n * @param layerId The layer ID to remove\n * @returns true if the operation was handled by an adapter\n */\n removeLayer(layerId: string): boolean {\n const adapter = this.getAdapterForLayer(layerId);\n if (adapter && adapter.removeLayer) {\n adapter.removeLayer(layerId);\n return true;\n }\n return false;\n }\n\n /**\n * Get the layer groups of every adapter. When two adapters define the same\n * group ID, the first registered adapter's group wins.\n * @returns The groups, in adapter order\n */\n getGroups(): LayerGroupState[] {\n const groups: LayerGroupState[] = [];\n const seen = new Set<string>();\n this.adapters.forEach(adapter => {\n for (const group of adapter.getGroups?.() ?? []) {\n if (seen.has(group.id)) continue;\n seen.add(group.id);\n groups.push(group);\n }\n });\n return groups;\n }\n\n /**\n * Get the ID of the group a custom layer belongs to.\n * @param layerId The layer ID\n * @returns The group ID, or undefined when the layer is ungrouped\n */\n getLayerGroupId(layerId: string): string | undefined {\n const adapter = this.getAdapterForLayer(layerId);\n return adapter?.getLayerGroupId?.(layerId);\n }\n\n /**\n * Get the adapter that defines a group.\n * @param groupId The group ID\n * @returns The adapter or null if no adapter defines the group\n */\n private getAdapterForGroup(groupId: string): CustomLayerAdapter | null {\n for (const adapter of this.adapters.values()) {\n if (adapter.getGroups?.().some(group => group.id === groupId)) {\n return adapter;\n }\n }\n return null;\n }\n\n /**\n * Set visibility of a group.\n * @param groupId The group ID\n * @param visible Whether the group should be visible\n * @returns true if the operation was handled by an adapter\n */\n setGroupVisibility(groupId: string, visible: boolean): boolean {\n const adapter = this.getAdapterForGroup(groupId);\n if (adapter?.setGroupVisibility) {\n adapter.setGroupVisibility(groupId, visible);\n return true;\n }\n return false;\n }\n\n /**\n * Set opacity of a group.\n * @param groupId The group ID\n * @param opacity The opacity value (0-1)\n * @returns true if the operation was handled by an adapter\n */\n setGroupOpacity(groupId: string, opacity: number): boolean {\n const adapter = this.getAdapterForGroup(groupId);\n if (adapter?.setGroupOpacity) {\n adapter.setGroupOpacity(groupId, opacity);\n return true;\n }\n return false;\n }\n\n /**\n * Record that a group was collapsed or expanded.\n * @param groupId The group ID\n * @param collapsed Whether the group is now collapsed\n * @returns true if the operation was handled by an adapter\n */\n setGroupCollapsed(groupId: string, collapsed: boolean): boolean {\n const adapter = this.getAdapterForGroup(groupId);\n if (adapter?.setGroupCollapsed) {\n adapter.setGroupCollapsed(groupId, collapsed);\n return true;\n }\n return false;\n }\n\n /**\n * Subscribe to layer changes across all adapters.\n * @param callback Function called when layers are added or removed\n * @returns Unsubscribe function\n */\n onChange(callback: (event: 'add' | 'remove', layerId: string) => void): () => void {\n this.changeListeners.push(callback);\n return () => {\n const idx = this.changeListeners.indexOf(callback);\n if (idx >= 0) {\n this.changeListeners.splice(idx, 1);\n }\n };\n }\n\n private notifyChange(event: 'add' | 'remove', layerId: string): void {\n this.changeListeners.forEach(cb => cb(event, layerId));\n }\n\n /**\n * Clean up all subscriptions and adapters.\n */\n destroy(): void {\n this.unsubscribers.forEach(unsub => unsub());\n this.unsubscribers.clear();\n this.adapters.clear();\n this.changeListeners = [];\n }\n}\n","import type { Map as MapLibreMap, AllPaintProperties } from 'maplibre-gl';\nimport type { StyleableLayerType } from '../core/types';\n\n/**\n * Get the opacity property name for a given layer type\n * Supports all MapLibre layer types: fill, line, symbol, circle, heatmap,\n * fill-extrusion, raster, hillshade, color-relief, background\n * @param layerType MapLibre layer type\n * @returns Opacity property name(s), or null if the layer type doesn't support opacity\n */\nexport function getOpacityProperty(layerType: string): string | string[] | null {\n switch (layerType) {\n case 'fill':\n return 'fill-opacity';\n case 'line':\n return 'line-opacity';\n case 'circle':\n return 'circle-opacity';\n case 'symbol':\n // Symbol layers have both icon and text opacity\n return ['icon-opacity', 'text-opacity'];\n case 'raster':\n return 'raster-opacity';\n case 'background':\n return 'background-opacity';\n case 'heatmap':\n return 'heatmap-opacity';\n case 'fill-extrusion':\n return 'fill-extrusion-opacity';\n case 'hillshade':\n // Hillshade uses exaggeration for intensity, not opacity\n return 'hillshade-exaggeration';\n case 'color-relief':\n // Color-relief doesn't have a standard opacity property\n return null;\n default:\n // For custom layer types, try the standard pattern\n return `${layerType}-opacity`;\n }\n}\n\n/**\n * Get the current opacity value for a layer\n * @param map MapLibre map instance\n * @param layerId Layer ID\n * @param layerType Layer type\n * @returns Current opacity value (0-1), or 1.0 if the layer type doesn't support opacity\n */\nexport function getLayerOpacity(\n map: MapLibreMap,\n layerId: string,\n layerType: string\n): number {\n const opacityProp = getOpacityProperty(layerType);\n\n // Layer type doesn't support opacity\n if (opacityProp === null) {\n return 1.0;\n }\n\n if (Array.isArray(opacityProp)) {\n // For symbol layers, use icon-opacity as the primary value\n const opacity = map.getPaintProperty(layerId, opacityProp[0] as keyof AllPaintProperties);\n return (opacity !== undefined && opacity !== null) ? opacity as number : 1.0;\n }\n\n const opacity = map.getPaintProperty(layerId, opacityProp as keyof AllPaintProperties);\n return (opacity !== undefined && opacity !== null) ? opacity as number : 1.0;\n}\n\n/**\n * Set the opacity for a layer\n * @param map MapLibre map instance\n * @param layerId Layer ID\n * @param layerType Layer type\n * @param opacity Opacity value (0-1)\n */\nexport function setLayerOpacity(\n map: MapLibreMap,\n layerId: string,\n layerType: string,\n opacity: number\n): void {\n const opacityProp = getOpacityProperty(layerType);\n\n // Layer type doesn't support opacity\n if (opacityProp === null) {\n return;\n }\n\n if (Array.isArray(opacityProp)) {\n // For symbol layers, set both icon and text opacity\n opacityProp.forEach((prop) => {\n map.setPaintProperty(layerId, prop as keyof AllPaintProperties, opacity);\n });\n } else {\n map.setPaintProperty(layerId, opacityProp as keyof AllPaintProperties, opacity);\n }\n}\n\n/**\n * Check if a layer type supports style editing\n * @param layerType Layer type\n * @returns True if the layer type supports style editing\n */\nexport function isStyleableLayerType(layerType: string): layerType is StyleableLayerType {\n return [\n 'fill',\n 'line',\n 'circle',\n 'symbol',\n 'raster',\n 'heatmap',\n 'fill-extrusion',\n 'hillshade',\n ].includes(layerType);\n}\n\n/**\n * Get layer type from map\n * @param map MapLibre map instance\n * @param layerId Layer ID\n * @returns Layer type or null if layer not found\n */\nexport function getLayerType(map: MapLibreMap, layerId: string): string | null {\n try {\n const layer = map.getLayer(layerId);\n return layer ? layer.type : null;\n } catch (error) {\n console.warn(`Failed to get layer type for ${layerId}:`, error);\n return null;\n }\n}\n","import type { Map as MapLibreMap, AllPaintProperties } from 'maplibre-gl';\nimport type { OriginalStyle } from '../core/types';\n\n/**\n * Deep clone a paint value (handles complex MapLibre expressions)\n * @param value Paint value to clone\n * @returns Cloned value\n */\nexport function clonePaintValue(value: any): any {\n if (Array.isArray(value)) {\n return value.map((item) => clonePaintValue(item));\n }\n if (value && typeof value === 'object') {\n try {\n return JSON.parse(JSON.stringify(value));\n } catch (error) {\n return value;\n }\n }\n return value;\n}\n\n/**\n * Cache the original paint properties for a layer\n * @param map MapLibre map instance\n * @param layerId Layer ID\n * @param originalStyles Map to store original styles\n */\nexport function cacheOriginalLayerStyle(\n map: MapLibreMap,\n layerId: string,\n originalStyles: Map<string, OriginalStyle>\n): void {\n if (originalStyles.has(layerId)) {\n return; // Already cached\n }\n\n try {\n const layer = map.getLayer(layerId);\n if (!layer) {\n return;\n }\n\n const paint: Record<string, any> = {};\n const style = map.getStyle();\n const layerDef = style.layers?.find(l => l.id === layerId);\n\n // For raster layers, handle all properties with defaults\n if (layer.type === 'raster') {\n // Default values from MapLibre GL spec\n const rasterDefaults: Record<string, number> = {\n 'raster-opacity': 1,\n 'raster-brightness-min': 0,\n 'raster-brightness-max': 1,\n 'raster-saturation': 0,\n 'raster-contrast': 0,\n 'raster-hue-rotate': 0\n };\n\n // Start with defaults\n Object.assign(paint, rasterDefaults);\n\n // Override with values from layer definition\n if (layerDef && 'paint' in layerDef && layerDef.paint) {\n Object.entries(layerDef.paint).forEach(([prop, value]) => {\n if (prop.startsWith('raster-')) {\n paint[prop] = clonePaintValue(value);\n }\n });\n }\n } else {\n // For non-raster layers, just get values from the layer definition\n if (layerDef && 'paint' in layerDef && layerDef.paint) {\n Object.entries(layerDef.paint).forEach(([prop, value]) => {\n paint[prop] = clonePaintValue(value);\n });\n }\n }\n\n originalStyles.set(layerId, { paint });\n } catch (error) {\n console.warn(`Failed to cache original style for ${layerId}:`, error);\n }\n}\n\n/**\n * Get the current value of a paint property\n * @param map MapLibre map instance\n * @param layerId Layer ID\n * @param property Property name\n * @param fallback Fallback value if property is not set\n * @returns Current property value\n */\nexport function getCurrentPaintValue(\n map: MapLibreMap,\n layerId: string,\n property: string,\n fallback?: any\n): any {\n try {\n const value = map.getPaintProperty(layerId, property as keyof AllPaintProperties);\n return value !== undefined ? value : fallback;\n } catch (error) {\n return fallback;\n }\n}\n\n/**\n * Restore original paint properties for a layer\n * @param map MapLibre map instance\n * @param layerId Layer ID\n * @param originalStyles Map of original styles\n * @returns Object with restored properties\n */\nexport function restoreOriginalStyle(\n map: MapLibreMap,\n layerId: string,\n originalStyles: Map<string, OriginalStyle>\n): Record<string, any> {\n const original = originalStyles.get(layerId);\n if (!original) {\n return {};\n }\n\n const applied: Record<string, any> = {};\n\n Object.entries(original.paint).forEach(([property, value]) => {\n try {\n const restoredValue = clonePaintValue(value);\n map.setPaintProperty(layerId, property as keyof AllPaintProperties, restoredValue);\n applied[property] = restoredValue;\n } catch (error) {\n console.warn(`Failed to restore ${property} for ${layerId}:`, error);\n }\n });\n\n if (\n !('fill-pattern' in original.paint) &&\n typeof map.getLayer === 'function' &&\n map.getLayer(layerId)?.type === 'fill'\n ) {\n try {\n map.setPaintProperty(layerId, 'fill-pattern', undefined);\n applied['fill-pattern'] = undefined;\n } catch (error) {\n console.warn(`Failed to restore fill-pattern for ${layerId}:`, error);\n }\n }\n\n return applied;\n}\n","for(var r={grad:.9,turn:360,rad:360/(2*Math.PI)},t=function(r){return\"string\"==typeof r?r.length>0:\"number\"==typeof r},n=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=Math.pow(10,t)),Math.round(n*r)/n+0},u=function(r,t,n){return void 0===t&&(t=0),void 0===n&&(n=1),r>n?n:r>t?r:t},e=function(r){return(r=isFinite(r)?r%360:0)<0?r+360:r},o=function(r,t){return void 0===t&&(t=0),n(r,t)%360},a=function(r){return{r:u(r.r,0,255),g:u(r.g,0,255),b:u(r.b,0,255),a:u(r.a)}},i=function(r){return{r:n(r.r),g:n(r.g),b:n(r.b),a:n(r.a,3)}},s=/^#([0-9a-f]{3,8})$/i,d=function(r,t){var n=r.charCodeAt(t);return(15&n)+9*(n>>6)},h=function(r,t){return d(r,t)<<4|d(r,t+1)},b=[],f=0;f<256;f++)b.push((f<16?\"0\":\"\")+f.toString(16));var g=function(r){return b[u(r,0,255)]},c=function(r){var t=r.r,n=r.g,u=r.b,e=r.a,o=Math.max(t,n,u),a=o-Math.min(t,n,u),i=a?o===t?(n-u)/a:o===n?2+(u-t)/a:4+(t-n)/a:0;return{h:60*(i<0?i+6:i),s:o?a/o*100:0,v:o/255*100,a:e}},v=function(r){var t=r.h,n=r.s,u=r.v,e=r.a;t=t/360*6,n/=100,u/=100;var o=Math.floor(t),a=u*(1-n),i=u*(1-(t-o)*n),s=u*(1-(1-t+o)*n),d=o%6;return{r:255*[u,i,a,a,s,u][d],g:255*[s,u,u,i,a,a][d],b:255*[a,a,s,u,u,i][d],a:e}},l=function(r){return{h:e(r.h),s:u(r.s,0,100),l:u(r.l,0,100),a:u(r.a)}},p=function(r){return{h:o(r.h),s:n(r.s),l:n(r.l),a:n(r.a,3)}},m=function(r){return v((n=(t=r).s,{h:t.h,s:(n*=((u=t.l)<50?u:100-u)/100)>0?2*n/(u+n)*100:0,v:u+n,a:t.a}));var t,n,u},y=function(r){return{h:(t=c(r)).h,s:(e=(200-(n=t.s))*(u=t.v)/100)>0&&e<200?n*u/100/(e<=100?e:200-e)*100:0,l:e/2,a:t.a};var t,n,u,e},N=/^hsla?\\(\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(deg|rad|grad|turn)?\\s*,\\s*([+-]?(?:\\d*\\.\\d+|\\d+))%\\s*,\\s*([+-]?(?:\\d*\\.\\d+|\\d+))%\\s*(?:,\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*)?\\)$/i,x=/^hsla?\\(\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(deg|rad|grad|turn)?\\s+([+-]?(?:\\d*\\.\\d+|\\d+))%\\s+([+-]?(?:\\d*\\.\\d+|\\d+))%\\s*(?:\\/\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*)?\\)$/i,M=/^rgba?\\(\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*,\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*,\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*(?:,\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*)?\\)$/i,H=/^rgba?\\(\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s+([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s+([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*(?:\\/\\s*([+-]?(?:\\d*\\.\\d+|\\d+))(%)?\\s*)?\\)$/i,$={string:[[function(r){if(!s.test(r))return null;var t=r.length;return t<=5?{r:17*d(r,1),g:17*d(r,2),b:17*d(r,3),a:5===t?n(17*d(r,4)/255,2):1}:7===t||9===t?{r:h(r,1),g:h(r,3),b:h(r,5),a:9===t?n(h(r,7)/255,2):1}:null},\"hex\"],[function(r){var t=M.exec(r)||H.exec(r);return t?t[2]!==t[4]||t[4]!==t[6]?null:a({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:void 0===t[7]?1:Number(t[7])/(t[8]?100:1)}):null},\"rgb\"],[function(t){var n=N.exec(t)||x.exec(t);if(!n)return null;var u,e,o=l({h:(u=n[1],e=n[2],void 0===e&&(e=\"deg\"),Number(u)*(r[e]||1)),s:Number(n[3]),l:Number(n[4]),a:void 0===n[5]?1:Number(n[5])/(n[6]?100:1)});return m(o)},\"hsl\"]],object:[[function(r){var n=r.r,u=r.g,e=r.b,o=r.a,i=void 0===o?1:o;return t(n)&&t(u)&&t(e)?a({r:Number(n),g:Number(u),b:Number(e),a:Number(i)}):null},\"rgb\"],[function(r){var n=r.h,u=r.s,e=r.l,o=r.a,a=void 0===o?1:o;if(!t(n)||!t(u)||!t(e))return null;var i=l({h:Number(n),s:Number(u),l:Number(e),a:Number(a)});return m(i)},\"hsl\"],[function(r){var n=r.h,o=r.s,a=r.v,i=r.a,s=void 0===i?1:i;if(!t(n)||!t(o)||!t(a))return null;var d=function(r){return{h:e(r.h),s:u(r.s,0,100),v:u(r.v,0,100),a:u(r.a)}}({h:Number(n),s:Number(o),v:Number(a),a:Number(s)});return v(d)},\"hsv\"]]},j=function(r,t){for(var n=0;n<t.length;n++){var u=t[n][0](r);if(u)return[u,t[n][1]]}return[null,void 0]},w=function(r){return\"string\"==typeof r?j(r.trim(),$.string):\"object\"==typeof r&&null!==r?j(r,$.object):[null,void 0]},S=function(r){return w(r)[1]},k=function(r,t){var n=y(r);return{h:n.h,s:u(n.s+100*t,0,100),l:n.l,a:n.a}},E=function(r){return(299*r.r+587*r.g+114*r.b)/1e3/255},R=function(r,t){var n=y(r);return{h:n.h,s:n.s,l:u(n.l+100*t,0,100),a:n.a}},q=function(){function r(r){this.parsed=w(r)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return r.prototype.isValid=function(){return null!==this.parsed},r.prototype.brightness=function(){return n(E(this.rgba),2)},r.prototype.isDark=function(){return E(this.rgba)<.5},r.prototype.isLight=function(){return E(this.rgba)>=.5},r.prototype.toHex=function(){return r=i(this.rgba),t=r.r,u=r.g,e=r.b,a=(o=r.a)<1?g(n(255*o)):\"\",\"#\"+g(t)+g(u)+g(e)+a;var r,t,u,e,o,a},r.prototype.toRgb=function(){return i(this.rgba)},r.prototype.toRgbString=function(){return r=i(this.rgba),t=r.r,n=r.g,u=r.b,(e=r.a)<1?\"rgba(\"+t+\", \"+n+\", \"+u+\", \"+e+\")\":\"rgb(\"+t+\", \"+n+\", \"+u+\")\";var r,t,n,u,e},r.prototype.toHsl=function(){return p(y(this.rgba))},r.prototype.toHslString=function(){return r=p(y(this.rgba)),t=r.h,n=r.s,u=r.l,(e=r.a)<1?\"hsla(\"+t+\", \"+n+\"%, \"+u+\"%, \"+e+\")\":\"hsl(\"+t+\", \"+n+\"%, \"+u+\"%)\";var r,t,n,u,e},r.prototype.toHsv=function(){return r=c(this.rgba),{h:o(r.h),s:n(r.s),v:n(r.v),a:n(r.a,3)};var r},r.prototype.invert=function(){return A({r:255-(r=this.rgba).r,g:255-r.g,b:255-r.b,a:r.a});var r},r.prototype.saturate=function(r){return void 0===r&&(r=.1),A(k(this.rgba,r))},r.prototype.desaturate=function(r){return void 0===r&&(r=.1),A(k(this.rgba,-r))},r.prototype.grayscale=function(){return A(k(this.rgba,-1))},r.prototype.lighten=function(r){return void 0===r&&(r=.1),A(R(this.rgba,r))},r.prototype.darken=function(r){return void 0===r&&(r=.1),A(R(this.rgba,-r))},r.prototype.rotate=function(r){return void 0===r&&(r=15),this.hue(y(this.rgba).h+r)},r.prototype.alpha=function(r){return\"number\"==typeof r?A({r:(t=this.rgba).r,g:t.g,b:t.b,a:r}):n(this.rgba.a,3);var t},r.prototype.hue=function(r){var t=y(this.rgba);return\"number\"==typeof r?A({h:r,s:t.s,l:t.l,a:t.a}):o(t.h)},r.prototype.isEqual=function(r){return this.toHex()===A(r).toHex()},r}(),A=function(r){return r instanceof q?r:new q(r)},C=[],D=function(r){r.forEach(function(r){C.indexOf(r)<0&&(r(q,$),C.push(r))})},F=function(){return new q({r:255*Math.random(),g:255*Math.random(),b:255*Math.random()})};export{q as Colord,A as colord,D as extend,S as getFormat,F as random};\n","var e=function(e,f){var a={white:\"#ffffff\",bisque:\"#ffe4c4\",blue:\"#0000ff\",cadetblue:\"#5f9ea0\",chartreuse:\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f50\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\",azure:\"#f0ffff\",whitesmoke:\"#f5f5f5\",papayawhip:\"#ffefd5\",plum:\"#dda0dd\",blanchedalmond:\"#ffebcd\",black:\"#000000\",gold:\"#ffd700\",goldenrod:\"#daa520\",gainsboro:\"#dcdcdc\",cornsilk:\"#fff8dc\",cornflowerblue:\"#6495ed\",burlywood:\"#deb887\",aquamarine:\"#7fffd4\",beige:\"#f5f5dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkkhaki:\"#bdb76b\",darkgray:\"#a9a9a9\",darkgreen:\"#006400\",darkgrey:\"#a9a9a9\",peachpuff:\"#ffdab9\",darkmagenta:\"#8b008b\",darkred:\"#8b0000\",darkorchid:\"#9932cc\",darkorange:\"#ff8c00\",darkslateblue:\"#483d8b\",gray:\"#808080\",darkslategray:\"#2f4f4f\",darkslategrey:\"#2f4f4f\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",wheat:\"#f5deb3\",firebrick:\"#b22222\",floralwhite:\"#fffaf0\",ghostwhite:\"#f8f8ff\",darkviolet:\"#9400d3\",magenta:\"#ff00ff\",green:\"#008000\",dodgerblue:\"#1e90ff\",grey:\"#808080\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",blueviolet:\"#8a2be2\",forestgreen:\"#228b22\",lawngreen:\"#7cfc00\",indianred:\"#cd5c5c\",indigo:\"#4b0082\",fuchsia:\"#ff00ff\",brown:\"#a52a2a\",maroon:\"#800000\",mediumblue:\"#0000cd\",lightcoral:\"#f08080\",darkturquoise:\"#00ced1\",lightcyan:\"#e0ffff\",ivory:\"#fffff0\",lightyellow:\"#ffffe0\",lightsalmon:\"#ffa07a\",lightseagreen:\"#20b2aa\",linen:\"#faf0e6\",mediumaquamarine:\"#66cdaa\",lemonchiffon:\"#fffacd\",lime:\"#00ff00\",khaki:\"#f0e68c\",mediumseagreen:\"#3cb371\",limegreen:\"#32cd32\",mediumspringgreen:\"#00fa9a\",lightskyblue:\"#87cefa\",lightblue:\"#add8e6\",midnightblue:\"#191970\",lightpink:\"#ffb6c1\",mistyrose:\"#ffe4e1\",moccasin:\"#ffe4b5\",mintcream:\"#f5fffa\",lightslategray:\"#778899\",lightslategrey:\"#778899\",navajowhite:\"#ffdead\",navy:\"#000080\",mediumvioletred:\"#c71585\",powderblue:\"#b0e0e6\",palegoldenrod:\"#eee8aa\",oldlace:\"#fdf5e6\",paleturquoise:\"#afeeee\",mediumturquoise:\"#48d1cc\",mediumorchid:\"#ba55d3\",rebeccapurple:\"#663399\",lightsteelblue:\"#b0c4de\",mediumslateblue:\"#7b68ee\",thistle:\"#d8bfd8\",tan:\"#d2b48c\",orchid:\"#da70d6\",mediumpurple:\"#9370db\",purple:\"#800080\",pink:\"#ffc0cb\",skyblue:\"#87ceeb\",springgreen:\"#00ff7f\",palegreen:\"#98fb98\",red:\"#ff0000\",yellow:\"#ffff00\",slateblue:\"#6a5acd\",lavenderblush:\"#fff0f5\",peru:\"#cd853f\",palevioletred:\"#db7093\",violet:\"#ee82ee\",teal:\"#008080\",slategray:\"#708090\",slategrey:\"#708090\",aliceblue:\"#f0f8ff\",darkseagreen:\"#8fbc8f\",darkolivegreen:\"#556b2f\",greenyellow:\"#adff2f\",seagreen:\"#2e8b57\",seashell:\"#fff5ee\",tomato:\"#ff6347\",silver:\"#c0c0c0\",sienna:\"#a0522d\",lavender:\"#e6e6fa\",lightgreen:\"#90ee90\",orange:\"#ffa500\",orangered:\"#ff4500\",steelblue:\"#4682b4\",royalblue:\"#4169e1\",turquoise:\"#40e0d0\",yellowgreen:\"#9acd32\",salmon:\"#fa8072\",saddlebrown:\"#8b4513\",sandybrown:\"#f4a460\",rosybrown:\"#bc8f8f\",darksalmon:\"#e9967a\",lightgoldenrodyellow:\"#fafad2\",snow:\"#fffafa\",lightgrey:\"#d3d3d3\",lightgray:\"#d3d3d3\",dimgray:\"#696969\",dimgrey:\"#696969\",olivedrab:\"#6b8e23\",olive:\"#808000\"},r={};for(var d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return\"transparent\";var d,i,n=r[this.toHex()];if(n)return n;if(null==f?void 0:f.closest){var o=this.toRgb(),t=1/0,b=\"black\";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(var g in a){var u=(d=o,i=l[g],Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2));u<t&&(t=u,b=g)}return b}};f.string.push([function(f){var r=f.toLowerCase(),d=\"transparent\"===r?\"#0000\":a[r];return d?new e(d).toRgb():null},\"name\"])};export{e as default};\n","import { colord, extend } from 'colord';\nimport namesPlugin from 'colord/plugins/names';\n\nextend([namesPlugin]);\n\n/**\n * Convert RGB values to hex color string\n * @param r Red component (0-255)\n * @param g Green component (0-255)\n * @param b Blue component (0-255)\n * @returns Hex color string (e.g., '#ff0000')\n */\nexport function rgbToHex(r: number, g: number, b: number): string {\n const clamp = (v: number) => Math.max(0, Math.min(255, Math.round(v)));\n const toHex = (v: number) => {\n const hex = clamp(v).toString(16);\n return hex.length === 1 ? `0${hex}` : hex;\n };\n return `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n}\n\n/**\n * Normalize a color value to six-digit RGB hex.\n * String values are parsed as CSS colors; numeric arrays use RGB byte channels.\n * Alpha channels are ignored.\n * @param value Color value in CSS string or RGB(A) array format\n * @returns Normalized hex color string, or null when the value is invalid\n */\nexport function normalizeColor(value: unknown): string | null {\n if (typeof value === 'string') {\n const color = colord(value);\n if (!color.isValid()) return null;\n const { r, g, b } = color.toRgb();\n return rgbToHex(r, g, b);\n }\n\n if (Array.isArray(value) && value.length >= 3) {\n const [r, g, b] = value;\n if (\n typeof r === 'number' &&\n Number.isFinite(r) &&\n typeof g === 'number' &&\n Number.isFinite(g) &&\n typeof b === 'number' &&\n Number.isFinite(b)\n ) {\n return rgbToHex(r, g, b);\n }\n }\n\n return null;\n}\n","/**\n * Format a numeric value based on the step size\n * @param value Numeric value to format\n * @param step Step size (determines decimal places)\n * @returns Formatted string\n */\nexport function formatNumericValue(value: number, step: number): string {\n let decimals = 0;\n\n if (step && Number(step) !== 1) {\n const stepNumber = Number(step);\n if (stepNumber > 0 && stepNumber < 1) {\n decimals = Math.min(4, Math.ceil(Math.abs(Math.log10(stepNumber))));\n }\n }\n\n return value.toFixed(decimals);\n}\n\n/**\n * Clamp a numeric value between min and max\n * @param value Value to clamp\n * @param min Minimum value\n * @param max Maximum value\n * @returns Clamped value\n */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n","/**\n * Style properties the style editor can edit, per layer type, with the\n * MapLibre style-spec defaults used when `showAllStyleProperties` exposes a\n * control whose value is absent from the layer style.\n */\n\nexport type EditableLayerType =\n | \"fill\"\n | \"line\"\n | \"circle\"\n | \"raster\"\n | \"symbol\";\n\nexport type StylePropertySpec =\n | {\n kind: \"color\";\n property: string;\n label: string;\n /** Style-spec default shown while the property is unset */\n defaultValue: string;\n /**\n * Property MapLibre falls back to while this one is unset (e.g.\n * `fill-outline-color` inherits `fill-color`)\n */\n inheritsFrom?: string;\n }\n | {\n kind: \"slider\";\n property: string;\n label: string;\n /** Style-spec default shown while the property is unset */\n defaultValue: number;\n min: number;\n max: number;\n step: number;\n }\n | { kind: \"pattern\"; property: \"fill-pattern\" };\n\nconst opacity = (property: string, label: string): StylePropertySpec => ({\n kind: \"slider\",\n property,\n label,\n defaultValue: 1,\n min: 0,\n max: 1,\n step: 0.05,\n});\n\nconst rasterSlider = (\n property: string,\n label: string,\n defaultValue: number,\n min = -1,\n max = 1,\n step = 0.05,\n): StylePropertySpec => ({\n kind: \"slider\",\n property,\n label,\n defaultValue,\n min,\n max,\n step,\n});\n\n/**\n * Every control the editor supports, in display order. Labels, ranges and\n * steps match the controls shown without `showAllStyleProperties`.\n */\nexport const STYLE_PROPERTY_SPECS: Record<\n EditableLayerType,\n StylePropertySpec[]\n> = {\n fill: [\n {\n kind: \"color\",\n property: \"fill-color\",\n label: \"Fill Color\",\n defaultValue: \"#000000\",\n },\n { kind: \"pattern\", property: \"fill-pattern\" },\n opacity(\"fill-opacity\", \"Fill Opacity\"),\n {\n kind: \"color\",\n property: \"fill-outline-color\",\n label: \"Outline Color\",\n defaultValue: \"#000000\",\n inheritsFrom: \"fill-color\",\n },\n ],\n line: [\n {\n kind: \"color\",\n property: \"line-color\",\n label: \"Line Color\",\n defaultValue: \"#000000\",\n },\n {\n kind: \"slider\",\n property: \"line-width\",\n label: \"Line Width\",\n defaultValue: 1,\n min: 0,\n max: 20,\n step: 0.5,\n },\n opacity(\"line-opacity\", \"Line Opacity\"),\n {\n kind: \"slider\",\n property: \"line-blur\",\n label: \"Line Blur\",\n defaultValue: 0,\n min: 0,\n max: 5,\n step: 0.1,\n },\n ],\n circle: [\n {\n kind: \"color\",\n property: \"circle-color\",\n label: \"Circle Color\",\n defaultValue: \"#000000\",\n },\n {\n kind: \"slider\",\n property: \"circle-radius\",\n label: \"Radius\",\n defaultValue: 5,\n min: 0,\n max: 40,\n step: 0.5,\n },\n opacity(\"circle-opacity\", \"Opacity\"),\n {\n kind: \"color\",\n property: \"circle-stroke-color\",\n label: \"Stroke Color\",\n defaultValue: \"#000000\",\n },\n {\n kind: \"slider\",\n property: \"circle-stroke-width\",\n label: \"Stroke Width\",\n defaultValue: 0,\n min: 0,\n max: 10,\n step: 0.1,\n },\n ],\n raster: [\n opacity(\"raster-opacity\", \"Opacity\"),\n rasterSlider(\"raster-brightness-min\", \"Brightness Min\", 0),\n rasterSlider(\"raster-brightness-max\", \"Brightness Max\", 1),\n rasterSlider(\"raster-saturation\", \"Saturation\", 0),\n rasterSlider(\"raster-contrast\", \"Contrast\", 0),\n rasterSlider(\"raster-hue-rotate\", \"Hue Rotate\", 0, 0, 350, 5),\n ],\n symbol: [\n {\n kind: \"color\",\n property: \"text-color\",\n label: \"Text Color\",\n defaultValue: \"#000000\",\n },\n opacity(\"text-opacity\", \"Text Opacity\"),\n opacity(\"icon-opacity\", \"Icon Opacity\"),\n ],\n};\n\n/** Editable paint property name -> its spec. */\nexport const STYLE_PROPERTY_SPEC_BY_PROPERTY: Record<\n string,\n StylePropertySpec\n> = Object.fromEntries(\n Object.values(STYLE_PROPERTY_SPECS)\n .flat()\n .map((spec) => [spec.property, spec]),\n);\n\n/**\n * Whether a paint/layout value counts as \"not set\" for dependency checks\n * (`fill-pattern`, `text-field`, `icon-image`).\n */\nexport function isUnsetValue(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n","import type { Map as MapLibreMap, LayerSpecification, AllPaintProperties } from 'maplibre-gl';\nimport { normalizeColor, rgbToHex } from './colorUtils';\n\n/**\n * Map of layer types to their primary color property\n */\nconst COLOR_PROPERTY_MAP: Record<string, (keyof AllPaintProperties)[]> = {\n fill: ['fill-color', 'fill-outline-color'],\n line: ['line-color'],\n circle: ['circle-color', 'circle-stroke-color'],\n symbol: ['icon-color', 'text-color'],\n background: ['background-color'],\n heatmap: ['heatmap-color'],\n 'fill-extrusion': ['fill-extrusion-color'],\n};\n\n/**\n * Narrows an unknown expression value to an array\n * @param value Value to check\n * @returns Whether the value is an array\n */\nfunction isExpressionArray(value: unknown): value is unknown[] {\n return Array.isArray(value);\n}\n\n/**\n * Extract the first color value from a MapLibre expression\n * Handles expressions like ['case', ...], ['match', ...], ['interpolate', ...],\n * and constant ['rgb', ...] / ['rgba', ...] operators\n * @param expression The MapLibre expression to extract color from\n * @param preserveFormat Keep CSS color syntax instead of normalizing to hex\n * @returns The first color found, or null\n */\nfunction extractColorFromExpression(\n expression: unknown,\n preserveFormat = false\n): string | null {\n if (!isExpressionArray(expression) || expression.length === 0) return null;\n\n const operator = expression[0];\n const components = expression.slice(1);\n if (\n (operator === 'rgb' && components.length === 3) ||\n (operator === 'rgba' && components.length === 4)\n ) {\n if (\n components.every(\n (component) =>\n typeof component === 'number' && Number.isFinite(component)\n )\n ) {\n const color = `${operator}(${components.join(', ')})`;\n return preserveFormat ? color : normalizeColor(color);\n }\n }\n\n let index = 0;\n let stride = 1;\n let end = expression.length;\n let fallbackIndex = -1;\n let firstResultIndex = 0;\n\n if (operator === 'case' || operator === 'match') {\n firstResultIndex = operator === 'case' ? 2 : 3;\n index = firstResultIndex;\n stride = 2;\n end = expression.length - 1;\n fallbackIndex = expression.length - 1;\n } else if (operator === 'interpolate') {\n index = 4;\n stride = 2;\n }\n\n const resolve = (item: unknown): string | null => {\n if (typeof item === 'string') {\n const color = normalizeColor(item);\n return color !== null && preserveFormat ? item : color;\n }\n return isExpressionArray(item)\n ? extractColorFromExpression(item, preserveFormat)\n : null;\n };\n\n for (; index < end; index += stride) {\n const color = resolve(expression[index]);\n if (color !== null) return color;\n }\n\n if (fallbackIndex >= firstResultIndex) {\n return resolve(expression[fallbackIndex]);\n }\n\n return null;\n}\n\n/**\n * Get the primary color from a layer's paint properties\n * @param map The MapLibre map instance\n * @param layerId The layer ID\n * @param layerType The layer type\n * @returns The normalized hex color, or null if not found\n */\nexport function getLayerColor(\n map: MapLibreMap,\n layerId: string,\n layerType: string\n): string | null {\n const propertyNames = COLOR_PROPERTY_MAP[layerType];\n if (!propertyNames) return null;\n\n for (const propertyName of propertyNames) {\n try {\n const runtimeColor = map.getPaintProperty(layerId, propertyName);\n if (runtimeColor) {\n if (typeof runtimeColor === 'string') {\n const color = normalizeColor(runtimeColor);\n if (color !== null) return color;\n }\n if (Array.isArray(runtimeColor)) {\n const extracted = extractColorFromExpression(runtimeColor);\n if (extracted !== null) return extracted;\n }\n }\n } catch {\n // Property doesn't exist, continue\n }\n\n const style = map.getStyle();\n const layer = style?.layers?.find(\n (styleLayer: LayerSpecification) => styleLayer.id === layerId\n );\n if (layer && 'paint' in layer && layer.paint) {\n const paintColor = (layer.paint as Record<string, unknown>)[propertyName];\n if (paintColor) {\n if (typeof paintColor === 'string') {\n const color = normalizeColor(paintColor);\n if (color !== null) return color;\n }\n if (Array.isArray(paintColor)) {\n const extracted = extractColorFromExpression(paintColor);\n if (extracted !== null) return extracted;\n }\n }\n }\n }\n\n return null;\n}\n\n/**\n * Get the primary color directly from a layer specification\n * @param layer The layer specification\n * @returns The normalized hex color, or null if not found\n */\nexport function getLayerColorFromSpec(layer: LayerSpecification): string | null {\n const propertyNames = COLOR_PROPERTY_MAP[layer.type];\n if (!propertyNames) return null;\n\n for (const propertyName of propertyNames) {\n if ('paint' in layer && layer.paint) {\n const paintColor = (layer.paint as Record<string, unknown>)[propertyName];\n if (paintColor) {\n if (typeof paintColor === 'string') {\n const color = normalizeColor(paintColor);\n if (color !== null) return color;\n }\n if (Array.isArray(paintColor)) {\n const extracted = extractColorFromExpression(paintColor);\n if (extracted !== null) return extracted;\n }\n }\n }\n }\n\n return null;\n}\n\n/**\n * Additional paint properties that affect a layer's preview symbol.\n */\nexport interface LayerSymbolStyle {\n /** line-dasharray in line-width units. */\n dasharray?: number[];\n /** Circle border colour; null disables the border. */\n strokeColor?: string | null;\n /** Registered MapLibre image for a fill-pattern; SDF images use the fill color. */\n fillPattern?: FillPatternImage;\n}\n\n/**\n * Extracts the first literal dash pattern from a paint value or expression\n * @param value Runtime or style-spec line-dasharray value\n * @returns A valid finite dash pattern, or null\n */\nfunction extractDasharray(value: unknown): number[] | null {\n if (!Array.isArray(value)) return null;\n\n if (\n value.length > 0 &&\n value.every((item) => typeof item === 'number' && Number.isFinite(item))\n ) {\n const dasharray = value as number[];\n if (dasharray.every((item) => item >= 0) && dasharray.some((item) => item > 0)) {\n return dasharray;\n }\n return null;\n }\n\n for (const item of value) {\n if (Array.isArray(item)) {\n const dasharray = extractDasharray(item);\n if (dasharray) return dasharray;\n }\n }\n\n return null;\n}\n\n/**\n * Resolves the preview styles supported for a layer type\n * @param layerType MapLibre layer type\n * @param getPaint Paint-property lookup for the current layer\n * @returns The resolved dash pattern or circle border style\n */\nfunction resolveSymbolStyle(\n layerType: string,\n getPaint: (property: keyof AllPaintProperties) => unknown\n): LayerSymbolStyle {\n if (layerType === 'line') {\n const dasharray = extractDasharray(getPaint('line-dasharray'));\n return dasharray ? { dasharray } : {};\n }\n\n if (layerType === 'circle') {\n if (getPaint('circle-stroke-width') === 0) {\n return { strokeColor: null };\n }\n\n const color = getPaint('circle-stroke-color');\n if (typeof color === 'string') {\n return { strokeColor: color };\n }\n if (isExpressionArray(color)) {\n const strokeColor = extractColorFromExpression(color, true);\n return strokeColor ? { strokeColor } : {};\n }\n }\n\n return {};\n}\n\n/** Read runtime paint values, falling back to the layer specification. */\nfunction readPaintValue(map: MapLibreMap, layerId: string, property: keyof AllPaintProperties): unknown {\n let value: unknown;\n try {\n value = map.getPaintProperty(layerId, property);\n } catch {\n // The runtime property may not be available yet.\n }\n if (value !== undefined) return value;\n const layer = map.getStyle()?.layers?.find((item) => item.id === layerId);\n return layer && 'paint' in layer && layer.paint\n ? (layer.paint as Record<string, unknown>)[property]\n : undefined;\n}\n\nexport interface ColorCategory {\n /** Text shown next to the swatch. */\n label: string;\n /** Normalized hex, or null for an unsupported output (gray swatch). */\n color: string | null;\n /** Full label or JSON condition for the tooltip. */\n title: string;\n}\n\nexport interface ColorCategories {\n /** Paint property that supplies the categories. */\n property: string;\n categories: ColorCategory[];\n}\n\nfunction formatCaseCondition(condition: unknown): string {\n if (Array.isArray(condition)) {\n const [operator, input, literal] = condition;\n if (\n ['==', '!=', '<', '<=', '>', '>='].includes(operator) &&\n Array.isArray(input) && input[0] === 'get' && typeof input[1] === 'string' &&\n ['string', 'number', 'boolean'].includes(typeof literal)\n ) {\n return `${input[1]} ${operator === '==' ? '=' : operator} ${literal}`;\n }\n if (operator === 'has' && typeof input === 'string') return `has ${input}`;\n if (\n operator === '!' && Array.isArray(input) &&\n input[0] === 'has' && typeof input[1] === 'string'\n ) return `no ${input[1]}`;\n }\n return JSON.stringify(condition) ?? String(condition);\n}\n\nfunction parseColorCategories(value: unknown): ColorCategory[] | null {\n if (!Array.isArray(value) || !['match', 'case'].includes(value[0])) return null;\n const categories: ColorCategory[] = [];\n const addCategory = (label: string, title: string, output: unknown): void => {\n categories.push({\n label: label.length > 40 ? `${label.slice(0, 39)}…` : label,\n title,\n color: typeof output === 'string' &&\n (output.startsWith('#') || output.startsWith('rgb'))\n ? normalizeColor(output)\n : null,\n });\n };\n const isMatch = value[0] === 'match';\n for (let i = isMatch ? 2 : 1; i < value.length - 1; i += 2) {\n const condition = value[i];\n const label = isMatch\n ? Array.isArray(condition) ? condition.map(String).join(', ') : String(condition)\n : formatCaseCondition(condition);\n addCategory(label, isMatch ? label : JSON.stringify(condition) ?? String(condition), value[i + 1]);\n }\n addCategory('Other', 'Other', value[value.length - 1]);\n return categories.length >= 2 ? categories : null;\n}\n\n/** Get ordered categories from a top-level match/case color expression. */\nexport function getLayerColorCategories(\n map: MapLibreMap,\n layerId: string,\n layerType: string\n): ColorCategories | null {\n if (!['fill', 'line', 'symbol', 'circle', 'fill-extrusion'].includes(layerType)) return null;\n if (layerType === 'fill' && readPaintValue(map, layerId, 'fill-pattern') !== undefined) return null;\n for (const property of COLOR_PROPERTY_MAP[layerType]) {\n const categories = parseColorCategories(readPaintValue(map, layerId, property));\n if (categories) return { property, categories };\n }\n return null;\n}\n\n/**\n * Get additional symbol styles from runtime paint properties, falling back to\n * the layer definition when a runtime property is unavailable\n * @param map The MapLibre map instance\n * @param layerId The layer ID\n * @param layerType The layer type\n * @returns The resolved dash pattern, circle border style, or fill pattern\n */\nexport function getLayerSymbolStyle(\n map: MapLibreMap,\n layerId: string,\n layerType: string\n): LayerSymbolStyle {\n if (layerType === 'fill') {\n const fillPattern = resolvePatternImage(map, readPaintValue(map, layerId, 'fill-pattern'));\n return fillPattern ? { fillPattern } : {};\n }\n\n const getPaint = (property: keyof AllPaintProperties): unknown => {\n const value = readPaintValue(map, layerId, property);\n if (value !== null) return value;\n const layer = map.getStyle()?.layers?.find((item) => item.id === layerId);\n return layer && 'paint' in layer && layer.paint\n ? (layer.paint as Record<string, unknown>)[property]\n : undefined;\n };\n\n return resolveSymbolStyle(layerType, getPaint);\n}\n\n/**\n * Get additional symbol styles directly from a layer specification\n * @param layer The layer specification\n * @returns The resolved dash pattern or circle border style\n */\nexport function getLayerSymbolStyleFromSpec(\n layer: LayerSpecification\n): LayerSymbolStyle {\n const getPaint = (property: keyof AllPaintProperties): unknown => {\n if ('paint' in layer && layer.paint) {\n return (layer.paint as Record<string, unknown>)[property];\n }\n return undefined;\n };\n\n return resolveSymbolStyle(layer.type, getPaint);\n}\n\n/**\n * Resolve a representative registered image from a fill-pattern expression.\n * Only visit output values, never match labels or condition operands.\n */\nfunction resolvePatternImage(\n map: MapLibreMap,\n value: unknown\n): FillPatternImage | undefined {\n if (typeof value === 'string') return map.getImage(value);\n if (!Array.isArray(value)) return undefined;\n\n const [operator] = value;\n let start: number;\n let stride: number;\n switch (operator) {\n case 'literal':\n case 'image':\n return typeof value[1] === 'string' ? map.getImage(value[1]) : undefined;\n case 'coalesce':\n start = 1;\n stride = 1;\n break;\n case 'match':\n start = 3;\n stride = 2;\n break;\n case 'case':\n case 'step':\n start = 2;\n stride = 2;\n break;\n case 'interpolate':\n case 'interpolate-hcl':\n case 'interpolate-lab':\n start = 4;\n stride = 2;\n break;\n default:\n return undefined;\n }\n for (let i = start; i < value.length; i += stride) {\n const image = resolvePatternImage(map, value[i]);\n if (image) return image;\n }\n // match/case have a final fallback outside the output/stop pairs.\n if (operator === 'match' || operator === 'case') {\n return resolvePatternImage(map, value[value.length - 1]);\n }\n return undefined;\n}\n\n/** Registered pattern pixels and metadata, compatible with map.getImage(). */\nexport interface FillPatternImage {\n data: {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n };\n pixelRatio: number;\n sdf: boolean;\n /** Incremented by MapLibre when image pixels change. */\n version?: number;\n}\n\n/** A registered map image usable as a fill-pattern. */\nexport interface PatternImageEntry {\n id: string;\n image: FillPatternImage;\n}\n\n/** List images currently registered in the map (style sprite and addImage), sorted by ID. */\nexport function listPatternImages(map: MapLibreMap): PatternImageEntry[] {\n if (\n typeof map.listImages !== 'function' ||\n typeof map.getImage !== 'function'\n ) {\n return [];\n }\n\n let ids: string[];\n try {\n ids = map.listImages();\n } catch {\n return [];\n }\n\n const images: PatternImageEntry[] = [];\n for (const id of ids) {\n try {\n const image = map.getImage(id) as FillPatternImage | undefined | null;\n if (image?.data) images.push({ id, image });\n } catch {\n // Ignore images that are no longer available.\n }\n }\n return images.sort((a, b) => a.id.localeCompare(b.id));\n}\n\nconst patternTiles = new WeakMap<\n FillPatternImage,\n { version: number | undefined; urls: Map<string, string> }\n>();\n\n/** Convert RGBA pixels or an SDF alpha channel into a browser-renderable tile. */\nfunction createPatternTile(image: FillPatternImage, color: string): string | null {\n const key = image.sdf ? color : '';\n let cached = patternTiles.get(image);\n if (cached?.version !== image.version) cached = undefined;\n const existing = cached?.urls.get(key);\n if (existing) return existing;\n if (typeof document === 'undefined') return null;\n\n const { width, height, data } = image.data;\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n const context = canvas.getContext('2d');\n if (!context) return null;\n const pixels = context.createImageData(width, height);\n if (image.sdf) {\n const normalizedColor = normalizeColor(color);\n if (normalizedColor === null) return null;\n const r = parseInt(normalizedColor.slice(1, 3), 16);\n const g = parseInt(normalizedColor.slice(3, 5), 16);\n const b = parseInt(normalizedColor.slice(5, 7), 16);\n // MapLibre's SDF contour is 0.75; smoothstep preserves antialiased edges.\n const gamma = 0.105 / image.pixelRatio;\n for (let i = 0; i < data.length; i += 4) {\n const t = Math.max(\n 0,\n Math.min(1, (data[i + 3] / 255 - 0.75 + gamma) / (2 * gamma))\n );\n pixels.data[i] = r;\n pixels.data[i + 1] = g;\n pixels.data[i + 2] = b;\n pixels.data[i + 3] = Math.round(255 * t * t * (3 - 2 * t));\n }\n } else {\n pixels.data.set(data);\n }\n context.putImageData(pixels, 0, 0);\n const url = canvas.toDataURL();\n if (!cached) {\n cached = { version: image.version, urls: new Map() };\n patternTiles.set(image, cached);\n }\n cached.urls.set(key, url);\n return url;\n}\n\n/**\n * Darken a hex color by a given amount\n * @param hexColor The hex color to darken (e.g., '#ff0000')\n * @param amount Amount to darken (0-1, where 1 is fully black)\n * @returns The darkened hex color\n */\nexport function darkenColor(hexColor: string, amount: number): string {\n // Normalize to 6-digit hex\n let hex = hexColor.replace('#', '');\n if (hex.length === 3) {\n hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];\n }\n\n const r = Math.max(\n 0,\n parseInt(hex.slice(0, 2), 16) - Math.round(255 * amount)\n );\n const g = Math.max(\n 0,\n parseInt(hex.slice(2, 4), 16) - Math.round(255 * amount)\n );\n const b = Math.max(\n 0,\n parseInt(hex.slice(4, 6), 16) - Math.round(255 * amount)\n );\n return rgbToHex(r, g, b);\n}\n\n// SVG Symbol Templates\n\n/**\n * Create a fill symbol (filled rectangle)\n */\nfunction createFillSymbol(\n size: number,\n color: string,\n image?: FillPatternImage\n): string {\n const padding = 2;\n const borderColor = darkenColor(color, 0.3);\n if (image) {\n const url = createPatternTile(image, color);\n if (url) {\n const id = `fillPattern_${Math.random().toString(36).slice(2, 9)}`;\n const width = image.data.width / image.pixelRatio;\n const height = image.data.height / image.pixelRatio;\n // Keep small patterns at their natural scale; fit two large tiles in\n // the swatch so the repeating motif remains recognizable.\n const scale = Math.min(1, (size - padding * 2) / (2 * Math.max(width, height)));\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <pattern id=\"${id}\" patternUnits=\"userSpaceOnUse\" x=\"${padding}\" y=\"${padding}\" width=\"${width * scale}\" height=\"${height * scale}\">\n <image href=\"${url}\" width=\"${width * scale}\" height=\"${height * scale}\"/>\n </pattern>\n </defs>\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"url(#${id})\" stroke=\"${borderColor}\" stroke-width=\"1\" rx=\"1\"/>\n </svg>`;\n }\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"1\" rx=\"1\"/>\n </svg>`;\n}\n\n/**\n * Create a line symbol (horizontal line)\n * @param size Symbol size in pixels\n * @param color Line color\n * @param strokeWidth Preview stroke width in pixels\n * @param dasharray Optional line-dasharray scaled to fit the symbol\n * @returns SVG markup string\n */\nfunction createLineSymbol(\n size: number,\n color: string,\n strokeWidth: number = 2,\n dasharray?: number[]\n): string {\n const y = size / 2;\n const padding = 2;\n let dashAttributes = 'stroke-linecap=\"round\"';\n if (dasharray && dasharray.length > 0) {\n const lineLength = size - padding * 2;\n const dashLength = dasharray[0];\n const gapLength = dasharray.length > 1 ? dasharray[1] : dashLength;\n const fitLength = dashLength + gapLength + dashLength;\n const scale =\n fitLength > 0\n ? Math.min(strokeWidth, lineLength / fitLength)\n : strokeWidth;\n const scaledDasharray = dasharray\n .map((value) => Number((value * scale).toFixed(2)))\n .join(' ');\n dashAttributes = `stroke-linecap=\"butt\" stroke-dasharray=\"${scaledDasharray}\"`;\n }\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <line x1=\"${padding}\" y1=\"${y}\" x2=\"${size - padding}\" y2=\"${y}\"\n stroke=\"${color}\" stroke-width=\"${strokeWidth}\" ${dashAttributes}/>\n </svg>`;\n}\n\n/**\n * Create a circle symbol (filled circle)\n * @param size Symbol size in pixels\n * @param color Circle fill color\n * @param strokeColor Border color; null disables the border, undefined uses a darkened fill\n * @returns SVG markup string\n */\nfunction createCircleSymbol(\n size: number,\n color: string,\n strokeColor?: string | null\n): string {\n const cx = size / 2;\n const cy = size / 2;\n const r = size / 2 - 3;\n const borderAttributes =\n strokeColor === undefined\n ? `stroke=\"${darkenColor(color, 0.3)}\" stroke-width=\"1\"`\n : strokeColor === null\n ? 'stroke=\"none\"'\n : `stroke=\"${strokeColor}\" stroke-width=\"1\"`;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <circle cx=\"${cx}\" cy=\"${cy}\" r=\"${r}\" fill=\"${color}\"\n ${borderAttributes}/>\n </svg>`;\n}\n\n/**\n * Create a marker/pin symbol for symbol layers\n */\nfunction createMarkerSymbol(size: number, color: string): string {\n const borderColor = darkenColor(color, 0.3);\n // Simple pin/marker shape\n const cx = size / 2;\n const pinWidth = size * 0.5;\n const pinHeight = size * 0.7;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M${cx} ${size - 2}\n L${cx - pinWidth / 2} ${size - pinHeight}\n A${pinWidth / 2} ${pinWidth / 2} 0 1 1 ${cx + pinWidth / 2} ${size - pinHeight}\n Z\"\n fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"1\"/>\n <circle cx=\"${cx}\" cy=\"${size - pinHeight - pinWidth / 4}\" r=\"${pinWidth / 5}\" fill=\"white\"/>\n </svg>`;\n}\n\n/**\n * Create a raster symbol (gradient pattern)\n */\nfunction createRasterSymbol(size: number): string {\n const padding = 2;\n const id = `rasterGrad_${Math.random().toString(36).slice(2, 9)}`;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"${id}\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stop-color=\"#e0e0e0\"/>\n <stop offset=\"50%\" stop-color=\"#808080\"/>\n <stop offset=\"100%\" stop-color=\"#404040\"/>\n </linearGradient>\n </defs>\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"url(#${id})\" rx=\"1\"/>\n </svg>`;\n}\n\n/**\n * Create a background symbol (rectangle with inner indicator)\n */\nfunction createBackgroundSymbol(size: number, color: string): string {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"1\" y=\"1\" width=\"${size - 2}\" height=\"${size - 2}\" fill=\"${color}\" rx=\"2\"/>\n <rect x=\"3\" y=\"3\" width=\"${size - 6}\" height=\"${size - 6}\" fill=\"none\"\n stroke=\"white\" stroke-width=\"1\" stroke-opacity=\"0.5\" rx=\"1\"/>\n </svg>`;\n}\n\n/**\n * Create a heatmap symbol (orange-red gradient)\n */\nfunction createHeatmapSymbol(size: number): string {\n const padding = 2;\n const id = `heatmapGrad_${Math.random().toString(36).slice(2, 9)}`;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <radialGradient id=\"${id}\" cx=\"50%\" cy=\"50%\" r=\"50%\">\n <stop offset=\"0%\" stop-color=\"#ffff00\"/>\n <stop offset=\"50%\" stop-color=\"#ff8800\"/>\n <stop offset=\"100%\" stop-color=\"#ff0000\"/>\n </radialGradient>\n </defs>\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"url(#${id})\" rx=\"1\"/>\n </svg>`;\n}\n\n/**\n * Create a hillshade symbol (gray gradient)\n */\nfunction createHillshadeSymbol(size: number): string {\n const padding = 2;\n const id = `hillshadeGrad_${Math.random().toString(36).slice(2, 9)}`;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"${id}\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stop-color=\"#ffffff\"/>\n <stop offset=\"100%\" stop-color=\"#666666\"/>\n </linearGradient>\n </defs>\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"url(#${id})\" rx=\"1\"/>\n </svg>`;\n}\n\n/**\n * Create a fill-extrusion symbol (3D-ish rectangle)\n */\nfunction createFillExtrusionSymbol(size: number, color: string): string {\n const borderColor = darkenColor(color, 0.3);\n const topColor = color;\n const sideColor = darkenColor(color, 0.2);\n const depth = 3;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <polygon points=\"${2 + depth},2 ${size - 2},2 ${size - 2},${size - 2 - depth} ${size - 2 - depth},${size - 2} 2,${size - 2} 2,${2 + depth}\"\n fill=\"${topColor}\" stroke=\"${borderColor}\" stroke-width=\"1\"/>\n <polygon points=\"2,${2 + depth} ${2 + depth},2 ${2 + depth},${size - 2 - depth} 2,${size - 2}\"\n fill=\"${sideColor}\" stroke=\"${borderColor}\" stroke-width=\"0.5\"/>\n <polygon points=\"${2 + depth},${size - 2 - depth} ${size - 2},${size - 2 - depth} ${size - 2 - depth},${size - 2} 2,${size - 2}\"\n fill=\"${sideColor}\" stroke=\"${borderColor}\" stroke-width=\"0.5\"/>\n </svg>`;\n}\n\n/**\n * Create a default symbol (simple square)\n */\nfunction createDefaultSymbol(size: number, color: string): string {\n const padding = 2;\n const borderColor = darkenColor(color, 0.3);\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"1\"/>\n </svg>`;\n}\n\n/**\n * Create a COG (Cloud Optimized GeoTIFF) symbol\n * Grid pattern representing raster tiles\n */\nfunction createCOGSymbol(size: number, color: string): string {\n const padding = 2;\n const borderColor = darkenColor(color, 0.3);\n const cellSize = (size - padding * 2) / 2;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${cellSize}\" height=\"${cellSize}\" fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"0.5\"/>\n <rect x=\"${padding + cellSize}\" y=\"${padding}\" width=\"${cellSize}\" height=\"${cellSize}\" fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.8\"/>\n <rect x=\"${padding}\" y=\"${padding + cellSize}\" width=\"${cellSize}\" height=\"${cellSize}\" fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.6\"/>\n <rect x=\"${padding + cellSize}\" y=\"${padding + cellSize}\" width=\"${cellSize}\" height=\"${cellSize}\" fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.4\"/>\n </svg>`;\n}\n\n/**\n * Create a Zarr symbol\n * Layered grid pattern representing multidimensional data\n */\nfunction createZarrSymbol(size: number, color: string): string {\n const padding = 2;\n const borderColor = darkenColor(color, 0.3);\n const innerSize = size - padding * 2;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"${padding + 2}\" y=\"${padding}\" width=\"${innerSize - 2}\" height=\"${innerSize - 2}\" fill=\"${darkenColor(color, 0.2)}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" rx=\"1\"/>\n <rect x=\"${padding + 1}\" y=\"${padding + 1}\" width=\"${innerSize - 2}\" height=\"${innerSize - 2}\" fill=\"${darkenColor(color, 0.1)}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" rx=\"1\"/>\n <rect x=\"${padding}\" y=\"${padding + 2}\" width=\"${innerSize - 2}\" height=\"${innerSize - 2}\" fill=\"${color}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" rx=\"1\"/>\n <line x1=\"${padding + 3}\" y1=\"${padding + 5}\" x2=\"${padding + innerSize - 5}\" y2=\"${padding + 5}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.5\"/>\n <line x1=\"${padding + 3}\" y1=\"${padding + 8}\" x2=\"${padding + innerSize - 5}\" y2=\"${padding + 8}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.5\"/>\n </svg>`;\n}\n\n/**\n * Create a generic custom raster symbol\n * Gradient grid representing custom raster layers\n */\nfunction createCustomRasterSymbol(size: number, color: string): string {\n const padding = 2;\n const borderColor = darkenColor(color, 0.3);\n const id = `customRasterGrad_${Math.random().toString(36).slice(2, 9)}`;\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <defs>\n <linearGradient id=\"${id}\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\">\n <stop offset=\"0%\" stop-color=\"${color}\"/>\n <stop offset=\"100%\" stop-color=\"${darkenColor(color, 0.4)}\"/>\n </linearGradient>\n </defs>\n <rect x=\"${padding}\" y=\"${padding}\" width=\"${size - padding * 2}\" height=\"${size - padding * 2}\"\n fill=\"url(#${id})\" stroke=\"${borderColor}\" stroke-width=\"1\" rx=\"1\"/>\n <line x1=\"${size / 2}\" y1=\"${padding}\" x2=\"${size / 2}\" y2=\"${size - padding}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.3\"/>\n <line x1=\"${padding}\" y1=\"${size / 2}\" x2=\"${size - padding}\" y2=\"${size / 2}\" stroke=\"${borderColor}\" stroke-width=\"0.5\" opacity=\"0.3\"/>\n </svg>`;\n}\n\n/**\n * Create a stacked layers symbol for background layer groups\n * Shows multiple overlapping rectangles to represent multiple layers\n */\nfunction createStackedLayersSymbol(size: number): string {\n const colors = ['#a8d4a8', '#8ec4e8', '#d4c4a8'];\n const borderColor = '#666666';\n // Three stacked rectangles offset diagonally\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 ${size} ${size}\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"4\" y=\"1\" width=\"${size - 6}\" height=\"${size - 6}\" fill=\"${colors[2]}\" stroke=\"${borderColor}\" stroke-width=\"0.75\" rx=\"1\"/>\n <rect x=\"2\" y=\"3\" width=\"${size - 6}\" height=\"${size - 6}\" fill=\"${colors[1]}\" stroke=\"${borderColor}\" stroke-width=\"0.75\" rx=\"1\"/>\n <rect x=\"0\" y=\"5\" width=\"${size - 6}\" height=\"${size - 6}\" fill=\"${colors[0]}\" stroke=\"${borderColor}\" stroke-width=\"0.75\" rx=\"1\"/>\n </svg>`;\n}\n\n/**\n * Symbol generation options\n */\nexport interface SymbolOptions {\n /** Symbol size in pixels (default: 16) */\n size?: number;\n /** Stroke width for line symbols (default: 2) */\n strokeWidth?: number;\n /** line-dasharray in line-width units; rendered to fit the line swatch. */\n dasharray?: number[];\n /** Circle border colour; null disables the border. */\n strokeColor?: string | null;\n /** Registered MapLibre image for a fill-pattern; SDF images use the fill color. */\n fillPattern?: FillPatternImage;\n}\n\n/**\n * Create an SVG symbol for a layer type\n * @param layerType The MapLibre layer type\n * @param color The primary color (hex format), or null for default\n * @param options Optional configuration\n * @returns SVG markup string\n */\nexport function createLayerSymbolSVG(\n layerType: string,\n color: string | null,\n options: SymbolOptions = {}\n): string {\n const size = options.size || 16;\n const strokeWidth = options.strokeWidth || 2;\n const fillColor = color || (options.fillPattern?.sdf ? '#000000' : '#888888');\n\n switch (layerType) {\n case 'fill':\n return createFillSymbol(size, fillColor, options.fillPattern);\n case 'line':\n return createLineSymbol(size, fillColor, strokeWidth, options.dasharray);\n case 'circle':\n return createCircleSymbol(size, fillColor, options.strokeColor);\n case 'symbol':\n return createMarkerSymbol(size, fillColor);\n case 'raster':\n return createRasterSymbol(size);\n case 'background':\n return createBackgroundSymbol(size, fillColor);\n case 'heatmap':\n return createHeatmapSymbol(size);\n case 'hillshade':\n return createHillshadeSymbol(size);\n case 'fill-extrusion':\n return createFillExtrusionSymbol(size, fillColor);\n case 'background-group':\n return createStackedLayersSymbol(size);\n case 'cog':\n return createCOGSymbol(size, fillColor);\n case 'zarr':\n return createZarrSymbol(size, fillColor);\n case 'custom-raster':\n return createCustomRasterSymbol(size, fillColor);\n default:\n return createDefaultSymbol(size, fillColor);\n }\n}\n\n/**\n * Create an SVG symbol for the Background layer group\n * @param size Symbol size in pixels (default: 16)\n * @returns SVG markup string\n */\nexport function createBackgroundGroupSymbolSVG(size: number = 16): string {\n return createStackedLayersSymbol(size);\n}\n\n/** Fixed categorized-renderer indicator, independent of layer colors. */\nexport function createCategorizedSymbolSVG(size: number = 16): string {\n return `<svg width=\"${size}\" height=\"${size}\" viewBox=\"0 0 16 16\" xmlns=\"http://www.w3.org/2000/svg\">\n <rect x=\"1.5\" y=\"1.5\" width=\"6\" height=\"6\" rx=\"1\" fill=\"#e15759\" stroke=\"rgba(0,0,0,0.35)\" stroke-width=\"1\"/>\n <rect x=\"8.5\" y=\"1.5\" width=\"6\" height=\"6\" rx=\"1\" fill=\"#4e79a7\" stroke=\"rgba(0,0,0,0.35)\" stroke-width=\"1\"/>\n <rect x=\"1.5\" y=\"8.5\" width=\"6\" height=\"6\" rx=\"1\" fill=\"#59a14f\" stroke=\"rgba(0,0,0,0.35)\" stroke-width=\"1\"/>\n <rect x=\"8.5\" y=\"8.5\" width=\"6\" height=\"6\" rx=\"1\" fill=\"#f2c94c\" stroke=\"rgba(0,0,0,0.35)\" stroke-width=\"1\"/>\n</svg>`;\n}\n","import type {\n IControl,\n Map as MapLibreMap,\n MapEventType,\n LayerSpecification,\n AllPaintProperties,\n} from \"maplibre-gl\";\nimport type {\n LayerControlOptions,\n LayerState,\n LayerStates,\n PartialLayerStates,\n OriginalStyle,\n InternalControlState,\n CustomLayerAdapter,\n LayerGroupState,\n BackgroundLayerVisibility,\n BackgroundPresets,\n} from \"./types\";\nimport { CustomLayerRegistry } from \"./CustomLayerRegistry\";\nimport {\n getLayerType,\n getLayerOpacity,\n getOpacityProperty,\n setLayerOpacity,\n} from \"../utils/layerUtils\";\nimport {\n cacheOriginalLayerStyle,\n restoreOriginalStyle,\n} from \"../utils/styleCache\";\nimport { normalizeColor } from \"../utils/colorUtils\";\nimport { formatNumericValue, clamp } from \"../utils/formatters\";\nimport {\n STYLE_PROPERTY_SPECS,\n STYLE_PROPERTY_SPEC_BY_PROPERTY,\n isUnsetValue,\n type EditableLayerType,\n type StylePropertySpec,\n} from \"../utils/styleProperties\";\nimport {\n getLayerColor,\n getLayerColorCategories,\n getLayerColorFromSpec,\n getLayerSymbolStyle,\n createLayerSymbolSVG,\n createBackgroundGroupSymbolSVG,\n createCategorizedSymbolSVG,\n listPatternImages,\n type FillPatternImage,\n} from \"../utils/symbolUtils\";\n\n/**\n * LayerControl - A comprehensive layer control for MapLibre GL\n * Provides visibility toggle, opacity control, and advanced style editing\n */\nexport class LayerControl implements IControl {\n private map!: MapLibreMap;\n private mapContainer!: HTMLElement;\n private container!: HTMLDivElement;\n private button!: HTMLButtonElement;\n private panel!: HTMLDivElement;\n\n // Panel positioning\n private resizeHandler: (() => void) | null = null;\n private mapResizeHandler: (() => void) | null = null;\n // Map listeners added by setupLayerChangeListeners, kept so onRemove can take them off again.\n private mapLayerListeners: Array<\n [keyof MapEventType, (e: MapEventType[keyof MapEventType]) => void]\n > = [];\n\n // State management\n private state: InternalControlState;\n private targetLayers: string[];\n private styleEditors: Map<string, HTMLElement>;\n private initialSourceIds: Set<string> | null = null;\n private initialLayerIds: Set<string> | null = null;\n private initialLayerStates: PartialLayerStates;\n\n // Panel width management\n private minPanelWidth: number;\n private maxPanelWidth: number;\n private initialPanelWidth: number;\n /** Explicit max panel height; null means fill available vertical space */\n private maxPanelHeight: number | null;\n private showStyleEditor: boolean;\n private showAllStyleProperties: boolean;\n private showOpacitySlider: boolean;\n private showLayerSymbol: boolean;\n private excludeDrawnLayers: boolean;\n private excludeLayerPatterns: RegExp[];\n private customLayerRegistry: CustomLayerRegistry | null = null;\n private customLayerUnsubscribe: (() => void) | null = null;\n private removedCustomLayerIds: Set<string> = new Set();\n private nativeLayerGroups: Map<string, string[]> = new Map();\n /** Layer groups from the custom layer adapters, as of the last panel build */\n private groupStates: Map<string, LayerGroupState> = new Map();\n /** Group IDs, parents, and memberships the panel was last built from */\n private groupStructureKey = \"\";\n private basemapStyleUrl: string | null = null;\n private basemapLayerIds: Set<string> | null = null;\n /** True when `basemapLayerIds` came from the option, which is authoritative even when empty. */\n private basemapLayerIdsProvided = false;\n /** Set once onAdd has listed the map's layers (after any basemapStyleUrl fetch). */\n private layersListed = false;\n /** setLayerState calls made before the layers were listed, applied once they are. */\n private pendingLayerStates = new Map<\n string,\n Partial<Pick<LayerState, \"visible\" | \"opacity\" | \"name\">>\n >();\n /** Panel order set through setLayerOrder, used to order layers with nothing on the map. */\n private layerOrderHint: string[] | null = null;\n private widthFrame: number | null = null;\n\n // Exact-opacity input popup\n private opacityInputEl: HTMLDivElement | null = null;\n\n // Panel edge-drag resizing (handles on both the left and right edges)\n private resizeHandleEls: HTMLDivElement[] = [];\n /** Which edge is anchored to the control corner (the other edge is \"free\") */\n private panelAnchorSide: \"left\" | \"right\" = \"right\";\n private isPanelResizing = false;\n /** The physical edge being dragged in the current resize gesture */\n private panelResizeEdge: \"left\" | \"right\" = \"left\";\n private panelResizeStartX: number | null = null;\n private panelResizeStartWidth: number | null = null;\n private panelResizeStartOffset = 0;\n\n // Context menu and drag-drop\n private contextMenuEl: HTMLDivElement | null = null;\n private enableContextMenu: boolean;\n private enableDragAndDrop: boolean;\n private onLayerRename?: (\n layerId: string,\n oldName: string,\n newName: string,\n ) => void;\n private onLayerReorder?: (layerOrder: string[]) => void;\n private onLayerRemove?: (layerId: string) => void;\n private onLayerStyleChange?: (\n layerId: string,\n property: string,\n value: unknown,\n ) => void;\n private onBackgroundVisibilityChange?: (visible: boolean) => void;\n private onBackgroundOpacityChange?: (opacity: number) => void;\n\n // Background-layer visibility presets\n private enableBackgroundPresets: boolean;\n private backgroundPresetStorageKey: string;\n private onBackgroundPresetsChange?: (presets: BackgroundPresets) => void;\n\n constructor(options: LayerControlOptions = {}) {\n this.minPanelWidth = options.panelMinWidth || 240;\n this.maxPanelWidth = options.panelMaxWidth || 960;\n this.initialPanelWidth = options.panelWidth || 350;\n // When no explicit max height is given, the panel grows to fill the\n // available vertical space in the map container (computed in\n // updatePanelPosition) instead of being capped at a fixed height.\n this.maxPanelHeight = options.panelMaxHeight ?? null;\n this.showStyleEditor = options.showStyleEditor !== false;\n this.showAllStyleProperties = options.showAllStyleProperties === true;\n this.showOpacitySlider = options.showOpacitySlider !== false;\n this.showLayerSymbol = options.showLayerSymbol !== false;\n this.excludeDrawnLayers = options.excludeDrawnLayers !== false;\n this.excludeLayerPatterns = this.wildcardPatternsToRegex(\n options.excludeLayers || [],\n );\n\n // Context menu and drag-drop options\n this.enableContextMenu = options.enableContextMenu !== false;\n this.enableDragAndDrop = options.enableDragAndDrop !== false;\n this.onLayerRename = options.onLayerRename;\n this.onLayerReorder = options.onLayerReorder;\n this.onLayerRemove = options.onLayerRemove;\n this.onLayerStyleChange = options.onLayerStyleChange;\n this.onBackgroundVisibilityChange = options.onBackgroundVisibilityChange;\n this.onBackgroundOpacityChange = options.onBackgroundOpacityChange;\n\n // Background-layer visibility presets\n this.enableBackgroundPresets = options.enableBackgroundPresets !== false;\n this.backgroundPresetStorageKey =\n options.backgroundPresetStorageKey ||\n \"maplibre-layer-control:background-presets\";\n this.onBackgroundPresetsChange = options.onBackgroundPresetsChange;\n\n this.initialLayerStates = options.layerStates || {};\n\n this.state = {\n collapsed: options.collapsed !== false,\n panelWidth: options.panelWidth || 350,\n activeStyleEditor: null,\n layerStates: {},\n originalStyles: new Map<string, OriginalStyle>(),\n userInteractingWithSlider: false,\n backgroundLegendOpen: false,\n expandedCategoryLayers: new Set<string>(),\n backgroundLayerVisibility: new Map<string, boolean>(),\n onlyRenderedFilter: false,\n contextMenu: {\n visible: false,\n targetLayerId: null,\n x: 0,\n y: 0,\n },\n renamingLayerId: null,\n customLayerNames: new Map<string, string>(),\n drag: {\n active: false,\n layerId: null,\n startY: 0,\n currentY: 0,\n placeholder: null,\n draggedElement: null,\n },\n isStyleOperationInProgress: false,\n };\n\n this.targetLayers = options.layers || Object.keys(this.initialLayerStates);\n this.styleEditors = new Map<string, HTMLElement>();\n\n // Initialize custom layer registry if adapters are provided\n if (options.customLayerAdapters && options.customLayerAdapters.length > 0) {\n this.customLayerRegistry = new CustomLayerRegistry();\n options.customLayerAdapters.forEach((adapter) => {\n this.customLayerRegistry!.register(adapter);\n });\n }\n\n // Store basemap style URL for reliable layer detection\n this.basemapStyleUrl = options.basemapStyleUrl || null;\n if (options.basemapLayerIds) {\n this.basemapLayerIds = new Set(options.basemapLayerIds);\n this.basemapLayerIdsProvided = true;\n }\n }\n\n /**\n * Whether basemap membership is decided by a known list of basemap layer IDs\n * (the `basemapLayerIds` option, or the layers of `basemapStyleUrl`) rather\n * than by heuristics. A fetched style only counts when it had layers; an\n * explicit list counts even when empty.\n */\n private hasBasemapLayerIds(): boolean {\n return (\n this.basemapLayerIds !== null &&\n (this.basemapLayerIdsProvided || this.basemapLayerIds.size > 0)\n );\n }\n\n /**\n * Called when the control is added to the map\n */\n onAdd(map: MapLibreMap): HTMLElement {\n this.map = map;\n this.mapContainer = map.getContainer();\n this.layersListed = false;\n this.pendingLayerStates.clear();\n\n // Capture initial source IDs and layer IDs (basemap) before auto-detecting layers\n // Sources and layers added after this point are considered user-added\n const style = this.map.getStyle();\n if (style && style.sources) {\n this.initialSourceIds = new Set(Object.keys(style.sources));\n } else {\n this.initialSourceIds = new Set();\n }\n\n // Capture initial layer IDs - any layer added after this is user-added\n if (style && style.layers) {\n this.initialLayerIds = new Set(style.layers.map((layer) => layer.id));\n } else {\n this.initialLayerIds = new Set();\n }\n\n this.container = this.createContainer();\n this.button = this.createToggleButton();\n this.panel = this.createPanel();\n\n this.container.appendChild(this.button);\n // Append panel to map container for independent positioning (avoids overlap with other controls)\n this.mapContainer.appendChild(this.panel);\n\n // Create context menu element (appended to map container)\n if (this.enableContextMenu) {\n this.contextMenuEl = this.createContextMenu();\n this.mapContainer.appendChild(this.contextMenuEl);\n }\n\n // Setup event listeners\n this.setupEventListeners();\n\n // If basemapStyleUrl is provided, fetch it first for reliable layer detection\n if (this.basemapStyleUrl && !this.basemapLayerIds) {\n this.fetchBasemapStyle()\n .then(() => {\n // Auto-detect layers after basemap style is fetched\n if (Object.keys(this.state.layerStates).length === 0) {\n this.autoDetectLayers();\n }\n // Build layer items\n this.buildLayerItems();\n this.finishListing();\n })\n .catch((error) => {\n console.warn(\n \"Failed to fetch basemap style, falling back to heuristic detection:\",\n error,\n );\n // Fall back to heuristic detection\n if (Object.keys(this.state.layerStates).length === 0) {\n this.autoDetectLayers();\n }\n this.buildLayerItems();\n this.finishListing();\n });\n } else {\n // Auto-detect layers using source-based heuristics\n if (Object.keys(this.state.layerStates).length === 0) {\n this.autoDetectLayers();\n }\n // Build layer items\n this.buildLayerItems();\n this.finishListing();\n }\n\n // If panel starts expanded, update position after control is added to DOM\n if (!this.state.collapsed) {\n // Use requestAnimationFrame to wait until container is in DOM and positioned\n requestAnimationFrame(() => {\n this.updatePanelPosition();\n });\n }\n\n return this.container;\n }\n\n /**\n * Fetch the basemap style JSON and extract layer IDs.\n * This provides reliable distinction between basemap and user-added layers.\n */\n private async fetchBasemapStyle(): Promise<void> {\n if (!this.basemapStyleUrl) return;\n\n try {\n const response = await fetch(this.basemapStyleUrl);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n const styleJson = await response.json();\n\n // Extract layer IDs from the basemap style\n if (styleJson && Array.isArray(styleJson.layers)) {\n this.basemapLayerIds = new Set(\n styleJson.layers.map((layer: { id: string }) => layer.id),\n );\n } else {\n this.basemapLayerIds = new Set();\n }\n } catch (error) {\n console.warn(\n \"Failed to fetch basemap style from URL:\",\n this.basemapStyleUrl,\n error,\n );\n throw error;\n }\n }\n\n /**\n * Called when the control is removed from the map\n */\n onRemove(): void {\n // Clean up custom layer registry subscription\n if (this.customLayerUnsubscribe) {\n this.customLayerUnsubscribe();\n this.customLayerUnsubscribe = null;\n }\n if (this.customLayerRegistry) {\n this.customLayerRegistry.destroy();\n this.customLayerRegistry = null;\n }\n\n // Remove resize event listeners\n if (this.resizeHandler) {\n window.removeEventListener(\"resize\", this.resizeHandler);\n this.resizeHandler = null;\n }\n if (this.mapResizeHandler) {\n this.map.off(\"resize\", this.mapResizeHandler);\n this.mapResizeHandler = null;\n }\n\n // Remove map layer-change listeners. Left behind, they kept syncing a removed control on\n // every map event, and a host that rebuilds the control piled up one more set each time.\n for (const [type, fn] of this.mapLayerListeners) {\n this.map.off(type, fn);\n }\n this.mapLayerListeners = [];\n\n // Clean up context menu\n if (this.contextMenuEl) {\n this.contextMenuEl.parentNode?.removeChild(this.contextMenuEl);\n this.contextMenuEl = null;\n }\n\n // Clean up the exact-opacity input popup\n this.hideOpacityInput();\n\n // Clean up any active drag state\n this.cleanupDragState();\n\n // Remove panel from map container\n this.panel.parentNode?.removeChild(this.panel);\n\n // Remove button container from control stack\n this.container.parentNode?.removeChild(this.container);\n }\n\n /**\n * Auto-detect layers from the map and populate layerStates\n */\n private autoDetectLayers(): void {\n const style = this.map.getStyle();\n if (!style || !style.layers) {\n return;\n }\n\n // Get all layer IDs from the map\n const allLayerIds = style.layers.map((layer) => layer.id);\n\n if (this.targetLayers.length === 0) {\n // No layers specified - auto-detect user-added layers vs background layers\n const userAddedLayers: string[] = [];\n const backgroundLayerIds: string[] = [];\n\n // Detection priority for INITIAL detection:\n // 1. basemapLayerIds (from basemapStyleUrl) - most reliable\n // 2. Source-based heuristics - works for layers added before OR after control\n // Note: initialLayerIds is NOT used here because it would incorrectly classify\n // user layers added BEFORE the control as basemap layers\n const useBasemapStyleDetection =\n this.hasBasemapLayerIds();\n\n // Identify which sources are user-added (for source-based heuristic detection)\n const userAddedSourceIds = useBasemapStyleDetection\n ? new Set<string>()\n : this.detectUserAddedSources();\n\n allLayerIds.forEach((layerId) => {\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n\n // Skip drawn layers if excludeDrawnLayers is enabled\n if (this.excludeDrawnLayers && this.isDrawnLayer(layerId)) {\n backgroundLayerIds.push(layerId);\n return;\n }\n\n // Skip layers matching user-defined exclusion patterns\n if (this.isExcludedByPattern(layerId)) {\n backgroundLayerIds.push(layerId);\n return;\n }\n\n if (useBasemapStyleDetection) {\n // Use basemap style layer IDs for reliable detection\n if (this.basemapLayerIds!.has(layerId)) {\n // This layer is from the basemap style\n backgroundLayerIds.push(layerId);\n } else {\n // This layer is not in the basemap style - it's user-added\n userAddedLayers.push(layerId);\n }\n } else {\n // Use source-based heuristics\n // Check if this layer uses a user-added source\n const sourceId = (layer as any).source;\n if (sourceId && userAddedSourceIds.has(sourceId)) {\n userAddedLayers.push(layerId);\n } else {\n // Layer uses a basemap source or has no source (like background color layer)\n backgroundLayerIds.push(layerId);\n }\n }\n });\n\n // Add Background entry if there are background layers\n if (backgroundLayerIds.length > 0) {\n this.state.layerStates[\"Background\"] = {\n visible: true,\n opacity: 1.0,\n name: \"Background\",\n };\n }\n\n // Add entries for auto-detected user layers\n userAddedLayers.forEach((layerId) => {\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n\n const { visible: isVisible, opacity } = this.readLayerRowState(\n layerId,\n layer.type,\n );\n const friendlyName = this.generateFriendlyName(layerId);\n\n this.state.layerStates[layerId] = this.mergeWithUserState(layerId, {\n visible: isVisible,\n opacity: opacity,\n name: friendlyName,\n });\n });\n } else {\n // Specific layers requested - separate into user layers + Background\n const userLayers: string[] = [];\n const basemapLayers: string[] = [];\n\n allLayerIds.forEach((layerId) => {\n // Skip layers matching user-defined exclusion patterns\n if (this.isExcludedByPattern(layerId)) {\n basemapLayers.push(layerId);\n return;\n }\n\n if (this.targetLayers.includes(layerId)) {\n userLayers.push(layerId);\n } else {\n basemapLayers.push(layerId);\n }\n });\n\n // Add Background entry if there are basemap layers\n if (basemapLayers.length > 0) {\n this.state.layerStates[\"Background\"] = {\n visible: true,\n opacity: 1.0,\n name: \"Background\",\n };\n }\n\n // Add entries for user-specified layers\n userLayers.forEach((layerId) => {\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n\n const { visible: isVisible, opacity } = this.readLayerRowState(\n layerId,\n layer.type,\n );\n const friendlyName = this.generateFriendlyName(layerId);\n\n this.state.layerStates[layerId] = this.mergeWithUserState(layerId, {\n visible: isVisible,\n opacity: opacity,\n name: friendlyName,\n });\n });\n }\n\n // Detect custom layers from registry\n if (this.customLayerRegistry) {\n const customLayerIds = this.customLayerRegistry.getAllLayerIds();\n customLayerIds.forEach((layerId) => {\n // Skip if already in state\n if (this.state.layerStates[layerId]) return;\n\n const customState = this.customLayerRegistry!.getLayerState(layerId);\n if (customState) {\n this.state.layerStates[layerId] = {\n visible: customState.visible,\n opacity: customState.opacity,\n name: customState.name,\n isCustomLayer: true,\n customLayerType:\n this.customLayerRegistry!.getSymbolType(layerId) || undefined,\n };\n }\n });\n }\n\n // Update targetLayers to include detected layers\n this.targetLayers = Object.keys(this.state.layerStates);\n }\n\n /**\n * Detect which sources are user-added (not from the basemap style)\n * User-added sources are identified by:\n * - Sources that were NOT present when the control was first added\n * - Additionally for sources added later:\n * - GeoJSON sources with inline data objects (not URL strings)\n * - Image, video, canvas sources\n * - Raster, raster-dem, vector sources from non-basemap tile providers\n */\n private detectUserAddedSources(): Set<string> {\n const userAddedSources = new Set<string>();\n const style = this.map.getStyle();\n if (!style || !style.sources) return userAddedSources;\n\n // First, detect the basemap's domain from sprite/glyphs URLs\n const basemapDomains = new Set<string>();\n\n // Known basemap providers\n const knownBasemapProviders = [\n \"demotiles.maplibre.org\",\n \"api.maptiler.com\",\n \"tiles.stadiamaps.com\",\n \"api.mapbox.com\",\n \"basemaps.cartocdn.com\",\n \"tiles.mapbox.com\",\n \"a.basemaps.cartocdn.com\",\n \"b.basemaps.cartocdn.com\",\n \"c.basemaps.cartocdn.com\",\n \"d.basemaps.cartocdn.com\",\n \"tiles.arcgis.com\",\n \"server.arcgisonline.com\",\n \"services.arcgisonline.com\",\n ];\n\n // Detect domains from sprite/glyphs URLs (these are likely basemap domains)\n const spriteUrl = style.sprite as string | undefined;\n if (spriteUrl && typeof spriteUrl === \"string\") {\n try {\n const url = new URL(spriteUrl);\n basemapDomains.add(url.hostname);\n } catch {\n /* ignore */\n }\n }\n if (style.glyphs) {\n try {\n const url = new URL(\n style.glyphs.replace(\"{fontstack}\", \"x\").replace(\"{range}\", \"x\"),\n );\n basemapDomains.add(url.hostname);\n } catch {\n /* ignore */\n }\n }\n\n // Check each source\n for (const [sourceId, source] of Object.entries(style.sources)) {\n // If we have a snapshot of initial sources, use that as the primary check\n // Sources that existed when the control was added are basemap sources\n if (this.initialSourceIds && this.initialSourceIds.has(sourceId)) {\n // This source was present in the initial style, it's a basemap source\n continue;\n }\n\n const src = source as any;\n const sourceType = src.type;\n\n // Image, video, and canvas sources are always user-added\n if (\n sourceType === \"image\" ||\n sourceType === \"video\" ||\n sourceType === \"canvas\"\n ) {\n userAddedSources.add(sourceId);\n continue;\n }\n\n // GeoJSON sources with inline data objects are user-added (if added after initial load)\n if (sourceType === \"geojson\") {\n if (src.data && typeof src.data === \"object\") {\n userAddedSources.add(sourceId);\n } else if (src.data && typeof src.data === \"string\") {\n // GeoJSON with URL - check if it's from a basemap domain\n try {\n const url = new URL(src.data);\n const isBasemap =\n knownBasemapProviders.some((p) => url.hostname.includes(p)) ||\n basemapDomains.has(url.hostname);\n if (!isBasemap) {\n userAddedSources.add(sourceId);\n }\n } catch {\n // Relative URL or invalid - assume user-added\n userAddedSources.add(sourceId);\n }\n }\n continue;\n }\n\n // Check tile URLs for raster, raster-dem, and vector sources\n if (\n sourceType === \"raster\" ||\n sourceType === \"raster-dem\" ||\n sourceType === \"vector\"\n ) {\n const tileUrl = src.url || (src.tiles && src.tiles[0]) || \"\";\n if (tileUrl) {\n try {\n const url = new URL(tileUrl.replace(/{[^}]+}/g, \"0\"));\n const hostname = url.hostname;\n\n // Check if this is a known basemap provider\n const isKnownBasemap = knownBasemapProviders.some(\n (provider) =>\n hostname === provider || hostname.endsWith(\".\" + provider),\n );\n\n // Check if this matches detected basemap domains\n const matchesBasemapDomain = basemapDomains.has(hostname);\n\n // If not a basemap source, it's user-added\n if (!isKnownBasemap && !matchesBasemapDomain) {\n userAddedSources.add(sourceId);\n }\n } catch {\n // If URL parsing fails, assume it could be user-added\n userAddedSources.add(sourceId);\n }\n }\n }\n }\n\n return userAddedSources;\n }\n\n /**\n * Generate a friendly display name from a layer ID\n */\n private generateFriendlyName(layerId: string): string {\n // Remove common prefixes\n let name = layerId.replace(/^(layer[-_]?|gl[-_]?)/, \"\");\n\n // Replace dashes and underscores with spaces\n name = name.replace(/[-_]/g, \" \");\n\n // Capitalize first letter of each word\n name = name.replace(/\\b\\w/g, (char) => char.toUpperCase());\n\n return name || layerId; // Fallback to original if empty\n }\n\n /**\n * Merge auto-detected layer state with user-provided initial state.\n * User-provided values take precedence over detected values.\n */\n private mergeWithUserState(\n layerId: string,\n detected: LayerState,\n ): LayerState {\n const userState = this.initialLayerStates[layerId];\n if (!userState) return detected;\n\n return {\n visible: userState.visible ?? detected.visible,\n opacity: userState.opacity ?? detected.opacity,\n name: userState.name ?? detected.name,\n ...(userState.isCustomLayer !== undefined && {\n isCustomLayer: userState.isCustomLayer,\n }),\n ...(userState.customLayerType !== undefined && {\n customLayerType: userState.customLayerType,\n }),\n };\n }\n\n /**\n * Check if a layer ID belongs to a drawing library (Geoman, Mapbox GL Draw, etc.)\n * @param layerId The layer ID to check\n * @returns true if the layer is from a drawing library\n */\n private isDrawnLayer(layerId: string): boolean {\n const drawnLayerPatterns = [\n // Drawing libraries\n /^gm[-_\\s]/i, // Geoman (gm-main-*, gm_*, Gm Temporary...)\n /^gl-draw[-_]/i, // Mapbox GL Draw\n /^mapbox-gl-draw[-_]/i, // Mapbox GL Draw alternative\n /^terra-draw[-_]/i, // Terra Draw\n /^maplibre-gl-draw[-_]/i, // MapLibre GL Draw\n /^draw[-_]layer/i, // Generic draw layers\n // maplibre-gl-components internal layers\n /^measure-/i, // MeasureControl (measure-{id}-fill, measure-{id}-line)\n /^pmtiles-source-/i, // PMTilesLayerControl (managed via adapter)\n /^stac-search-footprints/i, // StacSearchControl footprint layers\n ];\n\n return drawnLayerPatterns.some((pattern) => pattern.test(layerId));\n }\n\n /**\n * Convert wildcard patterns (e.g., '*-temp-*', 'debug-*') to RegExp objects\n */\n private wildcardPatternsToRegex(patterns: string[]): RegExp[] {\n return patterns.map((pattern) => {\n // Escape special regex characters except *\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n // Convert * to .* for wildcard matching\n const regexStr = escaped.replace(/\\*/g, \".*\");\n return new RegExp(`^${regexStr}$`, \"i\");\n });\n }\n\n /**\n * Check if a layer matches any of the user-defined exclusion patterns\n */\n private isExcludedByPattern(layerId: string): boolean {\n return this.excludeLayerPatterns.some((pattern) => pattern.test(layerId));\n }\n\n /**\n * Create the main container element\n */\n private createContainer(): HTMLDivElement {\n const container = document.createElement(\"div\");\n container.className =\n \"maplibregl-ctrl maplibregl-ctrl-group maplibregl-ctrl-layer-control\";\n return container;\n }\n\n /**\n * Create the toggle button\n */\n private createToggleButton(): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.type = \"button\";\n button.title = \"Layer Control\";\n button.setAttribute(\"aria-label\", \"Layer Control\");\n\n // Create layers icon (SVG)\n const icon = document.createElement(\"span\");\n icon.className = \"layer-control-icon\";\n icon.innerHTML =\n '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\" ' +\n 'fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">' +\n '<polygon points=\"12 3 3 8.25 12 13.5 21 8.25 12 3\"></polygon>' +\n '<polyline points=\"3 12.75 12 18 21 12.75\"></polyline>' +\n '<polyline points=\"3 17.25 12 22 21 17.25\"></polyline>' +\n \"</svg>\";\n\n button.appendChild(icon);\n return button;\n }\n\n /**\n * Create the panel element\n */\n private createPanel(): HTMLDivElement {\n const panel = document.createElement(\"div\");\n panel.className = \"layer-control-panel\";\n\n // Set initial width directly on the element. The max height is computed\n // dynamically in updatePanelPosition so the panel fills the available\n // vertical space.\n panel.style.width = `${this.state.panelWidth}px`;\n if (this.maxPanelHeight != null) {\n panel.style.maxHeight = `${this.maxPanelHeight}px`;\n }\n\n if (!this.state.collapsed) {\n panel.classList.add(\"expanded\");\n }\n\n // Add header\n const header = this.createPanelHeader();\n panel.appendChild(header);\n\n // Add action buttons (Show All / Hide All)\n const actionButtons = this.createActionButtons();\n panel.appendChild(actionButtons);\n\n // Add draggable edge handles (both sides) for resizing the panel width\n panel.appendChild(this.createResizeHandle(\"left\"));\n panel.appendChild(this.createResizeHandle(\"right\"));\n\n return panel;\n }\n\n /**\n * Create a draggable edge handle for resizing the panel width. A handle is\n * added on each side so the panel can be resized by dragging either edge,\n * like a conventional resizable window.\n *\n * @param side Which physical edge of the panel the handle sits on\n */\n private createResizeHandle(side: \"left\" | \"right\"): HTMLDivElement {\n const handle = document.createElement(\"div\");\n handle.className = `layer-control-resize-handle layer-control-resize-handle-${side}`;\n handle.title = \"Drag to resize panel\";\n handle.setAttribute(\"role\", \"separator\");\n handle.setAttribute(\"aria-orientation\", \"vertical\");\n this.resizeHandleEls.push(handle);\n this.setupResizeHandleEvents(handle, side);\n return handle;\n }\n\n /**\n * Wire pointer events for an edge resize handle.\n *\n * @param handle The handle element\n * @param side Which physical edge of the panel the handle sits on\n */\n private setupResizeHandleEvents(\n handle: HTMLDivElement,\n side: \"left\" | \"right\",\n ): void {\n handle.addEventListener(\"pointerdown\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n this.isPanelResizing = true;\n this.panelResizeEdge = side;\n this.panelResizeStartX = event.clientX;\n this.panelResizeStartWidth = this.state.panelWidth;\n // Remember the current offset of the anchored edge so we can keep the\n // opposite (free) edge fixed when the anchored edge is dragged.\n this.panelResizeStartOffset =\n parseFloat(this.panel.style[this.panelAnchorSide]) || 0;\n handle.setPointerCapture(event.pointerId);\n this.panel.classList.add(\"resizing-active\");\n });\n\n handle.addEventListener(\"pointermove\", (event) => {\n if (!this.isPanelResizing) return;\n this.resizePanelFromPointer(event.clientX);\n });\n\n const endResize = (event: PointerEvent) => {\n if (!this.isPanelResizing) return;\n if (event.pointerId !== undefined) {\n try {\n handle.releasePointerCapture(event.pointerId);\n } catch {\n // Ignore release errors\n }\n }\n this.isPanelResizing = false;\n this.panelResizeStartX = null;\n this.panelResizeStartWidth = null;\n this.panel.classList.remove(\"resizing-active\");\n };\n\n handle.addEventListener(\"pointerup\", endResize);\n handle.addEventListener(\"pointercancel\", endResize);\n handle.addEventListener(\"lostpointercapture\", endResize);\n\n // Double-click resets to the default/initial width\n handle.addEventListener(\"dblclick\", (event) => {\n event.preventDefault();\n event.stopPropagation();\n this.applyPanelWidth(this.initialPanelWidth, true);\n });\n }\n\n /**\n * Compute and apply a new panel width from the pointer position during an\n * edge drag. Dragging the free edge changes the width while the anchored\n * edge stays put; dragging the anchored edge shifts the anchor so the free\n * edge stays put — both feel like resizing a normal window.\n */\n private resizePanelFromPointer(clientX: number): void {\n const dx = clientX - (this.panelResizeStartX ?? clientX);\n const startWidth = this.panelResizeStartWidth ?? this.state.panelWidth;\n\n // Dragging the left edge left widens; dragging the right edge right widens.\n const desiredWidth =\n this.panelResizeEdge === \"left\" ? startWidth - dx : startWidth + dx;\n const clamped = Math.round(\n Math.min(this.maxPanelWidth, Math.max(this.minPanelWidth, desiredWidth)),\n );\n\n // When the dragged edge is the anchored edge, move the anchor so the\n // opposite edge does not drift.\n if (this.panelResizeEdge === this.panelAnchorSide) {\n let appliedDelta = clamped - startWidth;\n let newOffset = this.panelResizeStartOffset - appliedDelta;\n if (newOffset < 0) {\n // Don't push the panel past the map edge; cap the growth instead.\n newOffset = 0;\n appliedDelta = this.panelResizeStartOffset;\n }\n const finalWidth = Math.round(\n Math.min(\n this.maxPanelWidth,\n Math.max(this.minPanelWidth, startWidth + appliedDelta),\n ),\n );\n this.applyPanelWidth(finalWidth, true);\n this.panel.style[this.panelAnchorSide] = `${newOffset}px`;\n } else {\n this.applyPanelWidth(clamped, true);\n }\n }\n\n /**\n * Record which panel edge is anchored to the control corner, based on the\n * corner the control occupies. Right corners anchor the right edge (panel\n * grows leftward); left corners anchor the left edge (panel grows rightward).\n */\n private updatePanelAnchorSide(\n position: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\",\n ): void {\n this.panelAnchorSide =\n position === \"top-right\" || position === \"bottom-right\"\n ? \"right\"\n : \"left\";\n }\n\n /**\n * Detect which corner the control is positioned in\n * @returns The position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'\n */\n private getControlPosition():\n | \"top-left\"\n | \"top-right\"\n | \"bottom-left\"\n | \"bottom-right\" {\n const parent = this.container.parentElement;\n if (!parent) return \"top-right\"; // Default\n\n if (parent.classList.contains(\"maplibregl-ctrl-top-left\"))\n return \"top-left\";\n if (parent.classList.contains(\"maplibregl-ctrl-top-right\"))\n return \"top-right\";\n if (parent.classList.contains(\"maplibregl-ctrl-bottom-left\"))\n return \"bottom-left\";\n if (parent.classList.contains(\"maplibregl-ctrl-bottom-right\"))\n return \"bottom-right\";\n\n return \"top-right\"; // Default\n }\n\n /**\n * Update the panel position based on button location and control corner\n * Positions the panel next to the button, expanding in the appropriate direction\n */\n private updatePanelPosition(): void {\n if (!this.button || !this.panel || !this.mapContainer) return;\n\n const buttonRect = this.button.getBoundingClientRect();\n const mapRect = this.mapContainer.getBoundingClientRect();\n const position = this.getControlPosition();\n\n // Track which edge is anchored to the control corner (for edge-drag resize)\n this.updatePanelAnchorSide(position);\n\n // Calculate button position relative to map container\n const buttonTop = buttonRect.top - mapRect.top;\n const buttonBottom = mapRect.bottom - buttonRect.bottom;\n const buttonLeft = buttonRect.left - mapRect.left;\n const buttonRight = mapRect.right - buttonRect.right;\n\n const panelGap = 5; // Gap between button and panel\n\n // Reset all positioning\n this.panel.style.top = \"\";\n this.panel.style.bottom = \"\";\n this.panel.style.left = \"\";\n this.panel.style.right = \"\";\n\n switch (position) {\n case \"top-left\":\n // Panel expands down and to the right\n this.panel.style.top = `${buttonTop + buttonRect.height + panelGap}px`;\n this.panel.style.left = `${buttonLeft}px`;\n break;\n\n case \"top-right\":\n // Panel expands down and to the left\n this.panel.style.top = `${buttonTop + buttonRect.height + panelGap}px`;\n this.panel.style.right = `${buttonRight}px`;\n break;\n\n case \"bottom-left\":\n // Panel expands up and to the right\n this.panel.style.bottom = `${buttonBottom + buttonRect.height + panelGap}px`;\n this.panel.style.left = `${buttonLeft}px`;\n break;\n\n case \"bottom-right\":\n // Panel expands up and to the left\n this.panel.style.bottom = `${buttonBottom + buttonRect.height + panelGap}px`;\n this.panel.style.right = `${buttonRight}px`;\n break;\n }\n\n // Let the panel use all the available vertical space in the map container\n // so a long layer list fills the space before a scrollbar appears, rather\n // than being capped at a fixed height. A user-provided panelMaxHeight still\n // caps the panel.\n const edgeMargin = 8; // keep the panel off the opposite map edge\n const isTopAnchored = position === \"top-left\" || position === \"top-right\";\n const occupiedFromEdge = isTopAnchored\n ? buttonTop + buttonRect.height + panelGap\n : buttonBottom + buttonRect.height + panelGap;\n const availableHeight = Math.max(\n 120,\n Math.round(mapRect.height - occupiedFromEdge - edgeMargin),\n );\n const maxHeight =\n this.maxPanelHeight != null\n ? Math.min(this.maxPanelHeight, availableHeight)\n : availableHeight;\n this.panel.style.maxHeight = `${maxHeight}px`;\n }\n\n /**\n * Create action buttons for Show All / Hide All\n */\n private createActionButtons(): HTMLElement {\n const container = document.createElement(\"div\");\n container.className = \"layer-control-actions\";\n\n const showAllBtn = document.createElement(\"button\");\n showAllBtn.type = \"button\";\n showAllBtn.className = \"layer-control-action-btn\";\n showAllBtn.textContent = \"Show All\";\n showAllBtn.title = \"Show all layers\";\n showAllBtn.addEventListener(\"click\", () =>\n this.setAllLayersVisibility(true),\n );\n\n const hideAllBtn = document.createElement(\"button\");\n hideAllBtn.type = \"button\";\n hideAllBtn.className = \"layer-control-action-btn\";\n hideAllBtn.textContent = \"Hide All\";\n hideAllBtn.title = \"Hide all layers\";\n hideAllBtn.addEventListener(\"click\", () =>\n this.setAllLayersVisibility(false),\n );\n\n container.appendChild(showAllBtn);\n container.appendChild(hideAllBtn);\n\n return container;\n }\n\n /**\n * Set visibility of all layers\n */\n private setAllLayersVisibility(visible: boolean): void {\n // A hidden group would keep its layers hidden, so Show All / Hide All\n // covers the groups as well.\n this.groupStates.forEach((_group, groupId) => {\n this.setGroupVisibility(groupId, visible);\n });\n\n Object.keys(this.state.layerStates).forEach((layerId) => {\n // Use toggleLayerVisibility which handles both native and custom layers\n this.toggleLayerVisibility(layerId, visible);\n\n // Update checkbox in UI\n const itemEl = this.panel.querySelector(`[data-layer-id=\"${layerId}\"]`);\n if (itemEl) {\n const checkbox = itemEl.querySelector(\n \".layer-control-checkbox\",\n ) as HTMLInputElement;\n if (checkbox) {\n checkbox.checked = visible;\n checkbox.indeterminate = false;\n }\n }\n });\n }\n\n /**\n * Create the panel header with the title. Panel width is adjusted by\n * dragging either edge of the panel (see createResizeHandle).\n */\n private createPanelHeader(): HTMLElement {\n const header = document.createElement(\"div\");\n header.className = \"layer-control-panel-header\";\n\n const title = document.createElement(\"span\");\n title.className = \"layer-control-panel-title\";\n title.textContent = \"Layers\";\n header.appendChild(title);\n\n return header;\n }\n\n /**\n * Apply panel width (clamped to min/max)\n */\n private applyPanelWidth(width: number, immediate = false): void {\n const clamped = Math.round(\n Math.min(this.maxPanelWidth, Math.max(this.minPanelWidth, width)),\n );\n\n const applyWidth = () => {\n this.state.panelWidth = clamped;\n const px = `${clamped}px`;\n this.panel.style.width = px;\n };\n\n if (immediate) {\n applyWidth();\n return;\n }\n\n if (this.widthFrame) {\n cancelAnimationFrame(this.widthFrame);\n }\n this.widthFrame = requestAnimationFrame(() => {\n applyWidth();\n this.widthFrame = null;\n });\n }\n\n /**\n * Setup main event listeners\n */\n private setupEventListeners(): void {\n // Toggle button click\n this.button.addEventListener(\"click\", () => this.toggle());\n\n // Click outside to close panel and context menu\n document.addEventListener(\"click\", (e) => {\n const target = e.target as Node;\n\n // Close context menu if clicking outside of it\n if (this.contextMenuEl && this.state.contextMenu.visible) {\n if (!this.contextMenuEl.contains(target)) {\n this.hideContextMenu();\n }\n }\n\n // Close panel if clicking outside\n if (!this.container.contains(target) && !this.panel.contains(target)) {\n this.collapse();\n }\n });\n\n // Update panel position on window resize\n this.resizeHandler = () => {\n if (!this.state.collapsed) {\n this.updatePanelPosition();\n }\n };\n window.addEventListener(\"resize\", this.resizeHandler);\n\n // Update panel position on map resize (e.g., sidebar toggle)\n this.mapResizeHandler = () => {\n if (!this.state.collapsed) {\n this.updatePanelPosition();\n }\n };\n this.map.on(\"resize\", this.mapResizeHandler);\n\n // Listen for map layer changes\n this.setupLayerChangeListeners();\n }\n\n /**\n * Setup listeners for map layer changes\n */\n private setupLayerChangeListeners(): void {\n const listen = <T extends keyof MapEventType>(\n type: T,\n fn: (e: MapEventType[T]) => void,\n ): void => {\n this.map.on(type, fn);\n this.mapLayerListeners.push([\n type,\n fn as (e: MapEventType[keyof MapEventType]) => void,\n ]);\n };\n\n listen(\"styledata\", () => {\n setTimeout(() => {\n this.updateLayerStatesFromMap();\n this.checkForNewLayers();\n this.updateFillSymbols();\n this.refreshLayerCategories();\n }, 100);\n });\n\n // Observe updated image pixels after the next completed map render.\n listen(\"idle\", () => this.updateFillSymbols());\n\n listen(\"data\", (e) => {\n if (\"sourceDataType\" in e && e.sourceDataType === \"content\") {\n setTimeout(() => {\n this.updateLayerStatesFromMap();\n this.checkForNewLayers();\n }, 100);\n }\n });\n\n listen(\"sourcedata\", (e) => {\n if (e.sourceDataType === \"metadata\") {\n setTimeout(() => {\n this.checkForNewLayers();\n }, 150);\n }\n });\n\n // Subscribe to custom layer registry changes\n if (this.customLayerRegistry) {\n this.customLayerUnsubscribe = this.customLayerRegistry.onChange(\n (event, layerId) => {\n // If a previously removed layer is re-added, allow it to appear again\n if (event === \"add\" && layerId) {\n this.removedCustomLayerIds.delete(layerId);\n }\n setTimeout(() => this.checkForNewLayers(), 100);\n },\n );\n }\n }\n\n /**\n * Toggle panel expanded/collapsed state\n */\n private toggle(): void {\n if (this.state.collapsed) {\n this.expand();\n } else {\n this.collapse();\n }\n }\n\n /**\n * Whether the panel is collapsed (closed). Before the control is added to a\n * map this reflects the `collapsed` option.\n * @returns True while the panel is closed\n */\n isCollapsed(): boolean {\n return this.state.collapsed;\n }\n\n /**\n * Expand (open) the panel. Before the control is added to a map this only\n * records the state, and the panel opens when it is built.\n */\n expand(): void {\n this.state.collapsed = false;\n if (!this.panel) return;\n this.panel.classList.add(\"expanded\");\n this.updatePanelPosition();\n }\n\n /**\n * Collapse (close) the panel.\n */\n collapse(): void {\n this.state.collapsed = true;\n this.panel?.classList.remove(\"expanded\");\n }\n\n /**\n * Update a layer row's visibility, opacity and name in place, without\n * touching the map or firing any callback. Use it to mirror changes made\n * outside the control (for example by an application store that owns layer\n * state) into an already-built panel without rebuilding it.\n *\n * Only layers the control already lists are updated, with one exception:\n * `\"Background\"` adds the Background row when the control has none (a style\n * whose basemap lives in style imports has no root basemap layers to detect,\n * so the control would otherwise show no Background row).\n *\n * Until the control has listed the map's layers (during `onAdd`, and while a\n * `basemapStyleUrl` fetch is in flight) the update is queued and applied\n * once they are listed, since seeding state earlier would stop the control\n * from detecting layers on its own.\n *\n * @param layerId The layer ID, or `\"Background\"` for the basemap row\n * @param state The fields to change; omitted fields keep their value\n * @returns True if a layer state was updated, created or queued; false\n * before the control is added to a map or for a layer it does not list\n */\n setLayerState(layerId: string, state: Partial<Pick<LayerState, \"visible\" | \"opacity\" | \"name\">>): boolean {\n if (!this.panel) return false;\n if (!this.layersListed) {\n const queued = { ...this.pendingLayerStates.get(layerId) };\n // Merge only defined fields, matching how an applied update treats them.\n if (state.visible !== undefined) queued.visible = state.visible;\n if (state.opacity !== undefined) queued.opacity = state.opacity;\n if (state.name !== undefined) queued.name = state.name;\n this.pendingLayerStates.set(layerId, queued);\n return true;\n }\n let current = this.state.layerStates[layerId];\n if (!current) {\n if (layerId !== \"Background\") return false;\n current = this.state.layerStates.Background = {\n visible: state.visible ?? true,\n opacity: state.opacity ?? 1,\n name: state.name ?? \"Background\",\n };\n this.buildLayerItems();\n }\n if (state.visible !== undefined) current.visible = state.visible;\n if (state.opacity !== undefined) current.opacity = state.opacity;\n if (state.name !== undefined) {\n current.name = state.name;\n // A context-menu rename is cached and wins on the next rebuild.\n if (this.state.customLayerNames.has(layerId)) {\n this.state.customLayerNames.set(layerId, state.name);\n }\n }\n\n for (const item of this.rowsByLayerId().get(layerId) ?? []) {\n const checkbox = item.querySelector<HTMLInputElement>(\n \":scope > .layer-control-row > .layer-control-checkbox\",\n );\n if (checkbox) checkbox.checked = current.visible;\n const slider = item.querySelector<HTMLInputElement>(\n \":scope > .layer-control-row > .layer-control-opacity\",\n );\n if (slider) {\n slider.value = String(current.opacity);\n slider.title = `Opacity: ${Math.round(current.opacity * 100)}%`;\n }\n const name = item.querySelector<HTMLElement>(\n \":scope > .layer-control-row > .layer-control-name\",\n );\n if (name) {\n name.textContent = current.name;\n name.title = current.name;\n }\n }\n return true;\n }\n\n /**\n * Mark the map's layers as listed and apply setLayerState calls queued\n * before then.\n */\n private finishListing(): void {\n this.layersListed = true;\n const pending = [...this.pendingLayerStates];\n this.pendingLayerStates.clear();\n for (const [layerId, state] of pending) this.setLayerState(layerId, state);\n }\n\n /**\n * Set the order the panel lists layers in, then redraw the rows.\n *\n * Layers whose native MapLibre layers are on the map are always listed in\n * map stacking order; this order applies to the rest (custom-adapter layers\n * with nothing on the map yet, such as hidden ones). Use it to put the panel\n * back after an application refused a drag or context-menu move, since the\n * control has already moved the row by then. Layers not listed keep their\n * relative order after the listed ones, and Background stays at the bottom.\n * A hidden custom layer whose adapter has other layers on the map keeps its\n * slot beside them in that adapter's list, since the adapter is the source of\n * truth for where it sits; this order breaks the remaining ties.\n *\n * @param layerIds Layer IDs, top of the panel first\n */\n setLayerOrder(layerIds: readonly string[]): void {\n const states = this.state.layerStates;\n const order: string[] = [];\n const seen = new Set<string>([\"Background\"]);\n for (const id of [...layerIds, ...Object.keys(states)]) {\n if (id in states && !seen.has(id)) {\n seen.add(id);\n order.push(id);\n }\n }\n // Kept as a list: object key order cannot hold integer-like IDs in order.\n this.layerOrderHint = order;\n const ordered: LayerStates = {};\n if (\"Background\" in states) ordered.Background = states.Background;\n for (const id of order) ordered[id] = states[id];\n this.state.layerStates = ordered;\n if (this.panel) this.buildLayerItems();\n }\n\n /**\n * Build layer items (called initially and when layers change)\n */\n private buildLayerItems(): void {\n // Clear existing items (a group element takes its nested items with it)\n const existingItems = this.panel.querySelectorAll(\n \".layer-control-item, .layer-control-group\",\n );\n existingItems.forEach((item) => item.remove());\n this.styleEditors.clear();\n\n // Render in map stacking order: the top of the panel is the top-most layer\n // (highest z-index, rendered last) and the bottom is the lowest. The\n // Background group always sits at the very bottom, matching the basemap\n // being the bottom-most map layer. Iterating layerStates in insertion order\n // would instead put Background on top and reverse the user layers, so the\n // panel order would not match the actual map order (issue #449).\n const orderedLayerIds = this.getUserLayerIdsInMapOrder();\n\n // Include any user layers that map-order detection did not capture (e.g.\n // transient states where the layer is not yet on the map) so nothing\n // silently disappears from the panel.\n const captured = new Set(orderedLayerIds);\n for (const layerId of Object.keys(this.state.layerStates)) {\n if (layerId !== \"Background\" && !captured.has(layerId)) {\n orderedLayerIds.push(layerId);\n }\n }\n\n // Background always renders last so it appears at the bottom of the panel.\n if (this.state.layerStates[\"Background\"]) {\n orderedLayerIds.push(\"Background\");\n }\n\n this.groupStates = new Map(\n (this.customLayerRegistry?.getGroups() ?? []).map((group) => [\n group.id,\n { ...group },\n ]),\n );\n this.groupStructureKey = this.computeGroupStructureKey(this.groupStates);\n\n // Group elements created so far in this build, keyed by group ID, so each\n // group renders once, at the position of its top-most layer.\n const groupContainers = new Map<string, HTMLElement>();\n\n // Add items for all layers in our state. The Background group is a synthetic\n // entry (not a real target layer), so it always renders when present even\n // when an explicit targetLayers list is in use; otherwise restricting the\n // control to specific layers would hide the basemap group entirely.\n orderedLayerIds.forEach((layerId) => {\n const state = this.state.layerStates[layerId];\n if (!state) {\n return;\n }\n if (\n layerId === \"Background\" ||\n this.targetLayers.length === 0 ||\n this.targetLayers.includes(layerId)\n ) {\n const container =\n layerId === \"Background\"\n ? this.panel\n : this.getGroupContainer(\n this.getLayerGroupIdOf(layerId),\n groupContainers,\n new Set(),\n );\n this.addLayerItem(layerId, state, container);\n }\n });\n }\n\n /**\n * Get the ID of the group a layer belongs to, ignoring a group ID that no\n * adapter defines.\n * @param layerId The layer ID\n * @returns The group ID, or undefined when the layer is ungrouped\n */\n private getLayerGroupIdOf(layerId: string): string | undefined {\n if (this.groupStates.size === 0) return undefined;\n const groupId = this.customLayerRegistry?.getLayerGroupId(layerId);\n return groupId !== undefined && this.groupStates.has(groupId)\n ? groupId\n : undefined;\n }\n\n /**\n * Get the element a group's rows go into, creating the group (and any\n * enclosing groups) on first use.\n * @param groupId The group ID, or undefined for the panel's top level\n * @param containers Group child containers already created in this build\n * @param visiting Groups on the current parent chain, to stop on a cycle\n * @returns The element to append the group's rows to\n */\n private getGroupContainer(\n groupId: string | undefined,\n containers: Map<string, HTMLElement>,\n visiting: Set<string>,\n ): HTMLElement {\n if (groupId === undefined) return this.panel;\n const existing = containers.get(groupId);\n if (existing) return existing;\n const group = this.groupStates.get(groupId);\n if (!group || visiting.has(groupId)) return this.panel;\n visiting.add(groupId);\n\n const parentId =\n group.parentId !== undefined && this.groupStates.has(group.parentId)\n ? group.parentId\n : undefined;\n const parent = this.getGroupContainer(parentId, containers, visiting);\n const { element, children } = this.createGroupItem(group);\n parent.appendChild(element);\n containers.set(groupId, children);\n return children;\n }\n\n /**\n * Summarize the group structure the panel is built from: each group's ID\n * and parent, and each layer's group. A change to any of these needs a\n * rebuild; a change to a group's name, visibility, opacity, or collapsed\n * state does not.\n * @param groups The groups to summarize\n * @returns A string that changes whenever the structure does\n */\n private computeGroupStructureKey(groups: Map<string, LayerGroupState>): string {\n if (groups.size === 0) return \"\";\n const memberships = Object.keys(this.state.layerStates)\n .filter((layerId) => layerId !== \"Background\")\n .map((layerId) => [\n layerId,\n this.customLayerRegistry?.getLayerGroupId(layerId) ?? null,\n ]);\n return JSON.stringify({\n groups: Array.from(groups.values(), (group) => [\n group.id,\n group.parentId ?? null,\n ]),\n memberships,\n });\n }\n\n /**\n * Create the element for a layer group: a header row with a collapse\n * toggle, visibility checkbox, name, and opacity slider, followed by a\n * container for the group's layers and nested groups.\n * @param group The group to render\n * @returns The group element and its child container\n */\n private createGroupItem(group: LayerGroupState): {\n element: HTMLElement;\n children: HTMLElement;\n } {\n const element = document.createElement(\"div\");\n element.className = \"layer-control-group\";\n element.setAttribute(\"data-group-id\", group.id);\n\n const row = document.createElement(\"div\");\n row.className = \"layer-control-row layer-control-group-row\";\n\n // Groups are not draggable; keep the rows aligned with the layer rows.\n if (this.enableDragAndDrop) {\n row.appendChild(this.createDisabledDragHandle());\n }\n\n const checkbox = document.createElement(\"input\");\n checkbox.type = \"checkbox\";\n checkbox.className = \"layer-control-checkbox layer-control-group-checkbox\";\n checkbox.addEventListener(\"change\", () => {\n this.setGroupVisibility(group.id, checkbox.checked);\n });\n row.appendChild(checkbox);\n\n if (this.showLayerSymbol) {\n const symbol = document.createElement(\"span\");\n symbol.className = \"layer-control-symbol layer-control-group-symbol\";\n symbol.innerHTML = `<svg viewBox=\"0 0 16 16\" aria-hidden=\"true\">\n <path d=\"M1.5 3.5h4.5l1.5 1.5h7v8.5h-13z\" fill=\"#f2c94c\" stroke=\"#b8902a\" stroke-width=\"1\"/>\n </svg>`;\n symbol.title = \"Layer group\";\n row.appendChild(symbol);\n }\n\n const name = document.createElement(\"span\");\n name.className = \"layer-control-name layer-control-group-name\";\n row.appendChild(name);\n\n if (this.showOpacitySlider) {\n const opacity = document.createElement(\"input\");\n opacity.type = \"range\";\n opacity.className = \"layer-control-opacity layer-control-group-opacity\";\n opacity.min = \"0\";\n opacity.max = \"1\";\n opacity.step = \"0.01\";\n opacity.addEventListener(\"mousedown\", () => {\n this.state.userInteractingWithSlider = true;\n });\n opacity.addEventListener(\"mouseup\", () => {\n this.state.userInteractingWithSlider = false;\n });\n opacity.addEventListener(\"input\", () => {\n this.setGroupOpacity(group.id, parseFloat(opacity.value));\n });\n // Double-click to enter an exact opacity percentage (0-100)\n opacity.addEventListener(\"dblclick\", (event) => {\n event.preventDefault();\n this.showOpacityInput(opacity, (value) =>\n this.setGroupOpacity(group.id, value),\n );\n });\n row.appendChild(opacity);\n }\n\n // The collapse toggle sits at the end of the row, in the slot the layer\n // rows give their style button, so the group's checkbox and slider line\n // up with the layers' own.\n const toggle = document.createElement(\"button\");\n toggle.type = \"button\";\n toggle.className = \"layer-control-group-toggle\";\n toggle.innerHTML = `<svg viewBox=\"0 0 16 16\" fill=\"currentColor\" aria-hidden=\"true\">\n <path d=\"M6 4l4 4-4 4z\"/>\n </svg>`;\n toggle.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.setGroupCollapsed(group.id, !this.groupStates.get(group.id)?.collapsed);\n });\n row.appendChild(toggle);\n\n const children = document.createElement(\"div\");\n children.className = \"layer-control-group-children\";\n\n element.appendChild(row);\n element.appendChild(children);\n this.updateGroupElement(element, group);\n\n return { element, children };\n }\n\n /**\n * Show a group's state on its element.\n * @param element The group element\n * @param group The group state to show\n */\n private updateGroupElement(element: HTMLElement, group: LayerGroupState): void {\n element.classList.toggle(\"collapsed\", group.collapsed);\n element.classList.toggle(\"layer-control-group-hidden\", !group.visible);\n\n const row = element.querySelector(\":scope > .layer-control-group-row\");\n if (!row) return;\n\n const toggle = row.querySelector(\n \".layer-control-group-toggle\",\n ) as HTMLButtonElement | null;\n if (toggle) {\n toggle.setAttribute(\"aria-expanded\", String(!group.collapsed));\n toggle.title = group.collapsed ? \"Expand group\" : \"Collapse group\";\n toggle.setAttribute(\n \"aria-label\",\n `${group.collapsed ? \"Expand\" : \"Collapse\"} ${group.name}`,\n );\n }\n\n const checkbox = row.querySelector(\n \".layer-control-group-checkbox\",\n ) as HTMLInputElement | null;\n if (checkbox) checkbox.checked = group.visible;\n\n const name = row.querySelector(\".layer-control-group-name\") as HTMLElement | null;\n if (name) {\n name.textContent = group.name;\n name.title = group.name;\n }\n\n const opacity = row.querySelector(\n \".layer-control-group-opacity\",\n ) as HTMLInputElement | null;\n if (opacity) {\n opacity.value = String(group.opacity);\n opacity.title = `Opacity: ${Math.round(group.opacity * 100)}%`;\n }\n }\n\n /**\n * Get the element of a rendered group.\n * @param groupId The group ID\n * @returns The group element, or null when the group is not rendered\n */\n private getGroupElement(groupId: string): HTMLElement | null {\n const groups = this.panel.querySelectorAll(\".layer-control-group\");\n for (const element of Array.from(groups)) {\n if ((element as HTMLElement).dataset.groupId === groupId) {\n return element as HTMLElement;\n }\n }\n return null;\n }\n\n /**\n * Remove group elements left without any layer row, e.g. after their last\n * layer was removed.\n */\n private pruneEmptyGroups(): void {\n const groups = Array.from(this.panel.querySelectorAll(\".layer-control-group\"));\n // Innermost groups come last in document order; prune them first so an\n // enclosing group emptied by the removal is pruned too.\n for (const element of groups.reverse()) {\n if (!element.querySelector(\".layer-control-item\")) element.remove();\n }\n }\n\n /**\n * Set a group's visibility from the panel and report it to its adapter.\n * @param groupId The group ID\n * @param visible Whether the group should be visible\n */\n private setGroupVisibility(groupId: string, visible: boolean): void {\n const group = this.groupStates.get(groupId);\n if (!group) return;\n group.visible = visible;\n const element = this.getGroupElement(groupId);\n if (element) this.updateGroupElement(element, group);\n\n this.state.isStyleOperationInProgress = true;\n this.customLayerRegistry?.setGroupVisibility(groupId, visible);\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n }\n\n /**\n * Set a group's opacity from the panel and report it to its adapter.\n * @param groupId The group ID\n * @param opacity The opacity value (0-1)\n */\n private setGroupOpacity(groupId: string, opacity: number): void {\n const group = this.groupStates.get(groupId);\n if (!group) return;\n group.opacity = opacity;\n const element = this.getGroupElement(groupId);\n if (element) this.updateGroupElement(element, group);\n\n this.state.isStyleOperationInProgress = true;\n this.customLayerRegistry?.setGroupOpacity(groupId, opacity);\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n }\n\n /**\n * Collapse or expand a group in the panel and report it to its adapter.\n * @param groupId The group ID\n * @param collapsed Whether the group should be collapsed\n */\n private setGroupCollapsed(groupId: string, collapsed: boolean): void {\n const group = this.groupStates.get(groupId);\n if (!group) return;\n group.collapsed = collapsed;\n const element = this.getGroupElement(groupId);\n if (element) this.updateGroupElement(element, group);\n this.customLayerRegistry?.setGroupCollapsed(groupId, collapsed);\n }\n\n /**\n * Re-read the layer groups from the custom layer adapters. Call this after\n * groups change outside the control. The panel is rebuilt when a group was\n * added, removed, or re-parented, or a layer changed group; otherwise the\n * group rows' name, visibility, opacity, and collapsed state are updated in\n * place.\n */\n refreshGroups(): void {\n if (!this.panel) return;\n const next = new Map(\n (this.customLayerRegistry?.getGroups() ?? []).map((group) => [\n group.id,\n { ...group },\n ]),\n );\n if (this.computeGroupStructureKey(next) !== this.groupStructureKey) {\n this.buildLayerItems();\n return;\n }\n this.groupStates = next;\n next.forEach((group, groupId) => {\n const element = this.getGroupElement(groupId);\n if (element) this.updateGroupElement(element, group);\n });\n }\n\n /**\n * Add a single layer item to the panel\n */\n private addLayerItem(\n layerId: string,\n state: LayerState,\n container: HTMLElement = this.panel,\n ): void {\n const item = document.createElement(\"div\");\n item.className = \"layer-control-item\";\n item.setAttribute(\"data-layer-id\", layerId);\n\n const row = document.createElement(\"div\");\n row.className = \"layer-control-row\";\n\n // Add drag handle (disabled for Background layer for alignment)\n if (this.enableDragAndDrop) {\n if (layerId === \"Background\") {\n const disabledHandle = this.createDisabledDragHandle();\n row.appendChild(disabledHandle);\n } else {\n const dragHandle = this.createDragHandle(layerId);\n row.appendChild(dragHandle);\n }\n }\n\n // Visibility checkbox\n const checkbox = document.createElement(\"input\");\n checkbox.type = \"checkbox\";\n checkbox.className = \"layer-control-checkbox\";\n checkbox.checked = state.visible;\n checkbox.addEventListener(\"change\", () => {\n this.toggleLayerVisibility(layerId, checkbox.checked);\n });\n\n // Layer name - use custom name if set\n const displayName =\n this.state.customLayerNames.get(layerId) || state.name || layerId;\n const name = document.createElement(\"span\");\n name.className = \"layer-control-name\";\n name.textContent = displayName;\n name.title = displayName;\n\n row.appendChild(checkbox);\n\n // Add layer symbol (if enabled)\n if (this.showLayerSymbol) {\n if (layerId === \"Background\") {\n // Special stacked layers symbol for background group\n const symbol = this.createBackgroundGroupSymbol();\n row.appendChild(symbol);\n } else {\n const symbol = this.createLayerSymbol(layerId);\n if (symbol) {\n row.appendChild(symbol);\n }\n }\n }\n\n row.appendChild(name);\n\n // Opacity slider (conditionally shown)\n if (this.showOpacitySlider) {\n const opacity = document.createElement(\"input\");\n opacity.type = \"range\";\n opacity.className = \"layer-control-opacity\";\n opacity.min = \"0\";\n opacity.max = \"1\";\n opacity.step = \"0.01\";\n opacity.value = String(state.opacity);\n opacity.title = `Opacity: ${Math.round(state.opacity * 100)}%`;\n\n // Handle slider interaction tracking\n opacity.addEventListener(\"mousedown\", () => {\n this.state.userInteractingWithSlider = true;\n });\n opacity.addEventListener(\"mouseup\", () => {\n this.state.userInteractingWithSlider = false;\n });\n\n opacity.addEventListener(\"input\", () => {\n this.changeLayerOpacity(layerId, parseFloat(opacity.value));\n opacity.title = `Opacity: ${Math.round(parseFloat(opacity.value) * 100)}%`;\n });\n\n // Double-click to enter an exact opacity percentage (0-100)\n opacity.addEventListener(\"dblclick\", (event) => {\n event.preventDefault();\n this.showOpacityInput(opacity, (value) =>\n this.changeLayerOpacity(layerId, value),\n );\n });\n\n row.appendChild(opacity);\n }\n\n // Style button for regular layers, legend button for Background\n if (this.showStyleEditor) {\n if (layerId === \"Background\") {\n const legendButton = this.createBackgroundLegendButton();\n row.appendChild(legendButton);\n } else {\n const styleButton = this.createStyleButton(layerId);\n if (styleButton) {\n row.appendChild(styleButton);\n }\n }\n }\n\n item.appendChild(row);\n if (this.showLayerSymbol) this.applyLayerCategories(item, layerId, displayName);\n\n // Add context menu event listener (skip for Background layer)\n if (this.enableContextMenu && layerId !== \"Background\") {\n row.addEventListener(\"contextmenu\", (e) => {\n e.preventDefault();\n e.stopPropagation();\n this.showContextMenu(layerId, e.clientX, e.clientY);\n });\n }\n\n container.appendChild(item);\n }\n\n /** Refresh changed category legends without rebuilding rows or style editors. */\n private refreshLayerCategories(): void {\n if (!this.showLayerSymbol) return;\n this.panel\n .querySelectorAll<HTMLElement>(\".layer-control-item[data-layer-id]\")\n .forEach((item) => {\n const layerId = item.dataset.layerId!;\n const layer = this.map.getLayer(layerId);\n if (!layer || layerId === \"Background\" || this.state.layerStates[layerId]?.isCustomLayer) return;\n const result = getLayerColorCategories(this.map, layerId, layer.type);\n const signature = result ? JSON.stringify(result) : \"\";\n if (signature === (item.dataset.categorySignature ?? \"\")) return;\n const name = item.querySelector<HTMLElement>(\":scope > .layer-control-row > .layer-control-name\");\n this.applyLayerCategories(item, layerId, name?.textContent ?? layerId);\n });\n }\n\n /** Apply categories in place without disturbing the row or its style editor. */\n private applyLayerCategories(\n item: HTMLElement,\n layerId: string,\n displayName: string,\n ): void {\n item.querySelector(\":scope > .layer-control-categories\")?.remove();\n item.classList.remove(\"categories-expanded\");\n const row = item.querySelector<HTMLElement>(\":scope > .layer-control-row\");\n row?.querySelector(\".layer-control-categories-toggle\")?.remove();\n const symbol = row?.querySelector<HTMLElement>(\":scope > .layer-control-symbol\");\n if (!row || !symbol || layerId === \"Background\" || this.state.layerStates[layerId]?.isCustomLayer) return;\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n const layerType = layer.type;\n const result = getLayerColorCategories(this.map, layerId, layerType);\n item.dataset.categorySignature = result ? JSON.stringify(result) : \"\";\n if (!result) {\n if (symbol.dataset.categorized === \"true\") {\n symbol.innerHTML = createLayerSymbolSVG(\n layerType,\n getLayerColor(this.map, layerId, layerType),\n getLayerSymbolStyle(this.map, layerId, layerType),\n );\n symbol.title = `Layer type: ${layerType}`;\n delete symbol.dataset.categorized;\n if (layerType === \"fill\") symbol.dataset.previewLayerId = layerId;\n }\n return;\n }\n\n symbol.innerHTML = createCategorizedSymbolSVG(16);\n symbol.dataset.categorized = \"true\";\n delete symbol.dataset.previewLayerId;\n symbol.title = `Categorized by ${result.property} (${result.categories.length} classes)`;\n\n const toggle = document.createElement(\"button\");\n toggle.type = \"button\";\n toggle.className = \"layer-control-categories-toggle\";\n toggle.innerHTML = `<svg viewBox=\"0 0 16 16\" fill=\"currentColor\" aria-hidden=\"true\">\n <path d=\"M6 4l4 4-4 4z\"/>\n </svg>`;\n row.querySelector(\":scope > .layer-control-name\")?.after(toggle);\n\n const container = document.createElement(\"div\");\n container.className = \"layer-control-categories\";\n for (const category of result.categories) {\n const entry = document.createElement(\"div\");\n entry.className = \"layer-control-category\";\n const swatch = document.createElement(\"span\");\n swatch.className = \"layer-control-category-symbol\";\n swatch.innerHTML = createLayerSymbolSVG(layerType, category.color, { size: 14 });\n const label = document.createElement(\"span\");\n label.className = \"layer-control-category-label\";\n label.textContent = category.label;\n label.title = category.title;\n entry.append(swatch, label);\n container.appendChild(entry);\n }\n row.after(container);\n\n const setExpanded = (expanded: boolean): void => {\n item.classList.toggle(\"categories-expanded\", expanded);\n container.hidden = !expanded;\n toggle.setAttribute(\"aria-expanded\", String(expanded));\n toggle.title = expanded ? \"Hide categories\" : \"Show categories\";\n toggle.setAttribute(\"aria-label\", `${expanded ? \"Hide\" : \"Show\"} categories for ${displayName}`);\n };\n setExpanded(this.state.expandedCategoryLayers.has(layerId));\n toggle.addEventListener(\"click\", (event) => {\n event.stopPropagation();\n const expanded = !this.state.expandedCategoryLayers.has(layerId);\n if (expanded) this.state.expandedCategoryLayers.add(layerId);\n else this.state.expandedCategoryLayers.delete(layerId);\n setExpanded(expanded);\n });\n }\n\n /**\n * Create a symbol element for a layer\n * @param layerId The layer ID\n * @returns The symbol HTML element, or null if layer not found\n */\n private createLayerSymbol(layerId: string): HTMLElement | null {\n // Check if it's a custom layer first\n const layerState = this.state.layerStates[layerId];\n if (layerState?.isCustomLayer) {\n const symbolType = layerState.customLayerType || \"custom-raster\";\n // Use a default color for custom layers\n const color = \"#4a90d9\";\n const svgMarkup = createLayerSymbolSVG(symbolType, color);\n\n const symbolContainer = document.createElement(\"span\");\n symbolContainer.className = \"layer-control-symbol\";\n symbolContainer.innerHTML = svgMarkup;\n symbolContainer.title = `Layer type: ${symbolType}`;\n\n return symbolContainer;\n }\n\n // Fall back to MapLibre layer\n const layer = this.map.getLayer(layerId);\n if (!layer) return null;\n\n const layerType = layer.type;\n const color = getLayerColor(this.map, layerId, layerType);\n const symbolStyle = getLayerSymbolStyle(this.map, layerId, layerType);\n const svgMarkup = createLayerSymbolSVG(layerType, color, symbolStyle);\n\n const symbolContainer = document.createElement(\"span\");\n symbolContainer.className = \"layer-control-symbol\";\n symbolContainer.innerHTML = svgMarkup;\n symbolContainer.title = `Layer type: ${layerType}`;\n if (layerType === \"fill\") symbolContainer.dataset.previewLayerId = layerId;\n\n return symbolContainer;\n }\n\n /**\n * Create a symbol element for a background layer\n * @param layer The layer specification\n * @returns The symbol HTML element\n */\n private createBackgroundLayerSymbol(layer: LayerSpecification): HTMLElement {\n const color = getLayerColorFromSpec(layer);\n const symbolStyle = getLayerSymbolStyle(this.map, layer.id, layer.type);\n const svgMarkup = createLayerSymbolSVG(layer.type, color, {\n ...symbolStyle,\n size: 14,\n });\n\n const symbolContainer = document.createElement(\"span\");\n symbolContainer.className = \"background-legend-layer-symbol\";\n symbolContainer.innerHTML = svgMarkup;\n symbolContainer.title = `Layer type: ${layer.type}`;\n if (layer.type === \"fill\") symbolContainer.dataset.previewLayerId = layer.id;\n\n return symbolContainer;\n }\n\n /** Refresh pattern images and SDF tint after paint, sprite, or image changes. */\n private updateFillSymbols(): void {\n this.panel.querySelectorAll<HTMLElement>(\"[data-preview-layer-id]\").forEach((symbol) => {\n const layerId = symbol.dataset.previewLayerId!;\n if (!this.map.getLayer(layerId)) return;\n symbol.innerHTML = createLayerSymbolSVG(\n \"fill\",\n getLayerColor(this.map, layerId, \"fill\"),\n {\n ...getLayerSymbolStyle(this.map, layerId, \"fill\"),\n size: symbol.classList.contains(\"background-legend-layer-symbol\") ? 14 : 16,\n },\n );\n });\n }\n\n /**\n * Create a symbol element for the Background layer group\n * Shows a stacked layers icon to represent multiple background layers\n * @returns The symbol HTML element\n */\n private createBackgroundGroupSymbol(): HTMLElement {\n const svgMarkup = createBackgroundGroupSymbolSVG(16);\n\n const symbolContainer = document.createElement(\"span\");\n symbolContainer.className = \"layer-control-symbol\";\n symbolContainer.innerHTML = svgMarkup;\n symbolContainer.title = \"Background layers\";\n\n return symbolContainer;\n }\n\n /**\n * Toggle layer visibility\n */\n private toggleLayerVisibility(layerId: string, visible: boolean): void {\n // Handle Background layer group\n if (layerId === \"Background\") {\n this.toggleBackgroundVisibility(visible);\n return;\n }\n\n // Set flag to prevent checkForNewLayers from running during visibility change\n this.state.isStyleOperationInProgress = true;\n\n // Update local state\n if (this.state.layerStates[layerId]) {\n this.state.layerStates[layerId].visible = visible;\n }\n\n // Try custom layer registry first\n if (this.customLayerRegistry?.setVisibility(layerId, visible)) {\n // Clear flag after a delay for custom layers\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n return;\n }\n\n // Fallback to native MapLibre layer\n this.map.setLayoutProperty(\n layerId,\n \"visibility\",\n visible ? \"visible\" : \"none\",\n );\n\n // Clear flag after styledata events have settled\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n }\n\n /**\n * Show a small popup that lets the user type an exact opacity percentage\n * (0-100). Triggered by double-clicking an opacity slider.\n *\n * @param slider The opacity range input being edited\n * @param applyOpacity Called with the chosen opacity (0-1) when the user confirms\n */\n private showOpacityInput(\n slider: HTMLInputElement,\n applyOpacity: (opacity: number) => void,\n ): void {\n // Close any existing opacity popup first\n this.hideOpacityInput();\n\n const popup = document.createElement(\"div\");\n popup.className = \"layer-control-opacity-input\";\n\n const label = document.createElement(\"span\");\n label.className = \"layer-control-opacity-input-label\";\n label.textContent = \"Opacity\";\n\n const field = document.createElement(\"div\");\n field.className = \"layer-control-opacity-input-field\";\n\n const input = document.createElement(\"input\");\n input.type = \"number\";\n input.min = \"0\";\n input.max = \"100\";\n input.step = \"1\";\n input.value = String(Math.round(parseFloat(slider.value) * 100));\n\n const suffix = document.createElement(\"span\");\n suffix.className = \"layer-control-opacity-input-suffix\";\n suffix.textContent = \"%\";\n\n field.appendChild(input);\n field.appendChild(suffix);\n popup.appendChild(label);\n popup.appendChild(field);\n\n // Prevent clicks inside the popup from collapsing the panel\n popup.addEventListener(\"click\", (event) => event.stopPropagation());\n popup.addEventListener(\"pointerdown\", (event) => event.stopPropagation());\n\n let settled = false;\n const apply = () => {\n if (settled) return;\n settled = true;\n const pct = clamp(Math.round(parseFloat(input.value)), 0, 100);\n if (!Number.isNaN(pct)) {\n const opacity = pct / 100;\n slider.value = String(opacity);\n slider.title = `Opacity: ${pct}%`;\n applyOpacity(opacity);\n }\n this.hideOpacityInput();\n };\n const cancel = () => {\n if (settled) return;\n settled = true;\n this.hideOpacityInput();\n };\n\n input.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\") {\n event.preventDefault();\n apply();\n slider.focus();\n } else if (event.key === \"Escape\") {\n event.preventDefault();\n cancel();\n slider.focus();\n }\n });\n input.addEventListener(\"blur\", apply);\n\n this.mapContainer.appendChild(popup);\n this.opacityInputEl = popup;\n\n // Position the popup near the slider, relative to the map container\n const sliderRect = slider.getBoundingClientRect();\n const mapRect = this.mapContainer.getBoundingClientRect();\n const popupRect = popup.getBoundingClientRect();\n\n let left = sliderRect.left - mapRect.left;\n let top = sliderRect.bottom - mapRect.top + 4;\n\n // Keep the popup within the map bounds\n if (left + popupRect.width > mapRect.width) {\n left = Math.max(0, mapRect.width - popupRect.width - 5);\n }\n if (top + popupRect.height > mapRect.height) {\n top = sliderRect.top - mapRect.top - popupRect.height - 4;\n }\n\n popup.style.left = `${Math.max(0, left)}px`;\n popup.style.top = `${Math.max(0, top)}px`;\n\n input.focus();\n input.select();\n }\n\n /**\n * Remove the exact-opacity input popup if it is open.\n */\n private hideOpacityInput(): void {\n if (this.opacityInputEl) {\n this.opacityInputEl.remove();\n this.opacityInputEl = null;\n }\n }\n\n /**\n * Change layer opacity\n */\n private changeLayerOpacity(layerId: string, opacity: number): void {\n // Handle Background layer group\n if (layerId === \"Background\") {\n this.changeBackgroundOpacity(opacity);\n return;\n }\n\n // Set flag to prevent checkForNewLayers from running during opacity change\n this.state.isStyleOperationInProgress = true;\n\n // Update local state\n if (this.state.layerStates[layerId]) {\n this.state.layerStates[layerId].opacity = opacity;\n }\n\n // Try custom layer registry first\n if (this.customLayerRegistry?.setOpacity(layerId, opacity)) {\n // Clear flag after a delay for custom layers\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n return;\n }\n\n // Fallback to native MapLibre layer\n const layerType = getLayerType(this.map, layerId);\n if (layerType) {\n setLayerOpacity(this.map, layerId, layerType, opacity);\n }\n\n // Clear flag after styledata events have settled\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n }\n\n /**\n * Get the opacity property an adapter owns for a native map layer: the layer\n * type's primary opacity property, when an adapter reports state for the\n * layer. Such a layer's paint value is its own opacity combined with the\n * adapter's folder opacity, so it must be written and read through the\n * adapter. Returns null for other layers, including custom layers and\n * layers with native sub-layer groups.\n * @param layerId The layer ID\n */\n private getAdapterOwnedOpacityProperty(layerId: string): string | null {\n if (\n this.state.layerStates[layerId]?.isCustomLayer ||\n this.nativeLayerGroups.has(layerId) ||\n !this.customLayerRegistry?.getLayerState(layerId)\n ) {\n return null;\n }\n const layer = this.map.getLayer(layerId);\n if (!layer) return null;\n const property = getOpacityProperty(layer.type);\n return Array.isArray(property) ? property[0] : property;\n }\n\n /**\n * Get the value a style editor control shows for a paint property: the\n * adapter's own opacity for an adapter-owned opacity property, otherwise the\n * map's paint value.\n * @param layerId The layer ID\n * @param property The paint property\n */\n private getStyleValue(\n layerId: string,\n property: keyof AllPaintProperties,\n ): unknown {\n if (this.getAdapterOwnedOpacityProperty(layerId) === property) {\n return this.customLayerRegistry?.getLayerState(layerId)?.opacity;\n }\n return this.map.getPaintProperty(layerId, property);\n }\n\n /**\n * Check if a layer is a user-added layer (vs basemap layer)\n * Used primarily for the background legend to determine which layers are background\n */\n private isUserAddedLayer(layerId: string): boolean {\n // If this layer is in our state (and not Background), it's user-added\n if (\n this.state.layerStates[layerId] !== undefined &&\n layerId !== \"Background\"\n ) {\n return true;\n }\n\n // If we know the basemap layer IDs (option or basemapStyleUrl), check if the layer is NOT in the basemap\n if (this.hasBasemapLayerIds()) {\n return !this.basemapLayerIds!.has(layerId);\n }\n\n // For layers not in our state, check if the layer was added after control initialization\n // or uses a user-added source\n if (this.initialLayerIds !== null && !this.initialLayerIds.has(layerId)) {\n // Layer was added after control - it's user-added\n return true;\n }\n\n // Check source-based heuristics\n const layer = this.map.getLayer(layerId);\n if (layer) {\n const sourceId = (layer as any).source;\n if (sourceId) {\n const userAddedSourceIds = this.detectUserAddedSources();\n return userAddedSourceIds.has(sourceId);\n }\n }\n\n return false;\n }\n\n /**\n * Toggle visibility for all background layers (basemap layers)\n */\n private toggleBackgroundVisibility(visible: boolean): void {\n // Update local state\n if (this.state.layerStates[\"Background\"]) {\n this.state.layerStates[\"Background\"].visible = visible;\n }\n\n // Apply to all basemap layers (layers not in layerStates)\n const styleLayers = this.map.getStyle().layers || [];\n styleLayers.forEach((layer) => {\n if (!this.isUserAddedLayer(layer.id)) {\n // Update visibility cache\n this.state.backgroundLayerVisibility.set(layer.id, visible);\n this.map.setLayoutProperty(\n layer.id,\n \"visibility\",\n visible ? \"visible\" : \"none\",\n );\n }\n });\n\n // Update legend panel checkboxes if open\n if (this.state.backgroundLegendOpen) {\n const legendPanel = this.panel.querySelector(\n \".layer-control-background-legend\",\n );\n if (legendPanel) {\n const checkboxes = legendPanel.querySelectorAll(\n \".background-legend-checkbox\",\n ) as NodeListOf<HTMLInputElement>;\n checkboxes.forEach((checkbox) => {\n checkbox.checked = visible;\n });\n }\n }\n\n // Notify consumers so external basemap UI can mirror the new state.\n this.onBackgroundVisibilityChange?.(visible);\n }\n\n /**\n * Change opacity for all background layers (basemap layers)\n */\n private changeBackgroundOpacity(opacity: number): void {\n // Update local state\n if (this.state.layerStates[\"Background\"]) {\n this.state.layerStates[\"Background\"].opacity = opacity;\n }\n\n // Apply to all basemap layers (layers not in layerStates)\n const styleLayers = this.map.getStyle().layers || [];\n styleLayers.forEach((styleLayer) => {\n if (!this.isUserAddedLayer(styleLayer.id)) {\n const layerType = getLayerType(this.map, styleLayer.id);\n if (layerType) {\n setLayerOpacity(this.map, styleLayer.id, layerType, opacity);\n }\n }\n });\n\n // Notify consumers so external basemap UI can mirror the new opacity.\n this.onBackgroundOpacityChange?.(opacity);\n }\n\n // ===== Background Legend Methods =====\n\n /**\n * Create legend button for Background layer\n */\n private createBackgroundLegendButton(): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.className =\n \"layer-control-style-button layer-control-background-legend-button\";\n button.innerHTML = \"⚙\"; // Gear icon (same as style button)\n button.title = \"Show background layer details\";\n button.setAttribute(\n \"aria-label\",\n \"Show background layer visibility controls\",\n );\n button.setAttribute(\n \"aria-expanded\",\n String(this.state.backgroundLegendOpen),\n );\n\n button.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.toggleBackgroundLegend();\n });\n\n return button;\n }\n\n /**\n * Toggle background legend panel visibility\n */\n private toggleBackgroundLegend(): void {\n if (this.state.backgroundLegendOpen) {\n this.closeBackgroundLegend();\n } else {\n this.openBackgroundLegend();\n }\n }\n\n /**\n * Open background legend panel\n */\n private openBackgroundLegend(): void {\n // Close any open style editor first\n if (this.state.activeStyleEditor) {\n this.closeStyleEditor(this.state.activeStyleEditor);\n }\n\n const itemEl = this.panel.querySelector('[data-layer-id=\"Background\"]');\n if (!itemEl) return;\n\n // Check if panel already exists\n let legendPanel = itemEl.querySelector(\".layer-control-background-legend\");\n if (legendPanel) {\n // Refresh the list\n const layerList = legendPanel.querySelector(\n \".background-legend-layer-list\",\n );\n if (layerList) {\n this.populateBackgroundLayerList(layerList as HTMLElement);\n }\n } else {\n // Create new panel\n legendPanel = this.createBackgroundLegendPanel();\n itemEl.appendChild(legendPanel);\n }\n\n this.state.backgroundLegendOpen = true;\n\n // Update button aria state\n const button = itemEl.querySelector(\n \".layer-control-background-legend-button\",\n );\n if (button) {\n button.setAttribute(\"aria-expanded\", \"true\");\n button.classList.add(\"active\");\n }\n\n // Scroll into view\n setTimeout(() => {\n legendPanel?.scrollIntoView({ behavior: \"smooth\", block: \"nearest\" });\n }, 50);\n }\n\n /**\n * Close background legend panel\n */\n private closeBackgroundLegend(): void {\n const itemEl = this.panel.querySelector('[data-layer-id=\"Background\"]');\n if (!itemEl) return;\n\n const legendPanel = itemEl.querySelector(\n \".layer-control-background-legend\",\n );\n if (legendPanel) {\n legendPanel.remove();\n }\n\n this.state.backgroundLegendOpen = false;\n\n // Update button aria state\n const button = itemEl.querySelector(\n \".layer-control-background-legend-button\",\n );\n if (button) {\n button.setAttribute(\"aria-expanded\", \"false\");\n button.classList.remove(\"active\");\n }\n }\n\n /**\n * Create the background legend panel with individual layer controls\n */\n private createBackgroundLegendPanel(): HTMLDivElement {\n const panel = document.createElement(\"div\");\n panel.className = \"layer-control-background-legend\";\n\n // Header\n const header = document.createElement(\"div\");\n header.className = \"background-legend-header\";\n\n const title = document.createElement(\"span\");\n title.className = \"background-legend-title\";\n title.textContent = \"Background Layers\";\n\n const closeBtn = document.createElement(\"button\");\n closeBtn.className = \"background-legend-close\";\n closeBtn.innerHTML = \"×\";\n closeBtn.title = \"Close\";\n closeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeBackgroundLegend();\n });\n\n header.appendChild(title);\n header.appendChild(closeBtn);\n\n // Quick actions row\n const actionsRow = document.createElement(\"div\");\n actionsRow.className = \"background-legend-actions\";\n\n const showAllBtn = document.createElement(\"button\");\n showAllBtn.className = \"background-legend-action-btn\";\n showAllBtn.textContent = \"Show All\";\n showAllBtn.addEventListener(\"click\", () =>\n this.setAllBackgroundLayersVisibility(true),\n );\n\n const hideAllBtn = document.createElement(\"button\");\n hideAllBtn.className = \"background-legend-action-btn\";\n hideAllBtn.textContent = \"Hide All\";\n hideAllBtn.addEventListener(\"click\", () =>\n this.setAllBackgroundLayersVisibility(false),\n );\n\n actionsRow.appendChild(showAllBtn);\n actionsRow.appendChild(hideAllBtn);\n\n // Filter row - \"Only rendered\" checkbox\n const filterRow = document.createElement(\"div\");\n filterRow.className = \"background-legend-filter\";\n\n const filterCheckbox = document.createElement(\"input\");\n filterCheckbox.type = \"checkbox\";\n filterCheckbox.className = \"background-legend-filter-checkbox\";\n filterCheckbox.id = \"background-legend-only-rendered\";\n filterCheckbox.checked = this.state.onlyRenderedFilter;\n filterCheckbox.addEventListener(\"change\", () => {\n this.state.onlyRenderedFilter = filterCheckbox.checked;\n const layerList = panel.querySelector(\".background-legend-layer-list\");\n if (layerList) {\n this.populateBackgroundLayerList(layerList as HTMLElement);\n }\n });\n\n const filterLabel = document.createElement(\"label\");\n filterLabel.className = \"background-legend-filter-label\";\n filterLabel.htmlFor = \"background-legend-only-rendered\";\n filterLabel.textContent = \"Only rendered\";\n\n filterRow.appendChild(filterCheckbox);\n filterRow.appendChild(filterLabel);\n\n // Layer list container (scrollable)\n const layerList = document.createElement(\"div\");\n layerList.className = \"background-legend-layer-list\";\n\n // Populate with background layers\n this.populateBackgroundLayerList(layerList);\n\n panel.appendChild(header);\n panel.appendChild(actionsRow);\n panel.appendChild(filterRow);\n panel.appendChild(layerList);\n\n // Saved configurations (presets) row\n if (this.enableBackgroundPresets) {\n panel.appendChild(this.createBackgroundPresetsRow());\n }\n\n return panel;\n }\n\n /**\n * Build the \"Saved configurations\" controls: a dropdown of saved presets with\n * Apply/Delete actions, plus a name field and Save button to capture the\n * current basemap element visibility as a reusable, persisted preset.\n */\n private createBackgroundPresetsRow(): HTMLElement {\n const section = document.createElement(\"div\");\n section.className = \"background-legend-presets\";\n\n const label = document.createElement(\"div\");\n label.className = \"background-legend-presets-label\";\n label.textContent = \"Saved configurations\";\n section.appendChild(label);\n\n // Row 1: preset selector + apply/delete\n const selectRow = document.createElement(\"div\");\n selectRow.className = \"background-legend-presets-row\";\n\n const select = document.createElement(\"select\");\n select.className = \"background-legend-presets-select\";\n select.title = \"Saved configurations\";\n\n const applyBtn = document.createElement(\"button\");\n applyBtn.className = \"background-legend-action-btn\";\n applyBtn.textContent = \"Apply\";\n applyBtn.title = \"Apply the selected configuration\";\n\n const deleteBtn = document.createElement(\"button\");\n deleteBtn.className = \"background-legend-action-btn\";\n deleteBtn.textContent = \"Delete\";\n deleteBtn.title = \"Delete the selected configuration\";\n\n const refreshSelect = (selected?: string) => {\n const presets = this.getBackgroundPresets();\n const names = Object.keys(presets).sort((a, b) =>\n a.localeCompare(b, undefined, { sensitivity: \"base\" }),\n );\n select.innerHTML = \"\";\n\n const placeholder = document.createElement(\"option\");\n placeholder.value = \"\";\n placeholder.textContent = names.length\n ? \"Select a configuration…\"\n : \"No saved configurations\";\n placeholder.disabled = names.length > 0;\n select.appendChild(placeholder);\n\n names.forEach((name) => {\n const option = document.createElement(\"option\");\n option.value = name;\n option.textContent = name;\n select.appendChild(option);\n });\n\n select.value = selected && names.includes(selected) ? selected : \"\";\n const hasSelection = select.value !== \"\";\n applyBtn.disabled = !hasSelection;\n deleteBtn.disabled = !hasSelection;\n };\n\n select.addEventListener(\"change\", () => {\n const hasSelection = select.value !== \"\";\n applyBtn.disabled = !hasSelection;\n deleteBtn.disabled = !hasSelection;\n });\n\n applyBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n if (select.value) this.applyBackgroundPreset(select.value);\n });\n\n deleteBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n if (select.value) {\n this.deleteBackgroundPreset(select.value);\n refreshSelect();\n }\n });\n\n selectRow.appendChild(select);\n selectRow.appendChild(applyBtn);\n selectRow.appendChild(deleteBtn);\n\n // Row 2: name input + save\n const saveRow = document.createElement(\"div\");\n saveRow.className = \"background-legend-presets-row\";\n\n const nameInput = document.createElement(\"input\");\n nameInput.type = \"text\";\n nameInput.className = \"background-legend-presets-input\";\n nameInput.placeholder = \"Configuration name…\";\n nameInput.maxLength = 60;\n\n const saveBtn = document.createElement(\"button\");\n saveBtn.className = \"background-legend-action-btn\";\n saveBtn.textContent = \"Save\";\n saveBtn.title = \"Save the current visibility as a configuration\";\n\n const commitSave = () => {\n const name = nameInput.value.trim();\n if (!name) return;\n this.saveBackgroundPreset(name);\n nameInput.value = \"\";\n refreshSelect(name);\n };\n\n saveBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n commitSave();\n });\n nameInput.addEventListener(\"keydown\", (e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n commitSave();\n }\n });\n\n saveRow.appendChild(nameInput);\n saveRow.appendChild(saveBtn);\n\n section.appendChild(selectRow);\n section.appendChild(saveRow);\n\n refreshSelect();\n\n return section;\n }\n\n /**\n * Check if a layer is currently rendered in the map viewport\n */\n private isLayerRendered(layerId: string): boolean {\n try {\n const layer = this.map.getLayer(layerId);\n if (!layer) return false;\n\n // Check if layer is visible first\n const visibility = this.map.getLayoutProperty(layerId, \"visibility\");\n if (visibility === \"none\") return false;\n\n // For raster layers, check if tiles are loaded\n if (layer.type === \"raster\" || layer.type === \"hillshade\") {\n // Raster layers are considered rendered if visible\n return true;\n }\n\n // For background layers (solid color), they're always rendered if visible\n if (layer.type === \"background\") {\n return true;\n }\n\n // For vector layers, use queryRenderedFeatures to check if any features are visible\n const features = this.map.queryRenderedFeatures({ layers: [layerId] });\n return features.length > 0;\n } catch (error) {\n // If query fails, assume layer is rendered if we can see it\n return true;\n }\n }\n\n /**\n * Populate the background layer list with individual layers\n */\n private populateBackgroundLayerList(container: HTMLElement): void {\n container.innerHTML = \"\"; // Clear existing\n\n const styleLayers = this.map.getStyle().layers || [];\n\n styleLayers.forEach((layer) => {\n if (!this.isUserAddedLayer(layer.id)) {\n // Skip drawn layers if excludeDrawnLayers is enabled\n if (this.excludeDrawnLayers && this.isDrawnLayer(layer.id)) {\n return;\n }\n\n // Skip layers matching user-defined exclusion patterns\n if (this.isExcludedByPattern(layer.id)) {\n return;\n }\n\n // If \"Only rendered\" filter is enabled, skip layers that aren't rendered\n if (this.state.onlyRenderedFilter && !this.isLayerRendered(layer.id)) {\n return;\n }\n\n // This is a background layer\n const layerRow = document.createElement(\"div\");\n layerRow.className = \"background-legend-layer-row\";\n layerRow.setAttribute(\"data-background-layer-id\", layer.id);\n\n // Checkbox\n const checkbox = document.createElement(\"input\");\n checkbox.type = \"checkbox\";\n checkbox.className = \"background-legend-checkbox\";\n\n // Get visibility from map or cache\n const visibility = this.map.getLayoutProperty(layer.id, \"visibility\");\n const isVisible = visibility !== \"none\";\n checkbox.checked = isVisible;\n\n // Update cache\n this.state.backgroundLayerVisibility.set(layer.id, isVisible);\n\n checkbox.addEventListener(\"change\", () => {\n this.toggleIndividualBackgroundLayer(layer.id, checkbox.checked);\n });\n\n // Layer name\n const name = document.createElement(\"span\");\n name.className = \"background-legend-layer-name\";\n name.textContent = this.generateFriendlyName(layer.id);\n name.title = layer.id; // Show full ID on hover\n\n // Layer type indicator\n const typeIndicator = document.createElement(\"span\");\n typeIndicator.className = \"background-legend-layer-type\";\n typeIndicator.textContent = layer.type;\n\n layerRow.appendChild(checkbox);\n\n // Add layer symbol (if enabled)\n if (this.showLayerSymbol) {\n const symbol = this.createBackgroundLayerSymbol(layer);\n if (symbol) {\n layerRow.appendChild(symbol);\n }\n }\n\n layerRow.appendChild(name);\n layerRow.appendChild(typeIndicator);\n container.appendChild(layerRow);\n }\n });\n\n // Show message if no background layers\n if (container.children.length === 0) {\n const emptyMsg = document.createElement(\"p\");\n emptyMsg.className = \"background-legend-empty\";\n emptyMsg.textContent = this.state.onlyRenderedFilter\n ? \"No rendered layers in current view.\"\n : \"No background layers found.\";\n container.appendChild(emptyMsg);\n }\n }\n\n /**\n * Toggle visibility of an individual background layer\n */\n private toggleIndividualBackgroundLayer(\n layerId: string,\n visible: boolean,\n ): void {\n // Update visibility cache\n this.state.backgroundLayerVisibility.set(layerId, visible);\n\n // Apply to map\n this.map.setLayoutProperty(\n layerId,\n \"visibility\",\n visible ? \"visible\" : \"none\",\n );\n\n // Update the main Background checkbox state\n this.updateBackgroundCheckboxState();\n }\n\n /**\n * Set visibility for all background layers\n */\n private setAllBackgroundLayersVisibility(visible: boolean): void {\n this.getControllableBackgroundLayerIds().forEach((layerId) => {\n this.state.backgroundLayerVisibility.set(layerId, visible);\n this.map.setLayoutProperty(\n layerId,\n \"visibility\",\n visible ? \"visible\" : \"none\",\n );\n });\n\n // Update checkboxes in the legend panel\n const legendPanel = this.panel.querySelector(\n \".layer-control-background-legend\",\n );\n if (legendPanel) {\n const checkboxes = legendPanel.querySelectorAll(\n \".background-legend-checkbox\",\n ) as NodeListOf<HTMLInputElement>;\n checkboxes.forEach((checkbox) => {\n checkbox.checked = visible;\n });\n }\n\n // Update main Background checkbox\n this.updateBackgroundCheckboxState();\n }\n\n /**\n * Update the main Background checkbox based on individual layer states\n */\n private updateBackgroundCheckboxState(): void {\n let anyVisible = false;\n let allVisible = true;\n\n this.getControllableBackgroundLayerIds().forEach((layerId) => {\n const visible = this.state.backgroundLayerVisibility.get(layerId);\n if (visible === true) anyVisible = true;\n if (visible === false) allVisible = false;\n });\n\n // Update main checkbox\n const backgroundItem = this.panel.querySelector(\n '[data-layer-id=\"Background\"]',\n );\n if (backgroundItem) {\n const checkbox = backgroundItem.querySelector(\n \".layer-control-checkbox\",\n ) as HTMLInputElement;\n if (checkbox) {\n checkbox.checked = anyVisible;\n checkbox.indeterminate = anyVisible && !allVisible;\n }\n }\n\n // Update layerState\n if (this.state.layerStates[\"Background\"]) {\n this.state.layerStates[\"Background\"].visible = anyVisible;\n }\n }\n\n /**\n * Return the IDs of the background (basemap) style layers the control can\n * toggle, honoring the drawn-layer and user-defined exclusion filters but not\n * the transient \"only rendered\" view filter.\n */\n private getControllableBackgroundLayerIds(): string[] {\n const styleLayers = this.map.getStyle().layers || [];\n return styleLayers\n .filter((layer) => {\n if (this.isUserAddedLayer(layer.id)) return false;\n if (this.excludeDrawnLayers && this.isDrawnLayer(layer.id))\n return false;\n if (this.isExcludedByPattern(layer.id)) return false;\n return true;\n })\n .map((layer) => layer.id);\n }\n\n /**\n * Get the current visibility of every controllable background (basemap) layer.\n *\n * @returns A map of style-layer ID to whether it is currently visible.\n */\n getBackgroundLayerVisibility(): BackgroundLayerVisibility {\n const visibility: BackgroundLayerVisibility = {};\n for (const layerId of this.getControllableBackgroundLayerIds()) {\n const value = this.map.getLayoutProperty(layerId, \"visibility\");\n visibility[layerId] = value !== \"none\";\n }\n return visibility;\n }\n\n /**\n * Apply a saved background-layer visibility configuration to the map. Only\n * layers that currently exist in the style are affected, so a configuration\n * captured on one basemap degrades gracefully when applied to another.\n *\n * @param visibility - Map of style-layer ID to desired visibility.\n */\n applyBackgroundLayerVisibility(visibility: BackgroundLayerVisibility): void {\n for (const [layerId, visible] of Object.entries(visibility)) {\n if (this.isUserAddedLayer(layerId)) continue;\n if (!this.map.getLayer(layerId)) continue;\n this.state.backgroundLayerVisibility.set(layerId, visible);\n this.map.setLayoutProperty(\n layerId,\n \"visibility\",\n visible ? \"visible\" : \"none\",\n );\n }\n\n // Refresh the open legend panel (if any) and the main Background checkbox.\n const legendPanel = this.panel.querySelector(\n \".background-legend-layer-list\",\n );\n if (legendPanel) {\n this.populateBackgroundLayerList(legendPanel as HTMLElement);\n }\n this.updateBackgroundCheckboxState();\n }\n\n /**\n * Read all saved background-layer presets from localStorage. Returns an empty\n * object when storage is unavailable or the stored value is malformed.\n */\n getBackgroundPresets(): BackgroundPresets {\n try {\n const raw =\n typeof localStorage !== \"undefined\"\n ? localStorage.getItem(this.backgroundPresetStorageKey)\n : null;\n if (!raw) return {};\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {};\n }\n // Keep only safe, own keys mapping to plain objects, so a hand-crafted\n // storage value cannot smuggle in dangerous keys (e.g. `__proto__`).\n const presets: BackgroundPresets = {};\n for (const [name, value] of Object.entries(parsed)) {\n if (this.isUnsafePresetKey(name)) continue;\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n presets[name] = value as BackgroundLayerVisibility;\n }\n }\n return presets;\n } catch {\n return {};\n }\n }\n\n /**\n * Reject preset names that, used as object keys, could pollute the prototype\n * chain or otherwise alias built-in object members.\n */\n private isUnsafePresetKey(name: string): boolean {\n return (\n name === \"__proto__\" || name === \"constructor\" || name === \"prototype\"\n );\n }\n\n /**\n * Persist the full preset map to localStorage and notify listeners.\n */\n private writeBackgroundPresets(presets: BackgroundPresets): void {\n try {\n if (typeof localStorage !== \"undefined\") {\n localStorage.setItem(\n this.backgroundPresetStorageKey,\n JSON.stringify(presets),\n );\n }\n } catch {\n // Storage may be unavailable (private mode, quota); presets stay in-memory\n // for this session via the UI but cannot be persisted.\n }\n this.onBackgroundPresetsChange?.(presets);\n }\n\n /**\n * Save the current background-layer visibility as a named preset. Reusing an\n * existing name overwrites that preset.\n *\n * @param name - Preset name; whitespace is trimmed. Empty names are ignored.\n * @returns The updated preset map.\n */\n saveBackgroundPreset(name: string): BackgroundPresets {\n const trimmed = name.trim();\n const presets = this.getBackgroundPresets();\n if (!trimmed || this.isUnsafePresetKey(trimmed)) return presets;\n presets[trimmed] = this.getBackgroundLayerVisibility();\n this.writeBackgroundPresets(presets);\n return presets;\n }\n\n /**\n * Apply a previously saved preset to the map.\n *\n * @param name - The preset name to apply.\n * @returns `true` if a preset with that name existed and was applied.\n */\n applyBackgroundPreset(name: string): boolean {\n const presets = this.getBackgroundPresets();\n if (!Object.prototype.hasOwnProperty.call(presets, name)) return false;\n this.applyBackgroundLayerVisibility(presets[name]);\n return true;\n }\n\n /**\n * Delete a saved preset.\n *\n * @param name - The preset name to remove.\n * @returns The updated preset map.\n */\n deleteBackgroundPreset(name: string): BackgroundPresets {\n const presets = this.getBackgroundPresets();\n if (Object.prototype.hasOwnProperty.call(presets, name)) {\n delete presets[name];\n this.writeBackgroundPresets(presets);\n }\n return presets;\n }\n\n /**\n * Create style button for a layer\n */\n private createStyleButton(layerId: string): HTMLButtonElement | null {\n // Don't create button for Background layer\n if (layerId === \"Background\") {\n return null;\n }\n\n const layerState = this.state.layerStates[layerId];\n const isCustomLayer = layerState?.isCustomLayer === true;\n\n const button = document.createElement(\"button\");\n button.className = \"layer-control-style-button\";\n button.innerHTML = \"⚙\"; // Gear icon\n\n if (isCustomLayer) {\n // Custom layers don't support style editing - show info panel instead\n button.title = \"Layer info (style editing not available)\";\n button.setAttribute(\"aria-label\", `Layer info for ${layerId}`);\n } else {\n button.title = \"Edit layer style\";\n button.setAttribute(\"aria-label\", `Edit style for ${layerId}`);\n }\n\n button.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.toggleStyleEditor(layerId);\n });\n\n return button;\n }\n\n /**\n * Toggle style editor for a layer\n */\n private toggleStyleEditor(layerId: string): void {\n // If this editor is already open, close it\n if (this.state.activeStyleEditor === layerId) {\n this.closeStyleEditor(layerId);\n return;\n }\n\n // Close any other open editor\n if (this.state.activeStyleEditor) {\n this.closeStyleEditor(this.state.activeStyleEditor);\n }\n\n // Open this editor\n this.openStyleEditor(layerId);\n }\n\n /**\n * Open style editor for a layer\n */\n private openStyleEditor(layerId: string): void {\n const itemEl = this.panel.querySelector(`[data-layer-id=\"${layerId}\"]`);\n if (!itemEl) return;\n\n // Check if this is a custom layer\n const layerState = this.state.layerStates[layerId];\n if (layerState?.isCustomLayer) {\n // Check if the adapter provides native MapLibre layer IDs for style editing\n const nativeLayerIds =\n this.customLayerRegistry?.getNativeLayerIds(layerId);\n if (nativeLayerIds && nativeLayerIds.length > 0) {\n // Cache original styles for all native sublayers\n for (const nativeId of nativeLayerIds) {\n if (!this.state.originalStyles.has(nativeId)) {\n const nativeLayer = this.map.getLayer(nativeId);\n if (nativeLayer) {\n cacheOriginalLayerStyle(\n this.map,\n nativeId,\n this.state.originalStyles,\n );\n }\n }\n }\n\n // Create combined style editor for native sublayers\n const editor = this.createNativeSubLayerStyleEditor(\n layerId,\n nativeLayerIds,\n );\n if (editor) {\n itemEl.appendChild(editor);\n this.styleEditors.set(layerId, editor);\n this.state.activeStyleEditor = layerId;\n\n setTimeout(() => {\n editor.scrollIntoView({ behavior: \"smooth\", block: \"nearest\" });\n }, 50);\n return;\n }\n }\n\n // Fallback: show info message for custom layers without native sublayers\n const editor = this.createCustomLayerInfoPanel(layerId);\n itemEl.appendChild(editor);\n this.styleEditors.set(layerId, editor);\n this.state.activeStyleEditor = layerId;\n\n // Scroll into view\n setTimeout(() => {\n editor.scrollIntoView({ behavior: \"smooth\", block: \"nearest\" });\n }, 50);\n return;\n }\n\n // Cache original style if not already cached\n if (!this.state.originalStyles.has(layerId)) {\n const layer = this.map.getLayer(layerId);\n if (layer) {\n cacheOriginalLayerStyle(this.map, layerId, this.state.originalStyles);\n }\n }\n\n // Create style editor UI\n const editor = this.createStyleEditor(layerId);\n if (!editor) return;\n\n itemEl.appendChild(editor);\n this.styleEditors.set(layerId, editor);\n this.state.activeStyleEditor = layerId;\n\n // Scroll editor into view\n setTimeout(() => {\n editor.scrollIntoView({ behavior: \"smooth\", block: \"nearest\" });\n }, 50);\n }\n\n /**\n * Create info panel for custom layers (style editing not supported)\n */\n private createCustomLayerInfoPanel(layerId: string): HTMLDivElement {\n const editor = document.createElement(\"div\");\n editor.className = \"layer-control-style-editor layer-control-custom-info\";\n\n // Header\n const header = document.createElement(\"div\");\n header.className = \"style-editor-header\";\n\n const title = document.createElement(\"span\");\n title.className = \"style-editor-title\";\n title.textContent = \"Layer Info\";\n\n const closeBtn = document.createElement(\"button\");\n closeBtn.className = \"style-editor-close\";\n closeBtn.innerHTML = \"×\";\n closeBtn.title = \"Close\";\n closeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeStyleEditor(layerId);\n });\n\n header.appendChild(title);\n header.appendChild(closeBtn);\n\n // Info content\n const content = document.createElement(\"div\");\n content.className = \"style-editor-controls\";\n\n const infoText = document.createElement(\"p\");\n infoText.className = \"layer-control-custom-info-text\";\n infoText.textContent = `This is a custom layer. Style editing is not available for this layer type. Use the visibility toggle and opacity slider to control the layer.`;\n\n content.appendChild(infoText);\n\n // Action buttons\n const actions = document.createElement(\"div\");\n actions.className = \"style-editor-actions\";\n\n const removeBtn = document.createElement(\"button\");\n removeBtn.className = \"style-editor-button style-editor-button-remove\";\n removeBtn.textContent = \"Remove Layer\";\n removeBtn.title = \"Remove layer from map\";\n removeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.showRemoveConfirmation(editor, () => {\n this.closeStyleEditor(layerId);\n this.removeLayer(layerId);\n });\n });\n\n const closeActionBtn = document.createElement(\"button\");\n closeActionBtn.className = \"style-editor-button style-editor-button-close\";\n closeActionBtn.textContent = \"Close\";\n closeActionBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeStyleEditor(layerId);\n });\n\n actions.appendChild(removeBtn);\n actions.appendChild(closeActionBtn);\n\n editor.appendChild(header);\n editor.appendChild(content);\n editor.appendChild(actions);\n\n return editor;\n }\n\n /**\n * Create a combined style editor for custom layers with native MapLibre sublayers.\n * Groups controls by sublayer type (fill, line, circle, etc.).\n */\n private createNativeSubLayerStyleEditor(\n layerId: string,\n nativeLayerIds: string[],\n ): HTMLDivElement | null {\n // Group native layers by type\n const layersByType = new Map<string, string[]>();\n for (const nativeId of nativeLayerIds) {\n const layer = this.map.getLayer(nativeId);\n if (layer) {\n const type = layer.type;\n if (!layersByType.has(type)) {\n layersByType.set(type, []);\n }\n layersByType.get(type)!.push(nativeId);\n }\n }\n\n if (layersByType.size === 0) return null;\n\n const editor = document.createElement(\"div\");\n editor.className = \"layer-control-style-editor\";\n\n // Header\n const header = document.createElement(\"div\");\n header.className = \"style-editor-header\";\n\n const title = document.createElement(\"span\");\n title.className = \"style-editor-title\";\n title.textContent = \"Edit Style\";\n\n const closeBtn = document.createElement(\"button\");\n closeBtn.className = \"style-editor-close\";\n closeBtn.innerHTML = \"×\";\n closeBtn.title = \"Close\";\n closeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeStyleEditor(layerId);\n });\n\n header.appendChild(title);\n header.appendChild(closeBtn);\n editor.appendChild(header);\n\n // Controls container\n const controls = document.createElement(\"div\");\n controls.className = \"style-editor-controls\";\n\n // Type display names\n const typeLabels: Record<string, string> = {\n fill: \"Fill\",\n line: \"Line\",\n circle: \"Circle\",\n symbol: \"Symbol\",\n raster: \"Raster\",\n };\n\n // Add controls for each layer type, using the first native layer of that type\n for (const [type, ids] of layersByType) {\n // Add section header if there are multiple types\n if (layersByType.size > 1) {\n const sectionHeader = document.createElement(\"div\");\n sectionHeader.className = \"style-editor-section-header\";\n sectionHeader.textContent = typeLabels[type] || type;\n controls.appendChild(sectionHeader);\n }\n\n // Use the first layer of this type for controls\n // Changes will be applied to all layers of the same type\n const primaryId = ids[0];\n this.addStyleControlsForNativeGroup(controls, ids, primaryId, type);\n }\n\n // Action buttons\n const actions = document.createElement(\"div\");\n actions.className = \"style-editor-actions\";\n\n const resetBtn = document.createElement(\"button\");\n resetBtn.className = \"style-editor-button style-editor-button-reset\";\n resetBtn.textContent = \"Reset Style\";\n resetBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n // Reset all native sublayers\n for (const nativeId of nativeLayerIds) {\n restoreOriginalStyle(this.map, nativeId, this.state.originalStyles);\n }\n if (this.showAllStyleProperties) {\n this.clearUserAddedProperties(editor);\n }\n // Mirror the restored values to the host before the editor is rebuilt\n // (closeStyleEditor clears the active editor and group mappings).\n if (this.onLayerStyleChange) {\n editor.querySelectorAll(\"[data-property]\").forEach((el) => {\n const control = el as HTMLElement;\n const property = control.dataset.property as keyof AllPaintProperties | undefined;\n const sourceId = control.dataset.layerId;\n if (!property || !sourceId) return;\n if (property === \"fill-pattern\") {\n this.notifyLayerStyleChange(\n property,\n this.map.getPaintProperty(sourceId, property),\n );\n return;\n }\n const value = this.map.getPaintProperty(sourceId, property);\n if (value !== undefined) {\n const color =\n typeof value === \"number\" ? value : normalizeColor(value);\n if (color !== null) {\n this.notifyLayerStyleChange(property, color);\n }\n }\n });\n }\n // Refresh the editor\n this.closeStyleEditor(layerId);\n this.openStyleEditor(layerId);\n });\n\n const removeBtn = document.createElement(\"button\");\n removeBtn.className = \"style-editor-button style-editor-button-remove\";\n removeBtn.textContent = \"Remove Layer\";\n removeBtn.title = \"Remove layer from map\";\n removeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.showRemoveConfirmation(editor, () => {\n this.closeStyleEditor(layerId);\n this.removeLayer(layerId);\n });\n });\n\n const closeActionBtn = document.createElement(\"button\");\n closeActionBtn.className = \"style-editor-button style-editor-button-close\";\n closeActionBtn.textContent = \"Close\";\n closeActionBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeStyleEditor(layerId);\n });\n\n actions.appendChild(resetBtn);\n actions.appendChild(removeBtn);\n actions.appendChild(closeActionBtn);\n\n editor.appendChild(controls);\n editor.appendChild(actions);\n\n return editor;\n }\n\n /**\n * Add style controls for a group of native layers of the same type.\n * Changes to any control are applied to all layers in the group.\n */\n private addStyleControlsForNativeGroup(\n container: HTMLElement,\n layerIds: string[],\n primaryLayerId: string,\n layerType: string,\n ): void {\n // Register the group mapping so createColorControl/createSliderControl\n // will apply changes to all layers in the group\n this.nativeLayerGroups.set(primaryLayerId, layerIds);\n\n this.addStyleControlsForLayerType(container, primaryLayerId, layerType);\n }\n\n /**\n * Close style editor for a layer\n */\n private closeStyleEditor(layerId: string): void {\n const editor = this.styleEditors.get(layerId);\n if (editor) {\n editor.remove();\n this.styleEditors.delete(layerId);\n }\n\n // Clean up any native layer group mappings\n this.nativeLayerGroups.clear();\n\n if (this.state.activeStyleEditor === layerId) {\n this.state.activeStyleEditor = null;\n }\n }\n\n /**\n * Create style editor UI\n */\n private createStyleEditor(layerId: string): HTMLDivElement | null {\n const layer = this.map.getLayer(layerId);\n if (!layer) return null;\n\n const editor = document.createElement(\"div\");\n editor.className = \"layer-control-style-editor\";\n\n // Header\n const header = document.createElement(\"div\");\n header.className = \"style-editor-header\";\n\n const title = document.createElement(\"span\");\n title.className = \"style-editor-title\";\n title.textContent = \"Edit Style\";\n\n const closeBtn = document.createElement(\"button\");\n closeBtn.className = \"style-editor-close\";\n closeBtn.innerHTML = \"×\";\n closeBtn.title = \"Close\";\n closeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeStyleEditor(layerId);\n });\n\n header.appendChild(title);\n header.appendChild(closeBtn);\n\n // Controls container - populate based on layer type\n const controls = document.createElement(\"div\");\n controls.className = \"style-editor-controls\";\n\n const layerType = layer.type;\n this.addStyleControlsForLayerType(controls, layerId, layerType);\n\n // Action buttons\n const actions = document.createElement(\"div\");\n actions.className = \"style-editor-actions\";\n\n const resetBtn = document.createElement(\"button\");\n resetBtn.className = \"style-editor-button style-editor-button-reset\";\n resetBtn.textContent = \"Reset Style\";\n resetBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.resetLayerStyle(layerId);\n });\n\n const removeBtn = document.createElement(\"button\");\n removeBtn.className = \"style-editor-button style-editor-button-remove\";\n removeBtn.textContent = \"Remove Layer\";\n removeBtn.title = \"Remove layer from map\";\n removeBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.showRemoveConfirmation(editor, () => {\n this.closeStyleEditor(layerId);\n this.removeLayer(layerId);\n });\n });\n\n const closeActionBtn = document.createElement(\"button\");\n closeActionBtn.className = \"style-editor-button style-editor-button-close\";\n closeActionBtn.textContent = \"Close\";\n closeActionBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.closeStyleEditor(layerId);\n });\n\n actions.appendChild(resetBtn);\n actions.appendChild(removeBtn);\n actions.appendChild(closeActionBtn);\n\n editor.appendChild(header);\n editor.appendChild(controls);\n editor.appendChild(actions);\n\n return editor;\n }\n\n /**\n * Add style controls based on layer type\n */\n private addStyleControlsForLayerType(\n container: HTMLElement,\n layerId: string,\n layerType: string,\n ): void {\n switch (layerType) {\n case \"fill\":\n this.addFillControls(container, layerId);\n break;\n case \"line\":\n this.addLineControls(container, layerId);\n break;\n case \"circle\":\n this.addCircleControls(container, layerId);\n break;\n case \"raster\":\n this.addRasterControls(container, layerId);\n break;\n case \"symbol\":\n this.addSymbolControls(container, layerId);\n break;\n default:\n container.textContent = `Style controls for ${layerType} layers not yet implemented.`;\n }\n }\n\n /**\n * Add controls for fill layers\n */\n private addFillControls(container: HTMLElement, layerId: string): void {\n if (this.showAllStyleProperties) {\n this.addAllStyleControls(container, layerId, \"fill\");\n return;\n }\n // Fill Color - try layer definition first, then runtime property\n const style = this.map.getStyle();\n const layer = style.layers?.find((l) => l.id === layerId);\n let fillColor: any = undefined;\n\n // First try to get from layer definition\n if (\n layer &&\n \"paint\" in layer &&\n layer.paint &&\n \"fill-color\" in layer.paint\n ) {\n fillColor = layer.paint[\"fill-color\"];\n }\n\n // Fallback to runtime property if not in definition\n if (!fillColor) {\n fillColor = this.map.getPaintProperty(layerId, \"fill-color\");\n }\n\n const normalizedFillColor = normalizeColor(fillColor || \"#088\");\n if (normalizedFillColor !== null) {\n this.createColorControl(\n container,\n layerId,\n \"fill-color\",\n \"Fill Color\",\n normalizedFillColor,\n );\n }\n\n this.addFillPatternGroup(container, layerId);\n\n // Fill Opacity\n const fillOpacity = this.getStyleValue(layerId, \"fill-opacity\");\n if (fillOpacity !== undefined && typeof fillOpacity === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"fill-opacity\",\n \"Fill Opacity\",\n fillOpacity,\n 0,\n 1,\n 0.05,\n );\n }\n\n // Fill Outline Color\n const outlineColor = this.map.getPaintProperty(\n layerId,\n \"fill-outline-color\",\n );\n if (outlineColor !== undefined) {\n const normalizedOutlineColor = normalizeColor(outlineColor);\n if (normalizedOutlineColor !== null) {\n this.createColorControl(\n container,\n layerId,\n \"fill-outline-color\",\n \"Outline Color\",\n normalizedOutlineColor,\n );\n }\n }\n }\n\n /** Fill pattern picker group, with the Fill Color re-render hook. */\n private addFillPatternGroup(container: HTMLElement, layerId: string): void {\n const patternGroup = document.createElement(\"div\");\n patternGroup.className = \"style-control-group style-control-pattern-group\";\n patternGroup.dataset.property = \"fill-pattern\";\n patternGroup.dataset.layerId = layerId;\n container.appendChild(patternGroup);\n this.renderFillPatternPicker(patternGroup, layerId);\n\n container\n .querySelector<HTMLInputElement>(\n '.style-control-color-picker[data-property=\"fill-color\"]',\n )\n ?.addEventListener(\"change\", () =>\n this.renderFillPatternPicker(patternGroup, layerId),\n );\n }\n\n /**\n * `showAllStyleProperties`: add every control the editor supports for a\n * layer type. Controls are created from the style-spec default and then\n * refreshed from the map, so unset properties show their effective value\n * without anything being written to the style.\n */\n private addAllStyleControls(\n container: HTMLElement,\n layerId: string,\n layerType: EditableLayerType,\n ): void {\n for (const spec of STYLE_PROPERTY_SPECS[layerType]) {\n if (spec.kind === \"pattern\") {\n this.addFillPatternGroup(container, layerId);\n continue;\n }\n const property = spec.property as keyof AllPaintProperties;\n const group =\n spec.kind === \"color\"\n ? this.createColorControl(\n container,\n layerId,\n property,\n spec.label,\n spec.defaultValue,\n true,\n )\n : this.createSliderControl(\n container,\n layerId,\n property,\n spec.label,\n spec.defaultValue,\n spec.min,\n spec.max,\n spec.step,\n true,\n );\n this.refreshManagedControl(group);\n }\n }\n\n private renderFillPatternPicker(group: HTMLElement, layerId: string): void {\n group.replaceChildren();\n\n const targetIds = this.nativeLayerGroups.get(layerId) || [layerId];\n const currentValues = targetIds.map((id) =>\n this.map.getPaintProperty(id, \"fill-pattern\"),\n );\n const firstValue = currentValues[0];\n const firstValueIsUnset =\n firstValue === undefined || firstValue === null || firstValue === \"\";\n const mixed = currentValues.some((value) => {\n const valueIsUnset =\n value === undefined || value === null || value === \"\";\n if (valueIsUnset !== firstValueIsUnset) return true;\n return !valueIsUnset && JSON.stringify(value) !== JSON.stringify(firstValue);\n });\n const current = mixed ? undefined : firstValue;\n const images = listPatternImages(this.map);\n const color = getLayerColor(this.map, layerId, \"fill\");\n const kind = mixed\n ? \"mixed\"\n : current === undefined || current === null || current === \"\"\n ? \"none\"\n : typeof current === \"string\"\n ? \"constant\"\n : \"expression\";\n const selectedImage =\n kind === \"constant\"\n ? images.find((entry) => entry.id === current)\n : undefined;\n const missing = kind === \"constant\" && !selectedImage;\n const nonSdfPatternSelected = currentValues.some(\n (value) =>\n typeof value === \"string\" &&\n images.some((entry) => entry.id === value && !entry.image.sdf),\n );\n const fillColorPicker = group.parentElement?.querySelector<HTMLInputElement>(\n '.style-control-color-picker[data-property=\"fill-color\"]',\n );\n const fillColorGroup = fillColorPicker?.closest<HTMLElement>(\n \".style-control-group\",\n );\n if (fillColorGroup) {\n fillColorGroup.dataset.patternDisabled = String(nonSdfPatternSelected);\n this.syncControlDisabled(fillColorGroup);\n }\n // Outline color is unavailable while any fill pattern is set.\n this.refreshManagedControls(group.parentElement);\n\n const label = document.createElement(\"label\");\n label.className = \"style-control-label\";\n label.textContent = \"Fill Pattern\";\n group.appendChild(label);\n\n const currentLabel = document.createElement(\"div\");\n currentLabel.className = \"style-control-pattern-current\";\n if (mixed) {\n currentLabel.textContent = \"Current: Multiple patterns\";\n } else if (kind === \"none\") {\n currentLabel.textContent = \"Current: None (solid fill)\";\n } else if (kind === \"constant\" && missing) {\n currentLabel.textContent = `Current: ${current} (image not loaded)`;\n } else if (kind === \"constant\") {\n currentLabel.textContent = `Current: ${current}`;\n } else {\n currentLabel.textContent =\n \"Current: data-driven expression — select a pattern or None to replace it\";\n }\n group.appendChild(currentLabel);\n\n const list = document.createElement(\"div\");\n list.className = \"style-control-pattern-list\";\n list.setAttribute(\"role\", \"listbox\");\n list.setAttribute(\"aria-label\", \"Fill pattern\");\n\n const addOption = (\n patternId: string | null,\n optionLabel: string,\n image?: FillPatternImage,\n disabled = false,\n ): void => {\n const option = document.createElement(\"button\");\n option.className = \"style-control-pattern-option\";\n option.type = \"button\";\n option.setAttribute(\"role\", \"option\");\n option.dataset.patternId = patternId ?? \"\";\n option.title = optionLabel;\n option.disabled = disabled;\n option.setAttribute(\n \"aria-selected\",\n String(\n !mixed &&\n ((patternId === null && kind === \"none\") ||\n (kind === \"constant\" && patternId === current)),\n ),\n );\n\n const swatch = document.createElement(\"span\");\n swatch.className = \"style-control-pattern-swatch\";\n swatch.innerHTML = createLayerSymbolSVG(\"fill\", color, {\n fillPattern: image,\n size: 20,\n });\n\n const name = document.createElement(\"span\");\n name.className = \"style-control-pattern-name\";\n name.textContent = optionLabel;\n option.append(swatch, name);\n\n if (image?.sdf) {\n const badge = document.createElement(\"span\");\n badge.className = \"style-control-pattern-badge\";\n badge.textContent = \"SDF\";\n option.appendChild(badge);\n }\n\n if (!disabled) {\n option.addEventListener(\"click\", (event) => {\n event.stopPropagation();\n if (option.getAttribute(\"aria-selected\") === \"true\") return;\n\n const value = patternId ?? undefined;\n for (const id of targetIds) {\n this.map.setPaintProperty(id, \"fill-pattern\", value);\n }\n this.notifyLayerStyleChange(\"fill-pattern\", value);\n this.renderFillPatternPicker(group, layerId);\n group\n .querySelector<HTMLButtonElement>(\n '.style-control-pattern-option[aria-selected=\"true\"]',\n )\n ?.focus();\n });\n }\n list.appendChild(option);\n };\n\n if (missing) {\n addOption(current as string, `${current} (not loaded)`, undefined, true);\n }\n addOption(null, \"None (solid fill)\");\n images.forEach(({ id, image }) => addOption(id, id, image));\n group.appendChild(list);\n\n if (images.length === 0) {\n const empty = document.createElement(\"div\");\n empty.className = \"style-control-pattern-empty\";\n empty.textContent = \"No images loaded in the map style.\";\n group.appendChild(empty);\n }\n\n const hint = document.createElement(\"div\");\n hint.className = \"style-control-pattern-hint\";\n if (mixed) {\n hint.textContent = nonSdfPatternSelected\n ? \"Grouped layers use different patterns. Fill Color is disabled because at least one uses a non-SDF pattern. Selecting an option applies it to all.\"\n : \"Grouped layers use different patterns. Selecting an option applies it to all.\";\n } else if (kind === \"none\" || kind === \"expression\") {\n hint.hidden = true;\n } else if (missing) {\n hint.textContent =\n \"This image is not loaded in the map. The layer is unchanged until you choose another option.\";\n } else if (selectedImage?.image.sdf) {\n hint.textContent =\n \"SDF pattern: Fill Color recolors this pattern for this layer only.\";\n } else {\n hint.textContent =\n \"This pattern keeps its own colors; Fill Color is disabled while it is selected.\";\n }\n group.appendChild(hint);\n }\n\n /**\n * Add controls for line layers\n */\n private addLineControls(container: HTMLElement, layerId: string): void {\n if (this.showAllStyleProperties) {\n this.addAllStyleControls(container, layerId, \"line\");\n return;\n }\n // Line Color - try layer definition first, then runtime property\n const style = this.map.getStyle();\n const layer = style.layers?.find((l) => l.id === layerId);\n let lineColor: any = undefined;\n\n // First try to get from layer definition\n if (\n layer &&\n \"paint\" in layer &&\n layer.paint &&\n \"line-color\" in layer.paint\n ) {\n lineColor = layer.paint[\"line-color\"];\n }\n\n // Fallback to runtime property if not in definition\n if (!lineColor) {\n lineColor = this.map.getPaintProperty(layerId, \"line-color\");\n }\n\n const normalizedLineColor = normalizeColor(lineColor || \"#000\");\n if (normalizedLineColor !== null) {\n this.createColorControl(\n container,\n layerId,\n \"line-color\",\n \"Line Color\",\n normalizedLineColor,\n );\n }\n\n // Line Width\n const lineWidth = this.map.getPaintProperty(layerId, \"line-width\");\n this.createSliderControl(\n container,\n layerId,\n \"line-width\",\n \"Line Width\",\n typeof lineWidth === \"number\" ? lineWidth : 1,\n 0,\n 20,\n 0.5,\n );\n\n // Line Opacity\n const lineOpacity = this.getStyleValue(layerId, \"line-opacity\");\n if (lineOpacity !== undefined && typeof lineOpacity === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"line-opacity\",\n \"Line Opacity\",\n lineOpacity,\n 0,\n 1,\n 0.05,\n );\n }\n\n // Line Blur\n const lineBlur = this.map.getPaintProperty(layerId, \"line-blur\");\n if (lineBlur !== undefined && typeof lineBlur === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"line-blur\",\n \"Line Blur\",\n lineBlur,\n 0,\n 5,\n 0.1,\n );\n }\n }\n\n /**\n * Add controls for circle layers\n */\n private addCircleControls(container: HTMLElement, layerId: string): void {\n if (this.showAllStyleProperties) {\n this.addAllStyleControls(container, layerId, \"circle\");\n return;\n }\n // Circle Color - try layer definition first, then runtime property\n const style = this.map.getStyle();\n const layer = style.layers?.find((l) => l.id === layerId);\n let circleColor: any = undefined;\n\n // First try to get from layer definition\n if (\n layer &&\n \"paint\" in layer &&\n layer.paint &&\n \"circle-color\" in layer.paint\n ) {\n circleColor = layer.paint[\"circle-color\"];\n }\n\n // Fallback to runtime property if not in definition\n if (!circleColor) {\n circleColor = this.map.getPaintProperty(layerId, \"circle-color\");\n }\n\n const normalizedCircleColor = normalizeColor(circleColor || \"#000\");\n if (normalizedCircleColor !== null) {\n this.createColorControl(\n container,\n layerId,\n \"circle-color\",\n \"Circle Color\",\n normalizedCircleColor,\n );\n }\n\n // Circle Radius\n const circleRadius = this.map.getPaintProperty(layerId, \"circle-radius\");\n this.createSliderControl(\n container,\n layerId,\n \"circle-radius\",\n \"Radius\",\n typeof circleRadius === \"number\" ? circleRadius : 5,\n 0,\n 40,\n 0.5,\n );\n\n // Circle Opacity\n const circleOpacity = this.getStyleValue(layerId, \"circle-opacity\");\n if (circleOpacity !== undefined && typeof circleOpacity === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"circle-opacity\",\n \"Opacity\",\n circleOpacity,\n 0,\n 1,\n 0.05,\n );\n }\n\n // Circle Stroke Color\n const strokeColor = this.map.getPaintProperty(\n layerId,\n \"circle-stroke-color\",\n );\n if (strokeColor !== undefined) {\n const normalizedStrokeColor = normalizeColor(strokeColor);\n if (normalizedStrokeColor !== null) {\n this.createColorControl(\n container,\n layerId,\n \"circle-stroke-color\",\n \"Stroke Color\",\n normalizedStrokeColor,\n );\n }\n }\n\n // Circle Stroke Width\n const strokeWidth = this.map.getPaintProperty(\n layerId,\n \"circle-stroke-width\",\n );\n if (strokeWidth !== undefined && typeof strokeWidth === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"circle-stroke-width\",\n \"Stroke Width\",\n strokeWidth,\n 0,\n 10,\n 0.1,\n );\n }\n }\n\n /**\n * Add controls for raster layers\n */\n private addRasterControls(container: HTMLElement, layerId: string): void {\n if (this.showAllStyleProperties) {\n this.addAllStyleControls(container, layerId, \"raster\");\n return;\n }\n // Raster Opacity\n const rasterOpacity = this.getStyleValue(layerId, \"raster-opacity\");\n this.createSliderControl(\n container,\n layerId,\n \"raster-opacity\",\n \"Opacity\",\n typeof rasterOpacity === \"number\" ? rasterOpacity : 1,\n 0,\n 1,\n 0.05,\n );\n\n // Raster Brightness Min\n const brightnessMin = this.map.getPaintProperty(\n layerId,\n \"raster-brightness-min\",\n );\n this.createSliderControl(\n container,\n layerId,\n \"raster-brightness-min\",\n \"Brightness Min\",\n typeof brightnessMin === \"number\" ? brightnessMin : 0,\n -1,\n 1,\n 0.05,\n );\n\n // Raster Brightness Max\n const brightnessMax = this.map.getPaintProperty(\n layerId,\n \"raster-brightness-max\",\n );\n this.createSliderControl(\n container,\n layerId,\n \"raster-brightness-max\",\n \"Brightness Max\",\n typeof brightnessMax === \"number\" ? brightnessMax : 1,\n -1,\n 1,\n 0.05,\n );\n\n // Raster Saturation\n const saturation = this.map.getPaintProperty(layerId, \"raster-saturation\");\n this.createSliderControl(\n container,\n layerId,\n \"raster-saturation\",\n \"Saturation\",\n typeof saturation === \"number\" ? saturation : 0,\n -1,\n 1,\n 0.05,\n );\n\n // Raster Contrast\n const contrast = this.map.getPaintProperty(layerId, \"raster-contrast\");\n this.createSliderControl(\n container,\n layerId,\n \"raster-contrast\",\n \"Contrast\",\n typeof contrast === \"number\" ? contrast : 0,\n -1,\n 1,\n 0.05,\n );\n\n // Raster Hue Rotate\n const hueRotate = this.map.getPaintProperty(layerId, \"raster-hue-rotate\");\n this.createSliderControl(\n container,\n layerId,\n \"raster-hue-rotate\",\n \"Hue Rotate\",\n typeof hueRotate === \"number\" ? hueRotate : 0,\n 0,\n 350,\n 5,\n );\n }\n\n /**\n * Add controls for symbol layers\n */\n private addSymbolControls(container: HTMLElement, layerId: string): void {\n if (this.showAllStyleProperties) {\n this.addAllStyleControls(container, layerId, \"symbol\");\n return;\n }\n // Text Color\n const textColor = this.map.getPaintProperty(layerId, \"text-color\");\n if (textColor !== undefined) {\n const normalizedTextColor = normalizeColor(textColor);\n if (normalizedTextColor !== null) {\n this.createColorControl(\n container,\n layerId,\n \"text-color\",\n \"Text Color\",\n normalizedTextColor,\n );\n }\n }\n // Text Opacity\n const textOpacity = this.map.getPaintProperty(layerId, \"text-opacity\");\n if (textOpacity !== undefined && typeof textOpacity === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"text-opacity\",\n \"Text Opacity\",\n textOpacity,\n 0,\n 1,\n 0.05,\n );\n }\n\n // Icon Opacity\n const iconOpacity = this.getStyleValue(layerId, \"icon-opacity\");\n if (iconOpacity !== undefined && typeof iconOpacity === \"number\") {\n this.createSliderControl(\n container,\n layerId,\n \"icon-opacity\",\n \"Icon Opacity\",\n iconOpacity,\n 0,\n 1,\n 0.05,\n );\n }\n }\n\n /**\n * Notify the host that a paint property changed through the style editor.\n * Reports the layer the active style editor belongs to (`activeStyleEditor`),\n * not the internal native sub-layer id a control may edit, so consumers can\n * map the change back to their own layer model.\n */\n private notifyLayerStyleChange(property: string, value: unknown): void {\n const layerId = this.state.activeStyleEditor;\n if (layerId && this.onLayerStyleChange) {\n this.onLayerStyleChange(layerId, property, value);\n }\n }\n\n /**\n * Re-read an open style editor's controls from the current map paint so they\n * reflect changes made elsewhere (e.g. an external sidebar writing the same\n * paint properties). Setting input `.value` programmatically does not\n * dispatch an `input` event, so this never re-triggers\n * {@link LayerControlOptions.onLayerStyleChange}. The control the user is\n * actively dragging (the focused input) is left untouched so the refresh\n * does not fight an in-progress drag.\n *\n * @param layerId Restrict the refresh to one layer's editor. Defaults to the\n * currently active editor. No-op when that editor is not open.\n */\n public refreshStyleEditor(layerId?: string): void {\n const targetId = layerId ?? this.state.activeStyleEditor;\n if (!targetId) return;\n const editor = this.styleEditors.get(targetId);\n if (editor) {\n this.syncStyleEditorControlsFromMap(editor);\n }\n }\n\n /**\n * Update every slider/color control in a style editor from the layer's\n * current map paint. Each control records the layer it reads from in\n * `dataset.layerId` (see createSliderControl/createColorControl).\n */\n private syncStyleEditorControlsFromMap(editor: HTMLElement): void {\n const active = document.activeElement;\n\n const sliders = editor.querySelectorAll(\n \".style-control-slider\",\n ) as NodeListOf<HTMLInputElement>;\n sliders.forEach((slider) => {\n if (\n slider === active ||\n slider.parentElement?.querySelector(\".style-control-number-input\") === active\n ) return;\n const property = slider.dataset.property as keyof AllPaintProperties | undefined;\n const sourceId = slider.dataset.layerId;\n if (!property || !sourceId) return;\n const value = this.getStyleValue(sourceId, property);\n if (typeof value === \"number\") {\n slider.value = String(value);\n const valueDisplay = slider.parentElement?.querySelector(\n \".style-control-value\",\n );\n if (valueDisplay) {\n const step = parseFloat(slider.step);\n valueDisplay.textContent = formatNumericValue(value, step);\n }\n }\n });\n\n const colorPickers = editor.querySelectorAll(\n \".style-control-color-picker\",\n ) as NodeListOf<HTMLInputElement>;\n colorPickers.forEach((picker) => {\n if (picker === active) return;\n const property = picker.dataset.property as keyof AllPaintProperties | undefined;\n const sourceId = picker.dataset.layerId;\n if (!property || !sourceId) return;\n const value = this.map.getPaintProperty(sourceId, property);\n if (value !== undefined) {\n const hexColor = normalizeColor(value);\n if (hexColor === null) return;\n picker.value = hexColor;\n const hexDisplay = picker.parentElement?.querySelector(\n \".style-control-color-value\",\n ) as HTMLInputElement | null;\n if (hexDisplay) hexDisplay.value = hexColor;\n }\n });\n this.refreshManagedControls(editor);\n editor\n .querySelectorAll<HTMLElement>(\".style-control-pattern-group\")\n .forEach((group) => {\n const sourceId = group.dataset.layerId;\n if (sourceId) this.renderFillPatternPicker(group, sourceId);\n });\n\n }\n\n /**\n * Create a color control\n */\n private createColorControl(\n container: HTMLElement,\n layerId: string,\n property: keyof AllPaintProperties,\n label: string,\n initialValue: string,\n managed = false,\n ): HTMLElement {\n const controlGroup = document.createElement(\"div\");\n controlGroup.className = \"style-control-group\";\n if (managed) controlGroup.dataset.managed = \"true\";\n\n const labelEl = document.createElement(\"label\");\n labelEl.className = \"style-control-label\";\n labelEl.textContent = label;\n\n const inputWrapper = document.createElement(\"div\");\n inputWrapper.className = \"style-control-color-group\";\n\n const colorInput = document.createElement(\"input\");\n colorInput.type = \"color\";\n colorInput.className = \"style-control-color-picker\";\n colorInput.value = initialValue;\n colorInput.dataset.property = property;\n // The layer to read this property back from when refreshing the editor\n // from the map (see refreshStyleEditor). For native sub-layer groups this\n // is the primary group member; the rest stay in sync with it.\n colorInput.dataset.layerId = layerId;\n\n const hexDisplay = document.createElement(\"input\");\n hexDisplay.type = \"text\";\n hexDisplay.className = \"style-control-color-value\";\n hexDisplay.value = initialValue;\n hexDisplay.readOnly = true;\n\n colorInput.addEventListener(\"input\", () => {\n const color = colorInput.value;\n hexDisplay.value = color;\n const targetIds = this.nativeLayerGroups.get(layerId) || [layerId];\n for (const id of targetIds) {\n this.map.setPaintProperty(id, property, color);\n }\n this.notifyLayerStyleChange(property, color);\n if (managed) this.refreshManagedControls(controlGroup.parentElement, property);\n });\n\n inputWrapper.appendChild(colorInput);\n inputWrapper.appendChild(hexDisplay);\n\n controlGroup.appendChild(labelEl);\n controlGroup.appendChild(inputWrapper);\n\n container.appendChild(controlGroup);\n return controlGroup;\n }\n\n /**\n * Create a slider control\n */\n private createSliderControl(\n container: HTMLElement,\n layerId: string,\n property: keyof AllPaintProperties,\n label: string,\n initialValue: number,\n min: number,\n max: number,\n step: number,\n managed = false,\n ): HTMLElement {\n const controlGroup = document.createElement(\"div\");\n controlGroup.className = \"style-control-group\";\n if (managed) controlGroup.dataset.managed = \"true\";\n\n const labelEl = document.createElement(\"label\");\n labelEl.className = \"style-control-label\";\n labelEl.textContent = label;\n\n const inputWrapper = document.createElement(\"div\");\n inputWrapper.className = \"style-control-input-wrapper\";\n\n const slider = document.createElement(\"input\");\n slider.type = \"range\";\n slider.className = \"style-control-slider\";\n slider.min = String(min);\n slider.max = String(max);\n slider.step = String(step);\n slider.value = String(initialValue);\n slider.dataset.property = property;\n // The layer to read this property back from when refreshing the editor\n // from the map (see refreshStyleEditor). For native sub-layer groups this\n // is the primary group member; the rest stay in sync with it.\n slider.dataset.layerId = layerId;\n\n const valueDisplay = document.createElement(\"button\");\n valueDisplay.type = \"button\";\n valueDisplay.className = \"style-control-value\";\n valueDisplay.textContent = formatNumericValue(initialValue, step);\n valueDisplay.title = `Click to enter an exact ${label.toLowerCase()}`;\n valueDisplay.setAttribute(\"aria-label\", `Edit ${label}`);\n\n const updateValue = (value: number) => {\n // A range input may snap its thumb to a coarse step. Keep the exact\n // value in the display and paint rather than reading it back from the slider.\n slider.value = String(value);\n valueDisplay.textContent = formatNumericValue(value, step);\n if (this.getAdapterOwnedOpacityProperty(layerId) === property) {\n // The adapter folds in its folder opacity and records the layer's own\n // value; writing the paint property here would bypass both.\n this.changeLayerOpacity(layerId, value);\n const layerState = this.state.layerStates[layerId];\n this.updateUIForLayer(layerId, layerState?.visible ?? true, value);\n } else {\n const targetIds = this.nativeLayerGroups.get(layerId) || [layerId];\n for (const id of targetIds) {\n this.map.setPaintProperty(id, property, value);\n }\n }\n this.notifyLayerStyleChange(property, value);\n };\n\n slider.addEventListener(\"input\", () => {\n updateValue(parseFloat(slider.value));\n });\n\n valueDisplay.addEventListener(\"click\", (event) => {\n event.stopPropagation();\n const input = document.createElement(\"input\");\n input.type = \"number\";\n input.className = \"style-control-number-input\";\n input.min = String(min);\n input.max = String(max);\n // Exact entry uses the display precision, not the coarse slider increment.\n const decimals = formatNumericValue(0, step).split(\".\")[1]?.length ?? 0;\n input.step = String(10 ** -decimals);\n input.value = valueDisplay.textContent ?? \"\";\n input.setAttribute(\"aria-label\", label);\n input.addEventListener(\"click\", (event) => event.stopPropagation());\n input.addEventListener(\"pointerdown\", (event) => event.stopPropagation());\n\n // Match the opacity popup: Enter/blur apply, Escape cancels, and a\n // key-triggered settlement must not apply again when focus moves.\n let settled = false;\n const settle = (apply: boolean) => {\n if (settled) return;\n settled = true;\n const value = input.valueAsNumber;\n input.replaceWith(valueDisplay);\n if (apply && Number.isFinite(value)) {\n updateValue(Number(formatNumericValue(clamp(value, min, max), step)));\n }\n };\n input.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\" || event.key === \"Escape\") {\n event.preventDefault();\n event.stopPropagation();\n settle(event.key === \"Enter\");\n valueDisplay.focus();\n }\n });\n input.addEventListener(\"blur\", () => settle(true));\n\n valueDisplay.replaceWith(input);\n input.focus();\n input.select();\n });\n\n inputWrapper.appendChild(slider);\n inputWrapper.appendChild(valueDisplay);\n\n controlGroup.appendChild(labelEl);\n controlGroup.appendChild(inputWrapper);\n\n container.appendChild(controlGroup);\n return controlGroup;\n }\n\n /**\n * Read the effective value a managed (`showAllStyleProperties`) control\n * should display: the layer's own value, else the inherited value, else the\n * style-spec default. Returns `expressionOf` (the property whose value is\n * not editable) when that value is an expression or otherwise not a plain\n * number/color.\n */\n private resolveEffectiveValue(\n layerId: string,\n spec: Exclude<StylePropertySpec, { kind: \"pattern\" }>,\n ): { value: string | number } | { expressionOf: string } {\n if (\n spec.kind === \"slider\" &&\n this.getAdapterOwnedOpacityProperty(layerId) === spec.property\n ) {\n // The adapter owns this layer's opacity; the map paint is folded.\n return { value: this.getStyleValue(layerId, spec.property as keyof AllPaintProperties) as number };\n }\n const raw = this.map.getPaintProperty(\n layerId,\n spec.property as keyof AllPaintProperties,\n );\n if (isUnsetValue(raw)) {\n const parent =\n spec.kind === \"color\" && spec.inheritsFrom\n ? STYLE_PROPERTY_SPEC_BY_PROPERTY[spec.inheritsFrom]\n : undefined;\n if (parent && parent.kind !== \"pattern\") {\n return this.resolveEffectiveValue(layerId, parent);\n }\n return { value: spec.defaultValue };\n }\n const value =\n spec.kind === \"slider\"\n ? typeof raw === \"number\"\n ? raw\n : null\n : normalizeColor(raw);\n return value === null ? { expressionOf: spec.property } : { value };\n }\n\n /**\n * Explain why a managed control cannot take effect on any of the layers it\n * edits (style-spec `requires` dependencies), or null when it can. With\n * grouped native sublayers the control stays enabled while at least one\n * layer in the group can still use the edit.\n */\n private getDependencyReason(\n targetIds: string[],\n property: string,\n ): string | null {\n const paint = (id: string, prop: string) =>\n this.map.getPaintProperty(id, prop as keyof AllPaintProperties);\n const layout = (id: string, prop: string) =>\n this.map.getLayoutProperty(id, prop as never);\n switch (property) {\n case \"fill-outline-color\":\n if (targetIds.every((id) => paint(id, \"fill-antialias\") === false)) {\n return \"Outline color requires fill antialiasing, which is turned off for this layer.\";\n }\n if (targetIds.every((id) => !isUnsetValue(paint(id, \"fill-pattern\")))) {\n return \"Outline color has no effect while a fill pattern is set.\";\n }\n return null;\n case \"line-color\":\n return targetIds.every((id) => !isUnsetValue(paint(id, \"line-pattern\")))\n ? \"Line color has no effect while a line pattern is set.\"\n : null;\n case \"text-color\":\n case \"text-opacity\":\n return targetIds.every((id) => isUnsetValue(layout(id, \"text-field\")))\n ? \"Requires a text-field; this layer has no text to style.\"\n : null;\n case \"icon-opacity\":\n return targetIds.every((id) => isUnsetValue(layout(id, \"icon-image\")))\n ? \"Requires an icon-image; this layer has no icon to style.\"\n : null;\n default:\n return null;\n }\n }\n\n /**\n * Re-evaluate every managed control under `root` from the current map\n * state (see {@link refreshManagedControl}). `inheritsFrom` limits the pass\n * to controls whose unset value follows that property.\n */\n private refreshManagedControls(\n root: ParentNode | null | undefined,\n inheritsFrom?: string,\n ): void {\n root\n ?.querySelectorAll<HTMLElement>('.style-control-group[data-managed=\"true\"]')\n .forEach((group) => this.refreshManagedControl(group, inheritsFrom));\n }\n\n /**\n * Update a managed control's displayed value and its enabled/disabled state\n * with explanation from the current map state. Reads only; never writes to\n * the map.\n */\n private refreshManagedControl(\n group: HTMLElement,\n inheritsFrom?: string,\n ): void {\n const input = group.querySelector<HTMLInputElement>(\"[data-property]\");\n const property = input?.dataset.property;\n const sourceId = input?.dataset.layerId;\n const spec = property ? STYLE_PROPERTY_SPEC_BY_PROPERTY[property] : undefined;\n if (!input || !sourceId || !spec || spec.kind === \"pattern\") return;\n if (\n inheritsFrom &&\n !(spec.kind === \"color\" && spec.inheritsFrom === inheritsFrom)\n ) {\n return;\n }\n\n const targetIds = this.nativeLayerGroups.get(sourceId) || [sourceId];\n const effective = this.resolveEffectiveValue(sourceId, spec);\n const expressionOf =\n \"expressionOf\" in effective\n ? effective.expressionOf\n : targetIds\n .map((id) => this.resolveEffectiveValue(id, spec))\n .find((entry) => \"expressionOf\" in entry)?.expressionOf;\n\n let reason = this.getDependencyReason(targetIds, spec.property);\n if (!reason && expressionOf) {\n const owner = STYLE_PROPERTY_SPEC_BY_PROPERTY[expressionOf];\n const ownerLabel =\n owner && owner.kind !== \"pattern\" ? owner.label : expressionOf;\n reason =\n expressionOf === spec.property\n ? `${spec.label} uses a data-driven expression, which the editor cannot edit. The value shown is a placeholder.`\n : `Inherits ${ownerLabel}, which uses a data-driven expression the editor cannot edit. The value shown is a placeholder.`;\n }\n\n // Leave a control the user is dragging alone, as refreshStyleEditor does.\n if (\"value\" in effective && input !== document.activeElement) {\n input.value = String(effective.value);\n if (spec.kind === \"slider\") {\n const display = group.querySelector(\".style-control-value\");\n if (display) {\n display.textContent = formatNumericValue(\n Number(effective.value),\n spec.step,\n );\n }\n } else {\n const hex = group.querySelector<HTMLInputElement>(\n \".style-control-color-value\",\n );\n if (hex) hex.value = String(effective.value);\n }\n }\n\n this.setControlUnavailableReason(group, reason);\n }\n\n /** Show or clear the explanation for a disabled managed control. */\n private setControlUnavailableReason(\n group: HTMLElement,\n reason: string | null,\n ): void {\n let reasonEl = group.querySelector<HTMLElement>(\".style-control-reason\");\n if (reason) {\n group.dataset.unavailableReason = reason;\n group.title = reason;\n if (!reasonEl) {\n reasonEl = document.createElement(\"div\");\n reasonEl.className = \"style-control-reason\";\n group.appendChild(reasonEl);\n }\n reasonEl.textContent = reason;\n } else {\n delete group.dataset.unavailableReason;\n group.removeAttribute(\"title\");\n reasonEl?.remove();\n }\n group.classList.toggle(\"style-control-group-disabled\", reason !== null);\n this.syncControlDisabled(group);\n }\n\n /**\n * A control's inputs are disabled while it is unavailable (dependency or\n * expression) or while a non-SDF fill pattern owns its color.\n */\n private syncControlDisabled(group: HTMLElement): void {\n const disabled =\n group.dataset.unavailableReason !== undefined ||\n group.dataset.patternDisabled === \"true\";\n group.querySelectorAll<HTMLInputElement>(\"input\").forEach((input) => {\n input.disabled = disabled;\n });\n }\n\n /**\n * Unset properties that a managed control added on top of the layer's\n * original style, so Reset Style returns the layer to what it was before the\n * user edited a control the original style never set.\n */\n private clearUserAddedProperties(editor: HTMLElement): void {\n editor\n .querySelectorAll<HTMLElement>(\n '.style-control-group[data-managed=\"true\"] [data-property]',\n )\n .forEach((control) => {\n const property = control.dataset.property as\n | keyof AllPaintProperties\n | undefined;\n const sourceId = control.dataset.layerId;\n if (!property || !sourceId) return;\n let cleared = false;\n for (const id of this.nativeLayerGroups.get(sourceId) || [sourceId]) {\n const original = this.state.originalStyles.get(id);\n if (!original || property in original.paint) continue;\n if (this.map.getPaintProperty(id, property) === undefined) continue;\n this.map.setPaintProperty(id, property, undefined);\n cleared = true;\n }\n if (cleared) this.notifyLayerStyleChange(property, undefined);\n });\n }\n\n /**\n * Reset layer style to original\n */\n private resetLayerStyle(layerId: string): void {\n const originalStyle = this.state.originalStyles.get(layerId);\n if (!originalStyle) return;\n\n // Restore original paint properties\n restoreOriginalStyle(this.map, layerId, this.state.originalStyles);\n // The restored paint value is not the layer's own opacity when an adapter\n // owns it; re-apply the adapter's value so the map stays consistent with it.\n if (this.getAdapterOwnedOpacityProperty(layerId) !== null) {\n this.customLayerRegistry?.setOpacity(\n layerId,\n this.customLayerRegistry.getLayerState(layerId)!.opacity,\n );\n }\n\n // Update UI controls to reflect the reset values\n const editor = this.styleEditors.get(layerId);\n if (editor && this.showAllStyleProperties) {\n this.clearUserAddedProperties(editor);\n }\n if (editor) {\n // Update all slider controls\n const sliders = editor.querySelectorAll(\n \".style-control-slider\",\n ) as NodeListOf<HTMLInputElement>;\n sliders.forEach((slider) => {\n const property = slider.dataset.property as keyof AllPaintProperties | undefined;\n if (property) {\n const value = this.getStyleValue(layerId, property);\n if (value !== undefined && typeof value === \"number\") {\n slider.value = String(value);\n // Update value display\n const valueDisplay = slider.parentElement?.querySelector(\n \".style-control-value\",\n );\n if (valueDisplay) {\n const step = parseFloat(slider.step);\n valueDisplay.textContent = formatNumericValue(value, step);\n }\n this.notifyLayerStyleChange(property, value);\n }\n }\n });\n\n // Update all color controls\n const colorPickers = editor.querySelectorAll(\n \".style-control-color-picker\",\n ) as NodeListOf<HTMLInputElement>;\n colorPickers.forEach((picker) => {\n const property = picker.dataset.property as keyof AllPaintProperties | undefined;\n if (property) {\n const value = this.map.getPaintProperty(layerId, property);\n if (value !== undefined) {\n const hexColor = normalizeColor(value);\n if (hexColor === null) return;\n picker.value = hexColor;\n // Update hex display\n const hexDisplay = picker.parentElement?.querySelector(\n \".style-control-color-value\",\n ) as HTMLInputElement | null;\n if (hexDisplay) {\n hexDisplay.value = hexColor;\n }\n this.notifyLayerStyleChange(property, hexColor);\n }\n }\n });\n editor\n .querySelectorAll<HTMLElement>(\".style-control-pattern-group\")\n .forEach((group) => {\n const sourceId = group.dataset.layerId || layerId;\n this.renderFillPatternPicker(group, sourceId);\n this.notifyLayerStyleChange(\n \"fill-pattern\",\n this.map.getPaintProperty(sourceId, \"fill-pattern\"),\n );\n });\n this.refreshManagedControls(editor);\n }\n }\n\n /**\n * Read the visibility and opacity a layer's panel row should show. A native\n * layer an adapter manages reports its own values; the map's paint and layout\n * hold those combined with the adapter's folder settings, so reading them\n * back would corrupt the row.\n * @param layerId The layer ID\n * @param layerType The layer's map type\n */\n private readLayerRowState(\n layerId: string,\n layerType: string,\n ): { visible: boolean; opacity: number } {\n const adapterState = this.customLayerRegistry?.getLayerState(layerId);\n const visibility = this.map.getLayoutProperty(layerId, \"visibility\");\n return {\n visible: adapterState?.visible ?? visibility !== \"none\",\n opacity:\n adapterState?.opacity ?? getLayerOpacity(this.map, layerId, layerType),\n };\n }\n\n /**\n * Update layer states from map (sync UI with map)\n */\n private updateLayerStatesFromMap(): void {\n if (this.state.userInteractingWithSlider) {\n return; // Don't update while user is dragging\n }\n\n // Find the rows once. Looking each layer's row up by scanning every row made a sync cost\n // layers x rows, and a sync runs on every styledata and data event: with a few hundred\n // layers that froze the page.\n const rows = this.rowsByLayerId();\n\n Object.keys(this.state.layerStates).forEach((layerId) => {\n try {\n // Skip custom layers - they manage their own state via adapters\n if (this.state.layerStates[layerId]?.isCustomLayer) {\n return;\n }\n\n // Skip Background layer group\n if (layerId === \"Background\") {\n return;\n }\n\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n\n const { visible: isVisible, opacity } = this.readLayerRowState(\n layerId,\n layer.type,\n );\n\n // Update local state\n if (this.state.layerStates[layerId]) {\n this.state.layerStates[layerId].visible = isVisible;\n this.state.layerStates[layerId].opacity = opacity;\n }\n\n // Update UI\n this.updateUIForLayer(layerId, isVisible, opacity, rows);\n } catch (error) {\n console.warn(`Failed to update state for layer ${layerId}:`, error);\n }\n });\n }\n\n /**\n * Update UI elements for a specific layer\n */\n private updateUIForLayer(\n layerId: string,\n visible: boolean,\n opacity: number,\n rows: Map<string, HTMLElement[]> = this.rowsByLayerId(),\n ): void {\n for (const item of rows.get(layerId) ?? []) {\n const checkbox = item.querySelector(\n \".layer-control-checkbox\",\n ) as HTMLInputElement;\n const opacitySlider = item.querySelector(\n \".layer-control-opacity\",\n ) as HTMLInputElement;\n\n if (checkbox) {\n checkbox.checked = visible;\n }\n\n if (opacitySlider) {\n opacitySlider.value = String(opacity);\n opacitySlider.title = `Opacity: ${Math.round(opacity * 100)}%`;\n }\n }\n }\n\n /**\n * The panel's layer rows, by layer ID\n */\n private rowsByLayerId(): Map<string, HTMLElement[]> {\n const rows = new Map<string, HTMLElement[]>();\n this.panel\n .querySelectorAll<HTMLElement>(\".layer-control-item\")\n .forEach((item) => {\n const id = item.dataset.layerId;\n if (id === undefined) return;\n const list = rows.get(id);\n if (list) list.push(item);\n else rows.set(id, [item]);\n });\n return rows;\n }\n\n /**\n * Check for new layers and add them to the control, remove deleted layers\n */\n private checkForNewLayers(): void {\n // Skip checking for new layers during style operations to prevent race conditions\n // that could incorrectly delete custom layers\n if (this.state.isStyleOperationInProgress) {\n return;\n }\n\n try {\n const style = this.map.getStyle();\n if (!style || !style.layers) {\n return;\n }\n\n const currentMapLayerIds = new Set(style.layers.map((layer) => layer.id));\n\n // Check if we're in auto-detect mode (no specific layers were specified)\n const isAutoDetectMode =\n this.targetLayers.length === 0 ||\n (this.targetLayers.length === 1 &&\n this.targetLayers[0] === \"Background\") ||\n this.targetLayers.every(\n (id) => id === \"Background\" || this.state.layerStates[id],\n );\n\n // Track whether new layers were added so the panel can be rebuilt in the\n // correct stacking order afterwards (appending items would otherwise place\n // a newly added layer at the bottom, below the Background group).\n let layersAdded = false;\n\n // Find new layers that aren't in our state yet\n const newLayers: string[] = [];\n\n // Detection priority for NEW layers (added after control):\n // 1. basemapLayerIds (from basemapStyleUrl) - most reliable\n // 2. initialLayerIds - layer NOT in initialLayerIds means it was added after control\n // 3. Source-based heuristics - fallback\n const useBasemapStyleDetection =\n this.hasBasemapLayerIds();\n const useInitialLayerDetection =\n !useBasemapStyleDetection &&\n this.initialLayerIds !== null &&\n this.initialLayerIds.size > 0;\n\n currentMapLayerIds.forEach((layerId) => {\n if (layerId !== \"Background\" && !this.state.layerStates[layerId]) {\n const layer = this.map.getLayer(layerId);\n if (layer) {\n // Always skip layers that were present when control was initialized\n // These are background/basemap layers and should stay grouped under \"Background\"\n if (\n this.initialLayerIds !== null &&\n this.initialLayerIds.has(layerId)\n ) {\n // Layer was in initial set - it's a background layer, skip it\n return;\n }\n\n // In auto-detect mode, apply additional filtering\n if (isAutoDetectMode) {\n // Skip drawn layers if excludeDrawnLayers is enabled\n if (this.excludeDrawnLayers && this.isDrawnLayer(layerId)) {\n return;\n }\n\n // Skip layers matching user-defined exclusion patterns\n if (this.isExcludedByPattern(layerId)) {\n return;\n }\n\n // Skip layers that are not user-added (i.e., background/basemap layers)\n if (!this.isUserAddedLayer(layerId)) {\n return;\n }\n\n if (useBasemapStyleDetection) {\n // Use basemap style layer IDs - if layer is in basemap, skip it\n if (this.basemapLayerIds!.has(layerId)) {\n return;\n }\n } else if (useInitialLayerDetection) {\n // Layer NOT in initialLayerIds means it was added AFTER control\n // These are definitely user-added layers and should be included\n if (this.initialLayerIds!.has(layerId)) {\n // Layer was in initial set - check source-based heuristics\n const userAddedSourceIds = this.detectUserAddedSources();\n const sourceId = (layer as any).source;\n if (!sourceId || !userAddedSourceIds.has(sourceId)) {\n return;\n }\n }\n // Layer NOT in initialLayerIds - it's new, include it\n } else {\n // Fall back to source-based heuristics\n const userAddedSourceIds = this.detectUserAddedSources();\n const sourceId = (layer as any).source;\n if (!sourceId || !userAddedSourceIds.has(sourceId)) {\n return;\n }\n }\n }\n newLayers.push(layerId);\n }\n }\n });\n\n // Find removed layers that are still in our state\n // Skip custom layers - they have their own removal mechanism via the adapter\n const removedLayers: string[] = [];\n Object.keys(this.state.layerStates).forEach((layerId) => {\n const state = this.state.layerStates[layerId];\n // Skip Background, custom layers, and layers still in the map\n if (\n layerId !== \"Background\" &&\n !state.isCustomLayer &&\n !currentMapLayerIds.has(layerId)\n ) {\n removedLayers.push(layerId);\n }\n });\n\n // Remove deleted layers from UI and state\n if (removedLayers.length > 0) {\n removedLayers.forEach((layerId) => {\n // Remove from state\n delete this.state.layerStates[layerId];\n\n // Remove from UI\n const itemEl = this.panel.querySelector(\n `[data-layer-id=\"${layerId}\"]`,\n );\n if (itemEl) {\n itemEl.remove();\n }\n\n // Clean up style editor if open\n if (this.state.activeStyleEditor === layerId) {\n this.state.activeStyleEditor = null;\n }\n this.styleEditors.delete(layerId);\n });\n }\n\n // Add UI for new layers\n if (newLayers.length > 0) {\n newLayers.forEach((layerId) => {\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n\n const { visible: isVisible, opacity } = this.readLayerRowState(\n layerId,\n layer.type,\n );\n\n // Add to state\n this.state.layerStates[layerId] = {\n visible: isVisible,\n opacity: opacity,\n name: this.generateFriendlyName(layerId),\n };\n // Keep an explicit target-layer list in sync so the rebuilt panel\n // still renders this layer. An empty list means \"show all\", so it\n // must stay empty (pushing would start filtering out other layers\n // such as the Background group).\n if (\n this.targetLayers.length > 0 &&\n !this.targetLayers.includes(layerId)\n ) {\n this.targetLayers.push(layerId);\n }\n\n layersAdded = true;\n });\n }\n\n // Check for new/removed custom layers\n if (this.customLayerRegistry) {\n const customLayerIds = this.customLayerRegistry.getAllLayerIds();\n\n // Find new custom layers (skip ones explicitly removed by the user)\n customLayerIds.forEach((layerId) => {\n if (\n !this.state.layerStates[layerId] &&\n !this.removedCustomLayerIds.has(layerId)\n ) {\n const customState =\n this.customLayerRegistry!.getLayerState(layerId);\n if (customState) {\n this.state.layerStates[layerId] = {\n visible: customState.visible,\n opacity: customState.opacity,\n name: customState.name,\n isCustomLayer: true,\n customLayerType:\n this.customLayerRegistry!.getSymbolType(layerId) || undefined,\n };\n // See note above: only extend a restricted (non-empty) list.\n if (\n this.targetLayers.length > 0 &&\n !this.targetLayers.includes(layerId)\n ) {\n this.targetLayers.push(layerId);\n }\n layersAdded = true;\n }\n }\n });\n\n // Find removed custom layers\n Object.keys(this.state.layerStates).forEach((layerId) => {\n const state = this.state.layerStates[layerId];\n if (state.isCustomLayer && !customLayerIds.includes(layerId)) {\n // Remove from state\n delete this.state.layerStates[layerId];\n\n // Remove from UI\n const itemEl = this.panel.querySelector(\n `[data-layer-id=\"${layerId}\"]`,\n );\n if (itemEl) {\n itemEl.remove();\n }\n\n // Clean up style editor if open\n if (this.state.activeStyleEditor === layerId) {\n this.state.activeStyleEditor = null;\n }\n this.styleEditors.delete(layerId);\n }\n });\n }\n\n // Rebuild the panel so newly added layers are placed in the correct\n // stacking order (top of the panel = top-most layer) instead of being\n // appended below the Background group.\n if (layersAdded) {\n this.buildLayerItems();\n } else {\n this.pruneEmptyGroups();\n }\n } catch (error) {\n console.warn(\"Failed to check for new layers:\", error);\n }\n }\n\n /**\n * Register a custom layer adapter dynamically.\n * This allows adding adapters after the LayerControl has been initialized.\n * @param adapter The custom layer adapter to register\n */\n registerCustomAdapter(adapter: CustomLayerAdapter): void {\n // Create registry if it doesn't exist\n if (!this.customLayerRegistry) {\n this.customLayerRegistry = new CustomLayerRegistry();\n // Subscribe to registry changes\n this.customLayerUnsubscribe = this.customLayerRegistry.onChange(\n (event, layerId) => {\n if (event === \"add\" && layerId) {\n this.removedCustomLayerIds.delete(layerId);\n }\n this.checkForNewLayers();\n },\n );\n }\n\n // Register the adapter\n this.customLayerRegistry.register(adapter);\n\n // Rebuild layer items to include the new adapter's layers\n if (this.panel) {\n this.checkForNewLayers();\n }\n }\n\n // ===== Context Menu Methods =====\n\n /**\n * Create context menu element\n */\n private createContextMenu(): HTMLDivElement {\n const menu = document.createElement(\"div\");\n menu.className = \"layer-control-context-menu\";\n menu.style.display = \"none\";\n\n // Rename\n const renameItem = this.createContextMenuItem(\"Rename\", \"✏️\", () => {\n if (this.state.contextMenu.targetLayerId) {\n this.startRenaming(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n });\n\n // Zoom to layer\n const zoomItem = this.createContextMenuItem(\"Zoom to Layer\", \"🔍\", () => {\n if (this.state.contextMenu.targetLayerId) {\n this.zoomToLayer(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n });\n\n // Separator\n const sep1 = document.createElement(\"div\");\n sep1.className = \"context-menu-separator\";\n\n // Move up\n const moveUpItem = this.createContextMenuItem(\"Move Up\", \"↑\", () => {\n if (this.state.contextMenu.targetLayerId) {\n this.moveLayerUp(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n });\n\n // Move to top\n const moveTopItem = this.createContextMenuItem(\"Move to Top\", \"⤒\", () => {\n if (this.state.contextMenu.targetLayerId) {\n this.moveLayerToTop(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n });\n\n // Move down\n const moveDownItem = this.createContextMenuItem(\"Move Down\", \"↓\", () => {\n if (this.state.contextMenu.targetLayerId) {\n this.moveLayerDown(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n });\n\n // Move to bottom\n const moveBottomItem = this.createContextMenuItem(\n \"Move to Bottom\",\n \"⤓\",\n () => {\n if (this.state.contextMenu.targetLayerId) {\n this.moveLayerToBottom(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n },\n );\n\n // Separator\n const sep2 = document.createElement(\"div\");\n sep2.className = \"context-menu-separator\";\n\n // Remove layer\n const removeItem = this.createContextMenuItem(\n \"Remove Layer\",\n \"🗑️\",\n () => {\n if (this.state.contextMenu.targetLayerId) {\n this.removeLayer(this.state.contextMenu.targetLayerId);\n }\n this.hideContextMenu();\n },\n true,\n );\n\n menu.appendChild(renameItem);\n menu.appendChild(zoomItem);\n menu.appendChild(sep1);\n menu.appendChild(moveUpItem);\n menu.appendChild(moveTopItem);\n menu.appendChild(moveDownItem);\n menu.appendChild(moveBottomItem);\n menu.appendChild(sep2);\n menu.appendChild(removeItem);\n\n return menu;\n }\n\n /**\n * Create a context menu item\n */\n private createContextMenuItem(\n label: string,\n icon: string,\n onClick: () => void,\n isDanger = false,\n ): HTMLDivElement {\n const item = document.createElement(\"div\");\n item.className =\n \"context-menu-item\" + (isDanger ? \" context-menu-item-danger\" : \"\");\n\n const iconEl = document.createElement(\"span\");\n iconEl.className = \"context-menu-item-icon\";\n iconEl.textContent = icon;\n\n const labelEl = document.createElement(\"span\");\n labelEl.className = \"context-menu-item-label\";\n labelEl.textContent = label;\n\n item.appendChild(iconEl);\n item.appendChild(labelEl);\n\n item.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n onClick();\n });\n\n return item;\n }\n\n /**\n * Show context menu at position\n */\n private showContextMenu(layerId: string, x: number, y: number): void {\n if (!this.contextMenuEl) return;\n\n // Update state\n this.state.contextMenu = {\n visible: true,\n targetLayerId: layerId,\n x,\n y,\n };\n\n // Position the menu relative to the map container\n const mapRect = this.mapContainer.getBoundingClientRect();\n let menuX = x - mapRect.left;\n let menuY = y - mapRect.top;\n\n // Show menu to get dimensions\n this.contextMenuEl.style.display = \"block\";\n\n // Adjust if menu would go off screen\n const menuRect = this.contextMenuEl.getBoundingClientRect();\n if (menuX + menuRect.width > mapRect.width) {\n menuX = mapRect.width - menuRect.width - 5;\n }\n if (menuY + menuRect.height > mapRect.height) {\n menuY = mapRect.height - menuRect.height - 5;\n }\n\n this.contextMenuEl.style.left = `${menuX}px`;\n this.contextMenuEl.style.top = `${menuY}px`;\n }\n\n /**\n * Hide context menu\n */\n private hideContextMenu(): void {\n if (!this.contextMenuEl) return;\n\n this.state.contextMenu = {\n visible: false,\n targetLayerId: null,\n x: 0,\n y: 0,\n };\n\n this.contextMenuEl.style.display = \"none\";\n }\n\n /**\n * Start renaming a layer\n */\n private startRenaming(layerId: string): void {\n const itemEl = this.panel.querySelector(`[data-layer-id=\"${layerId}\"]`);\n if (!itemEl) return;\n\n const nameEl = itemEl.querySelector(\".layer-control-name\");\n if (!nameEl) return;\n\n this.state.renamingLayerId = layerId;\n\n const currentName =\n this.state.customLayerNames.get(layerId) ||\n this.state.layerStates[layerId]?.name ||\n layerId;\n\n // Replace name span with input\n const input = document.createElement(\"input\");\n input.type = \"text\";\n input.className = \"layer-control-name-input\";\n input.value = currentName;\n\n const finishRename = () => {\n const newName = input.value.trim() || currentName;\n const oldName = currentName;\n\n if (newName !== oldName) {\n this.state.customLayerNames.set(layerId, newName);\n if (this.state.layerStates[layerId]) {\n this.state.layerStates[layerId].name = newName;\n }\n this.onLayerRename?.(layerId, oldName, newName);\n }\n\n // Restore name span\n const newNameEl = document.createElement(\"span\");\n newNameEl.className = \"layer-control-name\";\n newNameEl.textContent = newName;\n newNameEl.title = newName;\n input.replaceWith(newNameEl);\n\n this.state.renamingLayerId = null;\n };\n\n input.addEventListener(\"blur\", finishRename);\n input.addEventListener(\"keydown\", (e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n finishRename();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n // Restore original name\n const newNameEl = document.createElement(\"span\");\n newNameEl.className = \"layer-control-name\";\n newNameEl.textContent = currentName;\n newNameEl.title = currentName;\n input.replaceWith(newNameEl);\n this.state.renamingLayerId = null;\n }\n });\n\n nameEl.replaceWith(input);\n input.focus();\n input.select();\n }\n\n /**\n * Zoom to a layer's bounds\n */\n private zoomToLayer(layerId: string): void {\n // Check if it's a custom layer with getBounds support\n const layerState = this.state.layerStates[layerId];\n if (layerState?.isCustomLayer && this.customLayerRegistry) {\n const bounds = this.customLayerRegistry.getBounds(layerId);\n if (bounds) {\n this.map.fitBounds(bounds as [number, number, number, number], {\n padding: 50,\n });\n return;\n }\n }\n\n // For native MapLibre layers, try to get bounds from features\n const layer = this.map.getLayer(layerId);\n if (!layer) return;\n\n try {\n // First try querySourceFeatures for all features\n const sourceId = (layer as any).source;\n let features = sourceId ? this.map.querySourceFeatures(sourceId) : [];\n\n // If no source features, try rendered features\n if (features.length === 0) {\n features = this.map.queryRenderedFeatures({ layers: [layerId] });\n }\n\n if (features.length === 0) return;\n\n // Calculate bounds\n let minLng = Infinity,\n minLat = Infinity,\n maxLng = -Infinity,\n maxLat = -Infinity;\n\n features.forEach((feature) => {\n if (!feature.geometry) return;\n\n const processCoords = (coords: any) => {\n if (typeof coords[0] === \"number\") {\n const [lng, lat] = coords;\n minLng = Math.min(minLng, lng);\n minLat = Math.min(minLat, lat);\n maxLng = Math.max(maxLng, lng);\n maxLat = Math.max(maxLat, lat);\n } else {\n coords.forEach(processCoords);\n }\n };\n\n if (feature.geometry.type === \"Point\") {\n processCoords((feature.geometry as any).coordinates);\n } else if (\n feature.geometry.type === \"LineString\" ||\n feature.geometry.type === \"MultiPoint\"\n ) {\n (feature.geometry as any).coordinates.forEach(processCoords);\n } else if (\n feature.geometry.type === \"Polygon\" ||\n feature.geometry.type === \"MultiLineString\"\n ) {\n (feature.geometry as any).coordinates.forEach((ring: any) =>\n ring.forEach(processCoords),\n );\n } else if (feature.geometry.type === \"MultiPolygon\") {\n (feature.geometry as any).coordinates.forEach((polygon: any) =>\n polygon.forEach((ring: any) => ring.forEach(processCoords)),\n );\n }\n });\n\n if (\n minLng !== Infinity &&\n minLat !== Infinity &&\n maxLng !== -Infinity &&\n maxLat !== -Infinity\n ) {\n this.map.fitBounds(\n [\n [minLng, minLat],\n [maxLng, maxLat],\n ],\n { padding: 50 },\n );\n }\n } catch (error) {\n console.warn(`Failed to zoom to layer ${layerId}:`, error);\n }\n }\n\n /**\n * Get user layer IDs in current map order (top to bottom in UI = high z-index to low)\n * Includes both MapLibre layers and custom layers managed by adapters.\n */\n private getUserLayerIdsInMapOrder(): string[] {\n const style = this.map.getStyle();\n if (!style?.layers) return [];\n\n // Get map layers in their actual order (low index = rendered first/bottom)\n const mapLayerIds = style.layers.map((l) => l.id);\n const indexById = new Map(mapLayerIds.map((id, i) => [id, i]));\n\n // Filter to only user layers that are in our state\n const userLayerIds = Object.keys(this.state.layerStates).filter(\n (id) => id !== \"Background\",\n );\n const hint = this.layerOrderHint;\n if (hint) {\n const rank = new Map(hint.map((id, index) => [id, index]));\n const keyIndex = new Map(userLayerIds.map((id, index) => [id, index]));\n userLayerIds.sort(\n (a, b) =>\n (rank.get(a) ?? hint.length + keyIndex.get(a)!) -\n (rank.get(b) ?? hint.length + keyIndex.get(b)!),\n );\n }\n\n // Compute a representative z-position (map index) for every user layer so\n // that MapLibre layers and custom layers can be ordered together by their\n // actual stacking order. Custom layers (e.g. deck.gl / raster adapters)\n // often expose a logical ID that differs from the underlying style layer\n // IDs, so look those up through the adapter (getNativeLayerIds) and use the\n // top-most native layer's index.\n const resolvedIndexOf = (id: string): number | undefined => {\n const direct = indexById.get(id);\n if (direct !== undefined) return direct;\n\n const nativeIds = this.customLayerRegistry?.getNativeLayerIds(id);\n if (nativeIds && nativeIds.length > 0) {\n let best = -1;\n for (const nativeId of nativeIds) {\n const idx = indexById.get(nativeId);\n if (idx !== undefined && idx > best) best = idx;\n }\n if (best !== -1) return best;\n }\n return undefined;\n };\n\n // A custom layer with no native layer on the map yet (hidden or still\n // loading) keeps its slot in its adapter's list: it sits just above the\n // nearest resolved layer beneath it in that list, or just below the nearest\n // one above it. `offset` orders several unresolved layers sharing an\n // anchor. Adapter lists are read bottom-to-top (like style.layers) unless\n // their resolved layers show they run top-to-bottom. An adapter with no\n // resolved layer at all keeps its layers on top (Infinity), preserving\n // their relative insertion order.\n const anchors = new Map<string, { mapIndex: number; offset: number }>();\n for (const group of this.customLayerRegistry?.getLayerIdGroups() ?? []) {\n const resolved = group.map(resolvedIndexOf);\n const known = resolved.filter((idx): idx is number => idx !== undefined);\n if (known.length === 0) continue;\n const ids = known[0] > known[known.length - 1] ? [...group].reverse() : group;\n const indexes = ids === group ? resolved : [...resolved].reverse();\n ids.forEach((id, position) => {\n if (indexes[position] !== undefined) return;\n for (let below = position - 1; below >= 0; below--) {\n const idx = indexes[below];\n if (idx !== undefined) {\n anchors.set(id, { mapIndex: idx, offset: position - below });\n return;\n }\n }\n for (let above = position + 1; above < ids.length; above++) {\n const idx = indexes[above];\n if (idx !== undefined) {\n anchors.set(id, { mapIndex: idx, offset: position - above });\n return;\n }\n }\n });\n }\n\n const stackKeyOf = (id: string): { mapIndex: number; offset: number } => {\n const resolved = resolvedIndexOf(id);\n if (resolved !== undefined) return { mapIndex: resolved, offset: 0 };\n return anchors.get(id) ?? { mapIndex: Number.POSITIVE_INFINITY, offset: 0 };\n };\n\n // Sort by map index descending (high index = top of UI), then by offset\n // from an anchor, keeping the original insertion order as a stable\n // tiebreaker (notably for unresolved custom layers that all share an\n // Infinity index).\n return userLayerIds\n .map((id, insertionIndex) => ({\n id,\n insertionIndex,\n ...stackKeyOf(id),\n }))\n .sort((a, b) => {\n if (a.mapIndex !== b.mapIndex) return a.mapIndex > b.mapIndex ? -1 : 1;\n if (a.offset !== b.offset) return b.offset - a.offset;\n return a.insertionIndex - b.insertionIndex;\n })\n .map((entry) => entry.id);\n }\n\n /**\n * Check if a layer is a MapLibre layer (not a custom layer)\n */\n private isMapLibreLayer(layerId: string): boolean {\n return this.map.getLayer(layerId) !== undefined;\n }\n\n /**\n * Find the next MapLibre layer ID in a direction from a given index\n * @param layerIds Array of layer IDs\n * @param startIndex Index to start searching from\n * @param direction 1 for forward (toward bottom), -1 for backward (toward top)\n * @returns MapLibre layer ID or undefined if not found\n */\n private findNextMapLibreLayer(\n layerIds: string[],\n startIndex: number,\n direction: 1 | -1,\n ): string | undefined {\n for (\n let i = startIndex;\n direction === 1 ? i < layerIds.length : i >= 0;\n i += direction\n ) {\n if (this.isMapLibreLayer(layerIds[i])) {\n return layerIds[i];\n }\n }\n return undefined;\n }\n\n /**\n * Move a layer up in UI (higher rendering order = move to higher z-index)\n */\n private moveLayerUp(layerId: string): void {\n if (this.groupStates.size > 0) {\n this.moveLayerWithinGroup(layerId, \"up\");\n return;\n }\n\n const layerIds = this.getUserLayerIdsInMapOrder();\n const index = layerIds.indexOf(layerId);\n if (index <= 0) return; // Already at top or not found\n\n // Check if this is a custom layer\n const isCustom = this.state.layerStates[layerId]?.isCustomLayer;\n\n if (!isCustom && this.isMapLibreLayer(layerId)) {\n // For MapLibre layers, we need to move them in the map\n // UI: [0]=top, [1], [2], ... [n]=bottom\n // Map array: bottom to top (low index = low z-index)\n // moveLayer(id, beforeId) moves id to render BELOW beforeId\n\n try {\n // Find the MapLibre layer to move before (2 positions above if exists)\n // If moving to top, use undefined as beforeId\n const targetBeforeId =\n index >= 2\n ? this.findNextMapLibreLayer(layerIds, index - 2, -1)\n : undefined;\n this.map.moveLayer(layerId, targetBeforeId);\n } catch (e) {\n // Ignore errors\n }\n }\n\n // For custom layers, just update the internal order\n // Swap positions in the state\n const newLayerStates: { [key: string]: LayerState } = {};\n const orderedIds = [...layerIds];\n [orderedIds[index], orderedIds[index - 1]] = [\n orderedIds[index - 1],\n orderedIds[index],\n ];\n\n // Add Background first if it exists\n if (this.state.layerStates[\"Background\"]) {\n newLayerStates[\"Background\"] = this.state.layerStates[\"Background\"];\n }\n orderedIds.forEach((id) => {\n if (this.state.layerStates[id]) {\n newLayerStates[id] = this.state.layerStates[id];\n }\n });\n this.state.layerStates = newLayerStates;\n\n // Rebuild UI\n this.buildLayerItems();\n // Report the order the move asked for. The map order would not show it\n // for a custom layer: those are left to the adapter to restack, so the\n // map still has the old order at this point.\n this.onLayerReorder?.(orderedIds);\n }\n\n /**\n * Move a layer to the top (highest rendering order)\n */\n private moveLayerToTop(layerId: string): void {\n if (this.groupStates.size > 0) {\n this.moveLayerWithinGroup(layerId, \"top\");\n return;\n }\n\n const layerIds = this.getUserLayerIdsInMapOrder();\n const index = layerIds.indexOf(layerId);\n if (index <= 0) return; // Already at top or not found\n\n // Check if this is a custom layer\n const isCustom = this.state.layerStates[layerId]?.isCustomLayer;\n\n if (!isCustom && this.isMapLibreLayer(layerId)) {\n // Move in MapLibre - no beforeId means move to top (highest z-index)\n try {\n this.map.moveLayer(layerId);\n } catch (e) {\n // Ignore errors\n }\n }\n\n // Update internal order - move to front\n const newLayerStates: { [key: string]: LayerState } = {};\n const orderedIds = [...layerIds];\n orderedIds.splice(index, 1);\n orderedIds.unshift(layerId);\n\n // Add Background first if it exists\n if (this.state.layerStates[\"Background\"]) {\n newLayerStates[\"Background\"] = this.state.layerStates[\"Background\"];\n }\n orderedIds.forEach((id) => {\n if (this.state.layerStates[id]) {\n newLayerStates[id] = this.state.layerStates[id];\n }\n });\n this.state.layerStates = newLayerStates;\n\n // Rebuild UI\n this.buildLayerItems();\n // Report the order the move asked for. The map order would not show it\n // for a custom layer: those are left to the adapter to restack, so the\n // map still has the old order at this point.\n this.onLayerReorder?.(orderedIds);\n }\n\n /**\n * Move a layer down in UI (lower rendering order = move to lower z-index)\n */\n private moveLayerDown(layerId: string): void {\n if (this.groupStates.size > 0) {\n this.moveLayerWithinGroup(layerId, \"down\");\n return;\n }\n\n const layerIds = this.getUserLayerIdsInMapOrder();\n const index = layerIds.indexOf(layerId);\n if (index < 0 || index >= layerIds.length - 1) return; // Already at bottom or not found\n\n // Check if this is a custom layer\n const isCustom = this.state.layerStates[layerId]?.isCustomLayer;\n\n if (!isCustom && this.isMapLibreLayer(layerId)) {\n // The layer below in UI is at index + 1, which has lower z-index in map\n // To move our layer below it, we call moveLayer(layerId, belowLayerId)\n // This puts layerId just below belowLayerId in rendering order\n // Find the next MapLibre layer below\n const belowLayerId = this.findNextMapLibreLayer(layerIds, index + 1, 1);\n\n if (belowLayerId) {\n try {\n this.map.moveLayer(layerId, belowLayerId);\n } catch (e) {\n // Ignore errors\n }\n }\n }\n\n // Update internal order - swap positions\n const newLayerStates: { [key: string]: LayerState } = {};\n const orderedIds = [...layerIds];\n [orderedIds[index], orderedIds[index + 1]] = [\n orderedIds[index + 1],\n orderedIds[index],\n ];\n\n // Add Background first if it exists\n if (this.state.layerStates[\"Background\"]) {\n newLayerStates[\"Background\"] = this.state.layerStates[\"Background\"];\n }\n orderedIds.forEach((id) => {\n if (this.state.layerStates[id]) {\n newLayerStates[id] = this.state.layerStates[id];\n }\n });\n this.state.layerStates = newLayerStates;\n\n // Rebuild UI\n this.buildLayerItems();\n // Report the order the move asked for. The map order would not show it\n // for a custom layer: those are left to the adapter to restack, so the\n // map still has the old order at this point.\n this.onLayerReorder?.(orderedIds);\n }\n\n /**\n * Move a layer to the bottom (lowest rendering order among user layers)\n */\n private moveLayerToBottom(layerId: string): void {\n if (this.groupStates.size > 0) {\n this.moveLayerWithinGroup(layerId, \"bottom\");\n return;\n }\n\n const layerIds = this.getUserLayerIdsInMapOrder();\n if (layerIds.length <= 1) return;\n\n const index = layerIds.indexOf(layerId);\n if (index < 0 || index === layerIds.length - 1) return; // Not found or already at bottom\n\n // Check if this is a custom layer\n const isCustom = this.state.layerStates[layerId]?.isCustomLayer;\n\n if (!isCustom && this.isMapLibreLayer(layerId)) {\n // The bottom layer in UI has the lowest z-index among user layers\n // Find the bottom-most MapLibre layer\n const bottomLayerId = this.findNextMapLibreLayer(\n layerIds,\n layerIds.length - 1,\n -1,\n );\n\n if (bottomLayerId && bottomLayerId !== layerId) {\n try {\n // Move this layer to be just below the current bottom layer\n this.map.moveLayer(layerId, bottomLayerId);\n } catch (e) {\n // Ignore errors\n }\n }\n }\n\n // Update internal order - move to end\n const newLayerStates: { [key: string]: LayerState } = {};\n const orderedIds = [...layerIds];\n orderedIds.splice(index, 1);\n orderedIds.push(layerId);\n\n // Add Background first if it exists\n if (this.state.layerStates[\"Background\"]) {\n newLayerStates[\"Background\"] = this.state.layerStates[\"Background\"];\n }\n orderedIds.forEach((id) => {\n if (this.state.layerStates[id]) {\n newLayerStates[id] = this.state.layerStates[id];\n }\n });\n this.state.layerStates = newLayerStates;\n\n // Rebuild UI\n this.buildLayerItems();\n // Report the order the move asked for. The map order would not show it\n // for a custom layer: those are left to the adapter to restack, so the\n // map still has the old order at this point.\n this.onLayerReorder?.(orderedIds);\n }\n\n /**\n * Move a layer within its own group (or among the top-level rows), so the\n * context-menu moves never carry it out of its group. A nested group counts\n * as one block: moving up or down steps past the whole block.\n * @param layerId The layer ID\n * @param direction Where to move the layer within its group\n */\n private moveLayerWithinGroup(\n layerId: string,\n direction: \"up\" | \"down\" | \"top\" | \"bottom\",\n ): void {\n const order = this.getUserLayerIdsInMapOrder();\n const groupId = this.getLayerGroupIdOf(layerId);\n\n // Split the group's rows, top to bottom, into blocks: each direct layer is\n // a block of its own, and each nested group's layers form one block.\n const blocks: { key: string; ids: string[] }[] = [];\n for (const id of order) {\n const key = this.getChildKeyWithin(id, groupId);\n if (key === null) continue;\n const lastBlock = blocks[blocks.length - 1];\n if (lastBlock && lastBlock.key === key && key !== `layer:${id}`) {\n lastBlock.ids.push(id);\n } else {\n blocks.push({ key, ids: [id] });\n }\n }\n\n const position = blocks.findIndex((block) => block.key === `layer:${layerId}`);\n const last = blocks.length - 1;\n if (position < 0) return;\n if ((direction === \"up\" || direction === \"top\") && position === 0) return;\n if ((direction === \"down\" || direction === \"bottom\") && position === last) {\n return;\n }\n\n // Take the layer out and put it back just above (up/top) or just below\n // (down/bottom) the block it moves past.\n const above = direction === \"up\" || direction === \"top\";\n const block = {\n up: blocks[position - 1],\n top: blocks[0],\n down: blocks[position + 1],\n bottom: blocks[last],\n }[direction];\n const anchor = above ? block.ids[0] : block.ids[block.ids.length - 1];\n const next = order.filter((id) => id !== layerId);\n const anchorIndex = next.indexOf(anchor);\n next.splice(above ? anchorIndex : anchorIndex + 1, 0, layerId);\n\n const newLayerStates: { [key: string]: LayerState } = {};\n if (this.state.layerStates[\"Background\"]) {\n newLayerStates[\"Background\"] = this.state.layerStates[\"Background\"];\n }\n next.forEach((id) => {\n if (this.state.layerStates[id]) {\n newLayerStates[id] = this.state.layerStates[id];\n }\n });\n this.state.layerStates = newLayerStates;\n\n this.applyLayerOrderToMap(next);\n this.buildLayerItems();\n this.onLayerReorder?.(next);\n }\n\n /**\n * Identify which row of a group a layer falls under: the layer itself when\n * it belongs to the group directly, or the nested group that holds it.\n * @param layerId The layer ID\n * @param groupId The group, or undefined for the panel's top level\n * @returns `layer:<id>` or `group:<id>`, or null when the layer is not\n * inside the group at all\n */\n private getChildKeyWithin(\n layerId: string,\n groupId: string | undefined,\n ): string | null {\n let current = this.getLayerGroupIdOf(layerId);\n if (current === groupId) return `layer:${layerId}`;\n const visited = new Set<string>();\n while (current !== undefined && !visited.has(current)) {\n visited.add(current);\n const parentId = this.groupStates.get(current)?.parentId;\n const parent =\n parentId !== undefined && this.groupStates.has(parentId)\n ? parentId\n : undefined;\n if (parent === groupId) return `group:${current}`;\n current = parent;\n }\n return null;\n }\n\n /**\n * Show inline remove confirmation instead of browser confirm() dialog.\n * Works in Jupyter notebooks where native dialogs may not appear.\n */\n private showRemoveConfirmation(\n container: HTMLElement,\n onConfirm: () => void,\n ): void {\n // Remove any existing confirmation in this container\n const existing = container.querySelector(\".layer-control-remove-confirm\");\n if (existing) {\n existing.remove();\n }\n\n const confirmEl = document.createElement(\"div\");\n confirmEl.className = \"layer-control-remove-confirm\";\n\n const message = document.createElement(\"div\");\n message.className = \"layer-control-remove-confirm-message\";\n message.innerHTML = `\n <svg class=\"layer-control-remove-confirm-icon\" viewBox=\"0 0 20 20\" fill=\"currentColor\">\n <path fill-rule=\"evenodd\" d=\"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 5a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 5zm0 9a1 1 0 100-2 1 1 0 000 2z\" clip-rule=\"evenodd\"/>\n </svg>\n <span>Remove this layer?</span>\n `;\n\n const buttons = document.createElement(\"div\");\n buttons.className = \"layer-control-remove-confirm-buttons\";\n\n const cancelBtn = document.createElement(\"button\");\n cancelBtn.className =\n \"layer-control-remove-confirm-btn layer-control-remove-confirm-btn-cancel\";\n cancelBtn.textContent = \"Cancel\";\n cancelBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n confirmEl.remove();\n });\n\n const confirmBtn = document.createElement(\"button\");\n confirmBtn.className =\n \"layer-control-remove-confirm-btn layer-control-remove-confirm-btn-confirm\";\n confirmBtn.textContent = \"Remove\";\n confirmBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n confirmEl.remove();\n onConfirm();\n });\n\n buttons.appendChild(cancelBtn);\n buttons.appendChild(confirmBtn);\n\n confirmEl.appendChild(message);\n confirmEl.appendChild(buttons);\n\n container.appendChild(confirmEl);\n\n // Scroll the confirmation into view\n requestAnimationFrame(() => {\n confirmEl.scrollIntoView({ behavior: \"smooth\", block: \"nearest\" });\n });\n }\n\n /**\n * Remove a layer from the map\n */\n private removeLayer(layerId: string): void {\n // Prevent checkForNewLayers() from running during removal\n // (removing a layer triggers styledata events that could cause race conditions)\n this.state.isStyleOperationInProgress = true;\n\n const layerState = this.state.layerStates[layerId];\n\n // Handle custom layer removal\n if (layerState?.isCustomLayer && this.customLayerRegistry) {\n // Track this ID so checkForNewLayers() won't re-add it\n this.removedCustomLayerIds.add(layerId);\n\n // Hide the layer immediately as a visual fallback\n this.customLayerRegistry.setVisibility(layerId, false);\n\n // Let the adapter perform its own cleanup\n this.customLayerRegistry.removeLayer(layerId);\n }\n\n // Remove native MapLibre layer from the map\n try {\n const layer = this.map.getLayer(layerId);\n if (layer) {\n const sourceId = (layer as any).source;\n this.map.removeLayer(layerId);\n\n // Check if source is still used by other layers\n if (sourceId) {\n const style = this.map.getStyle();\n const sourceStillUsed = style?.layers?.some(\n (l) => (l as any).source === sourceId,\n );\n if (!sourceStillUsed) {\n try {\n this.map.removeSource(sourceId);\n } catch (e) {\n // Source might not exist or be in use\n }\n }\n }\n }\n } catch (error) {\n console.warn(`Failed to remove layer ${layerId}:`, error);\n }\n\n // Remove from state\n delete this.state.layerStates[layerId];\n this.state.customLayerNames.delete(layerId);\n\n // Remove from UI\n const itemEl = this.panel.querySelector(`[data-layer-id=\"${layerId}\"]`);\n if (itemEl) {\n itemEl.remove();\n }\n this.pruneEmptyGroups();\n\n // Call callback\n this.onLayerRemove?.(layerId);\n\n // Clear flag after style events have settled\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n }\n\n // ===== Drag and Drop Methods =====\n\n /**\n * Create drag handle element\n */\n private createDragHandle(layerId: string): HTMLDivElement {\n const handle = document.createElement(\"div\");\n handle.className = \"layer-control-drag-handle\";\n handle.innerHTML = `<svg viewBox=\"0 0 16 16\" fill=\"currentColor\">\n <circle cx=\"5\" cy=\"3\" r=\"1.5\"/>\n <circle cx=\"11\" cy=\"3\" r=\"1.5\"/>\n <circle cx=\"5\" cy=\"8\" r=\"1.5\"/>\n <circle cx=\"11\" cy=\"8\" r=\"1.5\"/>\n <circle cx=\"5\" cy=\"13\" r=\"1.5\"/>\n <circle cx=\"11\" cy=\"13\" r=\"1.5\"/>\n </svg>`;\n handle.title = \"Drag to reorder\";\n\n // Pointer events for dragging\n handle.addEventListener(\"pointerdown\", (e) => {\n e.preventDefault();\n e.stopPropagation();\n this.startDrag(layerId, e);\n });\n\n return handle;\n }\n\n /**\n * Create a disabled drag handle for alignment (used for Background layer)\n */\n private createDisabledDragHandle(): HTMLDivElement {\n const handle = document.createElement(\"div\");\n handle.className =\n \"layer-control-drag-handle layer-control-drag-handle-disabled\";\n handle.innerHTML = `<svg viewBox=\"0 0 16 16\" fill=\"currentColor\">\n <circle cx=\"5\" cy=\"3\" r=\"1.5\"/>\n <circle cx=\"11\" cy=\"3\" r=\"1.5\"/>\n <circle cx=\"5\" cy=\"8\" r=\"1.5\"/>\n <circle cx=\"11\" cy=\"8\" r=\"1.5\"/>\n <circle cx=\"5\" cy=\"13\" r=\"1.5\"/>\n <circle cx=\"11\" cy=\"13\" r=\"1.5\"/>\n </svg>`;\n return handle;\n }\n\n /**\n * Start dragging a layer\n */\n private startDrag(layerId: string, e: PointerEvent): void {\n const itemEl = this.panel.querySelector(\n `[data-layer-id=\"${layerId}\"]`,\n ) as HTMLElement;\n if (!itemEl) return;\n\n // Get item rect before any modifications\n const rect = itemEl.getBoundingClientRect();\n\n // Set up drag state\n this.state.drag = {\n active: true,\n layerId,\n startY: e.clientY,\n currentY: e.clientY,\n placeholder: null,\n draggedElement: null,\n };\n\n // Add dragging class to panel\n this.panel.classList.add(\"dragging-active\");\n\n // Hide original first (before creating clone to avoid visual jump)\n itemEl.classList.add(\"dragging\");\n\n // Create placeholder at original position\n const placeholder = document.createElement(\"div\");\n placeholder.className = \"layer-control-drop-placeholder\";\n placeholder.style.height = `${rect.height}px`;\n itemEl.parentNode?.insertBefore(placeholder, itemEl);\n this.state.drag.placeholder = placeholder;\n\n // Create floating clone\n const clone = itemEl.cloneNode(true) as HTMLElement;\n clone.classList.remove(\"dragging\");\n clone.className = \"layer-control-item layer-control-item-dragging\";\n clone.style.width = `${rect.width}px`;\n clone.style.left = `${rect.left}px`;\n clone.style.top = `${rect.top}px`;\n document.body.appendChild(clone);\n this.state.drag.draggedElement = clone;\n\n // Set up move and end handlers on document\n const onMove = (moveE: PointerEvent) => this.onDragMove(moveE);\n const onEnd = (endE: PointerEvent) => {\n document.removeEventListener(\"pointermove\", onMove);\n document.removeEventListener(\"pointerup\", onEnd);\n document.removeEventListener(\"pointercancel\", onEnd);\n this.endDrag(endE);\n };\n\n document.addEventListener(\"pointermove\", onMove);\n document.addEventListener(\"pointerup\", onEnd);\n document.addEventListener(\"pointercancel\", onEnd);\n }\n\n /**\n * Handle drag move\n */\n private onDragMove(e: PointerEvent): void {\n if (!this.state.drag.active || !this.state.drag.draggedElement) return;\n\n const placeholder = this.state.drag.placeholder;\n if (!placeholder) return;\n\n // Move the floating element\n const deltaY = e.clientY - this.state.drag.startY;\n const clone = this.state.drag.draggedElement;\n const currentTop = parseFloat(clone.style.top) || 0;\n clone.style.top = `${currentTop + deltaY}px`;\n this.state.drag.startY = e.clientY;\n this.state.drag.currentY = e.clientY;\n\n // Get the rows the placeholder may move among: the dragged layer's own\n // siblings (they share the placeholder's parent element), whether layers\n // or nested groups, except the dragged item itself and Background. A drag\n // therefore never carries a layer into or out of a group; dropping on a\n // nested group places the layer above or below that whole group.\n const scope = placeholder.parentElement;\n const items = Array.from(scope?.children ?? []).filter(\n (item) =>\n (item.classList.contains(\"layer-control-item\") ||\n item.classList.contains(\"layer-control-group\")) &&\n !item.classList.contains(\"dragging\") &&\n (item as HTMLElement).dataset.layerId !== \"Background\",\n ) as HTMLElement[];\n\n // Find which item we're hovering over\n for (const item of items) {\n const itemRect = item.getBoundingClientRect();\n\n // Check if cursor is within this item's vertical bounds\n if (e.clientY >= itemRect.top && e.clientY <= itemRect.bottom) {\n const itemMiddle = itemRect.top + itemRect.height / 2;\n\n if (e.clientY < itemMiddle) {\n // Insert placeholder before this item (if not already there)\n if (placeholder.nextSibling !== item) {\n item.parentNode?.insertBefore(placeholder, item);\n }\n } else {\n // Insert placeholder after this item (if not already there)\n if (placeholder.previousSibling !== item) {\n item.parentNode?.insertBefore(placeholder, item.nextSibling);\n }\n }\n break;\n }\n }\n }\n\n /**\n * End dragging\n */\n private endDrag(_e: PointerEvent): void {\n if (!this.state.drag.active) return;\n\n const layerId = this.state.drag.layerId;\n const placeholder = this.state.drag.placeholder;\n\n // Get the original item\n const itemEl = this.panel.querySelector(\n `[data-layer-id=\"${layerId}\"]`,\n ) as HTMLElement;\n\n if (itemEl && placeholder) {\n // Move item to placeholder position\n placeholder.parentNode?.insertBefore(itemEl, placeholder);\n itemEl.classList.remove(\"dragging\");\n }\n\n // Clean up\n this.cleanupDragState();\n\n // Update map layer order based on UI order\n this.applyUIOrderToMap();\n }\n\n /**\n * Clean up drag state\n */\n private cleanupDragState(): void {\n // Remove floating element\n if (this.state.drag.draggedElement) {\n this.state.drag.draggedElement.remove();\n }\n\n // Remove placeholder\n if (this.state.drag.placeholder) {\n this.state.drag.placeholder.remove();\n }\n\n // Remove dragging class from panel\n this.panel.classList.remove(\"dragging-active\");\n\n // Remove dragging class from any items\n this.panel\n .querySelectorAll(\".layer-control-item.dragging\")\n .forEach((el) => {\n el.classList.remove(\"dragging\");\n });\n\n // Reset drag state\n this.state.drag = {\n active: false,\n layerId: null,\n startY: 0,\n currentY: 0,\n placeholder: null,\n draggedElement: null,\n };\n }\n\n /**\n * Apply UI order to map layers\n */\n private applyUIOrderToMap(): void {\n // Get layer items in current UI order\n const items = this.panel.querySelectorAll(\".layer-control-item\");\n const uiLayerIds: string[] = [];\n\n items.forEach((item) => {\n const layerId = (item as HTMLElement).dataset.layerId;\n if (layerId && layerId !== \"Background\") {\n uiLayerIds.push(layerId);\n }\n });\n\n this.applyLayerOrderToMap(uiLayerIds);\n\n // Call callback\n this.onLayerReorder?.(uiLayerIds);\n }\n\n /**\n * Restack the map's MapLibre layers to match a panel order.\n * @param uiLayerIds User layer IDs top-to-bottom, as the panel lists them\n */\n private applyLayerOrderToMap(uiLayerIds: string[]): void {\n // Set flag to prevent checkForNewLayers from running during reordering\n // This prevents custom layers from being incorrectly deleted due to race conditions\n this.state.isStyleOperationInProgress = true;\n\n // uiLayerIds is the panel order top-to-bottom, where the top row is the\n // top-most layer (highest z-index, rendered last / on top). MapLibre's\n // moveLayer(id, beforeId) places `id` visually beneath `beforeId`, so\n // iterating from the top of the panel downward and anchoring each layer\n // beneath the previous one reproduces that stacking on the map: the first\n // item goes to the top, each subsequent item just below it.\n const style = this.map.getStyle();\n const mapLibreLayerIds = new Set(style?.layers?.map((l) => l.id) || []);\n\n for (let i = 0; i < uiLayerIds.length; i++) {\n const layerId = uiLayerIds[i];\n\n // Skip custom (non-MapLibre) layers; they are managed by their adapters.\n if (!mapLibreLayerIds.has(layerId)) {\n continue;\n }\n\n // Anchor beneath the nearest higher (already-placed) MapLibre layer,\n // skipping any custom layers between them.\n let beforeId: string | undefined = undefined;\n for (let j = i - 1; j >= 0; j--) {\n if (mapLibreLayerIds.has(uiLayerIds[j])) {\n beforeId = uiLayerIds[j];\n break;\n }\n }\n\n try {\n this.map.moveLayer(layerId, beforeId);\n } catch (e) {\n // Ignore errors\n }\n }\n\n // Clear flag after styledata events have settled\n // The 200ms delay accounts for the 100ms timeout in the styledata event handler\n setTimeout(() => {\n this.state.isStyleOperationInProgress = false;\n }, 200);\n }\n}\n"],"names":["opacity","l","r","t","n","e","f","d","c","g","extend","namesPlugin","clamp","v","colord","y","p","color","svgMarkup","symbolContainer","layerList","editor","_a","event","x","block","j"],"mappings":";;;AAMO,MAAM,oBAAoB;AAAA,EAA1B;AACG,wDAAgD,IAAA;AAChD,2CAA6E,CAAA;AAC7E,6DAA6C,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrD,SAAS,SAAmC;AAC1C,SAAK,SAAS,IAAI,QAAQ,MAAM,OAAO;AAGvC,QAAI,QAAQ,eAAe;AACzB,YAAM,cAAc,QAAQ,cAAc,CAAC,OAAO,YAAY;AAC5D,aAAK,aAAa,OAAO,OAAO;AAAA,MAClC,CAAC;AACD,WAAK,cAAc,IAAI,QAAQ,MAAM,WAAW;AAAA,IAClD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAW,MAAoB;AAE7B,UAAM,cAAc,KAAK,cAAc,IAAI,IAAI;AAC/C,QAAI,aAAa;AACf,kBAAA;AACA,WAAK,cAAc,OAAO,IAAI;AAAA,IAChC;AACA,SAAK,SAAS,OAAO,IAAI;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAA2B;AACzB,UAAM,MAAgB,CAAA;AACtB,SAAK,SAAS,QAAQ,CAAA,YA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