@aceshooting/lyra-ui 10.0.1 → 11.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +271 -0
  2. package/custom-elements.json +1 -1
  3. package/design-tokens.json +13 -0
  4. package/dist/cli/migrate-wa.mjs +164 -1
  5. package/dist/cli/migration-contract.json +1 -1
  6. package/dist/components/charts/chart/box-plot.class.d.ts +27 -0
  7. package/dist/components/charts/chart/box-plot.class.js +14 -4
  8. package/dist/components/charts/chart/box-plot.styles.js +28 -0
  9. package/dist/components/charts/chart/chart.class.d.ts +27 -0
  10. package/dist/components/charts/chart/chart.class.js +15 -5
  11. package/dist/components/charts/chart/chart.styles.js +28 -0
  12. package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
  13. package/dist/components/charts/chart/lite-chart.class.js +17 -4
  14. package/dist/components/charts/chart/lite-chart.styles.js +29 -0
  15. package/dist/components/data/heatmap/heatmap.class.d.ts +35 -2
  16. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  17. package/dist/components/data/table/table.class.d.ts +19 -0
  18. package/dist/components/data/table/table.class.js +3 -3
  19. package/dist/components/forms/combobox/combobox.class.d.ts +71 -3
  20. package/dist/components/forms/combobox/combobox.class.js +4 -2
  21. package/dist/components/forms/combobox/combobox.styles.js +9 -0
  22. package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
  23. package/dist/components/forms/date-picker/date-input.class.js +4 -2
  24. package/dist/components/forms/date-picker/date-picker.class.d.ts +72 -0
  25. package/dist/components/forms/date-picker/date-picker.class.js +15 -3
  26. package/dist/components/forms/date-picker/date-picker.styles.js +46 -0
  27. package/dist/components/media/flag/flag.class.d.ts +3 -1
  28. package/dist/components/media/flag/flag.class.js +1 -1
  29. package/dist/components/media/map/map.class.d.ts +39 -2
  30. package/dist/components/media/map/map.class.js +1 -1
  31. package/dist/components/overlays/dialog/dialog.class.d.ts +20 -0
  32. package/dist/components/overlays/overlay/popover.class.d.ts +19 -3
  33. package/dist/components/overlays/overlay/popover.class.js +1 -1
  34. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  35. package/dist/custom-elements-jsx.d.ts +31 -16
  36. package/dist/internal/canvas.js +1 -1
  37. package/dist/internal/package-metadata.d.ts +1 -1
  38. package/dist/internal/package-metadata.js +1 -1
  39. package/dist/internal/tokens.styles.js +1 -0
  40. package/dist/lyra.d.ts +1 -1
  41. package/dist/svelte.d.ts +31 -16
  42. package/dist/theme.css +32 -0
  43. package/dist/vue.d.ts +31 -16
  44. package/llms/components/lr-agent-eval-dashboard.md +1 -1
  45. package/llms/components/lr-agent-workspace.md +1 -1
  46. package/llms/components/lr-bar-chart.md +4 -3
  47. package/llms/components/lr-box-plot.md +15 -4
  48. package/llms/components/lr-bubble-chart.md +4 -3
  49. package/llms/components/lr-chart.md +13 -3
  50. package/llms/components/lr-chunk-inspector.md +1 -1
  51. package/llms/components/lr-combobox.md +42 -6
  52. package/llms/components/lr-date-input.md +40 -4
  53. package/llms/components/lr-date-picker.md +40 -4
  54. package/llms/components/lr-dialog.md +2 -1
  55. package/llms/components/lr-doughnut-chart.md +4 -3
  56. package/llms/components/lr-entity-dossier.md +1 -1
  57. package/llms/components/lr-eval-run.md +1 -1
  58. package/llms/components/lr-flag.md +10 -3
  59. package/llms/components/lr-grounding-summary.md +1 -1
  60. package/llms/components/lr-heatmap.md +20 -2
  61. package/llms/components/lr-histogram.md +4 -3
  62. package/llms/components/lr-line-chart.md +4 -3
  63. package/llms/components/lr-lite-chart.md +19 -3
  64. package/llms/components/lr-map.md +21 -4
  65. package/llms/components/lr-memory-panel.md +1 -1
  66. package/llms/components/lr-option.md +41 -5
  67. package/llms/components/lr-pie-chart.md +4 -3
  68. package/llms/components/lr-polar-area-chart.md +4 -3
  69. package/llms/components/lr-popover.md +20 -1
  70. package/llms/components/lr-provenance-panel.md +1 -1
  71. package/llms/components/lr-radar-chart.md +4 -3
  72. package/llms/components/lr-rag-answer.md +1 -1
  73. package/llms/components/lr-rag-eval-dashboard.md +1 -1
  74. package/llms/components/lr-retrieval-results.md +1 -1
  75. package/llms/components/lr-retrieval-trace.md +1 -1
  76. package/llms/components/lr-scatter-chart.md +4 -3
  77. package/llms/peers.md +8 -8
  78. package/llms/tokens.md +27 -1
  79. package/llms-full.txt +231 -28
  80. package/package.json +1 -1
  81. package/vscode-css-data.json +70 -0
  82. package/vscode-html-data.json +131 -20
  83. package/web-types.json +190 -23
@@ -53,9 +53,28 @@ export interface LyraMapChoroplethLayer {
53
53
  * reading in real values instead of log units.
54
54
  */
55
55
  readonly interpolation?: LyraMapChoroplethInterpolation;
56
+ /**
57
+ * Color for values BELOW the first `stops` threshold, used only when `interpolation` is
58
+ * `'step'` — maplibre's `['step', …]` requires that base output before its first threshold.
59
+ *
60
+ * Defaults to the first stop's own color, which makes the common case (a legend whose first band
61
+ * starts at the data's minimum) need no extra configuration. Set it when the map should
62
+ * distinguish "below the lowest advertised band" from the lowest band itself.
63
+ */
64
+ readonly stepBaseColor?: string;
56
65
  }
57
- /** How a choropleth's fill color is interpolated between its stops. */
58
- export type LyraMapChoroplethInterpolation = 'linear' | 'logarithmic';
66
+ /**
67
+ * How a choropleth's fill color is derived from its stops.
68
+ *
69
+ * `'linear'` and `'logarithmic'` both emit a maplibre `['interpolate', …]` expression, producing a
70
+ * continuous ramp. `'step'` emits `['step', …]` instead, giving DISCRETE bands.
71
+ *
72
+ * A continuous ramp is wrong whenever the legend advertises a fixed set of ranges with one swatch
73
+ * each: it puts colors on the map that appear nowhere in the legend, and renders two regions in the
74
+ * same advertised band as visibly different colors. `legendGradient` covers the opposite case (a
75
+ * gradient legend) but could not express this one.
76
+ */
77
+ export type LyraMapChoroplethInterpolation = 'linear' | 'logarithmic' | 'step';
59
78
  /** One GeoJSON source rendered as three layers (`${sourceId}-fill` for polygons, `${sourceId}-line`
60
79
  * for lines/outlines, `${sourceId}-circle` for points). Colors resolve from `--lr-*` tokens at
61
80
  * apply time, defaulting to `accent`. */
@@ -65,6 +84,24 @@ export interface LyraMapGeoJsonDataLayer {
65
84
  readonly sourceId: string;
66
85
  readonly geojson: Feature | FeatureCollection;
67
86
  readonly tone?: 'accent' | 'success' | 'warning' | 'danger' | 'neutral';
87
+ /**
88
+ * Explicit fill color, overriding `tone` for the polygon fill only. Any CSS color, including a
89
+ * `var(--lr-…)` reference.
90
+ *
91
+ * Exists because a fill and its outline want opposite things on a choropleth-plus-overlay map,
92
+ * and the difference is measurable rather than aesthetic: the fill competes for area with the
93
+ * choropleth beside it, so it has to sit quiet, while the 1px outline competes with nothing and
94
+ * is the only thing keeping a no-data region's shape readable once the fill is that faint.
95
+ * Deriving one from the other put a real case at 1.41:1 against a light basemap — under WCAG
96
+ * 1.4.11's 3:1 floor for graphical objects — leaving the region indistinguishable from bare
97
+ * basemap.
98
+ */
99
+ readonly color?: string;
100
+ /**
101
+ * Explicit line/outline color, overriding `tone` for the `-line` and `-circle` layers. Falls back
102
+ * to `color`, then to `tone`. See `color` for why these are separable.
103
+ */
104
+ readonly strokeColor?: string;
68
105
  }
69
106
  export interface LyraMapMarker {
70
107
  /** Optional explicit business identity. Explicit IDs are trimmed and must be nonempty; the
@@ -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 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"};function dataLayerColor(host,tone){const token=TONE_TOKEN[tone??"accent"];return(ownerWindow(host)?.getComputedStyle(host).getPropertyValue(token).trim()??"")||"#0969da"}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._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();map.setMaxBounds(bounds),bounds!==null&&(Number.isFinite(map.getZoom())||(map.setMaxBounds(null),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 zoom, 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._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["-fill","-line","-circle"]){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="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)}}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._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);if(!dataLayer)continue;const color=dataLayerColor(this,dataLayer.tone);this._map.setPaintProperty(`${sourceId}-fill`,"fill-color",color),this._map.setPaintProperty(`${sourceId}-fill`,"fill-opacity",fillOpacity),this._map.setPaintProperty(`${sourceId}-line`,"line-color",color),this._map.setPaintProperty(`${sourceId}-circle`,"circle-color",color)}}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;const 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,tone}=layer,sourceId=this.resolveDataLayerSourceId(publicSourceId);warnOnUntileableProperties(geojson,publicSourceId);const existingSource=this._map.getSource(sourceId);existingSource?this.pushGeoJson(existingSource,sourceId,geojson):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojson));const color=dataLayerColor(this,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)?(this._map.setPaintProperty(fillId,"fill-color",color),this._map.setPaintProperty(fillId,"fill-opacity",choroplethFillOpacity(this))):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.setPaintProperty(lineId,"line-color",color):this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":color,"line-width":2}}),this._map.getLayer(circleId)?this._map.setPaintProperty(circleId,"circle-color",color):this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":color,"circle-radius":5}}),this._appliedDataLayerIds.set(publicSourceId,sourceId)}}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)||this._map?.getLayer(`${sourceId}-fill`)||this._map?.getLayer(`${sourceId}-line`)||this._map?.getLayer(`${sourceId}-circle`));return sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){for(const layerId of[`${sourceId}-fill`,`${sourceId}-line`,`${sourceId}-circle`])this._map.getLayer(layerId)&&this._map.removeLayer(layerId);this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.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{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 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"};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._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();map.setMaxBounds(bounds),bounds!==null&&(Number.isFinite(map.getZoom())||(map.setMaxBounds(null),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 zoom, 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._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["-fill","-line","-circle"]){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="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)}}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._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);if(!dataLayer)continue;const color=resolvedLayerColor(this,dataLayer.color,dataLayer.tone),stroke=resolvedLayerColor(this,dataLayer.strokeColor??dataLayer.color,dataLayer.tone);this._map.setPaintProperty(`${sourceId}-fill`,"fill-color",color),this._map.setPaintProperty(`${sourceId}-fill`,"fill-opacity",fillOpacity),this._map.setPaintProperty(`${sourceId}-line`,"line-color",stroke),this._map.setPaintProperty(`${sourceId}-circle`,"circle-color",stroke)}}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,tone}=layer,sourceId=this.resolveDataLayerSourceId(publicSourceId);warnOnUntileableProperties(geojson,publicSourceId);const existingSource=this._map.getSource(sourceId);existingSource?this.pushGeoJson(existingSource,sourceId,geojson):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojson));const 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.setPaintProperty(fillId,"fill-color",color),this._map.setPaintProperty(fillId,"fill-opacity",choroplethFillOpacity(this))):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.setPaintProperty(lineId,"line-color",stroke):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.setPaintProperty(circleId,"circle-color",stroke):this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":stroke,"circle-radius":5}}),this._appliedDataLayerIds.set(publicSourceId,sourceId)}}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)||this._map?.getLayer(`${sourceId}-fill`)||this._map?.getLayer(`${sourceId}-line`)||this._map?.getLayer(`${sourceId}-circle`));return sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){for(const layerId of[`${sourceId}-fill`,`${sourceId}-line`,`${sourceId}-circle`])this._map.getLayer(layerId)&&this._map.removeLayer(layerId);this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.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">
2
2
  <span part="legend-lo">${this.legendGradientLoLabel??this.formatCount(lo[0])}</span>
3
3
  <span
4
4
  part="legend-gradient"
@@ -121,6 +121,26 @@ export interface LyraDialogEventMap {
121
121
  * their close-reason detail as mirroring this shape. Also fired (with reason `'unmount'`,
122
122
  * non-cancelable there since the element is already being removed) when the dialog is removed
123
123
  * from the DOM while still open.
124
+ *
125
+ * **The name is not dialog-scoped, so filter by target.** `lr-close` is emitted by nine
126
+ * components in this library, several of which are commonly nested *inside* a dialog:
127
+ * `<lr-callout>` (an inline notice above a form), `<lr-tab>`/`<lr-tab-group>`,
128
+ * `<lr-command-palette>`, `<lr-document-viewer>`, `<lr-responsive-panel>`, and the three
129
+ * tool dialogs. Library events bubble and are composed, so a listener bound directly on
130
+ * `<lr-dialog>` also receives a descendant's close — and a closable callout inside a dialog would
131
+ * otherwise dismiss the whole dialog. Their details differ too (`<lr-callout>` and `<lr-tab>`
132
+ * carry none, where this event carries a `DialogCloseReason`), so a handler reading
133
+ * `event.detail.reason` would throw on a foreign one. This is latent rather than
134
+ * broken-on-arrival, because a callout or tab only emits once given a close affordance — which
135
+ * is what makes it a bad failure mode: it appears later and presents as the dialog dismissing
136
+ * itself. Guard on the target, the way `<lr-document-viewer>` already does internally:
137
+ *
138
+ * ```js
139
+ * dialog.addEventListener('lr-close', (event) => {
140
+ * if (event.target !== event.currentTarget) return; // a descendant's close, not this dialog's
141
+ * // ...
142
+ * });
143
+ * ```
124
144
  * @csspart base - Shoelace wrapper alias.
125
145
  * @csspart backdrop - The full-viewport scrim behind the panel; also carries `overlay`.
126
146
  * @csspart overlay - Shoelace alias on the backdrop.
@@ -5,7 +5,19 @@ import { type PlaceStrategy, type PlaceSync } from '../../../internal/positioner
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. */
8
- export type LyraPopupRole = 'dialog' | 'menu';
8
+ /**
9
+ * Semantic role a popover's positioned surface takes on.
10
+ *
11
+ * `'none'` is the escape hatch for the WAI-ARIA **disclosure navigation** pattern: a list of links
12
+ * is not an application action menu (`'menu'` announces "menu, menu item" and expects `menuitem`
13
+ * children) and is not an interruptive surface (`'dialog'`). Under `'none'` the popover contributes
14
+ * positioning, light dismiss, and the `aria-expanded`/`aria-controls` wiring the disclosure pattern
15
+ * requires, while the author's own `<nav>`/`<ul>` inside owns the semantics and the accessible
16
+ * name. No `role` and no generated `aria-label` are emitted, and the trigger carries no
17
+ * `aria-haspopup` -- a disclosure button does not own a popup, and `aria-haspopup="none"` is an
18
+ * invalid attribute value that axe flags as a critical violation.
19
+ */
20
+ export type LyraPopupRole = 'dialog' | 'menu' | 'none';
9
21
  export type { LyraArrowPlacement, OverlayVirtualRect };
10
22
  /** The `showAt()` rectangle, shared verbatim with `<lr-tooltip>` (see `./overlay-shared.ts`). */
11
23
  export interface LyraPopoverEventMap {
@@ -115,7 +127,10 @@ export declare class LyraPopover<Events extends LyraPopoverEventMap = LyraPopove
115
127
  * including an explicitly empty value, before this property or the localized role fallback. */
116
128
  accessibleLabel: string;
117
129
  private _popupRole;
118
- /** Semantic role used by the popup. */
130
+ /** Semantic role used by the popup. `dialog` (default) for a contextual surface, `menu` for an
131
+ * action menu, or `none` to render no role and no generated name so the slotted content owns
132
+ * its own semantics -- see `LyraPopupRole` for why a navigation disclosure needs that.
133
+ * @default 'dialog' */
119
134
  get popupRole(): LyraPopupRole;
120
135
  set popupRole(next: LyraPopupRole);
121
136
  private _disabled;
@@ -174,7 +189,8 @@ export declare class LyraPopover<Events extends LyraPopoverEventMap = LyraPopove
174
189
  * invariant even when their positioned wrapper is deliberately presentation-only. */
175
190
  protected get triggerPopupRole(): LyraPopupRole;
176
191
  /** Semantic role owned by the positioned surface. Dropdown overrides this because its contained
177
- * menu is the real role/name owner and the outer element contributes positioning chrome only. */
192
+ * menu is the real role/name owner and the outer element contributes positioning chrome only.
193
+ * `'none'` reaches the same undefined result by author request rather than by subclass. */
178
194
  protected get popupSurfaceRole(): LyraPopupRole | undefined;
179
195
  /** Resolved popup name, also available to a mapped subclass that delegates role ownership to a
180
196
  * contained semantic component. Presence-based host naming preserves an authored empty label. */
@@ -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}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;class LyraPopover extends LyraElement{constructor(){super(...arguments),this._open=!1,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.accessibleLabel="",this._popupRole="dialog",this._disabled=!1,this.resolvedSide="bottom",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=typeof this.attachInternals=="function"?this.attachInternals():void 0,this.onTriggerSlotChange=event=>{const next=event.target.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())},this.onTriggerClick=()=>{this.virtualAnchor||(this.syncTriggerA11y(),this.open?this.hide():this.show())},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get popupRole(){return this._popupRole}set popupRole(next){if(next===this._popupRole)return;const old=this._popupRole;this._popupRole=next,this.requestUpdate("popupRole",old)}get disabled(){return this._disabled}set disabled(next){const normalized=!!next;if(normalized===this._disabled)return;const old=this._disabled;this._disabled=normalized,this.requestUpdate("disabled",old),normalized&&this.open&&(this.hasUpdated?this.hide():this.open=!1)}get defaultDistance(){return DEFAULT_DISTANCE}get positioningStrategy(){return"fixed"}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return this.arrow&&!this.withoutArrow}get canOpen(){return!this.disabled}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){return path.includes(this)}onPopupPositioned(){this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1}),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),(changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole"))&&(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.positionPopup(),changed.has("open")&&(this.open?this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay()):(this.positionedAnchor=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger())),this.isConnected&&this.syncTriggerA11y())}connectedCallback(){if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.positionPopup()}}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.trigger?.removeEventListener("click",this.onTriggerClick),this.releaseTriggerA11y(),this.trigger=void 0,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.trigger){this.syncTriggerA11y();return}if(this.trigger?.removeEventListener("click",this.onTriggerClick),this.trigger=next,this.trigger&&this.trigger!==this.slottedTrigger&&this.trigger.addEventListener("click",this.onTriggerClick),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger,modal:!1,trapFocus:!1}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.trigger})}positionPopup(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.positioningStrategy,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),onPlaced:({placement,arrow})=>{const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0,becamePositioned&&this.updateComplete.then(()=>{this.open&&this.resolveAnchor()===anchor&&this.onPopupPositioned()});const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}syncTriggerA11y(){const trigger=this.trigger??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.trigger?resolveAccessibleTrigger(this.trigger):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
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}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;class LyraPopover extends LyraElement{constructor(){super(...arguments),this._open=!1,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.accessibleLabel="",this._popupRole="dialog",this._disabled=!1,this.resolvedSide="bottom",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=typeof this.attachInternals=="function"?this.attachInternals():void 0,this.onTriggerSlotChange=event=>{const next=event.target.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())},this.onTriggerClick=()=>{this.virtualAnchor||(this.syncTriggerA11y(),this.open?this.hide():this.show())},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get popupRole(){return this._popupRole}set popupRole(next){if(next===this._popupRole)return;const old=this._popupRole;this._popupRole=next,this.requestUpdate("popupRole",old)}get disabled(){return this._disabled}set disabled(next){const normalized=!!next;if(normalized===this._disabled)return;const old=this._disabled;this._disabled=normalized,this.requestUpdate("disabled",old),normalized&&this.open&&(this.hasUpdated?this.hide():this.open=!1)}get defaultDistance(){return DEFAULT_DISTANCE}get positioningStrategy(){return"fixed"}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole==="none"?void 0:this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return this.arrow&&!this.withoutArrow}get canOpen(){return!this.disabled}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){return path.includes(this)}onPopupPositioned(){this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1}),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),(changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole"))&&(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.positionPopup(),changed.has("open")&&(this.open?this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay()):(this.positionedAnchor=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger())),this.isConnected&&this.syncTriggerA11y())}connectedCallback(){if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.positionPopup()}}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.trigger?.removeEventListener("click",this.onTriggerClick),this.releaseTriggerA11y(),this.trigger=void 0,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.trigger){this.syncTriggerA11y();return}if(this.trigger?.removeEventListener("click",this.onTriggerClick),this.trigger=next,this.trigger&&this.trigger!==this.slottedTrigger&&this.trigger.addEventListener("click",this.onTriggerClick),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger,modal:!1,trapFocus:!1}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.trigger})}positionPopup(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.positioningStrategy,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),onPlaced:({placement,arrow})=>{const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0,becamePositioned&&this.updateComplete.then(()=>{this.open&&this.resolveAnchor()===anchor&&this.onPopupPositioned()});const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}syncTriggerA11y(){const trigger=this.trigger??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole==="none"?null:this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.trigger?resolveAccessibleTrigger(this.trigger):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
2
2
  <span part="trigger" @click=${this.onTriggerClick} @keydown=${this.onTriggerKeyDown}>
3
3
  <slot name="trigger" @slotchange=${this.onTriggerSlotChange}></slot>
4
4
  </span>
@@ -1,5 +1,5 @@
1
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}from"lit/decorators.js";import{ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedSelectionRects,boundedSelectionText,normalizeQuoteText,scopeFromItems,buildQuoteAnchor,createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{loadPdfJs}from"./pdf-loader.js";import{styles}from"./pdf-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_pdfViewerLabel,LYRA_DEFAULT_pdfViewerMissingLibrary,LYRA_DEFAULT_pdfViewerNextPage,LYRA_DEFAULT_pdfViewerPageOf,LYRA_DEFAULT_pdfViewerPreviousPage,LYRA_DEFAULT_pdfViewerZoomIn,LYRA_DEFAULT_pdfViewerZoomOut}from"../../../internal/default-strings.generated.js";const MIN_ZOOM=.25,MAX_ZOOM=4,ZOOM_STEP=.25,PAGE_TEXT_CACHE_LIMIT=64,PAGE_SEARCH_INDEX_CACHE_LIMIT=8,DEFAULT_THUMBNAIL_WIDTH=96,MAX_THUMBNAIL_WIDTH=2048,MAX_PAGE_COUNT=1e5,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_SEARCH_MATCHES=200,MAX_PAINTED_SEARCH_MARKS=200,MAX_PAINTED_HIGHLIGHTS=100,MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS=1e3,MAX_HIGHLIGHT_RECTS=1e3,MAX_SEARCH_PAGES=1e3,MAX_OUTLINE_ITEMS=1e4,MAX_OUTLINE_DEPTH=100,MAX_PDF_TEXT_CHUNKS=TEXT_QUOTE_LIMITS.maxNodes;function isReadablePdfTextStream(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"getReader"in value&&typeof value.getReader=="function"}function appendPdfTextItems(items,accumulator){if(Array.isArray(items))for(let index=0;index<items.length;index++){if(accumulator.inspectedItems>=TEXT_QUOTE_LIMITS.maxNodes){accumulator.truncated=!0;return}accumulator.inspectedItems++;const item=items[index],value=item&&typeof item=="object"&&"str"in item&&typeof item.str=="string"?item.str:"",separator=item&&typeof item=="object"&&"hasEOL"in item&&item.hasEOL===!0?`
2
- `:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length;if(remaining<=0){accumulator.truncated=!0;return}const retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[],fontNames=new Set;let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),typeof record.fontName=="string"&&fontNames.add(record.fontName),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length),"fontName"in item&&typeof item.fontName=="string"&&fontNames.add(item.fontName)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const fontName of fontNames)Object.prototype.hasOwnProperty.call(sourceStyles,fontName)&&(styles2[fontName]=sourceStyles[fontName])}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function nextPdfPaintNode(node,root){if(node.firstChild)return node.firstChild;let cursor=node;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;if(!doc||budget.marks<=0)return[];const textNodeType=doc.defaultView?.Node.TEXT_NODE??3;if(range.startContainer===range.endContainer&&range.startContainer.nodeType===textNodeType){const textNode=range.startContainer;if(budget.traversalNodes<=0||budget.codeUnits<=0)return[];const inspectedLength=textNode.data.length;if(inspectedLength>budget.codeUnits)return budget.codeUnits=0,[];budget.traversalNodes--,budget.codeUnits-=inspectedLength;let target=textNode;if(range.endOffset<target.data.length&&target.splitText(range.endOffset),range.startOffset>0&&(target=target.splitText(range.startOffset)),!target.data)return[];const mark=doc.createElement("mark");return mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),budget.marks--,[mark]}const ancestor=range.commonAncestorContainer,covered=[];let node=ancestor;for(;node&&budget.traversalNodes>0&&budget.codeUnits>0;){if(budget.traversalNodes--,node.nodeType===textNodeType){const textNode=node;if(textNode.data.length>budget.codeUnits){budget.codeUnits=0;break}budget.codeUnits-=textNode.data.length;try{if(textNode.data.length>0&&range.intersectsNode(textNode)){if(covered.length>=budget.marks)return[];covered.push(textNode)}}catch{return[]}}node=nextPdfPaintNode(node,ancestor)}if(node)return[];const marks=[];for(const textNode of covered){const start=textNode===range.startContainer?range.startOffset:0,end=textNode===range.endContainer?range.endOffset:textNode.data.length;let target=textNode;if(end<target.data.length&&target.splitText(end),start>0&&(target=target.splitText(start)),!target.data)continue;const mark=doc.createElement("mark");mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),marks.push(mark)}return budget.marks-=marks.length,marks}function unwrapPdfSearchMark(mark){const parent=mark.parentNode;if(!parent)return;const textNodeType=mark.ownerDocument.defaultView?.Node.TEXT_NODE??3,before=mark.previousSibling,after=mark.nextSibling,first=mark.firstChild;for(;mark.firstChild;)parent.insertBefore(mark.firstChild,mark);if(parent.removeChild(mark),before?.nodeType===textNodeType&&first?.nodeType===textNodeType){before.appendData(first.data),first.parentNode?.removeChild(first),after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after));return}first?.nodeType===textNodeType&&after?.nodeType===textNodeType?(first.appendData(after.data),after.parentNode?.removeChild(after)):!first&&before?.nodeType===textNodeType&&after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after))}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerIdentity=0,this.pageViewerSnapshotValue=Object.freeze({identity:0,status:"idle",page:1,pageCount:0}),this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
2
+ `:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length;if(remaining<=0){accumulator.truncated=!0;return}const retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function nextPdfPaintNode(node,root){if(node.firstChild)return node.firstChild;let cursor=node;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;if(!doc||budget.marks<=0)return[];const textNodeType=doc.defaultView?.Node.TEXT_NODE??3;if(range.startContainer===range.endContainer&&range.startContainer.nodeType===textNodeType){const textNode=range.startContainer;if(budget.traversalNodes<=0||budget.codeUnits<=0)return[];const inspectedLength=textNode.data.length;if(inspectedLength>budget.codeUnits)return budget.codeUnits=0,[];budget.traversalNodes--,budget.codeUnits-=inspectedLength;let target=textNode;if(range.endOffset<target.data.length&&target.splitText(range.endOffset),range.startOffset>0&&(target=target.splitText(range.startOffset)),!target.data)return[];const mark=doc.createElement("mark");return mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),budget.marks--,[mark]}const ancestor=range.commonAncestorContainer,covered=[];let node=ancestor;for(;node&&budget.traversalNodes>0&&budget.codeUnits>0;){if(budget.traversalNodes--,node.nodeType===textNodeType){const textNode=node;if(textNode.data.length>budget.codeUnits){budget.codeUnits=0;break}budget.codeUnits-=textNode.data.length;try{if(textNode.data.length>0&&range.intersectsNode(textNode)){if(covered.length>=budget.marks)return[];covered.push(textNode)}}catch{return[]}}node=nextPdfPaintNode(node,ancestor)}if(node)return[];const marks=[];for(const textNode of covered){const start=textNode===range.startContainer?range.startOffset:0,end=textNode===range.endContainer?range.endOffset:textNode.data.length;let target=textNode;if(end<target.data.length&&target.splitText(end),start>0&&(target=target.splitText(start)),!target.data)continue;const mark=doc.createElement("mark");mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),marks.push(mark)}return budget.marks-=marks.length,marks}function unwrapPdfSearchMark(mark){const parent=mark.parentNode;if(!parent)return;const textNodeType=mark.ownerDocument.defaultView?.Node.TEXT_NODE??3,before=mark.previousSibling,after=mark.nextSibling,first=mark.firstChild;for(;mark.firstChild;)parent.insertBefore(mark.firstChild,mark);if(parent.removeChild(mark),before?.nodeType===textNodeType&&first?.nodeType===textNodeType){before.appendData(first.data),first.parentNode?.removeChild(first),after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after));return}first?.nodeType===textNodeType&&after?.nodeType===textNodeType?(first.appendData(after.data),after.parentNode?.removeChild(after)):!first&&before?.nodeType===textNodeType&&after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after))}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerIdentity=0,this.pageViewerSnapshotValue=Object.freeze({identity:0,status:"idle",page:1,pageCount:0}),this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
3
3
  <canvas part="page-canvas" ${ref(this.pageCanvasRef(number))}></canvas>
4
4
  <div part="page-error" hidden></div>
5
5
  <lr-highlight-layer