@aceshooting/lyra-ui 12.0.0 → 12.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/autoloader.js +1 -1
  4. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
  5. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  6. package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
  7. package/dist/components/charts/chart/histogram-bin.js +1 -1
  8. package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
  9. package/dist/components/charts/chart/lite-chart.class.js +6 -6
  10. package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
  11. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  12. package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
  13. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  14. package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
  15. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  16. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  17. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
  18. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  19. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  20. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
  21. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  22. package/dist/components/data/heatmap/heatmap.class.d.ts +4 -1
  23. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  24. package/dist/components/data/table/table.class.d.ts +18 -4
  25. package/dist/components/data/table/table.class.js +2 -2
  26. package/dist/components/data/table/table.styles.js +2 -1
  27. package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
  28. package/dist/components/data/timeline/timeline-cluster.js +1 -0
  29. package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
  30. package/dist/components/data/timeline/timeline-item.class.js +13 -2
  31. package/dist/components/data/timeline/timeline-item.styles.js +65 -0
  32. package/dist/components/data/timeline/timeline.class.d.ts +83 -27
  33. package/dist/components/data/timeline/timeline.class.js +3 -3
  34. package/dist/components/data/timeline/timeline.d.ts +1 -0
  35. package/dist/components/data/timeline/timeline.js +1 -1
  36. package/dist/components/data/timeline/timeline.styles.js +14 -0
  37. package/dist/components/forms/button/button.class.js +1 -1
  38. package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
  39. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  40. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
  41. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  42. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  43. package/dist/components/forms/color-picker/color-picker.class.js +1 -1
  44. package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
  45. package/dist/components/forms/combobox/combobox.class.js +3 -2
  46. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  47. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  48. package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
  49. package/dist/components/forms/input/native-time-input.class.js +1 -1
  50. package/dist/components/forms/input/time-input-shared.d.ts +2 -1
  51. package/dist/components/forms/input/time-input.class.js +1 -1
  52. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
  53. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  54. package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
  55. package/dist/components/forms/radio/radio-button.styles.js +1 -1
  56. package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
  57. package/dist/components/forms/radio/radio-group.class.js +1 -1
  58. package/dist/components/forms/radio/radio.class.d.ts +0 -1
  59. package/dist/components/forms/radio/radio.class.js +1 -1
  60. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
  61. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  62. package/dist/components/forms/select/select.class.d.ts +0 -1
  63. package/dist/components/forms/select/select.class.js +1 -1
  64. package/dist/components/forms/slider/slider.class.d.ts +0 -1
  65. package/dist/components/forms/slider/slider.class.js +1 -1
  66. package/dist/components/forms/switch/switch.class.d.ts +0 -1
  67. package/dist/components/forms/switch/switch.class.js +1 -1
  68. package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
  69. package/dist/components/forms/time-range/time-range.class.js +1 -1
  70. package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
  71. package/dist/components/forms/token-input/token-input.class.js +1 -1
  72. package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
  73. package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
  74. package/dist/components/layout/details/accordion-owner.d.ts +1 -1
  75. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  76. package/dist/components/layout/menu/menu-item.class.js +1 -1
  77. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  78. package/dist/components/media/av-player/av-metadata.d.ts +0 -2
  79. package/dist/components/media/av-player/av-metadata.js +1 -1
  80. package/dist/components/media/file-input/file-input.class.d.ts +0 -1
  81. package/dist/components/media/file-input/file-input.class.js +1 -1
  82. package/dist/components/media/map/map-loader.d.ts +4 -1
  83. package/dist/components/media/map/map.class.d.ts +50 -12
  84. package/dist/components/media/map/map.class.js +2 -2
  85. package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
  86. package/dist/components/overlays/overlay/popover.class.js +1 -1
  87. package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
  88. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  89. package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
  90. package/dist/components/overlays/progress/progress-shared.js +1 -1
  91. package/dist/components/overlays/rating/rating.class.js +1 -1
  92. package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
  93. package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
  94. package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
  95. package/dist/components/utility/format/format-options.d.ts +0 -2
  96. package/dist/components/utility/format/format-options.js +1 -1
  97. package/dist/components/utility/icon/icon-resource.d.ts +0 -2
  98. package/dist/components/utility/icon/icon-resource.js +1 -1
  99. package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
  100. package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
  101. package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
  102. package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
  103. package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
  104. package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
  105. package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
  106. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  107. package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
  108. package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
  109. package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
  110. package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
  111. package/dist/custom-elements-jsx.d.ts +4 -4
  112. package/dist/events.d.ts +15 -0
  113. package/dist/internal/accessibility-visibility.d.ts +1 -1
  114. package/dist/internal/anchor-target.d.ts +1 -3
  115. package/dist/internal/anchor-target.js +2 -2
  116. package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
  117. package/dist/internal/anchored-overlay-runtime.js +1 -0
  118. package/dist/internal/announcement-text.d.ts +1 -1
  119. package/dist/internal/ansi.d.ts +0 -4
  120. package/dist/internal/ansi.js +1 -1
  121. package/dist/internal/aria-ownership.d.ts +2 -1
  122. package/dist/internal/default-strings.generated.d.ts +1 -0
  123. package/dist/internal/default-strings.generated.js +1 -1
  124. package/dist/internal/focus-navigation.d.ts +3 -2
  125. package/dist/internal/form-associated.d.ts +0 -1
  126. package/dist/internal/form-associated.js +1 -1
  127. package/dist/internal/form-control-labels.d.ts +0 -3
  128. package/dist/internal/form-control-labels.js +1 -1
  129. package/dist/internal/localization-runtime.js +1 -1
  130. package/dist/internal/localization-types.d.ts +1 -1
  131. package/dist/internal/localization.js +1 -1
  132. package/dist/internal/lyra-element.d.ts +0 -13
  133. package/dist/internal/lyra-element.js +1 -1
  134. package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
  135. package/dist/internal/nonmodal-overlay-manager.js +1 -0
  136. package/dist/internal/overlay-manager.d.ts +4 -20
  137. package/dist/internal/overlay-manager.js +1 -1
  138. package/dist/internal/overlay-stack.d.ts +66 -0
  139. package/dist/internal/overlay-stack.js +1 -0
  140. package/dist/internal/package-metadata.d.ts +1 -1
  141. package/dist/internal/package-metadata.js +1 -1
  142. package/dist/internal/positioner.js +1 -1
  143. package/dist/internal/text-quote.d.ts +1 -1
  144. package/dist/lyra.d.ts +2 -3
  145. package/dist/svelte.d.ts +4 -4
  146. package/dist/translations/ar.js +1 -1
  147. package/dist/translations/de.js +1 -1
  148. package/dist/translations/es.js +1 -1
  149. package/dist/translations/fa.js +1 -1
  150. package/dist/translations/fr.js +1 -1
  151. package/dist/translations/he.js +1 -1
  152. package/dist/translations/ja.js +1 -1
  153. package/dist/translations/pt-BR.js +1 -1
  154. package/dist/translations/ru.js +1 -1
  155. package/dist/translations/zh-CN.js +1 -1
  156. package/dist/utilities/localization.js +1 -1
  157. package/dist/vue.d.ts +4 -4
  158. package/llms/components/lr-combobox.md +42 -0
  159. package/llms/components/lr-date-input.md +1 -1
  160. package/llms/components/lr-date-picker.md +1 -1
  161. package/llms/components/lr-filter-bar.md +2 -2
  162. package/llms/components/lr-heatmap.md +4 -1
  163. package/llms/components/lr-lite-chart.md +20 -8
  164. package/llms/components/lr-map.md +52 -22
  165. package/llms/components/lr-option.md +42 -0
  166. package/llms/components/lr-popover.md +39 -0
  167. package/llms/components/lr-table.md +7 -3
  168. package/llms/components/lr-timeline-item.md +49 -24
  169. package/llms/components/lr-timeline.md +49 -24
  170. package/llms-full.txt +224 -60
  171. package/package.json +3 -4
  172. package/vscode-css-data.json +21 -0
  173. package/vscode-html-data.json +12 -6
  174. package/web-types.json +47 -16
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
2
2
  <span part="file-thumbnail" aria-hidden="true">
3
3
  ${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
4
4
  </span>
@@ -1,10 +1,13 @@
1
+ import type { Feature } from 'geojson';
1
2
  export interface MapLibreGeoJsonSource {
2
3
  setData(data: unknown): void;
3
4
  /** maplibre-gl 3+ incremental update. Optional because older peers lack it. */
4
5
  updateData?(diff: MapLibreGeoJsonDiff): void;
5
6
  }
6
- /** The subset of maplibre-gl's GeoJSON diff this component emits: per-feature property updates. */
7
+ /** The subset of maplibre-gl's GeoJSON diff this component emits. */
7
8
  export interface MapLibreGeoJsonDiff {
9
+ readonly remove?: readonly (string | number)[];
10
+ readonly add?: readonly Feature[];
8
11
  readonly update: readonly {
9
12
  readonly id: string | number;
10
13
  readonly addOrUpdateProperties: readonly {
@@ -122,6 +122,8 @@ export interface LyraMapClusterOptions {
122
122
  */
123
123
  readonly countFont?: readonly string[];
124
124
  }
125
+ /** A heatmap paint value expressed either as one constant or bounded `[zoom, value]` stops. */
126
+ export type LyraMapHeatmapZoomValue = number | readonly (readonly [zoom: number, value: number])[];
125
127
  /** Paint configuration for a `kind: 'heatmap'` data layer. */
126
128
  export interface LyraMapHeatmapOptions {
127
129
  /** Feature property weighting each point. Omitted, every point weighs 1 (MapLibre's default). */
@@ -143,10 +145,14 @@ export interface LyraMapHeatmapOptions {
143
145
  * default ramp.
144
146
  */
145
147
  readonly stops?: readonly (readonly [number, string])[];
146
- /** Kernel radius in pixels. Defaults to 30, MapLibre's own default. */
147
- readonly radius?: number;
148
- /** Global intensity multiplier. Defaults to 1, MapLibre's own default. */
149
- readonly intensity?: number;
148
+ /** Kernel radius in pixels, or linear `[zoom, radius]` stops. Zooms clamp to `[0, 24]`, radii
149
+ * to `[1, 200]`, and a scalar/default remains 30. */
150
+ readonly radius?: LyraMapHeatmapZoomValue;
151
+ /** Global intensity multiplier, or linear `[zoom, intensity]` stops. Zooms clamp to `[0, 24]`,
152
+ * intensity to `[0, 100]`, and a scalar/default remains 1. */
153
+ readonly intensity?: LyraMapHeatmapZoomValue;
154
+ /** Whole-layer opacity in `[0, 1]`. Omitted, MapLibre's own default remains in force. */
155
+ readonly opacity?: number;
150
156
  }
151
157
  /** One GeoJSON source rendered as three layers (`${sourceId}-fill` for polygons, `${sourceId}-line`
152
158
  * for lines/outlines, `${sourceId}-circle` for points), or — under `cluster`/`kind` — as the
@@ -210,6 +216,19 @@ export interface LyraMapMarker {
210
216
  */
211
217
  readonly unsafeHtml?: string;
212
218
  }
219
+ /** Input path that activated a declarative map marker. */
220
+ export type LyraMapMarkerActivationSource = 'pointer' | 'keyboard';
221
+ /** Immutable payload emitted when a declarative marker is activated. */
222
+ export interface LyraMapMarkerActivationDetail {
223
+ /** Trimmed explicit marker identity, or `undefined` for an idless marker. */
224
+ readonly id: string | undefined;
225
+ /** Validated marker position as `[longitude, latitude]`. */
226
+ readonly lngLat: readonly [number, number];
227
+ /** The accepted declarative marker snapshot. */
228
+ readonly marker: LyraMapMarker;
229
+ /** Whether activation came through click/pointer semantics or the keyboard contract. */
230
+ readonly source: LyraMapMarkerActivationSource;
231
+ }
213
232
  /** Peer-neutral subset of a MapLibre style accepted by `mapStyle`. */
214
233
  export interface LyraMapStyleSpecification {
215
234
  readonly version: 8;
@@ -256,23 +275,29 @@ export type LyraMapBounds = readonly [
256
275
  readonly [number, number]
257
276
  ];
258
277
  /**
259
- * Builds a maplibre-gl `updateData()` diff when `next` differs from `previous` only in feature
260
- * properties, and returns `null` otherwise so the caller replaces the whole source instead.
278
+ * Builds a maplibre-gl `updateData()` diff when stable feature ids make the change addressable,
279
+ * and returns `null` otherwise so the caller replaces the whole source instead. Property changes,
280
+ * additions, removals, and order changes all stay on the incremental path.
261
281
  *
262
282
  * `setData()` unconditionally re-tiles and repaints an entire source with no diffing. That is
263
283
  * invisible on a static map and expensive on an animated one: advancing a choropleth a step every
264
284
  * few hundred milliseconds re-tiles every polygon each time, when all that changed were the values
265
285
  * driving the colour ramp.
266
286
  *
267
- * Deliberately strict about what counts as "geometry unchanged": geometries must be the *same
268
- * object*, not merely deep-equal. Structurally comparing polygon rings would cost on the order of
269
- * the re-tile this exists to avoid, and a false positive here paints stale geometry -- a visibly
270
- * wrong map -- whereas a false negative merely takes the old path. An animation that reuses its
271
- * geometry across frames, which is the efficient way to build one anyway, hits the fast path.
287
+ * Geometry and bbox values must remain semantically unchanged. The component's ownership boundary
288
+ * necessarily detaches them on every accepted assignment, so reference identity cannot establish
289
+ * that fact; a bounded, accessor-free comparison verifies their JSON data graph instead. Any
290
+ * uncertainty still falls back to `setData()`.
291
+ *
292
+ * MapLibre applies removals before additions. To preserve the feature collection's observable
293
+ * order, the longest next-order prefix already appearing in previous order stays in place; the
294
+ * remaining suffix is removed and re-added in its exact next order. Appends and ordinary removals
295
+ * therefore remain minimal, while a reorder changes only the suffix it invalidated.
272
296
  */
273
297
  export declare function buildGeoJsonPropertyDiff(previous: unknown, next: unknown): MapLibreGeoJsonDiff | null;
274
298
  export interface LyraMapEventMap {
275
299
  'lr-map-load': CustomEvent<null>;
300
+ 'lr-map-marker-activate': CustomEvent<LyraMapMarkerActivationDetail>;
276
301
  'lr-map-click': CustomEvent<{
277
302
  readonly lngLat: readonly [number, number];
278
303
  readonly feature: Feature | undefined;
@@ -318,6 +343,9 @@ export interface LyraMapEventMap {
318
343
  *
319
344
  * @customElement lr-map
320
345
  * @event lr-map-load - Fired once the underlying maplibregl.Map loads.
346
+ * @event lr-map-marker-activate - Fired once when an accepted declarative marker is activated by
347
+ * pointer/click or by Enter/Space. The immutable detail carries its normalized `id`, validated
348
+ * `lngLat`, accepted marker snapshot, and activation `source`.
321
349
  * @event lr-map-click - `detail: { lngLat, feature?, origin?, sourceId? }`. `feature` resolves
322
350
  * against the choropleth fill *and* every applied `dataLayers` fill/line/circle/cluster layer,
323
351
  * topmost first; `origin`/`sourceId` name where it came from. A hit on a clustered entry's
@@ -382,6 +410,9 @@ export declare class LyraMap extends LyraElement<LyraMapEventMap> {
382
410
  center: readonly [number, number];
383
411
  /** Initial and controlled map zoom level. */
384
412
  zoom: number;
413
+ /** Whether the constructed peer repeats the world horizontally. `undefined` leaves MapLibre's
414
+ * own default in force. Construction-only; set before the map is created. */
415
+ renderWorldCopies?: boolean;
385
416
  /**
386
417
  * Box the map may not pan outside, `[[west, south], [east, north]]`, or `null` for unconstrained.
387
418
  *
@@ -495,10 +526,13 @@ export declare class LyraMap extends LyraElement<LyraMapEventMap> {
495
526
  private _markerInstances;
496
527
  private _markerLabels;
497
528
  private _markerPopupIds;
529
+ private readonly markerActivationDetails;
498
530
  private _configuredPopups;
499
531
  private _nextPopupId;
500
532
  private peerChromeObserver?;
501
533
  private observedPeerContainer?;
534
+ private mapResizeObserver?;
535
+ private observedMapContainer?;
502
536
  private _markerColors;
503
537
  private _connectGeneration;
504
538
  /** The underlying runtime `maplibregl.Map`, declared through Lyra's peer-neutral common-method
@@ -643,11 +677,15 @@ export declare class LyraMap extends LyraElement<LyraMapEventMap> {
643
677
  private removeDataLayer;
644
678
  private applyMarkers;
645
679
  private readonly configuredMarkerElements;
646
- private configureMarkerKeyboard;
680
+ private configureMarkerInteraction;
681
+ private emitMarkerActivation;
647
682
  private get effectiveMapLabel();
648
683
  private validMarkerLngLat;
649
684
  private popupId;
650
685
  private configurePopupSemantics;
686
+ private stopObservingMapAllocation;
687
+ /** Keeps MapLibre's canvas allocation synchronized with this component's live container. */
688
+ private observeMapAllocation;
651
689
  private stopObservingPeerChrome;
652
690
  /** Projects stable Lyra parts onto peer-owned nodes without erasing existing part tokens. */
653
691
  private syncPeerChromeParts;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{notifyMapCanvasReady}from"../../../internal/map-canvas-ready.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{srOnly}from"../../../internal/a11y.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{loadMaplibre}from"./map-loader.js";import{styles}from"./map.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_items,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_mapInitializationFailed,LYRA_DEFAULT_mapLegend,LYRA_DEFAULT_mapMissingLibrary,LYRA_DEFAULT_mapStyleRequired,LYRA_DEFAULT_mapWebglUnavailable,LYRA_DEFAULT_paginationSummary}from"../../../internal/default-strings.generated.js";function supportsWebGL2(host){try{return host.ownerDocument.createElement("canvas").getContext("webgl2")!==null}catch{return!1}}function hasMapStyle(style){return typeof style=="string"?style.trim().length>0:style!==void 0}const MAX_MAP_LEGEND_GRADIENT_STOPS=64;function normalizeMapLegendGradient(value){if(!Array.isArray(value))return[];const usable=[],scanCount=Math.min(value.length,MAX_MAP_LEGEND_GRADIENT_STOPS);for(let index=0;index<scanCount;index+=1){const stop=value[index];if(!Array.isArray(stop)||stop.length<2)continue;const[rawValue,rawColor]=stop;if(typeof rawValue!="number"||!Number.isFinite(rawValue)||typeof rawColor!="string")continue;const color=sanitizeCssColor(rawColor);color&&usable.push([rawValue,color])}return usable.length<2?[]:Object.freeze([...usable].sort((a,b)=>a[0]-b[0]))}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_PATTERNS=new Set(["solid","diagonal","dots","crosshatch"]),EMPTY_MAP_LEGEND=Object.freeze([]),EMPTY_MAP_LEGEND_PROJECTION=Object.freeze({inputCount:0,renderedCount:0,omittedCount:0,truncatedLabelCount:0,truncated:!1});function boundedLegendText(value,limit){return value.length<=limit?value:`${value.slice(0,Math.max(0,limit-1))}\u2026`}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,entries.push(Object.freeze({color:rawColor.slice(0,MAP_LEGEND_COLOR_LIMIT),label,pattern:rawPattern}))}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}}function addPartToken(element,token){const tokens=new Set((element.getAttribute("part")??"").split(/\s+/).filter(Boolean));tokens.add(token),element.setAttribute("part",[...tokens].join(" "))}const CHOROPLETH_LOG_INTERPOLATION_BASE=.25,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()}const MAX_MAP_DATA_LAYERS=100;function normalizedDataLayers(value){if(!Array.isArray(value))return[];const output=[],seenSourceIds=new Set,scanCount=Math.min(value.length,MAX_MAP_DATA_LAYERS);for(let index=0;index<scanCount;index++){const candidate=value[index];try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const rawSourceId=candidate.sourceId;if(typeof rawSourceId!="string")continue;const sourceId=rawSourceId.trim();if(sourceId.length===0||seenSourceIds.has(sourceId))continue;seenSourceIds.add(sourceId),output.push(rawSourceId===sourceId?candidate:{...candidate,sourceId})}catch{}}return output}const DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-cluster","-cluster-count","-heatmap"],QUERYABLE_DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-cluster"],MAX_MAP_STEP_STOPS=32;function normalizedSteps(value,isOutput,clampThreshold=threshold=>threshold){if(!Array.isArray(value))return[];const usable=[],scanCount=Math.min(value.length,MAX_MAP_STEP_STOPS);for(let index=0;index<scanCount;index+=1){const stop=value[index];if(!Array.isArray(stop)||stop.length<2)continue;const[rawThreshold,rawOutput]=stop;typeof rawThreshold!="number"||!Number.isFinite(rawThreshold)||isOutput(rawOutput)&&usable.push([clampThreshold(rawThreshold),rawOutput])}return usable.sort((a,b)=>a[0]-b[0]),usable.filter((stop,index)=>index===0||stop[0]>usable[index-1][0])}const isFiniteOutput=candidate=>typeof candidate=="number"&&Number.isFinite(candidate),isColorOutput=candidate=>typeof candidate=="string"&&candidate.trim().length>0;function stepExpression(input,stops){const expression=["step",input,stops[0][1]];for(const[threshold,output]of stops)expression.push(threshold,output);return expression}const DEFAULT_CLUSTER_RADIUS=50,DEFAULT_CLUSTER_MAX_ZOOM=14,DEFAULT_CLUSTER_RADIUS_STEPS=Object.freeze([[0,14],[10,18],[50,24]]),DEFAULT_HEATMAP_RADIUS=30,DEFAULT_HEATMAP_INTENSITY=1,HEATMAP_TRANSPARENT="rgba(0, 0, 0, 0)";function withTransparentFloor(stops){return stops.length&&stops[0][0]>0?[[0,HEATMAP_TRANSPARENT],...stops]:stops}const MAX_CLUSTER_COUNT_FONTS=8;function normalizedClusterOptions(value){if(value===null||typeof value!="object"||Array.isArray(value))return;const options=value,radiusSteps=normalizedSteps(options.radiusSteps,isFiniteOutput),fonts=Array.isArray(options.countFont)?options.countFont.filter(font=>typeof font=="string"&&font.trim().length>0).slice(0,MAX_CLUSTER_COUNT_FONTS):[];return{radius:finiteRange(Number(options.radius),DEFAULT_CLUSTER_RADIUS,1,1e3),maxZoom:finiteRange(Number(options.maxZoom),DEFAULT_CLUSTER_MAX_ZOOM,0,24),radiusSteps:radiusSteps.length?radiusSteps:DEFAULT_CLUSTER_RADIUS_STEPS,colorSteps:normalizedSteps(options.colorSteps,isColorOutput),countFont:fonts.length?fonts:void 0}}function dataLayerShape(layer){if(layer.kind==="heatmap")return"heatmap";const cluster=normalizedClusterOptions(layer.cluster);return cluster?`cluster:${cluster.radius}:${cluster.maxZoom}:${cluster.countFont?.join(",")??""}`:"auto"}function heatmapWeightExpression(options){const field=typeof options?.weightField=="string"?options.weightField.trim():"";if(!field)return;const range=options?.weightRange,min=Array.isArray(range)?Number(range[0]):Number.NaN,max=Array.isArray(range)?Number(range[1]):Number.NaN;return!Number.isFinite(min)||!Number.isFinite(max)||min>=max?["get",field]:["interpolate",["linear"],["get",field],min,0,max,1]}const FALLBACK_FILL_OPACITY=.75;function ownerWindow(host){return host.ownerDocument?.defaultView??null}function choroplethFillOpacity(host){const raw=ownerWindow(host)?.getComputedStyle(host).getPropertyValue("--lr-map-choropleth-fill-opacity").trim()??"",parsed=Number.parseFloat(raw);return Number.isFinite(parsed)?parsed:FALLBACK_FILL_OPACITY}const 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=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()??"")||"#0969da"}function resolvedLayerColor(host,explicit,tone){const candidate=typeof explicit=="string"?explicit.trim():"";if(!candidate)return dataLayerColor(host,tone);const reference=/^var\(\s*(--[\w-]+)/.exec(candidate);return reference?ownerWindow(host)?.getComputedStyle(host).getPropertyValue(reference[1]).trim()||dataLayerColor(host,tone):candidate}const UNTILEABLE_SCAN_FEATURE_LIMIT=1e4;function warnOnUntileableProperties(geojson,sourceLabel){const features=geojson?.features;if(!Array.isArray(features))return;const limit=Math.min(features.length,UNTILEABLE_SCAN_FEATURE_LIMIT);for(let index=0;index<limit;index+=1){const feature=features[index],properties=feature?.properties;if(!(!properties||typeof properties!="object"))for(const[key,value]of Object.entries(properties)){if(typeof value!="number"||!Number.isFinite(value)||Math.abs(value)<=Number.MAX_SAFE_INTEGER)continue;const identity=feature?.id??`index ${index}`;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 GEOJSON_DIFF_FEATURE_LIMIT=1e4;function buildGeoJsonPropertyDiff(previous,next){const previousFeatures=previous?.features,nextFeatures=next?.features;if(!Array.isArray(previousFeatures)||!Array.isArray(nextFeatures)||previousFeatures.length!==nextFeatures.length||nextFeatures.length>GEOJSON_DIFF_FEATURE_LIMIT)return null;const update=[];for(let index=0;index<nextFeatures.length;index+=1){const before=previousFeatures[index],after=nextFeatures[index];if(!before||!after)return null;const id=after.id;if(typeof id!="string"&&typeof id!="number"||before.id!==id||before.geometry!==after.geometry)return null;const beforeProperties=before.properties??{},afterProperties=after.properties??{},addOrUpdateProperties=[];for(const[key,value]of Object.entries(afterProperties))Object.is(beforeProperties[key],value)||addOrUpdateProperties.push({key,value});const removeProperties=Object.keys(beforeProperties).filter(key=>!(key in afterProperties));addOrUpdateProperties.length===0&&removeProperties.length===0||update.push({id,addOrUpdateProperties,removeProperties})}return{update}}class LyraMap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,items:LYRA_DEFAULT_items,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,mapInitializationFailed:LYRA_DEFAULT_mapInitializationFailed,mapLegend:LYRA_DEFAULT_mapLegend,mapMissingLibrary:LYRA_DEFAULT_mapMissingLibrary,mapStyleRequired:LYRA_DEFAULT_mapStyleRequired,mapWebglUnavailable:LYRA_DEFAULT_mapWebglUnavailable,paginationSummary:LYRA_DEFAULT_paginationSummary}}static{this.immutableEventDetails=Object.freeze(["lr-map-click"])}static{this.identityEventDetailProperties=Object.freeze({"lr-map-click":Object.freeze(["feature"])})}static{this.ownedCollectionProperties=Object.freeze(["center","mapStyle","choropleth","markers","dataLayers"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static preload(){return loadMaplibre().then(module=>module!==null)}constructor(){super(),this.center=[0,0],this.zoom=2,this.maxBounds=null,this._legend=EMPTY_MAP_LEGEND,this._legendProjection=EMPTY_MAP_LEGEND_PROJECTION,this.hasLegendSlot=!1,this._legendGradient=Object.freeze([]),this.legendGradientLoLabel=null,this.legendGradientHiLabel=null,this.markers=[],this.dataLayers=[],this.label="",this.loading=!0,this.loadLibrary=loadMaplibre,this.visible=ownerWindow(this)?.IntersectionObserver===void 0,this._styleLoaded=!1,this._appliedDataLayerIds=new Map,this._appliedDataLayerShapes=new Map,this._appliedGeoJson=new Map,this._nextDataLayerId=0,this._webglReady=!1,this._markerInstances=new Map,this._markerLabels=new Map,this._markerPopupIds=new Map,this._configuredPopups=new WeakSet,this._nextPopupId=0,this._markerColors=new Map,this._connectGeneration=0,this.configuredMarkerElements=new WeakSet,this.onLegendSlotChange=event=>{const slot=event.target;this.hasLegendSlot=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0)},new ThemeWatcher(this,()=>this.refreshThemePaint())}get legend(){return this._legend}set legend(value){const previous=this._legend,normalized=normalizeMapLegend(value);this._legend=normalized.entries,this._legendProjection=normalized.projection,this.requestUpdate("legend",previous)}probeLegendSlot(){for(const child of Array.from(this.children))if(child.getAttribute("slot")==="legend")return!0;return!1}get legendGradient(){return this._legendGradient}set legendGradient(value){const previous=this._legendGradient;this._legendGradient=normalizeMapLegendGradient(value),this.requestUpdate("legendGradient",previous)}get legendProjection(){return this._legendProjection}get map(){return this._map}pushGeoJson(source,resolvedSourceId,geojson){const previous=this._appliedGeoJson.get(resolvedSourceId),diff=typeof source.updateData=="function"&&previous!==void 0?buildGeoJsonPropertyDiff(previous,geojson):null;diff===null||typeof source.updateData!="function"?source.setData(geojson):diff.update.length>0&&source.updateData(diff),this._appliedGeoJson.set(resolvedSourceId,geojson)}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,zoomBefore=map.getZoom(),centerBefore=map.getCenter();try{if(map.setMaxBounds(bounds),bounds===null||Number.isFinite(map.getZoom()))return}catch{}try{map.setMaxBounds(null)}catch{}Number.isFinite(zoomBefore)&&map.setZoom(zoomBefore),centerBefore&&map.setCenter([centerBefore.lng,centerBefore.lat]),devWarnOnce("lyra-map-max-bounds-rejected","<lr-map>: maxBounds left maplibre-gl without a usable camera, so it was dropped and the camera restored. This is a peer limitation, not a bad value -- it shows up at sub-1 fractional zooms in wide containers. Raise the zoom, narrow the box, or leave maxBounds unset.")}get safeZoom(){return finiteRange(this.zoom,2,0,22)}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)]}connectedCallback(){super.connectedCallback(),this.syncErrorAnnouncementSink();const generation=++this._connectGeneration,IntersectionObserverCtor=ownerWindow(this)?.IntersectionObserver;if(this.visible=IntersectionObserverCtor===void 0,this.failure=void 0,this.loading=!0,this._webglReady=!1,IntersectionObserverCtor){const observer=new IntersectionObserverCtor(entries=>{entries[0]?.isIntersecting&&(this.visible=!0)});this.intersectionObserver=observer,observer.observe(this)}(async()=>{let mod;try{mod=await this.loadLibrary()}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.tryConstructMap()}})()}disconnectedCallback(){this.releaseErrorAnnouncementSink(),super.disconnectedCallback(),this.disposeMap(),this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0;for(const marker of this._markerInstances.values())marker.remove();this._markerInstances.clear(),this._markerColors.clear(),this._markerLabels.clear(),this._markerPopupIds.clear()}failureMessage(reason=this.failure??"initialization-failed"){switch(reason){case"missing-peer":return this.localize("mapMissingLibrary");case"style-required":return this.localize("mapStyleRequired");case"webgl-unavailable":return this.localize("mapWebglUnavailable");case"initialization-failed":return this.localize("mapInitializationFailed")}}failInitialization(reason,partialMap){try{partialMap?.remove()}catch{}this.disposeMap(),this.loading=!1,this.failure=reason,this.errorAnnouncementSink?.announce(this.failureMessage(reason))}disposeMap(){this.stopObservingPeerChrome();try{this._map?.remove()}catch{}this._map=void 0,this._styleLoaded=!1,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this._appliedGeoJson.clear()}adoptedCallback(){super.adoptedCallback(),this.stopObservingPeerChrome(),this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}tryConstructMap(){if(this._map||!this._maplibreModule||!this._webglReady||!this.containerEl||!this.visible||!this.isConnected)return;if(!hasMapStyle(this.mapStyle)){this.failInitialization("style-required");return}const mod=this._maplibreModule;let candidate;try{candidate=new mod.Map({container:this.containerEl,style:this.mapStyle,center:this.safeCenter,zoom:this.safeZoom,locale:{"Map.Title":this.effectiveMapLabel,"Marker.Title":this.localize("map"),"Popup.Close":this.localize("close")}}),candidate.on("error",event=>{if(this._map===candidate&&!this._styleLoaded){this.failInitialization("initialization-failed");return}console.error("lr-map:",event.error??event)}),candidate.on("load",()=>{if(this._map===candidate)try{this._styleLoaded=!0,this.applyChoropleth(),this.applyMarkers(),this.applyDataLayers(),this.emit("lr-map-load")}catch{this.failInitialization("initialization-failed")}}),candidate.on("click",event=>{if(this._map!==candidate)return;const fillLayerId=this._appliedFillLayerId,layerIds=[];fillLayerId&&candidate.getLayer(fillLayerId)&&layerIds.push(fillLayerId);for(const resolvedSourceId of this._appliedDataLayerIds.values())for(const suffix of QUERYABLE_DATA_LAYER_SUFFIXES){const layerId=`${resolvedSourceId}${suffix}`;candidate.getLayer(layerId)&&layerIds.push(layerId)}const hit=(layerIds.length?candidate.queryRenderedFeatures(event.point,{layers:layerIds}):[])[0],hitLayerId=hit?.layer?.id;let origin,sourceId;if(hitLayerId!==void 0){if(hitLayerId===fillLayerId)origin="choropleth";else for(const[publicSourceId,resolvedSourceId]of this._appliedDataLayerIds)if(hitLayerId.startsWith(`${resolvedSourceId}-`)){origin=hitLayerId===`${resolvedSourceId}-cluster`?"cluster":"data-layer",sourceId=publicSourceId;break}}this.emit("lr-map-click",{lngLat:[event.lngLat.lng,event.lngLat.lat],feature:hit,origin,sourceId})});const canvas=candidate.getCanvas?.();canvas&&notifyMapCanvasReady(this,canvas),this._map=candidate,this.observePeerChrome(),this.failure=void 0}catch{this.failInitialization("initialization-failed",candidate);return}this.applyMaxBounds()}updated(changed){if(super.updated(changed),this.setAttribute("aria-busy",String(this.loading)),changed.has("visible")&&this.visible&&this.tryConstructMap(),changed.has("mapStyle")&&!hasMapStyle(this.mapStyle)&&this._maplibreModule)this.failInitialization("style-required");else if(changed.has("mapStyle")&&!this._map&&this._maplibreModule&&hasMapStyle(this.mapStyle))this.tryConstructMap();else if(changed.has("mapStyle")&&this._map){this._styleLoaded=!1,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0;const map=this._map;try{map.once("style.load",()=>{if(this._map===map)try{this._styleLoaded=!0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this._appliedGeoJson.clear(),this.applyChoropleth(),this.applyDataLayers()}catch{this.scheduleAfterUpdate(()=>this.failInitialization("initialization-failed"),"map-style-failure")}}),map.setStyle(this.mapStyle)}catch{this.scheduleAfterUpdate(()=>this.failInitialization("initialization-failed"),"map-style-failure")}}else if(this._styleLoaded&&(changed.has("dataLayers")||changed.has("choropleth"))){const nextChoroplethSourceId=this.choropleth?this.resolveChoroplethSourceId(this.choropleth.sourceId):void 0;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==nextChoroplethSourceId&&this.removeChoropleth(),changed.has("dataLayers")&&this.applyDataLayers(),this.applyChoropleth()}changed.has("center")&&this._map&&this._map.setCenter(this.safeCenter),changed.has("zoom")&&this._map&&this._map.setZoom(this.safeZoom),changed.has("maxBounds")&&this._map&&this.applyMaxBounds(),changed.has("markers")&&this._map&&this.applyMarkers(),this.syncMapSemantics()}willUpdate(changed){super.willUpdate(changed),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.errorAnnouncementSink?.announce(this.failureMessage("webgl-unavailable"))))}refreshThemePaint(){if(!this._map||!this._styleLoaded)return;const fillOpacity=choroplethFillOpacity(this);this._appliedFillLayerId&&this._map.setPaintProperty(this._appliedFillLayerId,"fill-opacity",fillOpacity);const dataLayersBySourceId=new Map(normalizedDataLayers(this.dataLayers).map(layer=>[layer.sourceId,layer]));for(const[publicSourceId,sourceId]of this._appliedDataLayerIds){const dataLayer=dataLayersBySourceId.get(publicSourceId);dataLayer&&this.paintDataLayer(sourceId,dataLayer)}}applyChoropleth(){if(!this._map)return;if(!this.choropleth){this.removeChoropleth();return}const{geojson,field,stops}=this.choropleth,sourceId=this.resolveChoroplethSourceId(this.choropleth.sourceId),fillLayerId=`${sourceId}-fill`;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==sourceId&&this.removeChoropleth(),warnOnUntileableProperties(geojson,"choropleth");const existingSource=this._map.getSource(sourceId);if(existingSource?this.pushGeoJson(existingSource,sourceId,geojson):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojson)),this._appliedChoroplethSourceId=sourceId,stops.length===0)return;let colorExpr;if(this.choropleth.interpolation==="step"){const base=typeof this.choropleth.stepBaseColor=="string"&&this.choropleth.stepBaseColor.trim()?this.choropleth.stepBaseColor.trim():stops[0][1];colorExpr=["step",["get",field],base];for(const[value,color]of stops)colorExpr.push(value,color)}else{colorExpr=["interpolate",this.choropleth.interpolation==="logarithmic"?["exponential",CHOROPLETH_LOG_INTERPOLATION_BASE]:["linear"],["get",field]];for(const[value,color]of stops)colorExpr.push(value,color)}this._map.getLayer(fillLayerId)?(this._map.setPaintProperty(fillLayerId,"fill-color",colorExpr),this._map.setPaintProperty(fillLayerId,"fill-opacity",choroplethFillOpacity(this))):this._map.addLayer({id:fillLayerId,type:"fill",source:sourceId,paint:{"fill-color":colorExpr,"fill-opacity":choroplethFillOpacity(this)}}),this._appliedFillLayerId=fillLayerId}resolveChoroplethSourceId(sourceId){const dataSourceIds=new Set(normalizedDataLayers(this.dataLayers).map(layer=>layer.sourceId));let resolved=sourceId;for(;dataSourceIds.has(resolved);)resolved=`lr-choropleth-${resolved}`;return resolved}removeChoropleth(){!this._map||!this._appliedChoroplethSourceId||(this._appliedFillLayerId&&this._map.getLayer(this._appliedFillLayerId)&&this._map.removeLayer(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)}applyDataLayers(){if(!this._map)return;const layers=normalizedDataLayers(this.dataLayers),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){const{sourceId:publicSourceId,geojson}=layer,shape=dataLayerShape(layer),appliedShape=this._appliedDataLayerShapes.get(publicSourceId);appliedShape!==void 0&&appliedShape!==shape&&this.removeDataLayer(publicSourceId);const sourceId=this.resolveDataLayerSourceId(publicSourceId);warnOnUntileableProperties(geojson,publicSourceId);const cluster=layer.kind==="heatmap"?void 0:normalizedClusterOptions(layer.cluster),existingSource=this._map.getSource(sourceId);existingSource?this.pushGeoJson(existingSource,sourceId,geojson):(this._map.addSource(sourceId,{type:"geojson",data:geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}}),this._appliedGeoJson.set(sourceId,geojson)),this.applyDataLayerRendering(sourceId,layer),this._appliedDataLayerIds.set(publicSourceId,sourceId),this._appliedDataLayerShapes.set(publicSourceId,shape)}}applyDataLayerRendering(sourceId,layer){if(layer.kind==="heatmap"){this.applyHeatmapLayer(sourceId,layer);return}const cluster=normalizedClusterOptions(layer.cluster);if(cluster){this.applyClusterLayers(sourceId,layer,cluster);return}this.applyGeometryLayers(sourceId,layer)}paintDataLayer(sourceId,layer){if(layer.kind==="heatmap"){this.paintHeatmapLayer(sourceId,layer);return}const cluster=normalizedClusterOptions(layer.cluster);if(cluster){this.paintClusterLayers(sourceId,layer,cluster);return}this.paintGeometryLayers(sourceId,layer)}applyGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)||this._map.addLayer({id:fillId,type:"fill",source:sourceId,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":color,"fill-opacity":choroplethFillOpacity(this)}}),this._map.getLayer(lineId)||this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":stroke,"line-width":2}}),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.paintGeometryLayers(sourceId,layer)}paintGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone);this._map.setPaintProperty(`${sourceId}-fill`,"fill-color",color),this._map.setPaintProperty(`${sourceId}-fill`,"fill-opacity",choroplethFillOpacity(this)),this._map.setPaintProperty(`${sourceId}-line`,"line-color",stroke),this._map.setPaintProperty(`${sourceId}-circle`,"circle-color",stroke)}clusterColorExpression(layer,cluster){const tone=layer.tone;return cluster.colorSteps.length?stepExpression(["get","point_count"],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=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`,countId=`${sourceId}-cluster-count`,circleId=`${sourceId}-circle`,clusterColor=this.clusterColorExpression(layer,cluster),clusterRadius=stepExpression(["get","point_count"],cluster.radiusSteps),countColor=resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone);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}}),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=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`;this._map.setPaintProperty(clusterId,"circle-color",this.clusterColorExpression(layer,cluster)),this._map.setPaintProperty(clusterId,"circle-radius",stepExpression(["get","point_count"],cluster.radiusSteps)),this._map.setPaintProperty(clusterId,"circle-stroke-color",stroke),this.styleProvidesGlyphs()&&this._map.setPaintProperty(`${sourceId}-cluster-count`,"text-color",resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone)),this._map.setPaintProperty(`${sourceId}-circle`,"circle-color",stroke)}applyHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`,options=layer.heatmap,weight=heatmapWeightExpression(options),color=this.heatmapColorExpression(layer),radius=finiteRange(Number(options?.radius),DEFAULT_HEATMAP_RADIUS,1,200),intensity=finiteRange(Number(options?.intensity),DEFAULT_HEATMAP_INTENSITY,0,100);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}});return}this.paintHeatmapLayer(sourceId,layer)}paintHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`;this._map.setPaintProperty(heatmapId,"heatmap-weight",heatmapWeightExpression(layer.heatmap)??1),this._map.setPaintProperty(heatmapId,"heatmap-intensity",finiteRange(Number(layer.heatmap?.intensity),DEFAULT_HEATMAP_INTENSITY,0,100)),this._map.setPaintProperty(heatmapId,"heatmap-color",this.heatmapColorExpression(layer)),this._map.setPaintProperty(heatmapId,"heatmap-radius",finiteRange(Number(layer.heatmap?.radius),DEFAULT_HEATMAP_RADIUS,1,200))}heatmapColorExpression(layer){const tone=layer.tone,authored=normalizedSteps(layer.heatmap?.stops,isColorOutput,threshold=>finiteRange(threshold,0,0,1)).map(([density,color])=>[density,resolvedLayerColor(this,color,tone)]),authoredRamp=withTransparentFloor(authored),ramp=authoredRamp.length>=2?authoredRamp:withTransparentFloor(HEATMAP_RAMP_TOKENS.map(([density,token])=>[density,resolvedLayerColor(this,`var(${token})`,tone)])),expression=["interpolate",["linear"],["heatmap-density"]];for(const[density,color]of ramp)expression.push(density,color);return expression}styleProvidesGlyphs(){try{const liveGlyphs=this._map?.getStyle?.()?.glyphs;if(typeof liveGlyphs=="string"&&liveGlyphs.trim().length>0)return!0}catch{}const declared=this.mapStyle,declaredGlyphs=declared&&typeof declared=="object"?declared.glyphs:void 0;return typeof declaredGlyphs=="string"&&declaredGlyphs.trim().length>0}resolveDataLayerSourceId(publicSourceId){const applied=this._appliedDataLayerIds.get(publicSourceId);if(applied)return applied;let sourceId;do sourceId=`lr-data-layer-${this._nextDataLayerId++}`;while(this._map?.getSource(sourceId)||DATA_LAYER_SUFFIXES.some(suffix=>this._map?.getLayer(`${sourceId}${suffix}`)));return sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){for(const suffix of DATA_LAYER_SUFFIXES){const layerId=`${sourceId}${suffix}`;this._map.getLayer(layerId)&&this._map.removeLayer(layerId)}this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.delete(publicSourceId),this._appliedDataLayerShapes.delete(publicSourceId),this._appliedGeoJson.delete(sourceId)}}applyMarkers(){const map=this._map,mod=this._maplibreModule;if(!map||!mod)return;const visible=new Set,coordCounts=new Map,explicitIds=new Set,markers=Array.isArray(this.markers)?this.markers.slice(0,MAX_MAP_MARKERS):[];for(const candidate of markers){const lngLat=this.validMarkerLngLat(candidate);if(!lngLat)continue;const m=candidate,rawId=m.id;let key;if(rawId!==void 0){if(typeof rawId!="string")continue;const id=rawId.trim();if(id.length===0||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);if(existing&&this._markerColors.get(key)!==markerColor&&(existing.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),existing=void 0),existing){existing.setLngLat(lngLat);const popup=existing.getPopup();if(m.unsafeHtml)if(popup)popup.setHTML(m.unsafeHtml);else{const nextPopup=new mod.Popup({offset:12}).setHTML(m.unsafeHtml);existing.setPopup(nextPopup),this.configurePopupSemantics(key,existing,nextPopup)}else if(m.label)if(popup)popup.setText(m.label);else{const nextPopup=new mod.Popup({offset:12}).setText(m.label);existing.setPopup(nextPopup),this.configurePopupSemantics(key,existing,nextPopup)}else popup&&existing.setPopup(void 0)}else{const marker=new mod.Marker(markerColor?{color:markerColor}:void 0).setLngLat(lngLat);if(m.unsafeHtml||m.label){const popup=new mod.Popup({offset:12});m.unsafeHtml?popup.setHTML(m.unsafeHtml):m.label&&popup.setText(m.label),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()||(m.unsafeHtml?popupText(this,m.unsafeHtml):"");this._markerLabels.set(key,markerLabel||void 0);const markerElement=this._markerInstances.get(key)?.getElement?.();if(markerElement){addPartToken(markerElement,"marker"),markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const currentMarker=this._markerInstances.get(key),popup=currentMarker?.getPopup();popup&&currentMarker?(this.configurePopupSemantics(key,currentMarker,popup),this.syncPopupSemantics(key,currentMarker,popup),this.configureMarkerKeyboard(markerElement,currentMarker)):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"))}}for(const[key,marker]of this._markerInstances)visible.has(key)||(marker.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),this._markerLabels.delete(key),this._markerPopupIds.delete(key))}configureMarkerKeyboard(markerElement,marker){this.configuredMarkerElements.has(markerElement)||(this.configuredMarkerElements.add(markerElement),markerElement.addEventListener("keydown",event=>{event.key!==" "||!marker.getPopup?.()||event.defaultPrevented||event.preventDefault()},{capture:!0}))}get effectiveMapLabel(){return this.getAttribute("aria-label")===""?"":this.label||this.localize("map")}validMarkerLngLat(candidate){if(!candidate||typeof candidate!="object")return null;const lngLat=candidate.lngLat;if(!Array.isArray(lngLat)||lngLat.length<2)return null;const[lng,lat]=lngLat;return typeof lng!="number"||typeof lat!="number"||!Number.isFinite(lng)||!Number.isFinite(lat)||lat<-90||lat>90?null:[lng,lat]}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")}))}stopObservingPeerChrome(){this.peerChromeObserver?.disconnect(),this.peerChromeObserver=void 0,this.observedPeerContainer=void 0}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const selectors=[[".maplibregl-marker","marker"],[".maplibregl-popup","popup"],[".maplibregl-popup-content","popup-content"],[".maplibregl-popup-close-button","popup-close-button"],[".maplibregl-ctrl-attrib","attribution"],[".maplibregl-ctrl-attrib-button","attribution-toggle"]];for(const[selector,part]of selectors){const candidate=root;candidate.matches?.(selector)&&addPartToken(candidate,part);for(const element of root.querySelectorAll(selector))addPartToken(element,part)}}observePeerChrome(){const container=this.containerEl;if(!container||(this.syncPeerChromeParts(container),this.observedPeerContainer===container&&this.peerChromeObserver))return;this.stopObservingPeerChrome();const MutationObserverCtor=container.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.observedPeerContainer=container,this.peerChromeObserver=new MutationObserverCtor(records=>{if(!(!this.isConnected||this.containerEl!==container))for(const record of records)for(const node of record.addedNodes)node.nodeType===Node.ELEMENT_NODE&&this.syncPeerChromeParts(node)}),this.peerChromeObserver.observe(container,{childList:!0,subtree:!0}))}syncPopupSemantics(key,marker,popup){const markerElement=marker?.getElement?.();if(!markerElement)return;const id=this.popupId(key);markerElement.setAttribute("aria-controls",id),markerElement.setAttribute("aria-expanded",popup?.isOpen?.()?"true":"false");const popupElement=popup?.getElement?.();if(!popupElement)return;addPartToken(markerElement,"marker"),addPartToken(popupElement,"popup"),popupElement.id=id,popupElement.setAttribute("role","dialog"),popupElement.setAttribute("lang",this.effectiveLocale),popupElement.setAttribute("aria-label",this._markerLabels.get(key)||this.effectiveMapLabel);const popupContent=popupElement.querySelector(".maplibregl-popup-content");popupContent&&addPartToken(popupContent,"popup-content");const closeButton=popupElement.querySelector(".maplibregl-popup-close-button");closeButton&&addPartToken(closeButton,"popup-close-button"),closeButton?.setAttribute("aria-label",this.localize("close"))}syncMapSemantics(){const canvas=this._map?.getCanvas?.();canvas&&(canvas.setAttribute("aria-label",this.effectiveMapLabel),canvas.setAttribute("lang",this.effectiveLocale),this.legend.length||this.legendProjection.truncated?canvas.setAttribute("aria-describedby","map-legend"):canvas.removeAttribute("aria-describedby"));for(const[key,marker]of this._markerInstances){const markerElement=marker.getElement?.();if(!markerElement)continue;addPartToken(markerElement,"marker"),markerElement.setAttribute("aria-label",this._markerLabels.get(key)||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const popup=marker.getPopup?.();popup&&this.syncPopupSemantics(key,marker,popup)}this.syncPeerChromeParts()}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatCount(this.legend.length===0?0:1),end:this.formatCount(this.legend.length),total:this.formatCount(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendGradient(){const stops=this.legendGradient;if(stops.length<2)return nothing;const lo=stops[0],hi=stops[stops.length-1],span=hi[0]-lo[0],image=stops.map(([value,color],index)=>{const percent=span>0?(value-lo[0])/span*100:index/(stops.length-1)*100;return`${color} ${percent}%`}).join(", ");return html`<div class="legend-gradient">
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{notifyMapCanvasReady}from"../../../internal/map-canvas-ready.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{srOnly}from"../../../internal/a11y.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{loadMaplibre}from"./map-loader.js";import{styles}from"./map.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_items,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_mapInitializationFailed,LYRA_DEFAULT_mapLegend,LYRA_DEFAULT_mapMissingLibrary,LYRA_DEFAULT_mapStyleRequired,LYRA_DEFAULT_mapWebglUnavailable,LYRA_DEFAULT_paginationSummary}from"../../../internal/default-strings.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}}function hasMapStyle(style){return typeof style=="string"?style.trim().length>0:style!==void 0}const MAX_MAP_LEGEND_GRADIENT_STOPS=64;function normalizeMapLegendGradient(value){if(!Array.isArray(value))return[];const usable=[],scanCount=Math.min(value.length,MAX_MAP_LEGEND_GRADIENT_STOPS);for(let index=0;index<scanCount;index+=1){const stop=value[index];if(!Array.isArray(stop)||stop.length<2)continue;const[rawValue,rawColor]=stop;if(typeof rawValue!="number"||!Number.isFinite(rawValue)||typeof rawColor!="string")continue;const color=sanitizeCssColor(rawColor);color&&usable.push([rawValue,color])}return usable.length<2?[]:Object.freeze([...usable].sort((a,b)=>a[0]-b[0]))}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_PATTERNS=new Set(["solid","diagonal","dots","crosshatch"]),EMPTY_MAP_LEGEND=Object.freeze([]),EMPTY_MAP_LEGEND_PROJECTION=Object.freeze({inputCount:0,renderedCount:0,omittedCount:0,truncatedLabelCount:0,truncated:!1});function boundedLegendText(value,limit){return value.length<=limit?value:`${value.slice(0,Math.max(0,limit-1))}\u2026`}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,entries.push(Object.freeze({color:rawColor.slice(0,MAP_LEGEND_COLOR_LIMIT),label,pattern:rawPattern}))}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}}function addPartToken(element,token){const tokens=new Set((element.getAttribute("part")??"").split(/\s+/).filter(Boolean));tokens.add(token),element.setAttribute("part",[...tokens].join(" "))}const CHOROPLETH_LOG_INTERPOLATION_BASE=.25,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()}const MAX_MAP_DATA_LAYERS=100;function normalizedDataLayers(value){if(!Array.isArray(value))return[];const output=[],seenSourceIds=new Set,scanCount=Math.min(value.length,MAX_MAP_DATA_LAYERS);for(let index=0;index<scanCount;index++){const candidate=value[index];try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))continue;const rawSourceId=candidate.sourceId;if(typeof rawSourceId!="string")continue;const sourceId=rawSourceId.trim();if(sourceId.length===0||seenSourceIds.has(sourceId))continue;seenSourceIds.add(sourceId),output.push(rawSourceId===sourceId?candidate:{...candidate,sourceId})}catch{}}return output}const DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-cluster","-cluster-count","-heatmap"],QUERYABLE_DATA_LAYER_SUFFIXES=["-fill","-line","-circle","-cluster"],MAX_MAP_STEP_STOPS=32;function normalizedSteps(value,isOutput,clampThreshold=threshold=>threshold){if(!Array.isArray(value))return[];const usable=[],scanCount=Math.min(value.length,MAX_MAP_STEP_STOPS);for(let index=0;index<scanCount;index+=1){const stop=value[index];if(!Array.isArray(stop)||stop.length<2)continue;const[rawThreshold,rawOutput]=stop;typeof rawThreshold!="number"||!Number.isFinite(rawThreshold)||isOutput(rawOutput)&&usable.push([clampThreshold(rawThreshold),rawOutput])}return usable.sort((a,b)=>a[0]-b[0]),usable.filter((stop,index)=>index===0||stop[0]>usable[index-1][0])}const isFiniteOutput=candidate=>typeof candidate=="number"&&Number.isFinite(candidate),isColorOutput=candidate=>typeof candidate=="string"&&candidate.trim().length>0;function stepExpression(input,stops){const expression=["step",input,stops[0][1]];for(const[threshold,output]of stops)expression.push(threshold,output);return expression}const DEFAULT_CLUSTER_RADIUS=50,DEFAULT_CLUSTER_MAX_ZOOM=14,DEFAULT_CLUSTER_RADIUS_STEPS=Object.freeze([[0,14],[10,18],[50,24]]),DEFAULT_HEATMAP_RADIUS=30,DEFAULT_HEATMAP_INTENSITY=1,HEATMAP_TRANSPARENT="rgba(0, 0, 0, 0)";function withTransparentFloor(stops){return stops.length&&stops[0][0]>0?[[0,HEATMAP_TRANSPARENT],...stops]:stops}const MAX_CLUSTER_COUNT_FONTS=8;function normalizedClusterOptions(value){if(value===null||typeof value!="object"||Array.isArray(value))return;const options=value,radiusSteps=normalizedSteps(options.radiusSteps,isFiniteOutput),fonts=Array.isArray(options.countFont)?options.countFont.filter(font=>typeof font=="string"&&font.trim().length>0).slice(0,MAX_CLUSTER_COUNT_FONTS):[];return{radius:finiteRange(Number(options.radius),DEFAULT_CLUSTER_RADIUS,1,1e3),maxZoom:finiteRange(Number(options.maxZoom),DEFAULT_CLUSTER_MAX_ZOOM,0,24),radiusSteps:radiusSteps.length?radiusSteps:DEFAULT_CLUSTER_RADIUS_STEPS,colorSteps:normalizedSteps(options.colorSteps,isColorOutput),countFont:fonts.length?fonts:void 0}}function dataLayerShape(layer){if(layer.kind==="heatmap")return"heatmap";const cluster=normalizedClusterOptions(layer.cluster);return cluster?`cluster:${cluster.radius}:${cluster.maxZoom}:${cluster.countFont?.join(",")??""}`:"auto"}function heatmapWeightExpression(options){const field=typeof options?.weightField=="string"?options.weightField.trim():"";if(!field)return;const range=options?.weightRange,min=Array.isArray(range)?Number(range[0]):Number.NaN,max=Array.isArray(range)?Number(range[1]):Number.NaN;return!Number.isFinite(min)||!Number.isFinite(max)||min>=max?["get",field]:["interpolate",["linear"],["get",field],min,0,max,1]}function heatmapZoomValue(value,fallback,min,max){if(!Array.isArray(value))return finiteRange(Number(value),fallback,min,max);const stops=normalizedSteps(value,isFiniteOutput,zoom=>finiteRange(zoom,0,0,24)).map(([zoom,output])=>[zoom,finiteRange(output,fallback,min,max)]);if(stops.length===0)return fallback;if(stops.length===1)return stops[0][1];const expression=["interpolate",["linear"],["zoom"]];for(const[zoom,output]of stops)expression.push(zoom,output);return expression}const FALLBACK_FILL_OPACITY=.75;function ownerWindow(host){return host.ownerDocument?.defaultView??null}function choroplethFillOpacity(host){const raw=ownerWindow(host)?.getComputedStyle(host).getPropertyValue("--lr-map-choropleth-fill-opacity").trim()??"",parsed=Number.parseFloat(raw);return Number.isFinite(parsed)?parsed:FALLBACK_FILL_OPACITY}const 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=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()??"")||"#0969da"}function resolvedLayerColor(host,explicit,tone){const candidate=typeof explicit=="string"?explicit.trim():"";if(!candidate)return dataLayerColor(host,tone);const reference=/^var\(\s*(--[\w-]+)/.exec(candidate);return reference?ownerWindow(host)?.getComputedStyle(host).getPropertyValue(reference[1]).trim()||dataLayerColor(host,tone):candidate}const UNTILEABLE_SCAN_FEATURE_LIMIT=1e4;function warnOnUntileableProperties(geojson,sourceLabel){const features=geojson?.features;if(!Array.isArray(features))return;const limit=Math.min(features.length,UNTILEABLE_SCAN_FEATURE_LIMIT);for(let index=0;index<limit;index+=1){const feature=features[index],properties=feature?.properties;if(!(!properties||typeof properties!="object"))for(const[key,value]of Object.entries(properties)){if(typeof value!="number"||!Number.isFinite(value)||Math.abs(value)<=Number.MAX_SAFE_INTEGER)continue;const identity=feature?.id??`index ${index}`;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 GEOJSON_DIFF_FEATURE_LIMIT=1e4,GEOJSON_DIFF_VALUE_LIMIT=5e4;function isPlainGeoJsonRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");return!!(constructor&&"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object"&&Object.getPrototypeOf(prototype)===null)}catch{return!1}}function sameGeoJsonValue(previous,next,comparison){if(comparison.remaining<=0)return!1;if(comparison.remaining-=1,Object.is(previous,next))return!0;if(previous===null||next===null||typeof previous!="object"||typeof next!="object")return!1;const pairedNext=comparison.forward.get(previous);if(pairedNext)return pairedNext===next;const pairedPrevious=comparison.reverse.get(next);if(pairedPrevious)return pairedPrevious===previous;comparison.forward.set(previous,next),comparison.reverse.set(next,previous);const previousIsArray=Array.isArray(previous),nextIsArray=Array.isArray(next);if(previousIsArray||nextIsArray){if(!previousIsArray||!nextIsArray||previous.length!==next.length)return!1;for(let index=0;index<previous.length;index+=1){const before=Object.getOwnPropertyDescriptor(previous,String(index)),after=Object.getOwnPropertyDescriptor(next,String(index));if(!!before!=!!after)return!1;if(!(!before||!after)&&(!("value"in before)||!("value"in after)||!sameGeoJsonValue(before.value,after.value,comparison)))return!1}return!0}if(!isPlainGeoJsonRecord(previous)||!isPlainGeoJsonRecord(next))return!1;const previousKeys=Object.keys(previous),nextKeys=Object.keys(next);if(previousKeys.length!==nextKeys.length)return!1;for(let index=0;index<previousKeys.length;index+=1){const key=previousKeys[index];if(key!==nextKeys[index])return!1;const before=Object.getOwnPropertyDescriptor(previous,key),after=Object.getOwnPropertyDescriptor(next,key);if(!before||!after||!("value"in before)||!("value"in after)||!sameGeoJsonValue(before.value,after.value,comparison))return!1}return!0}function sameGeoJsonSnapshots(previous,next){try{return sameGeoJsonValue(previous,next,{remaining:GEOJSON_DIFF_VALUE_LIMIT,forward:new WeakMap,reverse:new WeakMap})}catch{return!1}}function indexGeoJsonCollection(value){try{if(value?.type!=="FeatureCollection")return null;const features=value?.features;if(!Array.isArray(features)||features.length>GEOJSON_DIFF_FEATURE_LIMIT)return null;const ordered=[],byId=new Map;for(let index=0;index<features.length;index+=1){const feature=features[index];if(!feature||Array.isArray(feature)||feature.type!=="Feature")return null;const id=feature.id;if(typeof id!="string"&&typeof id!="number"||byId.has(id))return null;const rawProperties=feature.properties;if(rawProperties!=null&&(typeof rawProperties!="object"||Array.isArray(rawProperties)))return null;const indexed={id,index,feature,geometry:feature.geometry,bbox:feature.bbox,properties:rawProperties??{}};ordered.push(indexed),byId.set(id,indexed)}return{ordered,byId}}catch{return null}}function buildGeoJsonPropertyDiff(previous,next){const previousCollection=indexGeoJsonCollection(previous),nextCollection=indexGeoJsonCollection(next);if(!previousCollection||!nextCollection)return null;const previousGeometry=[],nextGeometry=[];for(const after of nextCollection.ordered){const before=previousCollection.byId.get(after.id);before&&(previousGeometry.push(before.geometry,before.bbox),nextGeometry.push(after.geometry,after.bbox))}if(!sameGeoJsonSnapshots(previousGeometry,nextGeometry))return null;const retained=new Set;let previousIndex=-1;for(const feature of nextCollection.ordered){const before=previousCollection.byId.get(feature.id);if(!before||before.index<=previousIndex)break;retained.add(feature.id),previousIndex=before.index}const remove=previousCollection.ordered.filter(feature=>!retained.has(feature.id)).map(feature=>feature.id),add=nextCollection.ordered.filter(feature=>!retained.has(feature.id)).map(feature=>feature.feature),update=[];for(const after of nextCollection.ordered){if(!retained.has(after.id))continue;const before=previousCollection.byId.get(after.id),addOrUpdateProperties=[];for(const[key,value]of Object.entries(after.properties))Object.is(before.properties[key],value)||addOrUpdateProperties.push({key,value});const removeProperties=Object.keys(before.properties).filter(key=>!Object.hasOwn(after.properties,key));addOrUpdateProperties.length===0&&removeProperties.length===0||update.push({id:after.id,addOrUpdateProperties,removeProperties})}return{...remove.length?{remove}:{},...add.length?{add}:{},update}}class LyraMap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,items:LYRA_DEFAULT_items,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,mapInitializationFailed:LYRA_DEFAULT_mapInitializationFailed,mapLegend:LYRA_DEFAULT_mapLegend,mapMissingLibrary:LYRA_DEFAULT_mapMissingLibrary,mapStyleRequired:LYRA_DEFAULT_mapStyleRequired,mapWebglUnavailable:LYRA_DEFAULT_mapWebglUnavailable,paginationSummary:LYRA_DEFAULT_paginationSummary}}static{this.immutableEventDetails=Object.freeze(["lr-map-click","lr-map-marker-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-map-click":Object.freeze(["feature"])})}static{this.ownedCollectionProperties=Object.freeze(["center","mapStyle","choropleth","markers","dataLayers"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static preload(){return loadMaplibre().then(module=>module!==null)}constructor(){super(),this.center=[0,0],this.zoom=2,this.maxBounds=null,this._legend=EMPTY_MAP_LEGEND,this._legendProjection=EMPTY_MAP_LEGEND_PROJECTION,this.hasLegendSlot=!1,this._legendGradient=Object.freeze([]),this.legendGradientLoLabel=null,this.legendGradientHiLabel=null,this.markers=[],this.dataLayers=[],this.label="",this.loading=!0,this.loadLibrary=loadMaplibre,this.visible=ownerWindow(this)?.IntersectionObserver===void 0,this._styleLoaded=!1,this._appliedDataLayerIds=new Map,this._appliedDataLayerShapes=new Map,this._appliedGeoJson=new Map,this._nextDataLayerId=0,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._connectGeneration=0,this.configuredMarkerElements=new WeakSet,this.onLegendSlotChange=event=>{const slot=event.target;this.hasLegendSlot=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0)},new ThemeWatcher(this,()=>this.refreshThemePaint())}get legend(){return this._legend}set legend(value){const previous=this._legend,normalized=normalizeMapLegend(value);this._legend=normalized.entries,this._legendProjection=normalized.projection,this.requestUpdate("legend",previous)}probeLegendSlot(){for(const child of Array.from(this.children))if(child.getAttribute("slot")==="legend")return!0;return!1}get legendGradient(){return this._legendGradient}set legendGradient(value){const previous=this._legendGradient;this._legendGradient=normalizeMapLegendGradient(value),this.requestUpdate("legendGradient",previous)}get legendProjection(){return this._legendProjection}get map(){return this._map}pushGeoJson(source,resolvedSourceId,geojson){const previous=this._appliedGeoJson.get(resolvedSourceId),diff=typeof source.updateData=="function"&&previous!==void 0?buildGeoJsonPropertyDiff(previous,geojson):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,geojson)}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,zoomBefore=map.getZoom(),centerBefore=map.getCenter();try{if(map.setMaxBounds(bounds),bounds===null||Number.isFinite(map.getZoom()))return}catch{}try{map.setMaxBounds(null)}catch{}Number.isFinite(zoomBefore)&&map.setZoom(zoomBefore),centerBefore&&map.setCenter([centerBefore.lng,centerBefore.lat]),devWarnOnce("lyra-map-max-bounds-rejected","<lr-map>: maxBounds left maplibre-gl without a usable camera, so it was dropped and the camera restored. This is a peer limitation, not a bad value -- it shows up at sub-1 fractional zooms in wide containers. Raise the zoom, narrow the box, or leave maxBounds unset.")}get safeZoom(){return finiteRange(this.zoom,2,0,22)}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)]}connectedCallback(){super.connectedCallback(),this.syncErrorAnnouncementSink();const generation=++this._connectGeneration,IntersectionObserverCtor=ownerWindow(this)?.IntersectionObserver;if(this.visible=IntersectionObserverCtor===void 0,this.failure=void 0,this.loading=!0,this._webglReady=!1,IntersectionObserverCtor){const observer=new IntersectionObserverCtor(entries=>{entries[0]?.isIntersecting&&(this.visible=!0)});this.intersectionObserver=observer,observer.observe(this)}(async()=>{let mod;try{mod=await this.loadLibrary()}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.tryConstructMap()}})()}disconnectedCallback(){this.releaseErrorAnnouncementSink(),super.disconnectedCallback(),this.disposeMap(),this.intersectionObserver?.disconnect(),this.intersectionObserver=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()}failureMessage(reason=this.failure??"initialization-failed"){switch(reason){case"missing-peer":return this.localize("mapMissingLibrary");case"style-required":return this.localize("mapStyleRequired");case"webgl-unavailable":return this.localize("mapWebglUnavailable");case"initialization-failed":return this.localize("mapInitializationFailed")}}failInitialization(reason,partialMap){try{partialMap?.remove()}catch{}this.disposeMap(),this.loading=!1,this.failure=reason,this.errorAnnouncementSink?.announce(this.failureMessage(reason))}disposeMap(){this.stopObservingMapAllocation(),this.stopObservingPeerChrome();try{this._map?.remove()}catch{}this._map=void 0,this._styleLoaded=!1,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this._appliedGeoJson.clear()}adoptedCallback(){super.adoptedCallback(),this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this._map&&this.containerEl&&this.isConnected&&this.observeMapAllocation(this._map,this.containerEl)}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}tryConstructMap(){if(this._map||!this._maplibreModule||!this._webglReady||!this.containerEl||!this.visible||!this.isConnected)return;if(!hasMapStyle(this.mapStyle)){this.failInitialization("style-required");return}const mod=this._maplibreModule;let candidate;try{candidate=new mod.Map({container:this.containerEl,style:this.mapStyle,center:this.safeCenter,zoom:this.safeZoom,...typeof this.renderWorldCopies=="boolean"?{renderWorldCopies:this.renderWorldCopies}:{},locale:{"Map.Title":this.effectiveMapLabel,"Marker.Title":this.localize("map"),"Popup.Close":this.localize("close")}}),candidate.on("error",event=>{if(this._map===candidate&&!this._styleLoaded){this.failInitialization("initialization-failed");return}console.error("lr-map:",event.error??event)}),candidate.on("load",()=>{if(this._map===candidate)try{this._styleLoaded=!0,this.applyChoropleth(),this.applyMarkers(),this.applyDataLayers(),this.emit("lr-map-load")}catch{this.failInitialization("initialization-failed")}}),candidate.on("click",event=>{if(this._map!==candidate)return;const fillLayerId=this._appliedFillLayerId,layerIds=[];fillLayerId&&candidate.getLayer(fillLayerId)&&layerIds.push(fillLayerId);for(const resolvedSourceId of this._appliedDataLayerIds.values())for(const suffix of QUERYABLE_DATA_LAYER_SUFFIXES){const layerId=`${resolvedSourceId}${suffix}`;candidate.getLayer(layerId)&&layerIds.push(layerId)}const hit=(layerIds.length?candidate.queryRenderedFeatures(event.point,{layers:layerIds}):[])[0],hitLayerId=hit?.layer?.id;let origin,sourceId;if(hitLayerId!==void 0){if(hitLayerId===fillLayerId)origin="choropleth";else for(const[publicSourceId,resolvedSourceId]of this._appliedDataLayerIds)if(hitLayerId.startsWith(`${resolvedSourceId}-`)){origin=hitLayerId===`${resolvedSourceId}-cluster`?"cluster":"data-layer",sourceId=publicSourceId;break}}this.emit("lr-map-click",{lngLat:[event.lngLat.lng,event.lngLat.lat],feature:hit,origin,sourceId})});const canvas=candidate.getCanvas?.();canvas&&notifyMapCanvasReady(this,canvas),this._map=candidate,this.observeMapAllocation(candidate,this.containerEl),this.observePeerChrome(),this.failure=void 0}catch{this.failInitialization("initialization-failed",candidate);return}this.applyMaxBounds()}updated(changed){if(super.updated(changed),this.setAttribute("aria-busy",String(this.loading)),changed.has("visible")&&this.visible&&this.tryConstructMap(),changed.has("mapStyle")&&!hasMapStyle(this.mapStyle)&&this._maplibreModule)this.failInitialization("style-required");else if(changed.has("mapStyle")&&!this._map&&this._maplibreModule&&hasMapStyle(this.mapStyle))this.tryConstructMap();else if(changed.has("mapStyle")&&this._map){this._styleLoaded=!1,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0;const map=this._map;try{map.once("style.load",()=>{if(this._map===map)try{this._styleLoaded=!0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this._appliedGeoJson.clear(),this.applyChoropleth(),this.applyDataLayers()}catch{this.scheduleAfterUpdate(()=>this.failInitialization("initialization-failed"),"map-style-failure")}}),map.setStyle(this.mapStyle)}catch{this.scheduleAfterUpdate(()=>this.failInitialization("initialization-failed"),"map-style-failure")}}else if(this._styleLoaded&&(changed.has("dataLayers")||changed.has("choropleth"))){const nextChoroplethSourceId=this.choropleth?this.resolveChoroplethSourceId(this.choropleth.sourceId):void 0;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==nextChoroplethSourceId&&this.removeChoropleth(),changed.has("dataLayers")&&this.applyDataLayers(),this.applyChoropleth()}changed.has("center")&&this._map&&this._map.setCenter(this.safeCenter),changed.has("zoom")&&this._map&&this._map.setZoom(this.safeZoom),changed.has("maxBounds")&&this._map&&this.applyMaxBounds(),changed.has("markers")&&this._map&&this.applyMarkers(),this.syncMapSemantics()}willUpdate(changed){super.willUpdate(changed),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.errorAnnouncementSink?.announce(this.failureMessage("webgl-unavailable"))))}refreshThemePaint(){if(!this._map||!this._styleLoaded)return;const fillOpacity=choroplethFillOpacity(this);this._appliedFillLayerId&&this._map.setPaintProperty(this._appliedFillLayerId,"fill-opacity",fillOpacity);const dataLayersBySourceId=new Map(normalizedDataLayers(this.dataLayers).map(layer=>[layer.sourceId,layer]));for(const[publicSourceId,sourceId]of this._appliedDataLayerIds){const dataLayer=dataLayersBySourceId.get(publicSourceId);dataLayer&&this.paintDataLayer(sourceId,dataLayer)}}applyChoropleth(){if(!this._map)return;if(!this.choropleth){this.removeChoropleth();return}const{geojson,field,stops}=this.choropleth,sourceId=this.resolveChoroplethSourceId(this.choropleth.sourceId),fillLayerId=`${sourceId}-fill`;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==sourceId&&this.removeChoropleth(),warnOnUntileableProperties(geojson,"choropleth");const existingSource=this._map.getSource(sourceId);if(existingSource?this.pushGeoJson(existingSource,sourceId,geojson):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojson)),this._appliedChoroplethSourceId=sourceId,stops.length===0)return;let colorExpr;if(this.choropleth.interpolation==="step"){const base=typeof this.choropleth.stepBaseColor=="string"&&this.choropleth.stepBaseColor.trim()?this.choropleth.stepBaseColor.trim():stops[0][1];colorExpr=["step",["get",field],base];for(const[value,color]of stops)colorExpr.push(value,color)}else{colorExpr=["interpolate",this.choropleth.interpolation==="logarithmic"?["exponential",CHOROPLETH_LOG_INTERPOLATION_BASE]:["linear"],["get",field]];for(const[value,color]of stops)colorExpr.push(value,color)}this._map.getLayer(fillLayerId)?(this._map.setPaintProperty(fillLayerId,"fill-color",colorExpr),this._map.setPaintProperty(fillLayerId,"fill-opacity",choroplethFillOpacity(this))):this._map.addLayer({id:fillLayerId,type:"fill",source:sourceId,paint:{"fill-color":colorExpr,"fill-opacity":choroplethFillOpacity(this)}}),this._appliedFillLayerId=fillLayerId}resolveChoroplethSourceId(sourceId){const dataSourceIds=new Set(normalizedDataLayers(this.dataLayers).map(layer=>layer.sourceId));let resolved=sourceId;for(;dataSourceIds.has(resolved);)resolved=`lr-choropleth-${resolved}`;return resolved}removeChoropleth(){!this._map||!this._appliedChoroplethSourceId||(this._appliedFillLayerId&&this._map.getLayer(this._appliedFillLayerId)&&this._map.removeLayer(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)}applyDataLayers(){if(!this._map)return;const layers=normalizedDataLayers(this.dataLayers),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){const{sourceId:publicSourceId,geojson}=layer,shape=dataLayerShape(layer),appliedShape=this._appliedDataLayerShapes.get(publicSourceId);appliedShape!==void 0&&appliedShape!==shape&&this.removeDataLayer(publicSourceId);const sourceId=this.resolveDataLayerSourceId(publicSourceId);warnOnUntileableProperties(geojson,publicSourceId);const cluster=layer.kind==="heatmap"?void 0:normalizedClusterOptions(layer.cluster),existingSource=this._map.getSource(sourceId);existingSource?this.pushGeoJson(existingSource,sourceId,geojson):(this._map.addSource(sourceId,{type:"geojson",data:geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}}),this._appliedGeoJson.set(sourceId,geojson)),this.applyDataLayerRendering(sourceId,layer),this._appliedDataLayerIds.set(publicSourceId,sourceId),this._appliedDataLayerShapes.set(publicSourceId,shape)}}applyDataLayerRendering(sourceId,layer){if(layer.kind==="heatmap"){this.applyHeatmapLayer(sourceId,layer);return}const cluster=normalizedClusterOptions(layer.cluster);if(cluster){this.applyClusterLayers(sourceId,layer,cluster);return}this.applyGeometryLayers(sourceId,layer)}paintDataLayer(sourceId,layer){if(layer.kind==="heatmap"){this.paintHeatmapLayer(sourceId,layer);return}const cluster=normalizedClusterOptions(layer.cluster);if(cluster){this.paintClusterLayers(sourceId,layer,cluster);return}this.paintGeometryLayers(sourceId,layer)}applyGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)||this._map.addLayer({id:fillId,type:"fill",source:sourceId,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":color,"fill-opacity":choroplethFillOpacity(this)}}),this._map.getLayer(lineId)||this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":stroke,"line-width":2}}),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.paintGeometryLayers(sourceId,layer)}paintGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone);this._map.setPaintProperty(`${sourceId}-fill`,"fill-color",color),this._map.setPaintProperty(`${sourceId}-fill`,"fill-opacity",choroplethFillOpacity(this)),this._map.setPaintProperty(`${sourceId}-line`,"line-color",stroke),this._map.setPaintProperty(`${sourceId}-circle`,"circle-color",stroke)}clusterColorExpression(layer,cluster){const tone=layer.tone;return cluster.colorSteps.length?stepExpression(["get","point_count"],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=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`,countId=`${sourceId}-cluster-count`,circleId=`${sourceId}-circle`,clusterColor=this.clusterColorExpression(layer,cluster),clusterRadius=stepExpression(["get","point_count"],cluster.radiusSteps),countColor=resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone);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}}),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=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`;this._map.setPaintProperty(clusterId,"circle-color",this.clusterColorExpression(layer,cluster)),this._map.setPaintProperty(clusterId,"circle-radius",stepExpression(["get","point_count"],cluster.radiusSteps)),this._map.setPaintProperty(clusterId,"circle-stroke-color",stroke),this.styleProvidesGlyphs()&&this._map.setPaintProperty(`${sourceId}-cluster-count`,"text-color",resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone)),this._map.setPaintProperty(`${sourceId}-circle`,"circle-color",stroke)}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(Number(options?.opacity),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._map.setPaintProperty(heatmapId,"heatmap-weight",heatmapWeightExpression(layer.heatmap)??1),this._map.setPaintProperty(heatmapId,"heatmap-intensity",heatmapZoomValue(layer.heatmap?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100)),this._map.setPaintProperty(heatmapId,"heatmap-color",this.heatmapColorExpression(layer)),this._map.setPaintProperty(heatmapId,"heatmap-radius",heatmapZoomValue(layer.heatmap?.radius,DEFAULT_HEATMAP_RADIUS,1,200)),this._map.setPaintProperty(heatmapId,"heatmap-opacity",finiteRange(Number(layer.heatmap?.opacity),1,0,1))}heatmapColorExpression(layer){const tone=layer.tone,authored=normalizedSteps(layer.heatmap?.stops,isColorOutput,threshold=>finiteRange(threshold,0,0,1)).map(([density,color])=>[density,resolvedLayerColor(this,color,tone)]),authoredRamp=withTransparentFloor(authored),ramp=authoredRamp.length>=2?authoredRamp:withTransparentFloor(HEATMAP_RAMP_TOKENS.map(([density,token])=>[density,resolvedLayerColor(this,`var(${token})`,tone)])),expression=["interpolate",["linear"],["heatmap-density"]];for(const[density,color]of ramp)expression.push(density,color);return expression}styleProvidesGlyphs(){try{const liveGlyphs=this._map?.getStyle?.()?.glyphs;if(typeof liveGlyphs=="string"&&liveGlyphs.trim().length>0)return!0}catch{}const declared=this.mapStyle,declaredGlyphs=declared&&typeof declared=="object"?declared.glyphs:void 0;return typeof declaredGlyphs=="string"&&declaredGlyphs.trim().length>0}resolveDataLayerSourceId(publicSourceId){const applied=this._appliedDataLayerIds.get(publicSourceId);if(applied)return applied;let sourceId;do sourceId=`lr-data-layer-${this._nextDataLayerId++}`;while(this._map?.getSource(sourceId)||DATA_LAYER_SUFFIXES.some(suffix=>this._map?.getLayer(`${sourceId}${suffix}`)));return sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){for(const suffix of DATA_LAYER_SUFFIXES){const layerId=`${sourceId}${suffix}`;this._map.getLayer(layerId)&&this._map.removeLayer(layerId)}this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.delete(publicSourceId),this._appliedDataLayerShapes.delete(publicSourceId),this._appliedGeoJson.delete(sourceId)}}applyMarkers(){const map=this._map,mod=this._maplibreModule;if(!map||!mod)return;const visible=new Set,coordCounts=new Map,explicitIds=new Set,markers=Array.isArray(this.markers)?this.markers.slice(0,MAX_MAP_MARKERS):[];for(const candidate of markers){const lngLat=this.validMarkerLngLat(candidate);if(!lngLat)continue;const m=candidate,rawId=m.id;let key,id;if(rawId!==void 0){if(typeof rawId!="string"||(id=rawId.trim(),id.length===0||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);if(existing&&this._markerColors.get(key)!==markerColor){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(lngLat);const popup=existing.getPopup();if(m.unsafeHtml)if(popup)popup.setHTML(m.unsafeHtml);else{const nextPopup=new mod.Popup({offset:12}).setHTML(m.unsafeHtml);existing.setPopup(nextPopup),this.configurePopupSemantics(key,existing,nextPopup)}else if(m.label)if(popup)popup.setText(m.label);else{const nextPopup=new mod.Popup({offset:12}).setText(m.label);existing.setPopup(nextPopup),this.configurePopupSemantics(key,existing,nextPopup)}else popup&&existing.setPopup(void 0)}else{const marker=new mod.Marker(markerColor?{color:markerColor}:void 0).setLngLat(lngLat);if(m.unsafeHtml||m.label){const popup=new mod.Popup({offset:12});m.unsafeHtml?popup.setHTML(m.unsafeHtml):m.label&&popup.setText(m.label),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()||(m.unsafeHtml?popupText(this,m.unsafeHtml):"");this._markerLabels.set(key,markerLabel||void 0);const markerElement=this._markerInstances.get(key)?.getElement?.();if(markerElement){addPartToken(markerElement,"marker"),markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const currentMarker=this._markerInstances.get(key);this.configureMarkerInteraction(markerElement,{id,lngLat,marker:m});const popup=currentMarker?.getPopup();popup&&currentMarker?(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)}}configureMarkerInteraction(markerElement,activation){this.markerActivationDetails.set(markerElement,activation),markerElement.setAttribute("role","button"),markerElement.tabIndex=0;const markerLabel=activation.marker.label?.trim()||(activation.marker.unsafeHtml?popupText(this,activation.marker.unsafeHtml):"");markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale),!this.configuredMarkerElements.has(markerElement)&&(this.configuredMarkerElements.add(markerElement),markerElement.addEventListener("click",event=>{event.defaultPrevented||this.emitMarkerActivation(markerElement,"pointer")}),markerElement.addEventListener("keydown",event=>{event.key!==" "&&event.key!=="Enter"||event.repeat||event.defaultPrevented||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected)return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return this.getAttribute("aria-label")===""?"":this.label||this.localize("map")}validMarkerLngLat(candidate){if(!candidate||typeof candidate!="object")return null;const lngLat=candidate.lngLat;if(!Array.isArray(lngLat)||lngLat.length<2)return null;const[lng,lat]=lngLat;return typeof lng!="number"||typeof lat!="number"||!Number.isFinite(lng)||!Number.isFinite(lat)||lat<-90||lat>90?null:[lng,lat]}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;observer=new ResizeObserverCtor(()=>{if(!(this.mapResizeObserver!==observer||this.observedMapContainer!==container||this.containerEl!==container||this._map!==map||!this.isConnected))try{map.resize()}catch{}}),this.mapResizeObserver=observer,this.observedMapContainer=container;try{observer.observe(container)}catch{this.stopObservingMapAllocation()}}stopObservingPeerChrome(){this.peerChromeObserver?.disconnect(),this.peerChromeObserver=void 0,this.observedPeerContainer=void 0}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const selectors=[[".maplibregl-marker","marker"],[".maplibregl-popup","popup"],[".maplibregl-popup-content","popup-content"],[".maplibregl-popup-close-button","popup-close-button"],[".maplibregl-ctrl-attrib","attribution"],[".maplibregl-ctrl-attrib-button","attribution-toggle"]];for(const[selector,part]of selectors){const candidate=root;candidate.matches?.(selector)&&addPartToken(candidate,part);for(const element of root.querySelectorAll(selector))addPartToken(element,part)}}observePeerChrome(){const container=this.containerEl;if(!container||(this.syncPeerChromeParts(container),this.observedPeerContainer===container&&this.peerChromeObserver))return;this.stopObservingPeerChrome();const MutationObserverCtor=container.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.observedPeerContainer=container,this.peerChromeObserver=new MutationObserverCtor(records=>{if(!(!this.isConnected||this.containerEl!==container))for(const record of records)for(const node of record.addedNodes)node.nodeType===Node.ELEMENT_NODE&&this.syncPeerChromeParts(node)}),this.peerChromeObserver.observe(container,{childList:!0,subtree:!0}))}syncPopupSemantics(key,marker,popup){const markerElement=marker?.getElement?.();if(!markerElement)return;const id=this.popupId(key);markerElement.setAttribute("aria-controls",id),markerElement.setAttribute("aria-haspopup","dialog"),markerElement.setAttribute("aria-expanded",popup?.isOpen?.()?"true":"false");const popupElement=popup?.getElement?.();if(!popupElement)return;addPartToken(markerElement,"marker"),addPartToken(popupElement,"popup"),popupElement.id=id,popupElement.setAttribute("role","dialog"),popupElement.setAttribute("lang",this.effectiveLocale),popupElement.setAttribute("aria-label",this._markerLabels.get(key)||this.effectiveMapLabel);const popupContent=popupElement.querySelector(".maplibregl-popup-content");popupContent&&addPartToken(popupContent,"popup-content");const closeButton=popupElement.querySelector(".maplibregl-popup-close-button");closeButton&&addPartToken(closeButton,"popup-close-button"),closeButton?.setAttribute("aria-label",this.localize("close"))}syncMapSemantics(){const canvas=this._map?.getCanvas?.();canvas&&(canvas.setAttribute("aria-label",this.effectiveMapLabel),canvas.setAttribute("lang",this.effectiveLocale),this.legend.length||this.legendProjection.truncated?canvas.setAttribute("aria-describedby","map-legend"):canvas.removeAttribute("aria-describedby"));for(const[key,marker]of this._markerInstances){const markerElement=marker.getElement?.();if(!markerElement)continue;addPartToken(markerElement,"marker"),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",this._markerLabels.get(key)||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const popup=marker.getPopup?.();popup?this.syncPopupSemantics(key,marker,popup):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}this.syncPeerChromeParts()}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatCount(this.legend.length===0?0:1),end:this.formatCount(this.legend.length),total:this.formatCount(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendGradient(){const stops=this.legendGradient;if(stops.length<2)return nothing;const lo=stops[0],hi=stops[stops.length-1],span=hi[0]-lo[0],image=stops.map(([value,color],index)=>{const percent=span>0?(value-lo[0])/span*100:index/(stops.length-1)*100;return`${color} ${percent}%`}).join(", ");return html`<div class="legend-gradient">
2
2
  <span part="legend-lo">${this.legendGradientLoLabel??this.formatCount(lo[0])}</span>
3
3
  <span
4
4
  part="legend-gradient"
@@ -49,4 +49,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
49
49
  <slot name="legend" @slotchange=${this.onLegendSlotChange}></slot>
50
50
  </div>`:nothing}
51
51
  </div>
52
- `}}__decorate([property({type:Array})],LyraMap.prototype,"center",void 0),__decorate([property({type:Number})],LyraMap.prototype,"zoom",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"maxBounds",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"mapStyle",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"legend",null),__decorate([state()],LyraMap.prototype,"hasLegendSlot",void 0),__decorate([property({attribute:"legend-gradient-lo-label"})],LyraMap.prototype,"legendGradientLoLabel",void 0),__decorate([property({attribute:"legend-gradient-hi-label"})],LyraMap.prototype,"legendGradientHiLabel",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"choropleth",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"markers",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"dataLayers",void 0),__decorate([property()],LyraMap.prototype,"label",void 0),__decorate([state()],LyraMap.prototype,"loading",void 0),__decorate([state()],LyraMap.prototype,"failure",void 0),__decorate([state()],LyraMap.prototype,"visible",void 0),__decorate([query('[part="container"]')],LyraMap.prototype,"containerEl",void 0);export{LyraMap,buildGeoJsonPropertyDiff};
52
+ `}}__decorate([property({type:Array})],LyraMap.prototype,"center",void 0),__decorate([property({type:Number})],LyraMap.prototype,"zoom",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,"mapStyle",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"legend",null),__decorate([state()],LyraMap.prototype,"hasLegendSlot",void 0),__decorate([property({attribute:"legend-gradient-lo-label"})],LyraMap.prototype,"legendGradientLoLabel",void 0),__decorate([property({attribute:"legend-gradient-hi-label"})],LyraMap.prototype,"legendGradientHiLabel",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"choropleth",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"markers",void 0),__decorate([property({attribute:!1})],LyraMap.prototype,"dataLayers",void 0),__decorate([property()],LyraMap.prototype,"label",void 0),__decorate([state()],LyraMap.prototype,"loading",void 0),__decorate([state()],LyraMap.prototype,"failure",void 0),__decorate([state()],LyraMap.prototype,"visible",void 0),__decorate([query('[part="container"]')],LyraMap.prototype,"containerEl",void 0);export{LyraMap,buildGeoJsonPropertyDiff};
@@ -1,7 +1,7 @@
1
1
  import { type PropertyValues, type TemplateResult } from 'lit';
2
2
  import type { Placement } from '@floating-ui/dom';
3
3
  import { LyraElement } from '../../../internal/lyra-element.js';
4
- import { type PlaceStrategy, type PlaceSync } from '../../../internal/positioner.js';
4
+ import type { PlaceStrategy, PlaceSync } from '../../../internal/positioner.js';
5
5
  import { type LyraArrowPlacement } from './overlay-arrow.js';
6
6
  import { type OverlayVirtualRect } from './overlay-shared.js';
7
7
  /** Semantic role vocabulary for a popover surface or mapped trigger contract. */
@@ -159,6 +159,9 @@ export declare class LyraPopover<Events extends LyraPopoverEventMap = LyraPopove
159
159
  * `showAt()`'s doc comment and `activatePopoverOverlay()`'s focus-return configuration. */
160
160
  private returnFocusTo?;
161
161
  private cleanup?;
162
+ private positioningGeneration;
163
+ private positioningReady;
164
+ private resolvePositioningReady?;
162
165
  /** Registered with the shared overlay manager while every popover is open, so one topmost stack
163
166
  * owns Escape and focus restoration. */
164
167
  private overlayHandle?;
@@ -256,6 +259,9 @@ export declare class LyraPopover<Events extends LyraPopoverEventMap = LyraPopove
256
259
  * which resolves the identical chain. */
257
260
  private resolveAnchor;
258
261
  protected positionPopup(): void;
262
+ private invalidatePositioning;
263
+ private resolveCurrentPositioning;
264
+ private startPositioning;
259
265
  private syncTriggerA11y;
260
266
  private get accessibleTrigger();
261
267
  private releaseTriggerA11y;