@aceshooting/lyra-ui 32.0.0 → 32.1.0
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 +203 -0
- package/README.md +24 -6
- package/design-tokens.json +1 -1
- package/dist/all.d.ts +1 -1
- package/dist/all.js +1 -1
- package/dist/autoloader.d.ts +10 -0
- package/dist/autoloader.js +1 -1
- package/dist/cli/migrate-wa.mjs +45 -37
- package/dist/cli/migration-contract.json.gz +0 -0
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +1 -0
- package/dist/components/agent-tools/budget-meter/budget-meter.styles.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +3 -0
- package/dist/components/charts/chart/chart-band.js +1 -1
- package/dist/components/charts/chart/chart-input-projection.js +1 -1
- package/dist/components/charts/chart/chart-surface.styles.js +1 -1
- package/dist/components/charts/chart/chart-types.d.ts +16 -2
- package/dist/components/charts/chart/chart.class.d.ts +4 -1
- package/dist/components/charts/chart/chart.class.js +3 -3
- package/dist/components/charts/chart/lite-chart.class.d.ts +3 -0
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-base.class.d.ts +29 -3
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.d.ts +46 -2
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.d.ts +6 -2
- package/dist/components/conversation/code-block/code-block-shared.js +5 -4
- package/dist/components/conversation/code-block/code-block.class.d.ts +45 -1
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +12 -0
- package/dist/components/conversation/markdown/markdown.class.d.ts +12 -0
- package/dist/components/conversation/markdown/markdown.styles.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +6 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +3 -0
- package/dist/components/conversation/thread-list/thread-list.styles.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +6 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +21 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/stat/stat.class.d.ts +24 -1
- package/dist/components/data/stat/stat.class.js +2 -2
- package/dist/components/data/stat/stat.styles.js +1 -1
- package/dist/components/data/table/table-row-attributes.js +1 -0
- package/dist/components/data/table/table-support.d.ts +65 -5
- package/dist/components/data/table/table-support.js +1 -1
- package/dist/components/data/table/table.class.d.ts +77 -7
- package/dist/components/data/table/table.class.js +10 -10
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +27 -5
- package/dist/components/data/timeline/timeline-item.class.js +11 -7
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +40 -5
- package/dist/components/data/timeline/timeline.class.js +11 -7
- package/dist/components/data/timeline/timeline.styles.js +1 -1
- package/dist/components/data/tree/tree-item.class.d.ts +2 -0
- package/dist/components/data/tree/tree-item.class.js +2 -2
- package/dist/components/data/tree/tree-item.styles.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +13 -0
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +29 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +3 -3
- package/dist/components/forms/checkbox-group/checkbox-group.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.d.ts +6 -0
- package/dist/components/forms/color-picker/color-picker.class.d.ts +9 -0
- package/dist/components/forms/color-picker/color-picker.class.js +3 -3
- package/dist/components/forms/color-picker/color-picker.styles.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +114 -7
- package/dist/components/forms/combobox/combobox.class.js +9 -7
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/country-picker/country-picker.class.d.ts +2 -0
- package/dist/components/forms/currency-picker/currency-picker.class.d.ts +2 -0
- package/dist/components/forms/date-picker/date-input.class.d.ts +41 -0
- package/dist/components/forms/date-picker/date-input.class.js +2 -2
- package/dist/components/forms/date-picker/date-input.styles.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +4 -0
- package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
- package/dist/components/forms/input/input-shared.d.ts +12 -0
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +6 -0
- package/dist/components/forms/input/time-input.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +11 -0
- package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.d.ts +6 -0
- package/dist/components/forms/phone-input/phone-input.class.d.ts +6 -0
- package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +24 -2
- package/dist/components/forms/radio/radio-group.class.js +2 -2
- package/dist/components/forms/radio/radio-group.styles.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +4 -0
- package/dist/components/forms/select/select.class.d.ts +13 -0
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/select/select.styles.js +1 -1
- package/dist/components/forms/signature-pad/signature-pad.class.d.ts +6 -0
- package/dist/components/forms/signature-pad/signature-pad.styles.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +28 -2
- package/dist/components/forms/slider/slider.class.js +3 -3
- package/dist/components/forms/slider/slider.styles.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +2 -0
- package/dist/components/forms/switch/switch.styles.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +8 -0
- package/dist/components/forms/textarea/textarea.styles.js +1 -1
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.d.ts +2 -0
- package/dist/components/forms/token-input/token-input.class.d.ts +96 -18
- package/dist/components/forms/token-input/token-input.class.js +11 -8
- package/dist/components/forms/token-input/token-input.styles.js +1 -1
- package/dist/components/forms/unit-picker/unit-picker.class.d.ts +2 -0
- package/dist/components/layout/app-rail/app-rail.class.d.ts +3 -0
- package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
- package/dist/components/layout/button-group/button-group.class.d.ts +4 -0
- package/dist/components/layout/button-group/button-group.class.js +1 -1
- package/dist/components/layout/card/card.class.d.ts +15 -1
- package/dist/components/layout/card/card.styles.js +1 -1
- package/dist/components/layout/details/details.class.d.ts +6 -0
- package/dist/components/layout/details/details.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +6 -0
- package/dist/components/layout/filter-bar/filter-bar.styles.js +1 -1
- package/dist/components/layout/index.d.ts +1 -1
- package/dist/components/layout/index.js +1 -1
- package/dist/components/layout/menu/dropdown-item.class.d.ts +8 -2
- package/dist/components/layout/menu/dropdown-item.class.js +1 -1
- package/dist/components/layout/menu/menu-item.class.d.ts +7 -0
- package/dist/components/layout/menu/menu-item.styles.js +1 -1
- package/dist/components/layout/menu/menu-label.class.d.ts +5 -0
- package/dist/components/layout/menu/menu-label.class.js +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +3 -0
- package/dist/components/layout/menu/menu.styles.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +9 -1
- package/dist/components/layout/page/page.class.js +2 -2
- package/dist/components/layout/segmented/segmented.class.d.ts +22 -3
- package/dist/components/layout/segmented/segmented.class.js +3 -4
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/step.class.d.ts +89 -0
- package/dist/components/layout/stepper/step.class.js +18 -0
- package/dist/components/layout/stepper/step.styles.js +1 -0
- package/dist/components/layout/stepper/stepper.class.d.ts +106 -13
- package/dist/components/layout/stepper/stepper.class.js +6 -2
- package/dist/components/layout/stepper/stepper.styles.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +10 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.styles.js +1 -1
- package/dist/components/layout/tab-group/tab-panel.class.d.ts +1 -0
- package/dist/components/layout/tab-group/tab-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +4 -0
- package/dist/components/layout/widget/widget.class.d.ts +1 -0
- package/dist/components/layout/widget/widget.styles.js +1 -1
- package/dist/components/lr-code-block-core.d.ts +1 -1
- package/dist/components/lr-code-block.d.ts +1 -1
- package/dist/components/lr-counter.d.ts +1 -0
- package/dist/components/lr-counter.js +1 -0
- package/dist/components/lr-lightbox-item.d.ts +1 -0
- package/dist/components/lr-lightbox-item.js +1 -0
- package/dist/components/lr-lightbox.d.ts +1 -1
- package/dist/components/lr-lightbox.js +1 -1
- package/dist/components/lr-number-ticker.d.ts +1 -0
- package/dist/components/lr-number-ticker.js +1 -0
- package/dist/components/lr-step.d.ts +1 -0
- package/dist/components/lr-step.js +1 -0
- package/dist/components/media/file-input/file-input.class.d.ts +7 -1
- package/dist/components/media/file-input/file-input.class.js +2 -2
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/index.d.ts +1 -1
- package/dist/components/media/index.js +1 -1
- package/dist/components/media/lightbox/lightbox-item.class.d.ts +57 -0
- package/dist/components/media/lightbox/lightbox-item.class.js +9 -0
- package/dist/components/media/lightbox/lightbox-item.styles.js +1 -0
- package/dist/components/media/lightbox/lightbox.class.d.ts +90 -20
- package/dist/components/media/lightbox/lightbox.class.js +17 -12
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map-anchor-avoid.js +1 -1
- package/dist/components/media/map/map-drawing-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +137 -7
- package/dist/components/media/map/map.class.js +6 -6
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +9 -0
- package/dist/components/media/sequence-playback/sequence-playback.class.js +2 -2
- package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
- package/dist/components/media/video/video.class.d.ts +4 -0
- package/dist/components/media/video/video.class.js +2 -2
- package/dist/components/media/video/video.styles.js +1 -1
- package/dist/components/media/zoomable-frame/zoomable-frame.class.d.ts +15 -0
- package/dist/components/media/zoomable-frame/zoomable-frame.class.js +2 -2
- package/dist/components/overlays/badge/badge.class.d.ts +2 -0
- package/dist/components/overlays/badge/badge.styles.js +1 -1
- package/dist/components/overlays/badge/tag.class.d.ts +2 -0
- package/dist/components/overlays/badge/tag.class.js +1 -1
- package/dist/components/overlays/chip/chip-group.class.d.ts +31 -4
- package/dist/components/overlays/chip/chip-group.class.js +3 -3
- package/dist/components/overlays/context-menu/context-menu.class.d.ts +5 -0
- package/dist/components/overlays/context-menu/context-menu.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +36 -4
- package/dist/components/overlays/dialog/dialog.class.js +3 -3
- package/dist/components/overlays/dialog/dialog.styles.js +1 -1
- package/dist/components/overlays/dialog/prompt.d.ts +60 -0
- package/dist/components/overlays/dialog/prompt.js +1 -0
- package/dist/components/overlays/drawer/drawer.class.d.ts +16 -1
- package/dist/components/overlays/drawer/drawer.class.js +1 -1
- package/dist/components/overlays/empty/empty.class.d.ts +1 -0
- package/dist/components/overlays/empty/empty.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.d.ts +4 -0
- 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/popover.class.d.ts +29 -3
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/overlays/overlay/tooltip.class.d.ts +2 -0
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/toast/toast-item.class.d.ts +1 -0
- package/dist/components/overlays/toast/toast-item.class.js +1 -1
- package/dist/components/overlays/toast/toast-item.styles.js +1 -1
- package/dist/components/overlays/toast/toast.class.d.ts +6 -0
- package/dist/components/overlays/toast/toast.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +2 -0
- package/dist/components/utility/copy-button/copy-button.class.js +2 -2
- package/dist/components/utility/counter/counter-time.d.ts +15 -0
- package/dist/components/utility/counter/counter-time.js +1 -0
- package/dist/components/utility/counter/counter.class.d.ts +67 -0
- package/dist/components/utility/counter/counter.class.js +1 -0
- package/dist/components/utility/counter/counter.styles.js +1 -0
- package/dist/components/utility/divider/divider.class.d.ts +21 -3
- package/dist/components/utility/divider/divider.class.js +5 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +5 -0
- package/dist/components/utility/export-button/export-button.styles.js +1 -1
- package/dist/components/utility/icon/icon-library.d.ts +14 -1
- package/dist/components/utility/icon/icon-library.js +1 -1
- package/dist/components/utility/icon/icon-sprite.js +1 -0
- package/dist/components/utility/icon/icon.class.d.ts +4 -2
- package/dist/components/utility/icon/icon.class.js +2 -2
- package/dist/components/utility/index.d.ts +1 -1
- package/dist/components/utility/index.js +1 -1
- package/dist/components/utility/known-date/known-date.class.d.ts +4 -0
- package/dist/components/utility/number-ticker/number-ticker.class.d.ts +58 -0
- package/dist/components/utility/number-ticker/number-ticker.class.js +1 -0
- package/dist/components/utility/number-ticker/number-ticker.styles.js +1 -0
- package/dist/components/viewers/include/include.class.d.ts +4 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +10 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.styles.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/event-classes.d.ts +2342 -0
- package/dist/event-classes.js +1 -0
- package/dist/events.d.ts +48 -22
- package/dist/framework-types.d.ts +2 -2
- package/dist/internal/all-defined-arguments.d.ts +19 -0
- package/dist/internal/all-defined-arguments.js +1 -0
- package/dist/internal/autoloader-tags.d.ts +1 -1
- package/dist/internal/autoloader-tags.js +1 -1
- package/dist/internal/checked-control-label.js +1 -1
- package/dist/internal/component-loaders.generated.js +1 -1
- package/dist/internal/dedent.js +7 -0
- package/dist/internal/default-strings/forms.generated.js +1 -1
- package/dist/internal/default-strings/layout.generated.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/document-tokens.generated.js +3 -3
- package/dist/internal/form-control/chrome.styles.js +1 -1
- package/dist/internal/form-control.styles.js +1 -1
- package/dist/internal/interactive-control.styles.js +2 -2
- package/dist/internal/labeled-group.js +1 -1
- package/dist/internal/localization-runtime.d.ts +5 -0
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/lyra-event.d.ts +22 -0
- package/dist/internal/lyra-event.js +1 -0
- package/dist/internal/overlay-shared.d.ts +5 -2
- package/dist/internal/overlay-shared.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/root-registration-allowlist.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/shiki/core.d.ts +4 -1
- package/dist/internal/shiki/tokenize.js +1 -1
- package/dist/internal/srcset.js +1 -0
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/ssr/all.d.ts +1 -1
- package/dist/ssr/all.js +1 -1
- package/dist/ssr.d.ts +5 -5
- package/dist/ssr.js +1 -1
- package/dist/styles/native.css +1 -1
- package/dist/styles/palette.css +1 -0
- package/dist/styles/tokens-root.css +1 -1
- package/dist/styles/utilities.css +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/happy-dom-shims.d.ts +11 -2
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/lyra-tag-event-map.d.ts +2 -2
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/theme-core.css +1 -1
- package/dist/theme.css +1 -1
- package/dist/utilities/defined.d.ts +10 -1
- package/dist/utilities/defined.js +1 -1
- package/dist/utilities/form.d.ts +9 -0
- package/dist/utilities/form.js +1 -0
- package/dist/utilities/index.d.ts +1 -1
- package/dist/utilities/index.js +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-app-rail.md +4 -2
- package/llms/components/lr-badge.md +4 -4
- package/llms/components/lr-bar-chart.md +1 -1
- package/llms/components/lr-box-plot.md +6 -1
- package/llms/components/lr-bubble-chart.md +1 -1
- package/llms/components/lr-budget-meter.md +2 -2
- package/llms/components/lr-button-group.md +7 -3
- package/llms/components/lr-button.md +11 -1
- package/llms/components/lr-card.md +11 -1
- package/llms/components/lr-chart.md +21 -7
- package/llms/components/lr-checkbox-group.md +11 -1
- package/llms/components/lr-chip.md +11 -1
- package/llms/components/lr-code-block-core.md +36 -8
- package/llms/components/lr-code-block.md +45 -6
- package/llms/components/lr-code-editor.md +11 -1
- package/llms/components/lr-color-picker.md +17 -4
- package/llms/components/lr-combobox.md +62 -6
- package/llms/components/lr-context-menu.md +5 -3
- package/llms/components/lr-copy-button.md +2 -1
- package/llms/components/lr-counter.md +60 -0
- package/llms/components/lr-country-picker.md +5 -1
- package/llms/components/lr-currency-picker.md +5 -1
- package/llms/components/lr-date-input.md +1 -1
- package/llms/components/lr-date-picker.md +25 -1
- package/llms/components/lr-details.md +6 -2
- package/llms/components/lr-dialog.md +72 -8
- package/llms/components/lr-divider.md +14 -5
- package/llms/components/lr-doughnut-chart.md +1 -1
- package/llms/components/lr-drawer.md +26 -7
- package/llms/components/lr-dropdown-item.md +1 -1
- package/llms/components/lr-dropdown.md +8 -4
- package/llms/components/lr-emoji-picker.md +10 -1
- package/llms/components/lr-empty.md +3 -2
- package/llms/components/lr-export-button.md +5 -2
- package/llms/components/lr-file-input.md +13 -1
- package/llms/components/lr-filter-bar.md +6 -2
- package/llms/components/lr-graph-query-builder.md +10 -1
- package/llms/components/lr-heatmap.md +20 -3
- package/llms/components/lr-histogram.md +7 -2
- package/llms/components/lr-icon-button.md +3 -1
- package/llms/components/lr-icon.md +8 -0
- package/llms/components/lr-include.md +3 -0
- package/llms/components/lr-input.md +9 -1
- package/llms/components/lr-known-date.md +10 -1
- package/llms/components/lr-lightbox-item.md +14 -0
- package/llms/components/lr-lightbox.md +84 -5
- package/llms/components/lr-line-chart.md +7 -2
- package/llms/components/lr-lite-chart.md +3 -2
- package/llms/components/lr-locale-picker.md +17 -1
- package/llms/components/lr-map.md +122 -11
- package/llms/components/lr-markdown-core.md +15 -4
- package/llms/components/lr-markdown.md +13 -4
- package/llms/components/lr-menu-item.md +1 -1
- package/llms/components/lr-menu-label.md +5 -2
- package/llms/components/lr-menu.md +21 -6
- package/llms/components/lr-model-select.md +11 -1
- package/llms/components/lr-native-time-input.md +11 -1
- package/llms/components/lr-number-input.md +11 -1
- package/llms/components/lr-number-ticker.md +55 -0
- package/llms/components/lr-otp-input.md +11 -1
- package/llms/components/lr-page.md +7 -1
- package/llms/components/lr-pagination.md +18 -0
- package/llms/components/lr-pdf-viewer.md +6 -1
- package/llms/components/lr-phone-input.md +11 -1
- package/llms/components/lr-pie-chart.md +1 -1
- package/llms/components/lr-polar-area-chart.md +1 -1
- package/llms/components/lr-popover.md +25 -5
- package/llms/components/lr-radar-chart.md +1 -1
- package/llms/components/lr-radio-group.md +11 -1
- package/llms/components/lr-rubric-form.md +7 -1
- package/llms/components/lr-scatter-chart.md +1 -1
- package/llms/components/lr-segmented.md +20 -2
- package/llms/components/lr-select.md +10 -2
- package/llms/components/lr-sequence-playback.md +8 -2
- package/llms/components/lr-signature-pad.md +8 -1
- package/llms/components/lr-slider.md +17 -4
- package/llms/components/lr-stat.md +20 -5
- package/llms/components/lr-step.md +61 -0
- package/llms/components/lr-stepper.md +64 -8
- package/llms/components/lr-suggestion-chips.md +3 -2
- package/llms/components/lr-switch.md +4 -3
- package/llms/components/lr-tab-group.md +10 -3
- package/llms/components/lr-tab-panel.md +2 -2
- package/llms/components/lr-table.md +87 -8
- package/llms/components/lr-tag.md +1 -1
- package/llms/components/lr-textarea.md +17 -1
- package/llms/components/lr-thread-list.md +4 -2
- package/llms/components/lr-time-input.md +8 -1
- package/llms/components/lr-time-zone-picker.md +5 -1
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -1
- package/llms/components/lr-toast-item.md +1 -1
- package/llms/components/lr-toast.md +7 -2
- package/llms/components/lr-token-input.md +64 -8
- package/llms/components/lr-tooltip.md +3 -3
- package/llms/components/lr-tree-item.md +1 -1
- package/llms/components/lr-tree.md +2 -1
- package/llms/components/lr-unit-picker.md +5 -1
- package/llms/components/lr-video.md +5 -4
- package/llms/components/lr-voice-picker.md +8 -1
- package/llms/components/lr-widget.md +2 -2
- package/llms/components/lr-zoomable-frame.md +8 -0
- package/llms/index.md +145 -141
- package/llms/migration.md +20 -12
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +36 -0
- package/llms/shared/imports-and-registration.md +60 -1
- package/llms/shared/native-styles-and-utilities.md +109 -3
- package/llms/shared/styles-and-tokens.md +2 -2
- package/llms/shared/testing-and-utilities.md +21 -0
- package/llms/shared.md +227 -6
- package/llms/tokens.md +6 -1
- package/llms.txt +3 -3
- package/locales.json +1 -1
- package/package.json +38 -9
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +1 -1
- package/skills/lyra-ui/SKILL.md +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-canvas-target.js";import{MapPaintBatch}from"./map-paint-batch.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{OwnedFrame}from"../../../internal/owned-timer.js";import{OwnedMutationObserver}from"../../../internal/owned-observer.js";import{isElementNode}from"../../../internal/dom-guards.js";import{isSafeNonArrayObject}from"../../../internal/object-guards.js";import{escapeHtml}from"../../../internal/escape-html.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{LYRA_CONTEXT_UPDATE}from"../../../internal/context-update.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{getInheritedPropertyDescriptor,getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,projectFrozenRows,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{literalSetConverter,trueDefaultBooleanConverter,blankNumberConverter}from"../../../internal/converters.js";import{DEV_DIAGNOSTICS,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,readCanvasRgba,resolveCanvasColor,toRgbaString}from"../../../internal/canvas-color.js";import{finiteDuration,finiteInterpolate,finiteNumber,finiteRange,finiteRatio}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{createGroundFollowScene}from"../../../internal/map-camera-ground-follow-scene.js";import{registerSceneAttachmentProvider}from"../../../internal/map-scene-session-registry.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{chartValueFractionDigits,formatChartValue}from"../../../internal/chart-number-format.js";import{notifyMapCanvasReady}from"../../../internal/map-canvas-ready.js";import{AnnouncementSinkController,Announcer}from"../../../internal/announcer.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{normalizeLabel}from"../../../internal/accessible-name.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";import{MapAnchorAvoidance,mergeSafeAreas}from"./map-anchor-avoid.js";const DRAW_MODE=literalSetConverter(["none","line","polygon"],"none"),DRAWING_COMPLETE_BEHAVIOR=literalSetConverter(["clear","edit"],"clear"),HASH_FORMAT=literalSetConverter(["named","unnamed"],"named"),NO_DRAWING_WORK=Promise.resolve(),layerRuntime=()=>loadMapDataLayerRuntime.loaded;function dataLayersRequested(value){try{return Array.isArray(value)&&(readOwnArrayLength(value)??0)>0}catch{return!0}}const NO_OWNED_FEATURES=/* @__PURE__ */(()=>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{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,loadMapDataLayerRuntime,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{boundedLegendText,boundedOwnArrayLength,DEFAULT_ICON_STROKE_WIDTH,DEFAULT_ICON_VIEW_BOX,isRuntimeArray,isUnsafeDescriptor,normalizeMapLegendGradient,optionalDescriptorValue,projectIconPaint}from"./map-descriptor-values.js";const OVERLAY_GROUP_CHANGE=/* @__PURE__ */(()=>Object.freeze({}))();import{emptyExtent,extendExtent,extendExtentWithGeoJson,extentToBounds,normalizeCameraOptions}from"./map-camera.js";import{LYRA_MAP_EMPTY_STYLE}from"./map-empty-style.js";import{clusterColorExpression,heatmapColorExpression,heatmapWeightExpression,heatmapZoomValue,lineColorExpression,mutedCategoryOpacityExpression,pointColorExpression,pointRadiusExpression,stepExpression}from"./map-data-layers.js";import{buildGeoJsonPropertyDiff}from"./map-geojson-diff.js";import{activeElementIn}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair}from"../../../internal/focus-navigation.js";import{repairControlFocusOnUpdate}from"../../../internal/control-focus-repair.js";import{LYRA_DEFAULT_mapActivate,LYRA_DEFAULT_mapCancelDrawing,LYRA_DEFAULT_mapCancelPick,LYRA_DEFAULT_mapCloseWithLabel,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_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_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_close,LYRA_DEFAULT_items,LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_noData,LYRA_DEFAULT_paginationSummary,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_PLACEMENT=literalSetConverter(["top","bottom","start","end","top-start","top-end","bottom-start","bottom-end"],"bottom-start"),LEGEND_CONTROL_ROLE=literalSetConverter(["button","checkbox"],"button"),MAX_LEGEND_GRADIENT_TICKS=16,EMPTY_LEGEND_GRADIENT_TICKS=/* @__PURE__ */(()=>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;isSafeNonArrayObject(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 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=/* @__PURE__ */(()=>Object.freeze([]))(),EMPTY_MAP_LEGEND_PROJECTION=/* @__PURE__ */(()=>Object.freeze({inputCount:0,renderedCount:0,omittedCount:0,truncatedLabelCount:0,truncated:!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=isSafeNonArrayObject(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=/* @__PURE__ */(()=>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 class="legend-icon" viewBox=${`${x} ${y} ${width} ${height}`} focusable="false" ><path d=${icon.path} fill=${mode==="stroke"?"none":"currentColor"} stroke=${mode==="fill"?"none":"currentColor"} stroke-width=${icon.strokeWidth??DEFAULT_ICON_STROKE_WIDTH} stroke-linecap=${icon.lineCap??"round"} stroke-linejoin=${icon.lineJoin??"round"} ></path></svg>`}const PEER_CHROME_PARTS=[[".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"]],PEER_CHROME_SELECTOR=PEER_CHROME_PARTS.map(([selector])=>selector).join(", ");function addPartToken(element,token){const tokens=new Set((element.getAttribute("part")??"").split(/\s+/).filter(Boolean));tokens.add(token),element.setAttribute("part",[...tokens].join(" "))}function attributionExpanded(element){const shown=!element.classList.contains("maplibregl-compact")||element.classList.contains("maplibregl-compact-show");return element.localName==="details"?shown&&element.hasAttribute("open"):shown}const CHOROPLETH_LOG_INTERPOLATION_BASE=.25,CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL=8;function choroplethLogInterpolationFactor(input,lower,upper){const difference=upper-lower;if(difference===0)return 0;const progress=input-lower;return(Math.pow(CHOROPLETH_LOG_INTERPOLATION_BASE,progress)-1)/(Math.pow(CHOROPLETH_LOG_INTERPOLATION_BASE,difference)-1)}function compactGradientPercent(value){return String(Math.round(Math.min(100,Math.max(0,value))*1e4)/1e4)}function choroplethLegendGradientImage(stops,interpolation){const lo=stops[0],hi=stops[stops.length-1],hasRange=hi[0]>lo[0],stopPercent=(value,index)=>(hasRange?finiteRatio(value,lo[0],hi[0]):index/(stops.length-1))*100;if(interpolation!=="logarithmic"||!hasRange)return`linear-gradient(to right, ${stops.map(([value,color],index)=>`${color} ${compactGradientPercent(stopPercent(value,index))}%`).join(", ")})`;const image=[`${lo[1]} 0%`];for(let index=1;index<stops.length;index+=1){const lower=stops[index-1],upper=stops[index];if(upper[0]<=lower[0]){image.push(`${upper[1]} ${compactGradientPercent(stopPercent(upper[0],index))}%`);continue}for(let sample=1;sample<=CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL;sample+=1){const intervalProgress=sample/CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL,input=finiteInterpolate(lower[0],upper[0],intervalProgress),position=finiteRatio(input,lo[0],hi[0])*100;if(sample===CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL){image.push(`${upper[1]} ${compactGradientPercent(position)}%`);continue}const factor=Math.min(1,Math.max(0,choroplethLogInterpolationFactor(input,lower[0],upper[0]))),lowerWeight=compactGradientPercent((1-factor)*100),upperWeight=compactGradientPercent(factor*100);image.push(`color-mix(in srgb, ${lower[1]} ${lowerWeight}%, ${upper[1]} ${upperWeight}%) ${compactGradientPercent(position)}%`)}}return`linear-gradient(to right, ${image.join(", ")})`}const MAX_MAP_MARKERS=2e3;function popupText(host,markup){const template=host.ownerDocument.createElement("template");template.innerHTML=markup;for(const hidden of template.content.querySelectorAll('script, style, template, [hidden], [aria-hidden="true"]'))hidden.remove();return(template.content.textContent??"").replace(/\s+/gu," ").trim()}function markerPopupText(host,markup){return typeof markup=="string"&&markup?popupText(host,markup):""}const EMPTY_CANONICAL_MAP_DATA_LAYERS=/* @__PURE__ */(()=>Object.freeze([]))(),DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-point-icon","-cluster","-cluster-count","-heatmap","-label"],QUERYABLE_DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-cluster","-point-icon","-label"],DEFAULT_HEATMAP_RADIUS=30,DEFAULT_HEATMAP_INTENSITY=1,POINT_ICON_RASTER_SIZE=64;function rasterPointIcon(host,icon,color){try{const canvas=host.ownerDocument.createElement("canvas");canvas.width=canvas.height=POINT_ICON_RASTER_SIZE;const context=canvas.getContext("2d",{willReadFrequently:!0}),Path=host.ownerDocument.defaultView?.Path2D;if(!context||!Path)return;const[x,y,width,height]=icon.viewBox,scale=POINT_ICON_RASTER_SIZE/Math.max(width,height);context.translate((POINT_ICON_RASTER_SIZE-width*scale)/2,(POINT_ICON_RASTER_SIZE-height*scale)/2),context.scale(scale,scale),context.translate(-x,-y);const path=new Path(icon.path);return icon.mode!=="stroke"&&(context.fillStyle=color,context.fill(path)),icon.mode!=="fill"&&icon.strokeWidth>0&&(context.strokeStyle=color,context.lineWidth=icon.strokeWidth,context.lineCap=icon.lineCap,context.lineJoin=icon.lineJoin,context.stroke(path)),context.getImageData(0,0,POINT_ICON_RASTER_SIZE,POINT_ICON_RASTER_SIZE)}catch{return}}function dataLayerShape(layer){if(layer.kind==="heatmap")return"heatmap";const cluster=layer.cluster;return cluster?`cluster:${cluster.radius}:${cluster.maxZoom}:${cluster.countFont?.join(",")??""}`:"auto"}function choroplethHasValueExpression(field){return["==",["typeof",["get",field]],"number"]}const EMPTY_CANONICAL_MAP_MARKERS=/* @__PURE__ */(()=>Object.freeze([]))(),UNPROJECTED_MAP_VALUE=Symbol("unprojected-map-value");function projectMarkerLngLat(value){try{const length=boundedOwnArrayLength(value,2);if(length===void 0||length<2)return;const lngDescriptor=getOwnDataDescriptor(value,"0"),latDescriptor=getOwnDataDescriptor(value,"1");return lngDescriptor===MISSING_OWN_DATA_DESCRIPTOR||latDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(lngDescriptor)||isUnsafeDescriptor(latDescriptor)||typeof lngDescriptor.value!="number"||typeof latDescriptor.value!="number"||!Number.isFinite(lngDescriptor.value)||!Number.isFinite(latDescriptor.value)||latDescriptor.value<-90||latDescriptor.value>90?void 0:Object.freeze([lngDescriptor.value,latDescriptor.value])}catch{return}}function projectMapMarker(value){try{if(!isSafeNonArrayObject(value))return;const idDescriptor=getOwnDataDescriptor(value,"id"),lngLatDescriptor=getOwnDataDescriptor(value,"lngLat"),colorDescriptor=getOwnDataDescriptor(value,"color"),labelDescriptor=getOwnDataDescriptor(value,"label"),unsafeHtmlDescriptor=getOwnDataDescriptor(value,"unsafeHtml");if(lngLatDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(idDescriptor)||isUnsafeDescriptor(lngLatDescriptor)||isUnsafeDescriptor(colorDescriptor)||isUnsafeDescriptor(labelDescriptor)||isUnsafeDescriptor(unsafeHtmlDescriptor))return;const lngLat=projectMarkerLngLat(lngLatDescriptor.value),idValue=optionalDescriptorValue(idDescriptor),labelValue=optionalDescriptorValue(labelDescriptor);if(!lngLat||idValue!==void 0&&typeof idValue!="string"||typeof idValue=="string"&&idValue.trim().length===0||labelValue!==void 0&&typeof labelValue!="string")return;const colorValue=optionalDescriptorValue(colorDescriptor);return Object.freeze({id:typeof idValue=="string"?idValue.trim():void 0,lngLat,color:typeof colorValue=="string"?colorValue:void 0,label:typeof labelValue=="string"?labelValue:void 0,unsafeHtml:optionalDescriptorValue(unsafeHtmlDescriptor)})}catch{return}}function projectMapMarkers(value){const explicitIds=new Set;return projectFrozenRows(value,entry=>{const marker=projectMapMarker(entry);if(marker?.id!==void 0){if(explicitIds.has(marker.id))return;explicitIds.add(marker.id)}return marker},MAX_MAP_MARKERS,EMPTY_CANONICAL_MAP_MARKERS)}function setPopupContent(popup,marker){const options=popup.options,focus=options?.focusAfterOpen;return options&&(options.focusAfterOpen=!1),marker.unsafeHtml?popup.setHTML(marker.unsafeHtml):popup.setText(marker.label),options&&(options.focusAfterOpen=focus),popup}const FIT_EVENT_KEY="lyraMapFit",COMMAND_EVENT_KEY="lyraMapCommand",SESSION_COMMAND_EVENT_KEY="lyraMapCameraSession";function cameraSessionFailure(code){return Object.assign(new Error(code),{code})}const ZERO_CAMERA_PADDING=/* @__PURE__ */(()=>Object.freeze({top:0,right:0,bottom:0,left:0}))(),FIT_TO_DATA_MAX_ZOOM=16,DEFAULT_ZOOM_LIMITS=/* @__PURE__ */(()=>Object.freeze([0,22]))();function snapshotCenter(center){return Array.isArray(center)?[center[0],center[1]]:center}function sameCenterValue(a,b){return Array.isArray(a)&&Array.isArray(b)?Object.is(a[0],b[0])&&Object.is(a[1],b[1]):Object.is(a,b)}function isFiniteCoordinate(value){return typeof value=="number"&&Number.isFinite(value)}function normalizeFitBounds(bounds){if(!Array.isArray(bounds)||bounds.length!==2)return;const[southWest,northEast]=bounds;if(!Array.isArray(southWest)||!Array.isArray(northEast)||southWest.length!==2||northEast.length!==2)return;const[west,south]=southWest,[east,north]=northEast;if(!(!isFiniteCoordinate(west)||!isFiniteCoordinate(south)||!isFiniteCoordinate(east)||!isFiniteCoordinate(north))&&!(west<-180||west>180||east<-180||east>west+360)&&!(south<-90||north>90||south>north))return Object.freeze([Object.freeze([west,south]),Object.freeze([west>east?east+360:east,north])])}function normalizeFitPadding(padding){const side=value=>finiteRange(typeof value=="number"?value:0,0,0);if(typeof padding=="number"){const all=side(padding);return Object.freeze({top:all,right:all,bottom:all,left:all})}const record=typeof padding=="object"&&padding!==null?padding:{};return Object.freeze({top:side(record.top),right:side(record.right),bottom:side(record.bottom),left:side(record.left)})}function wrapLongitude(longitude){if(longitude>=-180&&longitude<=180)return longitude;const wrapped=((longitude+180)%360+360)%360-180;return wrapped===-180?180:wrapped}function readPeerCamera(map){let longitude,latitude,zoom;try{({lng:longitude,lat:latitude}=map.getCenter()),zoom=map.getZoom()}catch{return}if(!(!isFiniteCoordinate(longitude)||!isFiniteCoordinate(latitude)||!isFiniteCoordinate(zoom)))return{center:[wrapLongitude(longitude),finiteRange(latitude,0,-90,90)],zoom}}function ownerWindow(host){return host.ownerDocument?.defaultView??null}const DEFAULT_FILL_OPACITY=.75,DEFAULT_HIDDEN_CATEGORY_OPACITY=.15,DRAWING_TOKENS={"fill-opacity":"--lr-map-drawing-fill-opacity","line-width":"--lr-map-drawing-stroke-width","circle-radius":"--lr-map-drawing-vertex-radius","line-dasharray":"--lr-map-drawing-preview-dash"},TONE_TOKEN={accent:"--lr-color-brand",success:"--lr-color-success",warning:"--lr-color-warning",danger:"--lr-color-danger",neutral:"--lr-color-text-quiet"},ON_TONE_TOKEN={accent:"--lr-color-on-brand",success:"--lr-color-on-success",warning:"--lr-color-on-warning",danger:"--lr-color-on-danger",neutral:"--lr-color-on-neutral"},HEATMAP_RAMP_TOKENS=/* @__PURE__ */(()=>Object.freeze([[.25,"--lr-color-brand"],[.5,"--lr-color-success"],[.75,"--lr-color-warning"],[1,"--lr-color-danger"]]))();function dataLayerColor(host,tone){const token=TONE_TOKEN[tone??"accent"];return(ownerWindow(host)?.getComputedStyle(host).getPropertyValue(token).trim()??"")||DEFAULT_CANVAS_COLOR}const BASIC_MAP_PAINT_COLOR_NAMES=new Set(["aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","purple","red","silver","teal","white","yellow","transparent"]),THEME_PAINT_COLOR=/^\s*(?:var\(|currentcolor\s*$|(?:color-mix|color|oklch|oklab|lch|lab|hwb|light-dark)\()/iu,DRAWING_COLOR_TOKEN="--lr-map-drawing-color",EMPTY_STYLE_LAYERS=/* @__PURE__ */(()=>Object.freeze([]))(),EMPTY_STYLE_SOURCES=/* @__PURE__ */(()=>Object.freeze([]))(),paintColorCache=new WeakMap;function resolvedMapPaintColor(host,color,preserveLegacy){let cache=paintColorCache.get(host);cache||paintColorCache.set(host,cache=new Map);const key=`${preserveLegacy}:${color??""}`;if(cache.has(key))return cache.get(key);const result=resolveMapPaintColor(host,color,preserveLegacy);return cache.size>=512&&cache.clear(),cache.set(key,result),result}function resolveMapPaintColor(host,color,preserveLegacy){const candidate=typeof color=="string"?color.trim():"";if(!candidate)return;if(preserveLegacy){const reference=/^var\(\s*(--[\w-]+)\s*\)$/.exec(candidate),plain=reference?ownerWindow(host)?.getComputedStyle(host).getPropertyValue(reference[1]).trim()??"":candidate,namedPeerColor=BASIC_MAP_PAINT_COLOR_NAMES.has(plain.toLowerCase());if(/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(plain)||(/^rgba?\([\d\s.,/]+\)$/i.test(plain)||namedPeerColor)&&typeof CSS<"u"&&CSS.supports("color",plain))return plain}const resolved=resolveCanvasColor(host,candidate,"");if(resolved){if(/^rgba?\(/i.test(resolved))return resolved;try{const rgba=readCanvasRgba(host.ownerDocument,resolved);return rgba&&toRgbaString(rgba)}catch{return}}}function resolvedLayerColor(host,explicit,tone){return resolvedMapPaintColor(host,explicit,!0)??resolvedMapPaintColor(host,dataLayerColor(host,tone),!0)??DEFAULT_CANVAS_COLOR}function resolvedClusterCountColor(host,color){return resolvedMapPaintColor(host,color,!1)}function resolvedClusterStrokeColor(host,clusterStroke,layer){return resolvedMapPaintColor(host,clusterStroke,!0)??resolvedLayerColor(host,layer.strokeColor??layer.color,layer.tone)}function warnOnUntileableProperties(projection,sourceLabel){if(!(!DEV_DIAGNOSTICS||!litDevWarnings()))for(const feature of projection.diagnostics)for(const[key,value]of feature.properties){if(typeof value!="number"||!Number.isFinite(value)||Math.abs(value)<=Number.MAX_SAFE_INTEGER)continue;const identity=feature.id??`index ${feature.index}`;DEV_DIAGNOSTICS&&devWarnOnce(`lyra-map-untileable-property:${sourceLabel}:${key}`,`<lr-map>: feature ${String(identity)} in "${sourceLabel}" carries ${key}=${value}, which is too large to survive maplibre-gl's vector-tile encoding. Tiling happens in a worker, so the failure would reach you only as an opaque "Given varint doesn't fit into 10 bytes" error while the rest of the layer still paints. Carry a reduced figure in the feature and keep the exact value in your own data.`)}}const EMPTY_DERIVED_LEGEND=/* @__PURE__ */(()=>Object.freeze({rows:Object.freeze([]),gradient:Object.freeze([]),interpolation:"linear",ticks:EMPTY_LEGEND_GRADIENT_TICKS}))(),NO_DATA_SWATCH_COLOR="var(--lr-color-text-quiet)",ISOLATE_START="",ISOLATE_END="";function legendRow(color,label,pattern){return Object.freeze({color,label,pattern})}function buildDerivedChoroplethLegend(choropleth,format,noDataLabel){const rows=[];let gradient=Object.freeze([]),ticks=EMPTY_LEGEND_GRADIENT_TICKS;const stops=choropleth.stops,band=text=>`${ISOLATE_START}${text}${ISOLATE_END}`;if(choropleth.interpolation==="step"){const base=choropleth.stepBaseColor;base&&stops.length>0&&rows.push(legendRow(base,band(`< ${format(stops[0][0])}`),"solid")),(base||stops.length>1)&&stops.forEach(([lower,color],index)=>{const upper=stops[index+1],text=upper===void 0?`≥ ${format(lower)}`:!base&&index===0?`< ${format(upper[0])}`:`${format(lower)} – ${format(upper[0])}`;rows.push(legendRow(color,band(text),"solid"))})}else stops.length>=2&&(gradient=stops,ticks=normalizeMapLegendGradientTicks(stops.slice(1,-1).map(([value])=>value)));return choropleth.noData&&rows.push(legendRow(choropleth.noData.color??NO_DATA_SWATCH_COLOR,choropleth.noData.label??noDataLabel,"diagonal")),Object.freeze({rows:Object.freeze(rows),gradient,interpolation:choropleth.interpolation,ticks})}const MAX_FEATURE_COORDINATES=1e5,GEOMETRY_TYPES=new Set(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"]);function detachedGeometry(geometry){let budget=MAX_FEATURE_COORDINATES;const positions=(value,depth)=>{if(!Array.isArray(value))throw new TypeError("geometry");if(depth===0){if(value.length<2||value.length>4||(budget-=value.length)<0)throw new TypeError("geometry");return Object.freeze(value.map(entry=>{if(typeof entry!="number"||!Number.isFinite(entry))throw new TypeError("geometry");return entry}))}return Object.freeze(value.map(entry=>positions(entry,depth-1)))},one=(value,nested)=>{const type=mapOwnValue(value,"type")??value?.type;if(type==="GeometryCollection"&&!nested){const members=value.geometries;if(!Array.isArray(members))throw new TypeError("geometry");return Object.freeze({type,geometries:Object.freeze(members.map(member=>one(member,!0)))})}if(typeof type!="string"||!GEOMETRY_TYPES.has(type))throw new TypeError("geometry");const depth=type==="Point"?0:type==="MultiPoint"||type==="LineString"?1:type==="MultiPolygon"?3:2;return Object.freeze({type,coordinates:positions(value.coordinates,depth)})};try{return one(geometry,!1)}catch{return null}}function detachedMapFeature(raw,hit){let geometry;try{geometry=raw?.geometry}catch{geometry=void 0}return Object.freeze({type:"Feature",...hit.id===void 0?{}:{id:hit.id},properties:hit.properties,geometry:detachedGeometry(geometry)})}function sourceIdentity(source,layers){const data=source.data;if(typeof data!="object"||data===null)return[JSON.stringify(source),JSON.stringify(layers)];const{data:_data,...rest}=source;return[data,JSON.stringify([rest,layers])]}function featureStatePeer(map){try{return["setFeatureState","removeFeatureState"].every(key=>{const descriptor=getInheritedPropertyDescriptor(map,key);return descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"})}catch{return!1}}class LyraMap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,items:LYRA_DEFAULT_items,legendTypeHidden:LYRA_DEFAULT_legendTypeHidden,legendTypeShown:LYRA_DEFAULT_legendTypeShown,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,mapActivate:LYRA_DEFAULT_mapActivate,mapCancelDrawing:LYRA_DEFAULT_mapCancelDrawing,mapCancelPick:LYRA_DEFAULT_mapCancelPick,mapCloseWithLabel:LYRA_DEFAULT_mapCloseWithLabel,mapCompleteDrawing:LYRA_DEFAULT_mapCompleteDrawing,mapControlUnavailable:LYRA_DEFAULT_mapControlUnavailable,mapDrawAtCenter:LYRA_DEFAULT_mapDrawAtCenter,mapDrawingArea:LYRA_DEFAULT_mapDrawingArea,mapDrawingControls:LYRA_DEFAULT_mapDrawingControls,mapDrawingDuplicateVertex:LYRA_DEFAULT_mapDrawingDuplicateVertex,mapDrawingEditInstructions:LYRA_DEFAULT_mapDrawingEditInstructions,mapDrawingInvalidCoordinate:LYRA_DEFAULT_mapDrawingInvalidCoordinate,mapDrawingInvalidGeometry:LYRA_DEFAULT_mapDrawingInvalidGeometry,mapDrawingLength:LYRA_DEFAULT_mapDrawingLength,mapDrawingTooFewVertices:LYRA_DEFAULT_mapDrawingTooFewVertices,mapDrawingUnavailable:LYRA_DEFAULT_mapDrawingUnavailable,mapDrawingVertex:LYRA_DEFAULT_mapDrawingVertex,mapDrawingVertexLimit:LYRA_DEFAULT_mapDrawingVertexLimit,mapDrawingVertices:LYRA_DEFAULT_mapDrawingVertices,mapExportUnavailable:LYRA_DEFAULT_mapExportUnavailable,mapFeatureStateUnavailable:LYRA_DEFAULT_mapFeatureStateUnavailable,mapFeedback:LYRA_DEFAULT_mapFeedback,mapGeolocateError:LYRA_DEFAULT_mapGeolocateError,mapGeolocateFindLocation:LYRA_DEFAULT_mapGeolocateFindLocation,mapGeolocateOutOfBounds:LYRA_DEFAULT_mapGeolocateOutOfBounds,mapGeolocatePermissionDenied:LYRA_DEFAULT_mapGeolocatePermissionDenied,mapGeolocatePositionUnavailable:LYRA_DEFAULT_mapGeolocatePositionUnavailable,mapGeolocateTimeout:LYRA_DEFAULT_mapGeolocateTimeout,mapGeolocateUnavailable:LYRA_DEFAULT_mapGeolocateUnavailable,mapGlobe:LYRA_DEFAULT_mapGlobe,mapHashConflict:LYRA_DEFAULT_mapHashConflict,mapHashInvalid:LYRA_DEFAULT_mapHashInvalid,mapInitializationFailed:LYRA_DEFAULT_mapInitializationFailed,mapLegend:LYRA_DEFAULT_mapLegend,mapMarker:LYRA_DEFAULT_mapMarker,mapMissingLibrary:LYRA_DEFAULT_mapMissingLibrary,mapPickAtCenter:LYRA_DEFAULT_mapPickAtCenter,mapResetNorth:LYRA_DEFAULT_mapResetNorth,mapScaleFeet:LYRA_DEFAULT_mapScaleFeet,mapScaleKilometers:LYRA_DEFAULT_mapScaleKilometers,mapScaleMeters:LYRA_DEFAULT_mapScaleMeters,mapScaleMiles:LYRA_DEFAULT_mapScaleMiles,mapScaleNauticalMiles:LYRA_DEFAULT_mapScaleNauticalMiles,mapScene:LYRA_DEFAULT_mapScene,mapSceneArc:LYRA_DEFAULT_mapSceneArc,mapSceneEmpty:LYRA_DEFAULT_mapSceneEmpty,mapSceneInvalid:LYRA_DEFAULT_mapSceneInvalid,mapSceneLimit:LYRA_DEFAULT_mapSceneLimit,mapSceneMarker:LYRA_DEFAULT_mapSceneMarker,mapSceneModel:LYRA_DEFAULT_mapSceneModel,mapSceneNext:LYRA_DEFAULT_mapSceneNext,mapScenePage:LYRA_DEFAULT_mapScenePage,mapScenePartial:LYRA_DEFAULT_mapScenePartial,mapScenePath:LYRA_DEFAULT_mapScenePath,mapScenePrevious:LYRA_DEFAULT_mapScenePrevious,mapSceneUnavailable:LYRA_DEFAULT_mapSceneUnavailable,mapSquareKilometers:LYRA_DEFAULT_mapSquareKilometers,mapSquareMeters:LYRA_DEFAULT_mapSquareMeters,mapStyleRequired:LYRA_DEFAULT_mapStyleRequired,mapTerrain:LYRA_DEFAULT_mapTerrain,mapToggleAttribution:LYRA_DEFAULT_mapToggleAttribution,mapUndoDrawing:LYRA_DEFAULT_mapUndoDrawing,mapWebglUnavailable:LYRA_DEFAULT_mapWebglUnavailable,noData:LYRA_DEFAULT_noData,paginationSummary:LYRA_DEFAULT_paginationSummary,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-map-scene-state","lr-map-scene-activate","lr-map-camera-interrupt","lr-map-click","lr-map-feature-enter","lr-map-feature-leave","lr-map-pointer-move","lr-map-contextmenu","lr-map-pick","lr-map-anchor-close","lr-map-draw-start","lr-map-draw-change","lr-map-draw-complete","lr-map-draw-cancel","lr-map-draw-vertex-end","lr-map-legend-panel-toggle-request","lr-map-legend-toggle-request","lr-map-marker-activate","lr-map-move","lr-map-export-error","lr-map-geolocate","lr-map-style-load","lr-map-idle","lr-map-view-change"])}get scene(){return this.geographicSceneValue}set scene(value){const previous=this.geographicSceneValue;Object.is(previous,value)||(this.geographicSceneValue=value,this.requestUpdate("scene",previous),this.geographicSceneOwner?this.geographicSceneOwner.assign(value):this.geographicSceneConnection&&this.startGeographicScene())}connectGeographicScene(){this.closeGeographicScene();const connection=Object.freeze({});this.geographicSceneDocument=this.ownerDocument,this.geographicSceneConnection=connection,this.unregisterGeographicScene=registerSceneAttachmentProvider(this,create=>{if(!this.geographicSceneFacade){const facade=create({connection});if(this.geographicSceneFacade=facade,this.geographicSceneOwner&&!facade.bindState(this.geographicSceneOwner.state)){this.closeGeographicScene();return}}return this.geographicSceneFacade.attachment},objectId=>(this.geographicSceneOwner||this.startGeographicScene(),this.geographicSceneOwner&&createGroundFollowScene(this.geographicSceneOwner.state,objectId))),this.geographicSceneValue!==void 0&&this.startGeographicScene()}startGeographicScene(){const document=this.ownerDocument,generation=this._connectGeneration,owner=createMapSceneOwner({element:this,connection:this.geographicSceneConnection,isCurrentConnection:()=>this.isConnected&&this.ownerDocument===document&&this._connectGeneration===generation&&this.geographicSceneOwner===owner,changed:()=>this.geographicSceneChanged(owner)});if(this.geographicSceneOwner=owner,this.geographicSceneFacade&&!this.geographicSceneFacade.bindState(owner.state)){this.closeGeographicScene();return}this.geographicSceneValue!==void 0&&owner.assign(this.geographicSceneValue)}closeGeographicScene(){this.stopGeographicSceneRender();const owner=this.geographicSceneOwner,facade=this.geographicSceneFacade,unregister=this.unregisterGeographicScene;this.geographicSceneOwner=void 0,this.geographicSceneFacade=void 0,this.geographicSceneConnection=void 0,this.geographicSceneDocument=void 0,this.unregisterGeographicScene=void 0,this.geographicScenePublished=void 0,this.sceneRepairFocus=!1,this.scenePanelOpen=!1,this.scenePage=0,facade?.close(),unregister?.(),owner?.close()}geographicSceneChanged(owner){if(!this.isConnected||this.geographicSceneOwner!==owner)return;const view=owner.captureView();if(this.syncGeographicSceneRender(),this.geographicSceneOwner!==owner||owner.captureView()!==view)return;const focusedId=activeElementIn(this.shadowRoot)?.getAttribute("data-scene-id");this.scenePage=Math.min(this.scenePage,Math.max(0,Math.ceil(view.accepted.objects.length/100)-1)),focusedId&&!view.accepted.objects.slice(this.scenePage*100,(this.scenePage+1)*100).some(object=>object.id===focusedId&&object.interactive)&&(this.sceneRepairFocus=!0),this.scheduleAfterUpdate(()=>{const currentOwner=this.geographicSceneOwner;if(!this.isConnected||!currentOwner)return;const latest=currentOwner.captureView(),status=latest.status;!status||this.geographicScenePublished===status||(this.geographicScenePublished=status,this.requestUpdate(),this.emit("lr-map-scene-state",status),!(!this.isConnected||this.geographicSceneOwner!==currentOwner||currentOwner.captureView()!==latest)&&(!latest.active||status.state==="loading"||status.state==="ready"||(status.state==="partial"?this.announcements.announcePolite(this.sceneStatusMessage(status)):this.announcements.announceAssertive(this.sceneStatusMessage(status)))))},"map-geographic-scene-status")}stopGeographicSceneRender(){const controller=this.geographicSceneRender,owner=this.geographicSceneOwner;this.geographicSceneRender=void 0,this.geographicSceneRenderAttempt=void 0,this.geographicSceneRenderFailure=void 0,owner?.setViewport(void 0),controller?.dispose()}syncGeographicSceneStatus(){const owner=this.geographicSceneOwner;if(!owner||!this.isConnected)return;const accepted=owner.captureAccepted();if(accepted.objects.length===0)return;const counts=countSceneMembers(accepted.objects),controller=this.geographicSceneRender;let outcomes;if(controller)outcomes=controller.captureOutcomes();else{const failed=this.failure!==void 0||this.geographicSceneRenderFailure===accepted.acceptedSceneRevision,outcome=counts.markers+counts.lines===0?{state:"none"}:failed?{state:"failed",code:"engine"}:{state:"pending"};outcomes={markers:outcome,lines:outcome}}owner.reportRenderStatus(accepted.acceptedSceneRevision,summarizeSceneRender(counts,outcomes.markers,outcomes.lines))}syncGeographicSceneRender(){this.syncGeographicSceneRenderer(),this.syncGeographicSceneStatus()}syncGeographicSceneRenderer(){const owner=this.geographicSceneOwner,map=this._map,container=this.containerEl;if(!owner||!map||!container||!this.isConnected||!owner.captureAccepted().objects.some(row=>row.kind==="marker"||row.kind==="path"||row.kind==="arc")){this.stopGeographicSceneRender();return}if(this.geographicSceneRender){this.geographicSceneRender.sync();return}if(this.geographicSceneRenderAttempt||this.geographicSceneRenderFailure===owner.captureAccepted().acceptedSceneRevision)return;const attempt=Object.freeze({}),document=this.ownerDocument;this.geographicSceneRenderAttempt=attempt;const current=()=>this.isConnected&&this.ownerDocument===document&&this._map===map&&this.containerEl===container&&this.geographicSceneOwner===owner&&this.geographicSceneRenderAttempt===attempt,start=runtime2=>{if(!current())return;let controller;try{if(controller=runtime2.createMapSceneRenderController({element:this,map,container,owner,accentToken:TONE_TOKEN.accent,loadBridge:loadMapSceneBridge,isCurrent:current,styleLoaded:()=>this._styleLoaded,onStatusChange:()=>{current()&&this.syncGeographicSceneStatus()}}),!current()){controller.dispose();return}this.geographicSceneRender=controller}catch{controller?.dispose(),current()&&(this.geographicSceneRenderFailure=owner.captureAccepted().acceptedSceneRevision,this.geographicSceneRenderAttempt=void 0)}this.geographicSceneOwner===owner&&this.syncGeographicSceneStatus()},runtime=loadMapSceneRenderRuntime.loaded;runtime?start(runtime):loadMapSceneRenderRuntime().then(start,()=>{current()&&(this.geographicSceneRenderFailure=owner.captureAccepted().acceptedSceneRevision,this.geographicSceneRenderAttempt=void 0,this.syncGeographicSceneStatus())})}notifyCustomLayers(notify){for(const callbacks of[...this.customLayerCallbacks])try{notify(callbacks)}catch{}}acquireCustomLayer(callbacks){const connection=this._connectGeneration;this.customLayerCallbacks.add(callbacks);const current=()=>this.isConnected&&connection===this._connectGeneration&&this.customLayerCallbacks.has(callbacks);return{nativeMap:()=>current()&&this._styleLoaded?this._map:void 0,reducedMotion:()=>prefersReducedMotion(this),activate:(detail,event)=>{if(!current()||this.mapInteractionBlocked()||this.customLayerActivations.has(event))return;this.customLayerActivations.add(event);const activation=Object.freeze({id:detail.id,kind:"custom",layerId:detail.layerId,source:"pointer",...detail.position?{position:detail.position}:{}});this.emit("lr-map-scene-activate",activation)},release:()=>{this.customLayerCallbacks.delete(callbacks)}}}sceneStatusMessage(status){return status.state==="empty"?this.localize("mapSceneEmpty"):status.state==="loading"?this.localize("loading"):status.state==="partial"?this.localize("mapScenePartial"):status.code==="limit"?this.localize("mapSceneLimit"):status.code==="invalid"?this.localize("mapSceneInvalid"):this.localize("mapSceneUnavailable")}sceneInteractionAllowed(owner){return this.isConnected&&this.geographicSceneOwner===owner&&!this.mapInteractionBlocked()}activateSceneObject(owner,revision,object,event){if(!this.sceneInteractionAllowed(owner)||!object.interactive)return;const accepted=owner.captureAccepted();if(accepted.acceptedSceneRevision!==revision||!accepted.objects.includes(object))return;const detail=Object.freeze({id:object.id,kind:object.kind,source:event.detail===0?"keyboard":"pointer",...object.kind==="marker"||object.kind==="model"?{position:object.position}:{}});this.emit("lr-map-scene-activate",detail)}renderGeographicScene(){const owner=this.geographicSceneOwner,view=owner?.captureView();if(!owner||!view?.active)return nothing;const{objects,acceptedSceneRevision}=view.accepted,blocked=this.interactionBlocked,pages=Math.max(1,Math.ceil(objects.length/100)),page=Math.min(this.scenePage,pages-1),kindLabel=kind=>{switch(kind){case"marker":return this.localize("mapSceneMarker");case"path":return this.localize("mapScenePath");case"arc":return this.localize("mapSceneArc");case"model":return this.localize("mapSceneModel")}};return html`<section part="scene-panel" aria-label=${this.localize("mapScene")}>
|
|
1
|
+
import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-canvas-target.js";import{MapPaintBatch}from"./map-paint-batch.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{OwnedFrame}from"../../../internal/owned-timer.js";import{OwnedMutationObserver}from"../../../internal/owned-observer.js";import{isElementNode}from"../../../internal/dom-guards.js";import{isSafeNonArrayObject}from"../../../internal/object-guards.js";import{escapeHtml}from"../../../internal/escape-html.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{LYRA_CONTEXT_UPDATE}from"../../../internal/context-update.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{getInheritedPropertyDescriptor,getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,projectFrozenRows,readOwnArrayLength,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{literalSetConverter,trueDefaultBooleanConverter,blankNumberConverter}from"../../../internal/converters.js";import{DEV_DIAGNOSTICS,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,readCanvasRgba,resolveCanvasColor,toRgbaString}from"../../../internal/canvas-color.js";import{finiteDuration,finiteInterpolate,finiteNumber,finiteRange,finiteRatio}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{createGroundFollowScene}from"../../../internal/map-camera-ground-follow-scene.js";import{registerSceneAttachmentProvider}from"../../../internal/map-scene-session-registry.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{chartValueFractionDigits,formatChartValue}from"../../../internal/chart-number-format.js";import{notifyMapCanvasReady}from"../../../internal/map-canvas-ready.js";import{AnnouncementSinkController,Announcer}from"../../../internal/announcer.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{normalizeLabel}from"../../../internal/accessible-name.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";import{MapAnchorAvoidance,mergeSafeAreas}from"./map-anchor-avoid.js";const DRAW_MODE=literalSetConverter(["none","line","polygon"],"none"),DRAWING_COMPLETE_BEHAVIOR=literalSetConverter(["clear","edit"],"clear"),DRAWING_FINISH_BEHAVIOR=literalSetConverter(["clear","keep"],"clear"),HASH_FORMAT=literalSetConverter(["named","unnamed"],"named"),NO_DRAWING_WORK=Promise.resolve(),layerRuntime=()=>loadMapDataLayerRuntime.loaded;function dataLayersRequested(value){try{return Array.isArray(value)&&(readOwnArrayLength(value)??0)>0}catch{return!0}}const NO_OWNED_FEATURES=/* @__PURE__ */(()=>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{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,loadMapDataLayerRuntime,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{boundedLegendText,boundedOwnArrayLength,DEFAULT_ICON_STROKE_WIDTH,DEFAULT_ICON_VIEW_BOX,isRuntimeArray,isUnsafeDescriptor,normalizeMapLegendGradient,optionalDescriptorValue,projectIconPaint}from"./map-descriptor-values.js";const OVERLAY_GROUP_CHANGE=/* @__PURE__ */(()=>Object.freeze({}))();import{emptyExtent,extendExtent,extendExtentWithGeoJson,extentToBounds,normalizeCameraOptions}from"./map-camera.js";import{LYRA_MAP_EMPTY_STYLE}from"./map-empty-style.js";import{clusterColorExpression,heatmapColorExpression,heatmapWeightExpression,heatmapZoomValue,lineColorExpression,mutedCategoryOpacityExpression,pointColorExpression,pointRadiusExpression,stepExpression}from"./map-data-layers.js";import{buildGeoJsonPropertyDiff}from"./map-geojson-diff.js";import{activeElementIn}from"../../../internal/active-element.js";import{applyComposedFocusRepair,captureComposedFocusRepair}from"../../../internal/focus-navigation.js";import{repairControlFocusOnUpdate}from"../../../internal/control-focus-repair.js";import{LYRA_DEFAULT_mapActivate,LYRA_DEFAULT_mapCancelDrawing,LYRA_DEFAULT_mapCancelPick,LYRA_DEFAULT_mapCloseWithLabel,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_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_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_close,LYRA_DEFAULT_items,LYRA_DEFAULT_legendTypeHidden,LYRA_DEFAULT_legendTypeShown,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_noData,LYRA_DEFAULT_paginationSummary,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_CLEARANCE=literalSetConverter(["row","corner","none"],"row"),LEGEND_FLOW=literalSetConverter(["row","column"],"row"),LEGEND_PLACEMENT=literalSetConverter(["top","bottom","start","end","top-start","top-end","bottom-start","bottom-end"],"bottom-start"),LEGEND_CONTROL_ROLE=literalSetConverter(["button","checkbox"],"button"),MAX_LEGEND_GRADIENT_TICKS=16,EMPTY_LEGEND_GRADIENT_TICKS=/* @__PURE__ */(()=>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;isSafeNonArrayObject(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 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=/* @__PURE__ */(()=>Object.freeze([]))(),EMPTY_MAP_LEGEND_PROJECTION=/* @__PURE__ */(()=>Object.freeze({inputCount:0,renderedCount:0,omittedCount:0,truncatedLabelCount:0,truncated:!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=isSafeNonArrayObject(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=/* @__PURE__ */(()=>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 class="legend-icon" viewBox=${`${x} ${y} ${width} ${height}`} focusable="false" ><path d=${icon.path} fill=${mode==="stroke"?"none":"currentColor"} stroke=${mode==="fill"?"none":"currentColor"} stroke-width=${icon.strokeWidth??DEFAULT_ICON_STROKE_WIDTH} stroke-linecap=${icon.lineCap??"round"} stroke-linejoin=${icon.lineJoin??"round"} ></path></svg>`}const PEER_CHROME_PARTS=[[".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"]],PEER_CHROME_SELECTOR=PEER_CHROME_PARTS.map(([selector])=>selector).join(", ");function addPartToken(element,token){const tokens=new Set((element.getAttribute("part")??"").split(/\s+/).filter(Boolean));tokens.add(token),element.setAttribute("part",[...tokens].join(" "))}function attributionExpanded(element){const shown=!element.classList.contains("maplibregl-compact")||element.classList.contains("maplibregl-compact-show");return element.localName==="details"?shown&&element.hasAttribute("open"):shown}const CHOROPLETH_LOG_INTERPOLATION_BASE=.25,CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL=8;function choroplethLogInterpolationFactor(input,lower,upper){const difference=upper-lower;if(difference===0)return 0;const progress=input-lower;return(Math.pow(CHOROPLETH_LOG_INTERPOLATION_BASE,progress)-1)/(Math.pow(CHOROPLETH_LOG_INTERPOLATION_BASE,difference)-1)}function compactGradientPercent(value){return String(Math.round(Math.min(100,Math.max(0,value))*1e4)/1e4)}function choroplethLegendGradientImage(stops,interpolation){const lo=stops[0],hi=stops[stops.length-1],hasRange=hi[0]>lo[0],stopPercent=(value,index)=>(hasRange?finiteRatio(value,lo[0],hi[0]):index/(stops.length-1))*100;if(interpolation!=="logarithmic"||!hasRange)return`linear-gradient(to right, ${stops.map(([value,color],index)=>`${color} ${compactGradientPercent(stopPercent(value,index))}%`).join(", ")})`;const image=[`${lo[1]} 0%`];for(let index=1;index<stops.length;index+=1){const lower=stops[index-1],upper=stops[index];if(upper[0]<=lower[0]){image.push(`${upper[1]} ${compactGradientPercent(stopPercent(upper[0],index))}%`);continue}for(let sample=1;sample<=CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL;sample+=1){const intervalProgress=sample/CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL,input=finiteInterpolate(lower[0],upper[0],intervalProgress),position=finiteRatio(input,lo[0],hi[0])*100;if(sample===CHOROPLETH_LEGEND_SAMPLES_PER_INTERVAL){image.push(`${upper[1]} ${compactGradientPercent(position)}%`);continue}const factor=Math.min(1,Math.max(0,choroplethLogInterpolationFactor(input,lower[0],upper[0]))),lowerWeight=compactGradientPercent((1-factor)*100),upperWeight=compactGradientPercent(factor*100);image.push(`color-mix(in srgb, ${lower[1]} ${lowerWeight}%, ${upper[1]} ${upperWeight}%) ${compactGradientPercent(position)}%`)}}return`linear-gradient(to right, ${image.join(", ")})`}const MAX_MAP_MARKERS=2e3;function popupText(host,markup){const template=host.ownerDocument.createElement("template");template.innerHTML=markup;for(const hidden of template.content.querySelectorAll('script, style, template, [hidden], [aria-hidden="true"]'))hidden.remove();return(template.content.textContent??"").replace(/\s+/gu," ").trim()}function markerPopupText(host,markup){return typeof markup=="string"&&markup?popupText(host,markup):""}const EMPTY_CANONICAL_MAP_DATA_LAYERS=/* @__PURE__ */(()=>Object.freeze([]))(),DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-point-icon","-cluster","-cluster-count","-heatmap","-label"],QUERYABLE_DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-cluster","-point-icon","-label"],DEFAULT_HEATMAP_RADIUS=30,DEFAULT_HEATMAP_INTENSITY=1,POINT_ICON_RASTER_SIZE=64;function rasterPointIcon(host,icon,color){try{const canvas=host.ownerDocument.createElement("canvas");canvas.width=canvas.height=POINT_ICON_RASTER_SIZE;const context=canvas.getContext("2d",{willReadFrequently:!0}),Path=host.ownerDocument.defaultView?.Path2D;if(!context||!Path)return;const[x,y,width,height]=icon.viewBox,scale=POINT_ICON_RASTER_SIZE/Math.max(width,height);context.translate((POINT_ICON_RASTER_SIZE-width*scale)/2,(POINT_ICON_RASTER_SIZE-height*scale)/2),context.scale(scale,scale),context.translate(-x,-y);const path=new Path(icon.path);return icon.mode!=="stroke"&&(context.fillStyle=color,context.fill(path)),icon.mode!=="fill"&&icon.strokeWidth>0&&(context.strokeStyle=color,context.lineWidth=icon.strokeWidth,context.lineCap=icon.lineCap,context.lineJoin=icon.lineJoin,context.stroke(path)),context.getImageData(0,0,POINT_ICON_RASTER_SIZE,POINT_ICON_RASTER_SIZE)}catch{return}}function dataLayerShape(layer){if(layer.kind==="heatmap")return"heatmap";const cluster=layer.cluster;return cluster?`cluster:${cluster.radius}:${cluster.maxZoom}:${cluster.countFont?.join(",")??""}`:"auto"}function choroplethHasValueExpression(field){return["==",["typeof",["get",field]],"number"]}const EMPTY_CANONICAL_MAP_MARKERS=/* @__PURE__ */(()=>Object.freeze([]))(),UNPROJECTED_MAP_VALUE=Symbol("unprojected-map-value");function projectMarkerLngLat(value){try{const length=boundedOwnArrayLength(value,2);if(length===void 0||length<2)return;const lngDescriptor=getOwnDataDescriptor(value,"0"),latDescriptor=getOwnDataDescriptor(value,"1");return lngDescriptor===MISSING_OWN_DATA_DESCRIPTOR||latDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(lngDescriptor)||isUnsafeDescriptor(latDescriptor)||typeof lngDescriptor.value!="number"||typeof latDescriptor.value!="number"||!Number.isFinite(lngDescriptor.value)||!Number.isFinite(latDescriptor.value)||latDescriptor.value<-90||latDescriptor.value>90?void 0:Object.freeze([lngDescriptor.value,latDescriptor.value])}catch{return}}function projectMapMarker(value){try{if(!isSafeNonArrayObject(value))return;const idDescriptor=getOwnDataDescriptor(value,"id"),lngLatDescriptor=getOwnDataDescriptor(value,"lngLat"),colorDescriptor=getOwnDataDescriptor(value,"color"),labelDescriptor=getOwnDataDescriptor(value,"label"),unsafeHtmlDescriptor=getOwnDataDescriptor(value,"unsafeHtml");if(lngLatDescriptor===MISSING_OWN_DATA_DESCRIPTOR||isUnsafeDescriptor(idDescriptor)||isUnsafeDescriptor(lngLatDescriptor)||isUnsafeDescriptor(colorDescriptor)||isUnsafeDescriptor(labelDescriptor)||isUnsafeDescriptor(unsafeHtmlDescriptor))return;const lngLat=projectMarkerLngLat(lngLatDescriptor.value),idValue=optionalDescriptorValue(idDescriptor),labelValue=optionalDescriptorValue(labelDescriptor);if(!lngLat||idValue!==void 0&&typeof idValue!="string"||typeof idValue=="string"&&idValue.trim().length===0||labelValue!==void 0&&typeof labelValue!="string")return;const colorValue=optionalDescriptorValue(colorDescriptor);return Object.freeze({id:typeof idValue=="string"?idValue.trim():void 0,lngLat,color:typeof colorValue=="string"?colorValue:void 0,label:typeof labelValue=="string"?labelValue:void 0,unsafeHtml:optionalDescriptorValue(unsafeHtmlDescriptor)})}catch{return}}function projectMapMarkers(value){const explicitIds=new Set;return projectFrozenRows(value,entry=>{const marker=projectMapMarker(entry);if(marker?.id!==void 0){if(explicitIds.has(marker.id))return;explicitIds.add(marker.id)}return marker},MAX_MAP_MARKERS,EMPTY_CANONICAL_MAP_MARKERS)}function setPopupContent(popup,marker){const options=popup.options,focus=options?.focusAfterOpen;return options&&(options.focusAfterOpen=!1),marker.unsafeHtml?popup.setHTML(marker.unsafeHtml):popup.setText(marker.label),options&&(options.focusAfterOpen=focus),popup}const FIT_EVENT_KEY="lyraMapFit",COMMAND_EVENT_KEY="lyraMapCommand",SESSION_COMMAND_EVENT_KEY="lyraMapCameraSession";function cameraSessionFailure(code){return Object.assign(new Error(code),{code})}const ZERO_CAMERA_PADDING=/* @__PURE__ */(()=>Object.freeze({top:0,right:0,bottom:0,left:0}))(),FIT_TO_DATA_MAX_ZOOM=16,DEFAULT_ZOOM_LIMITS=/* @__PURE__ */(()=>Object.freeze([0,22]))();function snapshotCenter(center){return Array.isArray(center)?[center[0],center[1]]:center}function sameCenterValue(a,b){return Array.isArray(a)&&Array.isArray(b)?Object.is(a[0],b[0])&&Object.is(a[1],b[1]):Object.is(a,b)}function isFiniteCoordinate(value){return typeof value=="number"&&Number.isFinite(value)}function normalizeFitBounds(bounds){if(!Array.isArray(bounds)||bounds.length!==2)return;const[southWest,northEast]=bounds;if(!Array.isArray(southWest)||!Array.isArray(northEast)||southWest.length!==2||northEast.length!==2)return;const[west,south]=southWest,[east,north]=northEast;if(!(!isFiniteCoordinate(west)||!isFiniteCoordinate(south)||!isFiniteCoordinate(east)||!isFiniteCoordinate(north))&&!(west<-180||west>180||east<-180||east>west+360)&&!(south<-90||north>90||south>north))return Object.freeze([Object.freeze([west,south]),Object.freeze([west>east?east+360:east,north])])}function normalizeFitPadding(padding){const side=value=>finiteRange(typeof value=="number"?value:0,0,0);if(typeof padding=="number"){const all=side(padding);return Object.freeze({top:all,right:all,bottom:all,left:all})}const record=typeof padding=="object"&&padding!==null?padding:{};return Object.freeze({top:side(record.top),right:side(record.right),bottom:side(record.bottom),left:side(record.left)})}function wrapLongitude(longitude){if(longitude>=-180&&longitude<=180)return longitude;const wrapped=((longitude+180)%360+360)%360-180;return wrapped===-180?180:wrapped}function readPeerCamera(map){let longitude,latitude,zoom;try{({lng:longitude,lat:latitude}=map.getCenter()),zoom=map.getZoom()}catch{return}if(!(!isFiniteCoordinate(longitude)||!isFiniteCoordinate(latitude)||!isFiniteCoordinate(zoom)))return{center:[wrapLongitude(longitude),finiteRange(latitude,0,-90,90)],zoom}}function ownerWindow(host){return host.ownerDocument?.defaultView??null}const DEFAULT_FILL_OPACITY=.75,DEFAULT_HIDDEN_CATEGORY_OPACITY=.15,DRAWING_TOKENS={"fill-opacity":"--lr-map-drawing-fill-opacity","line-width":"--lr-map-drawing-stroke-width","circle-radius":"--lr-map-drawing-vertex-radius","line-dasharray":"--lr-map-drawing-preview-dash"},TONE_TOKEN={accent:"--lr-color-brand",success:"--lr-color-success",warning:"--lr-color-warning",danger:"--lr-color-danger",neutral:"--lr-color-text-quiet"},ON_TONE_TOKEN={accent:"--lr-color-on-brand",success:"--lr-color-on-success",warning:"--lr-color-on-warning",danger:"--lr-color-on-danger",neutral:"--lr-color-on-neutral"},HEATMAP_RAMP_TOKENS=/* @__PURE__ */(()=>Object.freeze([[.25,"--lr-color-brand"],[.5,"--lr-color-success"],[.75,"--lr-color-warning"],[1,"--lr-color-danger"]]))();function dataLayerColor(host,tone){const token=TONE_TOKEN[tone??"accent"];return(ownerWindow(host)?.getComputedStyle(host).getPropertyValue(token).trim()??"")||DEFAULT_CANVAS_COLOR}const BASIC_MAP_PAINT_COLOR_NAMES=new Set(["aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","purple","red","silver","teal","white","yellow","transparent"]),THEME_PAINT_COLOR=/^\s*(?:var\(|currentcolor\s*$|(?:color-mix|color|oklch|oklab|lch|lab|hwb|light-dark)\()/iu,DRAWING_COLOR_TOKEN="--lr-map-drawing-color",EMPTY_STYLE_LAYERS=/* @__PURE__ */(()=>Object.freeze([]))(),EMPTY_STYLE_SOURCES=/* @__PURE__ */(()=>Object.freeze([]))(),paintColorCache=new WeakMap;function resolvedMapPaintColor(host,color,preserveLegacy){let cache=paintColorCache.get(host);cache||paintColorCache.set(host,cache=new Map);const key=`${preserveLegacy}:${color??""}`;if(cache.has(key))return cache.get(key);const result=resolveMapPaintColor(host,color,preserveLegacy);return cache.size>=512&&cache.clear(),cache.set(key,result),result}function resolveMapPaintColor(host,color,preserveLegacy){const candidate=typeof color=="string"?color.trim():"";if(!candidate)return;if(preserveLegacy){const reference=/^var\(\s*(--[\w-]+)\s*\)$/.exec(candidate),plain=reference?ownerWindow(host)?.getComputedStyle(host).getPropertyValue(reference[1]).trim()??"":candidate,namedPeerColor=BASIC_MAP_PAINT_COLOR_NAMES.has(plain.toLowerCase());if(/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(plain)||(/^rgba?\([\d\s.,/]+\)$/i.test(plain)||namedPeerColor)&&typeof CSS<"u"&&CSS.supports("color",plain))return plain}const resolved=resolveCanvasColor(host,candidate,"");if(resolved){if(/^rgba?\(/i.test(resolved))return resolved;try{const rgba=readCanvasRgba(host.ownerDocument,resolved);return rgba&&toRgbaString(rgba)}catch{return}}}function resolvedLayerColor(host,explicit,tone){return resolvedMapPaintColor(host,explicit,!0)??resolvedMapPaintColor(host,dataLayerColor(host,tone),!0)??DEFAULT_CANVAS_COLOR}function resolvedClusterCountColor(host,color){return resolvedMapPaintColor(host,color,!1)}function resolvedClusterStrokeColor(host,clusterStroke,layer){return resolvedMapPaintColor(host,clusterStroke,!0)??resolvedLayerColor(host,layer.strokeColor??layer.color,layer.tone)}function warnOnUntileableProperties(projection,sourceLabel){if(!(!DEV_DIAGNOSTICS||!litDevWarnings()))for(const feature of projection.diagnostics)for(const[key,value]of feature.properties){if(typeof value!="number"||!Number.isFinite(value)||Math.abs(value)<=Number.MAX_SAFE_INTEGER)continue;const identity=feature.id??`index ${feature.index}`;DEV_DIAGNOSTICS&&devWarnOnce(`lyra-map-untileable-property:${sourceLabel}:${key}`,`<lr-map>: feature ${String(identity)} in "${sourceLabel}" carries ${key}=${value}, which is too large to survive maplibre-gl's vector-tile encoding. Tiling happens in a worker, so the failure would reach you only as an opaque "Given varint doesn't fit into 10 bytes" error while the rest of the layer still paints. Carry a reduced figure in the feature and keep the exact value in your own data.`)}}const EMPTY_DERIVED_LEGEND=/* @__PURE__ */(()=>Object.freeze({rows:Object.freeze([]),gradient:Object.freeze([]),interpolation:"linear",ticks:EMPTY_LEGEND_GRADIENT_TICKS}))(),NO_DATA_SWATCH_COLOR="var(--lr-color-text-quiet)",ISOLATE_START="",ISOLATE_END="";function legendRow(color,label,pattern){return Object.freeze({color,label,pattern})}function buildDerivedChoroplethLegend(choropleth,format,noDataLabel){const rows=[];let gradient=Object.freeze([]),ticks=EMPTY_LEGEND_GRADIENT_TICKS;const stops=choropleth.stops,band=text=>`${ISOLATE_START}${text}${ISOLATE_END}`;if(choropleth.interpolation==="step"){const base=choropleth.stepBaseColor;base&&stops.length>0&&rows.push(legendRow(base,band(`< ${format(stops[0][0])}`),"solid")),(base||stops.length>1)&&stops.forEach(([lower,color],index)=>{const upper=stops[index+1],text=upper===void 0?`≥ ${format(lower)}`:!base&&index===0?`< ${format(upper[0])}`:`${format(lower)} – ${format(upper[0])}`;rows.push(legendRow(color,band(text),"solid"))})}else stops.length>=2&&(gradient=stops,ticks=normalizeMapLegendGradientTicks(stops.slice(1,-1).map(([value])=>value)));return choropleth.noData&&rows.push(legendRow(choropleth.noData.color??NO_DATA_SWATCH_COLOR,choropleth.noData.label??noDataLabel,"diagonal")),Object.freeze({rows:Object.freeze(rows),gradient,interpolation:choropleth.interpolation,ticks})}const MAX_FEATURE_COORDINATES=1e5,GEOMETRY_TYPES=new Set(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon"]);function detachedGeometry(geometry){let budget=MAX_FEATURE_COORDINATES;const positions=(value,depth)=>{if(!Array.isArray(value))throw new TypeError("geometry");if(depth===0){if(value.length<2||value.length>4||(budget-=value.length)<0)throw new TypeError("geometry");return Object.freeze(value.map(entry=>{if(typeof entry!="number"||!Number.isFinite(entry))throw new TypeError("geometry");return entry}))}return Object.freeze(value.map(entry=>positions(entry,depth-1)))},one=(value,nested)=>{const type=mapOwnValue(value,"type")??value?.type;if(type==="GeometryCollection"&&!nested){const members=value.geometries;if(!Array.isArray(members))throw new TypeError("geometry");return Object.freeze({type,geometries:Object.freeze(members.map(member=>one(member,!0)))})}if(typeof type!="string"||!GEOMETRY_TYPES.has(type))throw new TypeError("geometry");const depth=type==="Point"?0:type==="MultiPoint"||type==="LineString"?1:type==="MultiPolygon"?3:2;return Object.freeze({type,coordinates:positions(value.coordinates,depth)})};try{return one(geometry,!1)}catch{return null}}function detachedMapFeature(raw,hit){let geometry;try{geometry=raw?.geometry}catch{geometry=void 0}return Object.freeze({type:"Feature",...hit.id===void 0?{}:{id:hit.id},properties:hit.properties,geometry:detachedGeometry(geometry)})}function sourceIdentity(source,layers){const data=source.data;if(typeof data!="object"||data===null)return[JSON.stringify(source),JSON.stringify(layers)];const{data:_data,...rest}=source;return[data,JSON.stringify([rest,layers])]}function featureStatePeer(map){try{return["setFeatureState","removeFeatureState"].every(key=>{const descriptor=getInheritedPropertyDescriptor(map,key);return descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"})}catch{return!1}}class LyraMap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,items:LYRA_DEFAULT_items,legendTypeHidden:LYRA_DEFAULT_legendTypeHidden,legendTypeShown:LYRA_DEFAULT_legendTypeShown,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,mapActivate:LYRA_DEFAULT_mapActivate,mapCancelDrawing:LYRA_DEFAULT_mapCancelDrawing,mapCancelPick:LYRA_DEFAULT_mapCancelPick,mapCloseWithLabel:LYRA_DEFAULT_mapCloseWithLabel,mapCompleteDrawing:LYRA_DEFAULT_mapCompleteDrawing,mapControlUnavailable:LYRA_DEFAULT_mapControlUnavailable,mapDrawAtCenter:LYRA_DEFAULT_mapDrawAtCenter,mapDrawingArea:LYRA_DEFAULT_mapDrawingArea,mapDrawingControls:LYRA_DEFAULT_mapDrawingControls,mapDrawingDuplicateVertex:LYRA_DEFAULT_mapDrawingDuplicateVertex,mapDrawingEditInstructions:LYRA_DEFAULT_mapDrawingEditInstructions,mapDrawingInvalidCoordinate:LYRA_DEFAULT_mapDrawingInvalidCoordinate,mapDrawingInvalidGeometry:LYRA_DEFAULT_mapDrawingInvalidGeometry,mapDrawingLength:LYRA_DEFAULT_mapDrawingLength,mapDrawingTooFewVertices:LYRA_DEFAULT_mapDrawingTooFewVertices,mapDrawingUnavailable:LYRA_DEFAULT_mapDrawingUnavailable,mapDrawingVertex:LYRA_DEFAULT_mapDrawingVertex,mapDrawingVertexLimit:LYRA_DEFAULT_mapDrawingVertexLimit,mapDrawingVertices:LYRA_DEFAULT_mapDrawingVertices,mapExportUnavailable:LYRA_DEFAULT_mapExportUnavailable,mapFeatureStateUnavailable:LYRA_DEFAULT_mapFeatureStateUnavailable,mapFeedback:LYRA_DEFAULT_mapFeedback,mapGeolocateError:LYRA_DEFAULT_mapGeolocateError,mapGeolocateFindLocation:LYRA_DEFAULT_mapGeolocateFindLocation,mapGeolocateOutOfBounds:LYRA_DEFAULT_mapGeolocateOutOfBounds,mapGeolocatePermissionDenied:LYRA_DEFAULT_mapGeolocatePermissionDenied,mapGeolocatePositionUnavailable:LYRA_DEFAULT_mapGeolocatePositionUnavailable,mapGeolocateTimeout:LYRA_DEFAULT_mapGeolocateTimeout,mapGeolocateUnavailable:LYRA_DEFAULT_mapGeolocateUnavailable,mapGlobe:LYRA_DEFAULT_mapGlobe,mapHashConflict:LYRA_DEFAULT_mapHashConflict,mapHashInvalid:LYRA_DEFAULT_mapHashInvalid,mapInitializationFailed:LYRA_DEFAULT_mapInitializationFailed,mapLegend:LYRA_DEFAULT_mapLegend,mapMarker:LYRA_DEFAULT_mapMarker,mapMissingLibrary:LYRA_DEFAULT_mapMissingLibrary,mapPickAtCenter:LYRA_DEFAULT_mapPickAtCenter,mapResetNorth:LYRA_DEFAULT_mapResetNorth,mapScaleFeet:LYRA_DEFAULT_mapScaleFeet,mapScaleKilometers:LYRA_DEFAULT_mapScaleKilometers,mapScaleMeters:LYRA_DEFAULT_mapScaleMeters,mapScaleMiles:LYRA_DEFAULT_mapScaleMiles,mapScaleNauticalMiles:LYRA_DEFAULT_mapScaleNauticalMiles,mapScene:LYRA_DEFAULT_mapScene,mapSceneArc:LYRA_DEFAULT_mapSceneArc,mapSceneEmpty:LYRA_DEFAULT_mapSceneEmpty,mapSceneInvalid:LYRA_DEFAULT_mapSceneInvalid,mapSceneLimit:LYRA_DEFAULT_mapSceneLimit,mapSceneMarker:LYRA_DEFAULT_mapSceneMarker,mapSceneModel:LYRA_DEFAULT_mapSceneModel,mapSceneNext:LYRA_DEFAULT_mapSceneNext,mapScenePage:LYRA_DEFAULT_mapScenePage,mapScenePartial:LYRA_DEFAULT_mapScenePartial,mapScenePath:LYRA_DEFAULT_mapScenePath,mapScenePrevious:LYRA_DEFAULT_mapScenePrevious,mapSceneUnavailable:LYRA_DEFAULT_mapSceneUnavailable,mapSquareKilometers:LYRA_DEFAULT_mapSquareKilometers,mapSquareMeters:LYRA_DEFAULT_mapSquareMeters,mapStyleRequired:LYRA_DEFAULT_mapStyleRequired,mapTerrain:LYRA_DEFAULT_mapTerrain,mapToggleAttribution:LYRA_DEFAULT_mapToggleAttribution,mapUndoDrawing:LYRA_DEFAULT_mapUndoDrawing,mapWebglUnavailable:LYRA_DEFAULT_mapWebglUnavailable,noData:LYRA_DEFAULT_noData,paginationSummary:LYRA_DEFAULT_paginationSummary,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-map-scene-state","lr-map-scene-activate","lr-map-camera-interrupt","lr-map-click","lr-map-feature-enter","lr-map-feature-leave","lr-map-pointer-move","lr-map-contextmenu","lr-map-pick","lr-map-anchor-close","lr-map-draw-start","lr-map-draw-change","lr-map-draw-complete","lr-map-draw-cancel","lr-map-draw-vertex-end","lr-map-legend-panel-toggle-request","lr-map-legend-toggle-request","lr-map-marker-activate","lr-map-move","lr-map-export-error","lr-map-geolocate","lr-map-style-load","lr-map-idle","lr-map-view-change"])}get scene(){return this.geographicSceneValue}set scene(value){const previous=this.geographicSceneValue;Object.is(previous,value)||(this.geographicSceneValue=value,this.requestUpdate("scene",previous),this.geographicSceneOwner?this.geographicSceneOwner.assign(value):this.geographicSceneConnection&&this.startGeographicScene())}connectGeographicScene(){this.closeGeographicScene();const connection=Object.freeze({});this.geographicSceneDocument=this.ownerDocument,this.geographicSceneConnection=connection,this.unregisterGeographicScene=registerSceneAttachmentProvider(this,create=>{if(!this.geographicSceneFacade){const facade=create({connection});if(this.geographicSceneFacade=facade,this.geographicSceneOwner&&!facade.bindState(this.geographicSceneOwner.state)){this.closeGeographicScene();return}}return this.geographicSceneFacade.attachment},objectId=>(this.geographicSceneOwner||this.startGeographicScene(),this.geographicSceneOwner&&createGroundFollowScene(this.geographicSceneOwner.state,objectId))),this.geographicSceneValue!==void 0&&this.startGeographicScene()}startGeographicScene(){const document=this.ownerDocument,generation=this._connectGeneration,owner=createMapSceneOwner({element:this,connection:this.geographicSceneConnection,isCurrentConnection:()=>this.isConnected&&this.ownerDocument===document&&this._connectGeneration===generation&&this.geographicSceneOwner===owner,changed:()=>this.geographicSceneChanged(owner)});if(this.geographicSceneOwner=owner,this.geographicSceneFacade&&!this.geographicSceneFacade.bindState(owner.state)){this.closeGeographicScene();return}this.geographicSceneValue!==void 0&&owner.assign(this.geographicSceneValue)}closeGeographicScene(){this.stopGeographicSceneRender();const owner=this.geographicSceneOwner,facade=this.geographicSceneFacade,unregister=this.unregisterGeographicScene;this.geographicSceneOwner=void 0,this.geographicSceneFacade=void 0,this.geographicSceneConnection=void 0,this.geographicSceneDocument=void 0,this.unregisterGeographicScene=void 0,this.geographicScenePublished=void 0,this.sceneRepairFocus=!1,this.scenePanelOpen=!1,this.scenePage=0,facade?.close(),unregister?.(),owner?.close()}geographicSceneChanged(owner){if(!this.isConnected||this.geographicSceneOwner!==owner)return;const view=owner.captureView();if(this.syncGeographicSceneRender(),this.geographicSceneOwner!==owner||owner.captureView()!==view)return;const focusedId=activeElementIn(this.shadowRoot)?.getAttribute("data-scene-id");this.scenePage=Math.min(this.scenePage,Math.max(0,Math.ceil(view.accepted.objects.length/100)-1)),focusedId&&!view.accepted.objects.slice(this.scenePage*100,(this.scenePage+1)*100).some(object=>object.id===focusedId&&object.interactive)&&(this.sceneRepairFocus=!0),this.scheduleAfterUpdate(()=>{const currentOwner=this.geographicSceneOwner;if(!this.isConnected||!currentOwner)return;const latest=currentOwner.captureView(),status=latest.status;!status||this.geographicScenePublished===status||(this.geographicScenePublished=status,this.requestUpdate(),this.emit("lr-map-scene-state",status),!(!this.isConnected||this.geographicSceneOwner!==currentOwner||currentOwner.captureView()!==latest)&&(!latest.active||status.state==="loading"||status.state==="ready"||(status.state==="partial"?this.announcements.announcePolite(this.sceneStatusMessage(status)):this.announcements.announceAssertive(this.sceneStatusMessage(status)))))},"map-geographic-scene-status")}stopGeographicSceneRender(){const controller=this.geographicSceneRender,owner=this.geographicSceneOwner;this.geographicSceneRender=void 0,this.geographicSceneRenderAttempt=void 0,this.geographicSceneRenderFailure=void 0,owner?.setViewport(void 0),controller?.dispose()}syncGeographicSceneStatus(){const owner=this.geographicSceneOwner;if(!owner||!this.isConnected)return;const accepted=owner.captureAccepted();if(accepted.objects.length===0)return;const counts=countSceneMembers(accepted.objects),controller=this.geographicSceneRender;let outcomes;if(controller)outcomes=controller.captureOutcomes();else{const failed=this.failure!==void 0||this.geographicSceneRenderFailure===accepted.acceptedSceneRevision,outcome=counts.markers+counts.lines===0?{state:"none"}:failed?{state:"failed",code:"engine"}:{state:"pending"};outcomes={markers:outcome,lines:outcome}}owner.reportRenderStatus(accepted.acceptedSceneRevision,summarizeSceneRender(counts,outcomes.markers,outcomes.lines))}syncGeographicSceneRender(){this.syncGeographicSceneRenderer(),this.syncGeographicSceneStatus()}syncGeographicSceneRenderer(){const owner=this.geographicSceneOwner,map=this._map,container=this.containerEl;if(!owner||!map||!container||!this.isConnected||!owner.captureAccepted().objects.some(row=>row.kind==="marker"||row.kind==="path"||row.kind==="arc")){this.stopGeographicSceneRender();return}if(this.geographicSceneRender){this.geographicSceneRender.sync();return}if(this.geographicSceneRenderAttempt||this.geographicSceneRenderFailure===owner.captureAccepted().acceptedSceneRevision)return;const attempt=Object.freeze({}),document=this.ownerDocument;this.geographicSceneRenderAttempt=attempt;const current=()=>this.isConnected&&this.ownerDocument===document&&this._map===map&&this.containerEl===container&&this.geographicSceneOwner===owner&&this.geographicSceneRenderAttempt===attempt,start=runtime2=>{if(!current())return;let controller;try{if(controller=runtime2.createMapSceneRenderController({element:this,map,container,owner,accentToken:TONE_TOKEN.accent,loadBridge:loadMapSceneBridge,isCurrent:current,styleLoaded:()=>this._styleLoaded,onStatusChange:()=>{current()&&this.syncGeographicSceneStatus()}}),!current()){controller.dispose();return}this.geographicSceneRender=controller}catch{controller?.dispose(),current()&&(this.geographicSceneRenderFailure=owner.captureAccepted().acceptedSceneRevision,this.geographicSceneRenderAttempt=void 0)}this.geographicSceneOwner===owner&&this.syncGeographicSceneStatus()},runtime=loadMapSceneRenderRuntime.loaded;runtime?start(runtime):loadMapSceneRenderRuntime().then(start,()=>{current()&&(this.geographicSceneRenderFailure=owner.captureAccepted().acceptedSceneRevision,this.geographicSceneRenderAttempt=void 0,this.syncGeographicSceneStatus())})}notifyCustomLayers(notify){for(const callbacks of[...this.customLayerCallbacks])try{notify(callbacks)}catch{}}acquireCustomLayer(callbacks){const connection=this._connectGeneration;this.customLayerCallbacks.add(callbacks);const current=()=>this.isConnected&&connection===this._connectGeneration&&this.customLayerCallbacks.has(callbacks);return{nativeMap:()=>current()&&this._styleLoaded?this._map:void 0,reducedMotion:()=>prefersReducedMotion(this),activate:(detail,event)=>{if(!current()||this.mapInteractionBlocked()||this.customLayerActivations.has(event))return;this.customLayerActivations.add(event);const activation=Object.freeze({id:detail.id,kind:"custom",layerId:detail.layerId,source:"pointer",...detail.position?{position:detail.position}:{}});this.emit("lr-map-scene-activate",activation)},release:()=>{this.customLayerCallbacks.delete(callbacks)}}}sceneStatusMessage(status){return status.state==="empty"?this.localize("mapSceneEmpty"):status.state==="loading"?this.localize("loading"):status.state==="partial"?this.localize("mapScenePartial"):status.code==="limit"?this.localize("mapSceneLimit"):status.code==="invalid"?this.localize("mapSceneInvalid"):this.localize("mapSceneUnavailable")}sceneInteractionAllowed(owner){return this.isConnected&&this.geographicSceneOwner===owner&&!this.mapInteractionBlocked()}activateSceneObject(owner,revision,object,event){if(!this.sceneInteractionAllowed(owner)||!object.interactive)return;const accepted=owner.captureAccepted();if(accepted.acceptedSceneRevision!==revision||!accepted.objects.includes(object))return;const detail=Object.freeze({id:object.id,kind:object.kind,source:event.detail===0?"keyboard":"pointer",...object.kind==="marker"||object.kind==="model"?{position:object.position}:{}});this.emit("lr-map-scene-activate",detail)}renderGeographicScene(){const owner=this.geographicSceneOwner,view=owner?.captureView();if(!owner||!view?.active)return nothing;const{objects,acceptedSceneRevision}=view.accepted,blocked=this.interactionBlocked,pages=Math.max(1,Math.ceil(objects.length/100)),page=Math.min(this.scenePage,pages-1),kindLabel=kind=>{switch(kind){case"marker":return this.localize("mapSceneMarker");case"path":return this.localize("mapScenePath");case"arc":return this.localize("mapSceneArc");case"model":return this.localize("mapSceneModel")}};return html`<section part="scene-panel" aria-label=${this.localize("mapScene")}>
|
|
2
2
|
<button type="button" part="scene-toggle" aria-expanded=${String(this.scenePanelOpen)} aria-controls="scene-objects-list" ?disabled=${blocked} @click=${()=>{this.sceneInteractionAllowed(owner)&&(this.scenePanelOpen=!this.scenePanelOpen)}}>${this.localize("mapScene")}</button>
|
|
3
3
|
${view.status&&view.status.state!=="ready"?html`<div part="scene-status">${this.sceneStatusMessage(view.status)}</div>`:nothing}
|
|
4
4
|
<div id="scene-objects-list" ?hidden=${!this.scenePanelOpen}>
|
|
@@ -11,8 +11,8 @@ import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-ca
|
|
|
11
11
|
<button type="button" ?disabled=${blocked||page+1===pages} @click=${()=>{this.sceneInteractionAllowed(owner)&&(this.scenePage=Math.min(pages-1,page+1))}}>${this.localize("mapSceneNext")}</button>
|
|
12
12
|
</div>`:nothing}
|
|
13
13
|
</div>
|
|
14
|
-
</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.projectionGuard=new VetoWriteGuard,this.terrainGuard=new VetoWriteGuard,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.moveFrame=new OwnedFrame(this),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._legendPlacement="bottom-start",this._legendOpen=!0,this.legendOpenGuard=new VetoWriteGuard,this.categoriesGuard=new VetoWriteGuard,this._hiddenCategories=EMPTY_HIDDEN_CATEGORIES,this._hiddenCategoriesRevision=0,this.markers=[],this.dataLayers=[],this.overlays={},this.images=[],this.styleOverrides=[],this.overlayGroups=new Map,this.overlayGroupSequence=0,this.overlayGroupRevision=0,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.dataLayerRuntimeFailed=!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.pickGuard=new VetoWriteGuard,this.keyboardActivation=!1,this.drawMode="none",this.drawingMeasurements=!1,this._drawingCompleteBehavior="clear",this.drawingSticky=!1,this.drawingRevision=0,this.drawingProgressAnnouncers=[0,1].map(()=>new Announcer({onFlush:text=>{this.announcements.announcePolite(text)}})),this.drawingProgressState=[void 0,void 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.openChildAnchors=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)&&DEV_DIAGNOSTICS&&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.detached=new DeferredTeardown(()=>this.releaseConnection()),this.mapUpdateActive=!1,this.actionBarFocusRepair=null,this.writingBusy=!1,this.authoredBusy=!1,this.fillOpacity=DEFAULT_FILL_OPACITY,this.hiddenOpacity=DEFAULT_HIDDEN_CATEGORY_OPACITY,this.drawingPaint={},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.pointerFrame=new OwnedFrame(this),this.pointerInside=!1,this.drawMapCenter=()=>{this.drawingController?.addCenter()},this.cancelMapPick=()=>{if(!this.pickMode||this.mapInteractionBlocked())return;const map=this._map,generation=this._connectGeneration,detail=Object.freeze({source:"control"});requestThenCommit({guard:this.pickGuard,requestDetail:detail,emitRequest:(proposal,init)=>this.emit("lr-map-pick-cancel-request",proposal,init),commit:()=>{!this.isConnected||this._connectGeneration!==generation||this._map!==map||this.mapInteractionBlocked()||(this.pickMode=!1,this.clearMapHover(),this.emit("lr-map-pick-cancel",detail))}})},this.pickMapCenter=()=>{const map=this._map,generation=this.interactionGeneration;if(!(!map||!this.pickMode||!this.mapInteractionAllowed()))try{const lngLat=mapCoordinates(map.getCenter());if(!lngLat||this._map!==map||generation!==this.interactionGeneration||!this.mapInteractionAllowed())return;const[x,y]=this.project(lngLat)??[];this.emit("lr-map-pick",Object.freeze({lngLat,...this.interactionPosition({x,y}),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"]'),repairControlFocusOnUpdate(this)}get projection(){return this._projection}set projection(value){markVetoGuardWrite(this.projectionGuard);const old=this._projection;this._projection=normalizeMapProjection(value),this.requestUpdate("projection",old)}get terrain(){return this._terrain}set terrain(value){markVetoGuardWrite(this.terrainGuard);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 DEV_DIAGNOSTICS&&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)}configurationMessage(issue){switch(issue){case"mapHashConflict":return this.localize("mapHashConflict");case"mapHashInvalid":return this.localize("mapHashInvalid");case"mapControlUnavailable":return this.localize("mapControlUnavailable");case"mapGeolocatePermissionDenied":return this.localize("mapGeolocatePermissionDenied");case"mapGeolocatePositionUnavailable":return this.localize("mapGeolocatePositionUnavailable");case"mapGeolocateTimeout":return this.localize("mapGeolocateTimeout");case"mapGeolocateError":return this.localize("mapGeolocateError");case"mapGeolocateOutOfBounds":return this.localize("mapGeolocateOutOfBounds")}}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.configurationMessage(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{}}effectiveAnchorSafeArea(){const authored=this.anchorSafeArea,avoid=this.anchorAvoidance?.area,cached=this.mergedSafeArea;if(cached&&cached.authored===authored&&cached.avoid===avoid)return cached.value;const value=mergeSafeAreas(authored,avoid);return this.mergedSafeArea={authored,avoid,value},value}syncAnchorAvoidance(){!this.anchorAvoid?.length&&!this.anchorAvoidance||(this.anchorAvoidance??=new MapAnchorAvoidance({element:this,direction:()=>this.effectiveDirection,changed:()=>{this.scheduleAnchorSync()}}),this.anchorAvoidance.observe(this.isConnected?this.anchorAvoid:void 0))}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(!DEV_DIAGNOSTICS||!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)})||DEV_DIAGNOSTICS&&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 legendPlacement(){return this._legendPlacement}set legendPlacement(next){const normalized=LEGEND_PLACEMENT.normalizeReflected(this,"legend-placement",next),old=this._legendPlacement;old!==normalized&&(this._legendPlacement=normalized,this.requestUpdate("legendPlacement",old))}get legendOpen(){return this._legendOpen}set legendOpen(value){markVetoGuardWrite(this.legendOpenGuard);const previous=this._legendOpen;this._legendOpen=value,this.requestUpdate("legendOpen",previous)}get legendCollapsed(){return this.legendCollapsible&&!this.legendOpen}toggleLegendPanel(){if(!this.legendCollapsible||this.mapInteractionBlocked())return;const open=!this.legendOpen,connection=this._connectGeneration;requestThenCommit({guard:this.legendOpenGuard,requestDetail:{open},emitRequest:(detail,init)=>this.emit("lr-map-legend-panel-toggle-request",detail,init),commit:()=>{this.isConnected&&this._connectGeneration===connection&&this.legendCollapsible&&!this.mapInteractionBlocked()&&(this.legendOpen=open)}})}renderLegendDisclosure(){return this.legendCollapsible?html`<button part="legend-disclosure" type="button" aria-expanded=${this.legendOpen?"true":"false"} aria-controls="map-legend-list" ?disabled=${this.interactionBlocked} @click=${()=>this.toggleLegendPanel()} ><span part="legend-disclosure-icon" class="legend-disclosure-icon" aria-hidden="true" >${chevronIcon()}</span
|
|
15
|
-
><span>${this.localize("mapLegend")}</span></button>`:nothing}get hiddenCategories(){return this._hiddenCategories}set hiddenCategories(value){if(markVetoGuardWrite(this.categoriesGuard),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}set markersTruncated(_value){}setOverlayGroup(key,group,options={}){if(typeof key!="string"||!key||group===null||typeof group!="object")return!1;const order=Number.isFinite(options.order)?options.order:0,previous=this.overlayGroups.get(key);return previous?.group===group&&previous.order===order||(this.overlayGroups.set(key,{order,sequence:previous?.sequence??this.overlayGroupSequence++,group}),this.overlayGroupsChanged()),!0}removeOverlayGroup(key){return this.overlayGroups.delete(key)?(this.overlayGroupsChanged(),!0):!1}sameOwnedOverlayInput(overlays,images,styleOverrides){const current=this.ownedOverlayInput();return current.overlays===overlays&¤t.images===images&¤t.styleOverrides===styleOverrides}ownedFeatureInputRequested(){const{overlays,images,styleOverrides}=this.ownedOverlayInput();return ownedFeaturesRequested(overlays,images,styleOverrides)}overlayGroupsChanged(){this.overlayGroupRevision+=1,this.requestUpdate("overlays",OVERLAY_GROUP_CHANGE)}ownedOverlayInput(){const{overlays,images,styleOverrides}=this;if(!this.overlayGroups.size)return{overlays,images,styleOverrides};const key=[overlays,images,styleOverrides,this.overlayGroupRevision],cached=this.ownedInputCache;if(cached&&cached.key.every((value2,index)=>value2===key[index]))return cached.value;const groups=[...this.overlayGroups.values()].sort((a,b)=>a.order-b.order||a.sequence-b.sequence).map(entry=>entry.group),list=(base,pick)=>Object.freeze([...Array.isArray(base)?base:[],...groups.flatMap(group=>{const value2=pick(group);return Array.isArray(value2)?value2:[]})]),value=Object.freeze({overlays:Object.freeze({sources:list(overlays.sources,group=>group.sources),layers:list(overlays.layers,group=>group.layers)}),images:list(images,group=>group.images),styleOverrides:list(styleOverrides,group=>group.styleOverrides)});return this.ownedInputCache={key,value},value}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")}requestDataLayerRuntime(){if(this.dataLayerRuntimeLoad||this.dataLayerRuntimeFailed)return;const load=this.dataLayerRuntimeLoad=loadMapDataLayerRuntime().then(()=>{},()=>{this.dataLayerRuntimeFailed=!0,this.setDataLayerIssue(!0)}).then(()=>{this.dataLayerRuntimeLoad===load&&(this.dataLayerRuntimeLoad=void 0),dataLayersRequested(this.dataLayers)&&this.requestUpdate("dataLayers",EMPTY_CANONICAL_MAP_DATA_LAYERS),isSafeNonArrayObject(this.choropleth)&&this.requestUpdate("choropleth",null),this.isConnected&&this.tryConstructMap()});this.trackFeatureLoad(load)}dataLayerRuntimeUnavailable(){return this.dataLayerRuntimeFailed&&!loadMapDataLayerRuntime.loaded&&(dataLayersRequested(this.dataLayers)||isSafeNonArrayObject(this.choropleth))}dataLayerRuntimePending(){return this.canonicalDataLayers,this.canonicalChoropleth,this.dataLayerRuntimeLoad!==void 0}async getUpdateComplete(){let complete=await super.getUpdateComplete();for(;this.dataLayerRuntimeLoad;)await this.dataLayerRuntimeLoad,complete=await super.getUpdateComplete();return complete}get canonicalChoropleth(){const source=this.choropleth;if(Object.is(source,this._canonicalChoroplethSource))return this._canonicalChoropleth;const runtime=loadMapDataLayerRuntime.loaded;if(!runtime&&isSafeNonArrayObject(source)){this.requestDataLayerRuntime();return}return this._canonicalChoroplethSource=source,this._canonicalChoropleth=runtime?.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;const runtime=loadMapDataLayerRuntime.loaded;if(!runtime&&dataLayersRequested(source))return this.requestDataLayerRuntime(),EMPTY_CANONICAL_MAP_DATA_LAYERS;this._canonicalDataLayersSource=source,this._canonicalDataLayersBase=base,this._canonicalDataLayersOrigin=origin;const model=runtime?.projectMapDataLayers(source,base,origin)??{ok:!0,geojson:EMPTY_CANONICAL_MAP_DATA_LAYERS,external:[]};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 pickMode(){return this._pickMode}set pickMode(value){markVetoGuardWrite(this.pickGuard);const previous=this._pickMode;this._pickMode=value,this.requestUpdate("pickMode",previous)}get drawingCompleteBehavior(){return this._drawingCompleteBehavior}set drawingCompleteBehavior(next){const normalized=DRAWING_COMPLETE_BEHAVIOR.normalizeReflected(this,"drawing-complete-behavior",next),old=this._drawingCompleteBehavior;old!==normalized&&(this._drawingCompleteBehavior=normalized,this.requestUpdate("drawingCompleteBehavior",old))}get drawingPending(){return this.drawingController?.pending===!0}get drawingWork(){return this.drawingController?.work??NO_DRAWING_WORK}get map(){return this._map}set map(_value){}whenStyleReady(){return this.readiness.whenStyleReady()}whenControlsReady(){return this.controlsReadiness.whenReady()}whenIdle(){return this.readiness.whenIdle()}pushGeoJson(source,resolvedSourceId,geojson,projection){const previous=this._appliedGeoJson.get(resolvedSourceId);if(previous===projection)return;const diff=typeof source.updateData=="function"&&previous!==void 0?layerRuntime().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]),DEV_DIAGNOSTICS&&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,()=>{DEV_DIAGNOSTICS&&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 DEV_DIAGNOSTICS&&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)}}return retired&&reason!=="disconnect"&&this.isConnected&&this.emit("lr-map-camera-interrupt",Object.freeze({reason})),this.isConnected&&(!this.cameraSession||this.cameraSession===owner&&owner.revision===revision&&owner.pendingAction===void 0)}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:(DEV_DIAGNOSTICS&&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.isConnected?this._map:void 0;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.isConnected?this._map:void 0;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}}scaleUnits(){return{ft:this.localize("mapScaleFeet"),m:this.localize("mapScaleMeters"),km:this.localize("mapScaleKilometers"),mi:this.localize("mapScaleMiles"),nm:this.localize("mapScaleNauticalMiles")}}controlLocale(){const units=this.scaleUnits();for(const native of["ft","m","km","mi","nm"])this.scaleLabels.set(native,native),this.scaleLabels.set(units[native],native);return{"GeolocateControl.FindMyLocation":this.localize("mapGeolocateFindLocation"),"GeolocateControl.LocationNotAvailable":this.localize("mapGeolocateUnavailable"),"ScaleControl.Feet":escapeHtml(units.ft),"ScaleControl.Meters":escapeHtml(units.m),"ScaleControl.Kilometers":escapeHtml(units.km),"ScaleControl.Miles":escapeHtml(units.mi),"ScaleControl.NauticalMiles":escapeHtml(units.nm)}}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=isSafeNonArrayObject(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",detail=Object.freeze({projection,source:"control"});requestThenCommit({guard:this.projectionGuard,requestDetail:detail,emitRequest:(proposal,init)=>this.emit("lr-map-projection-change-request",proposal,init),commit:()=>{!current()||this.mapInteractionBlocked()||(this.projection=projection,this.emit("lr-map-projection-change",detail))}})}else{const terrain=event.action.pressed===!0?null:event.action.terrain;if(terrain===void 0)return;const detail=Object.freeze({terrain,source:"control"});requestThenCommit({guard:this.terrainGuard,requestDetail:detail,emitRequest:(proposal,init)=>this.emit("lr-map-terrain-change-request",proposal,init),commit:()=>{!current()||this.mapInteractionBlocked()||(this.terrain=terrain,this.emit("lr-map-terrain-change",detail))}})}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.configurationMessage(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"&&code!=="busy"&&(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.openChildAnchors.size===0)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),anchor.open&&this.childAnchorSet.has(anchor)?this.openChildAnchors.add(anchor):this.openChildAnchors.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,mapSafeArea:()=>this.effectiveAnchorSafeArea()}}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.effectiveAnchorSafeArea(),closable:()=>this.anchorClosable,pending:()=>this.isUpdatePending,requestClose:detail=>!this.emit("lr-map-anchor-close-request",detail,{cancelable:!0}).defaultPrevented,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.pending)return;const view=ownerWindow(this);if(!view||typeof view.requestAnimationFrame!="function"){this.reportMove(map);return}this.moveFrame.schedule(()=>{this.reportMove(map)})}flushMoveReport(map){this.moveFrame.pending&&(this.cancelMoveReport(),this.reportMove(map))}cancelMoveReport(){this.moveFrame.pending&&this.moveFrame.cancel()}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(){if(super.connectedCallback(),this.detached.cancel()){this.resumeAfterMove();return}const ownerWindow2=this.ownerDocument.defaultView;if(ownerWindow2)for(const announcer of this.drawingProgressAnnouncers)announcer.setTimerHost(ownerWindow2);const generation=++this._connectGeneration;this.observeMapInteractionState(),this.syncAnchorAvoidance(),this.unregisterCameraSession?.(),this.unregisterCameraSession=registerMapCameraSession(this,{acquire:callbacks=>this.acquireCameraSession(callbacks)}),this.unregisterCustomLayers?.(),this.unregisterCustomLayers=registerMapCustomLayers(this,{acquire:callbacks=>this.acquireCustomLayer(callbacks)}),this.failure=void 0,this.loading=!0,this._webglReady=!1,this.connectGeographicScene(),this.readiness.reset(),this.controlsReadiness.reset(),this.hashRuntimeFailed=!1,this.dataLayerRuntimeFailed=!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=activeElementIn(this.shadowRoot)?.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),(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)}})()}resumeAfterMove(){const blocked=this.interactionBlocked;this.observeMapInteractionState();const observer=this.interactionObserver;this.interactionBlocked!==blocked&&this.applyMapInteractionState(()=>this.isConnected&&this.interactionObserver===observer),this.canvasAllocationController&&(this.releaseCanvasAllocation(),this.syncCanvasAllocation())}disconnectedCallback(){super.disconnectedCallback(),this.detached.schedule()}releaseConnection(){this.anchorAvoidance?.disconnect();for(const announcer of this.drawingProgressAnnouncers)announcer.cancel();this.drawingProgressState=[void 0,void 0],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(this.detached.flush(),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();const ownerWindow2=this.ownerDocument.defaultView;if(ownerWindow2)for(const announcer of this.drawingProgressAnnouncers)announcer.setTimerHost(ownerWindow2);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||this.dataLayerRuntimePending())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))}}(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);const contextUpdate=args[0]===LYRA_CONTEXT_UPDATE;if(valueChanged&&(args[0]===void 0||contextUpdate||["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||contextUpdate||["label","lang","locale","strings","markers","legend","legendGradient","hasLegendSlot","hasLegendStartSlot","choropleth","choroplethLegend"].includes(String(args[0])))&&(this.semanticsStale=!0),this.isUpdatePending&&(args[0]===void 0||contextUpdate||["label","lang","locale","strings","markers"].includes(String(args[0])))&&(this.markerSemanticsStale=!0)}performUpdate(){this.mapUpdateActive=!0;try{super.performUpdate()}finally{this.mapUpdateActive=!1}}captureActionBarFocus(){const bar=activeElementIn(this.shadowRoot)?.closest('[part="pick-controls"], [part="drawing-controls"]');this.actionBarFocusRepair=bar?captureComposedFocusRepair(bar,bar):null}repairActionBarFocus(){const repair=this.actionBarFocusRepair;if(this.actionBarFocusRepair=null,!repair||repair.activeElement.isConnected&&!repair.activeElement.matches(":disabled"))return;const survivors=this.renderRoot.querySelectorAll('[part="pick-controls"] button, [part="drawing-controls"] button'),canvas=this._map?.getCanvas?.(),activate=this.renderRoot.querySelector('[part="initialization-activate"]');applyComposedFocusRepair(repair,[...survivors,canvas,activate,this.containerEl])}announceDrawingProgress(){const drawing=this.drawingController,shown=(this.drawMode==="line"||this.drawMode==="polygon"||drawing?.editing===!0)&&!this.pickMode&&!this.failure&&!this.loading,vertices=drawing?.snapshot?.vertices??[],next=shown?[String(vertices.length),JSON.stringify(vertices)]:[void 0,void 0],[count,signature]=this.drawingProgressState;if(this.drawingProgressState=next,!shown)return;count!==void 0&&count!==next[0]&&this.drawingProgressAnnouncers[0].announce(this.localize("mapDrawingVertices",void 0,{count:this.formatLocaleNumber(vertices.length)}));const summary=this.drawingMeasurements?this.drawingSummary(drawing?.snapshot):void 0;summary&&signature!==void 0&&signature!==next[1]&&this.drawingProgressAnnouncers[1].announce(summary)}updated(changed){super.updated(changed),this.repairActionBarFocus(),this.announceDrawingProgress(),changed.has("failure")&&this.syncGeographicSceneStatus(),this.sceneRepairFocus&&(this.sceneRepairFocus=!1,this.shadowRoot?.querySelector('[part="scene-toggle"]')?.focus({preventScroll:!0})),this.cameraUpdatePending=!1;const busy=String(this.loading||!this._map&&!this.failure&&!this.awaitingActivation);if(!this.authoredBusy&&this.getAttribute("aria-busy")!==busy){this.writingBusy=!0;try{this.setAttribute("aria-busy",busy)}finally{this.writingBusy=!1}}if(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(),changed.has("anchorAvoid")?this.syncAnchorAvoidance():changed.has("dir")&&this.anchorAvoidance&&this.anchorAvoidance.refresh(),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)})}static get observedAttributes(){return[...super.observedAttributes,"aria-busy"]}attributeChangedCallback(name,previous,value){super.attributeChangedCallback(name,previous,value),name==="aria-busy"&&!this.writingBusy&&(this.authoredBusy=value!==null,value===null&&super.requestUpdate())}willUpdate(changed){if(this.drawingConfigApplying=this.drawingConfigRevision,this.cameraSessionConfigurationApplying=this.cameraSessionConfigurationRevision,super.willUpdate(changed),(this.anchorLngLat!=null||this.openChildAnchors.size>0)&&this.effectiveDirection,this.refreshingGeoJson=this.geoJsonRefreshRequested,this.geoJsonRefreshRequested=!1,this.captureActionBarFocus(),this.refreshingGeoJson){const choropleth=this.canonicalChoropleth;choropleth&&(this._canonicalChoropleth={...choropleth,geojsonProjection:layerRuntime().projectAdmittedGeoJson(choropleth.geojson,!0)}),this._canonicalDataLayers=this.canonicalDataLayers.map(layer=>({...layer,geojsonProjection:layerRuntime().projectAdmittedGeoJson(layer.geojson,!0)}))}(changed.has("legendGradient")||changed.has("dataLayers"))&&(this.legendIsLine=this.legendDescribesLine());const legendSource=this.choroplethLegend?this.canonicalChoropleth:void 0,locale=this.effectiveLocale,noData=legendSource?this.localize("noData"):"";(legendSource!==this.legendSource||locale!==this.legendLocale||noData!==this.legendNoData)&&(this.legendSource=legendSource,this.legendLocale=locale,this.legendNoData=noData,this.derivedLegend=legendSource?buildDerivedChoroplethLegend(legendSource,value=>this.formatLocaleNumber(value),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 owned=this.ownedOverlayInput(),sources=[this.dataLayers,this.choropleth,owned.styleOverrides,owned.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,...Object.values(DRAWING_TOKENS)]),inputs=JSON.stringify([this.canonicalDataLayers.map(({geojson:_geojson,geojsonProjection:_projection,...paint})=>paint),[this.canonicalChoropleth?.stops,this.canonicalChoropleth?.stepBaseColor,this.canonicalChoropleth?.noData],loadMapOwnedFeatureRuntime.loaded?.projectMapStyleOverrides(owned.styleOverrides),this._canonicalExternalLayers.map(({source:_source,...paint})=>paint)]),overlayPaint=loadMapOwnedFeatureRuntime.loaded?.overlayPaintText(owned.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],tokenValues=new Map;for(const token of tokens){const value=style.getPropertyValue(token).trim();if(values.push(token,value),tokenValues.set(token,value),tokens.size<512)for(const match of value.matchAll(/var\(\s*(--[\w-]+)/g))tokens.add(match[1])}const key=JSON.stringify(values);if(this.paintThemeKey===key)return!1;this.paintThemeKey=key,this.fillOpacity=finiteNumber(Number.parseFloat(tokenValues.get("--lr-map-choropleth-fill-opacity")),DEFAULT_FILL_OPACITY),this.hiddenOpacity=finiteRange(Number.parseFloat(tokenValues.get("--lr-map-hidden-category-opacity")),DEFAULT_HIDDEN_CATEGORY_OPACITY,0,1);const drawingPaint={};for(const[property2,token]of Object.entries(DRAWING_TOKENS)){const raw=tokenValues.get(token);if(raw)if(property2==="line-dasharray"){const dash=raw.split(/\s+/u).map(Number);dash.length===2&&dash.every(value=>Number.isFinite(value)&&value>0)&&(drawingPaint[property2]=dash)}else{const value=Number(raw);Number.isFinite(value)&&value>=0&&(drawingPaint[property2]=property2==="fill-opacity"?Math.min(1,value):value)}}return this.drawingPaint=drawingPaint,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||this.ownedFeatureInputRequested()?(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=this.fillOpacity;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}set styleLayers(_value){}get styleSources(){return this._styleSources}set styleSources(_value){}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()}applyMapInteractionState(current){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()}observeMapInteractionState(){if(this.stopObservingMapInteractionState(),!this.isConnected)return;this.interactionBlocked=this.mapInteractionBlocked();const current=()=>this.isConnected&&this.interactionObserver===observer,observer=new OwnedMutationObserver(this,()=>this.applyMapInteractionState(current));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.keyCode===229||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.pending))return;const report=()=>{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.schedule(report)}endPointerReports(emit=!0){this.pointerFrame.cancel(),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.isConnected?(this.drawingLoad==="failed"&&(this.drawingLoad=void 0),this.drawingRuntime()?.edit(snapshot)??!1):!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&&!(reason==="cancel"&&this.drawingSticky)&&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()},overlays:()=>this.ownedOverlayInput().overlays,rearm:mode=>{this.drawingResetting=!0;try{this.drawMode=mode}finally{this.drawingResetting=!1}},suppressClick:()=>{this.suppressDrawingClick=!0},syncCursor:()=>{this.syncMapCursor()},changed:()=>{this.drawingRevision+=1},invalidate:()=>{this.readiness.invalidate()},check:()=>{this.readiness.check()},fail:()=>{this.readiness.fail()},accentColor:()=>resolvedLayerColor(this,`var(${DRAWING_COLOR_TOKEN})`,"accent"),resolve:(value,property2)=>this.drawingPaint[property2]??this.resolveStyleOverride(value,property2)}}showDrawingError(error){this.drawingIssue=error??"inactive",this.announcements.announceAssertive(this.drawingErrorMessage())}drawingErrorMessage(){switch(this.drawingIssue){case"invalid-coordinate":return this.localize("mapDrawingInvalidCoordinate");case"duplicate-vertex":return this.localize("mapDrawingDuplicateVertex");case"vertex-limit":return this.localize("mapDrawingVertexLimit",void 0,{count:this.formatLocaleNumber(512)});case"empty":case"too-few-vertices":return this.localize("mapDrawingTooFewVertices",void 0,{count:this.formatLocaleNumber(this.drawMode==="polygon"?3:2)});case"inactive":return this.localize("mapDrawingUnavailable");default:return this.localize("mapDrawingInvalidGeometry")}}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{}}interactionPosition(point){const container=this.containerEl,rect=container.getBoundingClientRect();let x=mapOwnValue(point,"x"),y=mapOwnValue(point,"y");(!isFiniteCoordinate(x)||!isFiniteCoordinate(y))&&(x=container.clientWidth/2,y=container.clientHeight/2);const px=x,py=y;return{point:Object.freeze([px,py]),clientX:rect.left+container.clientLeft+px,clientY:rect.top+container.clientTop+py}}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,...this.interactionPosition(mapOwnValue(event,"point")),...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,...this.interactionPosition(mapOwnValue(event,"point")),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(build,owned,identities){if(identities.externalStyle!==this._styleGeneration&&(identities.externalStyle=this._styleGeneration,identities.external.clear()),!build)return{sources:[],layers:[],hits:new Map};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 build(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:this.hiddenOpacity})}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.dataLayerRuntimePending()||((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,images,styleOverrides}=this.ownedOverlayInput(),imageProvider=this.imageProvider,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&&this.sameOwnedOverlayInput(overlays,images,styleOverrides)&&imageProvider===this.imageProvider&&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(runtime?.buildMapExternalLayers,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(DEV_DIAGNOSTICS&&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||this.dataLayerRuntimeUnavailable()||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",this.fillOpacity),this.setMapPaint(fillLayerId,"fill-outline-color",outlineExpr??null)):this._map.addLayer({id:fillLayerId,type:"fill",source:sourceId,paint:{"fill-color":colorExpr,"fill-opacity":this.fillOpacity,...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=layerRuntime().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=layerRuntime().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":this.fillOpacity}}),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",this.fillOpacity),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=this.hiddenOpacity;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.isComposing||event.keyCode===229||event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected||this.mapInteractionBlocked())return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return hostAriaLabel(this)??normalizeLabel(this.label)??(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 elements=root.childElementCount?[...root.querySelectorAll(PEER_CHROME_SELECTOR)]:[];isElementNode(root)&&elements.unshift(root);for(const element of elements)for(const[selector,part]of PEER_CHROME_PARTS){if(!element.matches(selector))continue;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.scaleUnits()[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;const roots=new Set;let elementsChanged=!1,attributionChanged=!1;for(const record of records)if(container.contains(record.target)){if(record.type==="attributes"&&isElementNode(record.target)){if(record.attributeName==="class"&&!record.target.matches(".maplibregl-ctrl-geolocate, .maplibregl-ctrl-attrib"))continue;roots.add(record.target),record.target.matches(".maplibregl-ctrl-attrib")&&(attributionChanged=!0)}record.type==="characterData"&&roots.add(record.target.parentElement),record.type==="childList"&&isElementNode(record.target)&&record.target.matches(".maplibregl-ctrl-scale")&&roots.add(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"]')||roots.add(element)}}for(const root of roots)this.syncPeerChromeParts(root);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");const markerLabel=this._markerLabels.get(key);closeButton?.setAttribute("aria-label",markerLabel?this.localize("mapCloseWithLabel",void 0,{label:markerLabel}):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("mapMarker")),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"))}}formatDistance(metres){return metres<1e3?getNumberFormat(this.effectiveLocale,{style:"unit",unit:"meter",unitDisplay:"short",maximumFractionDigits:chartValueFractionDigits(metres,0,2)}).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:chartValueFractionDigits(squareMetres,0,2)}).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)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatLocaleNumber(this.legend.length===0?0:1),end:this.formatLocaleNumber(this.legend.length),total:this.formatLocaleNumber(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendRowContent(entry){const paint=sanitizeCssColor(entry.color);return html`${entry.icon?html`<span part="legend-swatch" data-pattern=${entry.pattern} data-icon="true" aria-hidden="true" inert style=${styleMap(paint?{color:paint}:{})} >${renderLegendIcon(entry.icon)}</span
|
|
14
|
+
</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.projectionGuard=new VetoWriteGuard,this.terrainGuard=new VetoWriteGuard,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.moveFrame=new OwnedFrame(this),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.anchorAvoidGap=0,this.anchorClosable=!1,this.anchorFill=!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._legendPlacement="bottom-start",this._legendClearance="row",this._legendFlow="row",this._legendOpen=!0,this.legendOpenGuard=new VetoWriteGuard,this.categoriesGuard=new VetoWriteGuard,this._hiddenCategories=EMPTY_HIDDEN_CATEGORIES,this._hiddenCategoriesRevision=0,this.markers=[],this.dataLayers=[],this.overlays={},this.images=[],this.styleOverrides=[],this.overlayGroups=new Map,this.overlayGroupSequence=0,this.overlayGroupRevision=0,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.dataLayerRuntimeFailed=!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.pickGuard=new VetoWriteGuard,this.keyboardActivation=!1,this.drawMode="none",this.drawingMeasurements=!1,this._drawingCompleteBehavior="clear",this._drawingFinishBehavior="clear",this.drawingSticky=!1,this.drawingRevision=0,this.drawingProgressAnnouncers=[0,1].map(()=>new Announcer({onFlush:text=>{this.announcements.announcePolite(text)}})),this.drawingProgressState=[void 0,void 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.openChildAnchors=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)&&DEV_DIAGNOSTICS&&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.detached=new DeferredTeardown(()=>this.releaseConnection()),this.mapUpdateActive=!1,this.actionBarFocusRepair=null,this.writingBusy=!1,this.authoredBusy=!1,this.fillOpacity=DEFAULT_FILL_OPACITY,this.hiddenOpacity=DEFAULT_HIDDEN_CATEGORY_OPACITY,this.drawingPaint={},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.pointerFrame=new OwnedFrame(this),this.pointerInside=!1,this.drawMapCenter=()=>{this.drawingController?.addCenter()},this.cancelMapPick=()=>{if(!this.pickMode||this.mapInteractionBlocked())return;const map=this._map,generation=this._connectGeneration,detail=Object.freeze({source:"control"});requestThenCommit({guard:this.pickGuard,requestDetail:detail,emitRequest:(proposal,init)=>this.emit("lr-map-pick-cancel-request",proposal,init),commit:()=>{!this.isConnected||this._connectGeneration!==generation||this._map!==map||this.mapInteractionBlocked()||(this.pickMode=!1,this.clearMapHover(),this.emit("lr-map-pick-cancel",detail))}})},this.pickMapCenter=()=>{const map=this._map,generation=this.interactionGeneration;if(!(!map||!this.pickMode||!this.mapInteractionAllowed()))try{const lngLat=mapCoordinates(map.getCenter());if(!lngLat||this._map!==map||generation!==this.interactionGeneration||!this.mapInteractionAllowed())return;const[x,y]=this.project(lngLat)??[];this.emit("lr-map-pick",Object.freeze({lngLat,...this.interactionPosition({x,y}),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"]'),repairControlFocusOnUpdate(this)}get projection(){return this._projection}set projection(value){markVetoGuardWrite(this.projectionGuard);const old=this._projection;this._projection=normalizeMapProjection(value),this.requestUpdate("projection",old)}get terrain(){return this._terrain}set terrain(value){markVetoGuardWrite(this.terrainGuard);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 DEV_DIAGNOSTICS&&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)}configurationMessage(issue){switch(issue){case"mapHashConflict":return this.localize("mapHashConflict");case"mapHashInvalid":return this.localize("mapHashInvalid");case"mapControlUnavailable":return this.localize("mapControlUnavailable");case"mapGeolocatePermissionDenied":return this.localize("mapGeolocatePermissionDenied");case"mapGeolocatePositionUnavailable":return this.localize("mapGeolocatePositionUnavailable");case"mapGeolocateTimeout":return this.localize("mapGeolocateTimeout");case"mapGeolocateError":return this.localize("mapGeolocateError");case"mapGeolocateOutOfBounds":return this.localize("mapGeolocateOutOfBounds")}}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.configurationMessage(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{}}syncControlsAvoidance(){!this.controlsAvoid?.length&&!this.controlsAvoidance||(this.controlsAvoidance??=new MapAnchorAvoidance({element:this,direction:()=>this.effectiveDirection,changed:()=>{this.applyControlsAvoid()}}),this.controlsAvoidance.observe(this.isConnected?this.controlsAvoid:void 0),this.applyControlsAvoid())}effectiveAnchorSafeArea(){const authored=this.anchorSafeArea,avoid=this.anchorAvoidance?.area,cached=this.mergedSafeArea;if(cached&&cached.authored===authored&&cached.avoid===avoid)return cached.value;const value=mergeSafeAreas(authored,avoid);return this.mergedSafeArea={authored,avoid,value},value}syncAnchorAvoidance(){!this.anchorAvoid?.length&&!this.anchorAvoidance||(this.anchorAvoidance??=new MapAnchorAvoidance({element:this,direction:()=>this.effectiveDirection,changed:()=>{this.scheduleAnchorSync()},gap:()=>Math.max(0,finiteNumber(this.anchorAvoidGap,0))}),this.anchorAvoidance.observe(this.isConnected?this.anchorAvoid:void 0))}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(!DEV_DIAGNOSTICS||!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)})||DEV_DIAGNOSTICS&&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 legendPlacement(){return this._legendPlacement}set legendPlacement(next){const normalized=LEGEND_PLACEMENT.normalizeReflected(this,"legend-placement",next),old=this._legendPlacement;old!==normalized&&(this._legendPlacement=normalized,this.requestUpdate("legendPlacement",old))}get legendClearance(){return this._legendClearance}set legendClearance(next){const normalized=LEGEND_CLEARANCE.normalizeReflected(this,"legend-clearance",next),old=this._legendClearance;old!==normalized&&(this._legendClearance=normalized,this.requestUpdate("legendClearance",old))}get legendFlow(){return this._legendFlow}set legendFlow(next){const normalized=LEGEND_FLOW.normalizeReflected(this,"legend-flow",next),old=this._legendFlow;old!==normalized&&(this._legendFlow=normalized,this.requestUpdate("legendFlow",old))}get legendOpen(){return this._legendOpen}set legendOpen(value){markVetoGuardWrite(this.legendOpenGuard);const previous=this._legendOpen;this._legendOpen=value,this.requestUpdate("legendOpen",previous)}get legendCollapsed(){return this.legendCollapsible&&!this.legendOpen}toggleLegendPanel(){if(!this.legendCollapsible||this.mapInteractionBlocked())return;const open=!this.legendOpen,connection=this._connectGeneration;requestThenCommit({guard:this.legendOpenGuard,requestDetail:{open},emitRequest:(detail,init)=>this.emit("lr-map-legend-panel-toggle-request",detail,init),commit:()=>{this.isConnected&&this._connectGeneration===connection&&this.legendCollapsible&&!this.mapInteractionBlocked()&&(this.legendOpen=open)}})}renderLegendDisclosure(){return this.legendCollapsible?html`<button part="legend-disclosure" type="button" aria-expanded=${this.legendOpen?"true":"false"} aria-controls="map-legend-list" ?disabled=${this.interactionBlocked} @click=${()=>this.toggleLegendPanel()} ><span part="legend-disclosure-icon" class="legend-disclosure-icon" aria-hidden="true" >${chevronIcon()}</span
|
|
15
|
+
><span>${this.localize("mapLegend")}</span></button>`:nothing}get hiddenCategories(){return this._hiddenCategories}set hiddenCategories(value){if(markVetoGuardWrite(this.categoriesGuard),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}set markersTruncated(_value){}setOverlayGroup(key,group,options={}){if(typeof key!="string"||!key||group===null||typeof group!="object")return!1;const order=Number.isFinite(options.order)?options.order:0,previous=this.overlayGroups.get(key);return previous?.group===group&&previous.order===order||(this.overlayGroups.set(key,{order,sequence:previous?.sequence??this.overlayGroupSequence++,group}),this.overlayGroupsChanged()),!0}removeOverlayGroup(key){return this.overlayGroups.delete(key)?(this.overlayGroupsChanged(),!0):!1}sameOwnedOverlayInput(overlays,images,styleOverrides){const current=this.ownedOverlayInput();return current.overlays===overlays&¤t.images===images&¤t.styleOverrides===styleOverrides}ownedFeatureInputRequested(){const{overlays,images,styleOverrides}=this.ownedOverlayInput();return ownedFeaturesRequested(overlays,images,styleOverrides)}overlayGroupsChanged(){this.overlayGroupRevision+=1,this.requestUpdate("overlays",OVERLAY_GROUP_CHANGE)}ownedOverlayInput(){const{overlays,images,styleOverrides}=this;if(!this.overlayGroups.size)return{overlays,images,styleOverrides};const key=[overlays,images,styleOverrides,this.overlayGroupRevision],cached=this.ownedInputCache;if(cached&&cached.key.every((value2,index)=>value2===key[index]))return cached.value;const groups=[...this.overlayGroups.values()].sort((a,b)=>a.order-b.order||a.sequence-b.sequence).map(entry=>entry.group),list=(base,pick)=>Object.freeze([...Array.isArray(base)?base:[],...groups.flatMap(group=>{const value2=pick(group);return Array.isArray(value2)?value2:[]})]),value=Object.freeze({overlays:Object.freeze({sources:list(overlays.sources,group=>group.sources),layers:list(overlays.layers,group=>group.layers)}),images:list(images,group=>group.images),styleOverrides:list(styleOverrides,group=>group.styleOverrides)});return this.ownedInputCache={key,value},value}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")}requestDataLayerRuntime(){if(this.dataLayerRuntimeLoad||this.dataLayerRuntimeFailed)return;const load=this.dataLayerRuntimeLoad=loadMapDataLayerRuntime().then(()=>{},()=>{this.dataLayerRuntimeFailed=!0,this.setDataLayerIssue(!0)}).then(()=>{this.dataLayerRuntimeLoad===load&&(this.dataLayerRuntimeLoad=void 0),dataLayersRequested(this.dataLayers)&&this.requestUpdate("dataLayers",EMPTY_CANONICAL_MAP_DATA_LAYERS),isSafeNonArrayObject(this.choropleth)&&this.requestUpdate("choropleth",null),this.isConnected&&this.tryConstructMap()});this.trackFeatureLoad(load)}dataLayerRuntimeUnavailable(){return this.dataLayerRuntimeFailed&&!loadMapDataLayerRuntime.loaded&&(dataLayersRequested(this.dataLayers)||isSafeNonArrayObject(this.choropleth))}dataLayerRuntimePending(){return this.canonicalDataLayers,this.canonicalChoropleth,this.dataLayerRuntimeLoad!==void 0}async getUpdateComplete(){let complete=await super.getUpdateComplete();for(;this.dataLayerRuntimeLoad;)await this.dataLayerRuntimeLoad,complete=await super.getUpdateComplete();return complete}get canonicalChoropleth(){const source=this.choropleth;if(Object.is(source,this._canonicalChoroplethSource))return this._canonicalChoropleth;const runtime=loadMapDataLayerRuntime.loaded;if(!runtime&&isSafeNonArrayObject(source)){this.requestDataLayerRuntime();return}return this._canonicalChoroplethSource=source,this._canonicalChoropleth=runtime?.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;const runtime=loadMapDataLayerRuntime.loaded;if(!runtime&&dataLayersRequested(source))return this.requestDataLayerRuntime(),EMPTY_CANONICAL_MAP_DATA_LAYERS;this._canonicalDataLayersSource=source,this._canonicalDataLayersBase=base,this._canonicalDataLayersOrigin=origin;const model=runtime?.projectMapDataLayers(source,base,origin)??{ok:!0,geojson:EMPTY_CANONICAL_MAP_DATA_LAYERS,external:[]};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 pickMode(){return this._pickMode}set pickMode(value){markVetoGuardWrite(this.pickGuard);const previous=this._pickMode;this._pickMode=value,this.requestUpdate("pickMode",previous)}get drawingCompleteBehavior(){return this._drawingCompleteBehavior}set drawingCompleteBehavior(next){const normalized=DRAWING_COMPLETE_BEHAVIOR.normalizeReflected(this,"drawing-complete-behavior",next),old=this._drawingCompleteBehavior;old!==normalized&&(this._drawingCompleteBehavior=normalized,this.requestUpdate("drawingCompleteBehavior",old))}get drawingFinishBehavior(){return this._drawingFinishBehavior}set drawingFinishBehavior(next){const normalized=DRAWING_FINISH_BEHAVIOR.normalizeReflected(this,"drawing-finish-behavior",next),old=this._drawingFinishBehavior;old!==normalized&&(this._drawingFinishBehavior=normalized,this.requestUpdate("drawingFinishBehavior",old))}get drawingPending(){return this.drawingController?.pending===!0}get drawingWork(){return this.drawingController?.work??NO_DRAWING_WORK}get map(){return this._map}set map(_value){}whenStyleReady(){return this.readiness.whenStyleReady()}whenControlsReady(){return this.controlsReadiness.whenReady()}whenIdle(){return this.readiness.whenIdle()}pushGeoJson(source,resolvedSourceId,geojson,projection){const previous=this._appliedGeoJson.get(resolvedSourceId);if(previous===projection)return;const diff=typeof source.updateData=="function"&&previous!==void 0?layerRuntime().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]),DEV_DIAGNOSTICS&&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,()=>{DEV_DIAGNOSTICS&&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 DEV_DIAGNOSTICS&&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)}}return retired&&reason!=="disconnect"&&this.isConnected&&this.emit("lr-map-camera-interrupt",Object.freeze({reason})),this.isConnected&&(!this.cameraSession||this.cameraSession===owner&&owner.revision===revision&&owner.pendingAction===void 0)}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:(DEV_DIAGNOSTICS&&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.isConnected?this._map:void 0;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.isConnected?this._map:void 0;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}}scaleUnits(){return{ft:this.localize("mapScaleFeet"),m:this.localize("mapScaleMeters"),km:this.localize("mapScaleKilometers"),mi:this.localize("mapScaleMiles"),nm:this.localize("mapScaleNauticalMiles")}}controlLocale(){const units=this.scaleUnits();for(const native of["ft","m","km","mi","nm"])this.scaleLabels.set(native,native),this.scaleLabels.set(units[native],native);return{"GeolocateControl.FindMyLocation":this.localize("mapGeolocateFindLocation"),"GeolocateControl.LocationNotAvailable":this.localize("mapGeolocateUnavailable"),"ScaleControl.Feet":escapeHtml(units.ft),"ScaleControl.Meters":escapeHtml(units.m),"ScaleControl.Kilometers":escapeHtml(units.km),"ScaleControl.Miles":escapeHtml(units.mi),"ScaleControl.NauticalMiles":escapeHtml(units.nm)}}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=isSafeNonArrayObject(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",detail=Object.freeze({projection,source:"control"});requestThenCommit({guard:this.projectionGuard,requestDetail:detail,emitRequest:(proposal,init)=>this.emit("lr-map-projection-change-request",proposal,init),commit:()=>{!current()||this.mapInteractionBlocked()||(this.projection=projection,this.emit("lr-map-projection-change",detail))}})}else{const terrain=event.action.pressed===!0?null:event.action.terrain;if(terrain===void 0)return;const detail=Object.freeze({terrain,source:"control"});requestThenCommit({guard:this.terrainGuard,requestDetail:detail,emitRequest:(proposal,init)=>this.emit("lr-map-terrain-change-request",proposal,init),commit:()=>{!current()||this.mapInteractionBlocked()||(this.terrain=terrain,this.emit("lr-map-terrain-change",detail))}})}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.configurationMessage(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"&&code!=="busy"&&(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.openChildAnchors.size===0)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),anchor.open&&this.childAnchorSet.has(anchor)?this.openChildAnchors.add(anchor):this.openChildAnchors.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,mapSafeArea:()=>this.effectiveAnchorSafeArea()}}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.effectiveAnchorSafeArea(),closable:()=>this.anchorClosable,pending:()=>this.isUpdatePending,requestClose:detail=>!this.emit("lr-map-anchor-close-request",detail,{cancelable:!0}).defaultPrevented,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.pending)return;const view=ownerWindow(this);if(!view||typeof view.requestAnimationFrame!="function"){this.reportMove(map);return}this.moveFrame.schedule(()=>{this.reportMove(map)})}flushMoveReport(map){this.moveFrame.pending&&(this.cancelMoveReport(),this.reportMove(map))}cancelMoveReport(){this.moveFrame.pending&&this.moveFrame.cancel()}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(){if(super.connectedCallback(),this.detached.cancel()){this.resumeAfterMove();return}const ownerWindow2=this.ownerDocument.defaultView;if(ownerWindow2)for(const announcer of this.drawingProgressAnnouncers)announcer.setTimerHost(ownerWindow2);const generation=++this._connectGeneration;this.observeMapInteractionState(),this.syncAnchorAvoidance(),this.syncControlsAvoidance(),this.unregisterCameraSession?.(),this.unregisterCameraSession=registerMapCameraSession(this,{acquire:callbacks=>this.acquireCameraSession(callbacks)}),this.unregisterCustomLayers?.(),this.unregisterCustomLayers=registerMapCustomLayers(this,{acquire:callbacks=>this.acquireCustomLayer(callbacks)}),this.failure=void 0,this.loading=!0,this._webglReady=!1,this.connectGeographicScene(),this.readiness.reset(),this.controlsReadiness.reset(),this.hashRuntimeFailed=!1,this.dataLayerRuntimeFailed=!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=activeElementIn(this.shadowRoot)?.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),(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)}})()}resumeAfterMove(){const blocked=this.interactionBlocked;this.observeMapInteractionState();const observer=this.interactionObserver;this.interactionBlocked!==blocked&&this.applyMapInteractionState(()=>this.isConnected&&this.interactionObserver===observer),this.canvasAllocationController&&(this.releaseCanvasAllocation(),this.syncCanvasAllocation())}disconnectedCallback(){super.disconnectedCallback(),this.detached.schedule()}releaseConnection(){this.anchorAvoidance?.disconnect(),this.controlsAvoidance?.disconnect();for(const announcer of this.drawingProgressAnnouncers)announcer.cancel();this.drawingProgressState=[void 0,void 0],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(this.detached.flush(),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();const ownerWindow2=this.ownerDocument.defaultView;if(ownerWindow2)for(const announcer of this.drawingProgressAnnouncers)announcer.setTimerHost(ownerWindow2);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||this.dataLayerRuntimePending())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))}}(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);const contextUpdate=args[0]===LYRA_CONTEXT_UPDATE;if(valueChanged&&(args[0]===void 0||contextUpdate||["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||contextUpdate||["label","lang","locale","strings","markers","legend","legendGradient","hasLegendSlot","hasLegendStartSlot","choropleth","choroplethLegend"].includes(String(args[0])))&&(this.semanticsStale=!0),this.isUpdatePending&&(args[0]===void 0||contextUpdate||["label","lang","locale","strings","markers"].includes(String(args[0])))&&(this.markerSemanticsStale=!0)}performUpdate(){this.mapUpdateActive=!0;try{super.performUpdate()}finally{this.mapUpdateActive=!1}}captureActionBarFocus(){const bar=activeElementIn(this.shadowRoot)?.closest('[part="pick-controls"], [part="drawing-controls"]');this.actionBarFocusRepair=bar?captureComposedFocusRepair(bar,bar):null}repairActionBarFocus(){const repair=this.actionBarFocusRepair;if(this.actionBarFocusRepair=null,!repair||repair.activeElement.isConnected&&!repair.activeElement.matches(":disabled"))return;const survivors=this.renderRoot.querySelectorAll('[part="pick-controls"] button, [part="drawing-controls"] button'),canvas=this._map?.getCanvas?.(),activate=this.renderRoot.querySelector('[part="initialization-activate"]');applyComposedFocusRepair(repair,[...survivors,canvas,activate,this.containerEl])}announceDrawingProgress(){const drawing=this.drawingController,shown=(this.drawMode==="line"||this.drawMode==="polygon"||drawing?.editing===!0)&&!this.pickMode&&!this.failure&&!this.loading,vertices=drawing?.snapshot?.vertices??[],next=shown?[String(vertices.length),JSON.stringify(vertices)]:[void 0,void 0],[count,signature]=this.drawingProgressState;if(this.drawingProgressState=next,!shown)return;count!==void 0&&count!==next[0]&&this.drawingProgressAnnouncers[0].announce(this.localize("mapDrawingVertices",void 0,{count:this.formatLocaleNumber(vertices.length)}));const summary=this.drawingMeasurements?this.drawingSummary(drawing?.snapshot):void 0;summary&&signature!==void 0&&signature!==next[1]&&this.drawingProgressAnnouncers[1].announce(summary)}updated(changed){super.updated(changed),this.repairActionBarFocus(),this.announceDrawingProgress(),changed.has("failure")&&this.syncGeographicSceneStatus(),this.sceneRepairFocus&&(this.sceneRepairFocus=!1,this.shadowRoot?.querySelector('[part="scene-toggle"]')?.focus({preventScroll:!0})),this.cameraUpdatePending=!1;const busy=String(this.loading||!this._map&&!this.failure&&!this.awaitingActivation);if(!this.authoredBusy&&this.getAttribute("aria-busy")!==busy){this.writingBusy=!0;try{this.setAttribute("aria-busy",busy)}finally{this.writingBusy=!1}}if(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(),changed.has("anchorAvoid")?this.syncAnchorAvoidance():(changed.has("dir")||changed.has("anchorAvoidGap"))&&this.anchorAvoidance&&this.anchorAvoidance.refresh(),changed.has("controlsAvoid")?this.syncControlsAvoidance():changed.has("dir")&&this.controlsAvoidance&&this.controlsAvoidance.refresh(),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)})}static get observedAttributes(){return[...super.observedAttributes,"aria-busy"]}attributeChangedCallback(name,previous,value){super.attributeChangedCallback(name,previous,value),name==="aria-busy"&&!this.writingBusy&&(this.authoredBusy=value!==null,value===null&&super.requestUpdate())}willUpdate(changed){if(this.drawingConfigApplying=this.drawingConfigRevision,this.cameraSessionConfigurationApplying=this.cameraSessionConfigurationRevision,super.willUpdate(changed),(this.anchorLngLat!=null||this.openChildAnchors.size>0)&&this.effectiveDirection,this.refreshingGeoJson=this.geoJsonRefreshRequested,this.geoJsonRefreshRequested=!1,this.captureActionBarFocus(),this.refreshingGeoJson){const choropleth=this.canonicalChoropleth;choropleth&&(this._canonicalChoropleth={...choropleth,geojsonProjection:layerRuntime().projectAdmittedGeoJson(choropleth.geojson,!0)}),this._canonicalDataLayers=this.canonicalDataLayers.map(layer=>({...layer,geojsonProjection:layerRuntime().projectAdmittedGeoJson(layer.geojson,!0)}))}(changed.has("legendGradient")||changed.has("dataLayers"))&&(this.legendIsLine=this.legendDescribesLine());const legendSource=this.choroplethLegend?this.canonicalChoropleth:void 0,locale=this.effectiveLocale,noData=legendSource?this.localize("noData"):"";(legendSource!==this.legendSource||locale!==this.legendLocale||noData!==this.legendNoData)&&(this.legendSource=legendSource,this.legendLocale=locale,this.legendNoData=noData,this.derivedLegend=legendSource?buildDerivedChoroplethLegend(legendSource,value=>this.formatLocaleNumber(value),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 owned=this.ownedOverlayInput(),sources=[this.dataLayers,this.choropleth,owned.styleOverrides,owned.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,...Object.values(DRAWING_TOKENS)]),inputs=JSON.stringify([this.canonicalDataLayers.map(({geojson:_geojson,geojsonProjection:_projection,...paint})=>paint),[this.canonicalChoropleth?.stops,this.canonicalChoropleth?.stepBaseColor,this.canonicalChoropleth?.noData],loadMapOwnedFeatureRuntime.loaded?.projectMapStyleOverrides(owned.styleOverrides),this._canonicalExternalLayers.map(({source:_source,...paint})=>paint)]),overlayPaint=loadMapOwnedFeatureRuntime.loaded?.overlayPaintText(owned.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],tokenValues=new Map;for(const token of tokens){const value=style.getPropertyValue(token).trim();if(values.push(token,value),tokenValues.set(token,value),tokens.size<512)for(const match of value.matchAll(/var\(\s*(--[\w-]+)/g))tokens.add(match[1])}const key=JSON.stringify(values);if(this.paintThemeKey===key)return!1;this.paintThemeKey=key,this.fillOpacity=finiteNumber(Number.parseFloat(tokenValues.get("--lr-map-choropleth-fill-opacity")),DEFAULT_FILL_OPACITY),this.hiddenOpacity=finiteRange(Number.parseFloat(tokenValues.get("--lr-map-hidden-category-opacity")),DEFAULT_HIDDEN_CATEGORY_OPACITY,0,1);const drawingPaint={};for(const[property2,token]of Object.entries(DRAWING_TOKENS)){const raw=tokenValues.get(token);if(raw)if(property2==="line-dasharray"){const dash=raw.split(/\s+/u).map(Number);dash.length===2&&dash.every(value=>Number.isFinite(value)&&value>0)&&(drawingPaint[property2]=dash)}else{const value=Number(raw);Number.isFinite(value)&&value>=0&&(drawingPaint[property2]=property2==="fill-opacity"?Math.min(1,value):value)}}return this.drawingPaint=drawingPaint,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||this.ownedFeatureInputRequested()?(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=this.fillOpacity;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}set styleLayers(_value){}get styleSources(){return this._styleSources}set styleSources(_value){}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()}applyMapInteractionState(current){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()}observeMapInteractionState(){if(this.stopObservingMapInteractionState(),!this.isConnected)return;this.interactionBlocked=this.mapInteractionBlocked();const current=()=>this.isConnected&&this.interactionObserver===observer,observer=new OwnedMutationObserver(this,()=>this.applyMapInteractionState(current));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.keyCode===229||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.pending))return;const report=()=>{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.schedule(report)}endPointerReports(emit=!0){this.pointerFrame.cancel(),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.isConnected?(this.drawingLoad==="failed"&&(this.drawingLoad=void 0),this.drawingRuntime()?.edit(snapshot)??!1):!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&&!(reason==="cancel"&&this.drawingSticky)&&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()},overlays:()=>this.ownedOverlayInput().overlays,rearm:mode=>{this.drawingResetting=!0;try{this.drawMode=mode}finally{this.drawingResetting=!1}},suppressClick:()=>{this.suppressDrawingClick=!0},syncCursor:()=>{this.syncMapCursor()},changed:()=>{this.drawingRevision+=1},invalidate:()=>{this.readiness.invalidate()},check:()=>{this.readiness.check()},fail:()=>{this.readiness.fail()},accentColor:()=>resolvedLayerColor(this,`var(${DRAWING_COLOR_TOKEN})`,"accent"),resolve:(value,property2)=>this.drawingPaint[property2]??this.resolveStyleOverride(value,property2)}}showDrawingError(error){this.drawingIssue=error??"inactive",this.announcements.announceAssertive(this.drawingErrorMessage())}drawingErrorMessage(){switch(this.drawingIssue){case"invalid-coordinate":return this.localize("mapDrawingInvalidCoordinate");case"duplicate-vertex":return this.localize("mapDrawingDuplicateVertex");case"vertex-limit":return this.localize("mapDrawingVertexLimit",void 0,{count:this.formatLocaleNumber(512)});case"empty":case"too-few-vertices":return this.localize("mapDrawingTooFewVertices",void 0,{count:this.formatLocaleNumber(this.drawMode==="polygon"?3:2)});case"inactive":return this.localize("mapDrawingUnavailable");default:return this.localize("mapDrawingInvalidGeometry")}}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{}}interactionPosition(point){const container=this.containerEl,rect=container.getBoundingClientRect();let x=mapOwnValue(point,"x"),y=mapOwnValue(point,"y");(!isFiniteCoordinate(x)||!isFiniteCoordinate(y))&&(x=container.clientWidth/2,y=container.clientHeight/2);const px=x,py=y;return{point:Object.freeze([px,py]),clientX:rect.left+container.clientLeft+px,clientY:rect.top+container.clientTop+py}}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,...this.interactionPosition(mapOwnValue(event,"point")),...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,...this.interactionPosition(mapOwnValue(event,"point")),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(build,owned,identities){if(identities.externalStyle!==this._styleGeneration&&(identities.externalStyle=this._styleGeneration,identities.external.clear()),!build)return{sources:[],layers:[],hits:new Map};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 build(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:this.hiddenOpacity})}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.dataLayerRuntimePending()||((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,images,styleOverrides}=this.ownedOverlayInput(),imageProvider=this.imageProvider,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&&this.sameOwnedOverlayInput(overlays,images,styleOverrides)&&imageProvider===this.imageProvider&&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(runtime?.buildMapExternalLayers,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(DEV_DIAGNOSTICS&&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||this.dataLayerRuntimeUnavailable()||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",this.fillOpacity),this.setMapPaint(fillLayerId,"fill-outline-color",outlineExpr??null)):this._map.addLayer({id:fillLayerId,type:"fill",source:sourceId,paint:{"fill-color":colorExpr,"fill-opacity":this.fillOpacity,...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=layerRuntime().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=layerRuntime().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":this.fillOpacity}}),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",this.fillOpacity),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=this.hiddenOpacity;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.isComposing||event.keyCode===229||event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected||this.mapInteractionBlocked())return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return hostAriaLabel(this)??normalizeLabel(this.label)??(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);for(const side of["left","right"]){const corner=container.querySelector(`.maplibregl-ctrl-${edge}-${side}`),cornerName=`--_lr-map-controls-${edge}-${side}`,cornerValue=`${corner?this.cornerContentHeight(corner):0}px`;base&&base.style.getPropertyValue(cornerName)!==cornerValue&&base.style.setProperty(cornerName,cornerValue)}}}}cornerContentHeight(corner){const view=corner.ownerDocument.defaultView;let start=1/0,end=-1/0;for(const node of corner.children){const child=node;if(!view||child.offsetParent!==corner)continue;const style=view.getComputedStyle(child);start=Math.min(start,child.offsetTop-(Number.parseFloat(style.marginTop)||0)),end=Math.max(end,child.offsetTop+child.offsetHeight+(Number.parseFloat(style.marginBottom)||0))}return end>start?Math.round(end-start):0}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const elements=root.childElementCount?[...root.querySelectorAll(PEER_CHROME_SELECTOR)]:[];isElementNode(root)&&elements.unshift(root);for(const element of elements)for(const[selector,part]of PEER_CHROME_PARTS){if(!element.matches(selector))continue;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.scaleUnits()[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,{box:"border-box"})}this.measurePeerControlInsets(container);const observer=new MutationObserverCtor(records=>{if(!this.isConnected||this.containerEl!==container||this.peerChromeObserver!==observer)return;const roots=new Set;let elementsChanged=!1,attributionChanged=!1;for(const record of records)if(container.contains(record.target)){if(record.type==="attributes"&&isElementNode(record.target)){if(record.attributeName==="class"&&!record.target.matches(".maplibregl-ctrl-geolocate, .maplibregl-ctrl-attrib"))continue;roots.add(record.target),record.target.matches(".maplibregl-ctrl-attrib")&&(attributionChanged=!0)}record.type==="characterData"&&roots.add(record.target.parentElement),record.type==="childList"&&isElementNode(record.target)&&record.target.matches(".maplibregl-ctrl-scale")&&roots.add(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"]')||roots.add(element)}}for(const root of roots)this.syncPeerChromeParts(root);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");const markerLabel=this._markerLabels.get(key);closeButton?.setAttribute("aria-label",markerLabel?this.localize("mapCloseWithLabel",void 0,{label:markerLabel}):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("mapMarker")),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"))}}formatDistance(metres){return metres<1e3?getNumberFormat(this.effectiveLocale,{style:"unit",unit:"meter",unitDisplay:"short",maximumFractionDigits:chartValueFractionDigits(metres,0,2)}).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:chartValueFractionDigits(squareMetres,0,2)}).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)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatLocaleNumber(this.legend.length===0?0:1),end:this.formatLocaleNumber(this.legend.length),total:this.formatLocaleNumber(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendRowContent(entry){const paint=sanitizeCssColor(entry.color);return html`${entry.icon?html`<span part="legend-swatch" data-pattern=${entry.pattern} data-icon="true" aria-hidden="true" inert style=${styleMap(paint?{color:paint}:{})} >${renderLegendIcon(entry.icon)}</span
|
|
16
16
|
>`:html`<span part="legend-swatch" data-pattern=${entry.pattern} aria-hidden="true" inert style=${styleMap(paint?{backgroundColor:paint}:{})} ></span>`}
|
|
17
17
|
<span>${entry.label}</span>`}toggleLegendCategory(entry,index){const value=entry.value,connection=this._connectGeneration,current=()=>this.isConnected&&this._connectGeneration===connection&&this.legendInteractive&&this.legend[index]===entry&&!this.mapInteractionBlocked();if(value===void 0||!current())return;const hidden=this.hiddenCategories,wasHidden=hidden.includes(value),next=wasHidden?hidden.filter(key=>key!==value):[...hidden,value];requestThenCommit({guard:this.categoriesGuard,requestDetail:{value,visible:wasHidden,hiddenCategories:[...next]},emitRequest:(detail,init)=>this.emit("lr-map-legend-toggle-request",detail,init),commit:()=>{current()&&(this.hiddenCategories=next,this.announceLegendVisibility(entry,wasHidden))}})}announceLegendVisibility(entry,nowVisible){this.announcements.announcePolite(this.localize(nowVisible?"legendTypeShown":"legendTypeHidden",void 0,{label:entry.label}))}renderLegendRow(entry,index){const key=entry.value,interactive=this.legendInteractive&&key!==void 0,visible=key===void 0||!this.hiddenCategories.includes(key),checkbox=this.legendControlRole==="checkbox";return html`<div class="legend-row" role="listitem" aria-posinset=${String(index+1)} aria-setsize=${String(this.legendProjection.inputCount)} >
|
|
18
18
|
${interactive?html`<button part=${visible?"legend-toggle":"legend-toggle legend-toggle-hidden"} type="button" role=${checkbox?"checkbox":nothing} aria-pressed=${checkbox?nothing:visible?"true":"false"} aria-checked=${checkbox?visible?"true":"false":nothing} ?disabled=${this.interactionBlocked} @click=${()=>this.toggleLegendCategory(entry,index)} >${this.renderLegendRowContent(entry)}</button>`:this.renderLegendRowContent(entry)}
|
|
@@ -26,7 +26,7 @@ import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-ca
|
|
|
26
26
|
<span part="legend-hi">${this.legendGradientHiLabel??format(hi[0])}</span>
|
|
27
27
|
</div>`}renderDerivedLegendRows(){const rows=this.derivedLegend.rows;return rows.length===0?nothing:html`<div class="legend-list" part="legend-derived" role="list" ?hidden=${this.legendCollapsed}>
|
|
28
28
|
${rows.map((entry,index)=>html`<div class="legend-row" role="listitem" aria-posinset=${String(index+1)} aria-setsize=${String(rows.length)} >${this.renderLegendRowContent(entry)}</div>`)}
|
|
29
|
-
</div>`}render(){const drawing=this.drawingController,placeholder=!this.failure&&!this.loading&&!this._map,initializationControls=placeholder?[...normalizeMapControlOptions(this.controls).controls.values()].sort((a,b)=>a.order-b.order):!this.failure&&!this.loading&&this._map?this.controlOutlines:[],outlines=html`<div class="initialization-controls" part="initialization-controls controls" aria-hidden="true" inert>
|
|
29
|
+
</div>`}applyControlsAvoid(){const base=this.shadowRoot?.querySelector('[part="base"]');if(!base)return;const area=this.controlsAvoidance?.area;for(const[key,edge]of[["blockStart","block-start"],["blockEnd","block-end"],["inlineStart","inline-start"],["inlineEnd","inline-end"]]){const name=`--_lr-map-controls-inset-${edge}`,value=area?.[key];value?base.style.setProperty(name,`calc(var(--lr-map-controls-inset-${edge}, 0px) + ${value}px)`):base.style.removeProperty(name)}}render(){const drawing=this.drawingController,placeholder=!this.failure&&!this.loading&&!this._map,initializationControls=placeholder?[...normalizeMapControlOptions(this.controls).controls.values()].sort((a,b)=>a.order-b.order):!this.failure&&!this.loading&&this._map?this.controlOutlines:[],outlines=html`<div class="initialization-controls" part="initialization-controls controls" aria-hidden="true" inert>
|
|
30
30
|
${["top","bottom"].map(row=>html`<div class="initialization-row initialization-row-${row}" part=${row==="top"?"controls-top":"controls-bottom"}>
|
|
31
31
|
${["left","right"].map(side=>html`<div class="initialization-corner initialization-corner-${side}" part=${{"top-left":"initialization-corner controls-top-left","top-right":"initialization-corner controls-top-right","bottom-left":"initialization-corner controls-bottom-left","bottom-right":"initialization-corner controls-bottom-right"}[`${row}-${side}`]}>
|
|
32
32
|
${initializationControls.filter(control=>control.position===`${row}-${side}`).map(control=>html`<span part=${{navigation:"initialization-control initialization-navigation",scale:"initialization-control initialization-scale",geolocate:"initialization-control initialization-geolocate",attribution:"initialization-control initialization-attribution",globe:"initialization-control initialization-globe",terrain:"initialization-control initialization-terrain"}[control.kind]} data-control=${control.kind}></span>`)}
|
|
@@ -69,7 +69,7 @@ import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-ca
|
|
|
69
69
|
<div class="anchor-boundary" aria-hidden="true"></div>
|
|
70
70
|
<div part="anchor" hidden @focusin=${this.onAnchorFocus}><div part="anchor-body"><slot name="anchor" @slotchange=${this.onAnchorSlotChange}></slot></div>${this.anchorClosable?html`<button type="button" part="anchor-close" @click=${()=>{this.anchorController?.close("close-button")}}>${this.localize("close")}</button>`:nothing}</div>
|
|
71
71
|
${this.anchorSlotPresence.has("anchors")?html`<slot name="anchors" @slotchange=${this.onAnchorsSlotChange}></slot>`:nothing}
|
|
72
|
-
${this.legend.length||this.legendProjection.truncated||this.legendGradient.length||this.hasDerivedLegend()||this.hasLegendSlot||this.hasLegendStartSlot||this.probeLegendSlot("legend")||this.probeLegendSlot("legend-start")?html`<div part="legend" id="map-legend" role="group" aria-label=${this.localize("mapLegend")} aria-controls=${this.failure||this.loading?nothing:"map-container"} data-truncated=${String(this.legendProjection.truncated)} data-placement=${this.legendPlacement} >
|
|
72
|
+
${this.legend.length||this.legendProjection.truncated||this.legendGradient.length||this.hasDerivedLegend()||this.hasLegendSlot||this.hasLegendStartSlot||this.probeLegendSlot("legend")||this.probeLegendSlot("legend-start")?html`<div part="legend" id="map-legend" role="group" aria-label=${this.localize("mapLegend")} aria-controls=${this.failure||this.loading?nothing:"map-container"} data-truncated=${String(this.legendProjection.truncated)} data-placement=${this.legendPlacement} data-clearance=${this.legendClearance} >
|
|
73
73
|
<slot name="legend-start" @slotchange=${this.onLegendSlotChange}></slot>
|
|
74
74
|
<div class="glass-scroll-layer" aria-hidden="true"></div>
|
|
75
75
|
${this.renderLegendDisclosure()}
|
|
@@ -84,4 +84,4 @@ import{__decorate}from"tslib";import{MapCanvasAllocationController}from"./map-ca
|
|
|
84
84
|
<slot name="legend" ?hidden=${this.legendCollapsed} @slotchange=${this.onLegendSlotChange}></slot>
|
|
85
85
|
</div>`:nothing}
|
|
86
86
|
</div>
|
|
87
|
-
`}}__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({converter:blankNumberConverter(2)})],LyraMap.prototype,"zoom",void 0),__decorate([property({converter:blankNumberConverter(void 0),attribute:"min-zoom"})],LyraMap.prototype,"minZoom",void 0),__decorate([property({converter:blankNumberConverter(void 0),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({attribute:!1})],LyraMap.prototype,"anchorAvoid",void 0),__decorate([property({type:Boolean,attribute:"anchor-closable"})],LyraMap.prototype,"anchorClosable",void 0),__decorate([property()],LyraMap.prototype,"initialization",void 0),__decorate([property({converter:blankNumberConverter(void 0),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:!1})],LyraMap.prototype,"legendGradient",null),__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({converter:LEGEND_PLACEMENT,attribute:"legend-placement",reflect:!0})],LyraMap.prototype,"legendPlacement",null),__decorate([property({attribute:"legend-open",reflect:!0,converter:trueDefaultBooleanConverter})],LyraMap.prototype,"legendOpen",null),__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",null),__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([property({attribute:"drawing-complete-behavior",converter:DRAWING_COMPLETE_BEHAVIOR,reflect:!0})],LyraMap.prototype,"drawingCompleteBehavior",null),__decorate([property({type:Boolean,attribute:"drawing-sticky",reflect:!0})],LyraMap.prototype,"drawingSticky",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};
|
|
87
|
+
`}}__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({converter:blankNumberConverter(2)})],LyraMap.prototype,"zoom",void 0),__decorate([property({converter:blankNumberConverter(void 0),attribute:"min-zoom"})],LyraMap.prototype,"minZoom",void 0),__decorate([property({converter:blankNumberConverter(void 0),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({attribute:!1})],LyraMap.prototype,"anchorAvoid",void 0),__decorate([property({converter:blankNumberConverter(0),attribute:"anchor-avoid-gap"})],LyraMap.prototype,"anchorAvoidGap",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"controlsAvoid",void 0),__decorate([property({type:Boolean,attribute:"anchor-closable"})],LyraMap.prototype,"anchorClosable",void 0),__decorate([property({type:Boolean,attribute:"anchor-fill",reflect:!0})],LyraMap.prototype,"anchorFill",void 0),__decorate([property()],LyraMap.prototype,"initialization",void 0),__decorate([property({converter:blankNumberConverter(void 0),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:!1})],LyraMap.prototype,"legendGradient",null),__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({converter:LEGEND_PLACEMENT,attribute:"legend-placement",reflect:!0})],LyraMap.prototype,"legendPlacement",null),__decorate([property({converter:LEGEND_CLEARANCE,attribute:"legend-clearance",reflect:!0})],LyraMap.prototype,"legendClearance",null),__decorate([property({converter:LEGEND_FLOW,attribute:"legend-flow",reflect:!0})],LyraMap.prototype,"legendFlow",null),__decorate([property({attribute:"legend-open",reflect:!0,converter:trueDefaultBooleanConverter})],LyraMap.prototype,"legendOpen",null),__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",null),__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([property({attribute:"drawing-complete-behavior",converter:DRAWING_COMPLETE_BEHAVIOR,reflect:!0})],LyraMap.prototype,"drawingCompleteBehavior",null),__decorate([property({attribute:"drawing-finish-behavior",converter:DRAWING_FINISH_BEHAVIOR,reflect:!0})],LyraMap.prototype,"drawingFinishBehavior",null),__decorate([property({type:Boolean,attribute:"drawing-sticky",reflect:!0})],LyraMap.prototype,"drawingSticky",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};
|