@aceshooting/lyra-ui 30.9.0 → 31.1.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/CHANGELOG.md +361 -335
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/autoloader-cdn.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +2 -2
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +26 -11
- package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
- package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +8 -4
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/document-library/document-library-cursor.js +1 -0
- package/dist/components/data/document-library/document-library-types.d.ts +20 -0
- package/dist/components/data/document-library/document-library.class.d.ts +37 -26
- package/dist/components/data/document-library/document-library.class.js +20 -11
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +3 -3
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
- package/dist/components/layout/segmented/segmented.class.js +34 -24
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map-canvas-target.js +1 -0
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +15 -6
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
- package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
- package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
- package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
- package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +9 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-order.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/runtime-diagnostics.js +1 -0
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-cursor-controller.js +1 -0
- package/dist/internal/source-cursor-projection.js +1 -0
- package/dist/internal/source-page-scope.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/utilities/overlay-manager.d.ts +2 -0
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-budget-meter.md +31 -0
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +26 -9
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +51 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-map.md +33 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-message-feedback.md +38 -3
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +6 -3
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +4 -1
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +46 -4
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +266 -117
- package/locales.json +1 -1
- package/package.json +22 -21
- package/registrations.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{MapPaintBatch}from"./map-paint-batch.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{snapshotMapStyle}from"./map-style-input.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{getInheritedPropertyDescriptor,getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{litDevWarnings}from"../../../internal/dev-warning.js";import{chevronIcon}from"../../../internal/icons.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{DEFAULT_CANVAS_COLOR,resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteDuration,finiteRange}from"../../../internal/numbers.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{admitMapViewpoint}from"../../../internal/map-camera-session-data.js";import{registerMapCameraSession}from"../../../internal/map-camera-session.js";import{createMapSceneSessionFacade,registerMapSceneSession}from"../../../internal/map-scene-session.js";import{registerMapCustomLayers}from"../../../internal/map-custom-layer-attachment.js";import{createMapSceneOwner}from"./map-scene-owner.js";import{countSceneMembers,summarizeSceneRender}from"./map-scene-status.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{notifyMapCanvasReady}from"../../../internal/map-canvas-ready.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{tag}from"../../../internal/prefix.js";import{loadMapControl,loadMaplibre,loadModularMap}from"./map-loader.js";import{styles}from"./map.styles.js";import{mapLayerHittable,queryMapHit}from"./map-hit-test.js";import{flattenedParentElement}from"../../../internal/composed-tree.js";import{syncMapControlRows}from"./map-control-chrome.js";import{MapFeatureStateRouter}from"./map-feature-state-router.js";const DRAW_MODE=literalSetConverter(["none","line","polygon"],"none"),HASH_FORMAT=literalSetConverter(["named","unnamed"],"named"),MAP_CONFIGURATION_MESSAGE={mapHashConflict:"mapHashConflict",mapHashInvalid:"mapHashInvalid",mapControlUnavailable:"mapControlUnavailable",mapGeolocatePermissionDenied:"mapGeolocatePermissionDenied",mapGeolocatePositionUnavailable:"mapGeolocatePositionUnavailable",mapGeolocateTimeout:"mapGeolocateTimeout",mapGeolocateError:"mapGeolocateError",mapGeolocateOutOfBounds:"mapGeolocateOutOfBounds"},MAP_SCALE_UNIT_MESSAGE={mapScaleFeet:"mapScaleFeet",mapScaleMeters:"mapScaleMeters",mapScaleKilometers:"mapScaleKilometers",mapScaleMiles:"mapScaleMiles",mapScaleNauticalMiles:"mapScaleNauticalMiles"},MAP_DRAWING_MESSAGE={mapDrawingUnavailable:"mapDrawingUnavailable",mapDrawingInvalidCoordinate:"mapDrawingInvalidCoordinate",mapDrawingDuplicateVertex:"mapDrawingDuplicateVertex",mapDrawingVertexLimit:"mapDrawingVertexLimit",mapDrawingTooFewVertices:"mapDrawingTooFewVertices",mapDrawingInvalidGeometry:"mapDrawingInvalidGeometry"},NO_DRAWING_WORK=Promise.resolve(),NO_OWNED_FEATURES=Object.freeze({overlays:Object.freeze({sources:Object.freeze([]),layers:Object.freeze([])}),images:Object.freeze([]),styleOverrides:Object.freeze([])});function ownedFeaturesRequested(overlays,images,styleOverrides){try{const empty=value=>Array.isArray(value)&&Object.getPrototypeOf(value)===Array.prototype&&readOwnArrayLength(value)===0;return!(isPlainDataRecord(overlays)&&Object.getPrototypeOf(overlays)===Object.prototype&&Reflect.ownKeys(overlays).length===0&&empty(images)&&empty(styleOverrides))}catch{return!0}}import{MapCursorOwner}from"./map-cursor.js";import{mapCoordinates,mapOwnValue,renderedSizeKey}from"./map-readers.js";import{projectMapInteractionOptions,projectMapBasemapInteractions,expandMapStyleLayerTargets}from"./map-interaction-options.js";import{MAP_HASH_UNNAMED}from"./map-hash-option.js";import{normalizeMapControlOptions}from"./map-control-options.js";import{MapEngineEvents}from"./map-engine-events.js";import{MapReadiness}from"./map-readiness.js";import{MapSceneConfigurationController}from"./map-scene-configuration-controller.js";import{admitMapTerrain,normalizeMapProjection}from"./map-scene-configuration.js";import{MapControlsReadiness}from"./map-controls-readiness.js";import{LyraMapImageExportError}from"./map-image-export-error.js";import{loadMapAnchorRuntime,loadMapControlRuntime,loadMapDrawingRuntime,loadMapFeatureStateRuntime,loadMapHashRuntime,loadMapImageExportRuntime,loadMapOwnedFeatureRuntime,loadMapSceneRenderRuntime,loadMapSceneBridge}from"./map-feature-loader.js";import{LyraMapImageExportError as LyraMapImageExportError2}from"./map-image-export-error.js";import{createMapConstructionScheduler}from"./map-construction-scheduler.js";import{projectMapDataLayerModel,projectMapRowPlacement,projectMapLabelOptions,buildMapLabelLayer,buildMapExternalLayers}from"./map-data-layer-model.js";import{emptyExtent,extendExtent,extendExtentWithGeoJson,extentToBounds,normalizeCameraOptions}from"./map-camera.js";import{LYRA_MAP_EMPTY_STYLE}from"./map-empty-style.js";import{projectGeoJson,projectAdmittedGeoJson,buildProjectedGeoJsonPropertyDiff}from"./map-geojson-diff.js";import{buildGeoJsonPropertyDiff}from"./map-geojson-diff.js";import{clusterColorExpression,heatmapColorExpression,heatmapWeightExpression,heatmapZoomValue,lineColorExpression,mutedCategoryOpacityExpression,pointColorExpression,pointRadiusExpression,stepExpression}from"./map-data-layers.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_mapActivate,LYRA_DEFAULT_mapCancelDrawing,LYRA_DEFAULT_mapCancelPick,LYRA_DEFAULT_mapCompleteDrawing,LYRA_DEFAULT_mapControlUnavailable,LYRA_DEFAULT_mapDrawAtCenter,LYRA_DEFAULT_mapDrawingArea,LYRA_DEFAULT_mapDrawingControls,LYRA_DEFAULT_mapDrawingDuplicateVertex,LYRA_DEFAULT_mapDrawingEditInstructions,LYRA_DEFAULT_mapDrawingInvalidCoordinate,LYRA_DEFAULT_mapDrawingInvalidGeometry,LYRA_DEFAULT_mapDrawingLength,LYRA_DEFAULT_mapDrawingTooFewVertices,LYRA_DEFAULT_mapDrawingUnavailable,LYRA_DEFAULT_mapDrawingVertex,LYRA_DEFAULT_mapDrawingVertexLimit,LYRA_DEFAULT_mapDrawingVertices,LYRA_DEFAULT_mapExportUnavailable,LYRA_DEFAULT_mapFeatureStateUnavailable,LYRA_DEFAULT_mapFeedback,LYRA_DEFAULT_mapGeolocateError,LYRA_DEFAULT_mapGeolocateFindLocation,LYRA_DEFAULT_mapGeolocateOutOfBounds,LYRA_DEFAULT_mapGeolocatePermissionDenied,LYRA_DEFAULT_mapGeolocatePositionUnavailable,LYRA_DEFAULT_mapGeolocateTimeout,LYRA_DEFAULT_mapGeolocateUnavailable,LYRA_DEFAULT_mapGlobe,LYRA_DEFAULT_mapHashConflict,LYRA_DEFAULT_mapHashInvalid,LYRA_DEFAULT_mapInitializationFailed,LYRA_DEFAULT_mapLegend,LYRA_DEFAULT_mapMarker,LYRA_DEFAULT_mapMissingLibrary,LYRA_DEFAULT_mapPickAtCenter,LYRA_DEFAULT_mapResetNorth,LYRA_DEFAULT_mapScaleFeet,LYRA_DEFAULT_mapScaleKilometers,LYRA_DEFAULT_mapScaleMeters,LYRA_DEFAULT_mapScaleMiles,LYRA_DEFAULT_mapScaleNauticalMiles,LYRA_DEFAULT_mapScene,LYRA_DEFAULT_mapSceneArc,LYRA_DEFAULT_mapSceneEmpty,LYRA_DEFAULT_mapSceneHide,LYRA_DEFAULT_mapSceneInvalid,LYRA_DEFAULT_mapSceneLimit,LYRA_DEFAULT_mapSceneMarker,LYRA_DEFAULT_mapSceneModel,LYRA_DEFAULT_mapSceneNext,LYRA_DEFAULT_mapScenePage,LYRA_DEFAULT_mapScenePartial,LYRA_DEFAULT_mapScenePath,LYRA_DEFAULT_mapScenePrevious,LYRA_DEFAULT_mapSceneShow,LYRA_DEFAULT_mapSceneUnavailable,LYRA_DEFAULT_mapSquareKilometers,LYRA_DEFAULT_mapSquareMeters,LYRA_DEFAULT_mapStyleRequired,LYRA_DEFAULT_mapTerrain,LYRA_DEFAULT_mapToggleAttribution,LYRA_DEFAULT_mapUndoDrawing,LYRA_DEFAULT_mapWebglUnavailable}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_close,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_duration,LYRA_DEFAULT_items,LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_model,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationSummary,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";function supportsWebGL2(host){try{const context=host.ownerDocument.createElement("canvas").getContext("webgl2");if(!context)return!1;try{context.getExtension("WEBGL_lose_context")?.loseContext()}catch{}return!0}catch{return!1}}const MAP_ENGINE=literalSetConverter(["modular","maplibre"],"modular");function hasMapStyle(style){return typeof style=="string"?style.trim().length>0:style!==void 0}const LEGEND_CONTROL_ROLE=literalSetConverter(["button","checkbox"],"button"),MAX_LEGEND_GRADIENT_TICKS=16,EMPTY_LEGEND_GRADIENT_TICKS=Object.freeze([]);function normalizeMapLegendGradientTicks(value){try{const scanCount=boundedOwnArrayLength(value,MAX_LEGEND_GRADIENT_TICKS*4);if(scanCount===void 0)return EMPTY_LEGEND_GRADIENT_TICKS;const byValue=new Map;for(let index=0;index<scanCount&&byValue.size<MAX_LEGEND_GRADIENT_TICKS;index+=1){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(descriptor))continue;const entry=descriptor.value;let tickValue=entry,label;isRuntimeRecord(entry)&&(tickValue=optionalDescriptorValue(getOwnDataDescriptor(entry,"value")),label=optionalDescriptorValue(getOwnDataDescriptor(entry,"label"))),!(typeof tickValue!="number"||!Number.isFinite(tickValue)||byValue.has(tickValue))&&byValue.set(tickValue,Object.freeze(typeof label=="string"&&label.trim().length>0?{value:tickValue,label:boundedLegendText(label.trim(),64)}:{value:tickValue}))}return byValue.size===0?EMPTY_LEGEND_GRADIENT_TICKS:Object.freeze([...byValue.values()].sort((a,b)=>a.value-b.value))}catch{return EMPTY_LEGEND_GRADIENT_TICKS}}const MAX_MAP_LEGEND_GRADIENT_STOPS=64;function isRuntimeArray(value){try{return Array.isArray(value)}catch{return!1}}function isRuntimeRecord(value){try{return value!==null&&typeof value=="object"&&!Array.isArray(value)}catch{return!1}}function boundedOwnArrayLength(value,limit){if(!isRuntimeArray(value))return;const descriptor=getOwnDataDescriptor(value,"length");if(!(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof descriptor.value!="number"||!Number.isSafeInteger(descriptor.value)||descriptor.value<0))return Math.min(descriptor.value,limit)}function isUnsafeDescriptor(descriptor){return descriptor===UNSAFE_OWN_DATA_DESCRIPTOR}function optionalDescriptorValue(descriptor){return descriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(descriptor)?void 0:descriptor.value}function normalizeMapLegendGradient(value){try{const scanCount=boundedOwnArrayLength(value,MAX_MAP_LEGEND_GRADIENT_STOPS);if(scanCount===void 0)return[];const usable=[];for(let index=0;index<scanCount;index+=1){const stopDescriptor=getOwnDataDescriptor(value,String(index));if(stopDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(stopDescriptor))continue;const stop=stopDescriptor.value,stopLength=boundedOwnArrayLength(stop,2);if(stopLength===void 0||stopLength<2)continue;const valueDescriptor=getOwnDataDescriptor(stop,"0"),colorDescriptor=getOwnDataDescriptor(stop,"1");if(valueDescriptor===MISSING_OWN_DATA_DESCRIPTOR||colorDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(valueDescriptor)||isUnsafeDescriptor(colorDescriptor)||typeof valueDescriptor.value!="number"||!Number.isFinite(valueDescriptor.value)||typeof colorDescriptor.value!="string")continue;const color=sanitizeCssColor(colorDescriptor.value);color&&usable.push([valueDescriptor.value,color])}return usable.length<2?[]:Object.freeze([...usable].sort((a,b)=>a[0]-b[0]))}catch{return[]}}const MAP_LEGEND_ITEM_LIMIT=100,MAP_LEGEND_SCAN_LIMIT=1e3,MAP_LEGEND_LABEL_LIMIT=256,MAP_LEGEND_TOTAL_LABEL_LIMIT=8192,MAP_LEGEND_COLOR_LIMIT=256,MAP_LEGEND_VALUE_LIMIT=256,MAP_LEGEND_PATTERNS=new Set(["solid","diagonal","dots","crosshatch"]),EMPTY_MAP_LEGEND=Object.freeze([]),EMPTY_MAP_LEGEND_PROJECTION=Object.freeze({inputCount:0,renderedCount:0,omittedCount:0,truncatedLabelCount:0,truncated:!1});function boundedLegendText(value,limit){return value.length<=limit?value:`${value.slice(0,Math.max(0,limit-1))}…`}function normalizeMapLegend(value){let input;try{input=Array.isArray(value)?value:[]}catch{input=[]}let inputCount=0;try{inputCount=Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,input.length))}catch{inputCount=0}const entries=[];let labelCharacters=0,truncatedLabelCount=0;const scanCount=Math.min(inputCount,MAP_LEGEND_SCAN_LIMIT);for(let index=0;index<scanCount&&entries.length<MAP_LEGEND_ITEM_LIMIT;index++)try{const candidate=input[index];if(!candidate||typeof candidate!="object")continue;const rawColor=candidate.color,rawLabel=candidate.label,rawPattern=candidate.pattern;if(typeof rawColor!="string"||typeof rawLabel!="string"||typeof rawPattern!="string"||!MAP_LEGEND_PATTERNS.has(rawPattern))continue;const remaining=MAP_LEGEND_TOTAL_LABEL_LIMIT-labelCharacters;if(remaining<=0)break;const labelLimit=Math.min(MAP_LEGEND_LABEL_LIMIT,remaining),label=boundedLegendText(rawLabel,labelLimit);if(!label.trim())continue;rawLabel.length>labelLimit&&truncatedLabelCount++,labelCharacters+=label.length;const rawValue=candidate.value,trimmedValue=typeof rawValue=="string"?rawValue.trim():"",value2=trimmedValue?trimmedValue.slice(0,MAP_LEGEND_VALUE_LIMIT):void 0,rawGroup=candidate.group,trimmedGroup=typeof rawGroup=="string"?rawGroup.trim():"",group=trimmedGroup?boundedLegendText(trimmedGroup,MAP_LEGEND_LABEL_LIMIT):void 0,rawIcon=candidate.icon,icon=isRuntimeRecord(rawIcon)?projectIconPaint(rawIcon):void 0;entries.push(Object.freeze({color:rawColor.slice(0,MAP_LEGEND_COLOR_LIMIT),label,pattern:rawPattern,...value2?{value:value2}:{},...group?{group}:{},...icon?{icon}:{}}))}catch{}const frozenEntries=entries.length?Object.freeze(entries):EMPTY_MAP_LEGEND,omittedCount=Math.max(0,inputCount-frozenEntries.length),projection=Object.freeze({inputCount,renderedCount:frozenEntries.length,omittedCount,truncatedLabelCount,truncated:omittedCount>0||truncatedLabelCount>0});return{entries:frozenEntries,projection,grouped:frozenEntries.some(entry=>entry.group!==void 0)}}const EMPTY_HIDDEN_CATEGORIES=Object.freeze([]);function normalizeMapHiddenCategories(value){let input,length=0;try{input=Array.isArray(value)?value:[],length=Math.max(0,Math.min(MAP_LEGEND_SCAN_LIMIT,input.length))}catch{return EMPTY_HIDDEN_CATEGORIES}const keys=[];for(let index=0;index<length&&keys.length<MAP_LEGEND_ITEM_LIMIT;index++)try{const candidate=input[index];if(typeof candidate!="string")continue;const key=candidate.trim().slice(0,MAP_LEGEND_VALUE_LIMIT);if(!key||keys.includes(key))continue;keys.push(key)}catch{}return keys.length?Object.freeze(keys):EMPTY_HIDDEN_CATEGORIES}function renderLegendIcon(icon){const[x,y,width,height]=icon.viewBox??DEFAULT_ICON_VIEW_BOX,mode=icon.mode??"fill";return html`<svg
|
|
1
|
+
import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-canvas-target.js";import{MapPaintBatch}from"./map-paint-batch.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{snapshotMapStyle}from"./map-style-input.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{getInheritedPropertyDescriptor,getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{litDevWarnings}from"../../../internal/dev-warning.js";import{chevronIcon}from"../../../internal/icons.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{DEFAULT_CANVAS_COLOR,resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteDuration,finiteRange}from"../../../internal/numbers.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{admitMapViewpoint}from"../../../internal/map-camera-session-data.js";import{registerMapCameraSession}from"../../../internal/map-camera-session.js";import{createMapSceneSessionFacade,registerMapSceneSession}from"../../../internal/map-scene-session.js";import{registerMapCustomLayers}from"../../../internal/map-custom-layer-attachment.js";import{createMapSceneOwner}from"./map-scene-owner.js";import{countSceneMembers,summarizeSceneRender}from"./map-scene-status.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{notifyMapCanvasReady}from"../../../internal/map-canvas-ready.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{tag}from"../../../internal/prefix.js";import{loadMapControl,loadMaplibre,loadModularMap}from"./map-loader.js";import{styles}from"./map.styles.js";import{mapLayerHittable,queryMapHit}from"./map-hit-test.js";import{flattenedParentElement}from"../../../internal/composed-tree.js";import{syncMapControlRows}from"./map-control-chrome.js";import{MapFeatureStateRouter}from"./map-feature-state-router.js";const DRAW_MODE=literalSetConverter(["none","line","polygon"],"none"),HASH_FORMAT=literalSetConverter(["named","unnamed"],"named"),MAP_CONFIGURATION_MESSAGE={mapHashConflict:"mapHashConflict",mapHashInvalid:"mapHashInvalid",mapControlUnavailable:"mapControlUnavailable",mapGeolocatePermissionDenied:"mapGeolocatePermissionDenied",mapGeolocatePositionUnavailable:"mapGeolocatePositionUnavailable",mapGeolocateTimeout:"mapGeolocateTimeout",mapGeolocateError:"mapGeolocateError",mapGeolocateOutOfBounds:"mapGeolocateOutOfBounds"},MAP_SCALE_UNIT_MESSAGE={mapScaleFeet:"mapScaleFeet",mapScaleMeters:"mapScaleMeters",mapScaleKilometers:"mapScaleKilometers",mapScaleMiles:"mapScaleMiles",mapScaleNauticalMiles:"mapScaleNauticalMiles"},MAP_DRAWING_MESSAGE={mapDrawingUnavailable:"mapDrawingUnavailable",mapDrawingInvalidCoordinate:"mapDrawingInvalidCoordinate",mapDrawingDuplicateVertex:"mapDrawingDuplicateVertex",mapDrawingVertexLimit:"mapDrawingVertexLimit",mapDrawingTooFewVertices:"mapDrawingTooFewVertices",mapDrawingInvalidGeometry:"mapDrawingInvalidGeometry"},NO_DRAWING_WORK=Promise.resolve(),NO_OWNED_FEATURES=Object.freeze({overlays:Object.freeze({sources:Object.freeze([]),layers:Object.freeze([])}),images:Object.freeze([]),styleOverrides:Object.freeze([])});function ownedFeaturesRequested(overlays,images,styleOverrides){try{const empty=value=>Array.isArray(value)&&Object.getPrototypeOf(value)===Array.prototype&&readOwnArrayLength(value)===0;return!(isPlainDataRecord(overlays)&&Object.getPrototypeOf(overlays)===Object.prototype&&Reflect.ownKeys(overlays).length===0&&empty(images)&&empty(styleOverrides))}catch{return!0}}import{MapCursorOwner}from"./map-cursor.js";import{mapCoordinates,mapOwnValue,renderedSizeKey}from"./map-readers.js";import{projectMapInteractionOptions,projectMapBasemapInteractions,expandMapStyleLayerTargets}from"./map-interaction-options.js";import{MAP_HASH_UNNAMED}from"./map-hash-option.js";import{normalizeMapControlOptions}from"./map-control-options.js";import{MapEngineEvents}from"./map-engine-events.js";import{MapReadiness}from"./map-readiness.js";import{MapSceneConfigurationController}from"./map-scene-configuration-controller.js";import{admitMapTerrain,normalizeMapProjection}from"./map-scene-configuration.js";import{MapControlsReadiness}from"./map-controls-readiness.js";import{LyraMapImageExportError}from"./map-image-export-error.js";import{loadMapAnchorRuntime,loadMapControlRuntime,loadMapDrawingRuntime,loadMapFeatureStateRuntime,loadMapHashRuntime,loadMapImageExportRuntime,loadMapOwnedFeatureRuntime,loadMapSceneRenderRuntime,loadMapSceneBridge}from"./map-feature-loader.js";import{LyraMapImageExportError as LyraMapImageExportError2}from"./map-image-export-error.js";import{createMapConstructionScheduler}from"./map-construction-scheduler.js";import{projectMapDataLayerModel,projectMapRowPlacement,projectMapLabelOptions,buildMapLabelLayer,buildMapExternalLayers}from"./map-data-layer-model.js";import{emptyExtent,extendExtent,extendExtentWithGeoJson,extentToBounds,normalizeCameraOptions}from"./map-camera.js";import{LYRA_MAP_EMPTY_STYLE}from"./map-empty-style.js";import{projectGeoJson,projectAdmittedGeoJson,buildProjectedGeoJsonPropertyDiff}from"./map-geojson-diff.js";import{buildGeoJsonPropertyDiff}from"./map-geojson-diff.js";import{clusterColorExpression,heatmapColorExpression,heatmapWeightExpression,heatmapZoomValue,lineColorExpression,mutedCategoryOpacityExpression,pointColorExpression,pointRadiusExpression,stepExpression}from"./map-data-layers.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_mapActivate,LYRA_DEFAULT_mapCancelDrawing,LYRA_DEFAULT_mapCancelPick,LYRA_DEFAULT_mapCompleteDrawing,LYRA_DEFAULT_mapControlUnavailable,LYRA_DEFAULT_mapDrawAtCenter,LYRA_DEFAULT_mapDrawingArea,LYRA_DEFAULT_mapDrawingControls,LYRA_DEFAULT_mapDrawingDuplicateVertex,LYRA_DEFAULT_mapDrawingEditInstructions,LYRA_DEFAULT_mapDrawingInvalidCoordinate,LYRA_DEFAULT_mapDrawingInvalidGeometry,LYRA_DEFAULT_mapDrawingLength,LYRA_DEFAULT_mapDrawingTooFewVertices,LYRA_DEFAULT_mapDrawingUnavailable,LYRA_DEFAULT_mapDrawingVertex,LYRA_DEFAULT_mapDrawingVertexLimit,LYRA_DEFAULT_mapDrawingVertices,LYRA_DEFAULT_mapExportUnavailable,LYRA_DEFAULT_mapFeatureStateUnavailable,LYRA_DEFAULT_mapFeedback,LYRA_DEFAULT_mapGeolocateError,LYRA_DEFAULT_mapGeolocateFindLocation,LYRA_DEFAULT_mapGeolocateOutOfBounds,LYRA_DEFAULT_mapGeolocatePermissionDenied,LYRA_DEFAULT_mapGeolocatePositionUnavailable,LYRA_DEFAULT_mapGeolocateTimeout,LYRA_DEFAULT_mapGeolocateUnavailable,LYRA_DEFAULT_mapGlobe,LYRA_DEFAULT_mapHashConflict,LYRA_DEFAULT_mapHashInvalid,LYRA_DEFAULT_mapInitializationFailed,LYRA_DEFAULT_mapLegend,LYRA_DEFAULT_mapMarker,LYRA_DEFAULT_mapMissingLibrary,LYRA_DEFAULT_mapPickAtCenter,LYRA_DEFAULT_mapResetNorth,LYRA_DEFAULT_mapScaleFeet,LYRA_DEFAULT_mapScaleKilometers,LYRA_DEFAULT_mapScaleMeters,LYRA_DEFAULT_mapScaleMiles,LYRA_DEFAULT_mapScaleNauticalMiles,LYRA_DEFAULT_mapScene,LYRA_DEFAULT_mapSceneArc,LYRA_DEFAULT_mapSceneEmpty,LYRA_DEFAULT_mapSceneHide,LYRA_DEFAULT_mapSceneInvalid,LYRA_DEFAULT_mapSceneLimit,LYRA_DEFAULT_mapSceneMarker,LYRA_DEFAULT_mapSceneModel,LYRA_DEFAULT_mapSceneNext,LYRA_DEFAULT_mapScenePage,LYRA_DEFAULT_mapScenePartial,LYRA_DEFAULT_mapScenePath,LYRA_DEFAULT_mapScenePrevious,LYRA_DEFAULT_mapSceneShow,LYRA_DEFAULT_mapSceneUnavailable,LYRA_DEFAULT_mapSquareKilometers,LYRA_DEFAULT_mapSquareMeters,LYRA_DEFAULT_mapStyleRequired,LYRA_DEFAULT_mapTerrain,LYRA_DEFAULT_mapToggleAttribution,LYRA_DEFAULT_mapUndoDrawing,LYRA_DEFAULT_mapWebglUnavailable}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_cancel,LYRA_DEFAULT_close,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_duration,LYRA_DEFAULT_items,LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_model,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationSummary,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";function supportsWebGL2(host){try{const context=host.ownerDocument.createElement("canvas").getContext("webgl2");if(!context)return!1;try{context.getExtension("WEBGL_lose_context")?.loseContext()}catch{}return!0}catch{return!1}}const MAP_ENGINE=literalSetConverter(["modular","maplibre"],"modular");function hasMapStyle(style){return typeof style=="string"?style.trim().length>0:style!==void 0}const LEGEND_CONTROL_ROLE=literalSetConverter(["button","checkbox"],"button"),MAX_LEGEND_GRADIENT_TICKS=16,EMPTY_LEGEND_GRADIENT_TICKS=Object.freeze([]);function normalizeMapLegendGradientTicks(value){try{const scanCount=boundedOwnArrayLength(value,MAX_LEGEND_GRADIENT_TICKS*4);if(scanCount===void 0)return EMPTY_LEGEND_GRADIENT_TICKS;const byValue=new Map;for(let index=0;index<scanCount&&byValue.size<MAX_LEGEND_GRADIENT_TICKS;index+=1){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(descriptor))continue;const entry=descriptor.value;let tickValue=entry,label;isRuntimeRecord(entry)&&(tickValue=optionalDescriptorValue(getOwnDataDescriptor(entry,"value")),label=optionalDescriptorValue(getOwnDataDescriptor(entry,"label"))),!(typeof tickValue!="number"||!Number.isFinite(tickValue)||byValue.has(tickValue))&&byValue.set(tickValue,Object.freeze(typeof label=="string"&&label.trim().length>0?{value:tickValue,label:boundedLegendText(label.trim(),64)}:{value:tickValue}))}return byValue.size===0?EMPTY_LEGEND_GRADIENT_TICKS:Object.freeze([...byValue.values()].sort((a,b)=>a.value-b.value))}catch{return EMPTY_LEGEND_GRADIENT_TICKS}}const MAX_MAP_LEGEND_GRADIENT_STOPS=64;function isRuntimeArray(value){try{return Array.isArray(value)}catch{return!1}}function isRuntimeRecord(value){try{return value!==null&&typeof value=="object"&&!Array.isArray(value)}catch{return!1}}function boundedOwnArrayLength(value,limit){if(!isRuntimeArray(value))return;const descriptor=getOwnDataDescriptor(value,"length");if(!(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof descriptor.value!="number"||!Number.isSafeInteger(descriptor.value)||descriptor.value<0))return Math.min(descriptor.value,limit)}function isUnsafeDescriptor(descriptor){return descriptor===UNSAFE_OWN_DATA_DESCRIPTOR}function optionalDescriptorValue(descriptor){return descriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(descriptor)?void 0:descriptor.value}function normalizeMapLegendGradient(value){try{const scanCount=boundedOwnArrayLength(value,MAX_MAP_LEGEND_GRADIENT_STOPS);if(scanCount===void 0)return[];const usable=[];for(let index=0;index<scanCount;index+=1){const stopDescriptor=getOwnDataDescriptor(value,String(index));if(stopDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(stopDescriptor))continue;const stop=stopDescriptor.value,stopLength=boundedOwnArrayLength(stop,2);if(stopLength===void 0||stopLength<2)continue;const valueDescriptor=getOwnDataDescriptor(stop,"0"),colorDescriptor=getOwnDataDescriptor(stop,"1");if(valueDescriptor===MISSING_OWN_DATA_DESCRIPTOR||colorDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(valueDescriptor)||isUnsafeDescriptor(colorDescriptor)||typeof valueDescriptor.value!="number"||!Number.isFinite(valueDescriptor.value)||typeof colorDescriptor.value!="string")continue;const color=sanitizeCssColor(colorDescriptor.value);color&&usable.push([valueDescriptor.value,color])}return usable.length<2?[]:Object.freeze([...usable].sort((a,b)=>a[0]-b[0]))}catch{return[]}}const MAP_LEGEND_ITEM_LIMIT=100,MAP_LEGEND_SCAN_LIMIT=1e3,MAP_LEGEND_LABEL_LIMIT=256,MAP_LEGEND_TOTAL_LABEL_LIMIT=8192,MAP_LEGEND_COLOR_LIMIT=256,MAP_LEGEND_VALUE_LIMIT=256,MAP_LEGEND_PATTERNS=new Set(["solid","diagonal","dots","crosshatch"]),EMPTY_MAP_LEGEND=Object.freeze([]),EMPTY_MAP_LEGEND_PROJECTION=Object.freeze({inputCount:0,renderedCount:0,omittedCount:0,truncatedLabelCount:0,truncated:!1});function boundedLegendText(value,limit){return value.length<=limit?value:`${value.slice(0,Math.max(0,limit-1))}…`}function normalizeMapLegend(value){let input;try{input=Array.isArray(value)?value:[]}catch{input=[]}let inputCount=0;try{inputCount=Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,input.length))}catch{inputCount=0}const entries=[];let labelCharacters=0,truncatedLabelCount=0;const scanCount=Math.min(inputCount,MAP_LEGEND_SCAN_LIMIT);for(let index=0;index<scanCount&&entries.length<MAP_LEGEND_ITEM_LIMIT;index++)try{const candidate=input[index];if(!candidate||typeof candidate!="object")continue;const rawColor=candidate.color,rawLabel=candidate.label,rawPattern=candidate.pattern;if(typeof rawColor!="string"||typeof rawLabel!="string"||typeof rawPattern!="string"||!MAP_LEGEND_PATTERNS.has(rawPattern))continue;const remaining=MAP_LEGEND_TOTAL_LABEL_LIMIT-labelCharacters;if(remaining<=0)break;const labelLimit=Math.min(MAP_LEGEND_LABEL_LIMIT,remaining),label=boundedLegendText(rawLabel,labelLimit);if(!label.trim())continue;rawLabel.length>labelLimit&&truncatedLabelCount++,labelCharacters+=label.length;const rawValue=candidate.value,trimmedValue=typeof rawValue=="string"?rawValue.trim():"",value2=trimmedValue?trimmedValue.slice(0,MAP_LEGEND_VALUE_LIMIT):void 0,rawGroup=candidate.group,trimmedGroup=typeof rawGroup=="string"?rawGroup.trim():"",group=trimmedGroup?boundedLegendText(trimmedGroup,MAP_LEGEND_LABEL_LIMIT):void 0,rawIcon=candidate.icon,icon=isRuntimeRecord(rawIcon)?projectIconPaint(rawIcon):void 0;entries.push(Object.freeze({color:rawColor.slice(0,MAP_LEGEND_COLOR_LIMIT),label,pattern:rawPattern,...value2?{value:value2}:{},...group?{group}:{},...icon?{icon}:{}}))}catch{}const frozenEntries=entries.length?Object.freeze(entries):EMPTY_MAP_LEGEND,omittedCount=Math.max(0,inputCount-frozenEntries.length),projection=Object.freeze({inputCount,renderedCount:frozenEntries.length,omittedCount,truncatedLabelCount,truncated:omittedCount>0||truncatedLabelCount>0});return{entries:frozenEntries,projection,grouped:frozenEntries.some(entry=>entry.group!==void 0)}}const EMPTY_HIDDEN_CATEGORIES=Object.freeze([]);function normalizeMapHiddenCategories(value){let input,length=0;try{input=Array.isArray(value)?value:[],length=Math.max(0,Math.min(MAP_LEGEND_SCAN_LIMIT,input.length))}catch{return EMPTY_HIDDEN_CATEGORIES}const keys=[];for(let index=0;index<length&&keys.length<MAP_LEGEND_ITEM_LIMIT;index++)try{const candidate=input[index];if(typeof candidate!="string")continue;const key=candidate.trim().slice(0,MAP_LEGEND_VALUE_LIMIT);if(!key||keys.includes(key))continue;keys.push(key)}catch{}return keys.length?Object.freeze(keys):EMPTY_HIDDEN_CATEGORIES}function renderLegendIcon(icon){const[x,y,width,height]=icon.viewBox??DEFAULT_ICON_VIEW_BOX,mode=icon.mode??"fill";return html`<svg
|
|
2
2
|
class="legend-icon"
|
|
3
3
|
viewBox=${`${x} ${y} ${width} ${height}`}
|
|
4
4
|
focusable="false"
|
|
@@ -25,7 +25,7 @@ import{__decorate}from"tslib";import{MapPaintBatch}from"./map-paint-batch.js";im
|
|
|
25
25
|
<button type="button" ?disabled=${blocked||page+1===pages} @click=${()=>{this.sceneInteractionAllowed(owner)&&(this.scenePage=Math.min(pages-1,page+1))}}>${this.localize("mapSceneNext")}</button>
|
|
26
26
|
</div>`:nothing}
|
|
27
27
|
</div>
|
|
28
|
-
</section>`}static{this.identityEventDetailProperties=Object.freeze({"lr-map-click":Object.freeze(["feature"]),"lr-map-feature-enter":Object.freeze(["feature"]),"lr-map-feature-leave":Object.freeze(["feature"]),"lr-map-contextmenu":Object.freeze(["feature"]),"lr-map-pick":Object.freeze(["feature"]),"lr-map-marker-activate":Object.freeze(["marker"])})}static{this.ownedCollectionProperties=Object.freeze(["center","mapStyle","overlays","choropleth","markers","dataLayers","images","styleOverrides","interactiveBasemapLayers"])}static{this.identityCollectionProperties=Object.freeze(["markers","dataLayers","images","styleOverrides"])}static{this.identityCollectionObjectProperties=Object.freeze(["mapStyle","choropleth","overlays"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static preload(engine="modular"){return(engine==="maplibre"?loadMaplibre():loadModularMap()).then(module=>module!==null)}constructor(){super(),this.sceneRepairFocus=!1,this.scenePanelOpen=!1,this.scenePage=0,this.hostDescription=new HostDescriptionController(this,()=>{try{return this._map?.getCanvas?.()??null}catch{return null}}),this.terrainInvalid=!1,this.sceneRequest=0,this.sceneControlsRequestPending=!1,this.hasAssignedCenter=!1,this._center=Object.freeze([0,0]),this.zoom=2,this.appliedPadding=ZERO_CAMERA_PADDING,this.commandToken=Object.freeze({}),this.reflectingCamera=!1,this.zoomLimitRevision=0,this.cameraUpdatePending=!1,this.deferredCameraWork=[],this.fitToken=Object.freeze({}),this.semanticsStale=!0,this.markerSemanticsStale=!0,this.geoJsonRefreshRequested=!1,this.refreshingGeoJson=!1,this.boxZoomSettling=!1,this.writingCamera=!1,this.maxBounds=null,this.hash=!1,this.hashFormat="named",this.hashRuntimePending=!1,this.hashRuntimeFailed=!1,this.applyingHash=!1,this.sceneControlIssue=!1,this.pendingSceneControlIssue=!1,this.controlOutlines=[],this.pendingControlOutlines=[],this.featureLoads=0,this.anchorClosable=!1,this.initialization="visible",this._mapStyleRevision=0,this._legend=EMPTY_MAP_LEGEND,this._legendProjection=EMPTY_MAP_LEGEND_PROJECTION,this._legendGrouped=!1,this.hasLegendSlot=!1,this.hasLegendStartSlot=!1,this._legendGradient=Object.freeze([]),this.legendIsLine=!1,this.legendGradientLoLabel=null,this.legendGradientHiLabel=null,this._legendGradientTicks=EMPTY_LEGEND_GRADIENT_TICKS,this._legendGradientTicksAssigned=!1,this.choroplethLegend=!1,this.derivedLegend=EMPTY_DERIVED_LEGEND,this.legendInteractive=!1,this._legendControlRole="button",this.legendCollapsible=!1,this.legendOpen=!0,this._hiddenCategories=EMPTY_HIDDEN_CATEGORIES,this.markers=[],this.dataLayers=[],this.overlays={},this.images=[],this.styleOverrides=[],this._canonicalChoroplethSource=UNPROJECTED_MAP_VALUE,this._canonicalDataLayersSource=UNPROJECTED_MAP_VALUE,this._canonicalDataLayersBase="",this._canonicalDataLayersOrigin="",this._canonicalExternalLayers=[],this.invalidDataLayerModel=!1,this.dataLayerIssue=!1,this.pendingDataLayerIssue=!1,this.committedDataLayers=EMPTY_CANONICAL_MAP_DATA_LAYERS,this.committedExternalLayers=[],this.groupOrderActive=!1,this.plannedDataLayerIds=new Map,this._canonicalDataLayers=EMPTY_CANONICAL_MAP_DATA_LAYERS,this._canonicalMarkersSource=UNPROJECTED_MAP_VALUE,this._canonicalMarkers=EMPTY_CANONICAL_MAP_MARKERS,this.engine="modular",this.loading=!0,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.loadLibrary=engine=>engine==="maplibre"?loadMaplibre():loadModularMap(),this.visible=!1,this.constructionMode="visible",this._styleLoaded=!1,this._appliedDataLayerIds=new Map,this._appliedDataLayerShapes=new Map,this._appliedGeoJson=new Map,this._nextDataLayerId=0,this.nextPointIconId=0,this.appliedPointPaint=new Set,this.appliedPointMuting=new Set,this.appliedPointIcons=new Map,this.cameraSessionConfigurationRevision=0,this.cameraSessionConfigurationApplied=0,this.cameraSessionConfigurationApplying=0,this.customLayerCallbacks=new Set,this.customLayerActivations=new WeakSet,this._webglReady=!1,this._markerInstances=new Map,this._markerLabels=new Map,this._markerPopupIds=new Map,this.markerActivationDetails=new WeakMap,this._configuredPopups=new WeakSet,this._nextPopupId=0,this._markerColors=new Map,this._markerSources=new Map,this._connectGeneration=0,this._styleGeneration=0,this.readiness=new MapReadiness,this.controlsReadiness=new MapControlsReadiness,this.externalFeatureWorkStarted=!1,this.externalIdStyle=-1,this.externalIdCounter=0,this.externalSourceIds=new Map,this.appliedGeoLabels=new Map,this.peerEvents=new MapEngineEvents,this.optionalFeatureWorkStarted=!1,this.interactiveBasemapLayers=[],this.pickMode=!1,this.keyboardActivation=!1,this.drawMode="none",this.drawingMeasurements=!1,this.drawingRevision=0,this.suppressDrawingClick=!1,this.drawingResetting=!1,this.drawingEpoch=0,this.featureStateIssue=!1,this.interactionBlocked=!1,this.stateRouter=new MapFeatureStateRouter,this.stateRequested=!1,this.stateRoutingAvailable=!0,this.stateRoutes=[],this.sourceIdentities=new Map,this.interactions=[],this.interactionGeneration=0,this.interactionQuery=0,this.queryingMap=!1,this.mapCursor=new MapCursorOwner,this.featureWork=Promise.resolve(),this.featureGeneration=0,this.preparingFeatures=!1,this.pendingMapLoad=!1,this.mapLoadEmitted=!1,this.rebuildGeneratedLayers=!1,this.scaleLabels=new Map,this.anchorSyncRequested=!1,this.childAnchorSet=new Set,this.anchorSlotPresence=new SlotPresenceController(this,{observeLightDom:!0}),this.exportIssue=!1,this.pendingExportIssue=!1,this.onAnchorFocus=event=>{this.anchorController?.focusIn(event)},this.onAnchorSlotChange=()=>{this.scheduleAnchorSync()},this.onAnchorsSlotChange=event=>{const refresh=node=>{node[MAP_ANCHOR_SEAM]?.("refresh")};this.childAnchorSet.forEach(refresh);for(const node of event.target.assignedElements({flatten:!0}))node.localName===tag("map-anchor")&&!customElements.get(node.localName)&&devWarnOnce("lyra-map-anchor-undefined",`<${this.localName}>: import @aceshooting/lyra-ui/components/${node.localName}.js to place <${node.localName}> children.`),refresh(node),node.querySelectorAll(tag("map-anchor")).forEach(refresh)},this.clusterZoomToken=0,this.mapUpdateActive=!1,this.paintThemeTokens=[],this.mapPaintBatch=new MapPaintBatch,this.mapPaintBatchActive=!1,this.pendingDrawingTheme=!1,this._styleLayers=EMPTY_STYLE_LAYERS,this._styleSources=EMPTY_STYLE_SOURCES,this.drawingConfigRevision=0,this.drawingConfigApplying=0,this.drawingConfigApplied=0,this.pointerInside=!1,this.drawMapCenter=()=>{this.drawingController?.addCenter()},this.cancelMapPick=()=>{this.pickMode=!1,this.clearMapHover()},this.pickMapCenter=()=>{const map=this._map,generation=this.interactionGeneration;if(!(!map||!this.pickMode||!this.mapInteractionAllowed()))try{const lngLat=mapCoordinates(map.getCenter());lngLat&&this._map===map&&generation===this.interactionGeneration&&this.mapInteractionAllowed()&&this.emit("lr-map-pick",Object.freeze({lngLat,trigger:"keyboard"}))}catch{}},this.appliedLayerPaintKeys=new Map,this.appliedRowRanges=new Map,this.configuredMarkerElements=new WeakSet,this.onLegendSlotChange=event=>{const slot=event.target,filled=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="legend-start"?this.hasLegendStartSlot=filled:this.hasLegendSlot=filled},new ThemeWatcher(this,()=>{if(this.geographicSceneRender?.refreshPresentation(),!this.syncPaintTheme())return;const coordinated=this.refreshThemePaint();this.legendIsLine=this.legendDescribesLine(),coordinated||this.drawingController?.repaint()}),new GlassScrollLayer(this,'[part="legend"]')}get projection(){return this._projection}set projection(value){const old=this._projection;this._projection=normalizeMapProjection(value),this.requestUpdate("projection",old)}get terrain(){return this._terrain}set terrain(value){const old=this._terrain;try{this._terrain=admitMapTerrain(value),this.terrainInvalid=!1}catch{this._terrain=void 0,this.terrainInvalid=!0}this.requestUpdate("terrain",old)}syncSceneConfiguration(){const map=this._map;if(!map||!this._styleLoaded||this.failure||!this.sceneConfiguration&&this.projection===void 0&&this.terrain===void 0&&!this.terrainInvalid)return;this.sceneConfiguration??=new MapSceneConfigurationController({changed:()=>{this.readiness.check(),this.flushMapLoad(),this.controlLifecycle?.refreshSceneControls()},failed:()=>{this.failInitialization("initialization-failed")}});const generation=this._styleGeneration,connection=this._connectGeneration,style=this.mapStyle,request=this.sceneRequest;this.sceneConfiguration.sync(map,generation,()=>this.isConnected&&this._map===map&&this._styleGeneration===generation&&this._connectGeneration===connection&&this.mapStyle===style&&this.sceneRequest===request,this.projection,this.terrainInvalid?{}:this.terrain)}get center(){return this._center}set center(value){this.hasAssignedCenter&&sameCenterValue(value,this.assignedCenter)||(this.hasAssignedCenter=!0,this.assignedCenter=snapshotCenter(value),this._center=value)}get zoomLimitsRequested(){return[this.minZoom,this.maxZoom].some(value=>typeof value=="number"&&Number.isFinite(value))}get zoomLimits(){const explicit=value=>typeof value=="number"&&Number.isFinite(value)?finiteRange(value,0,0,24):void 0,min=explicit(this.minZoom),max=explicit(this.maxZoom);if(min!==void 0&&max!==void 0&&min>max)return devWarnOnce("lyra-map-zoom-limits-inverted",`<${this.localName}>: minZoom ${min} exceeds maxZoom ${max}; both limits are ignored.`),DEFAULT_ZOOM_LIMITS;const lower=min??0;return[lower,max??Math.max(22,lower)]}get hashOption(){return this.hashFormat!=="unnamed"||!this.hashRequested()?this.hash:this.hash===!0?MAP_HASH_UNNAMED:""}setSceneControlIssue(unavailable){this.pendingSceneControlIssue!==unavailable&&(this.pendingSceneControlIssue=unavailable,this.mapUpdateActive?this.scheduleAfterUpdate(()=>{this.sceneControlIssue=this.pendingSceneControlIssue},"map-scene-control-feedback"):this.sceneControlIssue=unavailable)}setControlOutlines(outlines){outlines.length===0&&this.pendingControlOutlines.length===0||(this.pendingControlOutlines=outlines,this.mapUpdateActive?this.scheduleAfterUpdate(()=>{this.controlOutlines=this.pendingControlOutlines},"map-control-outlines"):this.controlOutlines=outlines)}setControlIssue(issue){this.pendingControlIssue=issue,this.mapUpdateActive?this.scheduleAfterUpdate(()=>{this.controlIssue=this.pendingControlIssue},"map-control-feedback"):this.controlIssue=issue}hashRequested(){return this.hash!==!1&&this.hash!==void 0&&this.hash!==null}hashRuntime(){if(this.hashOwner||!this.hashRequested()||this.hashRuntimeFailed)return this.hashOwner;const runtime=loadMapHashRuntime.loaded;if(runtime)return this.hashOwner=new runtime.MapHashOwner;this.hashRuntimePending||(this.hashRuntimePending=!0,this.trackFeatureLoad(loadMapHashRuntime().then(()=>{},()=>{this.hashRuntimeFailed=!0}).then(()=>{this.hashRuntimePending=!1,this.isConnected&&(this.syncHash(),this.applyHash(),this.tryConstructMap())})))}trackFeatureLoad(work){this.featureLoads+=1,this.readiness.invalidate(),work.finally(()=>{this.featureLoads-=1,this.readiness.check()})}syncHash(){if(!this.isConnected)return;const owner=this.hashRuntime(),status=owner?owner.configure(this.ownerDocument.defaultView,this.hashOption,()=>this.applyHash()):void 0,issue=status==="conflict"?"mapHashConflict":status==="invalid"?"mapHashInvalid":!owner&&this.hashRuntimeFailed&&this.hashRequested()?"mapControlUnavailable":void 0;this.pendingHashIssue=issue,this.scheduleAfterUpdate(()=>{const latest=this.pendingHashIssue;latest!==this.hashIssue&&(this.hashIssue=latest,latest&&this.announcements.announceAssertive(this.localize(MAP_CONFIGURATION_MESSAGE[latest])))},"map-hash-feedback")}applyHash(){if(this.mapUpdateActive){this.scheduleAfterUpdate(()=>this.applyHash(),"map-apply-hash");return}const map=this._map,connection=this._connectGeneration,option=this.hashOption,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===connection&&this.hashOption===option,owner=this.hashOwner;if(!owner)return;const result=owner.read();if(!map||!current()||this.applyingHash)return;if(result.status==="none"){this.writeHash(map);return}if(result.status!=="camera")return;const camera=result.camera;try{const shown=readPeerCamera(map);if(!current())return;const bearing=map.getBearing?.()??0;if(!current())return;const pitch=map.getPitch?.()??0;if(!current()||shown&&shown.zoom===camera.zoom&&shown.center[0]===camera.center[0]&&shown.center[1]===camera.center[1]&&bearing===camera.bearing&&pitch===camera.pitch)return;this.applyingHash=!0;try{this.applyCameraCommand(map,"jumpTo",{...camera,center:[...camera.center]},!1)}finally{this.applyingHash=!1}}catch{}}writeHash(map){const connection=this._connectGeneration,option=this.hashOption,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===connection&&this.hashOption===option;if(!(!current()||this.applyingHash))try{const camera=readPeerCamera(map);if(!camera||!current())return;const bearing=map.getBearing?.()??0;if(!current())return;const pitch=map.getPitch?.()??0;if(!current())return;this.hashOwner?.write({...camera,bearing,pitch})}catch{}}get safeInitializationDelay(){const delay=this.initializationDelay;return typeof delay=="number"&&Number.isFinite(delay)&&delay>=0?finiteDuration(delay,0):void 0}get initializationMode(){const mode=this.initialization;return mode==="idle"||mode==="eager"||mode==="interaction"?mode:"visible"}get awaitingActivation(){return this.initializationMode==="interaction"&&!this._map&&!this.failure&&!this.loading&&this.constructionScheduler?.constructed!==!0}get mapStyle(){return this._mapStyle}set mapStyle(value){if(value===this._mapStyleSource||value===this._mapStyle)return;const revision=++this._mapStyleRevision;this._mapStyleSource=value;const previous=this._mapStyle,snapshot=snapshotMapStyle(value,this.ownerDocument.defaultView);revision===this._mapStyleRevision&&(this._mapStyle=snapshot,this.requestUpdate("mapStyle",previous))}get legend(){return this._legend}set legend(value){if(value===this._legendSource||value===this._legend)return;this._legendSource=value;const previous=this._legend,normalized=normalizeMapLegend(value);this._legend=normalized.entries,this._legendProjection=normalized.projection,this._legendGrouped=normalized.grouped,this.requestUpdate("legend",previous)}probeLegendSlot(name){for(const child of Array.from(this.children))if(child.getAttribute("slot")===name)return!0;return!1}get legendGradient(){return this._legendGradient}set legendGradient(value){if(value===this._legendGradientSource||value===this._legendGradient)return;this._legendGradientSource=value;const previous=this._legendGradient;this._legendGradient=normalizeMapLegendGradient(value),this.requestUpdate("legendGradient",previous)}warnOnLegendChoroplethMismatch(){if(!litDevWarnings()||this.legendIsLine)return;const layer=this.canonicalChoropleth,legend=this.legendGradient;!layer||legend.length===0||layer.stops.length===0||legend.length===layer.stops.length&&legend.every(([legendValue,legendColor],index)=>{const layerStop=layer.stops[index];return layerStop!==void 0&&layerStop[0]===legendValue&&resolvedLayerColor(this,layerStop[1],void 0)===resolvedLayerColor(this,legendColor,void 0)})||devWarnOnce("lyra-map-legend-choropleth-mismatch",`<${this.localName}>: legendGradient does not match choropleth.stops, so the visible key may misdescribe the map. Assign the same stops array to both, or derive both from one source.`)}legendDescribesLine(){const stops=this.legendGradient;return stops.length<2?!1:this.canonicalDataLayers.some(layer=>layer.kind==="auto"&&!layer.cluster&&layer.line?.field&&layer.line.stops.length===stops.length&&layer.line.stops.every(([value,color],index)=>value===stops[index][0]&&resolvedLayerColor(this,color,layer.tone)===resolvedLayerColor(this,stops[index][1],layer.tone)))}get legendGradientTicks(){return this._legendGradientTicks}set legendGradientTicks(value){if(value===this._legendGradientTicksSource)return;this._legendGradientTicksSource=value;const previous=this._legendGradientTicks;this._legendGradientTicks=normalizeMapLegendGradientTicks(value),this._legendGradientTicksAssigned=Array.isArray(value),this.requestUpdate("legendGradientTicks",previous)}get legendProjection(){return this._legendProjection}set legendProjection(_value){}get legendControlRole(){return this._legendControlRole}set legendControlRole(next){const normalized=LEGEND_CONTROL_ROLE.normalizeReflected(this,"legend-control-role",next),old=this._legendControlRole;old!==normalized&&(this._legendControlRole=normalized,this.requestUpdate("legendControlRole",old))}get legendCollapsed(){return this.legendCollapsible&&!this.legendOpen}toggleLegendPanel(){if(!this.legendCollapsible)return;const open=!this.legendOpen;this.emit("lr-map-legend-panel-toggle-request",{open},{cancelable:!0}).defaultPrevented||(this.legendOpen=open)}renderLegendDisclosure(){return this.legendCollapsible?html`<button
|
|
28
|
+
</section>`}static{this.identityEventDetailProperties=Object.freeze({"lr-map-click":Object.freeze(["feature"]),"lr-map-feature-enter":Object.freeze(["feature"]),"lr-map-feature-leave":Object.freeze(["feature"]),"lr-map-contextmenu":Object.freeze(["feature"]),"lr-map-pick":Object.freeze(["feature"]),"lr-map-marker-activate":Object.freeze(["marker"])})}static{this.ownedCollectionProperties=Object.freeze(["center","mapStyle","overlays","choropleth","markers","dataLayers","images","styleOverrides","interactiveBasemapLayers"])}static{this.identityCollectionProperties=Object.freeze(["markers","dataLayers","images","styleOverrides"])}static{this.identityCollectionObjectProperties=Object.freeze(["mapStyle","choropleth","overlays"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static preload(engine="modular"){return(engine==="maplibre"?loadMaplibre():loadModularMap()).then(module=>module!==null)}constructor(){super(),this.sceneRepairFocus=!1,this.scenePanelOpen=!1,this.scenePage=0,this.hostDescription=new HostDescriptionController(this,()=>{try{return this._map?.getCanvas?.()??null}catch{return null}}),this.terrainInvalid=!1,this.sceneRequest=0,this.sceneControlsRequestPending=!1,this.hasAssignedCenter=!1,this._center=Object.freeze([0,0]),this.zoom=2,this.canvasPaddingUsable=!0,this.appliedPadding=ZERO_CAMERA_PADDING,this.commandToken=Object.freeze({}),this.reflectingCamera=!1,this.zoomLimitRevision=0,this.cameraUpdatePending=!1,this.deferredCameraWork=[],this.fitToken=Object.freeze({}),this.semanticsStale=!0,this.markerSemanticsStale=!0,this.geoJsonRefreshRequested=!1,this.refreshingGeoJson=!1,this.boxZoomSettling=!1,this.writingCamera=!1,this.maxBounds=null,this.hash=!1,this.hashFormat="named",this.hashRuntimePending=!1,this.hashRuntimeFailed=!1,this.applyingHash=!1,this.sceneControlIssue=!1,this.pendingSceneControlIssue=!1,this.controlOutlines=[],this.pendingControlOutlines=[],this.featureLoads=0,this.anchorClosable=!1,this.initialization="visible",this._mapStyleRevision=0,this._legend=EMPTY_MAP_LEGEND,this._legendRevision=0,this._legendProjection=EMPTY_MAP_LEGEND_PROJECTION,this._legendGrouped=!1,this.hasLegendSlot=!1,this.hasLegendStartSlot=!1,this._legendGradient=Object.freeze([]),this._legendGradientRevision=0,this.legendIsLine=!1,this.legendGradientLoLabel=null,this.legendGradientHiLabel=null,this._legendGradientTicks=EMPTY_LEGEND_GRADIENT_TICKS,this._legendGradientTicksRevision=0,this._legendGradientTicksAssigned=!1,this.choroplethLegend=!1,this.derivedLegend=EMPTY_DERIVED_LEGEND,this.legendInteractive=!1,this._legendControlRole="button",this.legendCollapsible=!1,this.legendOpen=!0,this._hiddenCategories=EMPTY_HIDDEN_CATEGORIES,this._hiddenCategoriesRevision=0,this.markers=[],this.dataLayers=[],this.overlays={},this.images=[],this.styleOverrides=[],this._canonicalChoroplethSource=UNPROJECTED_MAP_VALUE,this._canonicalDataLayersSource=UNPROJECTED_MAP_VALUE,this._canonicalDataLayersBase="",this._canonicalDataLayersOrigin="",this._canonicalExternalLayers=[],this.invalidDataLayerModel=!1,this.dataLayerIssue=!1,this.pendingDataLayerIssue=!1,this.committedDataLayers=EMPTY_CANONICAL_MAP_DATA_LAYERS,this.committedExternalLayers=[],this.groupOrderActive=!1,this.plannedDataLayerIds=new Map,this._canonicalDataLayers=EMPTY_CANONICAL_MAP_DATA_LAYERS,this._canonicalMarkersSource=UNPROJECTED_MAP_VALUE,this._canonicalMarkers=EMPTY_CANONICAL_MAP_MARKERS,this.engine="modular",this.loading=!0,this.announcements=new AnnouncementSinkController(this,{eager:["assertive"]}),this.loadLibrary=engine=>engine==="maplibre"?loadMaplibre():loadModularMap(),this.visible=!1,this.constructionMode="visible",this._styleLoaded=!1,this._appliedDataLayerIds=new Map,this._appliedDataLayerShapes=new Map,this._appliedGeoJson=new Map,this._nextDataLayerId=0,this.nextPointIconId=0,this.appliedPointPaint=new Set,this.appliedPointMuting=new Set,this.appliedPointIcons=new Map,this.cameraSessionConfigurationRevision=0,this.cameraSessionConfigurationApplied=0,this.cameraSessionConfigurationApplying=0,this.customLayerCallbacks=new Set,this.customLayerActivations=new WeakSet,this._webglReady=!1,this._markerInstances=new Map,this._markerLabels=new Map,this._markerPopupIds=new Map,this.markerActivationDetails=new WeakMap,this._configuredPopups=new WeakSet,this._nextPopupId=0,this._markerColors=new Map,this._markerSources=new Map,this._connectGeneration=0,this._styleGeneration=0,this.readiness=new MapReadiness,this.controlsReadiness=new MapControlsReadiness,this.externalFeatureWorkStarted=!1,this.externalIdStyle=-1,this.externalIdCounter=0,this.externalSourceIds=new Map,this.appliedGeoLabels=new Map,this.peerEvents=new MapEngineEvents,this.optionalFeatureWorkStarted=!1,this.interactiveBasemapLayers=[],this.pickMode=!1,this.keyboardActivation=!1,this.drawMode="none",this.drawingMeasurements=!1,this.drawingRevision=0,this.suppressDrawingClick=!1,this.drawingResetting=!1,this.drawingEpoch=0,this.featureStateIssue=!1,this.interactionBlocked=!1,this.stateRouter=new MapFeatureStateRouter,this.stateRequested=!1,this.stateRoutingAvailable=!0,this.stateRoutes=[],this.sourceIdentities=new Map,this.interactions=[],this.interactionGeneration=0,this.interactionQuery=0,this.queryingMap=!1,this.mapCursor=new MapCursorOwner,this.featureWork=Promise.resolve(),this.featureGeneration=0,this.preparingFeatures=!1,this.retainedOverlayInteractions=!1,this.pendingMapLoad=!1,this.mapLoadEmitted=!1,this.rebuildGeneratedLayers=!1,this.scaleLabels=new Map,this.anchorSyncRequested=!1,this.childAnchorSet=new Set,this.anchorSlotPresence=new SlotPresenceController(this,{observeLightDom:!0}),this.exportIssue=!1,this.pendingExportIssue=!1,this.onAnchorFocus=event=>{this.anchorController?.focusIn(event)},this.onAnchorSlotChange=()=>{this.scheduleAnchorSync()},this.onAnchorsSlotChange=event=>{const refresh=node=>{node[MAP_ANCHOR_SEAM]?.("refresh")};this.childAnchorSet.forEach(refresh);for(const node of event.target.assignedElements({flatten:!0}))node.localName===tag("map-anchor")&&!customElements.get(node.localName)&&devWarnOnce("lyra-map-anchor-undefined",`<${this.localName}>: import @aceshooting/lyra-ui/components/${node.localName}.js to place <${node.localName}> children.`),refresh(node),node.querySelectorAll(tag("map-anchor")).forEach(refresh)},this.clusterZoomToken=0,this.mapUpdateActive=!1,this.paintThemeTokens=[],this.mapPaintBatch=new MapPaintBatch,this.mapPaintBatchActive=!1,this.pendingDrawingTheme=!1,this._styleLayers=EMPTY_STYLE_LAYERS,this._styleSources=EMPTY_STYLE_SOURCES,this.drawingConfigRevision=0,this.drawingConfigApplying=0,this.drawingConfigApplied=0,this.pointerInside=!1,this.drawMapCenter=()=>{this.drawingController?.addCenter()},this.cancelMapPick=()=>{this.pickMode=!1,this.clearMapHover()},this.pickMapCenter=()=>{const map=this._map,generation=this.interactionGeneration;if(!(!map||!this.pickMode||!this.mapInteractionAllowed()))try{const lngLat=mapCoordinates(map.getCenter());lngLat&&this._map===map&&generation===this.interactionGeneration&&this.mapInteractionAllowed()&&this.emit("lr-map-pick",Object.freeze({lngLat,trigger:"keyboard"}))}catch{}},this.appliedLayerPaintKeys=new Map,this.appliedRowRanges=new Map,this.configuredMarkerElements=new WeakSet,this.onLegendSlotChange=event=>{const slot=event.target,filled=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="legend-start"?this.hasLegendStartSlot=filled:this.hasLegendSlot=filled},new ThemeWatcher(this,()=>{if(this.geographicSceneRender?.refreshPresentation(),!this.syncPaintTheme())return;const coordinated=this.refreshThemePaint();this.legendIsLine=this.legendDescribesLine(),coordinated||this.drawingController?.repaint()}),new GlassScrollLayer(this,'[part="legend"]')}get projection(){return this._projection}set projection(value){const old=this._projection;this._projection=normalizeMapProjection(value),this.requestUpdate("projection",old)}get terrain(){return this._terrain}set terrain(value){const old=this._terrain;try{this._terrain=admitMapTerrain(value),this.terrainInvalid=!1}catch{this._terrain=void 0,this.terrainInvalid=!0}this.requestUpdate("terrain",old)}syncSceneConfiguration(){const map=this._map;if(!map||!this._styleLoaded||this.failure||!this.sceneConfiguration&&this.projection===void 0&&this.terrain===void 0&&!this.terrainInvalid)return;this.sceneConfiguration??=new MapSceneConfigurationController({changed:()=>{this.readiness.check(),this.flushMapLoad(),this.controlLifecycle?.refreshSceneControls()},failed:()=>{this.failInitialization("initialization-failed")}});const generation=this._styleGeneration,connection=this._connectGeneration,style=this.mapStyle,request=this.sceneRequest;this.sceneConfiguration.sync(map,generation,()=>this.isConnected&&this._map===map&&this._styleGeneration===generation&&this._connectGeneration===connection&&this.mapStyle===style&&this.sceneRequest===request,this.projection,this.terrainInvalid?{}:this.terrain)}get center(){return this._center}set center(value){this.hasAssignedCenter&&sameCenterValue(value,this.assignedCenter)||(this.hasAssignedCenter=!0,this.assignedCenter=snapshotCenter(value),this._center=value)}get zoomLimitsRequested(){return[this.minZoom,this.maxZoom].some(value=>typeof value=="number"&&Number.isFinite(value))}get zoomLimits(){const explicit=value=>typeof value=="number"&&Number.isFinite(value)?finiteRange(value,0,0,24):void 0,min=explicit(this.minZoom),max=explicit(this.maxZoom);if(min!==void 0&&max!==void 0&&min>max)return devWarnOnce("lyra-map-zoom-limits-inverted",`<${this.localName}>: minZoom ${min} exceeds maxZoom ${max}; both limits are ignored.`),DEFAULT_ZOOM_LIMITS;const lower=min??0;return[lower,max??Math.max(22,lower)]}syncCanvasAllocation(){this.isConnected&&(!this.canvasAllocationController&&this.canvasTarget===void 0||(this.canvasAllocationController??=new MapCanvasAllocationController({element:this,base:()=>this.shadowRoot?.querySelector('[part="base"]')??void 0,target:()=>this.canvasTarget,changed:allocation=>{this.canvasAllocation=allocation;const map=this._map,generation=this._connectGeneration,document=this.ownerDocument,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===generation&&this.ownerDocument===document;if(map&¤t()){if(this.writeCamera(()=>{try{map.resize()}catch{}}),!current()||(this.applyCameraPadding(),!current()))return;this.drawingController?.scheduleHandles(),this.geographicSceneRender?.refreshAllocation(),this.scheduleAnchorSync()}}}),this.canvasAllocationController.refresh()))}releaseCanvasAllocation(){this.canvasAllocationController?.dispose(),this.canvasAllocationController=void 0,this.canvasAllocation=void 0,this.canvasPaddingUsable=!0}get hashOption(){return this.hashFormat!=="unnamed"||!this.hashRequested()?this.hash:this.hash===!0?MAP_HASH_UNNAMED:""}setSceneControlIssue(unavailable){this.pendingSceneControlIssue!==unavailable&&(this.pendingSceneControlIssue=unavailable,this.mapUpdateActive?this.scheduleAfterUpdate(()=>{this.sceneControlIssue=this.pendingSceneControlIssue},"map-scene-control-feedback"):this.sceneControlIssue=unavailable)}setControlOutlines(outlines){outlines.length===0&&this.pendingControlOutlines.length===0||(this.pendingControlOutlines=outlines,this.mapUpdateActive?this.scheduleAfterUpdate(()=>{this.controlOutlines=this.pendingControlOutlines},"map-control-outlines"):this.controlOutlines=outlines)}setControlIssue(issue){this.pendingControlIssue=issue,this.mapUpdateActive?this.scheduleAfterUpdate(()=>{this.controlIssue=this.pendingControlIssue},"map-control-feedback"):this.controlIssue=issue}hashRequested(){return this.hash!==!1&&this.hash!==void 0&&this.hash!==null}hashRuntime(){if(this.hashOwner||!this.hashRequested()||this.hashRuntimeFailed)return this.hashOwner;const runtime=loadMapHashRuntime.loaded;if(runtime)return this.hashOwner=new runtime.MapHashOwner;this.hashRuntimePending||(this.hashRuntimePending=!0,this.trackFeatureLoad(loadMapHashRuntime().then(()=>{},()=>{this.hashRuntimeFailed=!0}).then(()=>{this.hashRuntimePending=!1,this.isConnected&&(this.syncHash(),this.applyHash(),this.tryConstructMap())})))}trackFeatureLoad(work){this.featureLoads+=1,this.readiness.invalidate(),work.finally(()=>{this.featureLoads-=1,this.readiness.check()})}syncHash(){if(!this.isConnected)return;const owner=this.hashRuntime(),status=owner?owner.configure(this.ownerDocument.defaultView,this.hashOption,()=>this.applyHash()):void 0,issue=status==="conflict"?"mapHashConflict":status==="invalid"?"mapHashInvalid":!owner&&this.hashRuntimeFailed&&this.hashRequested()?"mapControlUnavailable":void 0;this.pendingHashIssue=issue,this.scheduleAfterUpdate(()=>{const latest=this.pendingHashIssue;latest!==this.hashIssue&&(this.hashIssue=latest,latest&&this.announcements.announceAssertive(this.localize(MAP_CONFIGURATION_MESSAGE[latest])))},"map-hash-feedback")}applyHash(){if(this.mapUpdateActive){this.scheduleAfterUpdate(()=>this.applyHash(),"map-apply-hash");return}const map=this._map,connection=this._connectGeneration,option=this.hashOption,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===connection&&this.hashOption===option,owner=this.hashOwner;if(!owner)return;const result=owner.read();if(!map||!current()||this.applyingHash)return;if(result.status==="none"){this.writeHash(map);return}if(result.status!=="camera")return;const camera=result.camera;try{const shown=readPeerCamera(map);if(!current())return;const bearing=map.getBearing?.()??0;if(!current())return;const pitch=map.getPitch?.()??0;if(!current()||shown&&shown.zoom===camera.zoom&&shown.center[0]===camera.center[0]&&shown.center[1]===camera.center[1]&&bearing===camera.bearing&&pitch===camera.pitch)return;this.applyingHash=!0;try{this.applyCameraCommand(map,"jumpTo",{...camera,center:[...camera.center]},!1)}finally{this.applyingHash=!1}}catch{}}writeHash(map){const connection=this._connectGeneration,option=this.hashOption,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===connection&&this.hashOption===option;if(!(!current()||this.applyingHash))try{const camera=readPeerCamera(map);if(!camera||!current())return;const bearing=map.getBearing?.()??0;if(!current())return;const pitch=map.getPitch?.()??0;if(!current())return;this.hashOwner?.write({...camera,bearing,pitch})}catch{}}get safeInitializationDelay(){const delay=this.initializationDelay;return typeof delay=="number"&&Number.isFinite(delay)&&delay>=0?finiteDuration(delay,0):void 0}get initializationMode(){const mode=this.initialization;return mode==="idle"||mode==="eager"||mode==="interaction"?mode:"visible"}get awaitingActivation(){return this.initializationMode==="interaction"&&!this._map&&!this.failure&&!this.loading&&this.constructionScheduler?.constructed!==!0}get mapStyle(){return this._mapStyle}set mapStyle(value){if(value===this._mapStyleSource)return;const revision=++this._mapStyleRevision;if(this._mapStyleSource=value,value===this._mapStyle)return;const previous=this._mapStyle,snapshot=snapshotMapStyle(value,this.ownerDocument.defaultView);revision===this._mapStyleRevision&&(this._mapStyle=snapshot,this.requestUpdate("mapStyle",previous))}get legend(){return this._legend}set legend(value){if(value===this._legendSource)return;const revision=++this._legendRevision;if(this._legendSource=value,value===this._legend)return;const previous=this._legend,normalized=normalizeMapLegend(value);revision===this._legendRevision&&(this._legend=normalized.entries,this._legendProjection=normalized.projection,this._legendGrouped=normalized.grouped,this.requestUpdate("legend",previous))}probeLegendSlot(name){for(const child of Array.from(this.children))if(child.getAttribute("slot")===name)return!0;return!1}get legendGradient(){return this._legendGradient}set legendGradient(value){if(value===this._legendGradientSource)return;const revision=++this._legendGradientRevision;if(this._legendGradientSource=value,value===this._legendGradient)return;const previous=this._legendGradient,normalized=normalizeMapLegendGradient(value);revision===this._legendGradientRevision&&(this._legendGradient=normalized,this.requestUpdate("legendGradient",previous))}warnOnLegendChoroplethMismatch(){if(!litDevWarnings()||this.legendIsLine)return;const layer=this.canonicalChoropleth,legend=this.legendGradient;!layer||legend.length===0||layer.stops.length===0||legend.length===layer.stops.length&&legend.every(([legendValue,legendColor],index)=>{const layerStop=layer.stops[index];return layerStop!==void 0&&layerStop[0]===legendValue&&resolvedLayerColor(this,layerStop[1],void 0)===resolvedLayerColor(this,legendColor,void 0)})||devWarnOnce("lyra-map-legend-choropleth-mismatch",`<${this.localName}>: legendGradient does not match choropleth.stops, so the visible key may misdescribe the map. Assign the same stops array to both, or derive both from one source.`)}legendDescribesLine(){const stops=this.legendGradient;return stops.length<2?!1:this.canonicalDataLayers.some(layer=>layer.kind==="auto"&&!layer.cluster&&layer.line?.field&&layer.line.stops.length===stops.length&&layer.line.stops.every(([value,color],index)=>value===stops[index][0]&&resolvedLayerColor(this,color,layer.tone)===resolvedLayerColor(this,stops[index][1],layer.tone)))}get legendGradientTicks(){return this._legendGradientTicks}set legendGradientTicks(value){if(value===this._legendGradientTicksSource)return;const revision=++this._legendGradientTicksRevision;this._legendGradientTicksSource=value;const previous=this._legendGradientTicks,normalized=normalizeMapLegendGradientTicks(value);revision===this._legendGradientTicksRevision&&(this._legendGradientTicks=normalized,this._legendGradientTicksAssigned=isRuntimeArray(value),this.requestUpdate("legendGradientTicks",previous))}get legendProjection(){return this._legendProjection}set legendProjection(_value){}get legendControlRole(){return this._legendControlRole}set legendControlRole(next){const normalized=LEGEND_CONTROL_ROLE.normalizeReflected(this,"legend-control-role",next),old=this._legendControlRole;old!==normalized&&(this._legendControlRole=normalized,this.requestUpdate("legendControlRole",old))}get legendCollapsed(){return this.legendCollapsible&&!this.legendOpen}toggleLegendPanel(){if(!this.legendCollapsible)return;const open=!this.legendOpen;this.emit("lr-map-legend-panel-toggle-request",{open},{cancelable:!0}).defaultPrevented||(this.legendOpen=open)}renderLegendDisclosure(){return this.legendCollapsible?html`<button
|
|
29
29
|
part="legend-disclosure"
|
|
30
30
|
type="button"
|
|
31
31
|
aria-expanded=${this.legendOpen?"true":"false"}
|
|
@@ -33,7 +33,7 @@ import{__decorate}from"tslib";import{MapPaintBatch}from"./map-paint-batch.js";im
|
|
|
33
33
|
@click=${()=>this.toggleLegendPanel()}
|
|
34
34
|
><span part="legend-disclosure-icon" class="legend-disclosure-icon" aria-hidden="true"
|
|
35
35
|
>${chevronIcon()}</span
|
|
36
|
-
><span>${this.localize("mapLegend")}</span></button>`:nothing}get hiddenCategories(){return this._hiddenCategories}set hiddenCategories(value){if(value===this._hiddenCategoriesSource||value===this._hiddenCategories)return;this._hiddenCategoriesSource=value;const previous=this._hiddenCategories;this._hiddenCategories=normalizeMapHiddenCategories(value),this.requestUpdate("hiddenCategories",previous)}get markersTruncated(){const descriptor=getOwnDataDescriptor(this.markers,"length");return typeof descriptor!="symbol"&&typeof descriptor.value=="number"&&descriptor.value>MAX_MAP_MARKERS}setDataLayerIssue(issue){this.pendingDataLayerIssue=issue,this.scheduleAfterUpdate(()=>{const next=this.pendingDataLayerIssue;next!==this.dataLayerIssue&&(this.dataLayerIssue=next,next&&this.isConnected&&this.announcements.announceAssertive(this.localize("mapInitializationFailed")))},"map-data-layer-feedback")}get canonicalChoropleth(){const source=this.choropleth;return Object.is(source,this._canonicalChoroplethSource)?this._canonicalChoropleth:(this._canonicalChoroplethSource=source,this._canonicalChoropleth=projectMapChoropleth(source),this._canonicalChoropleth)}get canonicalDataLayers(){const source=this.dataLayers,base=this.ownerDocument.baseURI,origin=this.ownerDocument.defaultView?.origin??"null";if(Object.is(source,this._canonicalDataLayersSource)&&base===this._canonicalDataLayersBase&&origin===this._canonicalDataLayersOrigin)return this._canonicalDataLayers;this._canonicalDataLayersSource=source,this._canonicalDataLayersBase=base,this._canonicalDataLayersOrigin=origin;const model=projectMapDataLayerModel(source,{baseUrl:base,ownerOrigin:origin,projectGeoJson:projectMapDataLayer});return this.invalidDataLayerModel=!model.ok,model.ok&&(this._canonicalDataLayers=model.geojson,this._canonicalExternalLayers=model.external),this._canonicalDataLayers}get canonicalMarkers(){const source=this.markers;return Object.is(source,this._canonicalMarkersSource)?this._canonicalMarkers:(this._canonicalMarkersSource=source,this._canonicalMarkers=projectMapMarkers(source),this._canonicalMarkers)}get drawingPending(){return this.drawingController?.pending===!0}get drawingWork(){return this.drawingController?.work??NO_DRAWING_WORK}get map(){return this._map}whenStyleReady(){return this.readiness.whenStyleReady()}whenControlsReady(){return this.controlsReadiness.whenReady()}whenIdle(){return this.readiness.whenIdle()}pushGeoJson(source,resolvedSourceId,geojson,projection=projectGeoJson(geojson)){const previous=this._appliedGeoJson.get(resolvedSourceId);if(previous===projection)return;const diff=typeof source.updateData=="function"&&previous!==void 0?buildProjectedGeoJsonPropertyDiff(previous,projection):null;diff===null||typeof source.updateData!="function"?source.setData(geojson):(diff.update.length>0||diff.add?.length||diff.remove?.length)&&source.updateData(diff),this._appliedGeoJson.set(resolvedSourceId,projection)}updateSourceData(sourceId,diff){if(!this._map||!this._styleLoaded||!this.isConnected||typeof sourceId!="string")return!1;const publicId=sourceId.trim(),resolved=this._appliedDataLayerIds.get(publicId)??(this.canonicalChoropleth?.sourceId===publicId?this._appliedChoroplethSourceId:void 0)??(this.ownedFeatures?.ownsGeoJsonSource(publicId)?publicId:void 0);if(!resolved)return!1;const source=this._map.getSource(resolved);return typeof source?.updateData!="function"?!1:(this._appliedGeoJson.delete(resolved),this.readiness.invalidate(),source.updateData(diff),this.readiness.check(),!0)}get safeMaxBounds(){const bounds=this.maxBounds;if(!Array.isArray(bounds)||bounds.length!==2)return null;const[southWest,northEast]=bounds;if(!Array.isArray(southWest)||!Array.isArray(northEast))return null;const[west,south]=southWest,[east,north]=northEast,values=[west,south,east,north].map(Number);if(!values.every(value=>Number.isFinite(value)))return null;const[w,s,e,n]=values;return w>=e||s>=n||w<-180||e>180||s<-90||n>90?null:[[w,s],[e,n]]}applyMaxBounds(){const map=this._map;if(!map||typeof map.setMaxBounds!="function")return;const bounds=this.safeMaxBounds;let zoomBefore,centerBefore;try{if(zoomBefore=map.getZoom(),centerBefore=map.getCenter(),this.constrainTo(map,bounds)||bounds!==null&&typeof zoomBefore=="number"&&Number.isFinite(zoomBefore)&&zoomBefore<1&&this.constrainFromWholeZoom(map,bounds,zoomBefore,centerBefore))return}catch{}try{map.setMaxBounds(null)}catch{}typeof zoomBefore=="number"&&Number.isFinite(zoomBefore)&&map.setZoom(zoomBefore),centerBefore&&map.setCenter([centerBefore.lng,centerBefore.lat]),devWarnOnce("lyra-map-max-bounds-rejected","<lr-map>: maxBounds left maplibre-gl without a usable camera, so it was dropped and the camera restored. This is a peer limitation, not a bad value -- it shows up at sub-1 fractional zooms in wide containers. Raise the zoom, narrow the box, or leave maxBounds unset.")}constrainTo(map,bounds){try{return map.setMaxBounds?.(bounds),bounds===null||Number.isFinite(map.getZoom())}catch{return!1}}applyZoomLimits(){const map=this._map;if(!map||typeof map.setMinZoom!="function"||typeof map.setMaxZoom!="function")return;const revision=++this.zoomLimitRevision,authoredZoom=this.zoom,minZoom=this.minZoom,maxZoom=this.maxZoom,connection=this._connectGeneration,generation=this._styleGeneration,style=this.mapStyle,[min,max]=this.zoomLimits,current=()=>this.isConnected&&this._map===map&&this.zoomLimitRevision===revision&&this._connectGeneration===connection&&this._styleGeneration===generation&&this.mapStyle===style&&Object.is(this.zoom,authoredZoom)&&Object.is(this.minZoom,minZoom)&&Object.is(this.maxZoom,maxZoom);this.writeCamera(()=>{try{const currentMax=map.getMaxZoom?.();typeof currentMax=="number"&&min>currentMax?(map.setMaxZoom(max),map.setMinZoom(min)):(map.setMinZoom(min),map.setMaxZoom(max))}catch{}}),!(!current()||this.zoom>=min&&this.zoom<=max)&&this.scheduleAfterUpdate(()=>{if(!current())return;const shown=readPeerCamera(map);if(!(!current()||!shown||this.zoom===shown.zoom)){this.reflectedCamera={center:shown.center,zoom:shown.zoom},this.reflectingCamera=!0;try{this.zoom=shown.zoom}finally{this.reflectingCamera=!1}}},`map-zoom-limits-${revision}`)}syncImageProvider(){const map=this._map,provider=this.imageProvider;if(!map)return;const apply=runtime2=>{this._map!==map||!this.isConnected||this.imageProvider!==provider||typeof provider!="function"&&!this.ownedFeatures||(this.ownedFeatures??=new runtime2.MapOwnedFeatures).configureImageProvider(map,provider,this)},runtime=loadMapOwnedFeatureRuntime.loaded;if(runtime){apply(runtime);return}if(typeof provider!="function"){this.ownedFeatures?.configureImageProvider(map,void 0,this);return}this.trackFeatureLoad(loadMapOwnedFeatureRuntime().then(apply,()=>{devWarnOnce("lyra-map-image-provider-runtime",`<${this.localName}>: the imageProvider runtime could not be loaded; missing images stay missing.`)}))}constrainFromWholeZoom(map,bounds,zoom,center){try{return map.setMaxBounds?.(null),map.setZoom(1),this.constrainTo(map,bounds)?(map.setZoom(zoom),map.setCenter([center.lng,center.lat]),Number.isFinite(map.getZoom())):!1}catch{return!1}}get safeZoom(){const[min,max]=this.zoomLimits;return finiteRange(this.zoom,2,min,max)}get safeCenter(){const center=Array.isArray(this.center)?this.center:[];return[finiteRange(Number(center[0]),0,-180,180),finiteRange(Number(center[1]),0,-90,90)]}fitBounds(bounds,options={}){const box=normalizeFitBounds(bounds);if(!box)return devWarnOnce("lyra-map-fit-bounds-rejected",`<${this.localName}>: fitBounds() ignored a box that is not [[west, south], [east, north]] with finite coordinates, latitudes in [-90, 90], south <= north, and longitudes in [-180, 180] (east may run past 180, up to one full turn east of west, for a box crossing the antimeridian).`),!1;const settings=typeof options=="object"&&options!==null?options:{},maxZoom=settings.maxZoom,fit=Object.freeze({bounds:box,padding:normalizeFitPadding(settings.padding),maxZoom:isFiniteCoordinate(maxZoom)?finiteRange(maxZoom,24,0,24):void 0,animate:settings.animate!==!1});return this.interruptCameraSession("external",!0)?(this.clusterZoomToken+=1,this.deferUntilCameraSettled(()=>this.executeFit(fit))?!0:this.executeFit(fit)):!1}executeFit(fit){const map=this._map;return map?(this.pendingFit=void 0,this.pendingCommand=void 0,this.applyFit(map,fit,fit.animate&&!prefersReducedMotion(this))):(this.pendingCommand=void 0,this.pendingFit=Object.freeze({fit,center:snapshotCenter(this.center),zoom:this.zoom}),!0)}deferUntilCameraSettled(run){return this.cameraUpdatePending?(this.deferredCameraWork.push(run),this.deferredCameraWork.length===1&&this.updateComplete.then(()=>{const work=this.deferredCameraWork;this.deferredCameraWork=[];for(const task of work)task()}),!0):!1}flyTo(options){return this.runCameraCommand("flyTo",options)}easeTo(options){return this.runCameraCommand("easeTo",options)}jumpTo(options){return this.runCameraCommand("jumpTo",options)}acquireCameraSession(callbacks){if(this.cameraSession)throw cameraSessionFailure("already-bound");const map=this._map;if(!map||!this.cameraSessionReady()||typeof map.getBearing!="function"||typeof map.getPitch!="function")throw cameraSessionFailure("unavailable");const owner={map,callbacks,connection:this._connectGeneration,revision:0,released:!1,interrupted:!1,markers:new WeakSet,stopMotion:()=>{},stopContext:()=>{}},current=()=>this.cameraSession===owner&&!owner.released&&this.isConnected&&this._map===map&&this._connectGeneration===owner.connection,prepared=new WeakMap,capture=()=>{if(!current()||typeof map.getBearing!="function"||typeof map.getPitch!="function")throw cameraSessionFailure("unavailable");try{const camera=readPeerCamera(map);if(!camera)throw cameraSessionFailure("unavailable");const result=admitMapViewpoint({...camera,bearing:map.getBearing(),pitch:map.getPitch()});if(!current())throw cameraSessionFailure("unavailable");return result}catch{throw cameraSessionFailure("unavailable")}},retire=(action,stopAnimation)=>{if(!current())return;owner.pendingAction===action&&(owner.pendingAction=void 0,owner.interrupted=!0);const active=owner.active;if(active?.action===action&&(owner.active=void 0,stopAnimation&&active.animated&&typeof map.stop=="function")){owner.stopping=active.marker;try{map.stop()}finally{owner.stopping===active.marker&&(owner.stopping=void 0)}}},lease={current,capture,reducedMotion:()=>prefersReducedMotion(this),start:action=>!current()||!this.cameraSessionReady()||owner.contextLost||owner.active||owner.pendingAction!==void 0&&owner.pendingAction!==action?!1:(owner.pendingAction=action,owner.interrupted=!1,!0),prepare:(action,input,transition)=>{if(!current()||!this.cameraSessionReady()||owner.contextLost)throw cameraSessionFailure("unavailable");const revision=owner.revision,style=this._styleGeneration,pending=owner.pendingAction,valid=()=>current()&&this.cameraSessionReady()&&!owner.contextLost&&owner.revision===revision&&this._styleGeneration===style&&owner.pendingAction===pending,accepted=admitMapViewpoint(input),reduced=prefersReducedMotion(this),kind=reduced?"jump":transition.kind,method=kind==="jump"?"jumpTo":kind==="ease"?"easeTo":"flyTo",readMoving=map.isMoving;if(typeof readMoving!="function"||!valid())throw cameraSessionFailure("unavailable");const moving=readMoving.call(map);if(typeof moving!="boolean"||!valid()||typeof map[method]!="function"||!valid()||(moving||kind!=="jump")&&(typeof map.stop!="function"||!valid()))throw cameraSessionFailure("unavailable");const command=Object.freeze({action,view:Object.freeze({...accepted,zoom:finiteRange(accepted.zoom,2,...this.zoomLimits)}),kind,...transition.duration===void 0?{}:{duration:transition.duration}});return prepared.set(command,{revision:owner.revision,style:this._styleGeneration,reduced}),command},commit:command=>{const admission=prepared.get(command);if(!admission)return!1;const pending=owner.pendingAction;if(pending!==void 0&&pending!==command.action)return!1;const valid=()=>current()&&this.cameraSessionReady()&&!owner.contextLost&&admission.revision===owner.revision&&admission.style===this._styleGeneration&&admission.reduced===prefersReducedMotion(this)&&owner.pendingAction===pending;if(!valid())return!1;prepared.delete(command);const method=command.kind==="jump"?"jumpTo":command.kind==="ease"?"easeTo":"flyTo";let move;try{let readMoving=map.isMoving;if(typeof readMoving!="function"||!valid())return!1;const moving=readMoving.call(map);if(typeof moving!="boolean"||!valid())return!1;if(moving||command.kind!=="jump"){const stop=map.stop;if(typeof stop!="function"||!valid()||moving&&(stop.call(map),!valid()||(readMoving=map.isMoving,typeof readMoving!="function"||!valid())||readMoving.call(map)!==!1||!valid()))return!1}if(move=map[method],typeof move!="function"||!valid())return!1}catch{return!1}owner.pendingAction=void 0,owner.revision+=1,owner.interrupted=!1;const marker={};owner.markers.add(marker);const active={action:command.action,marker,animated:command.kind!=="jump",invoking:!0,completionPending:!1};owner.active=active,this.pendingCommand=void 0,this.pendingFit=void 0,this.clusterZoomToken+=1,this.readiness.invalidate();try{move.call(map,{...command.view,center:[...command.view.center],...command.kind!=="jump"&&command.duration!==void 0?{duration:command.duration}:{}},{[SESSION_COMMAND_EVENT_KEY]:marker})}catch{return owner.active===active&&(owner.active=void 0),!1}finally{active.invoking=!1}return current()&&owner.active===active&&active.completionPending&&(owner.active=void 0,callbacks.complete(active.action)),!0},retire,release:()=>{if(!current())return;owner.pendingAction=void 0;const active=owner.active;active&&retire(active.action,!0),current()&&(owner.released=!0,owner.stopMotion(),owner.stopContext(),this.cameraSession=void 0)}};owner.lease=lease,this.cameraSession=owner;try{capture()}catch(error){throw lease.release(),error}try{owner.stopMotion=observeReducedMotion(this,reduced=>{current()&&callbacks.motion(reduced)});const canvas=map.getCanvas();if(!current()||!canvas||typeof canvas.addEventListener!="function"||typeof canvas.removeEventListener!="function")throw cameraSessionFailure("unavailable");const lost=()=>{owner.contextLost=!0,current()&&this.interruptCameraSession("engine",!1)},restored=()=>{owner.contextLost=!1};if(owner.stopContext=()=>{canvas.removeEventListener("webglcontextlost",lost),canvas.removeEventListener("webglcontextrestored",restored)},canvas.addEventListener("webglcontextlost",lost),!current()||(canvas.addEventListener("webglcontextrestored",restored),!current()))throw cameraSessionFailure("unavailable");return lease}catch{throw owner.stopMotion(),owner.stopContext(),owner.released=!0,this.cameraSession===owner&&(this.cameraSession=void 0),cameraSessionFailure("unavailable")}}cameraSessionReady(){return this.isConnected&&!!this._map&&this._styleLoaded&&!this.failure&&!this.preparingFeatures&&!this.mapUpdateActive&&!this.cameraUpdatePending&&this.deferredCameraWork.length===0&&this.cameraSessionConfigurationRevision===this.cameraSessionConfigurationApplied&&!this.sceneControlsRequestPending&&this.sceneConfiguration?.pending!==!0}interruptCameraSession(reason,stopAnimation){const owner=this.cameraSession;if(!owner||owner.released)return!0;const revision=++owner.revision;if(owner.pendingAction=void 0,owner.interrupted&&reason!=="disconnect"&&reason!=="engine")return!0;owner.interrupted=!0;const active=owner.active;owner.active=void 0;const retired=owner.callbacks.interrupt(reason)===!0;if(this.cameraSession===owner&&!owner.released&&owner.revision===revision&&!owner.active&&owner.pendingAction===void 0&&stopAnimation&&active?.animated&&typeof owner.map.stop=="function"){owner.stopping=active.marker;try{owner.map.stop()}finally{owner.stopping===active.marker&&(owner.stopping=void 0)}}const proceed=!this.cameraSession||this.cameraSession===owner&&owner.revision===revision&&owner.pendingAction===void 0;return retired&&reason!=="disconnect"&&this.isConnected&&this.emit("lr-map-camera-interrupt",Object.freeze({reason})),proceed}cameraSessionMovement(event){const owner=this.cameraSession;if(!owner||this.writingCamera)return;const marker=event?.[SESSION_COMMAND_EVENT_KEY];typeof marker=="object"&&marker!==null&&owner.markers.has(marker)||this.interruptCameraSession(event?.originalEvent?"user":"external",!1)}runCameraCommand(kind,options){const target=normalizeCameraOptions(options,this.zoomLimits);return target?this.interruptCameraSession("external",!0)?(this.clusterZoomToken+=1,this.deferUntilCameraSettled(()=>this.executeCameraCommand(kind,target))?!0:this.executeCameraCommand(kind,target)):!1:(devWarnOnce("lyra-map-camera-command-rejected",`<${this.localName}>: ${kind}() ignored options with no usable center, zoom, bearing or pitch (center is [longitude, latitude]; every number must be finite).`),!1)}executeCameraCommand(kind,target){const map=this._map;return this.pendingFit=void 0,this.pendingCommand=void 0,map?this.applyCameraCommand(map,kind,target,kind!=="jumpTo"&&!prefersReducedMotion(this)):(this.pendingCommand=Object.freeze({kind,target,center:snapshotCenter(this.center),zoom:this.zoom}),!0)}applyCameraCommand(map,kind,target,animate){const command=map[animate?kind:"jumpTo"];if(typeof command!="function")return!1;const{duration,...camera}=target;this.readiness.invalidate();try{command.call(map,{...camera,...animate&&duration!==void 0?{duration}:{}},{[COMMAND_EVENT_KEY]:this.commandToken})}catch{return!1}return!0}applyPendingCommand(){const map=this._map,pending=this.pendingCommand;!map||!pending||(this.pendingCommand=void 0,!(!sameCenterValue(this.center,pending.center)||!Object.is(this.zoom,pending.zoom))&&this.applyCameraCommand(map,pending.kind,pending.target,!1))}fitToData(options={}){const extent=emptyExtent();for(const marker of this.canonicalMarkers)extendExtent(extent,marker.lngLat[0],marker.lngLat[1]);for(const layer of this.canonicalDataLayers)extendExtentWithGeoJson(extent,layer.geojson);const choropleth=this.canonicalChoropleth;choropleth&&extendExtentWithGeoJson(extent,choropleth.geojson);const bounds=extentToBounds(extent);if(!bounds)return!1;const settings=typeof options=="object"&&options!==null?options:{};return this.fitBounds(bounds,{maxZoom:FIT_TO_DATA_MAX_ZOOM,...settings})}project(lngLat){const map=this._map;if(!(!map||typeof map.project!="function")&&!(!Array.isArray(lngLat)||!isFiniteCoordinate(lngLat[0])||!isFiniteCoordinate(lngLat[1])))try{const{x,y}=map.project([lngLat[0],lngLat[1]]);return isFiniteCoordinate(x)&&isFiniteCoordinate(y)?Object.freeze([x,y]):void 0}catch{return}}unproject(point){const map=this._map;if(!(!map||typeof map.unproject!="function")&&!(!Array.isArray(point)||!isFiniteCoordinate(point[0])||!isFiniteCoordinate(point[1])))try{const{lng,lat}=map.unproject([point[0],point[1]]);return isFiniteCoordinate(lng)&&isFiniteCoordinate(lat)?Object.freeze([wrapLongitude(lng),finiteRange(lat,0,-90,90)]):void 0}catch{return}}controlLocale(){const unitText=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");for(const[native,key]of[["ft","mapScaleFeet"],["m","mapScaleMeters"],["km","mapScaleKilometers"],["mi","mapScaleMiles"],["nm","mapScaleNauticalMiles"]])this.scaleLabels.set(native,key),this.scaleLabels.set(this.localize(MAP_SCALE_UNIT_MESSAGE[key]),key);return{"GeolocateControl.FindMyLocation":this.localize("mapGeolocateFindLocation"),"GeolocateControl.LocationNotAvailable":this.localize("mapGeolocateUnavailable"),"ScaleControl.Feet":unitText(this.localize("mapScaleFeet")),"ScaleControl.Meters":unitText(this.localize("mapScaleMeters")),"ScaleControl.Kilometers":unitText(this.localize("mapScaleKilometers")),"ScaleControl.Miles":unitText(this.localize("mapScaleMiles")),"ScaleControl.NauticalMiles":unitText(this.localize("mapScaleNauticalMiles"))}}syncControls(){const map=this._map;if(!map)return;const ready=this.controlsReadiness.begin(),input=this.controls,connection=this._connectGeneration,projected=normalizeMapControlOptions(input);this.setSceneControlIssue(!1);const wanted=new Map(projected.controls),attribution=isRuntimeRecord(input)?getOwnDataDescriptor(input,"attribution"):MISSING_OWN_DATA_DESCRIPTOR,defaultAttribution=attribution===MISSING_OWN_DATA_DESCRIPTOR||attribution!==UNSAFE_OWN_DATA_DESCRIPTOR&&attribution.value===void 0;(defaultAttribution||projected.diagnostics.some(issue=>issue.kind==="attribution"))&&wanted.set("attribution",normalizeMapControlOptions({attribution:!0}).controls.get("attribution")),this.setControlIssue(projected.diagnostics.length?"mapControlUnavailable":void 0);const current=()=>ready.isCurrent()&&this.isConnected&&this._map===map&&this.controls===input&&this._connectGeneration===connection,requested=[...projected.controls.values()].sort((a,b)=>a.order-b.order);if(this.setControlOutlines(this.controlLifecycle?[]:requested),projected.diagnostics.length&&ready.fail(),typeof map.addControl!="function"||typeof map.removeControl!="function"){this.setControlOutlines([]),wanted.size===0?ready.resolve():ready.fail();return}this.controlPeer?.map!==map&&(this.controlPeer={map,adapter:{addControl:(control,position)=>map.addControl(control,position),removeControl:control=>map.removeControl(control),controlContainer:position=>this.containerEl?.querySelector(`.maplibregl-ctrl-${position}`)??void 0}});const peer=this.controlPeer.adapter,run=({MapControlsLifecycle})=>{if(!current())return Promise.resolve();const lifecycle=this.controlLifecycle??=new MapControlsLifecycle(kind=>loadMapControl(kind,this.engine,this._maplibreModule)),synchronized=lifecycle.sync(peer,wanted,{isCurrent:current,scene:{isCurrent:current,state:kind=>({ready:this._styleLoaded&&!this.failure,busy:!this._styleLoaded||this.sceneControlsRequestPending||this.sceneConfiguration?.pending===!0,label:this.localize(kind==="globe"?"mapGlobe":"mapTerrain")}),unavailable:(kind,unavailable)=>{current()&&kind==="terrain"&&this.setSceneControlIssue(unavailable)}},onEvent:event=>{if(!current())return;if(event.kind==="scene-action"){if(event.action.kind==="globe"){const projection=event.action.pressed===!0?"mercator":"globe";this.projection=projection,this.emit("lr-map-projection-change",Object.freeze({projection,source:"control"}))}else{const terrain=event.action.pressed===!0?null:event.action.terrain;if(terrain===void 0)return;this.terrain=terrain,this.emit("lr-map-terrain-change",Object.freeze({terrain:this.terrain,source:"control"}))}return}if(event.kind==="geolocate-success"){this.pendingControlIssue!=="mapControlUnavailable"&&this.setControlIssue(void 0),event.lngLat&&event.accuracy!==void 0&&this.emit("lr-map-geolocate",{lngLat:event.lngLat,accuracy:event.accuracy});return}const issue=event.kind==="geolocate-out-of-bounds"?"mapGeolocateOutOfBounds":event.code==="permission-denied"?"mapGeolocatePermissionDenied":event.code==="position-unavailable"?"mapGeolocatePositionUnavailable":event.code==="timeout"?"mapGeolocateTimeout":"mapGeolocateError";this.setControlIssue(issue),this.announcements.announceAssertive(this.localize(MAP_CONFIGURATION_MESSAGE[issue])),event.kind==="geolocate-out-of-bounds"?this.emit("lr-map-geolocate-out-of-bounds",{code:event.code}):this.emit("lr-map-geolocate-error",{code:event.code})},onFailure:failure=>{current()&&(ready.fail(),this.setControlOutlines(this.pendingControlOutlines.filter(outline=>outline.kind!==failure.kind)),!(defaultAttribution&&failure.kind==="attribution")&&(this.setControlIssue("mapControlUnavailable"),this.announcements.announceAssertive(this.localize("mapControlUnavailable"))))}});if(current()){const pending=lifecycle.pendingKinds();this.setControlOutlines(requested.filter(outline=>pending.has(outline.kind)))}return synchronized},runtime=loadMapControlRuntime.loaded,sync=!this.controlLifecycle&&wanted.size===0?Promise.resolve():runtime?run(runtime):loadMapControlRuntime().then(run,()=>{current()&&(ready.fail(),[...wanted.keys()].some(kind=>!defaultAttribution||kind!=="attribution")&&(this.setControlIssue("mapControlUnavailable"),this.announcements.announceAssertive(this.localize("mapControlUnavailable"))))});this.trackFeatureLoad(Promise.race([ready.cancelled,sync.then(()=>{current()&&(this.syncPeerChromeParts(),current()&&(this.setControlOutlines([]),this.syncAttributionState(),this.controlLifecycle?.refreshSceneControls(),current()&&ready.resolve()))}).catch(()=>{current()&&(this.setControlOutlines([]),ready.fail())})]))}publishExportIssue(value){this.pendingExportIssue=value,this.scheduleAfterUpdate(()=>{this.exportIssue=this.pendingExportIssue},"map-export-feedback")}reportExportFailure(code){code!=="cancelled"&&(this.publishExportIssue(!0),this.announcements.announceAssertive(this.localize("mapExportUnavailable"))),this.emit("lr-map-export-error",Object.freeze({code}))}cancelImageExport(){this.exportController?.cancel()}exportImage(options){const map=this._map,style=this._styleGeneration,connection=this._connectGeneration;if(!map||!this.isConnected)return this.isConnected&&this.reportExportFailure("not-ready"),Promise.reject(new LyraMapImageExportError("not-ready"));let admitted,invalid=!1;if(options!==void 0)try{if(!isPlainDataRecord(options))throw new TypeError("Invalid export options.");const keys=Reflect.ownKeys(options);if(keys.length>2||keys.some(key=>key!=="type"&&key!=="attribution"))throw new TypeError("Invalid export options.");const snapshot={};for(const key of keys){const descriptor=getOwnDataDescriptor(options,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid export options.");snapshot[String(key)]=descriptor.value}admitted=Object.freeze(snapshot)}catch{invalid=!0}const request={map,style,connection,options:admitted,invalid},run=runtime2=>(this.exportController??=new runtime2.MapImageExportController(this.imageExportHost())).export(request),runtime=loadMapImageExportRuntime.loaded;return runtime?run(runtime):loadMapImageExportRuntime().then(run,()=>{const current=this.isConnected&&this._map===map&&this._styleGeneration===style&&this._connectGeneration===connection;throw current&&this.reportExportFailure("capture-failed"),new LyraMapImageExportError(current?"capture-failed":"cancelled")})}imageExportHost(){return{element:this,current:(map,style,connection)=>this.isConnected&&this._map===map&&this._styleGeneration===style&&this._connectGeneration===connection,generations:()=>[this.featureGeneration,this.drawingEpoch],pending:()=>this.isUpdatePending||this.preparingFeatures||this.drawingPending,onRender:(map,listener)=>this.peerEvents.subscribe(map,"render",listener),clearFeedback:()=>{this.publishExportIssue(!1)},fail:code=>{this.reportExportFailure(code)}}}closeAnchor(){return this.anchorController?.close("api")??!1}focusAnchor(){return this.anchorController?.focus()??!1}anchorRuntime(){if(this.anchorController)return this.anchorController;if(this.anchorLngLat===null||this.anchorLngLat===void 0)return;const runtime=this.anchorPlacementRuntime();return runtime&&(this.anchorController=new runtime.MapAnchorController(this.anchorHost()))}anchorPlacementRuntime(){const runtime=loadMapAnchorRuntime.loaded;if(runtime||this.anchorLoad)return runtime;this.anchorLoad="loading",loadMapAnchorRuntime().then(()=>{this.anchorLoad=void 0,this.isConnected&&this.scheduleAnchorSync()},()=>{this.anchorLoad="failed"})}anchorChildren(){if(this.childAnchors||![...this.childAnchorSet].some(anchor=>anchor.open))return this.childAnchors;const runtime=this.anchorPlacementRuntime();return this.childAnchors=runtime&&new runtime.MapAnchorChildren({...this.anchorMapHost(),engineReady:()=>this._styleLoaded||this.mapLoadEmitted,canvas:()=>{try{return this._map?.getCanvas?.()??null}catch{return null}}},this.childAnchorSet)}[MAP_ANCHOR_SEAM](anchor,operation,value){return operation==="attach"&&this.childAnchorSet.add(anchor),operation==="detach"&&this.childAnchorSet.delete(anchor),operation==="request"&&this.anchorLoad==="failed"&&(this.anchorLoad=void 0),this.anchorChildren()?.run(anchor,operation,value)}syncAnchor(){this.anchorRuntime()?.sync(),this.anchorChildren()?.sync()}scheduleAnchorSync(){this.anchorRuntime()?.schedule(),this.anchorChildren()?.schedule()}anchorMapHost(){return{element:this,container:()=>this.containerEl,map:()=>this._map,generations:()=>[this._styleGeneration,this._connectGeneration],updateActive:()=>this.mapUpdateActive,afterUpdate:(callback,key)=>{this.scheduleAfterUpdate(callback,key)},interactionBlocked:()=>this.mapInteractionBlocked(),direction:()=>this.effectiveDirection}}anchorHost(){return{...this.anchorMapHost(),key:"map-anchor",overlayHost:this,wrapper:()=>this.anchorEl,fence:()=>this.anchorBoundaryEl,content:()=>this.shadowRoot?.querySelector('slot[name="anchor"]'),styleLoaded:()=>this._styleLoaded,request:()=>this.anchorLngLat,boundary:()=>this.anchorBoundary,safeArea:()=>this.anchorSafeArea,closable:()=>this.anchorClosable,pending:()=>this.isUpdatePending,retire:()=>{this.anchorLngLat=null},emitClose:detail=>{this.emit("lr-map-anchor-close",detail)}}}zoomIntoCluster(publicSourceId,hit){const map=this._map,layer=this.canonicalDataLayers.find(entry=>entry.sourceId===publicSourceId);if(!map||!layer?.cluster?.zoomOnClick)return;const clusterId=hit?.properties?.cluster_id,geometry=hit?.geometry;if(typeof clusterId!="number"||geometry?.type!=="Point")return;const[lng,lat]=geometry.coordinates,resolvedId=this._appliedDataLayerIds.get(publicSourceId),source=resolvedId===void 0?void 0:map.getSource(resolvedId);if(!source||typeof source.getClusterExpansionZoom!="function")return;const token=++this.clusterZoomToken;let eased=!1;const ease=zoom=>{eased||token!==this.clusterZoomToken||this._map!==map||!isFiniteCoordinate(zoom)||this.canonicalDataLayers.find(entry=>entry.sourceId===publicSourceId)!==layer||this._appliedDataLayerIds.get(publicSourceId)!==resolvedId||map.getSource(resolvedId)!==source||(eased=!0,this.easeTo({center:[lng,lat],zoom}))};try{const pending=source.getClusterExpansionZoom(clusterId,(error,zoom)=>{error||ease(zoom)});pending&&typeof pending.then=="function"&&pending.then(ease,()=>{})}catch{}}applyCameraPadding(){const map=this._map;if(!map||typeof map.setPadding!="function")return;const next=normalizeFitPadding(this.cameraPadding),current=this.appliedPadding;next.top===current.top&&next.right===current.right&&next.bottom===current.bottom&&next.left===current.left||(this.appliedPadding=next,this.writeCamera(()=>{try{map.setPadding?.({...next})}catch{}}))}getVisibleBounds(options){const map=this._map;let padded=!0;try{padded=options?.padded!==!1}catch{}return map?this.readVisibleBounds(map,padded)??null:null}readVisibleBounds(map,padded=!0){try{const{top,right,bottom,left}=padded?this.appliedPadding:{top:0,right:0,bottom:0,left:0},container=this.containerEl;let west,south,east,north;const width=container?.clientWidth??0,height=container?.clientHeight??0;if((top||right||bottom||left)&&typeof map.unproject=="function"&&width-right>left&&height-bottom>top){const corners=[[left,top],[width-right,top],[width-right,height-bottom],[left,height-bottom]];west=south=1/0,east=north=-1/0;for(const[x,y]of corners){const{lng,lat}=map.unproject([x,y]);west=Math.min(west,lng),east=Math.max(east,lng),south=Math.min(south,lat),north=Math.max(north,lat)}}else{const box=map.getBounds?.();if(!box)return;west=box.getWest(),south=box.getSouth(),east=box.getEast(),north=box.getNorth()}if(![west,south,east,north].every(isFiniteCoordinate))return;const span=east-west;return span>=360?(west=-180,east=180):(west=wrapLongitude(west),east=west+span),Object.freeze([Object.freeze([west,finiteRange(south,0,-90,90)]),Object.freeze([east,finiteRange(north,0,-90,90)])])}catch{return}}scheduleMoveReport(map){if(this.moveFrame!==void 0)return;const view=ownerWindow(this);if(!view||typeof view.requestAnimationFrame!="function"){this.reportMove(map);return}this.moveFrame=view.requestAnimationFrame(()=>{this.moveFrame=void 0,this.reportMove(map)})}flushMoveReport(map){this.moveFrame!==void 0&&(this.cancelMoveReport(),this.reportMove(map))}cancelMoveReport(){this.moveFrame!==void 0&&(ownerWindow(this)?.cancelAnimationFrame?.(this.moveFrame),this.moveFrame=void 0)}reportMove(map){if(this._map!==map)return;this.syncAnchor();const camera=readPeerCamera(map);if(!camera)return;const bounds=this.readVisibleBounds(map);this.emit("lr-map-move",bounds?{...camera,bounds}:{...camera})}applyFit(map,fit,animate){if(typeof map.fitBounds!="function")return!1;const[[west,south],[east,north]]=fit.bounds,[minZoom,maxZoom]=this.zoomLimits,fitMaxZoom=fit.maxZoom!==void 0?finiteRange(fit.maxZoom,maxZoom,minZoom,maxZoom):this.zoomLimitsRequested?maxZoom:void 0;this.readiness.invalidate();try{map.fitBounds([[west,south],[east,north]],{padding:{...fit.padding},...fitMaxZoom===void 0?{}:{maxZoom:fitMaxZoom},animate},{[FIT_EVENT_KEY]:this.fitToken})}catch{return!1}return!0}applyPendingFit(){const map=this._map,pending=this.pendingFit;!map||!pending||(this.pendingFit=void 0,!(!sameCenterValue(this.center,pending.center)||!Object.is(this.zoom,pending.zoom))&&this.applyFit(map,pending.fit,!1))}reflectCamera(map,source){const camera=readPeerCamera(map);if(!camera)return;const center=Object.freeze(camera.center),{zoom}=camera;this.reflectedCamera={center,zoom};const previousCenter=this._center;this.reflectingCamera=!0;try{this._center=center,this.requestUpdate("center",previousCenter),this.zoom=zoom}finally{this.reflectingCamera=!1}const bounds=this.readVisibleBounds(map);this.emit("lr-map-view-change",bounds?{center,zoom,source,bounds}:{center,zoom,source})}pushCamera(changed){const reflected=this.reflectedCamera;this.reflectedCamera=void 0;const map=this._map;if(!map||!changed.has("center")&&!changed.has("zoom"))return;const center=this.safeCenter,zoom=this.safeZoom,shown=readPeerCamera(map),showsCenter=camera=>camera!==void 0&¢er[0]===camera.center[0]&¢er[1]===camera.center[1];let pushCenter=changed.has("center")&&!showsCenter(reflected)&&!showsCenter(shown),pushZoom=changed.has("zoom")&&zoom!==reflected?.zoom&&zoom!==shown?.zoom;if(!pushCenter&&!pushZoom)return;let interrupting=!1;try{interrupting=map.isMoving?.()===!0}catch{}interrupting&&(pushCenter=!showsCenter(shown),pushZoom=zoom!==shown?.zoom),this.writeCamera(()=>{pushCenter&&map.setCenter(center),pushZoom&&map.setZoom(zoom)})}writeCamera(write){const previous=this.writingCamera;this.readiness.invalidate(),this.writingCamera=!0;try{write()}finally{this.writingCamera=previous}}connectedCallback(){super.connectedCallback();const generation=++this._connectGeneration;this.observeMapInteractionState(),this.unregisterCameraSession?.(),this.unregisterCameraSession=registerMapCameraSession(this,{acquire:callbacks=>this.acquireCameraSession(callbacks)}),this.unregisterCustomLayers?.(),this.unregisterCustomLayers=registerMapCustomLayers(this,{acquire:callbacks=>this.acquireCustomLayer(callbacks)}),this.connectGeographicScene(),this.readiness.reset(),this.controlsReadiness.reset(),this.hashRuntimeFailed=!1,this.syncHash(),this.visible=!1,this.constructionScheduler?.disconnect();const scheduler=createMapConstructionScheduler(this,()=>{if(!this.isConnected||this._connectGeneration!==generation||this.constructionScheduler!==scheduler)return;this.visible=!0;const activator=this.shadowRoot?.activeElement?.matches?.('[part="initialization-activate"]')===!0;if(this.tryConstructMap(),activator&&this._map)try{this._map.getCanvas()?.focus?.({preventScroll:!0})}catch{}this.scheduleAfterUpdate(()=>{this.isConnected&&this._connectGeneration===generation&&this.constructionScheduler===scheduler&&this.requestUpdate()},`map-construction-${generation}`)});this.constructionScheduler=scheduler,this.constructionMode=this.initializationMode,this.constructionDelay=this.safeInitializationDelay,scheduler.connect(this.constructionMode,this.constructionDelay),this.failure=void 0,this.loading=!0,this._webglReady=!1,(async()=>{let mod;try{mod=await this.loadLibrary(this.engine)}catch{generation===this._connectGeneration&&this.isConnected&&this.failInitialization("missing-peer");return}if(!(generation!==this._connectGeneration||!this.isConnected)){if(this.loading=!1,!mod){this.failInitialization("missing-peer");return}if(this._maplibreModule=mod,!hasMapStyle(this.mapStyle)){this.failInitialization("style-required");return}if(!supportsWebGL2(this)){this.failInitialization("webgl-unavailable");return}this._webglReady=!0,await this.updateComplete,!(generation!==this._connectGeneration||!this.containerEl||!this.isConnected)&&this.constructionScheduler?.setReady(!0)}})()}disconnectedCallback(){super.disconnectedCallback(),this.stopObservingMapInteractionState(),this.interruptCameraSession("disconnect",!1);const session=this.cameraSession;session&&(session.released=!0,session.active=void 0,session.stopMotion(),session.stopContext(),this.cameraSession=void 0),this.unregisterCameraSession?.(),this.unregisterCameraSession=void 0,this.unregisterCustomLayers?.(),this.unregisterCustomLayers=void 0,this.notifyCustomLayers(callbacks=>callbacks.released()),this.customLayerCallbacks.clear(),this.closeGeographicScene(),this.hashOwner?.dispose(),this.disposeMap(),this.constructionScheduler?.disconnect(),this.constructionScheduler=void 0;for(const marker of this._markerInstances.values()){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove()}this._markerInstances.clear(),this._markerColors.clear(),this._markerLabels.clear(),this._markerPopupIds.clear(),this._markerSources.clear()}failureMessage(reason=this.failure??"initialization-failed"){switch(reason){case"missing-peer":return this.localize("mapMissingLibrary",void 0,{package:this.engine==="maplibre"?"maplibre-gl":"@aceshooting/lyra-map"});case"style-required":return this.localize("mapStyleRequired");case"webgl-unavailable":return this.localize("mapWebglUnavailable");case"initialization-failed":return this.localize("mapInitializationFailed")}}failInitialization(reason,partialMap){const connection=this._connectGeneration,generation=this._styleGeneration,style=this.mapStyle;this.readiness.fail(),this.controlsReadiness.fail();try{partialMap&&this.peerEvents.clear(partialMap),partialMap?.remove()}catch{}this.disposeMap(!1);const publish=()=>{!this.isConnected||this._connectGeneration!==connection||this._styleGeneration!==generation||this.mapStyle!==style||this._map||(this.loading=!1,this.failure=reason,this.announcements.announceAssertive(this.failureMessage(reason)))};this.mapUpdateActive?this.scheduleAfterUpdate(publish,`map-initialization-failure-${connection}-${generation}`):publish()}scheduleStyleRequiredFailure(){const generation=this._connectGeneration,module=this._maplibreModule;this.scheduleAfterUpdate(()=>{!this.isConnected||generation!==this._connectGeneration||module!==this._maplibreModule||hasMapStyle(this.mapStyle)||this.failInitialization("style-required")},"map-style-required")}disposeMap(cancelReadiness=!0){this.stopGeographicSceneRender(),this.notifyCustomLayers(callbacks=>callbacks.mapRemoved()),this.interruptCameraSession("engine",!1);const session=this.cameraSession;session&&(session.released=!0,session.stopMotion(),session.stopContext(),this.cameraSession=void 0),this.sceneConfiguration?.cancel(),this.sceneControlsRequestPending=!1,this.setSceneControlIssue(!1),this.cancelImageExport(),this.pendingExportIssue=!1,this.isConnected?this.publishExportIssue(!1):this.exportIssue=!1,this.cancelMapDrawing("disconnect"),this.drawingController?.cancelResources(),cancelReadiness&&(this.readiness.cancel(),this.controlsReadiness.cancel()),this.cancelFeaturePreparation(),this.pointerCleanup?.(),this.pointerCleanup=void 0,this.mapCursor.clear(),this.hovered=void 0,this.endPointerReports(!1),this.featureStates?.dispose(),this.featureStates=void 0,this.stateRouter.configure([]),this.featureStateLoad==="failed"&&(this.featureStateLoad=void 0),this.stateRequested=!1,this.stateRoutes=[],this.interactions=[],this.sourceIdentities.clear(),this.featureStateIssue=!1,this.preparedFeatureSignature=void 0,this.pendingMapLoad=!1,this.mapLoadEmitted=!1,this.rebuildGeneratedLayers=!1,this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.optionalFeatureWorkStarted=!1,this.controlLifecycle?.dispose(),this.controlPeer=void 0,this.attributionState=void 0,this.setControlOutlines([]),this._map&&this.peerEvents.clear(this._map);try{this._map?.remove()}catch{}this._map=void 0,this.drawingController?.disposeResources(),this.ownedFeatures?.dispose(),this.externalFeatures?.dispose(),this.externalSourceEffects?.dispose(),this.externalSourceEffects=void 0,this.externalFeatureWorkStarted=!1,this.externalSourceIds.clear(),this.plannedDataLayerIds.clear(),this.appliedRowRanges.clear(),this.dataLayerIssue=!1,this.pendingDataLayerIssue=!1,this.groupOrderActive=!1,this.basemapOrder?.reset(),this.pendingDrawingTheme=!1,this.setControlIssue(void 0),this.anchorController?.dispose(),this.childAnchors?.dispose(),this.cancelMoveReport(),this.appliedPadding=ZERO_CAMERA_PADDING,this._styleLoaded=!1,this._styleLayers=EMPTY_STYLE_LAYERS,this._styleSources=EMPTY_STYLE_SOURCES,this.boxZoomSettling=!1,this.reflectedCamera=void 0,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this.appliedChoroplethPaintKey=void 0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this.appliedLayerPaintKeys.clear(),this.appliedPointIcons.clear(),this.appliedPointPaint.clear(),this.appliedGeoLabels.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear()}adoptedCallback(){if(super.adoptedCallback(),this.observeMapInteractionState(),this.geographicSceneDocument&&this.geographicSceneDocument!==this.ownerDocument){this.interruptCameraSession("disconnect",!1);const session=this.cameraSession;session&&(session.released=!0,session.active=void 0,session.stopMotion(),session.stopContext(),this.cameraSession=void 0),this.closeGeographicScene(),this.isConnected&&this.connectGeographicScene()}this.hostDescription.adopted(),this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.announcements.adopted(),this._map&&this.containerEl&&this.isConnected&&this.observeMapAllocation(this._map,this.containerEl)}tryConstructMap(){if(this.mapUpdateActive){const connection=this._connectGeneration;this.scheduleAfterUpdate(()=>{this.isConnected&&this._connectGeneration===connection&&this.tryConstructMap()},`map-construct-${connection}`);return}if(this._map||!this._maplibreModule||!this._webglReady||!this.containerEl||!this.visible||!this.isConnected)return;if(!hasMapStyle(this.mapStyle)){this.scheduleStyleRequiredFailure();return}const mod=this._maplibreModule,authoredCenter=this.center,authoredZoom=this.zoom,option=this.hashOption;if(this.syncHash(),!this.hashOwner&&this.hashRequested()&&!this.hashRuntimeFailed)return;const initialHash=this.hashOwner?.read()??{status:"disabled"},hashCamera=initialHash.status==="camera"?initialHash.camera:void 0;let candidate;try{candidate=new mod.Map({container:this.containerEl,style:this.mapStyle,center:hashCamera?[...hashCamera.center]:this.safeCenter,zoom:hashCamera?finiteRange(hashCamera.zoom,this.safeZoom,...this.zoomLimits):this.safeZoom,...this.zoomLimitsRequested?{minZoom:this.zoomLimits[0],maxZoom:this.zoomLimits[1]}:{},...hashCamera?{bearing:hashCamera.bearing,pitch:hashCamera.pitch}:{},attributionControl:!1,...typeof this.renderWorldCopies=="boolean"?{renderWorldCopies:this.renderWorldCopies}:{},locale:{"Map.Title":this.effectiveMapLabel,"Marker.Title":this.localize("mapMarker"),"Popup.Close":this.localize("close"),"AttributionControl.ToggleAttribution":this.localize("mapToggleAttribution"),"AttributionControl.MapFeedback":this.localize("mapFeedback"),"NavigationControl.ZoomIn":this.localize("zoomIn"),"NavigationControl.ZoomOut":this.localize("zoomOut"),"NavigationControl.ResetBearing":this.localize("mapResetNorth"),...this.controlLocale()}}),this.peerEvents.subscribe(candidate,"error",event=>{if(this._map===candidate){if(!this._styleLoaded){this.failInitialization("initialization-failed");return}console.error("lr-map:",event?.error??event)}}),this.peerEvents.subscribe(candidate,"load",()=>{this._map!==candidate||this.mapLoadEmitted||(this.pendingMapLoad=!0,this.flushMapLoad(candidate),this.readiness.whenStyleReady().then(()=>{this.flushMapLoad(candidate)},()=>{}))}),this.peerEvents.subscribe(candidate,"click",event=>{this._map===candidate&&this.handleMapInteraction("click",event)}),this.peerEvents.subscribe(candidate,"contextmenu",event=>{this._map===candidate&&this.handleMapInteraction("contextmenu",event)}),this.peerEvents.subscribe(candidate,"mousemove",event=>{this._map===candidate&&(this.schedulePointerReport(candidate,event),this.drawingController?.preview(mapCoordinates(mapOwnValue(event,"lngLat"))),this.handleMapInteraction("mousemove",event))}),this.peerEvents.subscribe(candidate,"mouseout",()=>{this._map===candidate&&(this.clearMapHover(),this.endPointerReports(),this.drawingController?.preview(void 0))}),this.peerEvents.subscribe(candidate,"movestart",event=>{this._map===candidate&&(event?.originalEvent&&(this.clusterZoomToken+=1),this.cameraSessionMovement(event))}),this.peerEvents.subscribe(candidate,"boxzoomstart",event=>{this._map===candidate&&(this.clusterZoomToken+=1,this.cameraSessionMovement(event))});for(const eventName of["dragstart","zoomstart","rotatestart","pitchstart"])this.peerEvents.subscribe(candidate,eventName,event=>{this._map===candidate&&this.cameraSessionMovement(event)});this.peerEvents.subscribe(candidate,"boxzoomend",()=>{this._map===candidate&&(this.boxZoomSettling=!0)}),this.peerEvents.subscribe(candidate,"move",()=>{this._map===candidate&&(this.anchorController?.invalidate(),this.childAnchors?.invalidate(),this.scheduleMoveReport(candidate),this.drawingController?.scheduleHandles())}),this.peerEvents.subscribe(candidate,"moveend",event=>{if(this._map!==candidate||(this.flushMoveReport(candidate),this.writeHash(candidate),this._map!==candidate))return;const fit=event?.[FIT_EVENT_KEY]===this.fitToken,session=this.cameraSession,sessionMarker=event?.[SESSION_COMMAND_EVENT_KEY],sessionAction=session?.active&&session.active.marker===sessionMarker?session.active:void 0,sessionStopping=sessionMarker!==void 0&&session?.stopping===sessionMarker,command=event?.[COMMAND_EVENT_KEY]===this.commandToken||sessionAction!==void 0||sessionStopping,afterBoxZoom=!fit&&!command&&this.boxZoomSettling;if(!fit&&!command&&(this.boxZoomSettling=!1),this.writingCamera)return;const source=fit?"fit":command?"command":event?.originalEvent||afterBoxZoom?"user":void 0;source&&this.reflectCamera(candidate,source),session&&sessionAction&&this.cameraSession===session&&session.active===sessionAction&&!session.released&&(sessionAction.invoking?sessionAction.completionPending=!0:(session.active=void 0,session.callbacks.complete(sessionAction.action)))});const canvas=candidate.getCanvas?.();if(canvas&¬ifyMapCanvasReady(this,canvas),this._map=candidate,canvas&&this.observeMapInteractions(canvas),this.beginStyleReadiness(candidate,!0),!this.isConnected||this._map!==candidate||(this.syncMapSemantics(),this.observeMapAllocation(candidate,this.containerEl),this.syncGeographicSceneRender(),!this.isConnected||this._map!==candidate))return;this.observePeerChrome(),this.failure=void 0}catch{this.failInitialization("initialization-failed",candidate);return}if(this.applyMaxBounds(),!this.isConnected||this._map!==candidate)return;if(hashCamera){this.pendingFit=void 0;const connection=this._connectGeneration,shown=readPeerCamera(this._map);if(!this.isConnected||this._map!==candidate||this._connectGeneration!==connection)return;shown&&this.hashOption===option&&this.center===authoredCenter&&this.zoom===authoredZoom&&(this.reflectedCamera={center:shown.center,zoom:shown.zoom},this.scheduleAfterUpdate(()=>{if(!(!this.isConnected||this._map!==candidate||this._connectGeneration!==connection||this.hashOption!==option||this.center!==authoredCenter||this.zoom!==authoredZoom)){this.reflectingCamera=!0;try{this.center=shown.center,this.zoom=shown.zoom}finally{this.reflectingCamera=!1}}},`map-initial-hash-${connection}`))}this.applyCameraPadding(),this.syncControls(),this.syncAnchor(),this.syncImageProvider();const initialized=this._map;this.pendingFit?this.scheduleAfterUpdate(()=>{this._map===initialized&&(this.applyPendingFit(),initialized&&this.writeHash(initialized))},"map-pending-fit"):this.pendingCommand?this.scheduleAfterUpdate(()=>{this._map===initialized&&(this.applyPendingCommand(),initialized&&this.writeHash(initialized))},"map-pending-command"):initialized&&this.writeHash(initialized)}flushMapLoad(map=this._map){!map||this._map!==map||!this.isConnected||!this.pendingMapLoad||!this._styleLoaded||this.preparingFeatures||this.sceneConfiguration?.pending||this.isUpdatePending||(this.pendingMapLoad=!1,this.mapLoadEmitted=!0,this.emit("lr-map-load"))}beginStyleReadiness(map,initial,mutate,waitForStyleLoad=!1){const connection=this._connectGeneration,styleGeneration=this._styleGeneration,style=this.mapStyle,current=()=>this.isConnected&&this._map===map&&connection===this._connectGeneration&&styleGeneration===this._styleGeneration&&style===this.mapStyle;let started=!1;const startRestoration=()=>{started||!current()||(started=!0,this._styleLoaded=!0,this.captureStyleCatalog(map),this.geographicSceneRender?.styleReady(),current()&&(this.notifyCustomLayers(callbacks=>callbacks.styleReady(map)),current()&&(this.syncSceneConfiguration(),this.controlLifecycle?.refreshSceneControls(),current()&&(this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this.appliedChoroplethPaintKey=void 0,this._appliedDataLayerIds.clear(),this.plannedDataLayerIds.clear(),this.appliedRowRanges.clear(),this._appliedDataLayerShapes.clear(),this.appliedLayerPaintKeys.clear(),this.appliedPointPaint.clear(),this.appliedGeoLabels.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear(),this.rebuildGeneratedLayers=!0,initial&&this.applyMarkers(),this.reconcileGeneratedLayers(),this.anchorLngLat?this.scheduleAnchorSync():this.childAnchors?.schedule()))))};this.readiness.bind({subscribe:(event,listener)=>{const types=event==="style-ready"?["load","style.load"]:event==="busy"?["movestart","move","dataloading"]:[event];let active=!0;const removers=[],dispose=()=>{active=!1;for(const remove of removers)try{remove()}catch{}};try{for(const type of types)removers.push(this.peerEvents.subscribe(map,type,()=>{if(!(!active||!current()))try{event==="style-ready"&&startRestoration(),active&¤t()&&listener()}catch{current()&&this.readiness.fail()}}))}catch(error){throw dispose(),error}return dispose},mutate:initial?mutate:()=>{this.peerEvents.rotate(map),current()&&mutate?.()},isStyleReady:()=>{if(waitForStyleLoad)return!1;const ready=typeof map.isStyleLoaded=="function"?map.isStyleLoaded()===!0:typeof map.loaded=="function"&&map.loaded()===!0;return ready&&startRestoration(),ready},isIdle:()=>typeof map.isMoving=="function"&&map.isMoving()?!1:typeof map.loaded=="function"?map.loaded()===!0:void 0,ownerPending:()=>this.isUpdatePending||this.preparingFeatures||this.drawingPending||this.sceneConfiguration?.pending===!0||this.featureLoads>0||!current(),restore:async signal=>{if(!current()||signal.aborted)return;startRestoration();let work=this.featureWork,drawingWork=this.drawingWork,sceneWork=this.sceneConfiguration?.work;for(;;){if(await Promise.all([work,drawingWork,sceneWork]),!current()||signal.aborted||this.isUpdatePending&&(await this.updateComplete,!current()||signal.aborted)||work===this.featureWork&&drawingWork===this.drawingWork&&sceneWork===this.sceneConfiguration?.work)return;work=this.featureWork,drawingWork=this.drawingWork,sceneWork=this.sceneConfiguration?.work}},onStyleReady:generation=>{this.emit("lr-map-style-load",{generation})},onIdle:generation=>{this.emit("lr-map-idle",{generation})},onError:styleWasReady=>{styleWasReady||this._styleLoaded&&!this.preparingFeatures&&this.mapLoadEmitted||this.scheduleAfterUpdate(()=>{current()&&this.failInitialization("initialization-failed")},`map-readiness-failure-${styleGeneration}`)}})}requestUpdate(...args){args[0]===void 0&&(this.geoJsonRefreshRequested=!0),args[0]==="zoom"&&!this.reflectingCamera&&(this.zoomLimitRevision=(this.zoomLimitRevision??0)+1),super.requestUpdate(...args);const valueChanged=args[0]===void 0||!Object.is(args[1],Reflect.get(this,args[0]));if(this.isConnected&&valueChanged&&["mapStyle","projection","terrain","minZoom","maxZoom","maxBounds","cameraPadding"].includes(String(args[0]))&&(this.cameraSessionConfigurationRevision+=1),this.cameraSession&&valueChanged&&!this.reflectingCamera){const property2=args[0];if(property2==="mapStyle"||property2==="projection"||property2==="terrain")this.interruptCameraSession("style",!0);else if(property2==="minZoom"||property2==="maxZoom"||property2==="maxBounds"||property2==="cameraPadding")this.interruptCameraSession("external",!0);else if(property2==="center"||property2==="zoom"){const shown=this._map&&readPeerCamera(this._map);(property2==="center"?shown&&sameCenterValue(this.safeCenter,shown.center):shown?.zoom===this.safeZoom)||(this.cameraUpdatePending=!0,this.interruptCameraSession("external",!0))}}if((args[0]==="projection"||args[0]==="terrain")&&this.isUpdatePending&&(this.sceneRequest=(this.sceneRequest??0)+1,this.sceneControlsRequestPending=!0,this.controlLifecycle?.refreshSceneControls()),valueChanged&&args[0]==="mapStyle"&&this.isUpdatePending&&(this.sceneControlsRequestPending=!0,this.controlLifecycle?.refreshSceneControls()),valueChanged&&(args[0]===void 0||["mapStyle","dataLayers","choropleth","overlays","images","styleOverrides","interactiveBasemapLayers"].includes(String(args[0])))&&(this.drawingConfigRevision=(this.drawingConfigRevision??0)+1),valueChanged&&(args[0]===void 0||["anchorLngLat","anchorBoundary","anchorSafeArea","anchorClosable","mapStyle","dir"].includes(String(args[0])))){this.anchorSyncRequested=!0,args[0]==="anchorLngLat"&&this.anchorLoad==="failed"&&(this.anchorLoad=void 0);const anchor=this.anchorController;anchor&&!anchor.closing&&(args[0]==="mapStyle"||args[0]==="anchorLngLat"&&!this.anchorLngLat)?anchor.hide(!0,!0):anchor?.stop()}const drawing=this.drawingController?.active===!0;valueChanged&&!this.drawingResetting&&args[0]==="drawMode"&&(drawing||args[1]==="line"||args[1]==="polygon")&&this.cancelMapDrawing("mode-change",!0,args[1]==="polygon"?"polygon":"line"),valueChanged&&args[0]==="drawMode"&&this.drawingLoad==="failed"&&(this.drawingLoad=void 0),valueChanged&&args[0]==="pickMode"&&this.pickMode&&(drawing||this.drawMode==="line"||this.drawMode==="polygon")&&this.cancelMapDrawing("pick-mode"),valueChanged&&this.isUpdatePending&&(args[0]===void 0||["mapStyle","dataLayers","choropleth","overlays","images","styleOverrides","interactiveBasemapLayers"].includes(String(args[0])))&&(this.interactionGeneration=(this.interactionGeneration??0)+1,this.featureStates?.cancel()),valueChanged&&args[0]==="controls"&&this.controlsReadiness&&this.isConnected&&this.isUpdatePending&&(this.controlsReadiness.reset(),this.failure&&this.controlsReadiness.fail()),valueChanged&&this.readiness&&this.isConnected&&this.isUpdatePending&&(args[0]==="mapStyle"&&!Object.is(args[1],this.mapStyle)?(this.sceneConfiguration?.cancel(),this.readiness.reset()):(args[0]===void 0||["projection","terrain","center","zoom","minZoom","maxZoom","cameraPadding","maxBounds","dataLayers","choropleth","markers","hiddenCategories","overlays","images","styleOverrides","interactiveBasemapLayers"].includes(String(args[0])))&&this.readiness.invalidate()),(args[0]==="center"||args[0]==="zoom")&&this.isUpdatePending&&!this.reflectingCamera&&(this.clusterZoomToken+=1,this.cameraUpdatePending=!0),this.isUpdatePending&&(args[0]===void 0||["label","lang","locale","strings","markers","legend","legendGradient","hasLegendSlot","hasLegendStartSlot","choropleth","choroplethLegend"].includes(String(args[0])))&&(this.semanticsStale=!0),this.isUpdatePending&&(args[0]===void 0||["label","lang","locale","strings","markers"].includes(String(args[0])))&&(this.markerSemanticsStale=!0)}performUpdate(){this.mapUpdateActive=!0;try{super.performUpdate()}finally{this.mapUpdateActive=!1}}updated(changed){if(super.updated(changed),changed.has("failure")&&this.syncGeographicSceneStatus(),this.sceneRepairFocus&&(this.sceneRepairFocus=!1,this.shadowRoot?.querySelector('[part="scene-toggle"]')?.focus({preventScroll:!0})),this.cameraUpdatePending=!1,this.setAttribute("aria-busy",String(this.loading||!this._map&&!this.failure&&!this.awaitingActivation)),this.legendCollapsed&&(changed.has("legendOpen")||changed.has("legendCollapsible"))){const legend=this.shadowRoot?.querySelector('[part="legend"]');legend&&(legend.scrollTop=0)}if((changed.has("choropleth")||changed.has("legendGradient"))&&this.warnOnLegendChoroplethMismatch(),changed.has("mapStyle")&&(this.cancelImageExport(),this.drawingController?.styleChanging(),this.drawingController?.cancelResources(!0),this._styleGeneration+=1,this.basemapOrder?.reset(),this.cancelFeaturePreparation(),this.preparedFeatureSignature=void 0,this.featureStateLoad==="failed"&&(this.featureStateLoad=void 0)),!changed.has("mapStyle")&&(changed.has("projection")||changed.has("terrain"))&&this.syncSceneConfiguration(),changed.has("imageProvider")&&this._map&&this.syncImageProvider(),changed.has("mapStyle")&&!hasMapStyle(this.mapStyle)&&this._maplibreModule)this.scheduleStyleRequiredFailure();else if(changed.has("mapStyle")&&!this._map&&this._maplibreModule&&hasMapStyle(this.mapStyle))this.tryConstructMap();else if(changed.has("mapStyle")&&this._map){const replaceStyle=typeof this._map.prepareFeatures=="function"||typeof this.mapStyle=="string"||!this._styleLoaded;this._styleLoaded=!1,this._styleLayers=EMPTY_STYLE_LAYERS,this._styleSources=EMPTY_STYLE_SOURCES;const map2=this._map;this.beginStyleReadiness(map2,!1,()=>{for(const sourceId of this.appliedPointIcons.keys())this.removePointIcons(sourceId);this.geographicSceneRender?.invalidateStyle(),this.notifyCustomLayers(callbacks=>callbacks.styleInvalidated()),!(!this.isConnected||this._map!==map2)&&map2.setStyle(this.mapStyle,replaceStyle?{diff:!1}:void 0)},replaceStyle)}else this._styleLoaded&&(this.refreshingGeoJson||changed.has("dataLayers")||changed.has("choropleth")||changed.has("overlays")||changed.has("images")||changed.has("styleOverrides")||changed.has("interactiveBasemapLayers")||changed.has("imageProvider")&&this.preparingFeatures)&&this.reconcileGeneratedLayers();this.sceneControlsRequestPending=!1,this.controlLifecycle?.refreshSceneControls();const constructionMode=this.initializationMode,constructionDelay=this.safeInitializationDelay;(changed.has("initialization")||changed.has("initializationDelay"))&&(constructionMode!==this.constructionMode||constructionMode==="interaction"&&constructionDelay!==this.constructionDelay)&&(this.constructionMode=constructionMode,this.constructionDelay=constructionDelay,this.constructionScheduler?.reconfigure(constructionMode,constructionDelay)),this.constructionScheduler?.setReady(!!this.containerEl&&this._webglReady&&!!this._maplibreModule&&hasMapStyle(this.mapStyle)),changed.has("hiddenCategories")&&this._map&&this._styleLoaded&&this.refreshThemePaint(),changed.has("cameraPadding")&&this._map&&(this.applyCameraPadding(),this.geographicSceneRender?.refreshAllocation()),this.pushCamera(changed),changed.has("maxBounds")&&this._map&&this.writeCamera(()=>this.applyMaxBounds()),(changed.has("minZoom")||changed.has("maxZoom"))&&this._map&&this.applyZoomLimits(),changed.has("controls")&&this._map&&this.syncControls(),changed.has("drawingMeasurements")&&this.drawingController?.scheduleHandles(),(changed.has("pickMode")||changed.has("interactionBlocked"))&&(this.clearMapHover(),this.syncMapCursor()),(changed.has("hash")||changed.has("hashFormat"))&&(this.syncHash(),this.applyHash()),this._map&&(this.anchorSyncRequested||["anchorLngLat","anchorBoundary","anchorSafeArea","anchorClosable","dir","strings","lang","locale"].some(name=>changed.has(name)))&&(this.anchorSyncRequested=!1,this.syncAnchor()),changed.has("markers")&&this._map&&this.applyMarkers(),this.semanticsStale&&(this.semanticsStale=!1,this.syncMapSemantics(this.markerSemanticsStale),this.markerSemanticsStale=!1),this.drawingConfigApplied=this.drawingConfigApplying,this.cameraSessionConfigurationApplied=this.cameraSessionConfigurationApplying,this.syncDrawing(),this.readiness.check();const map=this._map;this.pendingMapLoad&&queueMicrotask(()=>{this.flushMapLoad(map)})}willUpdate(changed){if(this.drawingConfigApplying=this.drawingConfigRevision,this.cameraSessionConfigurationApplying=this.cameraSessionConfigurationRevision,super.willUpdate(changed),(this.anchorLngLat!=null||[...this.childAnchorSet].some(anchor=>anchor.open))&&this.effectiveDirection,this.refreshingGeoJson=this.geoJsonRefreshRequested,this.geoJsonRefreshRequested=!1,this.refreshingGeoJson){const choropleth=this.canonicalChoropleth;choropleth&&(this._canonicalChoropleth={...choropleth,geojsonProjection:projectAdmittedGeoJson(choropleth.geojson,!0)}),this._canonicalDataLayers=this.canonicalDataLayers.map(layer=>({...layer,geojsonProjection:projectAdmittedGeoJson(layer.geojson,!0)}))}(changed.has("legendGradient")||changed.has("dataLayers"))&&(this.legendIsLine=this.legendDescribesLine()),this.derivedLegend=this.choroplethLegend&&this.canonicalChoropleth?buildDerivedChoroplethLegend(this.canonicalChoropleth,value=>this.formatCount(value),this.localize("noData")):EMPTY_DERIVED_LEGEND,changed.has("mapStyle")&&!this._map&&this._maplibreModule&&hasMapStyle(this.mapStyle)&&(this._webglReady||(this._webglReady=supportsWebGL2(this)),this.failure=this._webglReady?void 0:"webgl-unavailable",this._webglReady||(this.loading=!1,this.announcements.announceAssertive(this.failureMessage("webgl-unavailable"))))}syncPaintTheme(){const sources=[this.dataLayers,this.choropleth,this.styleOverrides,this.overlays,loadMapOwnedFeatureRuntime.loaded];if(!this.paintThemeSources||sources.some((source,index)=>source!==this.paintThemeSources[index])){this.paintThemeSources=sources;const tokens2=new Set([...Object.values(TONE_TOKEN),...Object.values(ON_TONE_TOKEN),"--lr-map-choropleth-fill-opacity","--lr-map-hidden-category-opacity",DRAWING_COLOR_TOKEN]),inputs=JSON.stringify([this.canonicalDataLayers.map(({geojson:_geojson,geojsonProjection:_projection,...paint})=>paint),[this.canonicalChoropleth?.stops,this.canonicalChoropleth?.stepBaseColor,this.canonicalChoropleth?.noData],loadMapOwnedFeatureRuntime.loaded?.projectMapStyleOverrides(this.styleOverrides),this._canonicalExternalLayers.map(({source:_source,...paint})=>paint)]),overlayPaint=loadMapOwnedFeatureRuntime.loaded?.overlayPaintText(this.overlays)??"";for(const match of overlayPaint.matchAll(/var\(\s*(--[\w-]+)/g))tokens2.add(match[1]);for(const match of inputs.matchAll(/var\(\s*(--[\w-]+)/g))tokens2.add(match[1]);this.paintThemeTokens=[...tokens2]}const style=ownerWindow(this)?.getComputedStyle(this);if(!style)return!1;const tokens=new Set(this.paintThemeTokens),values=[style.color,style.colorScheme];for(const token of tokens){const value=style.getPropertyValue(token).trim();if(values.push(token,value),tokens.size<512)for(const match of value.matchAll(/var\(\s*(--[\w-]+)/g))tokens.add(match[1])}const key=JSON.stringify(values);return this.paintThemeKey===key?!1:(this.paintThemeKey=key,paintColorCache.delete(this),this.appliedLayerPaintKeys.clear(),this.appliedChoroplethPaintKey=void 0,!0)}withMapPaintBatch(apply){const map=this._map;if(!map||!this._styleLoaded||!this.isConnected)return!1;const style=this._styleGeneration,connection=this._connectGeneration,generation=this.featureGeneration,styleInput=this.mapStyle,data=this.dataLayers,choropleth=this.choropleth,hidden=this.hiddenCategories,current=()=>this.isConnected&&this._map===map&&this._styleLoaded&&this._styleGeneration===style&&this._connectGeneration===connection&&this.featureGeneration===generation&&this.mapStyle===styleInput&&this.dataLayers===data&&this.choropleth===choropleth&&this.hiddenCategories===hidden,previous=this.mapPaintBatchActive;this.mapPaintBatchActive=!0;try{return this.mapPaintBatch.run(map,style,current,apply),!0}catch(error){return this.appliedLayerPaintKeys.clear(),this.appliedChoroplethPaintKey=void 0,error instanceof DOMException&&error.name==="AbortError"?this.scheduleAfterUpdate(()=>{this.isConnected&&this._map&&this._styleLoaded&&this.reconcileGeneratedLayers()},"map-paint-reconcile"):current()&&this.failInitialization("initialization-failed"),!1}finally{this.mapPaintBatchActive=previous}}removeMapLayer(id){this.mapPaintBatch.invalidate(id),this._map?.removeLayer(id)}setMapPaint(id,property2,value){this.mapPaintBatchActive?this.mapPaintBatch.write(id,property2,value):this.withMapPaintBatch(()=>{this.mapPaintBatch.write(id,property2,value)})}refreshThemePaint(){return this._canonicalExternalLayers.length||this.externalFeatureWorkStarted||this.optionalFeatureWorkStarted||ownedFeaturesRequested(this.overlays,this.images,this.styleOverrides)?(paintColorCache.delete(this),this.appliedLayerPaintKeys.clear(),this.appliedChoroplethPaintKey=void 0,this.pendingDrawingTheme=!0,this.reconcileGeneratedLayers(),!0):(this.withMapPaintBatch(()=>this.refreshThemePaintBatch()),!1)}refreshThemePaintBatch(){if(paintColorCache.delete(this),!this._map||!this._styleLoaded)return;if(this.preparingFeatures){(this._canonicalExternalLayers.length||this.externalFeatureWorkStarted)&&this.appliedLayerPaintKeys.clear();return}this.readiness.invalidate();const fillOpacity=choroplethFillOpacity(this);if(this._appliedFillLayerId){const choropleth=this.canonicalChoropleth;choropleth&&choropleth.stops.length>0&&this.setMapPaint(this._appliedFillLayerId,"fill-color",this.choroplethColorExpression(choropleth)),this.setMapPaint(this._appliedFillLayerId,"fill-opacity",fillOpacity)}const dataLayersBySourceId=new Map(this.canonicalDataLayers.map(layer=>[layer.sourceId,layer]));for(const[publicSourceId,sourceId]of this._appliedDataLayerIds){const dataLayer=dataLayersBySourceId.get(publicSourceId);if(!dataLayer)continue;this.paintDataLayer(sourceId,dataLayer);const{geojson:_geojson,geojsonProjection:_projection,...paint}=dataLayer;this.appliedLayerPaintKeys.set(sourceId,JSON.stringify(paint))}}setFeatureState(target,patch){if(!this.canWriteFeatureState())return!1;const states=this.featureStateRuntime();if(!states)return!1;const accepted=states.set(target,patch).accepted;return accepted&&(this.stateRequested=!0,this.flushFeatureState()),accepted}getFeatureState(target){return this.featureStates?.get(target)}removeFeatureState(target,key){if(!this.canWriteFeatureState())return!1;const states=this.featureStateRuntime();if(!states)return!1;const accepted=states.remove(target,key).accepted;return accepted&&(this.stateRequested=!0,this.flushFeatureState()),accepted}featureStateRuntime(){if(this.featureStates)return this.featureStates;const runtime=loadMapFeatureStateRuntime.loaded;if(runtime){const states=new runtime.MapFeatureStateRoutes;return states.configure(this.stateRoutes),this.featureStates=states}this.featureStateLoad||(this.featureStateLoad="loading",this.trackFeatureLoad(loadMapFeatureStateRuntime().then(()=>{this.featureStateLoad=void 0},()=>{this.featureStateLoad="failed",this.isConnected&&(this.featureStateIssue=!0)})))}canWriteFeatureState(){const map=this._map,generation=this.interactionGeneration;return!!(map&&this.isConnected&&this._styleLoaded&&!this.preparingFeatures&&!this.isUpdatePending&&featureStatePeer(map)&&this._map===map&&generation===this.interactionGeneration&&!this.isUpdatePending)}flushFeatureState(){const map=this._map,generation=this.interactionGeneration;map&&(this.readiness.invalidate(),this.replayFeatureStates(map,()=>this.isConnected&&this._map===map&&generation===this.interactionGeneration&&!this.isUpdatePending),this.readiness.check())}replayFeatureStates(map,current,signal){if(!this.stateRequested||!current())return;if(!this.stateRoutingAvailable){this.featureStateIssue=!0,this.readiness.fail();return}const states=this.featureStates,result=states&&featureStatePeer(map)?states.replay(map,this._styleGeneration,signal,current):void 0;if(current()){if(!result?.accepted||result.diagnostics.length){this.featureStateIssue=!0,this.readiness.fail();return}if(this.featureStateIssue=!1,result.applied)try{map.triggerRepaint?.()}catch{current()&&(this.featureStateIssue=!0,this.readiness.fail())}}}sourceToken(origin,source,data,shape){const key=JSON.stringify([origin,source]),previous=this.sourceIdentities.get(key);if(previous&&Object.is(previous.data,data)&&previous.shape===shape)return previous.token;const token=Object.freeze({});return this.sourceIdentities.set(key,{data,shape,token}),token}basemapInteractionTargets(){const opted=projectMapBasemapInteractions(this.interactiveBasemapLayers);if(opted)return expandMapStyleLayerTargets(opted,this._styleLayers,entry=>entry).map(({layerId,entry})=>({layerId,interactive:entry.interactive,priority:entry.priority}))}get styleLayers(){return this._styleLayers}get styleSources(){return this._styleSources}captureStyleCatalog(map){let layers=[],sources=[];try{const style=map.getStyle?.(),rawLayers=mapOwnValue(style,"layers"),rawSources=mapOwnValue(style,"sources");if(Array.isArray(rawLayers))for(const layer of rawLayers.slice(0,4096)){const id=mapOwnValue(layer,"id"),type=mapOwnValue(layer,"type"),source=mapOwnValue(layer,"source"),sourceLayer=mapOwnValue(layer,"source-layer");typeof id!="string"||typeof type!="string"||layers.push(Object.freeze({id,type,...typeof source=="string"?{source}:{},...typeof sourceLayer=="string"?{sourceLayer}:{}}))}if(isPlainDataRecord(rawSources))for(const id of Object.keys(rawSources).slice(0,1024)){const type=mapOwnValue(mapOwnValue(rawSources,id),"type");typeof type=="string"&&sources.push(Object.freeze({id,type}))}}catch{layers=[],sources=[]}this._styleLayers=layers.length?Object.freeze(layers):EMPTY_STYLE_LAYERS,this._styleSources=sources.length?Object.freeze(sources):EMPTY_STYLE_SOURCES}mapStateDefinitions(owned){const routes=[],map=this._map;this.stateRoutingAvailable=!0;let identityText=0;if(!map)return routes;const generation=this.interactionGeneration,current=()=>this._map===map&&generation===this.interactionGeneration&&this.isConnected,add=(origin,source,nativeSource,data,shape,sourceLayers)=>{if(identityText+=typeof data=="string"?data.length:0,routes.length>=256||identityText>1048576){this.stateRoutingAvailable=!1;return}routes.push({origin,source,nativeSource,identity:this.sourceToken(origin,source,data,shape),...sourceLayers?{sourceLayers}:{}})},choropleth=this.canonicalChoropleth;choropleth&&add("choropleth",choropleth.sourceId,this._appliedChoroplethSourceId??"",choropleth.geojson,"geojson");for(const row of this.canonicalDataLayers)add("data-layer",row.sourceId,this._appliedDataLayerIds.get(row.sourceId)??"",row.geojson,dataLayerShape(row));for(const row of this._canonicalExternalLayers)row.sourceLayer&&add("data-layer",row.sourceId,this.externalSourceIds.get(row.sourceId)??"",JSON.stringify(row.source),row.sourceLayer,[row.sourceLayer]);for(const source of owned.sources){if(!this.stateRoutingAvailable)break;const type=source.source.type,layers=[...new Set(owned.layers.filter(row=>row.layer.source===source.id).map(row=>row.layer["source-layer"]).filter(value=>typeof value=="string"))].sort();(type==="geojson"||type==="vector"&&layers.length)&&add("overlay",source.id,source.id,...sourceIdentity(source.source,layers),type==="vector"?layers:void 0)}const opted=this.basemapInteractionTargets();if(opted?.length&&this.stateRoutingAvailable){const nativeOwned=new Set([...routes.map(route=>route.nativeSource),...owned.sources.map(source=>source.id),...this.externalSourceIds.values(),...[...this.externalSourceIds.values()].map(id=>`${id}-hit-source`),...this.drawingController?.sourceId?[this.drawingController.sourceId]:[]]),style=map.getStyle?.()??this.mapStyle;if(!current())return[];const sources=mapOwnValue(style,"sources"),groups=new Map;for(const option of opted){const layer=map.getLayer(option.layerId);if(!current())return[];const source=mapOwnValue(layer,"source"),sourceLayer=mapOwnValue(layer,"source-layer");if(!option.interactive||typeof source!="string"||nativeOwned.has(source))continue;let group=groups.get(source);group||groups.set(source,group=new Set),typeof sourceLayer=="string"&&group.add(sourceLayer)}for(const[id,group]of groups){if(!this.stateRoutingAvailable)break;const raw=mapOwnValue(sources,id);let snapshot;const admit=loadMapOwnedFeatureRuntime.loaded?.snapshotMapOwnedFeatureInput;if(!admit)continue;try{snapshot=admit({overlays:{sources:[{id,source:raw}],layers:[]},images:[],styleOverrides:[]})}catch{if(current())continue;return[]}if(!current())return[];const source=snapshot.overlays.sources[0]?.source,type=source?.type,layers=[...group].sort();source&&(type==="geojson"||type==="vector"&&layers.length)&&add("basemap",id,id,...sourceIdentity(source,layers),type==="vector"?layers:void 0)}}return this.stateRoutingAvailable?routes:[]}prepareStateRetirement(owned){const generation=this.interactionGeneration,map=this._map,desired=this.mapStateDefinitions(owned);if(generation!==this.interactionGeneration||map!==this._map)return;for(const old of this.stateRoutes){const next=desired.find(route=>route.origin===old.origin&&route.source===old.source);(!next||next.identity!==old.identity)&&this.featureStates?.invalidateNative(old.origin,old.nativeSource)}const keys=new Set(desired.map(route=>JSON.stringify([route.origin,route.source])));for(const key of this.sourceIdentities.keys())keys.has(key)||this.sourceIdentities.delete(key)}configureMapInteractions(owned,external){const generation=this.interactionGeneration,map=this._map,current=()=>generation===this.interactionGeneration&&map===this._map&&this.isConnected,routes=this.mapStateDefinitions(owned);if(!current())return;const states=this.featureStates;(states?states.configure(routes).accepted&&this.stateRouter.configure(routes):this.stateRouter.configure(routes))?this.stateRoutes=routes:(states?.configure([]),this.stateRouter.configure([]),this.stateRoutes=[],this.stateRequested&&(this.featureStateIssue=!0,this.readiness.fail()));const rules=[],add=(layerId,origin,source,options,sourceLayer,cluster=!1)=>{rules.push({layerId,owner:origin==="basemap"?"basemap":"overlay",origin,source,interactive:options.interactive??!0,priority:options.priority??0,...sourceLayer?{sourceLayer}:{},...cluster?{cluster}:{}})},choropleth=this.canonicalChoropleth;choropleth&&this._appliedFillLayerId&&add(this._appliedFillLayerId,"choropleth",choropleth.sourceId,choropleth);for(const row of this.canonicalDataLayers){const native=this._appliedDataLayerIds.get(row.sourceId);if(native)for(const suffix of QUERYABLE_DATA_LAYER_SUFFIXES)add(`${native}${suffix}`,"data-layer",row.sourceId,row,void 0,suffix==="-cluster")}for(const[layerId,hit]of external.hits){const row=this._canonicalExternalLayers.find(entry=>entry.sourceId===hit.sourceId);row&&add(layerId,"data-layer",row.sourceId,{...row,interactive:row.interactive&&!(row.category&&this.hiddenCategories.includes(row.category))},hit.sourceLayer)}for(const row of owned.layers){const source=row.layer.source,sourceLayer=row.layer["source-layer"];typeof source=="string"&&add(row.layer.id,"overlay",source,row,typeof sourceLayer=="string"?sourceLayer:void 0)}const opted=this.basemapInteractionTargets();if(opted)for(const row of opted){if(this.drawingController?.ownsLayer(row.layerId)===!0||rules.some(rule=>rule.layerId===row.layerId))continue;const layer=map?.getLayer(row.layerId);if(!current())return;const source=mapOwnValue(layer,"source"),sourceLayer=mapOwnValue(layer,"source-layer");typeof source=="string"&&!routes.some(route=>route.origin!=="basemap"&&route.nativeSource===source)&&add(row.layerId,"basemap",source,row,typeof sourceLayer=="string"?sourceLayer:void 0)}current()&&(this.interactions=Object.freeze(rules))}drawingActionAllowed(){return this.isConnected&&!!this._map&&this._styleLoaded&&!this.preparingFeatures&&this.drawingConfigRevision===this.drawingConfigApplied&&!this.mapInteractionBlocked()}mapInteractionAllowed(){return!this.isConnected||!this._map||!this._styleLoaded||this.preparingFeatures||this.isUpdatePending?!1:!this.mapInteractionBlocked()}mapInteractionBlocked(){for(let node=this;node;node=flattenedParentElement(node))if(node.hasAttribute("inert")||node===this&&node.hasAttribute("disabled"))return!0;return!1}syncMapCursor(){const map=this._map,generation=this.interactionGeneration;if(!map||!this.mapInteractionAllowed()){this.mapCursor.clear();return}try{const canvas=map.getCanvas();if(this._map!==map||generation!==this.interactionGeneration||!this.mapInteractionAllowed())return;this.mapCursor.set(canvas,this.pickMode?"pick":this.drawingController?.active?"drawing":this.hovered?"hover":void 0)}catch{this._map===map&&generation===this.interactionGeneration&&this.mapCursor.clear()}}stopObservingMapInteractionState(){const observer=this.interactionObserver;this.interactionObserver=void 0,observer?.disconnect()}observeMapInteractionState(){if(this.stopObservingMapInteractionState(),!this.isConnected)return;this.interactionBlocked=this.mapInteractionBlocked();const document=this.ownerDocument,generation=this._connectGeneration,MutationObserverCtor=document.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const current=()=>this.isConnected&&this.ownerDocument===document&&this._connectGeneration===generation&&this.interactionObserver===observer,observer=new MutationObserverCtor(()=>{if(!current())return;const blocked=this.mapInteractionBlocked(),map=this._map;this.interactionBlocked=blocked;const unchanged=()=>current()&&this._map===map&&this.mapInteractionBlocked()===blocked;if(blocked){if(this.cancelMapDrawing("disabled"),!unchanged()||(this.clearMapHover(),!unchanged())||(this.anchorController?.hide(),!unchanged()))return;this.childAnchors?.hide()}else this.syncMapCursor(),unchanged()&&this.scheduleAnchorSync()});this.interactionObserver=observer;for(let node=this;node;node=flattenedParentElement(node))observer.observe(node,{attributes:!0,attributeFilter:["inert","disabled"]})}observeMapInteractions(canvas){const map=this._map,current=()=>this._map===map&&this.isConnected,cancel=()=>{current()&&(this.cancelMapDrawing("pointercancel"),this.drawingController?.active||(this.clearMapHover(),this.mapCursor.clear()))},down=()=>{this.suppressDrawingClick=!1},click=event=>{this.suppressDrawingClick&&(this.suppressDrawingClick=!1,event.preventDefault(),event.stopImmediatePropagation())},key=event=>{!current()||!this.keyboardActivation||event.key!=="Enter"&&event.key!==" "||event.repeat||event.isComposing||event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey||this.pickMode||this.drawMode!=="none"||this.drawingController?.active||!this.mapInteractionAllowed()||(event.preventDefault(),this.activateMapCenter())};canvas.addEventListener("pointercancel",cancel,!0),canvas.addEventListener("pointerdown",down,!0),canvas.addEventListener("click",click,!0),canvas.addEventListener("keydown",key),this.pointerCleanup=()=>{canvas.removeEventListener("pointercancel",cancel,!0),canvas.removeEventListener("pointerdown",down,!0),canvas.removeEventListener("click",click,!0),canvas.removeEventListener("keydown",key)}}schedulePointerReport(map,event){const lngLat=mapCoordinates(mapOwnValue(event,"lngLat")),point=mapOwnValue(event,"point"),x=mapOwnValue(point,"x"),y=mapOwnValue(point,"y");if(!lngLat||!isFiniteCoordinate(x)||!isFiniteCoordinate(y)||(this.pendingPointer=Object.freeze({lngLat:Object.freeze([wrapLongitude(lngLat[0]),lngLat[1]]),point:Object.freeze([x,y])}),this.pointerFrame!==void 0))return;const report=()=>{this.pointerFrame=void 0;const detail=this.pendingPointer;this.pendingPointer=void 0,!(!detail||this._map!==map||!this.isConnected||this.mapInteractionBlocked())&&(this.pointerInside=!0,this.emit("lr-map-pointer-move",detail))},view=ownerWindow(this);if(!view||typeof view.requestAnimationFrame!="function"){report();return}this.pointerFrame=view.requestAnimationFrame(report)}endPointerReports(emit=!0){this.pointerFrame!==void 0&&ownerWindow(this)?.cancelAnimationFrame?.(this.pointerFrame),this.pointerFrame=void 0,this.pendingPointer=void 0;const inside=this.pointerInside;this.pointerInside=!1,inside&&emit&&this.isConnected&&this.emit("lr-map-pointer-leave")}clearMapHover(){const previous=this.hovered;this.hovered=void 0,this.mapCursor.clear(),previous&&this.isConnected&&this.emit("lr-map-feature-leave",previous.detail)}editDrawing(snapshot){return this.drawingLoad==="failed"&&(this.drawingLoad=void 0),this.drawingRuntime()?.edit(snapshot)??!1}undoDrawing(){return this.drawingController?.undo()??!1}completeDrawing(){return this.drawingController?.complete()??!1}cancelDrawing(){return this.cancelMapDrawing("cancel")}cancelMapDrawing(reason,keepMode=!1,armedMode=this.drawMode){const drawing=this.drawingController;return drawing?drawing.cancel(reason,keepMode,armedMode):armedMode!=="line"&&armedMode!=="polygon"?!1:(this.drawingIssue=void 0,keepMode||this.resetDrawingMode(),this.drawingEpoch++,this.syncMapCursor(),this.emit("lr-map-draw-cancel",Object.freeze({mode:armedMode,phase:"cancelled",vertices:Object.freeze([]),reason})),!0)}resetDrawingMode(){this.drawingResetting=!0;try{this.drawMode="none"}finally{this.drawingResetting=!1}}syncDrawing(){if(this.mapUpdateActive){this.scheduleAfterUpdate(()=>this.syncDrawing(),"map-sync-drawing");return}const drawing=this.drawingController;if(drawing){drawing.sync();return}if(this.pickMode){this.cancelMapDrawing("pick-mode");return}if(this.mapInteractionBlocked()){this.cancelMapDrawing("disabled");return}(this.drawMode==="line"||this.drawMode==="polygon")&&this.drawingRuntime()?.sync()}drawingRuntime(){if(this.drawingController)return this.drawingController;const runtime=loadMapDrawingRuntime.loaded;if(runtime)return this.drawingController=new runtime.MapDrawingController(this.drawingHost());this.drawingLoad||(this.drawingLoad="loading",this.trackFeatureLoad(loadMapDrawingRuntime().then(()=>{this.drawingLoad=void 0,this.isConnected&&this.syncDrawing()},()=>{this.drawingLoad="failed",this.isConnected&&this.showDrawingError()})))}drawingHost(){return{element:this,map:()=>this._map,styleLoaded:()=>this._styleLoaded,generations:()=>[this._styleGeneration,this._connectGeneration],usable:()=>!this.loading&&!this.failure,epoch:()=>this.drawingEpoch,advanceEpoch:()=>{this.drawingEpoch++},actionAllowed:()=>this.drawingActionAllowed(),interactionAllowed:()=>this.mapInteractionAllowed(),interactionBlocked:()=>this.mapInteractionBlocked(),updateActive:()=>this.mapUpdateActive,afterUpdate:(callback,key)=>{this.scheduleAfterUpdate(callback,key)},emit:(type,state2)=>{this.emit(type,state2)},emitCancel:detail=>{this.emit("lr-map-draw-cancel",detail)},emitVertexEnd:detail=>{this.emit("lr-map-draw-vertex-end",detail)},showError:error=>{this.showDrawingError(error)},clearError:()=>{this.drawingIssue=void 0},resetMode:()=>{this.resetDrawingMode()},suppressClick:()=>{this.suppressDrawingClick=!0},syncCursor:()=>{this.syncMapCursor()},changed:()=>{this.drawingRevision+=1},invalidate:()=>{this.readiness.invalidate()},check:()=>{this.readiness.check()},fail:()=>{this.readiness.fail()},direction:()=>this.effectiveDirection,accentColor:()=>resolvedLayerColor(this,`var(${DRAWING_COLOR_TOKEN})`,"accent"),resolve:(value,property2)=>this.resolveStyleOverride(value,property2)}}showDrawingError(error){this.drawingIssue=error==="invalid-coordinate"?"mapDrawingInvalidCoordinate":error==="duplicate-vertex"?"mapDrawingDuplicateVertex":error==="vertex-limit"?"mapDrawingVertexLimit":error==="too-few-vertices"||error==="empty"?"mapDrawingTooFewVertices":error&&error!=="inactive"?"mapDrawingInvalidGeometry":"mapDrawingUnavailable",this.announcements.announceAssertive(this.drawingErrorMessage())}drawingErrorMessage(){return this.localize(MAP_DRAWING_MESSAGE[this.drawingIssue],void 0,{count:this.drawingIssue==="mapDrawingVertexLimit"?512:this.drawMode==="polygon"?3:2})}activateMapCenter(){const map=this._map;if(map)try{const lngLat=mapCoordinates(map.getCenter());if(!lngLat||this._map!==map)return;const point=map.project?.([lngLat[0],lngLat[1]]),x=point?.x,y=point?.y;if(!isFiniteCoordinate(x)||!isFiniteCoordinate(y)||this._map!==map)return;this.handleMapInteraction("click",{point:{x,y},lngLat:{lng:lngLat[0],lat:lngLat[1]}},"keyboard")}catch{}}handleMapInteraction(kind,event,trigger="pointer"){const drawing=this.drawingController;if(kind==="click"&&trigger==="pointer"&&(this.suppressDrawingClick||drawing?.consumeClick())){this.suppressDrawingClick=!1;return}if(drawing?.dispatching)return;if(this.queryingMap){this.interactionQuery++;return}if(!this.mapInteractionAllowed()){this.clearMapHover();return}const map=this._map,generation=this.interactionGeneration,query2=++this.interactionQuery,style=this.mapStyle,current=()=>this._map===map&&generation===this.interactionGeneration&&query2===this.interactionQuery&&style===this.mapStyle&&this.mapInteractionAllowed();let lngLat,hit,rule,raw;this.queryingMap=!0;try{if(lngLat=mapCoordinates(mapOwnValue(event,"lngLat")),!lngLat||!current())return;if(kind==="click"&&drawing?.active&&!this.pickMode){drawing.editing||drawing.add(lngLat);return}let features;const rules=this.interactions;let zoom=Number.NaN;try{zoom=map.getZoom()}catch{}const result=queryMapHit({getLayer:id=>{const layer=map.getLayer(id),rule2=rules.find(rule3=>rule3.layerId===id),origin2=rule2?.origin;if(origin2==="data-layer"&&Number.isFinite(zoom)){const row=this.committedDataLayers.find(row2=>row2.sourceId===rule2?.source)??this.committedExternalLayers.find(row2=>row2.sourceId===rule2?.source);if(row&&(zoom<row.minZoom||zoom>=row.maxZoom))return}return layer&&mapLayerHittable(map,id,layer,zoom,origin2==="overlay"||origin2==="basemap")?layer:void 0},queryRenderedFeatures:(point,options)=>(features=map.queryRenderedFeatures([point.x,point.y],{layers:[...options.layers]}),features)},mapOwnValue(event,"point"),rules.map(({layerId,owner,interactive,priority})=>({layerId,owner,interactive,priority})),{current});if(!current()||result.status!=="hit"&&result.status!=="none")return;if(result.status==="hit"){if(rule=rules.find(row=>row.layerId===result.hit.layerId),!rule)return;const native=result.hit,target=native.id===void 0?void 0:this.stateRouter.resolve({origin:rule.origin,source:rule.source,id:native.id,...rule.sourceLayer?{sourceLayer:rule.sourceLayer}:{}});hit=Object.freeze({layerId:native.layerId,origin:rule.origin,source:rule.source,properties:native.properties,...native.id===void 0?{}:{id:native.id},...rule.sourceLayer?{sourceLayer:rule.sourceLayer}:{},...target?{target}:{}}),raw=mapOwnValue(features,String(result.featureIndex))}if(!current())return}finally{this.queryingMap=!1}if(!lngLat)return;const interaction=()=>Object.freeze({lngLat,...hit?{hit,feature:detachedMapFeature(raw,hit)}:{}});if(kind==="mousemove"){const key=hit?JSON.stringify([hit.origin,hit.source,hit.sourceLayer??null,hit.layerId,hit.id===void 0?["anonymous",query2]:["id",hit.id]]):void 0;if(key!==this.hovered?.key){if(this.clearMapHover(),!current())return;if(hit&&key){const detail=interaction();this.hovered={key,detail},this.emit("lr-map-feature-enter",detail)}}current()&&this.syncMapCursor();return}if(kind==="contextmenu"){this.emit("lr-map-contextmenu",interaction());return}if(this.pickMode){this.emit("lr-map-pick",Object.freeze({...interaction(),trigger:"pointer"}));return}const clickToken=++this.clusterZoomToken,origin=rule?.cluster?"cluster":rule?.origin,choropleth=this.canonicalChoropleth,noData=origin==="choropleth"&&choropleth?.noData!==void 0&&typeof hit?.properties[choropleth.field]!="number";this.emit("lr-map-click",{lngLat,feature:raw,origin,sourceId:origin==="choropleth"?void 0:rule?.source,...rule?.sourceLayer?{sourceLayer:rule.sourceLayer}:{},...hit?{hit,...hit.target?{target:hit.target}:{}}:{},...noData?{noData:!0}:{},...trigger==="keyboard"?{trigger}:{}}),origin==="cluster"&&rule&&clickToken===this.clusterZoomToken&¤t()&&this.zoomIntoCluster(rule.source,raw)}cancelFeaturePreparation(){this.interactionGeneration++,this.featureStates?.cancel(),this.clearMapHover(),this.ownedFeatures?.cancel(),this.externalFeatures?.cancel(),this.finishFeatureWork?.(),this.finishFeatureWork=void 0,this.featureGeneration+=1,this.featureAbort?.abort(),this.featureAbort=void 0,this.preparingFeatures=!1}generatedFeatureRequirements(){const sources={},layers=[],add=(source,types)=>{for(const[index,type]of types.entries())layers.push({id:`${source}-${type}-${index}`,type,source})},choropleth=this.canonicalChoropleth;choropleth&&(sources.choropleth={type:"geojson",data:choropleth.geojson},choropleth.stops.length&&add("choropleth",["fill"]));for(const[index,layer]of this.canonicalDataLayers.entries()){const source=`data-${index}`,cluster=layer.cluster;sources[source]={type:"geojson",data:layer.geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}},layer.kind==="heatmap"?add(source,["heatmap"]):(add(source,cluster?["circle"]:["fill","line","circle"]),(layer.label||cluster&&this.styleProvidesGlyphs()||layer.point?.iconField&&layer.point.icons.length)&&add(source,["symbol"]))}return{sources,layers}}externalLayerInput(owned,identities){identities.externalStyle!==this._styleGeneration&&(identities.externalStyle=this._styleGeneration,identities.external.clear());const reserved=new Set([...owned.sources.map(source=>source.id),...owned.layers.map(layer=>layer.layer.id)]),available=(id,retained)=>!reserved.has(id)&&!reserved.has(`${id}-render`)&&!reserved.has(`${id}-label`)&&!reserved.has(`${id}-hit`)&&!reserved.has(`${id}-hit-source`)&&(!this._map?.getSource(`${id}-hit-source`)&&!this._map?.getLayer(`${id}-hit`)||this.externalFeatures?.ownsLayer(`${id}-hit`)===!0)&&(retained||!this._map?.getSource(id)&&!this._map?.getLayer(`${id}-render`)&&!this._map?.getLayer(`${id}-label`));return buildMapExternalLayers(this._canonicalExternalLayers,{nativeId:row=>{const previous=identities.external.get(row.sourceId);if(previous&&available(previous,this.externalFeatures?.ownsLayer(`${previous}-render`)===!0))return previous;for(let index=0;index<512;index++){const id=`lr-external-layer-${identities.nextExternal++}`;if(available(id,!1))return identities.external.set(row.sourceId,id),id}throw new Error("Map source identity is unavailable.")},color:value=>resolvedLayerColor(this,value,"accent"),styleColor:value=>{const color=resolvedMapPaintColor(this,value,!0);if(!color)throw new Error("Map color could not be resolved.");return color},hidden:new Set(this.hiddenCategories),glyphs:this.styleProvidesGlyphs(),mutedOpacity:hiddenCategoryOpacity(this)})}dataLayerOrderGroups(owned,external,identities){const groups=[];for(const row of this.canonicalDataLayers){const native=this.resolveDataLayerSourceId(row,identities),suffixes=row.kind==="heatmap"?["-heatmap"]:row.cluster?["-cluster",...this.styleProvidesGlyphs()?["-cluster-count"]:[],"-circle"]:["-fill","-line","-circle"];row.kind!=="heatmap"&&row.point?.iconField&&row.point.icons.length&&suffixes.push("-point-icon"),row.label&&suffixes.push("-label"),groups.push({id:row.sourceId,layerIds:suffixes.map(suffix=>`${native}${suffix}`),...row.before?{before:row.before}:{}})}for(const row of this._canonicalExternalLayers){const source=identities.external.get(row.sourceId),layerIds=external.layers.filter(entry=>entry.layer.source===source||entry.layer.source===`${source}-hit-source`).map(entry=>entry.layer.id);groups.push({id:row.sourceId,layerIds,...row.before?{before:row.before}:{}})}for(const entry of owned.layers)groups.push({id:entry.layer.id,layerIds:[entry.layer.id],...entry.before?{before:entry.before}:{}});return groups}nativeLayerOrder(map){const layers=mapOwnValue(map.getStyle?.(),"layers");return Array.isArray(layers)?layers.map(layer=>mapOwnValue(layer,"id")).filter(id=>typeof id=="string"):[]}applyDataLayerOrder(groups,current,basemap){const map=this._map;if(!map||!current())return;const original=this.nativeLayerOrder(map);if(!current())return;const present=new Set(original),active=groups.map(group=>({...group,layerIds:group.layerIds.filter(id=>present.has(id))})).filter(group=>group.layerIds.length),runtime=loadMapOwnedFeatureRuntime.loaded;if(!runtime)throw new Error("Map layer order is unavailable.");const plan=basemap?basemap.plan(original,active):runtime.planMapLayerOrder(original,active);if(!plan.valid||plan.operations.some(operation=>operation.kind!=="move")||plan.operations.length&&!map.moveLayer)throw new Error("Map layer order is unavailable.");if(!basemap){try{for(const operation of plan.operations)if(!current()||(map.moveLayer(operation.id,operation.before),!current()))return}catch(error){const members=new Set(active.flatMap(group=>group.layerIds));for(let index=original.length-1;index>=0&¤t();index--){const id=original[index];if(members.has(id))try{map.moveLayer(id,original[index+1])}catch{break}}throw error}return}const sameOrder=(left,right)=>left.length===right.length&&left.every((id,index)=>id===right[index]),advance=(order,operation)=>{order.splice(order.indexOf(operation.id),1),order.splice(operation.before===void 0?order.length:order.indexOf(operation.before),0,operation.id)};let attempted=0;try{for(const operation of plan.operations)if(!current()||(attempted+=1,map.moveLayer(operation.id,operation.before),!current()))return;const shown=this.nativeLayerOrder(map);if(!current())return;if(!sameOrder(shown,plan.order))throw new Error("Map layer order was not applied.");basemap.commit(plan.order)}catch(error){if(!current())throw error;const shown=this.nativeLayerOrder(map);if(!current())throw error;const prefix=[...original];let rollbackSafe=sameOrder(shown,prefix);for(const operation of plan.operations.slice(0,attempted))advance(prefix,operation),rollbackSafe||=sameOrder(shown,prefix);const members=new Set(plan.operations.slice(0,attempted).map(operation=>operation.id));for(let index=original.length-1;rollbackSafe&&index>=0&¤t();index--){const id=original[index];if(!members.has(id))continue;const live=this.nativeLayerOrder(map);if(!current()||!live.includes(id))break;const before=original.slice(index+1).find(value=>live.includes(value)),restored=live.filter(value=>value!==id);restored.splice(before===void 0?restored.length:restored.indexOf(before),0,id);try{map.moveLayer(id,before)}catch{break}if(!current()||!sameOrder(this.nativeLayerOrder(map),restored))break}throw error}}reconcileGeneratedLayers(){const map=this._map;if(!map||!this._styleLoaded||((this.dataLayerIssue||this.pendingDataLayerIssue)&&(this._canonicalDataLayersSource=UNPROJECTED_MAP_VALUE),this.cancelFeaturePreparation(),this._map!==map||!this.isConnected))return Promise.resolve();this.readiness.invalidate();let finish;const work=new Promise(resolve=>{finish=resolve});this.featureWork=work,this.finishFeatureWork=finish;const generation=this.featureGeneration,connection=this._connectGeneration,styleGeneration=this._styleGeneration,style=this.mapStyle,dataLayers=this.dataLayers,choropleth=this.choropleth,overlays=this.overlays,images=this.images,imageProvider=this.imageProvider,styleOverrides=this.styleOverrides,hiddenCategories=this.hiddenCategories,interactiveBasemapLayers=this.interactiveBasemapLayers;let ownedInput,externalInput,orderGroups,basemapOrderDraft,retainGroupOrder=!1,mutationStarted=!1,preparedExternal=!1,finishApplication,settleApplication,rejectApplication;const identities={geojson:new Map(this.plannedDataLayerIds),external:new Map(this.externalSourceIds),nextGeojson:this._nextDataLayerId,nextExternal:this.externalIdCounter,externalStyle:this.externalIdStyle},controller=new AbortController;this.featureAbort=controller,this.preparingFeatures=!0;const current=()=>this.isConnected&&this._map===map&&generation===this.featureGeneration&&connection===this._connectGeneration&&styleGeneration===this._styleGeneration&&style===this.mapStyle&&dataLayers===this.dataLayers&&choropleth===this.choropleth&&overlays===this.overlays&&images===this.images&&imageProvider===this.imageProvider&&styleOverrides===this.styleOverrides&&interactiveBasemapLayers===this.interactiveBasemapLayers&&(!externalInput?.sources.length&&!this.externalFeatureWorkStarted||hiddenCategories===this.hiddenCategories),apply=()=>{if(!current()||controller.signal.aborted)return;mutationStarted=!0,this.plannedDataLayerIds.clear();for(const[key,value]of identities.geojson)this.plannedDataLayerIds.set(key,value);this.externalSourceIds.clear();for(const[key,value]of identities.external)this.externalSourceIds.set(key,value);if(this._nextDataLayerId=identities.nextGeojson,this.externalIdCounter=identities.nextExternal,this.externalIdStyle=identities.externalStyle,this.prepareStateRetirement(ownedInput.overlays),!current()||controller.signal.aborted)return;const next=this.canonicalChoropleth,nextId=next?this.resolveChoroplethSourceId(next.sourceId):void 0;if(this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==nextId&&this.removeChoropleth(),!this.withMapPaintBatch(()=>{this.rebuildGeneratedLayers?(this.applyChoropleth(),this.applyDataLayers(current),this.rebuildGeneratedLayers=!1):(this.applyDataLayers(current),this.applyChoropleth())}))return;const complete=()=>{if(!(!current()||controller.signal.aborted)){if(orderGroups){if(this.applyDataLayerOrder(orderGroups,current,basemapOrderDraft),!current())return;this.groupOrderActive=retainGroupOrder}current()&&(this.committedDataLayers=this._canonicalDataLayers,this.committedExternalLayers=this._canonicalExternalLayers,this.setDataLayerIssue(!1),this.configureMapInteractions(ownedInput.overlays,externalInput),!(!current()||controller.signal.aborted)&&(this.replayFeatureStates(map,current,controller.signal),!(!current()||controller.signal.aborted)&&(this.featureAbort=void 0,this.preparingFeatures=!1,this.syncDrawing(),this.syncMapCursor(),this.pendingDrawingTheme&¤t()&&(this.pendingDrawingTheme=!1,this.drawingController?.repaint()),current()&&(this.flushMapLoad(map),finish(),this.readiness.check()))))}};finishApplication=complete;const completeResources=()=>{preparedExternal?settleApplication?.():complete()},admittedOverlays=ownedInput.overlays;if(!this.optionalFeatureWorkStarted&&!this.externalFeatureWorkStarted&&externalInput.sources.length===0&&admittedOverlays.sources.length===0&&admittedOverlays.layers.length===0&&ownedInput.images.length===0&&ownedInput.styleOverrides.length===0){try{complete()}catch{fail()}return}this.optionalFeatureWorkStarted=!0;const failure=()=>{preparedExternal?rejectApplication?.():current()&&!controller.signal.aborted&&fail()},external=this.externalFeatureWorkStarted||externalInput.sources.length>0;external&&(this.externalFeatureWorkStarted=!0);const reconcileOwned=({MapOwnedFeatures})=>{if(!current()||controller.signal.aborted)return;const owned=this.ownedFeatures??=new MapOwnedFeatures,applyOwned=()=>owned.reconcile(map,styleGeneration,ownedInput,{owner:this,signal:controller.signal,isCurrent:current,beforeSourceChange:change=>{this.featureStates?.refreshNative("overlay",change.id)},isGeneratedLayer:id=>this.externalFeatures?.ownsLayer(id)===!0||id===this._appliedFillLayerId||[...this._appliedDataLayerIds.values()].some(sourceId=>DATA_LAYER_SUFFIXES.some(suffix=>id===`${sourceId}${suffix}`)),resolve:(value,property2)=>this.resolveStyleOverride(value,property2),styleLayers:()=>this._styleLayers});if(external){const applyExternal=()=>(this.externalFeatures??=new MapOwnedFeatures).reconcile(map,styleGeneration,{overlays:{sources:externalInput.sources,layers:externalInput.layers},images:[],styleOverrides:[]},{owner:this,signal:controller.signal,isCurrent:current,isGeneratedLayer:()=>!1,beforeSourceChange:change=>{this.featureStates?.refreshNative("data-layer",change.id)},resolve:value=>value});(this._canonicalExternalLayers.some(row=>!!row.style?.iconIds.length)?applyOwned().then(()=>current()&&!controller.signal.aborted?applyExternal():void 0):applyExternal().then(()=>current()&&!controller.signal.aborted?applyOwned():void 0)).then(completeResources).catch(failure)}else applyOwned().then(completeResources).catch(failure)},runtime=loadMapOwnedFeatureRuntime.loaded;runtime?reconcileOwned(runtime):loadMapOwnedFeatureRuntime().then(reconcileOwned).catch(failure)},fail=()=>{if(current()){if(this.preparingFeatures=!1,finish(),!mutationStarted&&this.mapLoadEmitted&&!this.pendingMapLoad){this._canonicalDataLayers=this.committedDataLayers,this._canonicalExternalLayers=this.committedExternalLayers,this.setDataLayerIssue(!0),this.readiness.check();return}if(this.readiness.fail(),!this.mapLoadEmitted||this.pendingMapLoad){this.failInitialization("initialization-failed");return}this.scheduleAfterUpdate(()=>{current()&&this.failInitialization("initialization-failed")},`map-feature-failure-${generation}`)}},begin=input=>{if(this.syncPaintTheme(),!current()||controller.signal.aborted){finish();return}const runtime=loadMapOwnedFeatureRuntime.loaded,owned=runtime?runtime.resolveMapOwnedOverlayPaint(input.overlays,(value,property2)=>this.resolveStyleOverride(value,property2)):input.overlays;ownedInput={...input,overlays:owned};const reserved=new Set([...owned.sources.map(source=>source.id),...owned.layers.map(entry=>entry.layer.id)]);for(const row of this.canonicalDataLayers){const id=this.resolveDataLayerSourceId(row,identities);if(reserved.has(id)||DATA_LAYER_SUFFIXES.some(suffix=>reserved.has(`${id}${suffix}`)))throw new Error("Map resource identity conflicts.")}if(externalInput=this.externalLayerInput(owned,identities),!current()||controller.signal.aborted){finish();return}const overrideOrders=ownedInput.styleOverrides.some(entry=>entry.before!==void 0);if(retainGroupOrder=overrideOrders||this.canonicalDataLayers.some(row=>row.before!==void 0)||this._canonicalExternalLayers.some(row=>row.before!==void 0)||owned.layers.some(row=>row.before!==void 0),this.groupOrderActive||retainGroupOrder){if(!runtime||typeof map.getStyle!="function"||typeof map.moveLayer!="function")throw new Error("Map layer order is unavailable.");if(orderGroups=this.dataLayerOrderGroups(owned,externalInput,identities),overrideOrders||this.basemapOrder?.active){const owner=this.basemapOrder??=new runtime.MapBasemapOrder,generated=new Set(orderGroups.flatMap(group=>group.layerIds));basemapOrderDraft=owner.stage(this.nativeLayerOrder(map),ownedInput.styleOverrides,this._styleLayers,id=>generated.has(id)||id===this._appliedFillLayerId||this.ownedFeatures?.ownsLayer(id)===!0||this.externalFeatures?.ownsLayer(id)===!0||this.drawingController?.ownsLayer(id)===!0)}const planned=basemapOrderDraft?basemapOrderDraft.plan(this.nativeLayerOrder(map),orderGroups):runtime.planMapLayerOrder(this.nativeLayerOrder(map),orderGroups);if(!planned.valid)throw new Error("Map layer order is invalid.");if(planned.diagnostics.some(issue=>issue.code==="missing-anchor")&&devWarnOnce("lyra-map-missing-layer-anchor",`<${this.localName}>: a missing layer anchor appends its group.`),!current()){finish();return}const allGroups=[...orderGroups,...basemapOrderDraft?.groups??[]],anchors=new Map(allGroups.map(group=>[group.id,group.layerIds[0]]));for(const group of allGroups)for(const id of group.layerIds)anchors.has(id)||anchors.set(id,group.layerIds[0]);const translate=entry=>entry.before&&anchors.has(entry.before)?{...entry,before:anchors.get(entry.before)}:entry;ownedInput={...ownedInput,overlays:{sources:owned.sources,layers:owned.layers.map(translate)}},externalInput={...externalInput,layers:externalInput.layers.map(translate)}}const preflight=()=>{const finalOwned=ownedInput.overlays;if(externalInput.sources.length||finalOwned.sources.length||finalOwned.layers.length){if(!runtime)throw new Error("Map resources are unavailable.");runtime.snapshotMapOwnedFeatureInput({overlays:{sources:[...finalOwned.sources,...externalInput.sources],layers:[...finalOwned.layers,...externalInput.layers]},images:ownedInput.images,styleOverrides:ownedInput.styleOverrides})}if(this.canonicalDataLayers.some(row=>row.placementRequested)&&typeof map.setLayerZoomRange!="function")throw new Error("Map layer bounds are unavailable.")},prepare=()=>{if(!current()||controller.signal.aborted||typeof map.prepareFeatures!="function")return;const requirements=this.generatedFeatureRequirements(),signature=JSON.stringify([Object.values(requirements.sources??{}).map(source=>source.type),(requirements.layers??[]).map(layer=>layer.type)]);if(signature!==this.preparedFeatureSignature)return map.prepareFeatures(requirements,{signal:controller.signal}).then(()=>{current()&&!controller.signal.aborted&&(this.preparedFeatureSignature=signature)})};if(externalInput.sources.length||this.externalFeatureWorkStarted){if(!runtime)throw new Error("Map resources are unavailable.");const effects=this.externalSourceEffects??=new runtime.MapExternalSourceEffects,revisions=new Map(this._canonicalExternalLayers.filter(row=>row.kind==="canvas").map(row=>[identities.external.get(row.sourceId),row.redrawRevision??0])),live=()=>this.isConnected&&this._map===map&&this._styleGeneration===styleGeneration&&this._connectGeneration===connection&&this.mapStyle===style;effects.reconcile(map,styleGeneration,externalInput.sources,revisions,{owner:this,signal:controller.signal,isCurrent:current,isLive:live,canPauseCanvas:id=>(this.canonicalDataLayers,!this.invalidDataLayerModel&&this._canonicalExternalLayers.some(row=>row.kind==="canvas"&&this.externalSourceIds.get(row.sourceId)===id&&row.source.animate===!1)),retire:()=>{live()&&this.failInitialization("initialization-failed")}},()=>new Promise((resolve,reject)=>{const aborted=()=>{reject(new Error("Map resource application was superseded."))},clear=()=>{controller.signal.removeEventListener("abort",aborted)};if(preparedExternal=!0,settleApplication=()=>{clear(),resolve()},rejectApplication=()=>{clear(),reject(new Error("Map resources could not be applied."))},controller.signal.addEventListener("abort",aborted,{once:!0}),controller.signal.aborted){clear(),aborted();return}try{apply()}catch(error){clear(),reject(error)}}),async sources=>{externalInput={...externalInput,sources},preflight(),await prepare()}).then(()=>{current()&&!controller.signal.aborted&&finishApplication?.()}).catch(()=>{current()&&!controller.signal.aborted&&fail()});return}if(preflight(),!current()||controller.signal.aborted){finish();return}const preparation=prepare();preparation?preparation.then(apply).catch(()=>{current()&&!controller.signal.aborted&&fail()}):apply()};try{const geojson=this.canonicalDataLayers;if(this.invalidDataLayerModel||geojson.some(layer=>layer.invalidLabel)||geojson.some(layer=>layer.label!==void 0)&&!this.styleProvidesGlyphs())throw new Error("Map labels or sources are unavailable.");const runtime=loadMapOwnedFeatureRuntime.loaded;runtime?begin(runtime.snapshotMapOwnedFeatureInput({overlays,images,styleOverrides})):!this._canonicalExternalLayers.length&&!this.groupOrderActive&&!geojson.some(layer=>layer.before!==void 0)&&!ownedFeaturesRequested(overlays,images,styleOverrides)&&!projectMapBasemapInteractions(interactiveBasemapLayers)?.length?begin(NO_OWNED_FEATURES):loadMapOwnedFeatureRuntime().then(loaded=>{current()&&!controller.signal.aborted&&begin(loaded.snapshotMapOwnedFeatureInput({overlays,images,styleOverrides}))}).catch(fail)}catch{fail()}return work}resolveStyleOverride(value,property2){if(!/(?:-color|-gradient)$/u.test(property2))return value;const resolve=entry=>{if(typeof entry=="string"&&THEME_PAINT_COLOR.test(entry)){const color=resolvedMapPaintColor(this,entry,!0);if(!color)throw new Error("Map color could not be resolved.");return color}return Array.isArray(entry)?entry[0]==="literal"?entry:entry.map(resolve):entry!==null&&typeof entry=="object"?Object.fromEntries(Object.entries(entry).map(([key,child])=>[key,resolve(child)])):entry};return resolve(value)}applyChoropleth(){if(!this._map)return;this.syncPaintTheme();const choropleth=this.canonicalChoropleth;if(!choropleth){this.removeChoropleth();return}const{geojson,geojsonProjection,stops}=choropleth,sourceId=this.resolveChoroplethSourceId(choropleth.sourceId),fillLayerId=`${sourceId}-fill`;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==sourceId&&this.removeChoropleth(),warnOnUntileableProperties(geojsonProjection,"choropleth");const existingSource=this._map.getSource(sourceId);if(existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojsonProjection)),this._appliedChoroplethSourceId=sourceId,stops.length===0)return;const{geojson:_geojson,geojsonProjection:_projection,...paint}=choropleth,paintKey=JSON.stringify(paint);if(this.appliedChoroplethPaintKey===paintKey&&this._map.getLayer(fillLayerId))return;const colorExpr=this.choroplethColorExpression(choropleth),outlineExpr=this.choroplethOutlineExpression(choropleth,colorExpr);this._map.getLayer(fillLayerId)?(this.setMapPaint(fillLayerId,"fill-color",colorExpr),this.setMapPaint(fillLayerId,"fill-opacity",choroplethFillOpacity(this)),this.setMapPaint(fillLayerId,"fill-outline-color",outlineExpr??null)):this._map.addLayer({id:fillLayerId,type:"fill",source:sourceId,paint:{"fill-color":colorExpr,"fill-opacity":choroplethFillOpacity(this),...outlineExpr?{"fill-outline-color":outlineExpr}:{}}}),this.appliedChoroplethPaintKey=paintKey,this._appliedFillLayerId=fillLayerId}choroplethColorExpression(choropleth){const{field,stops}=choropleth,resolvedStops=stops.map(([value,color])=>[value,resolvedLayerColor(this,color,void 0)]);let colorExpr;if(choropleth.interpolation==="step"){const base=choropleth.stepBaseColor?resolvedLayerColor(this,choropleth.stepBaseColor,void 0):resolvedStops[0][1];colorExpr=["step",["get",field],base];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}else{colorExpr=["interpolate",choropleth.interpolation==="logarithmic"?["exponential",CHOROPLETH_LOG_INTERPOLATION_BASE]:["linear"],["get",field]];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}const noData=choropleth.noData;return noData?["case",choroplethHasValueExpression(field),colorExpr,this.choroplethNoDataColor(noData)]:colorExpr}choroplethNoDataColor(noData){return resolvedLayerColor(this,noData.color,"neutral")}choroplethOutlineExpression(choropleth,colorExpr){const stroke=choropleth.noData?.strokeColor;if(!stroke)return;const resolved=resolvedMapPaintColor(this,stroke,!0);if(resolved)return["case",choroplethHasValueExpression(choropleth.field),colorExpr,resolved]}resolveChoroplethSourceId(sourceId){const dataSourceIds=new Set(this.canonicalDataLayers.map(layer=>layer.sourceId));let resolved=sourceId;for(let attempt=0;attempt<512;attempt+=1){const sourceTaken=resolved!==this._appliedChoroplethSourceId&&!!this._map?.getSource(resolved),fillId=`${resolved}-fill`,fillTaken=fillId!==this._appliedFillLayerId&&!!this._map?.getLayer(fillId);if(!dataSourceIds.has(resolved)&&!sourceTaken&&!fillTaken)return resolved;resolved=`lr-choropleth-${resolved}`}throw new Error("Map source namespace is unavailable.")}removeChoropleth(){!this._map||!this._appliedChoroplethSourceId||(this.featureStates?.refreshNative("choropleth",this._appliedChoroplethSourceId),this._appliedFillLayerId&&this._map.getLayer(this._appliedFillLayerId)&&this.removeMapLayer(this._appliedFillLayerId),this._map.getSource(this._appliedChoroplethSourceId)&&this._map.removeSource(this._appliedChoroplethSourceId),this._appliedGeoJson.delete(this._appliedChoroplethSourceId),this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this.appliedChoroplethPaintKey=void 0)}applyDataLayers(transactionCurrent){if(!this._map)return;const map=this._map,dataLayers=this.dataLayers,style=this.mapStyle,generation=this.featureGeneration,current=transactionCurrent??(()=>this.isConnected&&this._map===map&&dataLayers===this.dataLayers&&style===this.mapStyle&&generation===this.featureGeneration),check=()=>{if(!current())throw new DOMException("Map update superseded.","AbortError")};check(),this.syncPaintTheme();const layers=this.canonicalDataLayers,nextIds=new Set(layers.map(layer=>layer.sourceId));for(const publicSourceId of this._appliedDataLayerIds.keys())nextIds.has(publicSourceId)||this.removeDataLayer(publicSourceId);for(const layer of layers){check();const{sourceId:publicSourceId,geojson,geojsonProjection}=layer,shape=dataLayerShape(layer),appliedShape=this._appliedDataLayerShapes.get(publicSourceId),sourceId=this.resolveDataLayerSourceId(layer);appliedShape!==void 0&&appliedShape!==shape&&this.removeDataLayer(publicSourceId),warnOnUntileableProperties(geojsonProjection,publicSourceId);const cluster=layer.cluster,existingSource=this._map.getSource(sourceId);check(),existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}}),check(),this._appliedGeoJson.set(sourceId,geojsonProjection)),check();const{geojson:_geojson,geojsonProjection:_projection,...paint}=layer,paintKey=JSON.stringify(paint);(!existingSource||this.appliedLayerPaintKeys.get(sourceId)!==paintKey)&&(this.applyDataLayerRendering(sourceId,layer,current),check(),this.applyDataLayerRange(sourceId,layer,current),check(),this.appliedLayerPaintKeys.set(sourceId,paintKey)),this._appliedDataLayerIds.set(publicSourceId,sourceId),this._appliedDataLayerShapes.set(publicSourceId,shape)}}applyDataLayerRange(sourceId,layer,current){const map=this._map;if(!map||!layer.placementRequested&&!this.appliedRowRanges.has(sourceId))return;const changes=[];for(const suffix of DATA_LAYER_SUFFIXES){const id=`${sourceId}${suffix}`,native=map.getLayer(id);if(!current())throw new DOMException("Map update superseded.","AbortError");if(!native)continue;const min=Math.max(layer.minZoom,suffix==="-label"?layer.label?.minZoom??0:0),max=layer.maxZoom,rawMin=mapOwnValue(native,"minzoom"),rawMax=mapOwnValue(native,"maxzoom"),oldMin=typeof rawMin=="number"?rawMin:0,oldMax=typeof rawMax=="number"?rawMax:24;(min!==oldMin||max!==oldMax)&&changes.push({id,min,max,oldMin,oldMax})}if(changes.length&&typeof map.setLayerZoomRange!="function")throw new Error("Map layer bounds are unavailable.");const journal=[];try{for(const change of changes){if(!current())throw new DOMException("Map update superseded.","AbortError");if(journal.push(change),map.setLayerZoomRange(change.id,change.min,change.max),!current())throw new DOMException("Map update superseded.","AbortError")}this.appliedRowRanges.set(sourceId,`${layer.minZoom}:${layer.maxZoom}`)}catch(error){for(const change of journal.reverse()){if(!current())break;try{map.setLayerZoomRange(change.id,change.oldMin,change.oldMax)}catch{break}}throw error}}applyDataLayerRendering(sourceId,layer,current){if(layer.kind==="heatmap"){this.applyHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;if(cluster?this.applyClusterLayers(sourceId,layer,cluster):this.applyGeometryLayers(sourceId,layer),!current())throw new DOMException("Map update superseded.","AbortError");if(this.applyPointIcons(sourceId,layer),!current())throw new DOMException("Map update superseded.","AbortError");this.applyGeoLabel(sourceId,layer,current)}paintDataLayer(sourceId,layer){if(layer.kind==="heatmap"){this.paintHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;if(cluster?this.paintClusterLayers(sourceId,layer,cluster):this.paintGeometryLayers(sourceId,layer),this.paintPointIcons(sourceId,layer),layer.label&&this.appliedGeoLabels.has(sourceId)){const descriptor=buildMapLabelLayer(`${sourceId}-label`,sourceId,layer.label,value=>resolvedLayerColor(this,value,layer.tone));for(const[property2,value]of Object.entries(descriptor.paint))this.setMapPaint(descriptor.id,property2,value)}}applyGeoLabel(sourceId,layer,current){const map=this._map;if(!map)return;const check=()=>{if(!current())throw new DOMException("Map update superseded.","AbortError")};check();const id=`${sourceId}-label`,existing=map.getLayer(id);if(check(),!layer.label){this.appliedGeoLabels.delete(sourceId),existing&&(map.removeLayer(id),check());return}const descriptor=buildMapLabelLayer(id,sourceId,layer.label,value=>resolvedLayerColor(this,value,layer.tone)),native=layer.cluster?{...descriptor,filter:["all",["!",["has","point_count"]],["==",["geometry-type"],"Point"]]}:descriptor,key=JSON.stringify(native);if(this.appliedGeoLabels.get(sourceId)===key)return;const previousKey=this.appliedGeoLabels.get(sourceId);if(existing&&previousKey&&typeof map.setLayoutProperty=="function"&&typeof map.setFilter=="function"&&typeof map.setLayerZoomRange=="function"){const previous=JSON.parse(previousKey),journal=[],write=(apply,restore)=>{if(!current())throw new DOMException("Map update superseded.","AbortError");if(this.appliedGeoLabels.delete(sourceId),journal.push(restore),apply(),!current())throw new DOMException("Map update superseded.","AbortError")};try{for(const kind of["layout","paint"]){const before=previous[kind]??{},after=native[kind]??{};for(const property2 of new Set([...Object.keys(before),...Object.keys(after)])){if(JSON.stringify(before[property2])===JSON.stringify(after[property2]))continue;const setter=kind==="layout"?map.setLayoutProperty:map.setPaintProperty;write(()=>{setter.call(map,id,property2,after[property2]??null)},()=>{setter.call(map,id,property2,before[property2]??null)})}}if(JSON.stringify(previous.filter)!==JSON.stringify(native.filter)&&write(()=>{map.setFilter(id,native.filter??null)},()=>{map.setFilter(id,previous.filter??null)}),previous.minzoom!==native.minzoom&&write(()=>{map.setLayerZoomRange(id,Math.max(layer.minZoom,layer.label.minZoom),layer.maxZoom)},()=>{map.setLayerZoomRange(id,typeof previous.minzoom=="number"?previous.minzoom:0,layer.maxZoom)}),!current())throw new DOMException("Map update superseded.","AbortError")}catch(error){for(const restore of journal.reverse()){if(!current())break;try{restore()}catch{break}}throw error}}else existing&&(map.removeLayer(id),check()),map.addLayer(native),check();this.appliedGeoLabels.set(sourceId,key)}applyGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)||this._map.addLayer({id:fillId,type:"fill",source:sourceId,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":color,"fill-opacity":choroplethFillOpacity(this)}}),this._map.getLayer(lineId)||this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":this.lineColor(layer),"line-width":layer.line?.width??2,...layer.line?{"line-opacity":layer.line.opacity}:{}}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":stroke,"circle-radius":5}}),this.setMapPaint(lineId,"line-width",layer.line?.width??2),this.setMapPaint(lineId,"line-opacity",layer.line?.opacity??1),this.paintGeometryLayers(sourceId,layer)}paintGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone);this.setMapPaint(`${sourceId}-fill`,"fill-color",color),this.setMapPaint(`${sourceId}-fill`,"fill-opacity",choroplethFillOpacity(this)),this.setMapPaint(`${sourceId}-line`,"line-color",this.lineColor(layer)),this.paintPoints(sourceId,layer)}lineColor(layer){const fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),line=layer.line;return!line?.field||line.stops.length<2?fallback:lineColorExpression(line.field,line.stops.map(([value,color])=>[value,resolvedLayerColor(this,color,layer.tone)]),fallback)}mutedPointOpacity(layerId,field){const muted=field?this.hiddenCategories:EMPTY_HIDDEN_CATEGORIES;if(!muted.length)return this.appliedPointMuting.delete(layerId)?1:void 0;this.appliedPointMuting.add(layerId);const dim=hiddenCategoryOpacity(this);return mutedCategoryOpacityExpression(field,muted,dim)}paintPoints(sourceId,layer){if(!this._map)return;const point=layer.point,fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),color=pointColorExpression(point?.field,point?.field&&point.colors.length?point.colors.map(([value,paint])=>[value,resolvedLayerColor(this,paint,layer.tone)]):[],fallback),id=`${sourceId}-circle`;this.setMapPaint(id,"circle-color",color);const opacity=this.mutedPointOpacity(id,point?.field);opacity!==void 0&&(this.setMapPaint(id,"circle-opacity",opacity),this.setMapPaint(id,"circle-stroke-opacity",opacity)),!(!point&&!this.appliedPointPaint.has(sourceId))&&(this.setMapPaint(id,"circle-radius",pointRadiusExpression(point?.radius??5)),this.setMapPaint(id,"circle-stroke-width",point?.strokeWidth??0),this.setMapPaint(id,"circle-stroke-color",point?.strokeColor?resolvedLayerColor(this,point.strokeColor,layer.tone):fallback),point?this.appliedPointPaint.add(sourceId):this.appliedPointPaint.delete(sourceId))}pointIconColor(layer){const resolved=resolvedLayerColor(this,layer.point?.iconColor??`var(${ON_TONE_TOKEN[layer.tone??"accent"]})`,layer.tone);return resolveCanvasColor(this,resolved,dataLayerColor(this,layer.tone))}removePointIcons(sourceId){const applied=this.appliedPointIcons.get(sourceId);if(!applied||!this._map)return;const id=`${sourceId}-point-icon`;this._map.getLayer(id)&&this.removeMapLayer(id);for(const{id:imageId}of applied.icons)this._map.hasImage?.(imageId)&&this._map.removeImage?.(imageId);this.appliedPointIcons.delete(sourceId),this.appliedPointMuting.delete(id)}applyPointIcons(sourceId,layer){const map=this._map,point=layer.point,signature=JSON.stringify([point?.iconField,point?.iconSize,point?.icons]);if(this.appliedPointIcons.get(sourceId)?.signature===signature){this.paintPointIcons(sourceId,layer);return}if(this.removePointIcons(sourceId),!point?.iconField||!point.icons.length||!map||typeof map.addImage!="function"||typeof map.hasImage!="function"||typeof map.updateImage!="function"||typeof map.removeImage!="function")return;const color=this.pointIconColor(layer),icons=[];this.appliedPointIcons.set(sourceId,{signature,color,icons});for(const icon of point.icons){const raster=rasterPointIcon(this,icon,color);if(!raster)continue;let id;do id=`lr-point-icon-${this.nextPointIconId++}`;while(map.hasImage(id));icons.push({id,icon}),map.addImage(id,raster,{pixelRatio:2})}icons.length&&map.addLayer({id:`${sourceId}-point-icon`,type:"symbol",source:sourceId,filter:layer.cluster?["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]]:["==",["geometry-type"],"Point"],layout:{"icon-image":["match",["get",point.iconField],...icons.flatMap(({id,icon})=>[icon.value,id]),""],"icon-size":point.iconSize/(POINT_ICON_RASTER_SIZE/2),"icon-allow-overlap":!0,"icon-ignore-placement":!0}})}paintPointIcons(sourceId,layer){const applied=this.appliedPointIcons.get(sourceId);if(!applied)return;const iconLayerId=`${sourceId}-point-icon`,opacity=this.mutedPointOpacity(iconLayerId,layer.point?.iconField);opacity!==void 0&&this.setMapPaint(iconLayerId,"icon-opacity",opacity);const color=this.pointIconColor(layer);if(color!==applied.color){for(const{id,icon}of applied.icons){const raster=rasterPointIcon(this,icon,color);raster&&this._map?.updateImage?.(id,raster)}applied.color=color}}clusterColorExpression(layer,cluster){const tone=layer.tone;return clusterColorExpression(cluster.colorSteps.map(([count,stepColor])=>[count,resolvedLayerColor(this,stepColor,tone)]),()=>resolvedLayerColor(this,layer.color,tone))}applyClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedClusterStrokeColor(this,cluster.strokeColor,layer),clusterId=`${sourceId}-cluster`,countId=`${sourceId}-cluster-count`,circleId=`${sourceId}-circle`,clusterColor=this.clusterColorExpression(layer,cluster),clusterRadius=stepExpression(["get","point_count"],cluster.radiusSteps),countColor=resolvedClusterCountColor(this,cluster.countColor)??resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone),countHaloColor=resolvedClusterCountColor(this,cluster.countHaloColor);this._map.getLayer(clusterId)||this._map.addLayer({id:clusterId,type:"circle",source:sourceId,filter:["has","point_count"],paint:{"circle-color":clusterColor,"circle-radius":clusterRadius,"circle-stroke-width":1,"circle-stroke-color":stroke}}),this.styleProvidesGlyphs()&&!this._map.getLayer(countId)&&this._map.addLayer({id:countId,type:"symbol",source:sourceId,filter:["has","point_count"],layout:{"text-field":["get","point_count_abbreviated"],"text-size":12,...cluster.countFont?{"text-font":[...cluster.countFont]}:{}},paint:{"text-color":countColor,...countHaloColor?{"text-halo-color":countHaloColor,"text-halo-width":cluster.countHaloWidth}:{}}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]],paint:{"circle-color":stroke,"circle-radius":5}}),this.paintClusterLayers(sourceId,layer,cluster)}paintClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedClusterStrokeColor(this,cluster.strokeColor,layer),clusterId=`${sourceId}-cluster`;if(this.setMapPaint(clusterId,"circle-color",this.clusterColorExpression(layer,cluster)),this.setMapPaint(clusterId,"circle-radius",stepExpression(["get","point_count"],cluster.radiusSteps)),this.setMapPaint(clusterId,"circle-stroke-color",stroke),this.styleProvidesGlyphs()){this.setMapPaint(`${sourceId}-cluster-count`,"text-color",resolvedClusterCountColor(this,cluster.countColor)??resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone));const countHaloColor=resolvedClusterCountColor(this,cluster.countHaloColor);this.setMapPaint(`${sourceId}-cluster-count`,"text-halo-color",countHaloColor??null),this.setMapPaint(`${sourceId}-cluster-count`,"text-halo-width",countHaloColor?cluster.countHaloWidth:null)}this.paintPoints(sourceId,layer)}applyHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`,options=layer.heatmap,weight=heatmapWeightExpression(options),color=this.heatmapColorExpression(layer),radius=heatmapZoomValue(options?.radius,DEFAULT_HEATMAP_RADIUS,1,200),intensity=heatmapZoomValue(options?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100),opacity=finiteRange(options?.opacity??Number.NaN,1,0,1);if(!this._map.getLayer(heatmapId)){this._map.addLayer({id:heatmapId,type:"heatmap",source:sourceId,paint:{...weight?{"heatmap-weight":weight}:{},"heatmap-intensity":intensity,"heatmap-color":color,"heatmap-radius":radius,...options?.opacity===void 0?{}:{"heatmap-opacity":opacity}}});return}this.paintHeatmapLayer(sourceId,layer)}paintHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`;this.setMapPaint(heatmapId,"heatmap-weight",heatmapWeightExpression(layer.heatmap)??1),this.setMapPaint(heatmapId,"heatmap-intensity",heatmapZoomValue(layer.heatmap?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100)),this.setMapPaint(heatmapId,"heatmap-color",this.heatmapColorExpression(layer)),this.setMapPaint(heatmapId,"heatmap-radius",heatmapZoomValue(layer.heatmap?.radius,DEFAULT_HEATMAP_RADIUS,1,200)),this.setMapPaint(heatmapId,"heatmap-opacity",finiteRange(layer.heatmap?.opacity??Number.NaN,1,0,1))}heatmapColorExpression(layer){const tone=layer.tone,authored=(layer.heatmap?.stops??[]).map(([density,color])=>[density,resolvedLayerColor(this,color,tone)]);return heatmapColorExpression(authored,()=>HEATMAP_RAMP_TOKENS.map(([density,token])=>[density,resolvedLayerColor(this,`var(${token})`,tone)]))}styleHasTextFonts(style){try{if(!isPlainDataRecord(style))return!1;const glyphs=getOwnDataDescriptor(style,"glyphs");if(isUnsafeDescriptor(glyphs))return!1;const glyphUrl=optionalDescriptorValue(glyphs);if(typeof glyphUrl=="string"&&glyphUrl.trim().length>0)return!0;const facesDescriptor=getOwnDataDescriptor(style,"font-faces");if(isUnsafeDescriptor(facesDescriptor))return!1;const faces=optionalDescriptorValue(facesDescriptor);if(!isPlainDataRecord(faces))return!1;const families=Reflect.ownKeys(faces);if(families.length===0||families.length>64)return!1;let familyCount=0;for(const family of families){if(typeof family!="string"||!Object.getOwnPropertyDescriptor(faces,family)?.enumerable)continue;if(!family.trim())return!1;familyCount++;const declarationDescriptor=getOwnDataDescriptor(faces,family);if(isUnsafeDescriptor(declarationDescriptor))return!1;const declaration=optionalDescriptorValue(declarationDescriptor);if(typeof declaration=="string"){if(!declaration.trim())return!1;continue}const count=boundedOwnArrayLength(declaration,257);if(count===void 0||count===0||count>256)return!1;for(let index=0;index<count;index++){const face=optionalDescriptorValue(getOwnDataDescriptor(declaration,String(index)));if(!isPlainDataRecord(face))return!1;const faceKeys=Reflect.ownKeys(face);if(faceKeys.length>2||faceKeys.some(key=>key!=="url"&&key!=="unicode-range"))return!1;const url=optionalDescriptorValue(getOwnDataDescriptor(face,"url"));if(typeof url!="string"||!url.trim())return!1;const rangeDescriptor=getOwnDataDescriptor(face,"unicode-range");if(isUnsafeDescriptor(rangeDescriptor))return!1;if(rangeDescriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;const ranges=optionalDescriptorValue(rangeDescriptor),rangeCount=boundedOwnArrayLength(ranges,65);if(rangeCount===void 0||rangeCount>64)return!1;for(let rangeIndex=0;rangeIndex<rangeCount;rangeIndex++){const range=optionalDescriptorValue(getOwnDataDescriptor(ranges,String(rangeIndex)));if(typeof range!="string")return!1;const match=/^u\+(?:([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?|([0-9a-f]{0,5}\?{1,6}))$/i.exec(range);if(!match)return!1;if(match[3]!==void 0){if(match[3].length>6)return!1}else{const start=Number.parseInt(match[1],16),end=Number.parseInt(match[2]??match[1],16);if(start>end||end>1114111)return!1}}}}return familyCount>0}catch{return!1}}styleProvidesGlyphs(){try{const live=this._map?.getStyle?.();if(this.styleHasTextFonts(live))return!0}catch{}return this.styleHasTextFonts(this.mapStyle)}resolveDataLayerSourceId(layer,identities){const publicSourceId=layer.sourceId,planned=identities?.geojson??this.plannedDataLayerIds,applied=this._appliedDataLayerIds.get(publicSourceId),pending=planned.get(publicSourceId),appliedShape=this._appliedDataLayerShapes.get(publicSourceId),retained=appliedShape!==void 0&&appliedShape!==dataLayerShape(layer)?pending!==applied?pending:void 0:applied??pending;if(retained)return retained;let sourceId;do sourceId=`lr-data-layer-${identities?identities.nextGeojson++:this._nextDataLayerId++}`;while(this._map?.getSource(sourceId)||DATA_LAYER_SUFFIXES.some(suffix=>this._map?.getLayer(`${sourceId}${suffix}`)));return planned.set(publicSourceId,sourceId),sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){this.featureStates?.refreshNative("data-layer",sourceId),this.removePointIcons(sourceId),this.appliedPointPaint.delete(sourceId),this.appliedGeoLabels.delete(sourceId),this.appliedRowRanges.delete(sourceId);for(const suffix of DATA_LAYER_SUFFIXES){const layerId=`${sourceId}${suffix}`;this.appliedPointMuting.delete(layerId),this._map.getLayer(layerId)&&this.removeMapLayer(layerId)}this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.delete(publicSourceId),this.plannedDataLayerIds.get(publicSourceId)===sourceId&&this.plannedDataLayerIds.delete(publicSourceId),this._appliedDataLayerShapes.delete(publicSourceId),this._appliedGeoJson.delete(sourceId),this.appliedLayerPaintKeys.delete(sourceId)}}applyMarkers(){const map=this._map,mod=this._maplibreModule;if(!map||!mod)return;const visible=new Set,coordCounts=new Map,explicitIds=new Set;for(const m of this.canonicalMarkers){const lngLat=m.lngLat,mapLngLat=[lngLat[0],lngLat[1]];let key,id;if(m.id!==void 0){if(id=m.id,explicitIds.has(id))continue;explicitIds.add(id),key=`id:${id}`}else{const coordKey=`${lngLat[0]},${lngLat[1]}`,occurrence=coordCounts.get(coordKey)??0;coordCounts.set(coordKey,occurrence+1),key=`coordinate:${coordKey}#${occurrence}`}visible.add(key);let existing=this._markerInstances.get(key);const markerColor=sanitizeCssColor(m.color)??(m.color===void 0?"currentColor":void 0),previous=this._markerSources.get(key);this._markerSources.set(key,m);const sameColor=this._markerColors.get(key)===markerColor,sameContent=previous!==void 0&&previous.label===m.label&&Object.is(previous.unsafeHtml,m.unsafeHtml);if(existing&&sameColor&&sameContent&&previous.lngLat[0]===lngLat[0]&&previous.lngLat[1]===lngLat[1])continue;if(existing&&!sameColor){const existingElement=existing.getElement?.();existingElement&&this.markerActivationDetails.delete(existingElement),existing.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),existing=void 0}if(existing){existing.setLngLat(mapLngLat);const popup=existing.getPopup();if(!m.unsafeHtml&&!m.label)popup&&existing.setPopup(void 0);else if(popup)sameContent||setPopupContent(popup,m);else{const nextPopup=setPopupContent(new mod.Popup({offset:12}),m);existing.setPopup(nextPopup),this.configurePopupSemantics(key,existing,nextPopup)}}else{const marker=new mod.Marker(markerColor?{color:markerColor}:void 0).setLngLat(mapLngLat);if(m.unsafeHtml||m.label){const popup=setPopupContent(new mod.Popup({offset:12}),m);marker.setPopup(popup),this.configurePopupSemantics(key,marker,popup)}marker.addTo(map),this._markerInstances.set(key,marker),this._markerColors.set(key,markerColor)}const markerLabel=m.label?.trim()||markerPopupText(this,m.unsafeHtml);this._markerLabels.set(key,markerLabel||void 0);const markerElement=this._markerInstances.get(key)?.getElement?.();if(markerElement){addPartToken(markerElement,"marker");const currentMarker=this._markerInstances.get(key);this.configureMarkerInteraction(markerElement,{id,lngLat,marker:m},markerLabel);const popup=currentMarker?.getPopup();popup&¤tMarker?(this.configurePopupSemantics(key,currentMarker,popup),this.syncPopupSemantics(key,currentMarker,popup)):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}}for(const[key,marker]of this._markerInstances)if(!visible.has(key)){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),this._markerLabels.delete(key),this._markerPopupIds.delete(key),this._markerSources.delete(key)}}configureMarkerInteraction(markerElement,activation,markerLabel=activation.marker.label?.trim()||markerPopupText(this,activation.marker.unsafeHtml)){this.markerActivationDetails.set(markerElement,activation),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",markerLabel||this.localize("mapMarker")),markerElement.setAttribute("lang",this.effectiveLocale),!this.configuredMarkerElements.has(markerElement)&&(this.configuredMarkerElements.add(markerElement),markerElement.addEventListener("click",event=>{event.defaultPrevented||this.emitMarkerActivation(markerElement,"pointer")}),markerElement.addEventListener("keydown",event=>{event.key!==" "&&event.key!=="Enter"||event.repeat||event.defaultPrevented||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected)return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return hostAriaLabel(this)??this.label??this.localize("map")}popupId(key){let id=this._markerPopupIds.get(key);return id||(id=`map-popup-${this._connectGeneration}-${++this._nextPopupId}`,this._markerPopupIds.set(key,id)),id}configurePopupSemantics(key,marker,popup){!popup||typeof popup!="object"||this._configuredPopups.has(popup)||(this._configuredPopups.add(popup),popup.on?.("open",()=>this.syncPopupSemantics(key,marker,popup)),popup.on?.("close",()=>{marker.getElement?.()?.setAttribute("aria-expanded","false")}))}stopObservingMapAllocation(){this.mapResizeObserver?.disconnect(),this.mapResizeObserver=void 0,this.observedMapContainer=void 0}observeMapAllocation(map,container){this.stopObservingMapAllocation();const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;let observer,size=renderedSizeKey(container);observer=new ResizeObserverCtor(()=>{if(this.mapResizeObserver!==observer||this.observedMapContainer!==container||this.containerEl!==container||this._map!==map||!this.isConnected)return;try{this.cameraSession?this.writeCamera(()=>map.resize()):map.resize(),this.drawingController?.scheduleHandles()}catch{}this.geographicSceneRender?.refreshAllocation();const next=renderedSizeKey(container);next!==size&&(size=next,this.scheduleAnchorSync())}),this.mapResizeObserver=observer,this.observedMapContainer=container;try{observer.observe(container)}catch{this.stopObservingMapAllocation()}}stopObservingPeerChrome(){const pending=this.peerControlsResizeFrame;this.peerControlsResizeFrame=void 0,pending&&pending.view.cancelAnimationFrame(pending.handle),this.peerControlsResizeObserver?.disconnect(),this.peerControlsResizeObserver=void 0,this.peerChromeObserver?.disconnect(),this.peerChromeObserver=void 0,this.observedPeerContainer=void 0}schedulePeerControlInsets(observer,container){if(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||!this.isConnected||this.peerControlsResizeFrame)return;const view=container.ownerDocument.defaultView;if(!view)return;const pending={view,handle:0};this.peerControlsResizeFrame=pending,pending.handle=view.requestAnimationFrame(()=>{this.peerControlsResizeFrame===pending&&(this.peerControlsResizeFrame=void 0,!(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||container.ownerDocument.defaultView!==view||!this.isConnected)&&this.measurePeerControlInsets(container))})}measurePeerControlInsets(container){if(!(!this.isConnected||this.containerEl!==container)){for(const scale of container.querySelectorAll(".maplibregl-ctrl-scale")){const width=scale.style.width;width&&scale.style.getPropertyValue("--_lr-map-scale-width")!==width&&scale.style.setProperty("--_lr-map-scale-width",width)}for(const edge of["top","bottom"]){const height=Math.max(0,...[...container.querySelectorAll(`.maplibregl-ctrl-${edge}-left, .maplibregl-ctrl-${edge}-right`)].map(corner=>corner.offsetHeight)),base=container.parentElement,name=`--_lr-map-controls-${edge}`,value=`${height}px`;base&&base.style.getPropertyValue(name)!==value&&base.style.setProperty(name,value)}}}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const selectors=[[".maplibregl-marker","marker"],[".maplibregl-popup","popup"],[".maplibregl-popup-content","popup-content"],[".maplibregl-popup-close-button","popup-close-button"],[".maplibregl-control-container","controls"],[".map-control-row-top","controls-top"],[".map-control-row-bottom","controls-bottom"],[".maplibregl-ctrl-top-left","controls-top-left"],[".maplibregl-ctrl-top-right","controls-top-right"],[".maplibregl-ctrl-bottom-left","controls-bottom-left"],[".maplibregl-ctrl-bottom-right","controls-bottom-right"],[".maplibregl-ctrl-attrib","attribution"],[".maplibregl-ctrl-attrib a","attribution-link"],[".maplibregl-ctrl-attrib-button","attribution-toggle"],[".maplibregl-ctrl-attrib-inner","attribution-content"],[".maplibregl-ctrl-group:has(.maplibregl-ctrl-zoom-in, .maplibregl-ctrl-compass)","navigation"],[".maplibregl-ctrl-zoom-in","zoom-in"],[".maplibregl-ctrl-zoom-out","zoom-out"],[".maplibregl-ctrl-compass","compass"],[".maplibregl-ctrl-scale","scale"],[".maplibregl-ctrl:has(.maplibregl-ctrl-geolocate)","geolocate-control"],[".maplibregl-ctrl-geolocate","geolocate"],[".maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon","zoom-in-icon"],[".maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon","zoom-out-icon"],[".maplibregl-ctrl-compass .maplibregl-ctrl-icon","compass-icon"],[".maplibregl-ctrl-geolocate .maplibregl-ctrl-icon","geolocate-icon"],[".map-scene-globe-control","globe-control"],[".map-scene-globe-control button","globe-button"],[".map-scene-globe-control .map-scene-control-icon","globe-icon"],[".map-scene-terrain-control","terrain-control"],[".map-scene-terrain-control button","terrain-button"],[".map-scene-terrain-control .map-scene-control-icon","terrain-icon"]];for(const[selector,part]of selectors){const candidate=root,elements=[];candidate.matches?.(selector)&&elements.push(candidate),(!(root instanceof Element)||root.childElementCount>0)&&elements.push(...root.querySelectorAll(selector));for(const element of elements){if(addPartToken(element,part),part.endsWith("-icon")&&element.setAttribute("aria-hidden","true"),part==="geolocate")for(const[state2,statePart]of[["waiting","geolocate-waiting"],["active","geolocate-active"],["background","geolocate-background"],["error","geolocate-error"]]){const present=state2==="error"?element.classList.contains("maplibregl-ctrl-geolocate-active-error")||element.classList.contains("maplibregl-ctrl-geolocate-background-error"):element.classList.contains(`maplibregl-ctrl-geolocate-${state2}`);element.part.toggle(statePart,present)}if(part==="attribution"||part==="attribution-toggle"||part==="attribution-content"){const attribution=element.closest(".maplibregl-ctrl-attrib");element.part.toggle("attribution-expanded",!!attribution&&attributionExpanded(attribution))}if(part==="scale"){const text=element.textContent??"",unit=[...this.scaleLabels.keys()].sort((a,b)=>b.length-a.length).find(value=>text.endsWith(` ${value}`)||text.endsWith(` ${value}`));if(unit){const key=this.scaleLabels.get(unit),translated=this.localize(MAP_SCALE_UNIT_MESSAGE[key]);this.scaleLabels.set(translated,key);const next=text.slice(0,-unit.length)+translated;next!==text&&(element.textContent=next)}}const label=part==="attribution-toggle"?this.localize("mapToggleAttribution"):part==="zoom-in"?this.localize("zoomIn"):part==="zoom-out"?this.localize("zoomOut"):part==="compass"?this.localize("mapResetNorth"):part==="geolocate"?this.localize(element.disabled?"mapGeolocateUnavailable":"mapGeolocateFindLocation"):void 0;label!==void 0&&(element.getAttribute("aria-label")!==label&&element.setAttribute("aria-label",label),element.getAttribute("title")!==label&&element.setAttribute("title",label))}}}syncAttributionState(){const root=this.controlLifecycle?.ownedRoot("attribution"),container=this.containerEl;if(!root||!container||!this.isConnected||!container.contains(root)){this.attributionState=void 0;return}const expanded=attributionExpanded(root),previous=this.attributionState;if(previous?.root!==root){this.attributionState={root,expanded};return}previous.expanded!==expanded&&(previous.expanded=expanded,this.emit("lr-map-attribution-toggle",{expanded}))}syncPeerAttributionExpansion(container){for(const controls of container.querySelectorAll(".maplibregl-control-container")){const expanded=[...controls.querySelectorAll(".maplibregl-ctrl-attrib")].some(attributionExpanded);for(const node of[controls,...controls.querySelectorAll(".map-control-row, .maplibregl-ctrl-top-left, .maplibregl-ctrl-top-right, .maplibregl-ctrl-bottom-left, .maplibregl-ctrl-bottom-right")])node.part.toggle("controls-attribution-expanded",expanded)}}observePeerChrome(){const container=this.containerEl;if(!container||(syncMapControlRows(container,()=>this.isConnected&&this.containerEl===container),!this.isConnected||this.containerEl!==container)||(this.syncPeerChromeParts(container),this.syncPeerAttributionExpansion(container),this.observedPeerContainer===container&&this.peerChromeObserver))return;this.stopObservingPeerChrome();const MutationObserverCtor=container.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;this.observedPeerContainer=container;const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(ResizeObserverCtor){const observer2=new ResizeObserverCtor(()=>this.schedulePeerControlInsets(observer2,container));this.peerControlsResizeObserver=observer2;for(const corner of container.querySelectorAll(".maplibregl-ctrl-top-left, .maplibregl-ctrl-top-right, .maplibregl-ctrl-bottom-left, .maplibregl-ctrl-bottom-right"))this.peerControlsResizeObserver.observe(corner)}this.measurePeerControlInsets(container);const observer=new MutationObserverCtor(records=>{if(!this.isConnected||this.containerEl!==container||this.peerChromeObserver!==observer)return;let elementsChanged=!1,attributionChanged=!1;for(const record of records)if(container.contains(record.target)){if(record.type==="attributes"&&record.target instanceof Element){if(record.attributeName==="class"&&!record.target.matches(".maplibregl-ctrl-geolocate, .maplibregl-ctrl-attrib"))continue;this.syncPeerChromeParts(record.target),record.target.matches(".maplibregl-ctrl-attrib")&&(attributionChanged=!0)}record.type==="characterData"&&record.target.parentElement&&this.syncPeerChromeParts(record.target.parentElement),record.type==="childList"&&record.target instanceof Element&&record.target.matches(".maplibregl-ctrl-scale")&&this.syncPeerChromeParts(record.target);for(const node of record.removedNodes)node.nodeType===1&&(elementsChanged=!0);for(const node of record.addedNodes){if(node.nodeType!==1||!container.contains(node))continue;elementsChanged=!0;const element=node;element.matches('.maplibregl-marker[part~="marker"]')||this.syncPeerChromeParts(element)}}elementsChanged&&syncMapControlRows(container,()=>this.isConnected&&this.containerEl===container&&this.peerChromeObserver===observer),!(!this.isConnected||this.containerEl!==container||this.peerChromeObserver!==observer)&&((elementsChanged||attributionChanged)&&(this.syncPeerAttributionExpansion(container),this.syncAttributionState()),elementsChanged&&this.schedulePeerControlInsets(this.peerControlsResizeObserver,container))});this.peerChromeObserver=observer,observer.observe(container,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["disabled","class","open"]})}syncPopupSemantics(key,marker,popup){const markerElement=marker?.getElement?.();if(!markerElement)return;const id=this.popupId(key);markerElement.setAttribute("aria-controls",id),markerElement.setAttribute("aria-haspopup","dialog"),markerElement.setAttribute("aria-expanded",popup?.isOpen?.()?"true":"false");const popupElement=popup?.getElement?.();if(!popupElement)return;addPartToken(markerElement,"marker"),addPartToken(popupElement,"popup"),popupElement.id=id,popupElement.setAttribute("role","dialog"),popupElement.setAttribute("lang",this.effectiveLocale),popupElement.setAttribute("aria-label",this._markerLabels.get(key)||this.effectiveMapLabel);const popupContent=popupElement.querySelector(".maplibregl-popup-content");popupContent&&addPartToken(popupContent,"popup-content");const closeButton=popupElement.querySelector(".maplibregl-popup-close-button");closeButton&&addPartToken(closeButton,"popup-close-button"),closeButton?.setAttribute("aria-label",this.localize("close"))}syncMapSemantics(markers=!0){const canvas=this._map?.getCanvas?.();if(canvas&&(canvas.setAttribute("aria-label",this.effectiveMapLabel),canvas.setAttribute("lang",this.effectiveLocale),this.legend.length||this.legendGradient.length>=2||this.hasLegendSlot||this.hasLegendStartSlot||this.legendProjection.truncated||this.hasDerivedLegend()?canvas.setAttribute("aria-describedby","map-legend"):canvas.removeAttribute("aria-describedby")),this.hostDescription.refresh(),this.syncPeerChromeParts(),!!markers){for(const[key,marker]of this._markerInstances){const markerElement=marker.getElement?.();if(!markerElement)continue;addPartToken(markerElement,"marker"),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",this._markerLabels.get(key)||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const popup=marker.getPopup?.();popup?this.syncPopupSemantics(key,marker,popup):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}this.syncPeerChromeParts()}}formatDistance(metres){return metres<1e3?getNumberFormat(this.effectiveLocale,{style:"unit",unit:"meter",unitDisplay:"short",maximumFractionDigits:0}).format(metres):getNumberFormat(this.effectiveLocale,{style:"unit",unit:"kilometer",unitDisplay:"short",maximumFractionDigits:metres<1e4?2:1}).format(metres/1e3)}formatArea(squareMetres){return squareMetres<1e6?this.localize("mapSquareMeters",void 0,{value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(squareMetres)}):this.localize("mapSquareKilometers",void 0,{value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:2}).format(squareMetres/1e6)})}drawingSummary(snapshot){if(!snapshot||snapshot.vertices.length<2)return;const metrics=loadMapDrawingRuntime.loaded?.measureDrawing(snapshot.mode,snapshot.vertices);if(metrics)return snapshot.mode==="line"?this.localize("mapDrawingLength",void 0,{value:this.formatDistance(metrics.length)}):metrics.area===void 0?void 0:this.localize("mapDrawingArea",void 0,{value:this.formatArea(metrics.area)})}drawingLabelText(kind,value){return kind==="area"?this.localize("mapDrawingArea",void 0,{value:this.formatArea(value)}):kind==="length"?this.localize("mapDrawingLength",void 0,{value:this.formatDistance(value)}):this.formatDistance(value)}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatCount(this.legend.length===0?0:1),end:this.formatCount(this.legend.length),total:this.formatCount(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendRowContent(entry){const paint=sanitizeCssColor(entry.color);return html`${entry.icon?html`<span
|
|
36
|
+
><span>${this.localize("mapLegend")}</span></button>`:nothing}get hiddenCategories(){return this._hiddenCategories}set hiddenCategories(value){if(value===this._hiddenCategoriesSource)return;const revision=++this._hiddenCategoriesRevision;if(this._hiddenCategoriesSource=value,value===this._hiddenCategories)return;const previous=this._hiddenCategories,normalized=normalizeMapHiddenCategories(value);revision===this._hiddenCategoriesRevision&&(this._hiddenCategories=normalized,this.requestUpdate("hiddenCategories",previous))}get markersTruncated(){const descriptor=getOwnDataDescriptor(this.markers,"length");return typeof descriptor!="symbol"&&typeof descriptor.value=="number"&&descriptor.value>MAX_MAP_MARKERS}setDataLayerIssue(issue){this.pendingDataLayerIssue=issue,this.scheduleAfterUpdate(()=>{const next=this.pendingDataLayerIssue;next!==this.dataLayerIssue&&(this.dataLayerIssue=next,next&&this.isConnected&&this.announcements.announceAssertive(this.localize("mapInitializationFailed")))},"map-data-layer-feedback")}get canonicalChoropleth(){const source=this.choropleth;return Object.is(source,this._canonicalChoroplethSource)?this._canonicalChoropleth:(this._canonicalChoroplethSource=source,this._canonicalChoropleth=projectMapChoropleth(source),this._canonicalChoropleth)}get canonicalDataLayers(){const source=this.dataLayers,base=this.ownerDocument.baseURI,origin=this.ownerDocument.defaultView?.origin??"null";if(Object.is(source,this._canonicalDataLayersSource)&&base===this._canonicalDataLayersBase&&origin===this._canonicalDataLayersOrigin)return this._canonicalDataLayers;this._canonicalDataLayersSource=source,this._canonicalDataLayersBase=base,this._canonicalDataLayersOrigin=origin;const model=projectMapDataLayerModel(source,{baseUrl:base,ownerOrigin:origin,projectGeoJson:projectMapDataLayer});return this.invalidDataLayerModel=!model.ok,model.ok&&(this._canonicalDataLayers=model.geojson,this._canonicalExternalLayers=model.external),this._canonicalDataLayers}get canonicalMarkers(){const source=this.markers;return Object.is(source,this._canonicalMarkersSource)?this._canonicalMarkers:(this._canonicalMarkersSource=source,this._canonicalMarkers=projectMapMarkers(source),this._canonicalMarkers)}get drawingPending(){return this.drawingController?.pending===!0}get drawingWork(){return this.drawingController?.work??NO_DRAWING_WORK}get map(){return this._map}whenStyleReady(){return this.readiness.whenStyleReady()}whenControlsReady(){return this.controlsReadiness.whenReady()}whenIdle(){return this.readiness.whenIdle()}pushGeoJson(source,resolvedSourceId,geojson,projection=projectGeoJson(geojson)){const previous=this._appliedGeoJson.get(resolvedSourceId);if(previous===projection)return;const diff=typeof source.updateData=="function"&&previous!==void 0?buildProjectedGeoJsonPropertyDiff(previous,projection):null;diff===null||typeof source.updateData!="function"?source.setData(geojson):(diff.update.length>0||diff.add?.length||diff.remove?.length)&&source.updateData(diff),this._appliedGeoJson.set(resolvedSourceId,projection)}updateSourceData(sourceId,diff){if(!this._map||!this._styleLoaded||!this.isConnected||typeof sourceId!="string")return!1;const publicId=sourceId.trim(),resolved=this._appliedDataLayerIds.get(publicId)??(this.canonicalChoropleth?.sourceId===publicId?this._appliedChoroplethSourceId:void 0)??(this.ownedFeatures?.ownsGeoJsonSource(publicId)?publicId:void 0);if(!resolved)return!1;const source=this._map.getSource(resolved);return typeof source?.updateData!="function"?!1:(this._appliedGeoJson.delete(resolved),this.readiness.invalidate(),source.updateData(diff),this.readiness.check(),!0)}get safeMaxBounds(){const bounds=this.maxBounds;if(!Array.isArray(bounds)||bounds.length!==2)return null;const[southWest,northEast]=bounds;if(!Array.isArray(southWest)||!Array.isArray(northEast))return null;const[west,south]=southWest,[east,north]=northEast,values=[west,south,east,north].map(Number);if(!values.every(value=>Number.isFinite(value)))return null;const[w,s,e,n]=values;return w>=e||s>=n||w<-180||e>180||s<-90||n>90?null:[[w,s],[e,n]]}applyMaxBounds(){const map=this._map;if(!map||typeof map.setMaxBounds!="function")return;const bounds=this.safeMaxBounds;let zoomBefore,centerBefore;try{if(zoomBefore=map.getZoom(),centerBefore=map.getCenter(),this.constrainTo(map,bounds)||bounds!==null&&typeof zoomBefore=="number"&&Number.isFinite(zoomBefore)&&zoomBefore<1&&this.constrainFromWholeZoom(map,bounds,zoomBefore,centerBefore))return}catch{}try{map.setMaxBounds(null)}catch{}typeof zoomBefore=="number"&&Number.isFinite(zoomBefore)&&map.setZoom(zoomBefore),centerBefore&&map.setCenter([centerBefore.lng,centerBefore.lat]),devWarnOnce("lyra-map-max-bounds-rejected","<lr-map>: maxBounds left maplibre-gl without a usable camera, so it was dropped and the camera restored. This is a peer limitation, not a bad value -- it shows up at sub-1 fractional zooms in wide containers. Raise the zoom, narrow the box, or leave maxBounds unset.")}constrainTo(map,bounds){try{return map.setMaxBounds?.(bounds),bounds===null||Number.isFinite(map.getZoom())}catch{return!1}}applyZoomLimits(){const map=this._map;if(!map||typeof map.setMinZoom!="function"||typeof map.setMaxZoom!="function")return;const revision=++this.zoomLimitRevision,authoredZoom=this.zoom,minZoom=this.minZoom,maxZoom=this.maxZoom,connection=this._connectGeneration,generation=this._styleGeneration,style=this.mapStyle,[min,max]=this.zoomLimits,current=()=>this.isConnected&&this._map===map&&this.zoomLimitRevision===revision&&this._connectGeneration===connection&&this._styleGeneration===generation&&this.mapStyle===style&&Object.is(this.zoom,authoredZoom)&&Object.is(this.minZoom,minZoom)&&Object.is(this.maxZoom,maxZoom);this.writeCamera(()=>{try{const currentMax=map.getMaxZoom?.();typeof currentMax=="number"&&min>currentMax?(map.setMaxZoom(max),map.setMinZoom(min)):(map.setMinZoom(min),map.setMaxZoom(max))}catch{}}),!(!current()||this.zoom>=min&&this.zoom<=max)&&this.scheduleAfterUpdate(()=>{if(!current())return;const shown=readPeerCamera(map);if(!(!current()||!shown||this.zoom===shown.zoom)){this.reflectedCamera={center:shown.center,zoom:shown.zoom},this.reflectingCamera=!0;try{this.zoom=shown.zoom}finally{this.reflectingCamera=!1}}},`map-zoom-limits-${revision}`)}syncImageProvider(){const map=this._map,provider=this.imageProvider;if(!map)return;const apply=runtime2=>{this._map!==map||!this.isConnected||this.imageProvider!==provider||typeof provider!="function"&&!this.ownedFeatures||(this.ownedFeatures??=new runtime2.MapOwnedFeatures).configureImageProvider(map,provider,this)},runtime=loadMapOwnedFeatureRuntime.loaded;if(runtime){apply(runtime);return}if(typeof provider!="function"){this.ownedFeatures?.configureImageProvider(map,void 0,this);return}this.trackFeatureLoad(loadMapOwnedFeatureRuntime().then(apply,()=>{devWarnOnce("lyra-map-image-provider-runtime",`<${this.localName}>: the imageProvider runtime could not be loaded; missing images stay missing.`)}))}constrainFromWholeZoom(map,bounds,zoom,center){try{return map.setMaxBounds?.(null),map.setZoom(1),this.constrainTo(map,bounds)?(map.setZoom(zoom),map.setCenter([center.lng,center.lat]),Number.isFinite(map.getZoom())):!1}catch{return!1}}get safeZoom(){const[min,max]=this.zoomLimits;return finiteRange(this.zoom,2,min,max)}get safeCenter(){const center=Array.isArray(this.center)?this.center:[];return[finiteRange(Number(center[0]),0,-180,180),finiteRange(Number(center[1]),0,-90,90)]}fitBounds(bounds,options={}){const box=normalizeFitBounds(bounds);if(!box)return devWarnOnce("lyra-map-fit-bounds-rejected",`<${this.localName}>: fitBounds() ignored a box that is not [[west, south], [east, north]] with finite coordinates, latitudes in [-90, 90], south <= north, and longitudes in [-180, 180] (east may run past 180, up to one full turn east of west, for a box crossing the antimeridian).`),!1;const settings=typeof options=="object"&&options!==null?options:{},maxZoom=settings.maxZoom,fit=Object.freeze({bounds:box,padding:normalizeFitPadding(settings.padding),maxZoom:isFiniteCoordinate(maxZoom)?finiteRange(maxZoom,24,0,24):void 0,animate:settings.animate!==!1});return this.interruptCameraSession("external",!0)?(this.clusterZoomToken+=1,this.deferUntilCameraSettled(()=>this.executeFit(fit))?!0:this.executeFit(fit)):!1}executeFit(fit){const map=this._map;return map?(this.pendingFit=void 0,this.pendingCommand=void 0,this.applyFit(map,fit,fit.animate&&!prefersReducedMotion(this))):(this.pendingCommand=void 0,this.pendingFit=Object.freeze({fit,center:snapshotCenter(this.center),zoom:this.zoom}),!0)}deferUntilCameraSettled(run){return this.cameraUpdatePending?(this.deferredCameraWork.push(run),this.deferredCameraWork.length===1&&this.updateComplete.then(()=>{const work=this.deferredCameraWork;this.deferredCameraWork=[];for(const task of work)task()}),!0):!1}flyTo(options){return this.runCameraCommand("flyTo",options)}easeTo(options){return this.runCameraCommand("easeTo",options)}jumpTo(options){return this.runCameraCommand("jumpTo",options)}acquireCameraSession(callbacks){if(this.cameraSession)throw cameraSessionFailure("already-bound");const map=this._map;if(!map||!this.cameraSessionReady()||typeof map.getBearing!="function"||typeof map.getPitch!="function")throw cameraSessionFailure("unavailable");const owner={map,callbacks,connection:this._connectGeneration,revision:0,released:!1,interrupted:!1,markers:new WeakSet,stopMotion:()=>{},stopContext:()=>{}},current=()=>this.cameraSession===owner&&!owner.released&&this.isConnected&&this._map===map&&this._connectGeneration===owner.connection,prepared=new WeakMap,capture=()=>{if(!current()||typeof map.getBearing!="function"||typeof map.getPitch!="function")throw cameraSessionFailure("unavailable");try{const camera=readPeerCamera(map);if(!camera)throw cameraSessionFailure("unavailable");const result=admitMapViewpoint({...camera,bearing:map.getBearing(),pitch:map.getPitch()});if(!current())throw cameraSessionFailure("unavailable");return result}catch{throw cameraSessionFailure("unavailable")}},retire=(action,stopAnimation)=>{if(!current())return;owner.pendingAction===action&&(owner.pendingAction=void 0,owner.interrupted=!0);const active=owner.active;if(active?.action===action&&(owner.active=void 0,stopAnimation&&active.animated&&typeof map.stop=="function")){owner.stopping=active.marker;try{map.stop()}finally{owner.stopping===active.marker&&(owner.stopping=void 0)}}},lease={current,capture,reducedMotion:()=>prefersReducedMotion(this),start:action=>!current()||!this.cameraSessionReady()||owner.contextLost||owner.active||owner.pendingAction!==void 0&&owner.pendingAction!==action?!1:(owner.pendingAction=action,owner.interrupted=!1,!0),prepare:(action,input,transition)=>{if(!current()||!this.cameraSessionReady()||owner.contextLost)throw cameraSessionFailure("unavailable");const revision=owner.revision,style=this._styleGeneration,pending=owner.pendingAction,valid=()=>current()&&this.cameraSessionReady()&&!owner.contextLost&&owner.revision===revision&&this._styleGeneration===style&&owner.pendingAction===pending,accepted=admitMapViewpoint(input),reduced=prefersReducedMotion(this),kind=reduced?"jump":transition.kind,method=kind==="jump"?"jumpTo":kind==="ease"?"easeTo":"flyTo",readMoving=map.isMoving;if(typeof readMoving!="function"||!valid())throw cameraSessionFailure("unavailable");const moving=readMoving.call(map);if(typeof moving!="boolean"||!valid()||typeof map[method]!="function"||!valid()||(moving||kind!=="jump")&&(typeof map.stop!="function"||!valid()))throw cameraSessionFailure("unavailable");const command=Object.freeze({action,view:Object.freeze({...accepted,zoom:finiteRange(accepted.zoom,2,...this.zoomLimits)}),kind,...transition.duration===void 0?{}:{duration:transition.duration}});return prepared.set(command,{revision:owner.revision,style:this._styleGeneration,reduced}),command},commit:command=>{const admission=prepared.get(command);if(!admission)return!1;const pending=owner.pendingAction;if(pending!==void 0&&pending!==command.action)return!1;const valid=()=>current()&&this.cameraSessionReady()&&!owner.contextLost&&admission.revision===owner.revision&&admission.style===this._styleGeneration&&admission.reduced===prefersReducedMotion(this)&&owner.pendingAction===pending;if(!valid())return!1;prepared.delete(command);const method=command.kind==="jump"?"jumpTo":command.kind==="ease"?"easeTo":"flyTo";let move;try{let readMoving=map.isMoving;if(typeof readMoving!="function"||!valid())return!1;const moving=readMoving.call(map);if(typeof moving!="boolean"||!valid())return!1;if(moving||command.kind!=="jump"){const stop=map.stop;if(typeof stop!="function"||!valid()||moving&&(stop.call(map),!valid()||(readMoving=map.isMoving,typeof readMoving!="function"||!valid())||readMoving.call(map)!==!1||!valid()))return!1}if(move=map[method],typeof move!="function"||!valid())return!1}catch{return!1}owner.pendingAction=void 0,owner.revision+=1,owner.interrupted=!1;const marker={};owner.markers.add(marker);const active={action:command.action,marker,animated:command.kind!=="jump",invoking:!0,completionPending:!1};owner.active=active,this.pendingCommand=void 0,this.pendingFit=void 0,this.clusterZoomToken+=1,this.readiness.invalidate();try{move.call(map,{...command.view,center:[...command.view.center],...command.kind!=="jump"&&command.duration!==void 0?{duration:command.duration}:{}},{[SESSION_COMMAND_EVENT_KEY]:marker})}catch{return owner.active===active&&(owner.active=void 0),!1}finally{active.invoking=!1}return current()&&owner.active===active&&active.completionPending&&(owner.active=void 0,callbacks.complete(active.action)),!0},retire,release:()=>{if(!current())return;owner.pendingAction=void 0;const active=owner.active;active&&retire(active.action,!0),current()&&(owner.released=!0,owner.stopMotion(),owner.stopContext(),this.cameraSession=void 0)}};owner.lease=lease,this.cameraSession=owner;try{capture()}catch(error){throw lease.release(),error}try{owner.stopMotion=observeReducedMotion(this,reduced=>{current()&&callbacks.motion(reduced)});const canvas=map.getCanvas();if(!current()||!canvas||typeof canvas.addEventListener!="function"||typeof canvas.removeEventListener!="function")throw cameraSessionFailure("unavailable");const lost=()=>{owner.contextLost=!0,current()&&this.interruptCameraSession("engine",!1)},restored=()=>{owner.contextLost=!1};if(owner.stopContext=()=>{canvas.removeEventListener("webglcontextlost",lost),canvas.removeEventListener("webglcontextrestored",restored)},canvas.addEventListener("webglcontextlost",lost),!current()||(canvas.addEventListener("webglcontextrestored",restored),!current()))throw cameraSessionFailure("unavailable");return lease}catch{throw owner.stopMotion(),owner.stopContext(),owner.released=!0,this.cameraSession===owner&&(this.cameraSession=void 0),cameraSessionFailure("unavailable")}}cameraSessionReady(){return this.isConnected&&!!this._map&&this._styleLoaded&&!this.failure&&!this.preparingFeatures&&!this.mapUpdateActive&&!this.cameraUpdatePending&&this.deferredCameraWork.length===0&&this.cameraSessionConfigurationRevision===this.cameraSessionConfigurationApplied&&!this.sceneControlsRequestPending&&this.sceneConfiguration?.pending!==!0}interruptCameraSession(reason,stopAnimation){const owner=this.cameraSession;if(!owner||owner.released)return!0;const revision=++owner.revision;if(owner.pendingAction=void 0,owner.interrupted&&reason!=="disconnect"&&reason!=="engine")return!0;owner.interrupted=!0;const active=owner.active;owner.active=void 0;const retired=owner.callbacks.interrupt(reason)===!0;if(this.cameraSession===owner&&!owner.released&&owner.revision===revision&&!owner.active&&owner.pendingAction===void 0&&stopAnimation&&active?.animated&&typeof owner.map.stop=="function"){owner.stopping=active.marker;try{owner.map.stop()}finally{owner.stopping===active.marker&&(owner.stopping=void 0)}}const proceed=!this.cameraSession||this.cameraSession===owner&&owner.revision===revision&&owner.pendingAction===void 0;return retired&&reason!=="disconnect"&&this.isConnected&&this.emit("lr-map-camera-interrupt",Object.freeze({reason})),proceed}cameraSessionMovement(event){const owner=this.cameraSession;if(!owner||this.writingCamera)return;const marker=event?.[SESSION_COMMAND_EVENT_KEY];typeof marker=="object"&&marker!==null&&owner.markers.has(marker)||this.interruptCameraSession(event?.originalEvent?"user":"external",!1)}runCameraCommand(kind,options){const target=normalizeCameraOptions(options,this.zoomLimits);return target?this.interruptCameraSession("external",!0)?(this.clusterZoomToken+=1,this.deferUntilCameraSettled(()=>this.executeCameraCommand(kind,target))?!0:this.executeCameraCommand(kind,target)):!1:(devWarnOnce("lyra-map-camera-command-rejected",`<${this.localName}>: ${kind}() ignored options with no usable center, zoom, bearing or pitch (center is [longitude, latitude]; every number must be finite).`),!1)}executeCameraCommand(kind,target){const map=this._map;return this.pendingFit=void 0,this.pendingCommand=void 0,map?this.applyCameraCommand(map,kind,target,kind!=="jumpTo"&&!prefersReducedMotion(this)):(this.pendingCommand=Object.freeze({kind,target,center:snapshotCenter(this.center),zoom:this.zoom}),!0)}applyCameraCommand(map,kind,target,animate){const command=map[animate?kind:"jumpTo"];if(typeof command!="function")return!1;const{duration,...camera}=target;this.readiness.invalidate();try{command.call(map,{...camera,...animate&&duration!==void 0?{duration}:{}},{[COMMAND_EVENT_KEY]:this.commandToken})}catch{return!1}return!0}applyPendingCommand(){const map=this._map,pending=this.pendingCommand;!map||!pending||(this.pendingCommand=void 0,!(!sameCenterValue(this.center,pending.center)||!Object.is(this.zoom,pending.zoom))&&this.applyCameraCommand(map,pending.kind,pending.target,!1))}fitToData(options={}){const extent=emptyExtent();for(const marker of this.canonicalMarkers)extendExtent(extent,marker.lngLat[0],marker.lngLat[1]);for(const layer of this.canonicalDataLayers)extendExtentWithGeoJson(extent,layer.geojson);const choropleth=this.canonicalChoropleth;choropleth&&extendExtentWithGeoJson(extent,choropleth.geojson);const bounds=extentToBounds(extent);if(!bounds)return!1;const settings=typeof options=="object"&&options!==null?options:{};return this.fitBounds(bounds,{maxZoom:FIT_TO_DATA_MAX_ZOOM,...settings})}project(lngLat){const map=this._map;if(!(!map||typeof map.project!="function")&&!(!Array.isArray(lngLat)||!isFiniteCoordinate(lngLat[0])||!isFiniteCoordinate(lngLat[1])))try{const{x,y}=map.project([lngLat[0],lngLat[1]]);return isFiniteCoordinate(x)&&isFiniteCoordinate(y)?Object.freeze([x,y]):void 0}catch{return}}unproject(point){const map=this._map;if(!(!map||typeof map.unproject!="function")&&!(!Array.isArray(point)||!isFiniteCoordinate(point[0])||!isFiniteCoordinate(point[1])))try{const{lng,lat}=map.unproject([point[0],point[1]]);return isFiniteCoordinate(lng)&&isFiniteCoordinate(lat)?Object.freeze([wrapLongitude(lng),finiteRange(lat,0,-90,90)]):void 0}catch{return}}controlLocale(){const unitText=value=>value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");for(const[native,key]of[["ft","mapScaleFeet"],["m","mapScaleMeters"],["km","mapScaleKilometers"],["mi","mapScaleMiles"],["nm","mapScaleNauticalMiles"]])this.scaleLabels.set(native,key),this.scaleLabels.set(this.localize(MAP_SCALE_UNIT_MESSAGE[key]),key);return{"GeolocateControl.FindMyLocation":this.localize("mapGeolocateFindLocation"),"GeolocateControl.LocationNotAvailable":this.localize("mapGeolocateUnavailable"),"ScaleControl.Feet":unitText(this.localize("mapScaleFeet")),"ScaleControl.Meters":unitText(this.localize("mapScaleMeters")),"ScaleControl.Kilometers":unitText(this.localize("mapScaleKilometers")),"ScaleControl.Miles":unitText(this.localize("mapScaleMiles")),"ScaleControl.NauticalMiles":unitText(this.localize("mapScaleNauticalMiles"))}}syncControls(){const map=this._map;if(!map)return;const ready=this.controlsReadiness.begin(),input=this.controls,connection=this._connectGeneration,projected=normalizeMapControlOptions(input);this.setSceneControlIssue(!1);const wanted=new Map(projected.controls),attribution=isRuntimeRecord(input)?getOwnDataDescriptor(input,"attribution"):MISSING_OWN_DATA_DESCRIPTOR,defaultAttribution=attribution===MISSING_OWN_DATA_DESCRIPTOR||attribution!==UNSAFE_OWN_DATA_DESCRIPTOR&&attribution.value===void 0;(defaultAttribution||projected.diagnostics.some(issue=>issue.kind==="attribution"))&&wanted.set("attribution",normalizeMapControlOptions({attribution:!0}).controls.get("attribution")),this.setControlIssue(projected.diagnostics.length?"mapControlUnavailable":void 0);const current=()=>ready.isCurrent()&&this.isConnected&&this._map===map&&this.controls===input&&this._connectGeneration===connection,requested=[...projected.controls.values()].sort((a,b)=>a.order-b.order);if(this.setControlOutlines(this.controlLifecycle?[]:requested),projected.diagnostics.length&&ready.fail(),typeof map.addControl!="function"||typeof map.removeControl!="function"){this.setControlOutlines([]),wanted.size===0?ready.resolve():ready.fail();return}this.controlPeer?.map!==map&&(this.controlPeer={map,adapter:{addControl:(control,position)=>map.addControl(control,position),removeControl:control=>map.removeControl(control),controlContainer:position=>this.containerEl?.querySelector(`.maplibregl-ctrl-${position}`)??void 0}});const peer=this.controlPeer.adapter,run=({MapControlsLifecycle})=>{if(!current())return Promise.resolve();const lifecycle=this.controlLifecycle??=new MapControlsLifecycle(kind=>loadMapControl(kind,this.engine,this._maplibreModule)),synchronized=lifecycle.sync(peer,wanted,{isCurrent:current,scene:{isCurrent:current,state:kind=>({ready:this._styleLoaded&&!this.failure,busy:!this._styleLoaded||this.sceneControlsRequestPending||this.sceneConfiguration?.pending===!0,label:this.localize(kind==="globe"?"mapGlobe":"mapTerrain")}),unavailable:(kind,unavailable)=>{current()&&kind==="terrain"&&this.setSceneControlIssue(unavailable)}},onEvent:event=>{if(!current())return;if(event.kind==="scene-action"){if(event.action.kind==="globe"){const projection=event.action.pressed===!0?"mercator":"globe";this.projection=projection,this.emit("lr-map-projection-change",Object.freeze({projection,source:"control"}))}else{const terrain=event.action.pressed===!0?null:event.action.terrain;if(terrain===void 0)return;this.terrain=terrain,this.emit("lr-map-terrain-change",Object.freeze({terrain:this.terrain,source:"control"}))}return}if(event.kind==="geolocate-success"){this.pendingControlIssue!=="mapControlUnavailable"&&this.setControlIssue(void 0),event.lngLat&&event.accuracy!==void 0&&this.emit("lr-map-geolocate",{lngLat:event.lngLat,accuracy:event.accuracy});return}const issue=event.kind==="geolocate-out-of-bounds"?"mapGeolocateOutOfBounds":event.code==="permission-denied"?"mapGeolocatePermissionDenied":event.code==="position-unavailable"?"mapGeolocatePositionUnavailable":event.code==="timeout"?"mapGeolocateTimeout":"mapGeolocateError";this.setControlIssue(issue),this.announcements.announceAssertive(this.localize(MAP_CONFIGURATION_MESSAGE[issue])),event.kind==="geolocate-out-of-bounds"?this.emit("lr-map-geolocate-out-of-bounds",{code:event.code}):this.emit("lr-map-geolocate-error",{code:event.code})},onFailure:failure=>{current()&&(ready.fail(),this.setControlOutlines(this.pendingControlOutlines.filter(outline=>outline.kind!==failure.kind)),!(defaultAttribution&&failure.kind==="attribution")&&(this.setControlIssue("mapControlUnavailable"),this.announcements.announceAssertive(this.localize("mapControlUnavailable"))))}});if(current()){const pending=lifecycle.pendingKinds();this.setControlOutlines(requested.filter(outline=>pending.has(outline.kind)))}return synchronized},runtime=loadMapControlRuntime.loaded,sync=!this.controlLifecycle&&wanted.size===0?Promise.resolve():runtime?run(runtime):loadMapControlRuntime().then(run,()=>{current()&&(ready.fail(),[...wanted.keys()].some(kind=>!defaultAttribution||kind!=="attribution")&&(this.setControlIssue("mapControlUnavailable"),this.announcements.announceAssertive(this.localize("mapControlUnavailable"))))});this.trackFeatureLoad(Promise.race([ready.cancelled,sync.then(()=>{current()&&(this.syncPeerChromeParts(),current()&&(this.setControlOutlines([]),this.syncAttributionState(),this.controlLifecycle?.refreshSceneControls(),current()&&ready.resolve()))}).catch(()=>{current()&&(this.setControlOutlines([]),ready.fail())})]))}publishExportIssue(value){this.pendingExportIssue=value,this.scheduleAfterUpdate(()=>{this.exportIssue=this.pendingExportIssue},"map-export-feedback")}reportExportFailure(code){code!=="cancelled"&&(this.publishExportIssue(!0),this.announcements.announceAssertive(this.localize("mapExportUnavailable"))),this.emit("lr-map-export-error",Object.freeze({code}))}cancelImageExport(){this.exportController?.cancel()}exportImage(options){const map=this._map,style=this._styleGeneration,connection=this._connectGeneration;if(!map||!this.isConnected)return this.isConnected&&this.reportExportFailure("not-ready"),Promise.reject(new LyraMapImageExportError("not-ready"));let admitted,invalid=!1;if(options!==void 0)try{if(!isPlainDataRecord(options))throw new TypeError("Invalid export options.");const keys=Reflect.ownKeys(options);if(keys.length>2||keys.some(key=>key!=="type"&&key!=="attribution"))throw new TypeError("Invalid export options.");const snapshot={};for(const key of keys){const descriptor=getOwnDataDescriptor(options,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Invalid export options.");snapshot[String(key)]=descriptor.value}admitted=Object.freeze(snapshot)}catch{invalid=!0}const request={map,style,connection,options:admitted,invalid},run=runtime2=>(this.exportController??=new runtime2.MapImageExportController(this.imageExportHost())).export(request),runtime=loadMapImageExportRuntime.loaded;return runtime?run(runtime):loadMapImageExportRuntime().then(run,()=>{const current=this.isConnected&&this._map===map&&this._styleGeneration===style&&this._connectGeneration===connection;throw current&&this.reportExportFailure("capture-failed"),new LyraMapImageExportError(current?"capture-failed":"cancelled")})}imageExportHost(){return{element:this,current:(map,style,connection)=>this.isConnected&&this._map===map&&this._styleGeneration===style&&this._connectGeneration===connection,generations:()=>[this.featureGeneration,this.drawingEpoch],pending:()=>this.isUpdatePending||this.preparingFeatures||this.drawingPending,onRender:(map,listener)=>this.peerEvents.subscribe(map,"render",listener),clearFeedback:()=>{this.publishExportIssue(!1)},fail:code=>{this.reportExportFailure(code)}}}closeAnchor(){return this.anchorController?.close("api")??!1}focusAnchor(){return this.anchorController?.focus()??!1}anchorRuntime(){if(this.anchorController)return this.anchorController;if(this.anchorLngLat===null||this.anchorLngLat===void 0)return;const runtime=this.anchorPlacementRuntime();return runtime&&(this.anchorController=new runtime.MapAnchorController(this.anchorHost()))}anchorPlacementRuntime(){const runtime=loadMapAnchorRuntime.loaded;if(runtime||this.anchorLoad)return runtime;this.anchorLoad="loading",loadMapAnchorRuntime().then(()=>{this.anchorLoad=void 0,this.isConnected&&this.scheduleAnchorSync()},()=>{this.anchorLoad="failed"})}anchorChildren(){if(this.childAnchors||![...this.childAnchorSet].some(anchor=>anchor.open))return this.childAnchors;const runtime=this.anchorPlacementRuntime();return this.childAnchors=runtime&&new runtime.MapAnchorChildren({...this.anchorMapHost(),engineReady:()=>this._styleLoaded||this.mapLoadEmitted,canvas:()=>{try{return this._map?.getCanvas?.()??null}catch{return null}}},this.childAnchorSet)}[MAP_ANCHOR_SEAM](anchor,operation,value){return operation==="attach"&&this.childAnchorSet.add(anchor),operation==="detach"&&this.childAnchorSet.delete(anchor),operation==="request"&&this.anchorLoad==="failed"&&(this.anchorLoad=void 0),this.anchorChildren()?.run(anchor,operation,value)}syncAnchor(){this.anchorRuntime()?.sync(),this.anchorChildren()?.sync()}scheduleAnchorSync(){this.anchorRuntime()?.schedule(),this.anchorChildren()?.schedule()}anchorMapHost(){return{element:this,container:()=>this.containerEl,map:()=>this._map,generations:()=>[this._styleGeneration,this._connectGeneration],updateActive:()=>this.mapUpdateActive,afterUpdate:(callback,key)=>{this.scheduleAfterUpdate(callback,key)},interactionBlocked:()=>this.mapInteractionBlocked(),direction:()=>this.effectiveDirection}}anchorHost(){return{...this.anchorMapHost(),key:"map-anchor",overlayHost:this,wrapper:()=>this.anchorEl,fence:()=>this.anchorBoundaryEl,content:()=>this.shadowRoot?.querySelector('slot[name="anchor"]'),styleLoaded:()=>this._styleLoaded,request:()=>this.anchorLngLat,boundary:()=>this.anchorBoundary,safeArea:()=>this.anchorSafeArea,closable:()=>this.anchorClosable,pending:()=>this.isUpdatePending,retire:()=>{this.anchorLngLat=null},emitClose:detail=>{this.emit("lr-map-anchor-close",detail)}}}zoomIntoCluster(publicSourceId,hit){const map=this._map,layer=this.canonicalDataLayers.find(entry=>entry.sourceId===publicSourceId);if(!map||!layer?.cluster?.zoomOnClick)return;const clusterId=hit?.properties?.cluster_id,geometry=hit?.geometry;if(typeof clusterId!="number"||geometry?.type!=="Point")return;const[lng,lat]=geometry.coordinates,resolvedId=this._appliedDataLayerIds.get(publicSourceId),source=resolvedId===void 0?void 0:map.getSource(resolvedId);if(!source||typeof source.getClusterExpansionZoom!="function")return;const token=++this.clusterZoomToken;let eased=!1;const ease=zoom=>{eased||token!==this.clusterZoomToken||this._map!==map||!isFiniteCoordinate(zoom)||this.canonicalDataLayers.find(entry=>entry.sourceId===publicSourceId)!==layer||this._appliedDataLayerIds.get(publicSourceId)!==resolvedId||map.getSource(resolvedId)!==source||(eased=!0,this.easeTo({center:[lng,lat],zoom}))};try{const pending=source.getClusterExpansionZoom(clusterId,(error,zoom)=>{error||ease(zoom)});pending&&typeof pending.then=="function"&&pending.then(ease,()=>{})}catch{}}applyCameraPadding(){const map=this._map;if(!map||typeof map.setPadding!="function")return;const authored=normalizeFitPadding(this.cameraPadding),allocation=this.canvasAllocation;this.canvasPaddingUsable=!allocation||authored.left+authored.right<allocation.width-allocation.padding.left-allocation.padding.right&&authored.top+authored.bottom<allocation.height-allocation.padding.top-allocation.padding.bottom;const extra=this.canvasPaddingUsable?authored:ZERO_CAMERA_PADDING,next=allocation?{top:allocation.padding.top+extra.top,right:allocation.padding.right+extra.right,bottom:allocation.padding.bottom+extra.bottom,left:allocation.padding.left+extra.left}:authored,current=this.appliedPadding;next.top===current.top&&next.right===current.right&&next.bottom===current.bottom&&next.left===current.left||(this.appliedPadding=next,this.writeCamera(()=>{try{map.setPadding?.({...next})}catch{}}))}getVisibleBounds(options){const map=this._map;let padded=!0;try{padded=options?.padded!==!1}catch{}return map?this.readVisibleBounds(map,padded)??null:null}readVisibleBounds(map,padded=!0){const generation=this._connectGeneration,document=this.ownerDocument,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===generation&&this.ownerDocument===document;if(this.syncCanvasAllocation(),!(!current()||padded&&this.canvasAllocation&&!this.canvasPaddingUsable))try{const{top,right,bottom,left}=padded?this.appliedPadding:{top:0,right:0,bottom:0,left:0},container=this.containerEl;let west,south,east,north;const width=container?.clientWidth??0,height=container?.clientHeight??0;if((top||right||bottom||left)&&typeof map.unproject=="function"&&width-right>left&&height-bottom>top){const corners=[[left,top],[width-right,top],[width-right,height-bottom],[left,height-bottom]];west=south=1/0,east=north=-1/0;for(const[x,y]of corners){const{lng,lat}=map.unproject([x,y]);if(!current())return;west=Math.min(west,lng),east=Math.max(east,lng),south=Math.min(south,lat),north=Math.max(north,lat)}}else{const box=map.getBounds?.();if(!box||!current()||(west=box.getWest(),!current())||(south=box.getSouth(),!current())||(east=box.getEast(),!current())||(north=box.getNorth(),!current()))return}if(![west,south,east,north].every(isFiniteCoordinate))return;const span=east-west;return span>=360?(west=-180,east=180):(west=wrapLongitude(west),east=west+span),Object.freeze([Object.freeze([west,finiteRange(south,0,-90,90)]),Object.freeze([east,finiteRange(north,0,-90,90)])])}catch{return}}scheduleMoveReport(map){if(this.moveFrame!==void 0)return;const view=ownerWindow(this);if(!view||typeof view.requestAnimationFrame!="function"){this.reportMove(map);return}this.moveFrame=view.requestAnimationFrame(()=>{this.moveFrame=void 0,this.reportMove(map)})}flushMoveReport(map){this.moveFrame!==void 0&&(this.cancelMoveReport(),this.reportMove(map))}cancelMoveReport(){this.moveFrame!==void 0&&(ownerWindow(this)?.cancelAnimationFrame?.(this.moveFrame),this.moveFrame=void 0)}reportMove(map){const generation=this._connectGeneration,document=this.ownerDocument,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===generation&&this.ownerDocument===document;if(!current()||(this.syncAnchor(),!current()))return;const camera=readPeerCamera(map);if(!current()||!camera)return;const bounds=this.readVisibleBounds(map);current()&&this.emit("lr-map-move",bounds?{...camera,bounds}:{...camera})}applyFit(map,fit,animate){const generation=this._connectGeneration,document=this.ownerDocument;if(this.syncCanvasAllocation(),!this.isConnected||this._map!==map||this._connectGeneration!==generation||this.ownerDocument!==document)return!1;const allocation=this.canvasAllocation,padding=this.appliedPadding;if(allocation&&(!this.canvasPaddingUsable||padding.left+padding.right+fit.padding.left+fit.padding.right>=allocation.width||padding.top+padding.bottom+fit.padding.top+fit.padding.bottom>=allocation.height)||typeof map.fitBounds!="function")return!1;const[[west,south],[east,north]]=fit.bounds,[minZoom,maxZoom]=this.zoomLimits,fitMaxZoom=fit.maxZoom!==void 0?finiteRange(fit.maxZoom,maxZoom,minZoom,maxZoom):this.zoomLimitsRequested?maxZoom:void 0;this.readiness.invalidate();try{map.fitBounds([[west,south],[east,north]],{padding:{...fit.padding},...fitMaxZoom===void 0?{}:{maxZoom:fitMaxZoom},animate},{[FIT_EVENT_KEY]:this.fitToken})}catch{return!1}return!0}applyPendingFit(){const map=this._map,pending=this.pendingFit;!map||!pending||(this.pendingFit=void 0,!(!sameCenterValue(this.center,pending.center)||!Object.is(this.zoom,pending.zoom))&&this.applyFit(map,pending.fit,!1))}reflectCamera(map,source){const generation=this._connectGeneration,document=this.ownerDocument,current=()=>this.isConnected&&this._map===map&&this._connectGeneration===generation&&this.ownerDocument===document;if(!current())return;const camera=readPeerCamera(map);if(!current()||!camera)return;const center=Object.freeze(camera.center),{zoom}=camera;this.reflectedCamera={center,zoom};const previousCenter=this._center;this.reflectingCamera=!0;try{this._center=center,this.requestUpdate("center",previousCenter),this.zoom=zoom}finally{this.reflectingCamera=!1}if(!current())return;const bounds=this.readVisibleBounds(map);current()&&this.emit("lr-map-view-change",bounds?{center,zoom,source,bounds}:{center,zoom,source})}pushCamera(changed){const reflected=this.reflectedCamera;this.reflectedCamera=void 0;const map=this._map;if(!map||!changed.has("center")&&!changed.has("zoom"))return;const center=this.safeCenter,zoom=this.safeZoom,shown=readPeerCamera(map),showsCenter=camera=>camera!==void 0&¢er[0]===camera.center[0]&¢er[1]===camera.center[1];let pushCenter=changed.has("center")&&!showsCenter(reflected)&&!showsCenter(shown),pushZoom=changed.has("zoom")&&zoom!==reflected?.zoom&&zoom!==shown?.zoom;if(!pushCenter&&!pushZoom)return;let interrupting=!1;try{interrupting=map.isMoving?.()===!0}catch{}interrupting&&(pushCenter=!showsCenter(shown),pushZoom=zoom!==shown?.zoom),this.writeCamera(()=>{pushCenter&&map.setCenter(center),pushZoom&&map.setZoom(zoom)})}writeCamera(write){const previous=this.writingCamera;this.readiness.invalidate(),this.writingCamera=!0;try{write()}finally{this.writingCamera=previous}}connectedCallback(){super.connectedCallback();const generation=++this._connectGeneration;this.observeMapInteractionState(),this.unregisterCameraSession?.(),this.unregisterCameraSession=registerMapCameraSession(this,{acquire:callbacks=>this.acquireCameraSession(callbacks)}),this.unregisterCustomLayers?.(),this.unregisterCustomLayers=registerMapCustomLayers(this,{acquire:callbacks=>this.acquireCustomLayer(callbacks)}),this.connectGeographicScene(),this.readiness.reset(),this.controlsReadiness.reset(),this.hashRuntimeFailed=!1,this.syncHash(),this.visible=!1,this.constructionScheduler?.disconnect();const scheduler=createMapConstructionScheduler(this,()=>{if(!this.isConnected||this._connectGeneration!==generation||this.constructionScheduler!==scheduler)return;this.visible=!0;const activator=this.shadowRoot?.activeElement?.matches?.('[part="initialization-activate"]')===!0;if(this.tryConstructMap(),activator&&this._map)try{this._map.getCanvas()?.focus?.({preventScroll:!0})}catch{}this.scheduleAfterUpdate(()=>{this.isConnected&&this._connectGeneration===generation&&this.constructionScheduler===scheduler&&this.requestUpdate()},`map-construction-${generation}`)});this.constructionScheduler=scheduler,this.constructionMode=this.initializationMode,this.constructionDelay=this.safeInitializationDelay,scheduler.connect(this.constructionMode,this.constructionDelay),this.failure=void 0,this.loading=!0,this._webglReady=!1,(async()=>{let mod;try{mod=await this.loadLibrary(this.engine)}catch{generation===this._connectGeneration&&this.isConnected&&this.failInitialization("missing-peer");return}if(!(generation!==this._connectGeneration||!this.isConnected)){if(this.loading=!1,!mod){this.failInitialization("missing-peer");return}if(this._maplibreModule=mod,!hasMapStyle(this.mapStyle)){this.failInitialization("style-required");return}if(!supportsWebGL2(this)){this.failInitialization("webgl-unavailable");return}this._webglReady=!0,await this.updateComplete,!(generation!==this._connectGeneration||!this.containerEl||!this.isConnected)&&this.constructionScheduler?.setReady(!0)}})()}disconnectedCallback(){super.disconnectedCallback(),this.releaseCanvasAllocation(),this.stopObservingMapInteractionState(),this.interruptCameraSession("disconnect",!1);const session=this.cameraSession;session&&(session.released=!0,session.active=void 0,session.stopMotion(),session.stopContext(),this.cameraSession=void 0),this.unregisterCameraSession?.(),this.unregisterCameraSession=void 0,this.unregisterCustomLayers?.(),this.unregisterCustomLayers=void 0,this.notifyCustomLayers(callbacks=>callbacks.released()),this.customLayerCallbacks.clear(),this.closeGeographicScene(),this.hashOwner?.dispose(),this.disposeMap(),this.constructionScheduler?.disconnect(),this.constructionScheduler=void 0;for(const marker of this._markerInstances.values()){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove()}this._markerInstances.clear(),this._markerColors.clear(),this._markerLabels.clear(),this._markerPopupIds.clear(),this._markerSources.clear()}failureMessage(reason=this.failure??"initialization-failed"){switch(reason){case"missing-peer":return this.localize("mapMissingLibrary",void 0,{package:this.engine==="maplibre"?"maplibre-gl":"@aceshooting/lyra-map"});case"style-required":return this.localize("mapStyleRequired");case"webgl-unavailable":return this.localize("mapWebglUnavailable");case"initialization-failed":return this.localize("mapInitializationFailed")}}failInitialization(reason,partialMap){const connection=this._connectGeneration,generation=this._styleGeneration,style=this.mapStyle;this.readiness.fail(),this.controlsReadiness.fail();try{partialMap&&this.peerEvents.clear(partialMap),partialMap?.remove()}catch{}this.disposeMap(!1);const publish=()=>{!this.isConnected||this._connectGeneration!==connection||this._styleGeneration!==generation||this.mapStyle!==style||this._map||(this.loading=!1,this.failure=reason,this.announcements.announceAssertive(this.failureMessage(reason)))};this.mapUpdateActive?this.scheduleAfterUpdate(publish,`map-initialization-failure-${connection}-${generation}`):publish()}scheduleStyleRequiredFailure(){const generation=this._connectGeneration,module=this._maplibreModule;this.scheduleAfterUpdate(()=>{!this.isConnected||generation!==this._connectGeneration||module!==this._maplibreModule||hasMapStyle(this.mapStyle)||this.failInitialization("style-required")},"map-style-required")}disposeMap(cancelReadiness=!0){this.stopGeographicSceneRender(),this.notifyCustomLayers(callbacks=>callbacks.mapRemoved()),this.interruptCameraSession("engine",!1);const session=this.cameraSession;session&&(session.released=!0,session.stopMotion(),session.stopContext(),this.cameraSession=void 0),this.sceneConfiguration?.cancel(),this.sceneControlsRequestPending=!1,this.setSceneControlIssue(!1),this.cancelImageExport(),this.pendingExportIssue=!1,this.isConnected?this.publishExportIssue(!1):this.exportIssue=!1,this.cancelMapDrawing("disconnect"),this.drawingController?.cancelResources(),cancelReadiness&&(this.readiness.cancel(),this.controlsReadiness.cancel()),this.cancelFeaturePreparation(),this.pointerCleanup?.(),this.pointerCleanup=void 0,this.committedInteractionInputs=void 0,this.mapCursor.clear(),this.hovered=void 0,this.endPointerReports(!1),this.featureStates?.dispose(),this.featureStates=void 0,this.stateRouter.configure([]),this.featureStateLoad==="failed"&&(this.featureStateLoad=void 0),this.stateRequested=!1,this.stateRoutes=[],this.interactions=[],this.sourceIdentities.clear(),this.featureStateIssue=!1,this.preparedFeatureSignature=void 0,this.pendingMapLoad=!1,this.mapLoadEmitted=!1,this.rebuildGeneratedLayers=!1,this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.optionalFeatureWorkStarted=!1,this.controlLifecycle?.dispose(),this.controlPeer=void 0,this.attributionState=void 0,this.setControlOutlines([]),this._map&&this.peerEvents.clear(this._map);try{this._map?.remove()}catch{}this._map=void 0,this.drawingController?.disposeResources(),this.ownedFeatures?.dispose(),this.externalFeatures?.dispose(),this.externalSourceEffects?.dispose(),this.externalSourceEffects=void 0,this.externalFeatureWorkStarted=!1,this.externalSourceIds.clear(),this.plannedDataLayerIds.clear(),this.appliedRowRanges.clear(),this.dataLayerIssue=!1,this.pendingDataLayerIssue=!1,this.groupOrderActive=!1,this.basemapOrder?.reset(),this.pendingDrawingTheme=!1,this.setControlIssue(void 0),this.anchorController?.dispose(),this.childAnchors?.dispose(),this.cancelMoveReport(),this.appliedPadding=ZERO_CAMERA_PADDING,this._styleLoaded=!1,this._styleLayers=EMPTY_STYLE_LAYERS,this._styleSources=EMPTY_STYLE_SOURCES,this.boxZoomSettling=!1,this.reflectedCamera=void 0,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this.appliedChoroplethPaintKey=void 0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this.appliedLayerPaintKeys.clear(),this.appliedPointIcons.clear(),this.appliedPointPaint.clear(),this.appliedGeoLabels.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear()}adoptedCallback(){if(super.adoptedCallback(),this.releaseCanvasAllocation(),this.isConnected&&this.syncCanvasAllocation(),this.observeMapInteractionState(),this.geographicSceneDocument&&this.geographicSceneDocument!==this.ownerDocument){this.interruptCameraSession("disconnect",!1);const session=this.cameraSession;session&&(session.released=!0,session.active=void 0,session.stopMotion(),session.stopContext(),this.cameraSession=void 0),this.closeGeographicScene(),this.isConnected&&this.connectGeographicScene()}this.hostDescription.adopted(),this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.announcements.adopted(),this._map&&this.containerEl&&this.isConnected&&this.observeMapAllocation(this._map,this.containerEl)}tryConstructMap(){if(this.mapUpdateActive){const connection=this._connectGeneration;this.scheduleAfterUpdate(()=>{this.isConnected&&this._connectGeneration===connection&&this.tryConstructMap()},`map-construct-${connection}`);return}if(this._map||!this._maplibreModule||!this._webglReady||!this.containerEl||!this.visible||!this.isConnected)return;if(!hasMapStyle(this.mapStyle)){this.scheduleStyleRequiredFailure();return}this.syncCanvasAllocation();const mod=this._maplibreModule,authoredCenter=this.center,authoredZoom=this.zoom,option=this.hashOption;if(this.syncHash(),!this.hashOwner&&this.hashRequested()&&!this.hashRuntimeFailed)return;const initialHash=this.hashOwner?.read()??{status:"disabled"},hashCamera=initialHash.status==="camera"?initialHash.camera:void 0;let candidate;try{candidate=new mod.Map({container:this.containerEl,style:this.mapStyle,center:hashCamera?[...hashCamera.center]:this.safeCenter,zoom:hashCamera?finiteRange(hashCamera.zoom,this.safeZoom,...this.zoomLimits):this.safeZoom,...this.zoomLimitsRequested?{minZoom:this.zoomLimits[0],maxZoom:this.zoomLimits[1]}:{},...hashCamera?{bearing:hashCamera.bearing,pitch:hashCamera.pitch}:{},attributionControl:!1,...typeof this.renderWorldCopies=="boolean"?{renderWorldCopies:this.renderWorldCopies}:{},locale:{"Map.Title":this.effectiveMapLabel,"Marker.Title":this.localize("mapMarker"),"Popup.Close":this.localize("close"),"AttributionControl.ToggleAttribution":this.localize("mapToggleAttribution"),"AttributionControl.MapFeedback":this.localize("mapFeedback"),"NavigationControl.ZoomIn":this.localize("zoomIn"),"NavigationControl.ZoomOut":this.localize("zoomOut"),"NavigationControl.ResetBearing":this.localize("mapResetNorth"),...this.controlLocale()}}),this.peerEvents.subscribe(candidate,"error",event=>{if(this._map===candidate){if(!this._styleLoaded){this.failInitialization("initialization-failed");return}console.error("lr-map:",event?.error??event)}}),this.peerEvents.subscribe(candidate,"load",()=>{this._map!==candidate||this.mapLoadEmitted||(this.pendingMapLoad=!0,this.flushMapLoad(candidate),this.readiness.whenStyleReady().then(()=>{this.flushMapLoad(candidate)},()=>{}))}),this.peerEvents.subscribe(candidate,"click",event=>{this._map===candidate&&this.handleMapInteraction("click",event)}),this.peerEvents.subscribe(candidate,"contextmenu",event=>{this._map===candidate&&this.handleMapInteraction("contextmenu",event)}),this.peerEvents.subscribe(candidate,"mousemove",event=>{this._map===candidate&&(this.schedulePointerReport(candidate,event),this.drawingController?.preview(mapCoordinates(mapOwnValue(event,"lngLat"))),this.handleMapInteraction("mousemove",event))}),this.peerEvents.subscribe(candidate,"mouseout",()=>{this._map===candidate&&(this.clearMapHover(),this.endPointerReports(),this.drawingController?.preview(void 0))}),this.peerEvents.subscribe(candidate,"movestart",event=>{this._map===candidate&&(event?.originalEvent&&(this.clusterZoomToken+=1),this.cameraSessionMovement(event))}),this.peerEvents.subscribe(candidate,"boxzoomstart",event=>{this._map===candidate&&(this.clusterZoomToken+=1,this.cameraSessionMovement(event))});for(const eventName of["dragstart","zoomstart","rotatestart","pitchstart"])this.peerEvents.subscribe(candidate,eventName,event=>{this._map===candidate&&this.cameraSessionMovement(event)});this.peerEvents.subscribe(candidate,"boxzoomend",()=>{this._map===candidate&&(this.boxZoomSettling=!0)}),this.peerEvents.subscribe(candidate,"move",()=>{this._map===candidate&&(this.anchorController?.invalidate(),this.childAnchors?.invalidate(),this.scheduleMoveReport(candidate),this.drawingController?.scheduleHandles())}),this.peerEvents.subscribe(candidate,"moveend",event=>{if(this._map!==candidate||(this.flushMoveReport(candidate),this.writeHash(candidate),this._map!==candidate))return;const fit=event?.[FIT_EVENT_KEY]===this.fitToken,session=this.cameraSession,sessionMarker=event?.[SESSION_COMMAND_EVENT_KEY],sessionAction=session?.active&&session.active.marker===sessionMarker?session.active:void 0,sessionStopping=sessionMarker!==void 0&&session?.stopping===sessionMarker,command=event?.[COMMAND_EVENT_KEY]===this.commandToken||sessionAction!==void 0||sessionStopping,afterBoxZoom=!fit&&!command&&this.boxZoomSettling;if(!fit&&!command&&(this.boxZoomSettling=!1),this.writingCamera)return;const source=fit?"fit":command?"command":event?.originalEvent||afterBoxZoom?"user":void 0;source&&this.reflectCamera(candidate,source),session&&sessionAction&&this.cameraSession===session&&session.active===sessionAction&&!session.released&&(sessionAction.invoking?sessionAction.completionPending=!0:(session.active=void 0,session.callbacks.complete(sessionAction.action)))});const canvas=candidate.getCanvas?.();if(canvas&¬ifyMapCanvasReady(this,canvas),this._map=candidate,canvas&&this.observeMapInteractions(canvas),this.beginStyleReadiness(candidate,!0),!this.isConnected||this._map!==candidate||(this.syncMapSemantics(),this.observeMapAllocation(candidate,this.containerEl),this.syncGeographicSceneRender(),!this.isConnected||this._map!==candidate))return;this.observePeerChrome(),this.failure=void 0}catch{this.failInitialization("initialization-failed",candidate);return}if(this.applyMaxBounds(),!this.isConnected||this._map!==candidate)return;if(hashCamera){this.pendingFit=void 0;const connection=this._connectGeneration,shown=readPeerCamera(this._map);if(!this.isConnected||this._map!==candidate||this._connectGeneration!==connection)return;shown&&this.hashOption===option&&this.center===authoredCenter&&this.zoom===authoredZoom&&(this.reflectedCamera={center:shown.center,zoom:shown.zoom},this.scheduleAfterUpdate(()=>{if(!(!this.isConnected||this._map!==candidate||this._connectGeneration!==connection||this.hashOption!==option||this.center!==authoredCenter||this.zoom!==authoredZoom)){this.reflectingCamera=!0;try{this.center=shown.center,this.zoom=shown.zoom}finally{this.reflectingCamera=!1}}},`map-initial-hash-${connection}`))}this.applyCameraPadding(),this.syncControls(),this.syncAnchor(),this.syncImageProvider();const initialized=this._map;this.pendingFit?this.scheduleAfterUpdate(()=>{this._map===initialized&&(this.applyPendingFit(),initialized&&this.writeHash(initialized))},"map-pending-fit"):this.pendingCommand?this.scheduleAfterUpdate(()=>{this._map===initialized&&(this.applyPendingCommand(),initialized&&this.writeHash(initialized))},"map-pending-command"):initialized&&this.writeHash(initialized)}flushMapLoad(map=this._map){!map||this._map!==map||!this.isConnected||!this.pendingMapLoad||!this._styleLoaded||this.preparingFeatures||this.sceneConfiguration?.pending||this.isUpdatePending||(this.pendingMapLoad=!1,this.mapLoadEmitted=!0,this.emit("lr-map-load"))}beginStyleReadiness(map,initial,mutate,waitForStyleLoad=!1){const connection=this._connectGeneration,styleGeneration=this._styleGeneration,style=this.mapStyle,current=()=>this.isConnected&&this._map===map&&connection===this._connectGeneration&&styleGeneration===this._styleGeneration&&style===this.mapStyle;let started=!1;const startRestoration=()=>{started||!current()||(started=!0,this._styleLoaded=!0,this.captureStyleCatalog(map),this.geographicSceneRender?.styleReady(),current()&&(this.notifyCustomLayers(callbacks=>callbacks.styleReady(map)),current()&&(this.syncSceneConfiguration(),this.controlLifecycle?.refreshSceneControls(),current()&&(this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this.appliedChoroplethPaintKey=void 0,this._appliedDataLayerIds.clear(),this.plannedDataLayerIds.clear(),this.appliedRowRanges.clear(),this._appliedDataLayerShapes.clear(),this.appliedLayerPaintKeys.clear(),this.appliedPointPaint.clear(),this.appliedGeoLabels.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear(),this.rebuildGeneratedLayers=!0,initial&&this.applyMarkers(),this.reconcileGeneratedLayers(),this.anchorLngLat?this.scheduleAnchorSync():this.childAnchors?.schedule()))))};this.readiness.bind({subscribe:(event,listener)=>{const types=event==="style-ready"?["load","style.load"]:event==="busy"?["movestart","move","dataloading"]:[event];let active=!0;const removers=[],dispose=()=>{active=!1;for(const remove of removers)try{remove()}catch{}};try{for(const type of types)removers.push(this.peerEvents.subscribe(map,type,()=>{if(!(!active||!current()))try{event==="style-ready"&&startRestoration(),active&¤t()&&listener()}catch{current()&&this.readiness.fail()}}))}catch(error){throw dispose(),error}return dispose},mutate:initial?mutate:()=>{this.peerEvents.rotate(map),current()&&mutate?.()},isStyleReady:()=>{if(waitForStyleLoad)return!1;const ready=typeof map.isStyleLoaded=="function"?map.isStyleLoaded()===!0:typeof map.loaded=="function"&&map.loaded()===!0;return ready&&startRestoration(),ready},isIdle:()=>typeof map.isMoving=="function"&&map.isMoving()?!1:typeof map.loaded=="function"?map.loaded()===!0:void 0,ownerPending:()=>this.isUpdatePending||this.preparingFeatures||this.drawingPending||this.sceneConfiguration?.pending===!0||this.featureLoads>0||!current(),restore:async signal=>{if(!current()||signal.aborted)return;startRestoration();let work=this.featureWork,drawingWork=this.drawingWork,sceneWork=this.sceneConfiguration?.work;for(;;){if(await Promise.all([work,drawingWork,sceneWork]),!current()||signal.aborted||this.isUpdatePending&&(await this.updateComplete,!current()||signal.aborted)||work===this.featureWork&&drawingWork===this.drawingWork&&sceneWork===this.sceneConfiguration?.work)return;work=this.featureWork,drawingWork=this.drawingWork,sceneWork=this.sceneConfiguration?.work}},onStyleReady:generation=>{this.emit("lr-map-style-load",{generation})},onIdle:generation=>{this.emit("lr-map-idle",{generation})},onError:styleWasReady=>{styleWasReady||this._styleLoaded&&!this.preparingFeatures&&this.mapLoadEmitted||this.scheduleAfterUpdate(()=>{current()&&this.failInitialization("initialization-failed")},`map-readiness-failure-${styleGeneration}`)}})}requestUpdate(...args){args[0]===void 0&&(this.geoJsonRefreshRequested=!0),args[0]==="zoom"&&!this.reflectingCamera&&(this.zoomLimitRevision=(this.zoomLimitRevision??0)+1),super.requestUpdate(...args);const valueChanged=args[0]===void 0||!Object.is(args[1],Reflect.get(this,args[0]));if(this.isConnected&&valueChanged&&["mapStyle","projection","terrain","minZoom","maxZoom","maxBounds","cameraPadding"].includes(String(args[0]))&&(this.cameraSessionConfigurationRevision+=1),this.cameraSession&&valueChanged&&!this.reflectingCamera){const property2=args[0];if(property2==="mapStyle"||property2==="projection"||property2==="terrain")this.interruptCameraSession("style",!0);else if(property2==="minZoom"||property2==="maxZoom"||property2==="maxBounds"||property2==="cameraPadding")this.interruptCameraSession("external",!0);else if(property2==="center"||property2==="zoom"){const shown=this._map&&readPeerCamera(this._map);(property2==="center"?shown&&sameCenterValue(this.safeCenter,shown.center):shown?.zoom===this.safeZoom)||(this.cameraUpdatePending=!0,this.interruptCameraSession("external",!0))}}if((args[0]==="projection"||args[0]==="terrain")&&this.isUpdatePending&&(this.sceneRequest=(this.sceneRequest??0)+1,this.sceneControlsRequestPending=!0,this.controlLifecycle?.refreshSceneControls()),valueChanged&&args[0]==="mapStyle"&&this.isUpdatePending&&(this.sceneControlsRequestPending=!0,this.controlLifecycle?.refreshSceneControls()),valueChanged&&(args[0]===void 0||["mapStyle","dataLayers","choropleth","overlays","images","styleOverrides","interactiveBasemapLayers"].includes(String(args[0])))&&(this.drawingConfigRevision=(this.drawingConfigRevision??0)+1),valueChanged&&(args[0]===void 0||["anchorLngLat","anchorBoundary","anchorSafeArea","anchorClosable","mapStyle","dir"].includes(String(args[0])))){this.anchorSyncRequested=!0,args[0]==="anchorLngLat"&&this.anchorLoad==="failed"&&(this.anchorLoad=void 0);const anchor=this.anchorController;anchor&&!anchor.closing&&(args[0]==="mapStyle"||args[0]==="anchorLngLat"&&!this.anchorLngLat)?anchor.hide(!0,!0):anchor?.stop()}const drawing=this.drawingController?.active===!0;valueChanged&&!this.drawingResetting&&args[0]==="drawMode"&&(drawing||args[1]==="line"||args[1]==="polygon")&&this.cancelMapDrawing("mode-change",!0,args[1]==="polygon"?"polygon":"line"),valueChanged&&args[0]==="drawMode"&&this.drawingLoad==="failed"&&(this.drawingLoad=void 0),valueChanged&&args[0]==="pickMode"&&this.pickMode&&(drawing||this.drawMode==="line"||this.drawMode==="polygon")&&this.cancelMapDrawing("pick-mode"),valueChanged&&this.isUpdatePending&&(args[0]===void 0||["mapStyle","dataLayers","choropleth","overlays","images","styleOverrides","interactiveBasemapLayers"].includes(String(args[0])))&&(this.interactionGeneration=(this.interactionGeneration??0)+1,this.featureStates?.cancel()),valueChanged&&args[0]==="controls"&&this.controlsReadiness&&this.isConnected&&this.isUpdatePending&&(this.controlsReadiness.reset(),this.failure&&this.controlsReadiness.fail()),valueChanged&&this.readiness&&this.isConnected&&this.isUpdatePending&&(args[0]==="mapStyle"&&!Object.is(args[1],this.mapStyle)?(this.sceneConfiguration?.cancel(),this.readiness.reset()):(args[0]===void 0||["projection","terrain","center","zoom","minZoom","maxZoom","cameraPadding","maxBounds","dataLayers","choropleth","markers","hiddenCategories","overlays","images","styleOverrides","interactiveBasemapLayers"].includes(String(args[0])))&&this.readiness.invalidate()),(args[0]==="center"||args[0]==="zoom")&&this.isUpdatePending&&!this.reflectingCamera&&(this.clusterZoomToken+=1,this.cameraUpdatePending=!0),this.isUpdatePending&&(args[0]===void 0||["label","lang","locale","strings","markers","legend","legendGradient","hasLegendSlot","hasLegendStartSlot","choropleth","choroplethLegend"].includes(String(args[0])))&&(this.semanticsStale=!0),this.isUpdatePending&&(args[0]===void 0||["label","lang","locale","strings","markers"].includes(String(args[0])))&&(this.markerSemanticsStale=!0)}performUpdate(){this.mapUpdateActive=!0;try{super.performUpdate()}finally{this.mapUpdateActive=!1}}updated(changed){if(super.updated(changed),changed.has("failure")&&this.syncGeographicSceneStatus(),this.sceneRepairFocus&&(this.sceneRepairFocus=!1,this.shadowRoot?.querySelector('[part="scene-toggle"]')?.focus({preventScroll:!0})),this.cameraUpdatePending=!1,this.setAttribute("aria-busy",String(this.loading||!this._map&&!this.failure&&!this.awaitingActivation)),this.legendCollapsed&&(changed.has("legendOpen")||changed.has("legendCollapsible"))){const legend=this.shadowRoot?.querySelector('[part="legend"]');legend&&(legend.scrollTop=0)}if((changed.has("choropleth")||changed.has("legendGradient"))&&this.warnOnLegendChoroplethMismatch(),changed.has("mapStyle")&&(this.cancelImageExport(),this.drawingController?.styleChanging(),this.drawingController?.cancelResources(!0),this._styleGeneration+=1,this.basemapOrder?.reset(),this.cancelFeaturePreparation(),this.preparedFeatureSignature=void 0,this.featureStateLoad==="failed"&&(this.featureStateLoad=void 0)),!changed.has("mapStyle")&&(changed.has("projection")||changed.has("terrain"))&&this.syncSceneConfiguration(),changed.has("imageProvider")&&this._map&&this.syncImageProvider(),changed.has("mapStyle")&&!hasMapStyle(this.mapStyle)&&this._maplibreModule)this.scheduleStyleRequiredFailure();else if(changed.has("mapStyle")&&!this._map&&this._maplibreModule&&hasMapStyle(this.mapStyle))this.tryConstructMap();else if(changed.has("mapStyle")&&this._map){const replaceStyle=typeof this._map.prepareFeatures=="function"||typeof this.mapStyle=="string"||!this._styleLoaded;this._styleLoaded=!1,this._styleLayers=EMPTY_STYLE_LAYERS,this._styleSources=EMPTY_STYLE_SOURCES;const map2=this._map;this.beginStyleReadiness(map2,!1,()=>{for(const sourceId of this.appliedPointIcons.keys())this.removePointIcons(sourceId);this.geographicSceneRender?.invalidateStyle(),this.notifyCustomLayers(callbacks=>callbacks.styleInvalidated()),!(!this.isConnected||this._map!==map2)&&map2.setStyle(this.mapStyle,replaceStyle?{diff:!1}:void 0)},replaceStyle)}else this._styleLoaded&&(this.refreshingGeoJson||changed.has("dataLayers")||changed.has("choropleth")||changed.has("overlays")||changed.has("images")||changed.has("styleOverrides")||changed.has("interactiveBasemapLayers")||changed.has("imageProvider")&&this.preparingFeatures)&&this.reconcileGeneratedLayers();this.sceneControlsRequestPending=!1,this.controlLifecycle?.refreshSceneControls();const constructionMode=this.initializationMode,constructionDelay=this.safeInitializationDelay;(changed.has("initialization")||changed.has("initializationDelay"))&&(constructionMode!==this.constructionMode||constructionMode==="interaction"&&constructionDelay!==this.constructionDelay)&&(this.constructionMode=constructionMode,this.constructionDelay=constructionDelay,this.constructionScheduler?.reconfigure(constructionMode,constructionDelay)),this.constructionScheduler?.setReady(!!this.containerEl&&this._webglReady&&!!this._maplibreModule&&hasMapStyle(this.mapStyle)),changed.has("hiddenCategories")&&this._map&&this._styleLoaded&&this.refreshThemePaint(),this.syncCanvasAllocation(),changed.has("cameraPadding")&&this._map&&(this.applyCameraPadding(),this.geographicSceneRender?.refreshAllocation()),this.pushCamera(changed),changed.has("maxBounds")&&this._map&&this.writeCamera(()=>this.applyMaxBounds()),(changed.has("minZoom")||changed.has("maxZoom"))&&this._map&&this.applyZoomLimits(),changed.has("controls")&&this._map&&this.syncControls(),changed.has("drawingMeasurements")&&this.drawingController?.scheduleHandles(),(changed.has("pickMode")||changed.has("interactionBlocked"))&&(this.clearMapHover(),this.syncMapCursor()),(changed.has("hash")||changed.has("hashFormat"))&&(this.syncHash(),this.applyHash()),this._map&&(this.anchorSyncRequested||["anchorLngLat","anchorBoundary","anchorSafeArea","anchorClosable","dir","strings","lang","locale"].some(name=>changed.has(name)))&&(this.anchorSyncRequested=!1,this.syncAnchor()),changed.has("markers")&&this._map&&this.applyMarkers(),this.semanticsStale&&(this.semanticsStale=!1,this.syncMapSemantics(this.markerSemanticsStale),this.markerSemanticsStale=!1),this.drawingConfigApplied=this.drawingConfigApplying,this.cameraSessionConfigurationApplied=this.cameraSessionConfigurationApplying,this.syncDrawing(),this.readiness.check();const map=this._map;this.pendingMapLoad&&queueMicrotask(()=>{this.flushMapLoad(map)})}willUpdate(changed){if(this.drawingConfigApplying=this.drawingConfigRevision,this.cameraSessionConfigurationApplying=this.cameraSessionConfigurationRevision,super.willUpdate(changed),(this.anchorLngLat!=null||[...this.childAnchorSet].some(anchor=>anchor.open))&&this.effectiveDirection,this.refreshingGeoJson=this.geoJsonRefreshRequested,this.geoJsonRefreshRequested=!1,this.refreshingGeoJson){const choropleth=this.canonicalChoropleth;choropleth&&(this._canonicalChoropleth={...choropleth,geojsonProjection:projectAdmittedGeoJson(choropleth.geojson,!0)}),this._canonicalDataLayers=this.canonicalDataLayers.map(layer=>({...layer,geojsonProjection:projectAdmittedGeoJson(layer.geojson,!0)}))}(changed.has("legendGradient")||changed.has("dataLayers"))&&(this.legendIsLine=this.legendDescribesLine()),this.derivedLegend=this.choroplethLegend&&this.canonicalChoropleth?buildDerivedChoroplethLegend(this.canonicalChoropleth,value=>this.formatCount(value),this.localize("noData")):EMPTY_DERIVED_LEGEND,changed.has("mapStyle")&&!this._map&&this._maplibreModule&&hasMapStyle(this.mapStyle)&&(this._webglReady||(this._webglReady=supportsWebGL2(this)),this.failure=this._webglReady?void 0:"webgl-unavailable",this._webglReady||(this.loading=!1,this.announcements.announceAssertive(this.failureMessage("webgl-unavailable"))))}syncPaintTheme(){const sources=[this.dataLayers,this.choropleth,this.styleOverrides,this.overlays,loadMapOwnedFeatureRuntime.loaded];if(!this.paintThemeSources||sources.some((source,index)=>source!==this.paintThemeSources[index])){this.paintThemeSources=sources;const tokens2=new Set([...Object.values(TONE_TOKEN),...Object.values(ON_TONE_TOKEN),"--lr-map-choropleth-fill-opacity","--lr-map-hidden-category-opacity",DRAWING_COLOR_TOKEN]),inputs=JSON.stringify([this.canonicalDataLayers.map(({geojson:_geojson,geojsonProjection:_projection,...paint})=>paint),[this.canonicalChoropleth?.stops,this.canonicalChoropleth?.stepBaseColor,this.canonicalChoropleth?.noData],loadMapOwnedFeatureRuntime.loaded?.projectMapStyleOverrides(this.styleOverrides),this._canonicalExternalLayers.map(({source:_source,...paint})=>paint)]),overlayPaint=loadMapOwnedFeatureRuntime.loaded?.overlayPaintText(this.overlays)??"";for(const match of overlayPaint.matchAll(/var\(\s*(--[\w-]+)/g))tokens2.add(match[1]);for(const match of inputs.matchAll(/var\(\s*(--[\w-]+)/g))tokens2.add(match[1]);this.paintThemeTokens=[...tokens2]}const style=ownerWindow(this)?.getComputedStyle(this);if(!style)return!1;const tokens=new Set(this.paintThemeTokens),values=[style.color,style.colorScheme];for(const token of tokens){const value=style.getPropertyValue(token).trim();if(values.push(token,value),tokens.size<512)for(const match of value.matchAll(/var\(\s*(--[\w-]+)/g))tokens.add(match[1])}const key=JSON.stringify(values);return this.paintThemeKey===key?!1:(this.paintThemeKey=key,paintColorCache.delete(this),this.appliedLayerPaintKeys.clear(),this.appliedChoroplethPaintKey=void 0,!0)}withMapPaintBatch(apply){const map=this._map;if(!map||!this._styleLoaded||!this.isConnected)return!1;const style=this._styleGeneration,connection=this._connectGeneration,generation=this.featureGeneration,styleInput=this.mapStyle,data=this.dataLayers,choropleth=this.choropleth,hidden=this.hiddenCategories,current=()=>this.isConnected&&this._map===map&&this._styleLoaded&&this._styleGeneration===style&&this._connectGeneration===connection&&this.featureGeneration===generation&&this.mapStyle===styleInput&&this.dataLayers===data&&this.choropleth===choropleth&&this.hiddenCategories===hidden,previous=this.mapPaintBatchActive;this.mapPaintBatchActive=!0;try{return this.mapPaintBatch.run(map,style,current,apply),!0}catch(error){return this.appliedLayerPaintKeys.clear(),this.appliedChoroplethPaintKey=void 0,error instanceof DOMException&&error.name==="AbortError"?this.scheduleAfterUpdate(()=>{this.isConnected&&this._map&&this._styleLoaded&&this.reconcileGeneratedLayers()},"map-paint-reconcile"):current()&&this.failInitialization("initialization-failed"),!1}finally{this.mapPaintBatchActive=previous}}removeMapLayer(id){this.mapPaintBatch.invalidate(id),this._map?.removeLayer(id)}setMapPaint(id,property2,value){this.mapPaintBatchActive?this.mapPaintBatch.write(id,property2,value):this.withMapPaintBatch(()=>{this.mapPaintBatch.write(id,property2,value)})}refreshThemePaint(){return this._canonicalExternalLayers.length||this.externalFeatureWorkStarted||this.optionalFeatureWorkStarted||ownedFeaturesRequested(this.overlays,this.images,this.styleOverrides)?(paintColorCache.delete(this),this.appliedLayerPaintKeys.clear(),this.appliedChoroplethPaintKey=void 0,this.pendingDrawingTheme=!0,this.reconcileGeneratedLayers(),!0):(this.withMapPaintBatch(()=>this.refreshThemePaintBatch()),!1)}refreshThemePaintBatch(){if(paintColorCache.delete(this),!this._map||!this._styleLoaded)return;if(this.preparingFeatures){(this._canonicalExternalLayers.length||this.externalFeatureWorkStarted)&&this.appliedLayerPaintKeys.clear();return}this.readiness.invalidate();const fillOpacity=choroplethFillOpacity(this);if(this._appliedFillLayerId){const choropleth=this.canonicalChoropleth;choropleth&&choropleth.stops.length>0&&this.setMapPaint(this._appliedFillLayerId,"fill-color",this.choroplethColorExpression(choropleth)),this.setMapPaint(this._appliedFillLayerId,"fill-opacity",fillOpacity)}const dataLayersBySourceId=new Map(this.canonicalDataLayers.map(layer=>[layer.sourceId,layer]));for(const[publicSourceId,sourceId]of this._appliedDataLayerIds){const dataLayer=dataLayersBySourceId.get(publicSourceId);if(!dataLayer)continue;this.paintDataLayer(sourceId,dataLayer);const{geojson:_geojson,geojsonProjection:_projection,...paint}=dataLayer;this.appliedLayerPaintKeys.set(sourceId,JSON.stringify(paint))}}setFeatureState(target,patch){if(!this.canWriteFeatureState())return!1;const states=this.featureStateRuntime();if(!states)return!1;const accepted=states.set(target,patch).accepted;return accepted&&(this.stateRequested=!0,this.flushFeatureState()),accepted}getFeatureState(target){return this.featureStates?.get(target)}removeFeatureState(target,key){if(!this.canWriteFeatureState())return!1;const states=this.featureStateRuntime();if(!states)return!1;const accepted=states.remove(target,key).accepted;return accepted&&(this.stateRequested=!0,this.flushFeatureState()),accepted}featureStateRuntime(){if(this.featureStates)return this.featureStates;const runtime=loadMapFeatureStateRuntime.loaded;if(runtime){const states=new runtime.MapFeatureStateRoutes;return states.configure(this.stateRoutes),this.featureStates=states}this.featureStateLoad||(this.featureStateLoad="loading",this.trackFeatureLoad(loadMapFeatureStateRuntime().then(()=>{this.featureStateLoad=void 0},()=>{this.featureStateLoad="failed",this.isConnected&&(this.featureStateIssue=!0)})))}canWriteFeatureState(){const map=this._map,generation=this.interactionGeneration;return!!(map&&this.isConnected&&this._styleLoaded&&!this.preparingFeatures&&!this.isUpdatePending&&featureStatePeer(map)&&this._map===map&&generation===this.interactionGeneration&&!this.isUpdatePending)}flushFeatureState(){const map=this._map,generation=this.interactionGeneration;map&&(this.readiness.invalidate(),this.replayFeatureStates(map,()=>this.isConnected&&this._map===map&&generation===this.interactionGeneration&&!this.isUpdatePending),this.readiness.check())}replayFeatureStates(map,current,signal){if(!this.stateRequested||!current())return;if(!this.stateRoutingAvailable){this.featureStateIssue=!0,this.readiness.fail();return}const states=this.featureStates,result=states&&featureStatePeer(map)?states.replay(map,this._styleGeneration,signal,current):void 0;if(current()){if(!result?.accepted||result.diagnostics.length){this.featureStateIssue=!0,this.readiness.fail();return}if(this.featureStateIssue=!1,result.applied)try{map.triggerRepaint?.()}catch{current()&&(this.featureStateIssue=!0,this.readiness.fail())}}}sourceToken(origin,source,data,shape){const key=JSON.stringify([origin,source]),previous=this.sourceIdentities.get(key);if(previous&&Object.is(previous.data,data)&&previous.shape===shape)return previous.token;const token=Object.freeze({});return this.sourceIdentities.set(key,{data,shape,token}),token}basemapInteractionTargets(){const opted=projectMapBasemapInteractions(this.interactiveBasemapLayers);if(opted)return expandMapStyleLayerTargets(opted,this._styleLayers,entry=>entry).map(({layerId,entry})=>({layerId,interactive:entry.interactive,priority:entry.priority}))}get styleLayers(){return this._styleLayers}get styleSources(){return this._styleSources}captureStyleCatalog(map){let layers=[],sources=[];try{const style=map.getStyle?.(),rawLayers=mapOwnValue(style,"layers"),rawSources=mapOwnValue(style,"sources");if(Array.isArray(rawLayers))for(const layer of rawLayers.slice(0,4096)){const id=mapOwnValue(layer,"id"),type=mapOwnValue(layer,"type"),source=mapOwnValue(layer,"source"),sourceLayer=mapOwnValue(layer,"source-layer");typeof id!="string"||typeof type!="string"||layers.push(Object.freeze({id,type,...typeof source=="string"?{source}:{},...typeof sourceLayer=="string"?{sourceLayer}:{}}))}if(isPlainDataRecord(rawSources))for(const id of Object.keys(rawSources).slice(0,1024)){const type=mapOwnValue(mapOwnValue(rawSources,id),"type");typeof type=="string"&&sources.push(Object.freeze({id,type}))}}catch{layers=[],sources=[]}this._styleLayers=layers.length?Object.freeze(layers):EMPTY_STYLE_LAYERS,this._styleSources=sources.length?Object.freeze(sources):EMPTY_STYLE_SOURCES}mapStateDefinitions(owned){const routes=[],map=this._map;this.stateRoutingAvailable=!0;let identityText=0;if(!map)return routes;const generation=this.interactionGeneration,current=()=>this._map===map&&generation===this.interactionGeneration&&this.isConnected,add=(origin,source,nativeSource,data,shape,sourceLayers)=>{if(identityText+=typeof data=="string"?data.length:0,routes.length>=256||identityText>1048576){this.stateRoutingAvailable=!1;return}routes.push({origin,source,nativeSource,identity:this.sourceToken(origin,source,data,shape),...sourceLayers?{sourceLayers}:{}})},choropleth=this.canonicalChoropleth;choropleth&&add("choropleth",choropleth.sourceId,this._appliedChoroplethSourceId??"",choropleth.geojson,"geojson");for(const row of this.canonicalDataLayers)add("data-layer",row.sourceId,this._appliedDataLayerIds.get(row.sourceId)??"",row.geojson,dataLayerShape(row));for(const row of this._canonicalExternalLayers)row.sourceLayer&&add("data-layer",row.sourceId,this.externalSourceIds.get(row.sourceId)??"",JSON.stringify(row.source),row.sourceLayer,[row.sourceLayer]);for(const source of owned.sources){if(!this.stateRoutingAvailable)break;const type=source.source.type,layers=[...new Set(owned.layers.filter(row=>row.layer.source===source.id).map(row=>row.layer["source-layer"]).filter(value=>typeof value=="string"))].sort();(type==="geojson"||type==="vector"&&layers.length)&&add("overlay",source.id,source.id,...sourceIdentity(source.source,layers),type==="vector"?layers:void 0)}const opted=this.basemapInteractionTargets();if(opted?.length&&this.stateRoutingAvailable){const nativeOwned=new Set([...routes.map(route=>route.nativeSource),...owned.sources.map(source=>source.id),...this.externalSourceIds.values(),...[...this.externalSourceIds.values()].map(id=>`${id}-hit-source`),...this.drawingController?.sourceId?[this.drawingController.sourceId]:[]]),style=map.getStyle?.()??this.mapStyle;if(!current())return[];const sources=mapOwnValue(style,"sources"),groups=new Map;for(const option of opted){const layer=map.getLayer(option.layerId);if(!current())return[];const source=mapOwnValue(layer,"source"),sourceLayer=mapOwnValue(layer,"source-layer");if(!option.interactive||typeof source!="string"||nativeOwned.has(source))continue;let group=groups.get(source);group||groups.set(source,group=new Set),typeof sourceLayer=="string"&&group.add(sourceLayer)}for(const[id,group]of groups){if(!this.stateRoutingAvailable)break;const raw=mapOwnValue(sources,id);let snapshot;const admit=loadMapOwnedFeatureRuntime.loaded?.snapshotMapOwnedFeatureInput;if(!admit)continue;try{snapshot=admit({overlays:{sources:[{id,source:raw}],layers:[]},images:[],styleOverrides:[]})}catch{if(current())continue;return[]}if(!current())return[];const source=snapshot.overlays.sources[0]?.source,type=source?.type,layers=[...group].sort();source&&(type==="geojson"||type==="vector"&&layers.length)&&add("basemap",id,id,...sourceIdentity(source,layers),type==="vector"?layers:void 0)}}return this.stateRoutingAvailable?routes:[]}prepareStateRetirement(owned){const generation=this.interactionGeneration,map=this._map,desired=this.mapStateDefinitions(owned);if(generation!==this.interactionGeneration||map!==this._map)return;for(const old of this.stateRoutes){const next=desired.find(route=>route.origin===old.origin&&route.source===old.source);(!next||next.identity!==old.identity)&&this.featureStates?.invalidateNative(old.origin,old.nativeSource)}const keys=new Set(desired.map(route=>JSON.stringify([route.origin,route.source])));for(const key of this.sourceIdentities.keys())keys.has(key)||this.sourceIdentities.delete(key)}configureMapInteractions(owned,external){const generation=this.interactionGeneration,map=this._map,current=()=>generation===this.interactionGeneration&&map===this._map&&this.isConnected,routes=this.mapStateDefinitions(owned);if(!current())return;const states=this.featureStates;(states?states.configure(routes).accepted&&this.stateRouter.configure(routes):this.stateRouter.configure(routes))?this.stateRoutes=routes:(states?.configure([]),this.stateRouter.configure([]),this.stateRoutes=[],this.stateRequested&&(this.featureStateIssue=!0,this.readiness.fail()));const rules=[],add=(layerId,origin,source,options,sourceLayer,cluster=!1)=>{rules.push({layerId,owner:origin==="basemap"?"basemap":"overlay",origin,source,interactive:options.interactive??!0,priority:options.priority??0,...sourceLayer?{sourceLayer}:{},...cluster?{cluster}:{}})},choropleth=this.canonicalChoropleth;choropleth&&this._appliedFillLayerId&&add(this._appliedFillLayerId,"choropleth",choropleth.sourceId,choropleth);for(const row of this.canonicalDataLayers){const native=this._appliedDataLayerIds.get(row.sourceId);if(native)for(const suffix of QUERYABLE_DATA_LAYER_SUFFIXES)add(`${native}${suffix}`,"data-layer",row.sourceId,row,void 0,suffix==="-cluster")}for(const[layerId,hit]of external.hits){const row=this._canonicalExternalLayers.find(entry=>entry.sourceId===hit.sourceId);row&&add(layerId,"data-layer",row.sourceId,{...row,interactive:row.interactive&&!(row.category&&this.hiddenCategories.includes(row.category))},hit.sourceLayer)}for(const row of owned.layers){const source=row.layer.source,sourceLayer=row.layer["source-layer"];typeof source=="string"&&add(row.layer.id,"overlay",source,row,typeof sourceLayer=="string"?sourceLayer:void 0)}const opted=this.basemapInteractionTargets();if(opted)for(const row of opted){if(this.drawingController?.ownsLayer(row.layerId)===!0||rules.some(rule=>rule.layerId===row.layerId))continue;const layer=map?.getLayer(row.layerId);if(!current())return;const source=mapOwnValue(layer,"source"),sourceLayer=mapOwnValue(layer,"source-layer");typeof source=="string"&&!routes.some(route=>route.origin!=="basemap"&&route.nativeSource===source)&&add(row.layerId,"basemap",source,row,typeof sourceLayer=="string"?sourceLayer:void 0)}current()&&(this.interactions=Object.freeze(rules))}drawingActionAllowed(){return this.isConnected&&!!this._map&&this._styleLoaded&&!this.preparingFeatures&&this.drawingConfigRevision===this.drawingConfigApplied&&!this.mapInteractionBlocked()}mapInteractionAllowed(){return!this.isConnected||!this._map||!this._styleLoaded||this.preparingFeatures&&!this.retainedOverlayInteractions||this.isUpdatePending?!1:!this.mapInteractionBlocked()}mapInteractionBlocked(){for(let node=this;node;node=flattenedParentElement(node))if(node.hasAttribute("inert")||node===this&&node.hasAttribute("disabled"))return!0;return!1}syncMapCursor(){const map=this._map,generation=this.interactionGeneration;if(!map||!this.mapInteractionAllowed()){this.mapCursor.clear();return}try{const canvas=map.getCanvas();if(this._map!==map||generation!==this.interactionGeneration||!this.mapInteractionAllowed())return;this.mapCursor.set(canvas,this.pickMode?"pick":this.drawingController?.active?"drawing":this.hovered?"hover":void 0)}catch{this._map===map&&generation===this.interactionGeneration&&this.mapCursor.clear()}}stopObservingMapInteractionState(){const observer=this.interactionObserver;this.interactionObserver=void 0,observer?.disconnect()}observeMapInteractionState(){if(this.stopObservingMapInteractionState(),!this.isConnected)return;this.interactionBlocked=this.mapInteractionBlocked();const document=this.ownerDocument,generation=this._connectGeneration,MutationObserverCtor=document.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const current=()=>this.isConnected&&this.ownerDocument===document&&this._connectGeneration===generation&&this.interactionObserver===observer,observer=new MutationObserverCtor(()=>{if(!current())return;const blocked=this.mapInteractionBlocked(),map=this._map;this.interactionBlocked=blocked;const unchanged=()=>current()&&this._map===map&&this.mapInteractionBlocked()===blocked;if(blocked){if(this.cancelMapDrawing("disabled"),!unchanged()||(this.clearMapHover(),!unchanged())||(this.anchorController?.hide(),!unchanged()))return;this.childAnchors?.hide()}else this.syncMapCursor(),unchanged()&&this.scheduleAnchorSync()});this.interactionObserver=observer;for(let node=this;node;node=flattenedParentElement(node))observer.observe(node,{attributes:!0,attributeFilter:["inert","disabled"]})}observeMapInteractions(canvas){const map=this._map,current=()=>this._map===map&&this.isConnected,cancel=()=>{current()&&(this.cancelMapDrawing("pointercancel"),this.drawingController?.active||(this.clearMapHover(),this.mapCursor.clear()))},down=()=>{this.suppressDrawingClick=!1},click=event=>{this.suppressDrawingClick&&(this.suppressDrawingClick=!1,event.preventDefault(),event.stopImmediatePropagation())},key=event=>{!current()||!this.keyboardActivation||event.key!=="Enter"&&event.key!==" "||event.repeat||event.isComposing||event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey||this.pickMode||this.drawMode!=="none"||this.drawingController?.active||!this.mapInteractionAllowed()||(event.preventDefault(),this.activateMapCenter())};canvas.addEventListener("pointercancel",cancel,!0),canvas.addEventListener("pointerdown",down,!0),canvas.addEventListener("click",click,!0),canvas.addEventListener("keydown",key),this.pointerCleanup=()=>{canvas.removeEventListener("pointercancel",cancel,!0),canvas.removeEventListener("pointerdown",down,!0),canvas.removeEventListener("click",click,!0),canvas.removeEventListener("keydown",key)}}schedulePointerReport(map,event){const lngLat=mapCoordinates(mapOwnValue(event,"lngLat")),point=mapOwnValue(event,"point"),x=mapOwnValue(point,"x"),y=mapOwnValue(point,"y");if(!lngLat||!isFiniteCoordinate(x)||!isFiniteCoordinate(y)||(this.pendingPointer=Object.freeze({lngLat:Object.freeze([wrapLongitude(lngLat[0]),lngLat[1]]),point:Object.freeze([x,y])}),this.pointerFrame!==void 0))return;const report=()=>{this.pointerFrame=void 0;const detail=this.pendingPointer;this.pendingPointer=void 0,!(!detail||this._map!==map||!this.isConnected||this.mapInteractionBlocked())&&(this.pointerInside=!0,this.emit("lr-map-pointer-move",detail))},view=ownerWindow(this);if(!view||typeof view.requestAnimationFrame!="function"){report();return}this.pointerFrame=view.requestAnimationFrame(report)}endPointerReports(emit=!0){this.pointerFrame!==void 0&&ownerWindow(this)?.cancelAnimationFrame?.(this.pointerFrame),this.pointerFrame=void 0,this.pendingPointer=void 0;const inside=this.pointerInside;this.pointerInside=!1,inside&&emit&&this.isConnected&&this.emit("lr-map-pointer-leave")}clearMapHover(){const previous=this.hovered;this.hovered=void 0,this.mapCursor.clear(),previous&&this.isConnected&&this.emit("lr-map-feature-leave",previous.detail)}editDrawing(snapshot){return this.drawingLoad==="failed"&&(this.drawingLoad=void 0),this.drawingRuntime()?.edit(snapshot)??!1}undoDrawing(){return this.drawingController?.undo()??!1}completeDrawing(){return this.drawingController?.complete()??!1}cancelDrawing(){return this.cancelMapDrawing("cancel")}cancelMapDrawing(reason,keepMode=!1,armedMode=this.drawMode){const drawing=this.drawingController;return drawing?drawing.cancel(reason,keepMode,armedMode):armedMode!=="line"&&armedMode!=="polygon"?!1:(this.drawingIssue=void 0,keepMode||this.resetDrawingMode(),this.drawingEpoch++,this.syncMapCursor(),this.emit("lr-map-draw-cancel",Object.freeze({mode:armedMode,phase:"cancelled",vertices:Object.freeze([]),reason})),!0)}resetDrawingMode(){this.drawingResetting=!0;try{this.drawMode="none"}finally{this.drawingResetting=!1}}syncDrawing(){if(this.mapUpdateActive){this.scheduleAfterUpdate(()=>this.syncDrawing(),"map-sync-drawing");return}const drawing=this.drawingController;if(drawing){drawing.sync();return}if(this.pickMode){this.cancelMapDrawing("pick-mode");return}if(this.mapInteractionBlocked()){this.cancelMapDrawing("disabled");return}(this.drawMode==="line"||this.drawMode==="polygon")&&this.drawingRuntime()?.sync()}drawingRuntime(){if(this.drawingController)return this.drawingController;const runtime=loadMapDrawingRuntime.loaded;if(runtime)return this.drawingController=new runtime.MapDrawingController(this.drawingHost());this.drawingLoad||(this.drawingLoad="loading",this.trackFeatureLoad(loadMapDrawingRuntime().then(()=>{this.drawingLoad=void 0,this.isConnected&&this.syncDrawing()},()=>{this.drawingLoad="failed",this.isConnected&&this.showDrawingError()})))}drawingHost(){return{element:this,map:()=>this._map,styleLoaded:()=>this._styleLoaded,generations:()=>[this._styleGeneration,this._connectGeneration],usable:()=>!this.loading&&!this.failure,epoch:()=>this.drawingEpoch,advanceEpoch:()=>{this.drawingEpoch++},actionAllowed:()=>this.drawingActionAllowed(),interactionAllowed:()=>this.mapInteractionAllowed(),interactionBlocked:()=>this.mapInteractionBlocked(),updateActive:()=>this.mapUpdateActive,afterUpdate:(callback,key)=>{this.scheduleAfterUpdate(callback,key)},emit:(type,state2)=>{this.emit(type,state2)},emitCancel:detail=>{this.emit("lr-map-draw-cancel",detail)},emitVertexEnd:detail=>{this.emit("lr-map-draw-vertex-end",detail)},showError:error=>{this.showDrawingError(error)},clearError:()=>{this.drawingIssue=void 0},resetMode:()=>{this.resetDrawingMode()},suppressClick:()=>{this.suppressDrawingClick=!0},syncCursor:()=>{this.syncMapCursor()},changed:()=>{this.drawingRevision+=1},invalidate:()=>{this.readiness.invalidate()},check:()=>{this.readiness.check()},fail:()=>{this.readiness.fail()},direction:()=>this.effectiveDirection,accentColor:()=>resolvedLayerColor(this,`var(${DRAWING_COLOR_TOKEN})`,"accent"),resolve:(value,property2)=>this.resolveStyleOverride(value,property2)}}showDrawingError(error){this.drawingIssue=error==="invalid-coordinate"?"mapDrawingInvalidCoordinate":error==="duplicate-vertex"?"mapDrawingDuplicateVertex":error==="vertex-limit"?"mapDrawingVertexLimit":error==="too-few-vertices"||error==="empty"?"mapDrawingTooFewVertices":error&&error!=="inactive"?"mapDrawingInvalidGeometry":"mapDrawingUnavailable",this.announcements.announceAssertive(this.drawingErrorMessage())}drawingErrorMessage(){return this.localize(MAP_DRAWING_MESSAGE[this.drawingIssue],void 0,{count:this.drawingIssue==="mapDrawingVertexLimit"?512:this.drawMode==="polygon"?3:2})}activateMapCenter(){const map=this._map;if(map)try{const lngLat=mapCoordinates(map.getCenter());if(!lngLat||this._map!==map)return;const point=map.project?.([lngLat[0],lngLat[1]]),x=point?.x,y=point?.y;if(!isFiniteCoordinate(x)||!isFiniteCoordinate(y)||this._map!==map)return;this.handleMapInteraction("click",{point:{x,y},lngLat:{lng:lngLat[0],lat:lngLat[1]}},"keyboard")}catch{}}handleMapInteraction(kind,event,trigger="pointer"){const drawing=this.drawingController;if(kind==="click"&&trigger==="pointer"&&(this.suppressDrawingClick||drawing?.consumeClick())){this.suppressDrawingClick=!1;return}if(drawing?.dispatching)return;if(this.queryingMap){this.interactionQuery++;return}if(!this.mapInteractionAllowed()){this.clearMapHover();return}const map=this._map,generation=this.interactionGeneration,query2=++this.interactionQuery,style=this.mapStyle,current=()=>this._map===map&&generation===this.interactionGeneration&&query2===this.interactionQuery&&style===this.mapStyle&&this.mapInteractionAllowed();let lngLat,hit,rule,raw;this.queryingMap=!0;try{if(lngLat=mapCoordinates(mapOwnValue(event,"lngLat")),!lngLat||!current())return;if(kind==="click"&&drawing?.active&&!this.pickMode){drawing.editing||drawing.add(lngLat);return}let features;const rules=this.interactions;let zoom=Number.NaN;try{zoom=map.getZoom()}catch{}const result=queryMapHit({getLayer:id=>{const layer=map.getLayer(id),rule2=rules.find(rule3=>rule3.layerId===id),origin2=rule2?.origin;if(origin2==="data-layer"&&Number.isFinite(zoom)){const row=this.committedDataLayers.find(row2=>row2.sourceId===rule2?.source)??this.committedExternalLayers.find(row2=>row2.sourceId===rule2?.source);if(row&&(zoom<row.minZoom||zoom>=row.maxZoom))return}return layer&&mapLayerHittable(map,id,layer,zoom,origin2==="overlay"||origin2==="basemap")?layer:void 0},queryRenderedFeatures:(point,options)=>(features=map.queryRenderedFeatures([point.x,point.y],{layers:[...options.layers]}),features)},mapOwnValue(event,"point"),rules.map(({layerId,owner,interactive,priority})=>({layerId,owner,interactive,priority})),{current});if(!current()||result.status!=="hit"&&result.status!=="none")return;if(result.status==="hit"){if(rule=rules.find(row=>row.layerId===result.hit.layerId),!rule)return;const native=result.hit,target=native.id===void 0?void 0:this.stateRouter.resolve({origin:rule.origin,source:rule.source,id:native.id,...rule.sourceLayer?{sourceLayer:rule.sourceLayer}:{}});hit=Object.freeze({layerId:native.layerId,origin:rule.origin,source:rule.source,properties:native.properties,...native.id===void 0?{}:{id:native.id},...rule.sourceLayer?{sourceLayer:rule.sourceLayer}:{},...target?{target}:{}}),raw=mapOwnValue(features,String(result.featureIndex))}if(!current())return}finally{this.queryingMap=!1}if(!lngLat)return;const interaction=()=>Object.freeze({lngLat,...hit?{hit,feature:detachedMapFeature(raw,hit)}:{}});if(kind==="mousemove"){const key=hit?JSON.stringify([hit.origin,hit.source,hit.sourceLayer??null,hit.layerId,hit.id===void 0?["anonymous",query2]:["id",hit.id]]):void 0;if(key!==this.hovered?.key){if(this.clearMapHover(),!current())return;if(hit&&key){const detail=interaction();this.hovered={key,detail},this.emit("lr-map-feature-enter",detail)}}current()&&this.syncMapCursor();return}if(kind==="contextmenu"){this.emit("lr-map-contextmenu",interaction());return}if(this.pickMode){this.emit("lr-map-pick",Object.freeze({...interaction(),trigger:"pointer"}));return}const clickToken=++this.clusterZoomToken,origin=rule?.cluster?"cluster":rule?.origin,choropleth=this.canonicalChoropleth,noData=origin==="choropleth"&&choropleth?.noData!==void 0&&typeof hit?.properties[choropleth.field]!="number";this.emit("lr-map-click",{lngLat,feature:raw,origin,sourceId:origin==="choropleth"?void 0:rule?.source,...rule?.sourceLayer?{sourceLayer:rule.sourceLayer}:{},...hit?{hit,...hit.target?{target:hit.target}:{}}:{},...noData?{noData:!0}:{},...trigger==="keyboard"?{trigger}:{}}),origin==="cluster"&&rule&&clickToken===this.clusterZoomToken&¤t()&&this.zoomIntoCluster(rule.source,raw)}cancelFeaturePreparation(){this.retainedOverlayInteractions=!1,this.interactionGeneration++,this.featureStates?.cancel(),this.clearMapHover(),this.ownedFeatures?.cancel(),this.externalFeatures?.cancel(),this.finishFeatureWork?.(),this.finishFeatureWork=void 0,this.featureGeneration+=1,this.featureAbort?.abort(),this.featureAbort=void 0,this.preparingFeatures=!1}generatedFeatureRequirements(){const sources={},layers=[],add=(source,types)=>{for(const[index,type]of types.entries())layers.push({id:`${source}-${type}-${index}`,type,source})},choropleth=this.canonicalChoropleth;choropleth&&(sources.choropleth={type:"geojson",data:choropleth.geojson},choropleth.stops.length&&add("choropleth",["fill"]));for(const[index,layer]of this.canonicalDataLayers.entries()){const source=`data-${index}`,cluster=layer.cluster;sources[source]={type:"geojson",data:layer.geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}},layer.kind==="heatmap"?add(source,["heatmap"]):(add(source,cluster?["circle"]:["fill","line","circle"]),(layer.label||cluster&&this.styleProvidesGlyphs()||layer.point?.iconField&&layer.point.icons.length)&&add(source,["symbol"]))}return{sources,layers}}externalLayerInput(owned,identities){identities.externalStyle!==this._styleGeneration&&(identities.externalStyle=this._styleGeneration,identities.external.clear());const reserved=new Set([...owned.sources.map(source=>source.id),...owned.layers.map(layer=>layer.layer.id)]),available=(id,retained)=>!reserved.has(id)&&!reserved.has(`${id}-render`)&&!reserved.has(`${id}-label`)&&!reserved.has(`${id}-hit`)&&!reserved.has(`${id}-hit-source`)&&(!this._map?.getSource(`${id}-hit-source`)&&!this._map?.getLayer(`${id}-hit`)||this.externalFeatures?.ownsLayer(`${id}-hit`)===!0)&&(retained||!this._map?.getSource(id)&&!this._map?.getLayer(`${id}-render`)&&!this._map?.getLayer(`${id}-label`));return buildMapExternalLayers(this._canonicalExternalLayers,{nativeId:row=>{const previous=identities.external.get(row.sourceId);if(previous&&available(previous,this.externalFeatures?.ownsLayer(`${previous}-render`)===!0))return previous;for(let index=0;index<512;index++){const id=`lr-external-layer-${identities.nextExternal++}`;if(available(id,!1))return identities.external.set(row.sourceId,id),id}throw new Error("Map source identity is unavailable.")},color:value=>resolvedLayerColor(this,value,"accent"),styleColor:value=>{const color=resolvedMapPaintColor(this,value,!0);if(!color)throw new Error("Map color could not be resolved.");return color},hidden:new Set(this.hiddenCategories),glyphs:this.styleProvidesGlyphs(),mutedOpacity:hiddenCategoryOpacity(this)})}dataLayerOrderGroups(owned,external,identities){const groups=[];for(const row of this.canonicalDataLayers){const native=this.resolveDataLayerSourceId(row,identities),suffixes=row.kind==="heatmap"?["-heatmap"]:row.cluster?["-cluster",...this.styleProvidesGlyphs()?["-cluster-count"]:[],"-circle"]:["-fill","-line","-circle"];row.kind!=="heatmap"&&row.point?.iconField&&row.point.icons.length&&suffixes.push("-point-icon"),row.label&&suffixes.push("-label"),groups.push({id:row.sourceId,layerIds:suffixes.map(suffix=>`${native}${suffix}`),...row.before?{before:row.before}:{}})}for(const row of this._canonicalExternalLayers){const source=identities.external.get(row.sourceId),layerIds=external.layers.filter(entry=>entry.layer.source===source||entry.layer.source===`${source}-hit-source`).map(entry=>entry.layer.id);groups.push({id:row.sourceId,layerIds,...row.before?{before:row.before}:{}})}for(const entry of owned.layers)groups.push({id:entry.layer.id,layerIds:[entry.layer.id],...entry.before?{before:entry.before}:{}});return groups}nativeLayerOrder(map){const layers=mapOwnValue(map.getStyle?.(),"layers");return Array.isArray(layers)?layers.map(layer=>mapOwnValue(layer,"id")).filter(id=>typeof id=="string"):[]}applyDataLayerOrder(groups,current,basemap){const map=this._map;if(!map||!current())return;const original=this.nativeLayerOrder(map);if(!current())return;const present=new Set(original),active=groups.map(group=>({...group,layerIds:group.layerIds.filter(id=>present.has(id))})).filter(group=>group.layerIds.length),runtime=loadMapOwnedFeatureRuntime.loaded;if(!runtime)throw new Error("Map layer order is unavailable.");const plan=basemap?basemap.plan(original,active):runtime.planMapLayerOrder(original,active);if(!plan.valid||plan.operations.some(operation=>operation.kind!=="move")||plan.operations.length&&!map.moveLayer)throw new Error("Map layer order is unavailable.");if(!basemap){try{for(const operation of plan.operations)if(!current()||(map.moveLayer(operation.id,operation.before),!current()))return}catch(error){const members=new Set(active.flatMap(group=>group.layerIds));for(let index=original.length-1;index>=0&¤t();index--){const id=original[index];if(members.has(id))try{map.moveLayer(id,original[index+1])}catch{break}}throw error}return}const sameOrder=(left,right)=>left.length===right.length&&left.every((id,index)=>id===right[index]),advance=(order,operation)=>{order.splice(order.indexOf(operation.id),1),order.splice(operation.before===void 0?order.length:order.indexOf(operation.before),0,operation.id)};let attempted=0;try{for(const operation of plan.operations)if(!current()||(attempted+=1,map.moveLayer(operation.id,operation.before),!current()))return;const shown=this.nativeLayerOrder(map);if(!current())return;if(!sameOrder(shown,plan.order))throw new Error("Map layer order was not applied.");basemap.commit(plan.order)}catch(error){if(!current())throw error;const shown=this.nativeLayerOrder(map);if(!current())throw error;const prefix=[...original];let rollbackSafe=sameOrder(shown,prefix);for(const operation of plan.operations.slice(0,attempted))advance(prefix,operation),rollbackSafe||=sameOrder(shown,prefix);const members=new Set(plan.operations.slice(0,attempted).map(operation=>operation.id));for(let index=original.length-1;rollbackSafe&&index>=0&¤t();index--){const id=original[index];if(!members.has(id))continue;const live=this.nativeLayerOrder(map);if(!current()||!live.includes(id))break;const before=original.slice(index+1).find(value=>live.includes(value)),restored=live.filter(value=>value!==id);restored.splice(before===void 0?restored.length:restored.indexOf(before),0,id);try{map.moveLayer(id,before)}catch{break}if(!current()||!sameOrder(this.nativeLayerOrder(map),restored))break}throw error}}reconcileGeneratedLayers(){const map=this._map;if(!map||!this._styleLoaded||((this.dataLayerIssue||this.pendingDataLayerIssue)&&(this._canonicalDataLayersSource=UNPROJECTED_MAP_VALUE),this.cancelFeaturePreparation(),this._map!==map||!this.isConnected))return Promise.resolve();this.readiness.invalidate();let finish;const work=new Promise(resolve=>{finish=resolve});this.featureWork=work,this.finishFeatureWork=finish;const generation=this.featureGeneration,connection=this._connectGeneration,styleGeneration=this._styleGeneration,style=this.mapStyle,dataLayers=this.dataLayers,choropleth=this.choropleth,overlays=this.overlays,images=this.images,imageProvider=this.imageProvider,styleOverrides=this.styleOverrides,hiddenCategories=this.hiddenCategories,interactiveBasemapLayers=this.interactiveBasemapLayers,interactionInputs=[map,connection,styleGeneration,style,dataLayers,choropleth,images,imageProvider,styleOverrides,interactiveBasemapLayers,hiddenCategories];let ownedInput,externalInput,orderGroups,basemapOrderDraft,retainGroupOrder=!1,mutationStarted=!1,preparedExternal=!1,finishApplication,settleApplication,rejectApplication;const identities={geojson:new Map(this.plannedDataLayerIds),external:new Map(this.externalSourceIds),nextGeojson:this._nextDataLayerId,nextExternal:this.externalIdCounter,externalStyle:this.externalIdStyle},controller=new AbortController;this.featureAbort=controller,this.preparingFeatures=!0;const current=()=>this.isConnected&&this._map===map&&generation===this.featureGeneration&&connection===this._connectGeneration&&styleGeneration===this._styleGeneration&&style===this.mapStyle&&dataLayers===this.dataLayers&&choropleth===this.choropleth&&overlays===this.overlays&&images===this.images&&imageProvider===this.imageProvider&&styleOverrides===this.styleOverrides&&interactiveBasemapLayers===this.interactiveBasemapLayers&&(!externalInput?.sources.length&&!this.externalFeatureWorkStarted||hiddenCategories===this.hiddenCategories),apply=()=>{if(!current()||controller.signal.aborted)return;mutationStarted=!0,this.plannedDataLayerIds.clear();for(const[key,value]of identities.geojson)this.plannedDataLayerIds.set(key,value);this.externalSourceIds.clear();for(const[key,value]of identities.external)this.externalSourceIds.set(key,value);if(this._nextDataLayerId=identities.nextGeojson,this.externalIdCounter=identities.nextExternal,this.externalIdStyle=identities.externalStyle,this.prepareStateRetirement(ownedInput.overlays),!current()||controller.signal.aborted)return;const next=this.canonicalChoropleth,nextId=next?this.resolveChoroplethSourceId(next.sourceId):void 0;if(this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==nextId&&this.removeChoropleth(),!this.withMapPaintBatch(()=>{this.rebuildGeneratedLayers?(this.applyChoropleth(),this.applyDataLayers(current),this.rebuildGeneratedLayers=!1):(this.applyDataLayers(current),this.applyChoropleth())}))return;const complete=()=>{if(!(!current()||controller.signal.aborted)){if(orderGroups){if(this.applyDataLayerOrder(orderGroups,current,basemapOrderDraft),!current())return;this.groupOrderActive=retainGroupOrder}current()&&(this.committedDataLayers=this._canonicalDataLayers,this.committedExternalLayers=this._canonicalExternalLayers,this.setDataLayerIssue(!1),this.configureMapInteractions(ownedInput.overlays,externalInput),!(!current()||controller.signal.aborted)&&(this.replayFeatureStates(map,current,controller.signal),!(!current()||controller.signal.aborted)&&(this.featureAbort=void 0,this.preparingFeatures=!1,this.retainedOverlayInteractions=!1,this.committedInteractionInputs=interactionInputs,this.syncDrawing(),this.syncMapCursor(),this.pendingDrawingTheme&¤t()&&(this.pendingDrawingTheme=!1,this.drawingController?.repaint()),current()&&(this.flushMapLoad(map),finish(),this.readiness.check()))))}};finishApplication=complete;const completeResources=()=>{preparedExternal?settleApplication?.():complete()},admittedOverlays=ownedInput.overlays;if(!this.optionalFeatureWorkStarted&&!this.externalFeatureWorkStarted&&externalInput.sources.length===0&&admittedOverlays.sources.length===0&&admittedOverlays.layers.length===0&&ownedInput.images.length===0&&ownedInput.styleOverrides.length===0){try{complete()}catch{fail()}return}this.optionalFeatureWorkStarted=!0;const failure=()=>{preparedExternal?rejectApplication?.():current()&&!controller.signal.aborted&&fail()},external=this.externalFeatureWorkStarted||externalInput.sources.length>0;external&&(this.externalFeatureWorkStarted=!0);const reconcileOwned=({MapOwnedFeatures})=>{if(!current()||controller.signal.aborted)return;const owned=this.ownedFeatures??=new MapOwnedFeatures,applyOwned=()=>owned.reconcile(map,styleGeneration,ownedInput,{owner:this,signal:controller.signal,isCurrent:current,beforeSourceChange:change=>{this.featureStates?.refreshNative("overlay",change.id)},isGeneratedLayer:id=>this.externalFeatures?.ownsLayer(id)===!0||id===this._appliedFillLayerId||[...this._appliedDataLayerIds.values()].some(sourceId=>DATA_LAYER_SUFFIXES.some(suffix=>id===`${sourceId}${suffix}`)),resolve:(value,property2)=>this.resolveStyleOverride(value,property2),styleLayers:()=>this._styleLayers});if(external){const applyExternal=()=>(this.externalFeatures??=new MapOwnedFeatures).reconcile(map,styleGeneration,{overlays:{sources:externalInput.sources,layers:externalInput.layers},images:[],styleOverrides:[]},{owner:this,signal:controller.signal,isCurrent:current,isGeneratedLayer:()=>!1,beforeSourceChange:change=>{this.featureStates?.refreshNative("data-layer",change.id)},resolve:value=>value});(this._canonicalExternalLayers.some(row=>!!row.style?.iconIds.length)?applyOwned().then(()=>current()&&!controller.signal.aborted?applyExternal():void 0):applyExternal().then(()=>current()&&!controller.signal.aborted?applyOwned():void 0)).then(completeResources).catch(failure)}else applyOwned().then(completeResources).catch(failure)},runtime=loadMapOwnedFeatureRuntime.loaded;runtime?reconcileOwned(runtime):loadMapOwnedFeatureRuntime().then(reconcileOwned).catch(failure)},fail=()=>{if(current()){if(this.preparingFeatures=!1,this.retainedOverlayInteractions=!1,finish(),!mutationStarted&&this.mapLoadEmitted&&!this.pendingMapLoad){this._canonicalDataLayers=this.committedDataLayers,this._canonicalExternalLayers=this.committedExternalLayers,this.setDataLayerIssue(!0),this.readiness.check();return}if(this.readiness.fail(),!this.mapLoadEmitted||this.pendingMapLoad){this.failInitialization("initialization-failed");return}this.scheduleAfterUpdate(()=>{current()&&this.failInitialization("initialization-failed")},`map-feature-failure-${generation}`)}},begin=input=>{if(this.syncPaintTheme(),!current()||controller.signal.aborted){finish();return}const runtime=loadMapOwnedFeatureRuntime.loaded,owned=runtime?runtime.resolveMapOwnedOverlayPaint(input.overlays,(value,property2)=>this.resolveStyleOverride(value,property2)):input.overlays;ownedInput={...input,overlays:owned};const reserved=new Set([...owned.sources.map(source=>source.id),...owned.layers.map(entry=>entry.layer.id)]);for(const row of this.canonicalDataLayers){const id=this.resolveDataLayerSourceId(row,identities);if(reserved.has(id)||DATA_LAYER_SUFFIXES.some(suffix=>reserved.has(`${id}${suffix}`)))throw new Error("Map resource identity conflicts.")}if(externalInput=this.externalLayerInput(owned,identities),!current()||controller.signal.aborted){finish();return}const overrideOrders=ownedInput.styleOverrides.some(entry=>entry.before!==void 0);if(retainGroupOrder=overrideOrders||this.canonicalDataLayers.some(row=>row.before!==void 0)||this._canonicalExternalLayers.some(row=>row.before!==void 0)||owned.layers.some(row=>row.before!==void 0),this.groupOrderActive||retainGroupOrder){if(!runtime||typeof map.getStyle!="function"||typeof map.moveLayer!="function")throw new Error("Map layer order is unavailable.");if(orderGroups=this.dataLayerOrderGroups(owned,externalInput,identities),overrideOrders||this.basemapOrder?.active){const owner=this.basemapOrder??=new runtime.MapBasemapOrder,generated=new Set(orderGroups.flatMap(group=>group.layerIds));basemapOrderDraft=owner.stage(this.nativeLayerOrder(map),ownedInput.styleOverrides,this._styleLayers,id=>generated.has(id)||id===this._appliedFillLayerId||this.ownedFeatures?.ownsLayer(id)===!0||this.externalFeatures?.ownsLayer(id)===!0||this.drawingController?.ownsLayer(id)===!0)}const planned=basemapOrderDraft?basemapOrderDraft.plan(this.nativeLayerOrder(map),orderGroups):runtime.planMapLayerOrder(this.nativeLayerOrder(map),orderGroups);if(!planned.valid)throw new Error("Map layer order is invalid.");if(planned.diagnostics.some(issue=>issue.code==="missing-anchor")&&devWarnOnce("lyra-map-missing-layer-anchor",`<${this.localName}>: a missing layer anchor appends its group.`),!current()){finish();return}const allGroups=[...orderGroups,...basemapOrderDraft?.groups??[]],anchors=new Map(allGroups.map(group=>[group.id,group.layerIds[0]]));for(const group of allGroups)for(const id of group.layerIds)anchors.has(id)||anchors.set(id,group.layerIds[0]);const translate=entry=>entry.before&&anchors.has(entry.before)?{...entry,before:anchors.get(entry.before)}:entry;ownedInput={...ownedInput,overlays:{sources:owned.sources,layers:owned.layers.map(translate)}},externalInput={...externalInput,layers:externalInput.layers.map(translate)}}const preflight=()=>{const finalOwned=ownedInput.overlays;if(externalInput.sources.length||finalOwned.sources.length||finalOwned.layers.length){if(!runtime)throw new Error("Map resources are unavailable.");runtime.snapshotMapOwnedFeatureInput({overlays:{sources:[...finalOwned.sources,...externalInput.sources],layers:[...finalOwned.layers,...externalInput.layers]},images:ownedInput.images,styleOverrides:ownedInput.styleOverrides})}if(this.canonicalDataLayers.some(row=>row.placementRequested)&&typeof map.setLayerZoomRange!="function")throw new Error("Map layer bounds are unavailable.");const retainInteractions=this.committedInteractionInputs?.every((input2,index)=>input2===interactionInputs[index])===!0&&this.ownedFeatures?.canRetainInteractions(map,styleGeneration,ownedInput.overlays)===!0;!current()||controller.signal.aborted||(this.retainedOverlayInteractions=retainInteractions)},prepare=()=>{if(!current()||controller.signal.aborted||typeof map.prepareFeatures!="function")return;const requirements=this.generatedFeatureRequirements(),signature=JSON.stringify([Object.values(requirements.sources??{}).map(source=>source.type),(requirements.layers??[]).map(layer=>layer.type)]);if(signature!==this.preparedFeatureSignature)return map.prepareFeatures(requirements,{signal:controller.signal}).then(()=>{current()&&!controller.signal.aborted&&(this.preparedFeatureSignature=signature)})};if(externalInput.sources.length||this.externalFeatureWorkStarted){if(!runtime)throw new Error("Map resources are unavailable.");const effects=this.externalSourceEffects??=new runtime.MapExternalSourceEffects,revisions=new Map(this._canonicalExternalLayers.filter(row=>row.kind==="canvas").map(row=>[identities.external.get(row.sourceId),row.redrawRevision??0])),live=()=>this.isConnected&&this._map===map&&this._styleGeneration===styleGeneration&&this._connectGeneration===connection&&this.mapStyle===style;effects.reconcile(map,styleGeneration,externalInput.sources,revisions,{owner:this,signal:controller.signal,isCurrent:current,isLive:live,canPauseCanvas:id=>(this.canonicalDataLayers,!this.invalidDataLayerModel&&this._canonicalExternalLayers.some(row=>row.kind==="canvas"&&this.externalSourceIds.get(row.sourceId)===id&&row.source.animate===!1)),retire:()=>{live()&&this.failInitialization("initialization-failed")}},()=>new Promise((resolve,reject)=>{const aborted=()=>{reject(new Error("Map resource application was superseded."))},clear=()=>{controller.signal.removeEventListener("abort",aborted)};if(preparedExternal=!0,settleApplication=()=>{clear(),resolve()},rejectApplication=()=>{clear(),reject(new Error("Map resources could not be applied."))},controller.signal.addEventListener("abort",aborted,{once:!0}),controller.signal.aborted){clear(),aborted();return}try{apply()}catch(error){clear(),reject(error)}}),async sources=>{externalInput={...externalInput,sources},preflight(),await prepare()}).then(()=>{current()&&!controller.signal.aborted&&finishApplication?.()}).catch(()=>{current()&&!controller.signal.aborted&&fail()});return}if(preflight(),!current()||controller.signal.aborted){finish();return}const preparation=prepare();preparation?preparation.then(apply).catch(()=>{current()&&!controller.signal.aborted&&fail()}):apply()};try{const geojson=this.canonicalDataLayers;if(this.invalidDataLayerModel||geojson.some(layer=>layer.invalidLabel)||geojson.some(layer=>layer.label!==void 0)&&!this.styleProvidesGlyphs())throw new Error("Map labels or sources are unavailable.");const runtime=loadMapOwnedFeatureRuntime.loaded;runtime?begin(runtime.snapshotMapOwnedFeatureInput({overlays,images,styleOverrides})):!this._canonicalExternalLayers.length&&!this.groupOrderActive&&!geojson.some(layer=>layer.before!==void 0)&&!ownedFeaturesRequested(overlays,images,styleOverrides)&&!projectMapBasemapInteractions(interactiveBasemapLayers)?.length?begin(NO_OWNED_FEATURES):loadMapOwnedFeatureRuntime().then(loaded=>{current()&&!controller.signal.aborted&&begin(loaded.snapshotMapOwnedFeatureInput({overlays,images,styleOverrides}))}).catch(fail)}catch{fail()}return work}resolveStyleOverride(value,property2){if(!/(?:-color|-gradient)$/u.test(property2))return value;const resolve=entry=>{if(typeof entry=="string"&&THEME_PAINT_COLOR.test(entry)){const color=resolvedMapPaintColor(this,entry,!0);if(!color)throw new Error("Map color could not be resolved.");return color}return Array.isArray(entry)?entry[0]==="literal"?entry:entry.map(resolve):entry!==null&&typeof entry=="object"?Object.fromEntries(Object.entries(entry).map(([key,child])=>[key,resolve(child)])):entry};return resolve(value)}applyChoropleth(){if(!this._map)return;this.syncPaintTheme();const choropleth=this.canonicalChoropleth;if(!choropleth){this.removeChoropleth();return}const{geojson,geojsonProjection,stops}=choropleth,sourceId=this.resolveChoroplethSourceId(choropleth.sourceId),fillLayerId=`${sourceId}-fill`;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==sourceId&&this.removeChoropleth(),warnOnUntileableProperties(geojsonProjection,"choropleth");const existingSource=this._map.getSource(sourceId);if(existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojsonProjection)),this._appliedChoroplethSourceId=sourceId,stops.length===0)return;const{geojson:_geojson,geojsonProjection:_projection,...paint}=choropleth,paintKey=JSON.stringify(paint);if(this.appliedChoroplethPaintKey===paintKey&&this._map.getLayer(fillLayerId))return;const colorExpr=this.choroplethColorExpression(choropleth),outlineExpr=this.choroplethOutlineExpression(choropleth,colorExpr);this._map.getLayer(fillLayerId)?(this.setMapPaint(fillLayerId,"fill-color",colorExpr),this.setMapPaint(fillLayerId,"fill-opacity",choroplethFillOpacity(this)),this.setMapPaint(fillLayerId,"fill-outline-color",outlineExpr??null)):this._map.addLayer({id:fillLayerId,type:"fill",source:sourceId,paint:{"fill-color":colorExpr,"fill-opacity":choroplethFillOpacity(this),...outlineExpr?{"fill-outline-color":outlineExpr}:{}}}),this.appliedChoroplethPaintKey=paintKey,this._appliedFillLayerId=fillLayerId}choroplethColorExpression(choropleth){const{field,stops}=choropleth,resolvedStops=stops.map(([value,color])=>[value,resolvedLayerColor(this,color,void 0)]);let colorExpr;if(choropleth.interpolation==="step"){const base=choropleth.stepBaseColor?resolvedLayerColor(this,choropleth.stepBaseColor,void 0):resolvedStops[0][1];colorExpr=["step",["get",field],base];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}else{colorExpr=["interpolate",choropleth.interpolation==="logarithmic"?["exponential",CHOROPLETH_LOG_INTERPOLATION_BASE]:["linear"],["get",field]];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}const noData=choropleth.noData;return noData?["case",choroplethHasValueExpression(field),colorExpr,this.choroplethNoDataColor(noData)]:colorExpr}choroplethNoDataColor(noData){return resolvedLayerColor(this,noData.color,"neutral")}choroplethOutlineExpression(choropleth,colorExpr){const stroke=choropleth.noData?.strokeColor;if(!stroke)return;const resolved=resolvedMapPaintColor(this,stroke,!0);if(resolved)return["case",choroplethHasValueExpression(choropleth.field),colorExpr,resolved]}resolveChoroplethSourceId(sourceId){const dataSourceIds=new Set(this.canonicalDataLayers.map(layer=>layer.sourceId));let resolved=sourceId;for(let attempt=0;attempt<512;attempt+=1){const sourceTaken=resolved!==this._appliedChoroplethSourceId&&!!this._map?.getSource(resolved),fillId=`${resolved}-fill`,fillTaken=fillId!==this._appliedFillLayerId&&!!this._map?.getLayer(fillId);if(!dataSourceIds.has(resolved)&&!sourceTaken&&!fillTaken)return resolved;resolved=`lr-choropleth-${resolved}`}throw new Error("Map source namespace is unavailable.")}removeChoropleth(){!this._map||!this._appliedChoroplethSourceId||(this.featureStates?.refreshNative("choropleth",this._appliedChoroplethSourceId),this._appliedFillLayerId&&this._map.getLayer(this._appliedFillLayerId)&&this.removeMapLayer(this._appliedFillLayerId),this._map.getSource(this._appliedChoroplethSourceId)&&this._map.removeSource(this._appliedChoroplethSourceId),this._appliedGeoJson.delete(this._appliedChoroplethSourceId),this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this.appliedChoroplethPaintKey=void 0)}applyDataLayers(transactionCurrent){if(!this._map)return;const map=this._map,dataLayers=this.dataLayers,style=this.mapStyle,generation=this.featureGeneration,current=transactionCurrent??(()=>this.isConnected&&this._map===map&&dataLayers===this.dataLayers&&style===this.mapStyle&&generation===this.featureGeneration),check=()=>{if(!current())throw new DOMException("Map update superseded.","AbortError")};check(),this.syncPaintTheme();const layers=this.canonicalDataLayers,nextIds=new Set(layers.map(layer=>layer.sourceId));for(const publicSourceId of this._appliedDataLayerIds.keys())nextIds.has(publicSourceId)||this.removeDataLayer(publicSourceId);for(const layer of layers){check();const{sourceId:publicSourceId,geojson,geojsonProjection}=layer,shape=dataLayerShape(layer),appliedShape=this._appliedDataLayerShapes.get(publicSourceId),sourceId=this.resolveDataLayerSourceId(layer);appliedShape!==void 0&&appliedShape!==shape&&this.removeDataLayer(publicSourceId),warnOnUntileableProperties(geojsonProjection,publicSourceId);const cluster=layer.cluster,existingSource=this._map.getSource(sourceId);check(),existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}}),check(),this._appliedGeoJson.set(sourceId,geojsonProjection)),check();const{geojson:_geojson,geojsonProjection:_projection,...paint}=layer,paintKey=JSON.stringify(paint);(!existingSource||this.appliedLayerPaintKeys.get(sourceId)!==paintKey)&&(this.applyDataLayerRendering(sourceId,layer,current),check(),this.applyDataLayerRange(sourceId,layer,current),check(),this.appliedLayerPaintKeys.set(sourceId,paintKey)),this._appliedDataLayerIds.set(publicSourceId,sourceId),this._appliedDataLayerShapes.set(publicSourceId,shape)}}applyDataLayerRange(sourceId,layer,current){const map=this._map;if(!map||!layer.placementRequested&&!this.appliedRowRanges.has(sourceId))return;const changes=[];for(const suffix of DATA_LAYER_SUFFIXES){const id=`${sourceId}${suffix}`,native=map.getLayer(id);if(!current())throw new DOMException("Map update superseded.","AbortError");if(!native)continue;const min=Math.max(layer.minZoom,suffix==="-label"?layer.label?.minZoom??0:0),max=layer.maxZoom,rawMin=mapOwnValue(native,"minzoom"),rawMax=mapOwnValue(native,"maxzoom"),oldMin=typeof rawMin=="number"?rawMin:0,oldMax=typeof rawMax=="number"?rawMax:24;(min!==oldMin||max!==oldMax)&&changes.push({id,min,max,oldMin,oldMax})}if(changes.length&&typeof map.setLayerZoomRange!="function")throw new Error("Map layer bounds are unavailable.");const journal=[];try{for(const change of changes){if(!current())throw new DOMException("Map update superseded.","AbortError");if(journal.push(change),map.setLayerZoomRange(change.id,change.min,change.max),!current())throw new DOMException("Map update superseded.","AbortError")}this.appliedRowRanges.set(sourceId,`${layer.minZoom}:${layer.maxZoom}`)}catch(error){for(const change of journal.reverse()){if(!current())break;try{map.setLayerZoomRange(change.id,change.oldMin,change.oldMax)}catch{break}}throw error}}applyDataLayerRendering(sourceId,layer,current){if(layer.kind==="heatmap"){this.applyHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;if(cluster?this.applyClusterLayers(sourceId,layer,cluster):this.applyGeometryLayers(sourceId,layer),!current())throw new DOMException("Map update superseded.","AbortError");if(this.applyPointIcons(sourceId,layer),!current())throw new DOMException("Map update superseded.","AbortError");this.applyGeoLabel(sourceId,layer,current)}paintDataLayer(sourceId,layer){if(layer.kind==="heatmap"){this.paintHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;if(cluster?this.paintClusterLayers(sourceId,layer,cluster):this.paintGeometryLayers(sourceId,layer),this.paintPointIcons(sourceId,layer),layer.label&&this.appliedGeoLabels.has(sourceId)){const descriptor=buildMapLabelLayer(`${sourceId}-label`,sourceId,layer.label,value=>resolvedLayerColor(this,value,layer.tone));for(const[property2,value]of Object.entries(descriptor.paint))this.setMapPaint(descriptor.id,property2,value)}}applyGeoLabel(sourceId,layer,current){const map=this._map;if(!map)return;const check=()=>{if(!current())throw new DOMException("Map update superseded.","AbortError")};check();const id=`${sourceId}-label`,existing=map.getLayer(id);if(check(),!layer.label){this.appliedGeoLabels.delete(sourceId),existing&&(map.removeLayer(id),check());return}const descriptor=buildMapLabelLayer(id,sourceId,layer.label,value=>resolvedLayerColor(this,value,layer.tone)),native=layer.cluster?{...descriptor,filter:["all",["!",["has","point_count"]],["==",["geometry-type"],"Point"]]}:descriptor,key=JSON.stringify(native);if(this.appliedGeoLabels.get(sourceId)===key)return;const previousKey=this.appliedGeoLabels.get(sourceId);if(existing&&previousKey&&typeof map.setLayoutProperty=="function"&&typeof map.setFilter=="function"&&typeof map.setLayerZoomRange=="function"){const previous=JSON.parse(previousKey),journal=[],write=(apply,restore)=>{if(!current())throw new DOMException("Map update superseded.","AbortError");if(this.appliedGeoLabels.delete(sourceId),journal.push(restore),apply(),!current())throw new DOMException("Map update superseded.","AbortError")};try{for(const kind of["layout","paint"]){const before=previous[kind]??{},after=native[kind]??{};for(const property2 of new Set([...Object.keys(before),...Object.keys(after)])){if(JSON.stringify(before[property2])===JSON.stringify(after[property2]))continue;const setter=kind==="layout"?map.setLayoutProperty:map.setPaintProperty;write(()=>{setter.call(map,id,property2,after[property2]??null)},()=>{setter.call(map,id,property2,before[property2]??null)})}}if(JSON.stringify(previous.filter)!==JSON.stringify(native.filter)&&write(()=>{map.setFilter(id,native.filter??null)},()=>{map.setFilter(id,previous.filter??null)}),previous.minzoom!==native.minzoom&&write(()=>{map.setLayerZoomRange(id,Math.max(layer.minZoom,layer.label.minZoom),layer.maxZoom)},()=>{map.setLayerZoomRange(id,typeof previous.minzoom=="number"?previous.minzoom:0,layer.maxZoom)}),!current())throw new DOMException("Map update superseded.","AbortError")}catch(error){for(const restore of journal.reverse()){if(!current())break;try{restore()}catch{break}}throw error}}else existing&&(map.removeLayer(id),check()),map.addLayer(native),check();this.appliedGeoLabels.set(sourceId,key)}applyGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)||this._map.addLayer({id:fillId,type:"fill",source:sourceId,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":color,"fill-opacity":choroplethFillOpacity(this)}}),this._map.getLayer(lineId)||this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":this.lineColor(layer),"line-width":layer.line?.width??2,...layer.line?{"line-opacity":layer.line.opacity}:{}}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":stroke,"circle-radius":5}}),this.setMapPaint(lineId,"line-width",layer.line?.width??2),this.setMapPaint(lineId,"line-opacity",layer.line?.opacity??1),this.paintGeometryLayers(sourceId,layer)}paintGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone);this.setMapPaint(`${sourceId}-fill`,"fill-color",color),this.setMapPaint(`${sourceId}-fill`,"fill-opacity",choroplethFillOpacity(this)),this.setMapPaint(`${sourceId}-line`,"line-color",this.lineColor(layer)),this.paintPoints(sourceId,layer)}lineColor(layer){const fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),line=layer.line;return!line?.field||line.stops.length<2?fallback:lineColorExpression(line.field,line.stops.map(([value,color])=>[value,resolvedLayerColor(this,color,layer.tone)]),fallback)}mutedPointOpacity(layerId,field){const muted=field?this.hiddenCategories:EMPTY_HIDDEN_CATEGORIES;if(!muted.length)return this.appliedPointMuting.delete(layerId)?1:void 0;this.appliedPointMuting.add(layerId);const dim=hiddenCategoryOpacity(this);return mutedCategoryOpacityExpression(field,muted,dim)}paintPoints(sourceId,layer){if(!this._map)return;const point=layer.point,fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),color=pointColorExpression(point?.field,point?.field&&point.colors.length?point.colors.map(([value,paint])=>[value,resolvedLayerColor(this,paint,layer.tone)]):[],fallback),id=`${sourceId}-circle`;this.setMapPaint(id,"circle-color",color);const opacity=this.mutedPointOpacity(id,point?.field);opacity!==void 0&&(this.setMapPaint(id,"circle-opacity",opacity),this.setMapPaint(id,"circle-stroke-opacity",opacity)),!(!point&&!this.appliedPointPaint.has(sourceId))&&(this.setMapPaint(id,"circle-radius",pointRadiusExpression(point?.radius??5)),this.setMapPaint(id,"circle-stroke-width",point?.strokeWidth??0),this.setMapPaint(id,"circle-stroke-color",point?.strokeColor?resolvedLayerColor(this,point.strokeColor,layer.tone):fallback),point?this.appliedPointPaint.add(sourceId):this.appliedPointPaint.delete(sourceId))}pointIconColor(layer){const resolved=resolvedLayerColor(this,layer.point?.iconColor??`var(${ON_TONE_TOKEN[layer.tone??"accent"]})`,layer.tone);return resolveCanvasColor(this,resolved,dataLayerColor(this,layer.tone))}removePointIcons(sourceId){const applied=this.appliedPointIcons.get(sourceId);if(!applied||!this._map)return;const id=`${sourceId}-point-icon`;this._map.getLayer(id)&&this.removeMapLayer(id);for(const{id:imageId}of applied.icons)this._map.hasImage?.(imageId)&&this._map.removeImage?.(imageId);this.appliedPointIcons.delete(sourceId),this.appliedPointMuting.delete(id)}applyPointIcons(sourceId,layer){const map=this._map,point=layer.point,signature=JSON.stringify([point?.iconField,point?.iconSize,point?.icons]);if(this.appliedPointIcons.get(sourceId)?.signature===signature){this.paintPointIcons(sourceId,layer);return}if(this.removePointIcons(sourceId),!point?.iconField||!point.icons.length||!map||typeof map.addImage!="function"||typeof map.hasImage!="function"||typeof map.updateImage!="function"||typeof map.removeImage!="function")return;const color=this.pointIconColor(layer),icons=[],applied={signature:"",color,icons};this.appliedPointIcons.set(sourceId,applied);for(const icon of point.icons){const raster=rasterPointIcon(this,icon,color);if(!raster)continue;let id;do id=`lr-point-icon-${this.nextPointIconId++}`;while(map.hasImage(id));icons.push({id,icon}),map.addImage(id,raster,{pixelRatio:2})}icons.length&&(map.addLayer({id:`${sourceId}-point-icon`,type:"symbol",source:sourceId,filter:layer.cluster?["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]]:["==",["geometry-type"],"Point"],layout:{"icon-image":["match",["get",point.iconField],...icons.flatMap(({id,icon})=>[icon.value,id]),""],"icon-size":point.iconSize/(POINT_ICON_RASTER_SIZE/2),"icon-allow-overlap":!0,"icon-ignore-placement":!0}}),icons.length===point.icons.length&&(applied.signature=signature))}paintPointIcons(sourceId,layer){const applied=this.appliedPointIcons.get(sourceId);if(!applied)return;const iconLayerId=`${sourceId}-point-icon`,opacity=this.mutedPointOpacity(iconLayerId,layer.point?.iconField);opacity!==void 0&&this.setMapPaint(iconLayerId,"icon-opacity",opacity);const color=this.pointIconColor(layer);if(color===applied.color)return;const updates=[];for(const{id,icon}of applied.icons){const raster=rasterPointIcon(this,icon,color);if(!raster)return;updates.push({id,raster})}for(const{id,raster}of updates)this._map?.updateImage?.(id,raster);applied.color=color}clusterColorExpression(layer,cluster){const tone=layer.tone;return clusterColorExpression(cluster.colorSteps.map(([count,stepColor])=>[count,resolvedLayerColor(this,stepColor,tone)]),()=>resolvedLayerColor(this,layer.color,tone))}applyClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedClusterStrokeColor(this,cluster.strokeColor,layer),clusterId=`${sourceId}-cluster`,countId=`${sourceId}-cluster-count`,circleId=`${sourceId}-circle`,clusterColor=this.clusterColorExpression(layer,cluster),clusterRadius=stepExpression(["get","point_count"],cluster.radiusSteps),countColor=resolvedClusterCountColor(this,cluster.countColor)??resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone),countHaloColor=resolvedClusterCountColor(this,cluster.countHaloColor);this._map.getLayer(clusterId)||this._map.addLayer({id:clusterId,type:"circle",source:sourceId,filter:["has","point_count"],paint:{"circle-color":clusterColor,"circle-radius":clusterRadius,"circle-stroke-width":1,"circle-stroke-color":stroke}}),this.styleProvidesGlyphs()&&!this._map.getLayer(countId)&&this._map.addLayer({id:countId,type:"symbol",source:sourceId,filter:["has","point_count"],layout:{"text-field":["get","point_count_abbreviated"],"text-size":12,...cluster.countFont?{"text-font":[...cluster.countFont]}:{}},paint:{"text-color":countColor,...countHaloColor?{"text-halo-color":countHaloColor,"text-halo-width":cluster.countHaloWidth}:{}}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]],paint:{"circle-color":stroke,"circle-radius":5}}),this.paintClusterLayers(sourceId,layer,cluster)}paintClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedClusterStrokeColor(this,cluster.strokeColor,layer),clusterId=`${sourceId}-cluster`;if(this.setMapPaint(clusterId,"circle-color",this.clusterColorExpression(layer,cluster)),this.setMapPaint(clusterId,"circle-radius",stepExpression(["get","point_count"],cluster.radiusSteps)),this.setMapPaint(clusterId,"circle-stroke-color",stroke),this.styleProvidesGlyphs()){this.setMapPaint(`${sourceId}-cluster-count`,"text-color",resolvedClusterCountColor(this,cluster.countColor)??resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone));const countHaloColor=resolvedClusterCountColor(this,cluster.countHaloColor);this.setMapPaint(`${sourceId}-cluster-count`,"text-halo-color",countHaloColor??null),this.setMapPaint(`${sourceId}-cluster-count`,"text-halo-width",countHaloColor?cluster.countHaloWidth:null)}this.paintPoints(sourceId,layer)}applyHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`,options=layer.heatmap,weight=heatmapWeightExpression(options),color=this.heatmapColorExpression(layer),radius=heatmapZoomValue(options?.radius,DEFAULT_HEATMAP_RADIUS,1,200),intensity=heatmapZoomValue(options?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100),opacity=finiteRange(options?.opacity??Number.NaN,1,0,1);if(!this._map.getLayer(heatmapId)){this._map.addLayer({id:heatmapId,type:"heatmap",source:sourceId,paint:{...weight?{"heatmap-weight":weight}:{},"heatmap-intensity":intensity,"heatmap-color":color,"heatmap-radius":radius,...options?.opacity===void 0?{}:{"heatmap-opacity":opacity}}});return}this.paintHeatmapLayer(sourceId,layer)}paintHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`;this.setMapPaint(heatmapId,"heatmap-weight",heatmapWeightExpression(layer.heatmap)??1),this.setMapPaint(heatmapId,"heatmap-intensity",heatmapZoomValue(layer.heatmap?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100)),this.setMapPaint(heatmapId,"heatmap-color",this.heatmapColorExpression(layer)),this.setMapPaint(heatmapId,"heatmap-radius",heatmapZoomValue(layer.heatmap?.radius,DEFAULT_HEATMAP_RADIUS,1,200)),this.setMapPaint(heatmapId,"heatmap-opacity",finiteRange(layer.heatmap?.opacity??Number.NaN,1,0,1))}heatmapColorExpression(layer){const tone=layer.tone,authored=(layer.heatmap?.stops??[]).map(([density,color])=>[density,resolvedLayerColor(this,color,tone)]);return heatmapColorExpression(authored,()=>HEATMAP_RAMP_TOKENS.map(([density,token])=>[density,resolvedLayerColor(this,`var(${token})`,tone)]))}styleHasTextFonts(style){try{if(!isPlainDataRecord(style))return!1;const glyphs=getOwnDataDescriptor(style,"glyphs");if(isUnsafeDescriptor(glyphs))return!1;const glyphUrl=optionalDescriptorValue(glyphs);if(typeof glyphUrl=="string"&&glyphUrl.trim().length>0)return!0;const facesDescriptor=getOwnDataDescriptor(style,"font-faces");if(isUnsafeDescriptor(facesDescriptor))return!1;const faces=optionalDescriptorValue(facesDescriptor);if(!isPlainDataRecord(faces))return!1;const families=Reflect.ownKeys(faces);if(families.length===0||families.length>64)return!1;let familyCount=0;for(const family of families){if(typeof family!="string"||!Object.getOwnPropertyDescriptor(faces,family)?.enumerable)continue;if(!family.trim())return!1;familyCount++;const declarationDescriptor=getOwnDataDescriptor(faces,family);if(isUnsafeDescriptor(declarationDescriptor))return!1;const declaration=optionalDescriptorValue(declarationDescriptor);if(typeof declaration=="string"){if(!declaration.trim())return!1;continue}const count=boundedOwnArrayLength(declaration,257);if(count===void 0||count===0||count>256)return!1;for(let index=0;index<count;index++){const face=optionalDescriptorValue(getOwnDataDescriptor(declaration,String(index)));if(!isPlainDataRecord(face))return!1;const faceKeys=Reflect.ownKeys(face);if(faceKeys.length>2||faceKeys.some(key=>key!=="url"&&key!=="unicode-range"))return!1;const url=optionalDescriptorValue(getOwnDataDescriptor(face,"url"));if(typeof url!="string"||!url.trim())return!1;const rangeDescriptor=getOwnDataDescriptor(face,"unicode-range");if(isUnsafeDescriptor(rangeDescriptor))return!1;if(rangeDescriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;const ranges=optionalDescriptorValue(rangeDescriptor),rangeCount=boundedOwnArrayLength(ranges,65);if(rangeCount===void 0||rangeCount>64)return!1;for(let rangeIndex=0;rangeIndex<rangeCount;rangeIndex++){const range=optionalDescriptorValue(getOwnDataDescriptor(ranges,String(rangeIndex)));if(typeof range!="string")return!1;const match=/^u\+(?:([0-9a-f]{1,6})(?:-([0-9a-f]{1,6}))?|([0-9a-f]{0,5}\?{1,6}))$/i.exec(range);if(!match)return!1;if(match[3]!==void 0){if(match[3].length>6)return!1}else{const start=Number.parseInt(match[1],16),end=Number.parseInt(match[2]??match[1],16);if(start>end||end>1114111)return!1}}}}return familyCount>0}catch{return!1}}styleProvidesGlyphs(){try{const live=this._map?.getStyle?.();if(this.styleHasTextFonts(live))return!0}catch{}return this.styleHasTextFonts(this.mapStyle)}resolveDataLayerSourceId(layer,identities){const publicSourceId=layer.sourceId,planned=identities?.geojson??this.plannedDataLayerIds,applied=this._appliedDataLayerIds.get(publicSourceId),pending=planned.get(publicSourceId),appliedShape=this._appliedDataLayerShapes.get(publicSourceId),retained=appliedShape!==void 0&&appliedShape!==dataLayerShape(layer)?pending!==applied?pending:void 0:applied??pending;if(retained)return retained;let sourceId;do sourceId=`lr-data-layer-${identities?identities.nextGeojson++:this._nextDataLayerId++}`;while(this._map?.getSource(sourceId)||DATA_LAYER_SUFFIXES.some(suffix=>this._map?.getLayer(`${sourceId}${suffix}`)));return planned.set(publicSourceId,sourceId),sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){this.featureStates?.refreshNative("data-layer",sourceId),this.removePointIcons(sourceId),this.appliedPointPaint.delete(sourceId),this.appliedGeoLabels.delete(sourceId),this.appliedRowRanges.delete(sourceId);for(const suffix of DATA_LAYER_SUFFIXES){const layerId=`${sourceId}${suffix}`;this.appliedPointMuting.delete(layerId),this._map.getLayer(layerId)&&this.removeMapLayer(layerId)}this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.delete(publicSourceId),this.plannedDataLayerIds.get(publicSourceId)===sourceId&&this.plannedDataLayerIds.delete(publicSourceId),this._appliedDataLayerShapes.delete(publicSourceId),this._appliedGeoJson.delete(sourceId),this.appliedLayerPaintKeys.delete(sourceId)}}applyMarkers(){const map=this._map,mod=this._maplibreModule;if(!map||!mod)return;const visible=new Set,coordCounts=new Map,explicitIds=new Set;for(const m of this.canonicalMarkers){const lngLat=m.lngLat,mapLngLat=[lngLat[0],lngLat[1]];let key,id;if(m.id!==void 0){if(id=m.id,explicitIds.has(id))continue;explicitIds.add(id),key=`id:${id}`}else{const coordKey=`${lngLat[0]},${lngLat[1]}`,occurrence=coordCounts.get(coordKey)??0;coordCounts.set(coordKey,occurrence+1),key=`coordinate:${coordKey}#${occurrence}`}visible.add(key);let existing=this._markerInstances.get(key);const markerColor=sanitizeCssColor(m.color)??(m.color===void 0?"currentColor":void 0),previous=this._markerSources.get(key);this._markerSources.set(key,m);const sameColor=this._markerColors.get(key)===markerColor,sameContent=previous!==void 0&&previous.label===m.label&&Object.is(previous.unsafeHtml,m.unsafeHtml);if(existing&&sameColor&&sameContent&&previous.lngLat[0]===lngLat[0]&&previous.lngLat[1]===lngLat[1])continue;if(existing&&!sameColor){const existingElement=existing.getElement?.();existingElement&&this.markerActivationDetails.delete(existingElement),existing.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),existing=void 0}if(existing){existing.setLngLat(mapLngLat);const popup=existing.getPopup();if(!m.unsafeHtml&&!m.label)popup&&existing.setPopup(void 0);else if(popup)sameContent||setPopupContent(popup,m);else{const nextPopup=setPopupContent(new mod.Popup({offset:12}),m);existing.setPopup(nextPopup),this.configurePopupSemantics(key,existing,nextPopup)}}else{const marker=new mod.Marker(markerColor?{color:markerColor}:void 0).setLngLat(mapLngLat);if(m.unsafeHtml||m.label){const popup=setPopupContent(new mod.Popup({offset:12}),m);marker.setPopup(popup),this.configurePopupSemantics(key,marker,popup)}marker.addTo(map),this._markerInstances.set(key,marker),this._markerColors.set(key,markerColor)}const markerLabel=m.label?.trim()||markerPopupText(this,m.unsafeHtml);this._markerLabels.set(key,markerLabel||void 0);const markerElement=this._markerInstances.get(key)?.getElement?.();if(markerElement){addPartToken(markerElement,"marker");const currentMarker=this._markerInstances.get(key);this.configureMarkerInteraction(markerElement,{id,lngLat,marker:m},markerLabel);const popup=currentMarker?.getPopup();popup&¤tMarker?(this.configurePopupSemantics(key,currentMarker,popup),this.syncPopupSemantics(key,currentMarker,popup)):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}}for(const[key,marker]of this._markerInstances)if(!visible.has(key)){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),this._markerLabels.delete(key),this._markerPopupIds.delete(key),this._markerSources.delete(key)}}configureMarkerInteraction(markerElement,activation,markerLabel=activation.marker.label?.trim()||markerPopupText(this,activation.marker.unsafeHtml)){this.markerActivationDetails.set(markerElement,activation),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",markerLabel||this.localize("mapMarker")),markerElement.setAttribute("lang",this.effectiveLocale),!this.configuredMarkerElements.has(markerElement)&&(this.configuredMarkerElements.add(markerElement),markerElement.addEventListener("click",event=>{event.defaultPrevented||this.emitMarkerActivation(markerElement,"pointer")}),markerElement.addEventListener("keydown",event=>{event.key!==" "&&event.key!=="Enter"||event.repeat||event.defaultPrevented||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected)return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return hostAriaLabel(this)??this.label??this.localize("map")}popupId(key){let id=this._markerPopupIds.get(key);return id||(id=`map-popup-${this._connectGeneration}-${++this._nextPopupId}`,this._markerPopupIds.set(key,id)),id}configurePopupSemantics(key,marker,popup){!popup||typeof popup!="object"||this._configuredPopups.has(popup)||(this._configuredPopups.add(popup),popup.on?.("open",()=>this.syncPopupSemantics(key,marker,popup)),popup.on?.("close",()=>{marker.getElement?.()?.setAttribute("aria-expanded","false")}))}stopObservingMapAllocation(){this.mapResizeObserver?.disconnect(),this.mapResizeObserver=void 0,this.observedMapContainer=void 0}observeMapAllocation(map,container){this.stopObservingMapAllocation();const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;let observer,size=renderedSizeKey(container);observer=new ResizeObserverCtor(()=>{if(this.mapResizeObserver!==observer||this.observedMapContainer!==container||this.containerEl!==container||this._map!==map||!this.isConnected)return;try{this.cameraSession?this.writeCamera(()=>map.resize()):map.resize(),this.drawingController?.scheduleHandles()}catch{}this.geographicSceneRender?.refreshAllocation();const next=renderedSizeKey(container);next!==size&&(size=next,this.scheduleAnchorSync())}),this.mapResizeObserver=observer,this.observedMapContainer=container;try{observer.observe(container)}catch{this.stopObservingMapAllocation()}}stopObservingPeerChrome(){const pending=this.peerControlsResizeFrame;this.peerControlsResizeFrame=void 0,pending&&pending.view.cancelAnimationFrame(pending.handle),this.peerControlsResizeObserver?.disconnect(),this.peerControlsResizeObserver=void 0,this.peerChromeObserver?.disconnect(),this.peerChromeObserver=void 0,this.observedPeerContainer=void 0}schedulePeerControlInsets(observer,container){if(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||!this.isConnected||this.peerControlsResizeFrame)return;const view=container.ownerDocument.defaultView;if(!view)return;const pending={view,handle:0};this.peerControlsResizeFrame=pending,pending.handle=view.requestAnimationFrame(()=>{this.peerControlsResizeFrame===pending&&(this.peerControlsResizeFrame=void 0,!(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||container.ownerDocument.defaultView!==view||!this.isConnected)&&this.measurePeerControlInsets(container))})}measurePeerControlInsets(container){if(!(!this.isConnected||this.containerEl!==container)){for(const scale of container.querySelectorAll(".maplibregl-ctrl-scale")){const width=scale.style.width;width&&scale.style.getPropertyValue("--_lr-map-scale-width")!==width&&scale.style.setProperty("--_lr-map-scale-width",width)}for(const edge of["top","bottom"]){const height=Math.max(0,...[...container.querySelectorAll(`.maplibregl-ctrl-${edge}-left, .maplibregl-ctrl-${edge}-right`)].map(corner=>corner.offsetHeight)),base=container.parentElement,name=`--_lr-map-controls-${edge}`,value=`${height}px`;base&&base.style.getPropertyValue(name)!==value&&base.style.setProperty(name,value)}}}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const selectors=[[".maplibregl-marker","marker"],[".maplibregl-popup","popup"],[".maplibregl-popup-content","popup-content"],[".maplibregl-popup-close-button","popup-close-button"],[".maplibregl-control-container","controls"],[".map-control-row-top","controls-top"],[".map-control-row-bottom","controls-bottom"],[".maplibregl-ctrl-top-left","controls-top-left"],[".maplibregl-ctrl-top-right","controls-top-right"],[".maplibregl-ctrl-bottom-left","controls-bottom-left"],[".maplibregl-ctrl-bottom-right","controls-bottom-right"],[".maplibregl-ctrl-attrib","attribution"],[".maplibregl-ctrl-attrib a","attribution-link"],[".maplibregl-ctrl-attrib-button","attribution-toggle"],[".maplibregl-ctrl-attrib-inner","attribution-content"],[".maplibregl-ctrl-group:has(.maplibregl-ctrl-zoom-in, .maplibregl-ctrl-compass)","navigation"],[".maplibregl-ctrl-zoom-in","zoom-in"],[".maplibregl-ctrl-zoom-out","zoom-out"],[".maplibregl-ctrl-compass","compass"],[".maplibregl-ctrl-scale","scale"],[".maplibregl-ctrl:has(.maplibregl-ctrl-geolocate)","geolocate-control"],[".maplibregl-ctrl-geolocate","geolocate"],[".maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon","zoom-in-icon"],[".maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon","zoom-out-icon"],[".maplibregl-ctrl-compass .maplibregl-ctrl-icon","compass-icon"],[".maplibregl-ctrl-geolocate .maplibregl-ctrl-icon","geolocate-icon"],[".map-scene-globe-control","globe-control"],[".map-scene-globe-control button","globe-button"],[".map-scene-globe-control .map-scene-control-icon","globe-icon"],[".map-scene-terrain-control","terrain-control"],[".map-scene-terrain-control button","terrain-button"],[".map-scene-terrain-control .map-scene-control-icon","terrain-icon"]];for(const[selector,part]of selectors){const candidate=root,elements=[];candidate.matches?.(selector)&&elements.push(candidate),(!(root instanceof Element)||root.childElementCount>0)&&elements.push(...root.querySelectorAll(selector));for(const element of elements){if(addPartToken(element,part),part.endsWith("-icon")&&element.setAttribute("aria-hidden","true"),part==="geolocate")for(const[state2,statePart]of[["waiting","geolocate-waiting"],["active","geolocate-active"],["background","geolocate-background"],["error","geolocate-error"]]){const present=state2==="error"?element.classList.contains("maplibregl-ctrl-geolocate-active-error")||element.classList.contains("maplibregl-ctrl-geolocate-background-error"):element.classList.contains(`maplibregl-ctrl-geolocate-${state2}`);element.part.toggle(statePart,present)}if(part==="attribution"||part==="attribution-toggle"||part==="attribution-content"){const attribution=element.closest(".maplibregl-ctrl-attrib");element.part.toggle("attribution-expanded",!!attribution&&attributionExpanded(attribution))}if(part==="scale"){const text=element.textContent??"",unit=[...this.scaleLabels.keys()].sort((a,b)=>b.length-a.length).find(value=>text.endsWith(` ${value}`)||text.endsWith(` ${value}`));if(unit){const key=this.scaleLabels.get(unit),translated=this.localize(MAP_SCALE_UNIT_MESSAGE[key]);this.scaleLabels.set(translated,key);const next=text.slice(0,-unit.length)+translated;next!==text&&(element.textContent=next)}}const label=part==="attribution-toggle"?this.localize("mapToggleAttribution"):part==="zoom-in"?this.localize("zoomIn"):part==="zoom-out"?this.localize("zoomOut"):part==="compass"?this.localize("mapResetNorth"):part==="geolocate"?this.localize(element.disabled?"mapGeolocateUnavailable":"mapGeolocateFindLocation"):void 0;label!==void 0&&(element.getAttribute("aria-label")!==label&&element.setAttribute("aria-label",label),element.getAttribute("title")!==label&&element.setAttribute("title",label))}}}syncAttributionState(){const root=this.controlLifecycle?.ownedRoot("attribution"),container=this.containerEl;if(!root||!container||!this.isConnected||!container.contains(root)){this.attributionState=void 0;return}const expanded=attributionExpanded(root),previous=this.attributionState;if(previous?.root!==root){this.attributionState={root,expanded};return}previous.expanded!==expanded&&(previous.expanded=expanded,this.emit("lr-map-attribution-toggle",{expanded}))}syncPeerAttributionExpansion(container){for(const controls of container.querySelectorAll(".maplibregl-control-container")){const expanded=[...controls.querySelectorAll(".maplibregl-ctrl-attrib")].some(attributionExpanded);for(const node of[controls,...controls.querySelectorAll(".map-control-row, .maplibregl-ctrl-top-left, .maplibregl-ctrl-top-right, .maplibregl-ctrl-bottom-left, .maplibregl-ctrl-bottom-right")])node.part.toggle("controls-attribution-expanded",expanded)}}observePeerChrome(){const container=this.containerEl;if(!container||(syncMapControlRows(container,()=>this.isConnected&&this.containerEl===container),!this.isConnected||this.containerEl!==container)||(this.syncPeerChromeParts(container),this.syncPeerAttributionExpansion(container),this.observedPeerContainer===container&&this.peerChromeObserver))return;this.stopObservingPeerChrome();const MutationObserverCtor=container.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;this.observedPeerContainer=container;const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(ResizeObserverCtor){const observer2=new ResizeObserverCtor(()=>this.schedulePeerControlInsets(observer2,container));this.peerControlsResizeObserver=observer2;for(const corner of container.querySelectorAll(".maplibregl-ctrl-top-left, .maplibregl-ctrl-top-right, .maplibregl-ctrl-bottom-left, .maplibregl-ctrl-bottom-right"))this.peerControlsResizeObserver.observe(corner)}this.measurePeerControlInsets(container);const observer=new MutationObserverCtor(records=>{if(!this.isConnected||this.containerEl!==container||this.peerChromeObserver!==observer)return;let elementsChanged=!1,attributionChanged=!1;for(const record of records)if(container.contains(record.target)){if(record.type==="attributes"&&record.target instanceof Element){if(record.attributeName==="class"&&!record.target.matches(".maplibregl-ctrl-geolocate, .maplibregl-ctrl-attrib"))continue;this.syncPeerChromeParts(record.target),record.target.matches(".maplibregl-ctrl-attrib")&&(attributionChanged=!0)}record.type==="characterData"&&record.target.parentElement&&this.syncPeerChromeParts(record.target.parentElement),record.type==="childList"&&record.target instanceof Element&&record.target.matches(".maplibregl-ctrl-scale")&&this.syncPeerChromeParts(record.target);for(const node of record.removedNodes)node.nodeType===1&&(elementsChanged=!0);for(const node of record.addedNodes){if(node.nodeType!==1||!container.contains(node))continue;elementsChanged=!0;const element=node;element.matches('.maplibregl-marker[part~="marker"]')||this.syncPeerChromeParts(element)}}elementsChanged&&syncMapControlRows(container,()=>this.isConnected&&this.containerEl===container&&this.peerChromeObserver===observer),!(!this.isConnected||this.containerEl!==container||this.peerChromeObserver!==observer)&&((elementsChanged||attributionChanged)&&(this.syncPeerAttributionExpansion(container),this.syncAttributionState()),elementsChanged&&this.schedulePeerControlInsets(this.peerControlsResizeObserver,container))});this.peerChromeObserver=observer,observer.observe(container,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["disabled","class","open"]})}syncPopupSemantics(key,marker,popup){const markerElement=marker?.getElement?.();if(!markerElement)return;const id=this.popupId(key);markerElement.setAttribute("aria-controls",id),markerElement.setAttribute("aria-haspopup","dialog"),markerElement.setAttribute("aria-expanded",popup?.isOpen?.()?"true":"false");const popupElement=popup?.getElement?.();if(!popupElement)return;addPartToken(markerElement,"marker"),addPartToken(popupElement,"popup"),popupElement.id=id,popupElement.setAttribute("role","dialog"),popupElement.setAttribute("lang",this.effectiveLocale),popupElement.setAttribute("aria-label",this._markerLabels.get(key)||this.effectiveMapLabel);const popupContent=popupElement.querySelector(".maplibregl-popup-content");popupContent&&addPartToken(popupContent,"popup-content");const closeButton=popupElement.querySelector(".maplibregl-popup-close-button");closeButton&&addPartToken(closeButton,"popup-close-button"),closeButton?.setAttribute("aria-label",this.localize("close"))}syncMapSemantics(markers=!0){const canvas=this._map?.getCanvas?.();if(canvas&&(canvas.setAttribute("aria-label",this.effectiveMapLabel),canvas.setAttribute("lang",this.effectiveLocale),this.legend.length||this.legendGradient.length>=2||this.hasLegendSlot||this.hasLegendStartSlot||this.legendProjection.truncated||this.hasDerivedLegend()?canvas.setAttribute("aria-describedby","map-legend"):canvas.removeAttribute("aria-describedby")),this.hostDescription.refresh(),this.syncPeerChromeParts(),!!markers){for(const[key,marker]of this._markerInstances){const markerElement=marker.getElement?.();if(!markerElement)continue;addPartToken(markerElement,"marker"),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",this._markerLabels.get(key)||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const popup=marker.getPopup?.();popup?this.syncPopupSemantics(key,marker,popup):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}this.syncPeerChromeParts()}}formatDistance(metres){return metres<1e3?getNumberFormat(this.effectiveLocale,{style:"unit",unit:"meter",unitDisplay:"short",maximumFractionDigits:0}).format(metres):getNumberFormat(this.effectiveLocale,{style:"unit",unit:"kilometer",unitDisplay:"short",maximumFractionDigits:metres<1e4?2:1}).format(metres/1e3)}formatArea(squareMetres){return squareMetres<1e6?this.localize("mapSquareMeters",void 0,{value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(squareMetres)}):this.localize("mapSquareKilometers",void 0,{value:getNumberFormat(this.effectiveLocale,{maximumFractionDigits:2}).format(squareMetres/1e6)})}drawingSummary(snapshot){if(!snapshot||snapshot.vertices.length<2)return;const metrics=loadMapDrawingRuntime.loaded?.measureDrawing(snapshot.mode,snapshot.vertices);if(metrics)return snapshot.mode==="line"?this.localize("mapDrawingLength",void 0,{value:this.formatDistance(metrics.length)}):metrics.area===void 0?void 0:this.localize("mapDrawingArea",void 0,{value:this.formatArea(metrics.area)})}drawingLabelText(kind,value){return kind==="area"?this.localize("mapDrawingArea",void 0,{value:this.formatArea(value)}):kind==="length"?this.localize("mapDrawingLength",void 0,{value:this.formatDistance(value)}):this.formatDistance(value)}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatCount(this.legend.length===0?0:1),end:this.formatCount(this.legend.length),total:this.formatCount(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendRowContent(entry){const paint=sanitizeCssColor(entry.color);return html`${entry.icon?html`<span
|
|
37
37
|
part="legend-swatch"
|
|
38
38
|
data-pattern=${entry.pattern}
|
|
39
39
|
data-icon="true"
|
|
@@ -174,4 +174,4 @@ import{__decorate}from"tslib";import{MapPaintBatch}from"./map-paint-batch.js";im
|
|
|
174
174
|
<slot name="legend" ?hidden=${this.legendCollapsed} @slotchange=${this.onLegendSlotChange}></slot>
|
|
175
175
|
</div>`:nothing}
|
|
176
176
|
</div>
|
|
177
|
-
`}}__decorate([state()],LyraMap.prototype,"scenePanelOpen",void 0),__decorate([state()],LyraMap.prototype,"scenePage",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"scene",null),__decorate([property({reflect:!0,hasChanged:()=>!0,converter:{fromAttribute:value=>normalizeMapProjection(value),toAttribute:value=>value??null}})],LyraMap.prototype,"projection",null),__decorate([property({attribute:!1,hasChanged:()=>!0})],LyraMap.prototype,"terrain",null),__decorate([property({type:Array})],LyraMap.prototype,"center",null),__decorate([property({type:Number})],LyraMap.prototype,"zoom",void 0),__decorate([property({type:Number,attribute:"min-zoom"})],LyraMap.prototype,"minZoom",void 0),__decorate([property({type:Number,attribute:"max-zoom"})],LyraMap.prototype,"maxZoom",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"cameraPadding",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"renderWorldCopies",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"maxBounds",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"controls",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"hash",void 0),__decorate([property({attribute:"hash-format",converter:HASH_FORMAT})],LyraMap.prototype,"hashFormat",void 0),__decorate([state()],LyraMap.prototype,"hashIssue",void 0),__decorate([state()],LyraMap.prototype,"controlIssue",void 0),__decorate([state()],LyraMap.prototype,"sceneControlIssue",void 0),__decorate([state()],LyraMap.prototype,"controlOutlines",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"anchorLngLat",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"anchorBoundary",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"anchorSafeArea",void 0),__decorate([property({type:Boolean,attribute:"anchor-closable"})],LyraMap.prototype,"anchorClosable",void 0),__decorate([property()],LyraMap.prototype,"initialization",void 0),__decorate([property({type:Number,attribute:"initialization-delay"})],LyraMap.prototype,"initializationDelay",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"mapStyle",null),__decorate([property({attribute:!1})],LyraMap.prototype,"legend",null),__decorate([state()],LyraMap.prototype,"hasLegendSlot",void 0),__decorate([state()],LyraMap.prototype,"hasLegendStartSlot",void 0),__decorate([property({attribute:"legend-gradient-lo-label"})],LyraMap.prototype,"legendGradientLoLabel",void 0),__decorate([property({attribute:"legend-gradient-hi-label"})],LyraMap.prototype,"legendGradientHiLabel",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"legendGradientTicks",null),__decorate([property({type:Boolean,attribute:"choropleth-legend",reflect:!0})],LyraMap.prototype,"choroplethLegend",void 0),__decorate([property({type:Boolean,attribute:"legend-interactive",reflect:!0})],LyraMap.prototype,"legendInteractive",void 0),__decorate([property({converter:LEGEND_CONTROL_ROLE,attribute:"legend-control-role",reflect:!0})],LyraMap.prototype,"legendControlRole",null),__decorate([property({type:Boolean,attribute:"legend-collapsible",reflect:!0})],LyraMap.prototype,"legendCollapsible",void 0),__decorate([property({attribute:"legend-open",reflect:!0,converter:trueDefaultBooleanConverter})],LyraMap.prototype,"legendOpen",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"hiddenCategories",null),__decorate([property({attribute:!1})],LyraMap.prototype,"choropleth",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"markers",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"dataLayers",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"overlays",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"images",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"imageProvider",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"styleOverrides",void 0),__decorate([state()],LyraMap.prototype,"dataLayerIssue",void 0),__decorate([property()],LyraMap.prototype,"label",void 0),__decorate([property({converter:MAP_ENGINE})],LyraMap.prototype,"engine",void 0),__decorate([state()],LyraMap.prototype,"loading",void 0),__decorate([state()],LyraMap.prototype,"failure",void 0),__decorate([query('[part="container"]')],LyraMap.prototype,"containerEl",void 0),__decorate([query('[part="anchor"]')],LyraMap.prototype,"anchorEl",void 0),__decorate([query(".anchor-boundary")],LyraMap.prototype,"anchorBoundaryEl",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"interactiveBasemapLayers",void 0),__decorate([property({type:Boolean,attribute:"pick-mode"})],LyraMap.prototype,"pickMode",void 0),__decorate([property({type:Boolean,attribute:"keyboard-activation"})],LyraMap.prototype,"keyboardActivation",void 0),__decorate([property({attribute:"draw-mode",converter:DRAW_MODE})],LyraMap.prototype,"drawMode",void 0),__decorate([property({type:Boolean,attribute:"drawing-measurements",reflect:!0})],LyraMap.prototype,"drawingMeasurements",void 0),__decorate([state()],LyraMap.prototype,"drawingIssue",void 0),__decorate([state()],LyraMap.prototype,"drawingRevision",void 0),__decorate([state()],LyraMap.prototype,"featureStateIssue",void 0),__decorate([state()],LyraMap.prototype,"interactionBlocked",void 0),__decorate([state()],LyraMap.prototype,"exportIssue",void 0);export{LYRA_MAP_EMPTY_STYLE,LyraMap,LyraMapImageExportError2 as LyraMapImageExportError,buildGeoJsonPropertyDiff};
|
|
177
|
+
`}}__decorate([state()],LyraMap.prototype,"scenePanelOpen",void 0),__decorate([state()],LyraMap.prototype,"scenePage",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"scene",null),__decorate([property({reflect:!0,hasChanged:()=>!0,converter:{fromAttribute:value=>normalizeMapProjection(value),toAttribute:value=>value??null}})],LyraMap.prototype,"projection",null),__decorate([property({attribute:!1,hasChanged:()=>!0})],LyraMap.prototype,"terrain",null),__decorate([property({type:Array})],LyraMap.prototype,"center",null),__decorate([property({type:Number})],LyraMap.prototype,"zoom",void 0),__decorate([property({type:Number,attribute:"min-zoom"})],LyraMap.prototype,"minZoom",void 0),__decorate([property({type:Number,attribute:"max-zoom"})],LyraMap.prototype,"maxZoom",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"cameraPadding",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"canvasTarget",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"renderWorldCopies",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"maxBounds",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"controls",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"hash",void 0),__decorate([property({attribute:"hash-format",converter:HASH_FORMAT})],LyraMap.prototype,"hashFormat",void 0),__decorate([state()],LyraMap.prototype,"hashIssue",void 0),__decorate([state()],LyraMap.prototype,"controlIssue",void 0),__decorate([state()],LyraMap.prototype,"sceneControlIssue",void 0),__decorate([state()],LyraMap.prototype,"controlOutlines",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"anchorLngLat",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"anchorBoundary",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"anchorSafeArea",void 0),__decorate([property({type:Boolean,attribute:"anchor-closable"})],LyraMap.prototype,"anchorClosable",void 0),__decorate([property()],LyraMap.prototype,"initialization",void 0),__decorate([property({type:Number,attribute:"initialization-delay"})],LyraMap.prototype,"initializationDelay",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"mapStyle",null),__decorate([property({attribute:!1})],LyraMap.prototype,"legend",null),__decorate([state()],LyraMap.prototype,"hasLegendSlot",void 0),__decorate([state()],LyraMap.prototype,"hasLegendStartSlot",void 0),__decorate([property({attribute:"legend-gradient-lo-label"})],LyraMap.prototype,"legendGradientLoLabel",void 0),__decorate([property({attribute:"legend-gradient-hi-label"})],LyraMap.prototype,"legendGradientHiLabel",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"legendGradientTicks",null),__decorate([state()],LyraMap.prototype,"_legendGradientTicksAssigned",void 0),__decorate([property({type:Boolean,attribute:"choropleth-legend",reflect:!0})],LyraMap.prototype,"choroplethLegend",void 0),__decorate([property({type:Boolean,attribute:"legend-interactive",reflect:!0})],LyraMap.prototype,"legendInteractive",void 0),__decorate([property({converter:LEGEND_CONTROL_ROLE,attribute:"legend-control-role",reflect:!0})],LyraMap.prototype,"legendControlRole",null),__decorate([property({type:Boolean,attribute:"legend-collapsible",reflect:!0})],LyraMap.prototype,"legendCollapsible",void 0),__decorate([property({attribute:"legend-open",reflect:!0,converter:trueDefaultBooleanConverter})],LyraMap.prototype,"legendOpen",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"hiddenCategories",null),__decorate([property({attribute:!1})],LyraMap.prototype,"choropleth",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"markers",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"dataLayers",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"overlays",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"images",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"imageProvider",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"styleOverrides",void 0),__decorate([state()],LyraMap.prototype,"dataLayerIssue",void 0),__decorate([property()],LyraMap.prototype,"label",void 0),__decorate([property({converter:MAP_ENGINE})],LyraMap.prototype,"engine",void 0),__decorate([state()],LyraMap.prototype,"loading",void 0),__decorate([state()],LyraMap.prototype,"failure",void 0),__decorate([query('[part="container"]')],LyraMap.prototype,"containerEl",void 0),__decorate([query('[part="anchor"]')],LyraMap.prototype,"anchorEl",void 0),__decorate([query(".anchor-boundary")],LyraMap.prototype,"anchorBoundaryEl",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"interactiveBasemapLayers",void 0),__decorate([property({type:Boolean,attribute:"pick-mode"})],LyraMap.prototype,"pickMode",void 0),__decorate([property({type:Boolean,attribute:"keyboard-activation"})],LyraMap.prototype,"keyboardActivation",void 0),__decorate([property({attribute:"draw-mode",converter:DRAW_MODE})],LyraMap.prototype,"drawMode",void 0),__decorate([property({type:Boolean,attribute:"drawing-measurements",reflect:!0})],LyraMap.prototype,"drawingMeasurements",void 0),__decorate([state()],LyraMap.prototype,"drawingIssue",void 0),__decorate([state()],LyraMap.prototype,"drawingRevision",void 0),__decorate([state()],LyraMap.prototype,"featureStateIssue",void 0),__decorate([state()],LyraMap.prototype,"interactionBlocked",void 0),__decorate([state()],LyraMap.prototype,"exportIssue",void 0);export{LYRA_MAP_EMPTY_STYLE,LyraMap,LyraMapImageExportError2 as LyraMapImageExportError,buildGeoJsonPropertyDiff};
|