@aceshooting/lyra-ui 25.0.0 → 25.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/custom-elements.json +1 -1
- package/dist/components/conversation/code-block/shiki-dark-theme.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +7 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +5 -2
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +5 -0
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +6 -4
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-combobox.md +3 -2
- package/llms/components/lr-tour.md +4 -2
- package/package.json +1 -1
- package/web-types.json +1 -1
|
@@ -17,7 +17,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
17
17
|
@click=${()=>this.toggleLegendPanel()}
|
|
18
18
|
><span part="legend-disclosure-icon" class="legend-disclosure-icon" aria-hidden="true"
|
|
19
19
|
>${chevronIcon()}</span
|
|
20
|
-
><span>${this.localize("mapLegend")}</span></button>`:nothing}get hiddenCategories(){return this._hiddenCategories}set hiddenCategories(value){const previous=this._hiddenCategories;this._hiddenCategories=normalizeMapHiddenCategories(value),this.requestUpdate("hiddenCategories",previous)}get canonicalChoropleth(){const source=this.choropleth;return Object.is(source,this._canonicalChoroplethSource)?this._canonicalChoropleth:(this._canonicalChoroplethSource=source,this._canonicalChoropleth=projectMapChoropleth(source),this._canonicalChoropleth)}get canonicalDataLayers(){const source=this.dataLayers;return Object.is(source,this._canonicalDataLayersSource)?this._canonicalDataLayers:(this._canonicalDataLayersSource=source,this._canonicalDataLayers=projectMapDataLayers(source),this._canonicalDataLayers)}get canonicalMarkers(){const source=this.markers;return Object.is(source,this._canonicalMarkersSource)?this._canonicalMarkers:(this._canonicalMarkersSource=source,this._canonicalMarkers=projectMapMarkers(source),this._canonicalMarkers)}get map(){return this._map}pushGeoJson(source,resolvedSourceId,geojson,projection=projectGeoJson(geojson)){const previous=this._appliedGeoJson.get(resolvedSourceId),diff=typeof source.updateData=="function"&&previous!==void 0?buildProjectedGeoJsonPropertyDiff(previous,projection):null;diff===null||typeof source.updateData!="function"?source.setData(geojson):(diff.update.length>0||diff.add?.length||diff.remove?.length)&&source.updateData(diff),this._appliedGeoJson.set(resolvedSourceId,projection)}get safeMaxBounds(){const bounds=this.maxBounds;if(!Array.isArray(bounds)||bounds.length!==2)return null;const[southWest,northEast]=bounds;if(!Array.isArray(southWest)||!Array.isArray(northEast))return null;const[west,south]=southWest,[east,north]=northEast,values=[west,south,east,north].map(Number);if(!values.every(value=>Number.isFinite(value)))return null;const[w,s,e,n]=values;return w>=e||s>=n||w<-180||e>180||s<-90||n>90?null:[[w,s],[e,n]]}applyMaxBounds(){const map=this._map;if(!map||typeof map.setMaxBounds!="function")return;const bounds=this.safeMaxBounds;let zoomBefore,centerBefore;try{if(zoomBefore=map.getZoom(),centerBefore=map.getCenter(),map.setMaxBounds(bounds),bounds===null||Number.isFinite(map.getZoom()))return}catch{}try{map.setMaxBounds(null)}catch{}typeof zoomBefore=="number"&&Number.isFinite(zoomBefore)&&map.setZoom(zoomBefore),centerBefore&&map.setCenter([centerBefore.lng,centerBefore.lat]),devWarnOnce("lyra-map-max-bounds-rejected","<lr-map>: maxBounds left maplibre-gl without a usable camera, so it was dropped and the camera restored. This is a peer limitation, not a bad value -- it shows up at sub-1 fractional zooms in wide containers. Raise the zoom, narrow the box, or leave maxBounds unset.")}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)]}fitBounds(bounds,options={}){const box=normalizeFitBounds(bounds);if(!box)return devWarnOnce("lyra-map-fit-bounds-rejected",`<${this.localName}>: fitBounds() ignored a box that is not [[west, south], [east, north]] with finite coordinates, latitudes in [-90, 90], south <= north, and longitudes in [-180, 180] (east may run past 180, up to one full turn east of west, for a box crossing the antimeridian).`),!1;const settings=typeof options=="object"&&options!==null?options:{},maxZoom=settings.maxZoom,fit=Object.freeze({bounds:box,padding:normalizeFitPadding(settings.padding),maxZoom:isFiniteCoordinate(maxZoom)?finiteRange(maxZoom,22,0,22):void 0,animate:settings.animate!==!1}),map=this._map;return map?(this.pendingFit=void 0,this.applyFit(map,fit,fit.animate&&!prefersReducedMotion(this))):(this.pendingFit=Object.freeze({fit,center:snapshotCenter(this.center),zoom:this.zoom}),!0)}applyFit(map,fit,animate){if(typeof map.fitBounds!="function")return!1;const[[west,south],[east,north]]=fit.bounds;try{map.fitBounds([[west,south],[east,north]],{padding:{...fit.padding},...fit.maxZoom===void 0?{}:{maxZoom:fit.maxZoom},animate},{[FIT_EVENT_KEY]:this.fitToken})}catch{return!1}return!0}applyPendingFit(){const map=this._map,pending=this.pendingFit;!map||!pending||(this.pendingFit=void 0,!(!sameCenterValue(this.center,pending.center)||!Object.is(this.zoom,pending.zoom))&&this.applyFit(map,pending.fit,!1))}reflectCamera(map,source){const camera=readPeerCamera(map);if(!camera)return;const center=Object.freeze(camera.center),{zoom}=camera;this.reflectedCamera={center,zoom},this.center=center,this.zoom=zoom,this.emit("lr-map-view-change",{center,zoom,source})}pushCamera(changed){const reflected=this.reflectedCamera;this.reflectedCamera=void 0;const map=this._map;if(!map||!changed.has("center")&&!changed.has("zoom"))return;const center=this.safeCenter,zoom=this.safeZoom,shown=readPeerCamera(map),showsCenter=camera=>camera!==void 0&¢er[0]===camera.center[0]&¢er[1]===camera.center[1];let pushCenter=changed.has("center")&&!showsCenter(reflected)&&!showsCenter(shown),pushZoom=changed.has("zoom")&&zoom!==reflected?.zoom&&zoom!==shown?.zoom;if(!pushCenter&&!pushZoom)return;let interrupting=!1;try{interrupting=map.isMoving?.()===!0}catch{}interrupting&&(pushCenter=!showsCenter(shown),pushZoom=zoom!==shown?.zoom),this.writeCamera(()=>{pushCenter&&map.setCenter(center),pushZoom&&map.setZoom(zoom)})}writeCamera(write){const previous=this.writingCamera;this.writingCamera=!0;try{write()}finally{this.writingCamera=previous}}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(),this.releaseLegendAnnouncementSink(),super.disconnectedCallback(),this.disposeMap(),this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0;for(const marker of this._markerInstances.values()){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove()}this._markerInstances.clear(),this._markerColors.clear(),this._markerLabels.clear(),this._markerPopupIds.clear()}failureMessage(reason=this.failure??"initialization-failed"){switch(reason){case"missing-peer":return this.localize("mapMissingLibrary");case"style-required":return this.localize("mapStyleRequired");case"webgl-unavailable":return this.localize("mapWebglUnavailable");case"initialization-failed":return this.localize("mapInitializationFailed")}}failInitialization(reason,partialMap){try{partialMap?.remove()}catch{}this.disposeMap(),this.loading=!1,this.failure=reason,this.errorAnnouncementSink?.announce(this.failureMessage(reason))}disposeMap(){this.stopObservingMapAllocation(),this.stopObservingPeerChrome();try{this._map?.remove()}catch{}this._map=void 0,this._styleLoaded=!1,this.boxZoomSettling=!1,this.reflectedCamera=void 0,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this.appliedPointIcons.clear(),this.appliedPointPaint.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear()}adoptedCallback(){super.adoptedCallback(),this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.releaseLegendAnnouncementSink(),this._map&&this.containerEl&&this.isConnected&&this.observeMapAllocation(this._map,this.containerEl)}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}tryConstructMap(){if(this._map||!this._maplibreModule||!this._webglReady||!this.containerEl||!this.visible||!this.isConnected)return;if(!hasMapStyle(this.mapStyle)){this.failInitialization("style-required");return}const mod=this._maplibreModule;let candidate;try{candidate=new mod.Map({container:this.containerEl,style:this.mapStyle,center:this.safeCenter,zoom:this.safeZoom,...typeof this.renderWorldCopies=="boolean"?{renderWorldCopies:this.renderWorldCopies}:{},locale:{"Map.Title":this.effectiveMapLabel,"Marker.Title":this.localize("map"),"Popup.Close":this.localize("close"),"NavigationControl.ZoomIn":this.localize("zoomIn"),"NavigationControl.ZoomOut":this.localize("zoomOut"),"NavigationControl.ResetBearing":this.localize("mapResetNorth")}}),candidate.on("error",event=>{if(this._map===candidate&&!this._styleLoaded){this.failInitialization("initialization-failed");return}console.error("lr-map:",event.error??event)}),candidate.on("load",()=>{if(this._map===candidate)try{this._styleLoaded=!0,this.applyChoropleth(),this.applyMarkers(),this.applyDataLayers(),this.emit("lr-map-load")}catch{this.failInitialization("initialization-failed")}}),candidate.on("click",event=>{if(this._map!==candidate)return;const fillLayerId=this._appliedFillLayerId,layerIds=[];fillLayerId&&candidate.getLayer(fillLayerId)&&layerIds.push(fillLayerId);for(const resolvedSourceId of this._appliedDataLayerIds.values())for(const suffix of QUERYABLE_DATA_LAYER_SUFFIXES){const layerId=`${resolvedSourceId}${suffix}`;candidate.getLayer(layerId)&&layerIds.push(layerId)}const hit=(layerIds.length?candidate.queryRenderedFeatures(event.point,{layers:layerIds}):[])[0],hitLayerId=hit?.layer?.id;let origin,sourceId;if(hitLayerId!==void 0){if(hitLayerId===fillLayerId)origin="choropleth";else for(const[publicSourceId,resolvedSourceId]of this._appliedDataLayerIds)if(hitLayerId.startsWith(`${resolvedSourceId}-`)){origin=hitLayerId===`${resolvedSourceId}-cluster`?"cluster":"data-layer",sourceId=publicSourceId;break}}this.emit("lr-map-click",{lngLat:[event.lngLat.lng,event.lngLat.lat],feature:hit,origin,sourceId})}),candidate.on("boxzoomend",()=>{this._map===candidate&&(this.boxZoomSettling=!0)}),candidate.on("moveend",event=>{if(this._map!==candidate)return;const fit=event?.[FIT_EVENT_KEY]===this.fitToken,afterBoxZoom=!fit&&this.boxZoomSettling;if(fit||(this.boxZoomSettling=!1),this.writingCamera)return;const source=fit?"fit":event?.originalEvent||afterBoxZoom?"user":void 0;source&&this.reflectCamera(candidate,source)});const canvas=candidate.getCanvas?.();canvas&¬ifyMapCanvasReady(this,canvas),this._map=candidate,this.observeMapAllocation(candidate,this.containerEl),this.observePeerChrome(),this.failure=void 0}catch{this.failInitialization("initialization-failed",candidate);return}this.applyMaxBounds(),this.pendingFit&&this.scheduleAfterUpdate(()=>this.applyPendingFit(),"map-pending-fit")}updated(changed){if(super.updated(changed),this.setAttribute("aria-busy",String(this.loading)),this.legendCollapsed&&(changed.has("legendOpen")||changed.has("legendCollapsible"))){const legend=this.shadowRoot?.querySelector('[part="legend"]');legend&&(legend.scrollTop=0)}if((changed.has("choropleth")||changed.has("legendGradient"))&&this.warnOnLegendChoroplethMismatch(),changed.has("visible")&&this.visible&&this.tryConstructMap(),changed.has("mapStyle")&&(this._styleGeneration+=1),changed.has("mapStyle")&&!hasMapStyle(this.mapStyle)&&this._maplibreModule){const generation=this._connectGeneration,module=this._maplibreModule;this.scheduleAfterUpdate(()=>{!this.isConnected||generation!==this._connectGeneration||module!==this._maplibreModule||hasMapStyle(this.mapStyle)||this.failInitialization("style-required")},"map-style-required")}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,style=this.mapStyle,generation=this._connectGeneration,styleGeneration=this._styleGeneration,current=()=>this.isConnected&&this._map===map&&generation===this._connectGeneration&&styleGeneration===this._styleGeneration&&this.mapStyle===style,failStyle=()=>{current()&&this.scheduleAfterUpdate(()=>{current()&&this.failInitialization("initialization-failed")},`map-style-failure-${styleGeneration}`)};try{for(const sourceId of this.appliedPointIcons.keys())this.removePointIcons(sourceId);map.once("style.load",()=>{if(current())try{this._styleLoaded=!0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this.appliedPointPaint.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear(),this.applyChoropleth(),this.applyDataLayers()}catch{failStyle()}}),map.setStyle(style)}catch{failStyle()}}else if(this._styleLoaded&&(changed.has("dataLayers")||changed.has("choropleth"))){const choropleth=this.canonicalChoropleth,nextChoroplethSourceId=choropleth?this.resolveChoroplethSourceId(choropleth.sourceId):void 0;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==nextChoroplethSourceId&&this.removeChoropleth(),changed.has("dataLayers")&&this.applyDataLayers(),this.applyChoropleth()}changed.has("hiddenCategories")&&this._map&&this._styleLoaded&&this.refreshThemePaint(),this.pushCamera(changed),changed.has("maxBounds")&&this._map&&this.writeCamera(()=>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);if(this._appliedFillLayerId){const choropleth=this.canonicalChoropleth;choropleth&&choropleth.stops.length>0&&this._map.setPaintProperty(this._appliedFillLayerId,"fill-color",this.choroplethColorExpression(choropleth)),this._map.setPaintProperty(this._appliedFillLayerId,"fill-opacity",fillOpacity)}const dataLayersBySourceId=new Map(this.canonicalDataLayers.map(layer=>[layer.sourceId,layer]));for(const[publicSourceId,sourceId]of this._appliedDataLayerIds){const dataLayer=dataLayersBySourceId.get(publicSourceId);dataLayer&&this.paintDataLayer(sourceId,dataLayer)}}applyChoropleth(){if(!this._map)return;const choropleth=this.canonicalChoropleth;if(!choropleth){this.removeChoropleth();return}const{geojson,geojsonProjection,stops}=choropleth,sourceId=this.resolveChoroplethSourceId(choropleth.sourceId),fillLayerId=`${sourceId}-fill`;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==sourceId&&this.removeChoropleth(),warnOnUntileableProperties(geojsonProjection,"choropleth");const existingSource=this._map.getSource(sourceId);if(existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojsonProjection)),this._appliedChoroplethSourceId=sourceId,stops.length===0)return;const colorExpr=this.choroplethColorExpression(choropleth);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}choroplethColorExpression(choropleth){const{field,stops}=choropleth,resolvedStops=stops.map(([value,color])=>[value,resolvedLayerColor(this,color,void 0)]);let colorExpr;if(choropleth.interpolation==="step"){const base=choropleth.stepBaseColor?resolvedLayerColor(this,choropleth.stepBaseColor,void 0):resolvedStops[0][1];colorExpr=["step",["get",field],base];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}else{colorExpr=["interpolate",choropleth.interpolation==="logarithmic"?["exponential",CHOROPLETH_LOG_INTERPOLATION_BASE]:["linear"],["get",field]];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}return colorExpr}resolveChoroplethSourceId(sourceId){const dataSourceIds=new Set(this.canonicalDataLayers.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=this.canonicalDataLayers,nextIds=new Set(layers.map(layer=>layer.sourceId));for(const publicSourceId of this._appliedDataLayerIds.keys())nextIds.has(publicSourceId)||this.removeDataLayer(publicSourceId);for(const layer of layers){const{sourceId:publicSourceId,geojson,geojsonProjection}=layer,shape=dataLayerShape(layer),appliedShape=this._appliedDataLayerShapes.get(publicSourceId);appliedShape!==void 0&&appliedShape!==shape&&this.removeDataLayer(publicSourceId);const sourceId=this.resolveDataLayerSourceId(publicSourceId);warnOnUntileableProperties(geojsonProjection,publicSourceId);const cluster=layer.cluster,existingSource=this._map.getSource(sourceId);existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}}),this._appliedGeoJson.set(sourceId,geojsonProjection)),this.applyDataLayerRendering(sourceId,layer),this._appliedDataLayerIds.set(publicSourceId,sourceId),this._appliedDataLayerShapes.set(publicSourceId,shape)}}applyDataLayerRendering(sourceId,layer){if(layer.kind==="heatmap"){this.applyHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;cluster?this.applyClusterLayers(sourceId,layer,cluster):this.applyGeometryLayers(sourceId,layer),this.applyPointIcons(sourceId,layer)}paintDataLayer(sourceId,layer){if(layer.kind==="heatmap"){this.paintHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;cluster?this.paintClusterLayers(sourceId,layer,cluster):this.paintGeometryLayers(sourceId,layer),this.paintPointIcons(sourceId,layer)}applyGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)||this._map.addLayer({id:fillId,type:"fill",source:sourceId,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":color,"fill-opacity":choroplethFillOpacity(this)}}),this._map.getLayer(lineId)||this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":this.lineColor(layer),"line-width":layer.line?.width??2,...layer.line?{"line-opacity":layer.line.opacity}:{}}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":stroke,"circle-radius":5}}),this._map.setPaintProperty(lineId,"line-width",layer.line?.width??2),this._map.setPaintProperty(lineId,"line-opacity",layer.line?.opacity??1),this.paintGeometryLayers(sourceId,layer)}paintGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone);this._map.setPaintProperty(`${sourceId}-fill`,"fill-color",color),this._map.setPaintProperty(`${sourceId}-fill`,"fill-opacity",choroplethFillOpacity(this)),this._map.setPaintProperty(`${sourceId}-line`,"line-color",this.lineColor(layer)),this.paintPoints(sourceId,layer)}lineColor(layer){const fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),line=layer.line;return!line?.field||line.stops.length<2?fallback:lineColorExpression(line.field,line.stops.map(([value,color])=>[value,resolvedLayerColor(this,color,layer.tone)]),fallback)}mutedPointOpacity(layerId,field){const muted=field?this.hiddenCategories:EMPTY_HIDDEN_CATEGORIES;if(!muted.length)return this.appliedPointMuting.delete(layerId)?1:void 0;this.appliedPointMuting.add(layerId);const dim=hiddenCategoryOpacity(this);return mutedCategoryOpacityExpression(field,muted,dim)}paintPoints(sourceId,layer){if(!this._map)return;const point=layer.point,fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),color=pointColorExpression(point?.field,point?.field&&point.colors.length?point.colors.map(([value,paint])=>[value,resolvedLayerColor(this,paint,layer.tone)]):[],fallback),id=`${sourceId}-circle`;this._map.setPaintProperty(id,"circle-color",color);const opacity=this.mutedPointOpacity(id,point?.field);opacity!==void 0&&(this._map.setPaintProperty(id,"circle-opacity",opacity),this._map.setPaintProperty(id,"circle-stroke-opacity",opacity)),!(!point&&!this.appliedPointPaint.has(sourceId))&&(this._map.setPaintProperty(id,"circle-radius",pointRadiusExpression(point?.radius??5)),this._map.setPaintProperty(id,"circle-stroke-width",point?.strokeWidth??0),this._map.setPaintProperty(id,"circle-stroke-color",point?.strokeColor?resolvedLayerColor(this,point.strokeColor,layer.tone):fallback),point?this.appliedPointPaint.add(sourceId):this.appliedPointPaint.delete(sourceId))}pointIconColor(layer){const resolved=resolvedLayerColor(this,layer.point?.iconColor??`var(${ON_TONE_TOKEN[layer.tone??"accent"]})`,layer.tone);return resolveCanvasColor(this,resolved,dataLayerColor(this,layer.tone))}removePointIcons(sourceId){const applied=this.appliedPointIcons.get(sourceId);if(!applied||!this._map)return;const id=`${sourceId}-point-icon`;this._map.getLayer(id)&&this._map.removeLayer(id);for(const{id:imageId}of applied.icons)this._map.hasImage?.(imageId)&&this._map.removeImage?.(imageId);this.appliedPointIcons.delete(sourceId),this.appliedPointMuting.delete(id)}applyPointIcons(sourceId,layer){const map=this._map,point=layer.point,signature=JSON.stringify([point?.iconField,point?.iconSize,point?.icons]);if(this.appliedPointIcons.get(sourceId)?.signature===signature){this.paintPointIcons(sourceId,layer);return}if(this.removePointIcons(sourceId),!point?.iconField||!point.icons.length||!map||typeof map.addImage!="function"||typeof map.hasImage!="function"||typeof map.updateImage!="function"||typeof map.removeImage!="function")return;const color=this.pointIconColor(layer),icons=[];this.appliedPointIcons.set(sourceId,{signature,color,icons});for(const icon of point.icons){const raster=rasterPointIcon(this,icon,color);if(!raster)continue;let id;do id=`lr-point-icon-${this.nextPointIconId++}`;while(map.hasImage(id));icons.push({id,icon}),map.addImage(id,raster,{pixelRatio:2})}icons.length&&map.addLayer({id:`${sourceId}-point-icon`,type:"symbol",source:sourceId,filter:layer.cluster?["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]]:["==",["geometry-type"],"Point"],layout:{"icon-image":["match",["get",point.iconField],...icons.flatMap(({id,icon})=>[icon.value,id]),""],"icon-size":point.iconSize/(POINT_ICON_RASTER_SIZE/2),"icon-allow-overlap":!0,"icon-ignore-placement":!0}})}paintPointIcons(sourceId,layer){const applied=this.appliedPointIcons.get(sourceId);if(!applied)return;const iconLayerId=`${sourceId}-point-icon`,opacity=this.mutedPointOpacity(iconLayerId,layer.point?.iconField);opacity!==void 0&&this._map?.setPaintProperty(iconLayerId,"icon-opacity",opacity);const color=this.pointIconColor(layer);if(color!==applied.color){for(const{id,icon}of applied.icons){const raster=rasterPointIcon(this,icon,color);raster&&this._map?.updateImage?.(id,raster)}applied.color=color}}clusterColorExpression(layer,cluster){const tone=layer.tone;return clusterColorExpression(cluster.colorSteps.map(([count,stepColor])=>[count,resolvedLayerColor(this,stepColor,tone)]),()=>resolvedLayerColor(this,layer.color,tone))}applyClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`,countId=`${sourceId}-cluster-count`,circleId=`${sourceId}-circle`,clusterColor=this.clusterColorExpression(layer,cluster),clusterRadius=stepExpression(["get","point_count"],cluster.radiusSteps),countColor=resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone);this._map.getLayer(clusterId)||this._map.addLayer({id:clusterId,type:"circle",source:sourceId,filter:["has","point_count"],paint:{"circle-color":clusterColor,"circle-radius":clusterRadius,"circle-stroke-width":1,"circle-stroke-color":stroke}}),this.styleProvidesGlyphs()&&!this._map.getLayer(countId)&&this._map.addLayer({id:countId,type:"symbol",source:sourceId,filter:["has","point_count"],layout:{"text-field":["get","point_count_abbreviated"],"text-size":12,...cluster.countFont?{"text-font":[...cluster.countFont]}:{}},paint:{"text-color":countColor}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]],paint:{"circle-color":stroke,"circle-radius":5}}),this.paintClusterLayers(sourceId,layer,cluster)}paintClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`;this._map.setPaintProperty(clusterId,"circle-color",this.clusterColorExpression(layer,cluster)),this._map.setPaintProperty(clusterId,"circle-radius",stepExpression(["get","point_count"],cluster.radiusSteps)),this._map.setPaintProperty(clusterId,"circle-stroke-color",stroke),this.styleProvidesGlyphs()&&this._map.setPaintProperty(`${sourceId}-cluster-count`,"text-color",resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone)),this.paintPoints(sourceId,layer)}applyHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`,options=layer.heatmap,weight=heatmapWeightExpression(options),color=this.heatmapColorExpression(layer),radius=heatmapZoomValue(options?.radius,DEFAULT_HEATMAP_RADIUS,1,200),intensity=heatmapZoomValue(options?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100),opacity=finiteRange(options?.opacity??Number.NaN,1,0,1);if(!this._map.getLayer(heatmapId)){this._map.addLayer({id:heatmapId,type:"heatmap",source:sourceId,paint:{...weight?{"heatmap-weight":weight}:{},"heatmap-intensity":intensity,"heatmap-color":color,"heatmap-radius":radius,...options?.opacity===void 0?{}:{"heatmap-opacity":opacity}}});return}this.paintHeatmapLayer(sourceId,layer)}paintHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`;this._map.setPaintProperty(heatmapId,"heatmap-weight",heatmapWeightExpression(layer.heatmap)??1),this._map.setPaintProperty(heatmapId,"heatmap-intensity",heatmapZoomValue(layer.heatmap?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100)),this._map.setPaintProperty(heatmapId,"heatmap-color",this.heatmapColorExpression(layer)),this._map.setPaintProperty(heatmapId,"heatmap-radius",heatmapZoomValue(layer.heatmap?.radius,DEFAULT_HEATMAP_RADIUS,1,200)),this._map.setPaintProperty(heatmapId,"heatmap-opacity",finiteRange(layer.heatmap?.opacity??Number.NaN,1,0,1))}heatmapColorExpression(layer){const tone=layer.tone,authored=(layer.heatmap?.stops??[]).map(([density,color])=>[density,resolvedLayerColor(this,color,tone)]);return heatmapColorExpression(authored,()=>HEATMAP_RAMP_TOKENS.map(([density,token])=>[density,resolvedLayerColor(this,`var(${token})`,tone)]))}styleProvidesGlyphs(){try{const liveGlyphs=this._map?.getStyle?.()?.glyphs;if(typeof liveGlyphs=="string"&&liveGlyphs.trim().length>0)return!0}catch{}const declared=this.mapStyle,declaredGlyphs=declared&&typeof declared=="object"?declared.glyphs:void 0;return typeof declaredGlyphs=="string"&&declaredGlyphs.trim().length>0}resolveDataLayerSourceId(publicSourceId){const applied=this._appliedDataLayerIds.get(publicSourceId);if(applied)return applied;let sourceId;do sourceId=`lr-data-layer-${this._nextDataLayerId++}`;while(this._map?.getSource(sourceId)||DATA_LAYER_SUFFIXES.some(suffix=>this._map?.getLayer(`${sourceId}${suffix}`)));return sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){this.removePointIcons(sourceId),this.appliedPointPaint.delete(sourceId);for(const suffix of DATA_LAYER_SUFFIXES){const layerId=`${sourceId}${suffix}`;this.appliedPointMuting.delete(layerId),this._map.getLayer(layerId)&&this._map.removeLayer(layerId)}this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.delete(publicSourceId),this._appliedDataLayerShapes.delete(publicSourceId),this._appliedGeoJson.delete(sourceId)}}applyMarkers(){const map=this._map,mod=this._maplibreModule;if(!map||!mod)return;const visible=new Set,coordCounts=new Map,explicitIds=new Set;for(const m of this.canonicalMarkers){const lngLat=m.lngLat,mapLngLat=[lngLat[0],lngLat[1]];let key,id;if(m.id!==void 0){if(id=m.id,explicitIds.has(id))continue;explicitIds.add(id),key=`id:${id}`}else{const coordKey=`${lngLat[0]},${lngLat[1]}`,occurrence=coordCounts.get(coordKey)??0;coordCounts.set(coordKey,occurrence+1),key=`coordinate:${coordKey}#${occurrence}`}visible.add(key);let existing=this._markerInstances.get(key);const markerColor=sanitizeCssColor(m.color)??(m.color===void 0?dataLayerColor(this,"accent"):void 0);if(existing&&this._markerColors.get(key)!==markerColor){const existingElement=existing.getElement?.();existingElement&&this.markerActivationDetails.delete(existingElement),existing.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),existing=void 0}if(existing){existing.setLngLat(mapLngLat);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(mapLngLat);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()||markerPopupText(this,m.unsafeHtml);this._markerLabels.set(key,markerLabel||void 0);const markerElement=this._markerInstances.get(key)?.getElement?.();if(markerElement){addPartToken(markerElement,"marker"),markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const currentMarker=this._markerInstances.get(key);this.configureMarkerInteraction(markerElement,{id,lngLat,marker:m});const popup=currentMarker?.getPopup();popup&¤tMarker?(this.configurePopupSemantics(key,currentMarker,popup),this.syncPopupSemantics(key,currentMarker,popup)):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}}for(const[key,marker]of this._markerInstances)if(!visible.has(key)){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),this._markerLabels.delete(key),this._markerPopupIds.delete(key)}}configureMarkerInteraction(markerElement,activation){this.markerActivationDetails.set(markerElement,activation),markerElement.setAttribute("role","button"),markerElement.tabIndex=0;const markerLabel=activation.marker.label?.trim()||markerPopupText(this,activation.marker.unsafeHtml);markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale),!this.configuredMarkerElements.has(markerElement)&&(this.configuredMarkerElements.add(markerElement),markerElement.addEventListener("click",event=>{event.defaultPrevented||this.emitMarkerActivation(markerElement,"pointer")}),markerElement.addEventListener("keydown",event=>{event.key!==" "&&event.key!=="Enter"||event.repeat||event.defaultPrevented||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected)return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return this.getAttribute("aria-label")===""?"":this.label==null?this.localize("map"):this.label}popupId(key){let id=this._markerPopupIds.get(key);return id||(id=`map-popup-${this._connectGeneration}-${++this._nextPopupId}`,this._markerPopupIds.set(key,id)),id}configurePopupSemantics(key,marker,popup){!popup||typeof popup!="object"||this._configuredPopups.has(popup)||(this._configuredPopups.add(popup),popup.on?.("open",()=>this.syncPopupSemantics(key,marker,popup)),popup.on?.("close",()=>{marker.getElement?.()?.setAttribute("aria-expanded","false")}))}stopObservingMapAllocation(){this.mapResizeObserver?.disconnect(),this.mapResizeObserver=void 0,this.observedMapContainer=void 0}observeMapAllocation(map,container){this.stopObservingMapAllocation();const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;let observer;observer=new ResizeObserverCtor(()=>{if(!(this.mapResizeObserver!==observer||this.observedMapContainer!==container||this.containerEl!==container||this._map!==map||!this.isConnected))try{map.resize()}catch{}}),this.mapResizeObserver=observer,this.observedMapContainer=container;try{observer.observe(container)}catch{this.stopObservingMapAllocation()}}stopObservingPeerChrome(){const pending=this.peerControlsResizeFrame;this.peerControlsResizeFrame=void 0,pending&&pending.view.cancelAnimationFrame(pending.handle),this.peerControlsResizeObserver?.disconnect(),this.peerControlsResizeObserver=void 0,this.peerChromeObserver?.disconnect(),this.peerChromeObserver=void 0,this.observedPeerContainer=void 0}schedulePeerControlInsets(observer,container){if(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||!this.isConnected||this.peerControlsResizeFrame)return;const view=container.ownerDocument.defaultView;if(!view)return;const pending={view,handle:0};this.peerControlsResizeFrame=pending,pending.handle=view.requestAnimationFrame(()=>{this.peerControlsResizeFrame===pending&&(this.peerControlsResizeFrame=void 0,!(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||container.ownerDocument.defaultView!==view||!this.isConnected)&&this.measurePeerControlInsets(container))})}measurePeerControlInsets(container){if(!(!this.isConnected||this.containerEl!==container)){for(const scale of container.querySelectorAll(".maplibregl-ctrl-scale")){const width=scale.style.width;width&&scale.style.getPropertyValue("--_lr-map-scale-width")!==width&&scale.style.setProperty("--_lr-map-scale-width",width)}for(const edge of["top","bottom"]){const height=Math.max(0,...[...container.querySelectorAll(`.maplibregl-ctrl-${edge}-left, .maplibregl-ctrl-${edge}-right`)].map(corner=>corner.getBoundingClientRect().height)),base=container.parentElement,name=`--_lr-map-controls-${edge}`,value=`${height}px`;base&&base.style.getPropertyValue(name)!==value&&base.style.setProperty(name,value)}}}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const selectors=[[".maplibregl-marker","marker"],[".maplibregl-popup","popup"],[".maplibregl-popup-content","popup-content"],[".maplibregl-popup-close-button","popup-close-button"],[".maplibregl-ctrl-attrib","attribution"],[".maplibregl-ctrl-attrib-button","attribution-toggle"],[".maplibregl-ctrl-group:has(.maplibregl-ctrl-zoom-in, .maplibregl-ctrl-compass)","navigation"],[".maplibregl-ctrl-zoom-in","zoom-in"],[".maplibregl-ctrl-zoom-out","zoom-out"],[".maplibregl-ctrl-compass","compass"],[".maplibregl-ctrl-scale","scale"]];for(const[selector,part]of selectors){const candidate=root,elements=[...root.querySelectorAll(selector)];candidate.matches?.(selector)&&elements.push(candidate);for(const element of elements){addPartToken(element,part);const label=part==="zoom-in"?this.localize("zoomIn"):part==="zoom-out"?this.localize("zoomOut"):part==="compass"?this.localize("mapResetNorth"):void 0;label!==void 0&&(element.setAttribute("aria-label",label),element.setAttribute("title",label))}}}observePeerChrome(){const container=this.containerEl;if(!container||(this.syncPeerChromeParts(container),this.observedPeerContainer===container&&this.peerChromeObserver))return;this.stopObservingPeerChrome();const MutationObserverCtor=container.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;this.observedPeerContainer=container;const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(ResizeObserverCtor){const observer=new ResizeObserverCtor(()=>this.schedulePeerControlInsets(observer,container));this.peerControlsResizeObserver=observer;for(const corner of container.querySelectorAll(".maplibregl-ctrl-top-left, .maplibregl-ctrl-top-right, .maplibregl-ctrl-bottom-left, .maplibregl-ctrl-bottom-right"))this.peerControlsResizeObserver.observe(corner)}this.measurePeerControlInsets(container),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.measurePeerControlInsets(container)}}),this.peerChromeObserver.observe(container,{childList:!0,subtree:!0})}syncPopupSemantics(key,marker,popup){const markerElement=marker?.getElement?.();if(!markerElement)return;const id=this.popupId(key);markerElement.setAttribute("aria-controls",id),markerElement.setAttribute("aria-haspopup","dialog"),markerElement.setAttribute("aria-expanded",popup?.isOpen?.()?"true":"false");const popupElement=popup?.getElement?.();if(!popupElement)return;addPartToken(markerElement,"marker"),addPartToken(popupElement,"popup"),popupElement.id=id,popupElement.setAttribute("role","dialog"),popupElement.setAttribute("lang",this.effectiveLocale),popupElement.setAttribute("aria-label",this._markerLabels.get(key)||this.effectiveMapLabel);const popupContent=popupElement.querySelector(".maplibregl-popup-content");popupContent&&addPartToken(popupContent,"popup-content");const closeButton=popupElement.querySelector(".maplibregl-popup-close-button");closeButton&&addPartToken(closeButton,"popup-close-button"),closeButton?.setAttribute("aria-label",this.localize("close"))}syncMapSemantics(){const canvas=this._map?.getCanvas?.();canvas&&(canvas.setAttribute("aria-label",this.effectiveMapLabel),canvas.setAttribute("lang",this.effectiveLocale),this.legend.length||this.legendGradient.length>=2||this.hasLegendSlot||this.hasLegendStartSlot||this.legendProjection.truncated?canvas.setAttribute("aria-describedby","map-legend"):canvas.removeAttribute("aria-describedby"));for(const[key,marker]of this._markerInstances){const markerElement=marker.getElement?.();if(!markerElement)continue;addPartToken(markerElement,"marker"),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",this._markerLabels.get(key)||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const popup=marker.getPopup?.();popup?this.syncPopupSemantics(key,marker,popup):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}this.syncPeerChromeParts()}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatCount(this.legend.length===0?0:1),end:this.formatCount(this.legend.length),total:this.formatCount(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendRowContent(entry){const paint=sanitizeCssColor(entry.color);return html`${entry.icon?html`<span
|
|
20
|
+
><span>${this.localize("mapLegend")}</span></button>`:nothing}get hiddenCategories(){return this._hiddenCategories}set hiddenCategories(value){const previous=this._hiddenCategories;this._hiddenCategories=normalizeMapHiddenCategories(value),this.requestUpdate("hiddenCategories",previous)}get canonicalChoropleth(){const source=this.choropleth;return Object.is(source,this._canonicalChoroplethSource)?this._canonicalChoropleth:(this._canonicalChoroplethSource=source,this._canonicalChoropleth=projectMapChoropleth(source),this._canonicalChoropleth)}get canonicalDataLayers(){const source=this.dataLayers;return Object.is(source,this._canonicalDataLayersSource)?this._canonicalDataLayers:(this._canonicalDataLayersSource=source,this._canonicalDataLayers=projectMapDataLayers(source),this._canonicalDataLayers)}get canonicalMarkers(){const source=this.markers;return Object.is(source,this._canonicalMarkersSource)?this._canonicalMarkers:(this._canonicalMarkersSource=source,this._canonicalMarkers=projectMapMarkers(source),this._canonicalMarkers)}get map(){return this._map}pushGeoJson(source,resolvedSourceId,geojson,projection=projectGeoJson(geojson)){const previous=this._appliedGeoJson.get(resolvedSourceId),diff=typeof source.updateData=="function"&&previous!==void 0?buildProjectedGeoJsonPropertyDiff(previous,projection):null;diff===null||typeof source.updateData!="function"?source.setData(geojson):(diff.update.length>0||diff.add?.length||diff.remove?.length)&&source.updateData(diff),this._appliedGeoJson.set(resolvedSourceId,projection)}get safeMaxBounds(){const bounds=this.maxBounds;if(!Array.isArray(bounds)||bounds.length!==2)return null;const[southWest,northEast]=bounds;if(!Array.isArray(southWest)||!Array.isArray(northEast))return null;const[west,south]=southWest,[east,north]=northEast,values=[west,south,east,north].map(Number);if(!values.every(value=>Number.isFinite(value)))return null;const[w,s,e,n]=values;return w>=e||s>=n||w<-180||e>180||s<-90||n>90?null:[[w,s],[e,n]]}applyMaxBounds(){const map=this._map;if(!map||typeof map.setMaxBounds!="function")return;const bounds=this.safeMaxBounds;let zoomBefore,centerBefore;try{if(zoomBefore=map.getZoom(),centerBefore=map.getCenter(),map.setMaxBounds(bounds),bounds===null||Number.isFinite(map.getZoom()))return}catch{}try{map.setMaxBounds(null)}catch{}typeof zoomBefore=="number"&&Number.isFinite(zoomBefore)&&map.setZoom(zoomBefore),centerBefore&&map.setCenter([centerBefore.lng,centerBefore.lat]),devWarnOnce("lyra-map-max-bounds-rejected","<lr-map>: maxBounds left maplibre-gl without a usable camera, so it was dropped and the camera restored. This is a peer limitation, not a bad value -- it shows up at sub-1 fractional zooms in wide containers. Raise the zoom, narrow the box, or leave maxBounds unset.")}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)]}fitBounds(bounds,options={}){const box=normalizeFitBounds(bounds);if(!box)return devWarnOnce("lyra-map-fit-bounds-rejected",`<${this.localName}>: fitBounds() ignored a box that is not [[west, south], [east, north]] with finite coordinates, latitudes in [-90, 90], south <= north, and longitudes in [-180, 180] (east may run past 180, up to one full turn east of west, for a box crossing the antimeridian).`),!1;const settings=typeof options=="object"&&options!==null?options:{},maxZoom=settings.maxZoom,fit=Object.freeze({bounds:box,padding:normalizeFitPadding(settings.padding),maxZoom:isFiniteCoordinate(maxZoom)?finiteRange(maxZoom,22,0,22):void 0,animate:settings.animate!==!1}),map=this._map;return map?(this.pendingFit=void 0,this.applyFit(map,fit,fit.animate&&!prefersReducedMotion(this))):(this.pendingFit=Object.freeze({fit,center:snapshotCenter(this.center),zoom:this.zoom}),!0)}applyFit(map,fit,animate){if(typeof map.fitBounds!="function")return!1;const[[west,south],[east,north]]=fit.bounds;try{map.fitBounds([[west,south],[east,north]],{padding:{...fit.padding},...fit.maxZoom===void 0?{}:{maxZoom:fit.maxZoom},animate},{[FIT_EVENT_KEY]:this.fitToken})}catch{return!1}return!0}applyPendingFit(){const map=this._map,pending=this.pendingFit;!map||!pending||(this.pendingFit=void 0,!(!sameCenterValue(this.center,pending.center)||!Object.is(this.zoom,pending.zoom))&&this.applyFit(map,pending.fit,!1))}reflectCamera(map,source){const camera=readPeerCamera(map);if(!camera)return;const center=Object.freeze(camera.center),{zoom}=camera;this.reflectedCamera={center,zoom},this.center=center,this.zoom=zoom,this.emit("lr-map-view-change",{center,zoom,source})}pushCamera(changed){const reflected=this.reflectedCamera;this.reflectedCamera=void 0;const map=this._map;if(!map||!changed.has("center")&&!changed.has("zoom"))return;const center=this.safeCenter,zoom=this.safeZoom,shown=readPeerCamera(map),showsCenter=camera=>camera!==void 0&¢er[0]===camera.center[0]&¢er[1]===camera.center[1];let pushCenter=changed.has("center")&&!showsCenter(reflected)&&!showsCenter(shown),pushZoom=changed.has("zoom")&&zoom!==reflected?.zoom&&zoom!==shown?.zoom;if(!pushCenter&&!pushZoom)return;let interrupting=!1;try{interrupting=map.isMoving?.()===!0}catch{}interrupting&&(pushCenter=!showsCenter(shown),pushZoom=zoom!==shown?.zoom),this.writeCamera(()=>{pushCenter&&map.setCenter(center),pushZoom&&map.setZoom(zoom)})}writeCamera(write){const previous=this.writingCamera;this.writingCamera=!0;try{write()}finally{this.writingCamera=previous}}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(),this.releaseLegendAnnouncementSink(),super.disconnectedCallback(),this.disposeMap(),this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0;for(const marker of this._markerInstances.values()){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove()}this._markerInstances.clear(),this._markerColors.clear(),this._markerLabels.clear(),this._markerPopupIds.clear()}failureMessage(reason=this.failure??"initialization-failed"){switch(reason){case"missing-peer":return this.localize("mapMissingLibrary");case"style-required":return this.localize("mapStyleRequired");case"webgl-unavailable":return this.localize("mapWebglUnavailable");case"initialization-failed":return this.localize("mapInitializationFailed")}}failInitialization(reason,partialMap){try{partialMap?.remove()}catch{}this.disposeMap(),this.loading=!1,this.failure=reason,this.errorAnnouncementSink?.announce(this.failureMessage(reason))}disposeMap(){this.stopObservingMapAllocation(),this.stopObservingPeerChrome();try{this._map?.remove()}catch{}this._map=void 0,this._styleLoaded=!1,this.boxZoomSettling=!1,this.reflectedCamera=void 0,this._appliedChoroplethSourceId=void 0,this._appliedFillLayerId=void 0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this.appliedPointIcons.clear(),this.appliedPointPaint.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear()}adoptedCallback(){super.adoptedCallback(),this.stopObservingMapAllocation(),this.stopObservingPeerChrome(),this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.releaseLegendAnnouncementSink(),this._map&&this.containerEl&&this.isConnected&&this.observeMapAllocation(this._map,this.containerEl)}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}tryConstructMap(){if(this._map||!this._maplibreModule||!this._webglReady||!this.containerEl||!this.visible||!this.isConnected)return;if(!hasMapStyle(this.mapStyle)){this.failInitialization("style-required");return}const mod=this._maplibreModule;let candidate;try{candidate=new mod.Map({container:this.containerEl,style:this.mapStyle,center:this.safeCenter,zoom:this.safeZoom,...typeof this.renderWorldCopies=="boolean"?{renderWorldCopies:this.renderWorldCopies}:{},locale:{"Map.Title":this.effectiveMapLabel,"Marker.Title":this.localize("map"),"Popup.Close":this.localize("close"),"NavigationControl.ZoomIn":this.localize("zoomIn"),"NavigationControl.ZoomOut":this.localize("zoomOut"),"NavigationControl.ResetBearing":this.localize("mapResetNorth")}}),candidate.on("error",event=>{if(this._map===candidate&&!this._styleLoaded){this.failInitialization("initialization-failed");return}console.error("lr-map:",event.error??event)}),candidate.on("load",()=>{if(this._map===candidate)try{this._styleLoaded=!0,this.applyChoropleth(),this.applyMarkers(),this.applyDataLayers(),this.emit("lr-map-load")}catch{this.failInitialization("initialization-failed")}}),candidate.on("click",event=>{if(this._map!==candidate)return;const fillLayerId=this._appliedFillLayerId,layerIds=[];fillLayerId&&candidate.getLayer(fillLayerId)&&layerIds.push(fillLayerId);for(const resolvedSourceId of this._appliedDataLayerIds.values())for(const suffix of QUERYABLE_DATA_LAYER_SUFFIXES){const layerId=`${resolvedSourceId}${suffix}`;candidate.getLayer(layerId)&&layerIds.push(layerId)}const hit=(layerIds.length?candidate.queryRenderedFeatures(event.point,{layers:layerIds}):[])[0],hitLayerId=hit?.layer?.id;let origin,sourceId;if(hitLayerId!==void 0){if(hitLayerId===fillLayerId)origin="choropleth";else for(const[publicSourceId,resolvedSourceId]of this._appliedDataLayerIds)if(hitLayerId.startsWith(`${resolvedSourceId}-`)){origin=hitLayerId===`${resolvedSourceId}-cluster`?"cluster":"data-layer",sourceId=publicSourceId;break}}this.emit("lr-map-click",{lngLat:[event.lngLat.lng,event.lngLat.lat],feature:hit,origin,sourceId})}),candidate.on("boxzoomend",()=>{this._map===candidate&&(this.boxZoomSettling=!0)}),candidate.on("moveend",event=>{if(this._map!==candidate)return;const fit=event?.[FIT_EVENT_KEY]===this.fitToken,afterBoxZoom=!fit&&this.boxZoomSettling;if(fit||(this.boxZoomSettling=!1),this.writingCamera)return;const source=fit?"fit":event?.originalEvent||afterBoxZoom?"user":void 0;source&&this.reflectCamera(candidate,source)});const canvas=candidate.getCanvas?.();canvas&¬ifyMapCanvasReady(this,canvas),this._map=candidate,this.observeMapAllocation(candidate,this.containerEl),this.observePeerChrome(),this.failure=void 0}catch{this.failInitialization("initialization-failed",candidate);return}this.applyMaxBounds(),this.pendingFit&&this.scheduleAfterUpdate(()=>this.applyPendingFit(),"map-pending-fit")}updated(changed){if(super.updated(changed),this.setAttribute("aria-busy",String(this.loading)),this.legendCollapsed&&(changed.has("legendOpen")||changed.has("legendCollapsible"))){const legend=this.shadowRoot?.querySelector('[part="legend"]');legend&&(legend.scrollTop=0)}if((changed.has("choropleth")||changed.has("legendGradient"))&&this.warnOnLegendChoroplethMismatch(),changed.has("visible")&&this.visible&&this.tryConstructMap(),changed.has("mapStyle")&&(this._styleGeneration+=1),changed.has("mapStyle")&&!hasMapStyle(this.mapStyle)&&this._maplibreModule){const generation=this._connectGeneration,module=this._maplibreModule;this.scheduleAfterUpdate(()=>{!this.isConnected||generation!==this._connectGeneration||module!==this._maplibreModule||hasMapStyle(this.mapStyle)||this.failInitialization("style-required")},"map-style-required")}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,style=this.mapStyle,generation=this._connectGeneration,styleGeneration=this._styleGeneration,current=()=>this.isConnected&&this._map===map&&generation===this._connectGeneration&&styleGeneration===this._styleGeneration&&this.mapStyle===style,failStyle=()=>{current()&&this.scheduleAfterUpdate(()=>{current()&&this.failInitialization("initialization-failed")},`map-style-failure-${styleGeneration}`)};try{for(const sourceId of this.appliedPointIcons.keys())this.removePointIcons(sourceId);map.once("style.load",()=>{if(current())try{this._styleLoaded=!0,this._appliedDataLayerIds.clear(),this._appliedDataLayerShapes.clear(),this.appliedPointPaint.clear(),this.appliedPointMuting.clear(),this._appliedGeoJson.clear(),this.applyChoropleth(),this.applyDataLayers()}catch{failStyle()}}),map.setStyle(style)}catch{failStyle()}}else if(this._styleLoaded&&(changed.has("dataLayers")||changed.has("choropleth"))){const choropleth=this.canonicalChoropleth,nextChoroplethSourceId=choropleth?this.resolveChoroplethSourceId(choropleth.sourceId):void 0;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==nextChoroplethSourceId&&this.removeChoropleth(),changed.has("dataLayers")&&this.applyDataLayers(),this.applyChoropleth()}changed.has("hiddenCategories")&&this._map&&this._styleLoaded&&this.refreshThemePaint(),this.pushCamera(changed),changed.has("maxBounds")&&this._map&&this.writeCamera(()=>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);if(this._appliedFillLayerId){const choropleth=this.canonicalChoropleth;choropleth&&choropleth.stops.length>0&&this._map.setPaintProperty(this._appliedFillLayerId,"fill-color",this.choroplethColorExpression(choropleth)),this._map.setPaintProperty(this._appliedFillLayerId,"fill-opacity",fillOpacity)}const dataLayersBySourceId=new Map(this.canonicalDataLayers.map(layer=>[layer.sourceId,layer]));for(const[publicSourceId,sourceId]of this._appliedDataLayerIds){const dataLayer=dataLayersBySourceId.get(publicSourceId);dataLayer&&this.paintDataLayer(sourceId,dataLayer)}}applyChoropleth(){if(!this._map)return;const choropleth=this.canonicalChoropleth;if(!choropleth){this.removeChoropleth();return}const{geojson,geojsonProjection,stops}=choropleth,sourceId=this.resolveChoroplethSourceId(choropleth.sourceId),fillLayerId=`${sourceId}-fill`;this._appliedChoroplethSourceId&&this._appliedChoroplethSourceId!==sourceId&&this.removeChoropleth(),warnOnUntileableProperties(geojsonProjection,"choropleth");const existingSource=this._map.getSource(sourceId);if(existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson}),this._appliedGeoJson.set(sourceId,geojsonProjection)),this._appliedChoroplethSourceId=sourceId,stops.length===0)return;const colorExpr=this.choroplethColorExpression(choropleth);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}choroplethColorExpression(choropleth){const{field,stops}=choropleth,resolvedStops=stops.map(([value,color])=>[value,resolvedLayerColor(this,color,void 0)]);let colorExpr;if(choropleth.interpolation==="step"){const base=choropleth.stepBaseColor?resolvedLayerColor(this,choropleth.stepBaseColor,void 0):resolvedStops[0][1];colorExpr=["step",["get",field],base];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}else{colorExpr=["interpolate",choropleth.interpolation==="logarithmic"?["exponential",CHOROPLETH_LOG_INTERPOLATION_BASE]:["linear"],["get",field]];for(const[value,color]of resolvedStops)colorExpr.push(value,color)}return colorExpr}resolveChoroplethSourceId(sourceId){const dataSourceIds=new Set(this.canonicalDataLayers.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=this.canonicalDataLayers,nextIds=new Set(layers.map(layer=>layer.sourceId));for(const publicSourceId of this._appliedDataLayerIds.keys())nextIds.has(publicSourceId)||this.removeDataLayer(publicSourceId);for(const layer of layers){const{sourceId:publicSourceId,geojson,geojsonProjection}=layer,shape=dataLayerShape(layer),appliedShape=this._appliedDataLayerShapes.get(publicSourceId);appliedShape!==void 0&&appliedShape!==shape&&this.removeDataLayer(publicSourceId);const sourceId=this.resolveDataLayerSourceId(publicSourceId);warnOnUntileableProperties(geojsonProjection,publicSourceId);const cluster=layer.cluster,existingSource=this._map.getSource(sourceId);existingSource?this.pushGeoJson(existingSource,sourceId,geojson,geojsonProjection):(this._map.addSource(sourceId,{type:"geojson",data:geojson,...cluster?{cluster:!0,clusterRadius:cluster.radius,clusterMaxZoom:cluster.maxZoom}:{}}),this._appliedGeoJson.set(sourceId,geojsonProjection)),this.applyDataLayerRendering(sourceId,layer),this._appliedDataLayerIds.set(publicSourceId,sourceId),this._appliedDataLayerShapes.set(publicSourceId,shape)}}applyDataLayerRendering(sourceId,layer){if(layer.kind==="heatmap"){this.applyHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;cluster?this.applyClusterLayers(sourceId,layer,cluster):this.applyGeometryLayers(sourceId,layer),this.applyPointIcons(sourceId,layer)}paintDataLayer(sourceId,layer){if(layer.kind==="heatmap"){this.paintHeatmapLayer(sourceId,layer);return}const cluster=layer.cluster;cluster?this.paintClusterLayers(sourceId,layer,cluster):this.paintGeometryLayers(sourceId,layer),this.paintPointIcons(sourceId,layer)}applyGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone),stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),fillId=`${sourceId}-fill`,lineId=`${sourceId}-line`,circleId=`${sourceId}-circle`;this._map.getLayer(fillId)||this._map.addLayer({id:fillId,type:"fill",source:sourceId,filter:["==",["geometry-type"],"Polygon"],paint:{"fill-color":color,"fill-opacity":choroplethFillOpacity(this)}}),this._map.getLayer(lineId)||this._map.addLayer({id:lineId,type:"line",source:sourceId,filter:["in",["geometry-type"],["literal",["LineString","Polygon"]]],paint:{"line-color":this.lineColor(layer),"line-width":layer.line?.width??2,...layer.line?{"line-opacity":layer.line.opacity}:{}}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["==",["geometry-type"],"Point"],paint:{"circle-color":stroke,"circle-radius":5}}),this._map.setPaintProperty(lineId,"line-width",layer.line?.width??2),this._map.setPaintProperty(lineId,"line-opacity",layer.line?.opacity??1),this.paintGeometryLayers(sourceId,layer)}paintGeometryLayers(sourceId,layer){if(!this._map)return;const tone=layer.tone,color=resolvedLayerColor(this,layer.color,tone);this._map.setPaintProperty(`${sourceId}-fill`,"fill-color",color),this._map.setPaintProperty(`${sourceId}-fill`,"fill-opacity",choroplethFillOpacity(this)),this._map.setPaintProperty(`${sourceId}-line`,"line-color",this.lineColor(layer)),this.paintPoints(sourceId,layer)}lineColor(layer){const fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),line=layer.line;return!line?.field||line.stops.length<2?fallback:lineColorExpression(line.field,line.stops.map(([value,color])=>[value,resolvedLayerColor(this,color,layer.tone)]),fallback)}mutedPointOpacity(layerId,field){const muted=field?this.hiddenCategories:EMPTY_HIDDEN_CATEGORIES;if(!muted.length)return this.appliedPointMuting.delete(layerId)?1:void 0;this.appliedPointMuting.add(layerId);const dim=hiddenCategoryOpacity(this);return mutedCategoryOpacityExpression(field,muted,dim)}paintPoints(sourceId,layer){if(!this._map)return;const point=layer.point,fallback=resolvedLayerColor(this,layer.strokeColor??layer.color,layer.tone),color=pointColorExpression(point?.field,point?.field&&point.colors.length?point.colors.map(([value,paint])=>[value,resolvedLayerColor(this,paint,layer.tone)]):[],fallback),id=`${sourceId}-circle`;this._map.setPaintProperty(id,"circle-color",color);const opacity=this.mutedPointOpacity(id,point?.field);opacity!==void 0&&(this._map.setPaintProperty(id,"circle-opacity",opacity),this._map.setPaintProperty(id,"circle-stroke-opacity",opacity)),!(!point&&!this.appliedPointPaint.has(sourceId))&&(this._map.setPaintProperty(id,"circle-radius",pointRadiusExpression(point?.radius??5)),this._map.setPaintProperty(id,"circle-stroke-width",point?.strokeWidth??0),this._map.setPaintProperty(id,"circle-stroke-color",point?.strokeColor?resolvedLayerColor(this,point.strokeColor,layer.tone):fallback),point?this.appliedPointPaint.add(sourceId):this.appliedPointPaint.delete(sourceId))}pointIconColor(layer){const resolved=resolvedLayerColor(this,layer.point?.iconColor??`var(${ON_TONE_TOKEN[layer.tone??"accent"]})`,layer.tone);return resolveCanvasColor(this,resolved,dataLayerColor(this,layer.tone))}removePointIcons(sourceId){const applied=this.appliedPointIcons.get(sourceId);if(!applied||!this._map)return;const id=`${sourceId}-point-icon`;this._map.getLayer(id)&&this._map.removeLayer(id);for(const{id:imageId}of applied.icons)this._map.hasImage?.(imageId)&&this._map.removeImage?.(imageId);this.appliedPointIcons.delete(sourceId),this.appliedPointMuting.delete(id)}applyPointIcons(sourceId,layer){const map=this._map,point=layer.point,signature=JSON.stringify([point?.iconField,point?.iconSize,point?.icons]);if(this.appliedPointIcons.get(sourceId)?.signature===signature){this.paintPointIcons(sourceId,layer);return}if(this.removePointIcons(sourceId),!point?.iconField||!point.icons.length||!map||typeof map.addImage!="function"||typeof map.hasImage!="function"||typeof map.updateImage!="function"||typeof map.removeImage!="function")return;const color=this.pointIconColor(layer),icons=[];this.appliedPointIcons.set(sourceId,{signature,color,icons});for(const icon of point.icons){const raster=rasterPointIcon(this,icon,color);if(!raster)continue;let id;do id=`lr-point-icon-${this.nextPointIconId++}`;while(map.hasImage(id));icons.push({id,icon}),map.addImage(id,raster,{pixelRatio:2})}icons.length&&map.addLayer({id:`${sourceId}-point-icon`,type:"symbol",source:sourceId,filter:layer.cluster?["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]]:["==",["geometry-type"],"Point"],layout:{"icon-image":["match",["get",point.iconField],...icons.flatMap(({id,icon})=>[icon.value,id]),""],"icon-size":point.iconSize/(POINT_ICON_RASTER_SIZE/2),"icon-allow-overlap":!0,"icon-ignore-placement":!0}})}paintPointIcons(sourceId,layer){const applied=this.appliedPointIcons.get(sourceId);if(!applied)return;const iconLayerId=`${sourceId}-point-icon`,opacity=this.mutedPointOpacity(iconLayerId,layer.point?.iconField);opacity!==void 0&&this._map?.setPaintProperty(iconLayerId,"icon-opacity",opacity);const color=this.pointIconColor(layer);if(color!==applied.color){for(const{id,icon}of applied.icons){const raster=rasterPointIcon(this,icon,color);raster&&this._map?.updateImage?.(id,raster)}applied.color=color}}clusterColorExpression(layer,cluster){const tone=layer.tone;return clusterColorExpression(cluster.colorSteps.map(([count,stepColor])=>[count,resolvedLayerColor(this,stepColor,tone)]),()=>resolvedLayerColor(this,layer.color,tone))}applyClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`,countId=`${sourceId}-cluster-count`,circleId=`${sourceId}-circle`,clusterColor=this.clusterColorExpression(layer,cluster),clusterRadius=stepExpression(["get","point_count"],cluster.radiusSteps),countColor=resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone);this._map.getLayer(clusterId)||this._map.addLayer({id:clusterId,type:"circle",source:sourceId,filter:["has","point_count"],paint:{"circle-color":clusterColor,"circle-radius":clusterRadius,"circle-stroke-width":1,"circle-stroke-color":stroke}}),this.styleProvidesGlyphs()&&!this._map.getLayer(countId)&&this._map.addLayer({id:countId,type:"symbol",source:sourceId,filter:["has","point_count"],layout:{"text-field":["get","point_count_abbreviated"],"text-size":12,...cluster.countFont?{"text-font":[...cluster.countFont]}:{}},paint:{"text-color":countColor}}),this._map.getLayer(circleId)||this._map.addLayer({id:circleId,type:"circle",source:sourceId,filter:["all",["==",["geometry-type"],"Point"],["!",["has","point_count"]]],paint:{"circle-color":stroke,"circle-radius":5}}),this.paintClusterLayers(sourceId,layer,cluster)}paintClusterLayers(sourceId,layer,cluster){if(!this._map)return;const tone=layer.tone,stroke=resolvedLayerColor(this,layer.strokeColor??layer.color,tone),clusterId=`${sourceId}-cluster`;this._map.setPaintProperty(clusterId,"circle-color",this.clusterColorExpression(layer,cluster)),this._map.setPaintProperty(clusterId,"circle-radius",stepExpression(["get","point_count"],cluster.radiusSteps)),this._map.setPaintProperty(clusterId,"circle-stroke-color",stroke),this.styleProvidesGlyphs()&&this._map.setPaintProperty(`${sourceId}-cluster-count`,"text-color",resolvedLayerColor(this,`var(${ON_TONE_TOKEN[tone??"accent"]})`,tone)),this.paintPoints(sourceId,layer)}applyHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`,options=layer.heatmap,weight=heatmapWeightExpression(options),color=this.heatmapColorExpression(layer),radius=heatmapZoomValue(options?.radius,DEFAULT_HEATMAP_RADIUS,1,200),intensity=heatmapZoomValue(options?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100),opacity=finiteRange(options?.opacity??Number.NaN,1,0,1);if(!this._map.getLayer(heatmapId)){this._map.addLayer({id:heatmapId,type:"heatmap",source:sourceId,paint:{...weight?{"heatmap-weight":weight}:{},"heatmap-intensity":intensity,"heatmap-color":color,"heatmap-radius":radius,...options?.opacity===void 0?{}:{"heatmap-opacity":opacity}}});return}this.paintHeatmapLayer(sourceId,layer)}paintHeatmapLayer(sourceId,layer){if(!this._map)return;const heatmapId=`${sourceId}-heatmap`;this._map.setPaintProperty(heatmapId,"heatmap-weight",heatmapWeightExpression(layer.heatmap)??1),this._map.setPaintProperty(heatmapId,"heatmap-intensity",heatmapZoomValue(layer.heatmap?.intensity,DEFAULT_HEATMAP_INTENSITY,0,100)),this._map.setPaintProperty(heatmapId,"heatmap-color",this.heatmapColorExpression(layer)),this._map.setPaintProperty(heatmapId,"heatmap-radius",heatmapZoomValue(layer.heatmap?.radius,DEFAULT_HEATMAP_RADIUS,1,200)),this._map.setPaintProperty(heatmapId,"heatmap-opacity",finiteRange(layer.heatmap?.opacity??Number.NaN,1,0,1))}heatmapColorExpression(layer){const tone=layer.tone,authored=(layer.heatmap?.stops??[]).map(([density,color])=>[density,resolvedLayerColor(this,color,tone)]);return heatmapColorExpression(authored,()=>HEATMAP_RAMP_TOKENS.map(([density,token])=>[density,resolvedLayerColor(this,`var(${token})`,tone)]))}styleProvidesGlyphs(){try{const liveGlyphs=this._map?.getStyle?.()?.glyphs;if(typeof liveGlyphs=="string"&&liveGlyphs.trim().length>0)return!0}catch{}const declared=this.mapStyle,declaredGlyphs=declared&&typeof declared=="object"?declared.glyphs:void 0;return typeof declaredGlyphs=="string"&&declaredGlyphs.trim().length>0}resolveDataLayerSourceId(publicSourceId){const applied=this._appliedDataLayerIds.get(publicSourceId);if(applied)return applied;let sourceId;do sourceId=`lr-data-layer-${this._nextDataLayerId++}`;while(this._map?.getSource(sourceId)||DATA_LAYER_SUFFIXES.some(suffix=>this._map?.getLayer(`${sourceId}${suffix}`)));return sourceId}removeDataLayer(publicSourceId){if(!this._map)return;const sourceId=this._appliedDataLayerIds.get(publicSourceId);if(sourceId){this.removePointIcons(sourceId),this.appliedPointPaint.delete(sourceId);for(const suffix of DATA_LAYER_SUFFIXES){const layerId=`${sourceId}${suffix}`;this.appliedPointMuting.delete(layerId),this._map.getLayer(layerId)&&this._map.removeLayer(layerId)}this._map.getSource(sourceId)&&this._map.removeSource(sourceId),this._appliedDataLayerIds.delete(publicSourceId),this._appliedDataLayerShapes.delete(publicSourceId),this._appliedGeoJson.delete(sourceId)}}applyMarkers(){const map=this._map,mod=this._maplibreModule;if(!map||!mod)return;const visible=new Set,coordCounts=new Map,explicitIds=new Set;for(const m of this.canonicalMarkers){const lngLat=m.lngLat,mapLngLat=[lngLat[0],lngLat[1]];let key,id;if(m.id!==void 0){if(id=m.id,explicitIds.has(id))continue;explicitIds.add(id),key=`id:${id}`}else{const coordKey=`${lngLat[0]},${lngLat[1]}`,occurrence=coordCounts.get(coordKey)??0;coordCounts.set(coordKey,occurrence+1),key=`coordinate:${coordKey}#${occurrence}`}visible.add(key);let existing=this._markerInstances.get(key);const markerColor=sanitizeCssColor(m.color)??(m.color===void 0?dataLayerColor(this,"accent"):void 0);if(existing&&this._markerColors.get(key)!==markerColor){const existingElement=existing.getElement?.();existingElement&&this.markerActivationDetails.delete(existingElement),existing.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),existing=void 0}if(existing){existing.setLngLat(mapLngLat);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(mapLngLat);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()||markerPopupText(this,m.unsafeHtml);this._markerLabels.set(key,markerLabel||void 0);const markerElement=this._markerInstances.get(key)?.getElement?.();if(markerElement){addPartToken(markerElement,"marker"),markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const currentMarker=this._markerInstances.get(key);this.configureMarkerInteraction(markerElement,{id,lngLat,marker:m});const popup=currentMarker?.getPopup();popup&¤tMarker?(this.configurePopupSemantics(key,currentMarker,popup),this.syncPopupSemantics(key,currentMarker,popup)):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}}for(const[key,marker]of this._markerInstances)if(!visible.has(key)){const markerElement=marker.getElement?.();markerElement&&this.markerActivationDetails.delete(markerElement),marker.remove(),this._markerInstances.delete(key),this._markerColors.delete(key),this._markerLabels.delete(key),this._markerPopupIds.delete(key)}}configureMarkerInteraction(markerElement,activation){this.markerActivationDetails.set(markerElement,activation),markerElement.setAttribute("role","button"),markerElement.tabIndex=0;const markerLabel=activation.marker.label?.trim()||markerPopupText(this,activation.marker.unsafeHtml);markerElement.setAttribute("aria-label",markerLabel||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale),!this.configuredMarkerElements.has(markerElement)&&(this.configuredMarkerElements.add(markerElement),markerElement.addEventListener("click",event=>{event.defaultPrevented||this.emitMarkerActivation(markerElement,"pointer")}),markerElement.addEventListener("keydown",event=>{event.key!==" "&&event.key!=="Enter"||event.repeat||event.defaultPrevented||(event.key===" "&&event.preventDefault(),this.emitMarkerActivation(markerElement,"keyboard"))},{capture:!0}))}emitMarkerActivation(markerElement,source){if(!this.isConnected)return;const activation=this.markerActivationDetails.get(markerElement);activation&&this.emit("lr-map-marker-activate",{...activation,source})}get effectiveMapLabel(){return this.getAttribute("aria-label")===""?"":this.label==null?this.localize("map"):this.label}popupId(key){let id=this._markerPopupIds.get(key);return id||(id=`map-popup-${this._connectGeneration}-${++this._nextPopupId}`,this._markerPopupIds.set(key,id)),id}configurePopupSemantics(key,marker,popup){!popup||typeof popup!="object"||this._configuredPopups.has(popup)||(this._configuredPopups.add(popup),popup.on?.("open",()=>this.syncPopupSemantics(key,marker,popup)),popup.on?.("close",()=>{marker.getElement?.()?.setAttribute("aria-expanded","false")}))}stopObservingMapAllocation(){this.mapResizeObserver?.disconnect(),this.mapResizeObserver=void 0,this.observedMapContainer=void 0}observeMapAllocation(map,container){this.stopObservingMapAllocation();const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;let observer;observer=new ResizeObserverCtor(()=>{if(!(this.mapResizeObserver!==observer||this.observedMapContainer!==container||this.containerEl!==container||this._map!==map||!this.isConnected))try{map.resize()}catch{}}),this.mapResizeObserver=observer,this.observedMapContainer=container;try{observer.observe(container)}catch{this.stopObservingMapAllocation()}}stopObservingPeerChrome(){const pending=this.peerControlsResizeFrame;this.peerControlsResizeFrame=void 0,pending&&pending.view.cancelAnimationFrame(pending.handle),this.peerControlsResizeObserver?.disconnect(),this.peerControlsResizeObserver=void 0,this.peerChromeObserver?.disconnect(),this.peerChromeObserver=void 0,this.observedPeerContainer=void 0}schedulePeerControlInsets(observer,container){if(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||!this.isConnected||this.peerControlsResizeFrame)return;const view=container.ownerDocument.defaultView;if(!view)return;const pending={view,handle:0};this.peerControlsResizeFrame=pending,pending.handle=view.requestAnimationFrame(()=>{this.peerControlsResizeFrame===pending&&(this.peerControlsResizeFrame=void 0,!(this.peerControlsResizeObserver!==observer||this.observedPeerContainer!==container||this.containerEl!==container||container.ownerDocument.defaultView!==view||!this.isConnected)&&this.measurePeerControlInsets(container))})}measurePeerControlInsets(container){if(!(!this.isConnected||this.containerEl!==container)){for(const scale of container.querySelectorAll(".maplibregl-ctrl-scale")){const width=scale.style.width;width&&scale.style.getPropertyValue("--_lr-map-scale-width")!==width&&scale.style.setProperty("--_lr-map-scale-width",width)}for(const edge of["top","bottom"]){const height=Math.max(0,...[...container.querySelectorAll(`.maplibregl-ctrl-${edge}-left, .maplibregl-ctrl-${edge}-right`)].map(corner=>corner.offsetHeight)),base=container.parentElement,name=`--_lr-map-controls-${edge}`,value=`${height}px`;base&&base.style.getPropertyValue(name)!==value&&base.style.setProperty(name,value)}}}syncPeerChromeParts(root=this.containerEl??this.renderRoot){const selectors=[[".maplibregl-marker","marker"],[".maplibregl-popup","popup"],[".maplibregl-popup-content","popup-content"],[".maplibregl-popup-close-button","popup-close-button"],[".maplibregl-ctrl-attrib","attribution"],[".maplibregl-ctrl-attrib-button","attribution-toggle"],[".maplibregl-ctrl-group:has(.maplibregl-ctrl-zoom-in, .maplibregl-ctrl-compass)","navigation"],[".maplibregl-ctrl-zoom-in","zoom-in"],[".maplibregl-ctrl-zoom-out","zoom-out"],[".maplibregl-ctrl-compass","compass"],[".maplibregl-ctrl-scale","scale"]];for(const[selector,part]of selectors){const candidate=root,elements=[...root.querySelectorAll(selector)];candidate.matches?.(selector)&&elements.push(candidate);for(const element of elements){addPartToken(element,part);const label=part==="zoom-in"?this.localize("zoomIn"):part==="zoom-out"?this.localize("zoomOut"):part==="compass"?this.localize("mapResetNorth"):void 0;label!==void 0&&(element.setAttribute("aria-label",label),element.setAttribute("title",label))}}}observePeerChrome(){const container=this.containerEl;if(!container||(this.syncPeerChromeParts(container),this.observedPeerContainer===container&&this.peerChromeObserver))return;this.stopObservingPeerChrome();const MutationObserverCtor=container.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;this.observedPeerContainer=container;const ResizeObserverCtor=container.ownerDocument.defaultView?.ResizeObserver;if(ResizeObserverCtor){const observer=new ResizeObserverCtor(()=>this.schedulePeerControlInsets(observer,container));this.peerControlsResizeObserver=observer;for(const corner of container.querySelectorAll(".maplibregl-ctrl-top-left, .maplibregl-ctrl-top-right, .maplibregl-ctrl-bottom-left, .maplibregl-ctrl-bottom-right"))this.peerControlsResizeObserver.observe(corner)}this.measurePeerControlInsets(container),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.measurePeerControlInsets(container)}}),this.peerChromeObserver.observe(container,{childList:!0,subtree:!0})}syncPopupSemantics(key,marker,popup){const markerElement=marker?.getElement?.();if(!markerElement)return;const id=this.popupId(key);markerElement.setAttribute("aria-controls",id),markerElement.setAttribute("aria-haspopup","dialog"),markerElement.setAttribute("aria-expanded",popup?.isOpen?.()?"true":"false");const popupElement=popup?.getElement?.();if(!popupElement)return;addPartToken(markerElement,"marker"),addPartToken(popupElement,"popup"),popupElement.id=id,popupElement.setAttribute("role","dialog"),popupElement.setAttribute("lang",this.effectiveLocale),popupElement.setAttribute("aria-label",this._markerLabels.get(key)||this.effectiveMapLabel);const popupContent=popupElement.querySelector(".maplibregl-popup-content");popupContent&&addPartToken(popupContent,"popup-content");const closeButton=popupElement.querySelector(".maplibregl-popup-close-button");closeButton&&addPartToken(closeButton,"popup-close-button"),closeButton?.setAttribute("aria-label",this.localize("close"))}syncMapSemantics(){const canvas=this._map?.getCanvas?.();canvas&&(canvas.setAttribute("aria-label",this.effectiveMapLabel),canvas.setAttribute("lang",this.effectiveLocale),this.legend.length||this.legendGradient.length>=2||this.hasLegendSlot||this.hasLegendStartSlot||this.legendProjection.truncated?canvas.setAttribute("aria-describedby","map-legend"):canvas.removeAttribute("aria-describedby"));for(const[key,marker]of this._markerInstances){const markerElement=marker.getElement?.();if(!markerElement)continue;addPartToken(markerElement,"marker"),markerElement.setAttribute("role","button"),markerElement.tabIndex=0,markerElement.setAttribute("aria-label",this._markerLabels.get(key)||this.localize("map")),markerElement.setAttribute("lang",this.effectiveLocale);const popup=marker.getPopup?.();popup?this.syncPopupSemantics(key,marker,popup):(markerElement.removeAttribute("aria-controls"),markerElement.removeAttribute("aria-expanded"),markerElement.removeAttribute("aria-haspopup"))}this.syncPeerChromeParts()}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}legendLimitText(){return this.localize("paginationSummary",void 0,{start:this.formatCount(this.legend.length===0?0:1),end:this.formatCount(this.legend.length),total:this.formatCount(this.legendProjection.inputCount),itemLabel:this.localize("items")})}renderLegendRowContent(entry){const paint=sanitizeCssColor(entry.color);return html`${entry.icon?html`<span
|
|
21
21
|
part="legend-swatch"
|
|
22
22
|
data-pattern=${entry.pattern}
|
|
23
23
|
data-icon="true"
|
|
@@ -46,10 +46,11 @@ readonly hidePrevious?:boolean;}
|
|
|
46
46
|
* Reason a tour ended, forwarded as `lr-tour-end` detail.reason.
|
|
47
47
|
* `'completed'`/`'skip'`/`'escape'` are emitted by the tour's own built-in dismiss triggers;
|
|
48
48
|
* `'unmount'` is emitted when the tour is removed from the DOM while still open by something
|
|
49
|
-
* other than its own `end()` (mirrors `lr-dialog`'s identical `'unmount'` case);
|
|
50
|
-
*
|
|
49
|
+
* other than its own `end()` (mirrors `lr-dialog`'s identical `'unmount'` case);
|
|
50
|
+
* `'unavailable'` is emitted when deferred placement fails and the hidden panel cannot remain open;
|
|
51
|
+
* any other string is whatever a caller passes to `end()` directly.
|
|
51
52
|
*/
|
|
52
|
-
export type LyraTourEndReason='completed'|'skip'|'escape'|'api'|'unmount'|(string&Record<never,never>);export interface LyraTourEventMap{'lr-tour-start':CustomEvent<{readonly index:number;}>;
|
|
53
|
+
export type LyraTourEndReason='completed'|'skip'|'escape'|'api'|'unmount'|'unavailable'|(string&Record<never,never>);export interface LyraTourEventMap{'lr-tour-start':CustomEvent<{readonly index:number;}>;
|
|
53
54
|
/** Cancelable proposal to move to another step, fired before `activeIndex` changes. */
|
|
54
55
|
'lr-tour-step-change-request':CustomEvent<{readonly index:number;readonly previousIndex:number;readonly step:Readonly<LyraTourStep>;readonly via:'next'|'back'|'goto';}>;'lr-tour-end-request':CustomEvent<{reason:LyraTourEndReason;}>;'lr-tour-end':CustomEvent<{reason:LyraTourEndReason;}>;'lr-tour-target-missing':CustomEvent<{readonly index:number;readonly step:Readonly<LyraTourStep>;}>;}
|
|
55
56
|
/**
|
|
@@ -121,7 +122,8 @@ export type LyraTourEndReason='completed'|'skip'|'escape'|'api'|'unmount'|(strin
|
|
|
121
122
|
* @event lr-tour-end-request - Cancelable proposal before an ordinary tour end. `detail: { reason }`.
|
|
122
123
|
* Preventing it keeps the tour open. Removal from the document does not request permission.
|
|
123
124
|
* @event lr-tour-end - Non-cancelable notification after the tour closes. `detail: { reason }`.
|
|
124
|
-
* Forced removal emits reason `unmount
|
|
125
|
+
* Forced removal emits reason `unmount`; unavailable deferred placement emits `unavailable`.
|
|
126
|
+
* Neither requests permission because the closure cannot be vetoed.
|
|
125
127
|
* @event lr-tour-target-missing - The active step's `target` did not resolve to a connected
|
|
126
128
|
* element. `detail: { index, step }`. Not cancelable -- informational. The tour does not
|
|
127
129
|
* auto-end; it renders that step's popover unanchored (viewport-centered, no spotlight cutout)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{DeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{needsTopLayerEscape,promoteToTopLayer,releaseTopLayer}from"../../../internal/top-layer-escape.js";import{styles}from"./tour.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256,MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,SPOTLIGHT_PADDING_LENGTH=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em|vw|vh)$/i,spotlightPaddingConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return SPOTLIGHT_PADDING_LENGTH.test(trimmed)?trimmed:Number(value)}},TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.localName=="string"&&typeof value.matches=="function"}function isPlainRecord(value){if(typeof value!="object"||value===null)return!1;try{if(Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this.open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.withoutProgress=!1,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.end("escape")},onUnexpectedClose:()=>{this.end("escape"),this.open&&this.nativeModal.show()}}),this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.deferredFocusReturn=new DeferredFocusReturn,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;interactive&&this.nativeModal.hide(),this.nativeModal.prepare(!interactive)}if(this.open&&this.steps.length===0)this.open=!1,this.deactivateOverlayInternal();else if(changed.has("open"))if(this.open){this.deferredFocusReturn.cancel();const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal();this.nativeModal.show();const shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;this.nativeModal.show();const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.nativeModal.hide(),this.overlay?.suspend(),this.deferredFocusReturn.cancel(),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.open=!1,this.emit("lr-tour-end",{reason:"unmount"}))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.open=!0,this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-tour-end",{reason}))}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change-request",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;this.escapeContainingBlock();const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const reducedMotion=!target.ownerDocument.defaultView||prefersReducedMotion(this);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,this.spotlightPaddingPx(step),interactive)),this.placeCleanup}spotlightPaddingPx(step){const value=step.spotlightPadding??this.spotlightPadding,px=typeof value=="string"?resolveCssLength(value,{host:this})??Number.NaN:value;return finiteRange(px,DEFAULT_SPOTLIGHT_PADDING,0)}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.open=!1,this.deactivateOverlayInternal()}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=this.renderRoot.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const cutout=this.renderRoot?.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]');cutout&&(cutout.setAttribute("x","0"),cutout.setAttribute("y","0"),cutout.setAttribute("width","0"),cutout.setAttribute("height","0")),spotlight&&(spotlight.hidden=!0,spotlight.style.removeProperty("left"),spotlight.style.removeProperty("top"),spotlight.style.removeProperty("width"),spotlight.style.removeProperty("height")),backdrop?.style.removeProperty("clip-path")}escapeContainingBlock(){if(!(!needsTopLayerEscape(this)||!promoteToTopLayer(this))&&!this.escapedInset){const previous=["top","right","bottom","left"].map(property2=>({property:property2,value:this.style.getPropertyValue(property2),priority:this.style.getPropertyPriority(property2)}));this.style.setProperty("inset","0"),this.escapedInset={previous,written:this.style.getPropertyValue("top")}}}releaseContainingBlockEscape(){releaseTopLayer(this);const inset=this.escapedInset;if(this.escapedInset=void 0,!!inset)for(const{property:property2,value,priority}of inset.previous)this.style.getPropertyValue(property2)!==inset.written||this.style.getPropertyPriority(property2)!==""||(this.style.removeProperty(property2),value&&this.style.setProperty(property2,value,priority))}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.releaseContainingBlockEscape(),this.activeTargetSnapshot=null;const hadOverlay=this.overlay!==void 0;this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0;const trigger=this.focusReturnTarget;this.focusReturnTarget=null,hadOverlay&&trigger&&this.isConnected&&this.deferredFocusReturn.schedule({host:this,candidates:()=>[trigger.isConnected&&trigger.ownerDocument===this.ownerDocument?trigger:null],isCurrent:()=>!this.open})}ownsDirectionalKeys(event){return event.composedPath().some(node=>isElementNode(node)&&node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="combobox"], [role="grid"], [role="gridcell"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="scrollbar"], [role="slider"], [role="spinbutton"], [role="tab"], [role="tablist"], [role="tree"], [role="treeitem"]'))}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.withoutProgress?"":this.progressTextId].filter(id=>id.length>0).join(" ");return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{DeferredFocusReturn}from"../../../internal/deferred-focus-return.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{needsTopLayerEscape,promoteToTopLayer,releaseTopLayer}from"../../../internal/top-layer-escape.js";import{styles}from"./tour.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256,MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,SPOTLIGHT_PADDING_LENGTH=/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em|vw|vh)$/i,spotlightPaddingConverter={fromAttribute:value=>{if(value===null)return value;const trimmed=value.trim();return SPOTLIGHT_PADDING_LENGTH.test(trimmed)?trimmed:Number(value)}},TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.localName=="string"&&typeof value.matches=="function"}function isPlainRecord(value){if(typeof value!="object"||value===null)return!1;try{if(Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this.open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.withoutProgress=!1,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.end("escape")},onUnexpectedClose:()=>{this.end("escape"),this.open&&this.nativeModal.show()}}),this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.deferredFocusReturn=new DeferredFocusReturn,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;interactive&&this.nativeModal.hide(),this.nativeModal.prepare(!interactive)}if(this.open&&this.steps.length===0)this.open=!1,this.deactivateOverlayInternal();else if(changed.has("open"))if(this.open){this.deferredFocusReturn.cancel();const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal();this.nativeModal.show();const shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;this.nativeModal.show();const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.nativeModal.hide(),this.overlay?.suspend(),this.deferredFocusReturn.cancel(),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.open=!1,this.emit("lr-tour-end",{reason:"unmount"}))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.open=!0,this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end-request",{reason},{cancelable:!0}).defaultPrevented||(this.open=!1,this.emit("lr-tour-end",{reason}))}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change-request",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;this.escapeContainingBlock();const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const reducedMotion=!target.ownerDocument.defaultView||prefersReducedMotion(this);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,this.spotlightPaddingPx(step),interactive)),this.placeCleanup}spotlightPaddingPx(step){const value=step.spotlightPadding??this.spotlightPadding,px=typeof value=="string"?resolveCssLength(value,{host:this})??Number.NaN:value;return finiteRange(px,DEFAULT_SPOTLIGHT_PADDING,0)}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.open=!1,this.deactivateOverlayInternal(),this.emit("lr-tour-end",{reason:"unavailable"})}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=this.renderRoot.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const cutout=this.renderRoot?.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]');cutout&&(cutout.setAttribute("x","0"),cutout.setAttribute("y","0"),cutout.setAttribute("width","0"),cutout.setAttribute("height","0")),spotlight&&(spotlight.hidden=!0,spotlight.style.removeProperty("left"),spotlight.style.removeProperty("top"),spotlight.style.removeProperty("width"),spotlight.style.removeProperty("height")),backdrop?.style.removeProperty("clip-path")}escapeContainingBlock(){if(!(!needsTopLayerEscape(this)||!promoteToTopLayer(this))&&!this.escapedInset){const previous=["top","right","bottom","left"].map(property2=>({property:property2,value:this.style.getPropertyValue(property2),priority:this.style.getPropertyPriority(property2)}));this.style.setProperty("inset","0"),this.escapedInset={previous,written:this.style.getPropertyValue("top")}}}releaseContainingBlockEscape(){releaseTopLayer(this);const inset=this.escapedInset;if(this.escapedInset=void 0,!!inset)for(const{property:property2,value,priority}of inset.previous)this.style.getPropertyValue(property2)!==inset.written||this.style.getPropertyPriority(property2)!==""||(this.style.removeProperty(property2),value&&this.style.setProperty(property2,value,priority))}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.releaseContainingBlockEscape(),this.activeTargetSnapshot=null;const hadOverlay=this.overlay!==void 0;this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0;const trigger=this.focusReturnTarget;this.focusReturnTarget=null,hadOverlay&&trigger&&this.isConnected&&this.deferredFocusReturn.schedule({host:this,candidates:()=>[trigger.isConnected&&trigger.ownerDocument===this.ownerDocument?trigger:null],isCurrent:()=>!this.open})}ownsDirectionalKeys(event){return event.composedPath().some(node=>isElementNode(node)&&node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="combobox"], [role="grid"], [role="gridcell"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="scrollbar"], [role="slider"], [role="spinbutton"], [role="tab"], [role="tablist"], [role="tree"], [role="treeitem"]'))}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.withoutProgress?"":this.progressTextId].filter(id=>id.length>0).join(" ");return this.nativeModal.render(html`
|
|
2
2
|
<svg part="backdrop" aria-hidden="true" @click=${this.onBackdropClick}>
|
|
3
3
|
${this.unanchored?html`<rect class="scrim" x="0" y="0" width="100%" height="100%"></rect>`:html`
|
|
4
4
|
<defs>
|
|
@@ -2,4 +2,4 @@
|
|
|
2
2
|
* Generated from package.json by scripts/generate-package-metadata.mjs.
|
|
3
3
|
* Run `pnpm package-metadata` after changing package identity or version.
|
|
4
4
|
*/
|
|
5
|
-
export declare const LYRA_PACKAGE_NAME:'@aceshooting/lyra-ui';export declare const LYRA_PACKAGE_VERSION:'25.
|
|
5
|
+
export declare const LYRA_PACKAGE_NAME:'@aceshooting/lyra-ui';export declare const LYRA_PACKAGE_VERSION:'25.1.0';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="25.
|
|
1
|
+
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="25.1.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
|
|
@@ -399,8 +399,9 @@ options, and refreshes an async source when present; it preserves the committed
|
|
|
399
399
|
Activating the clear button is a user edit: when a query existed it emits `lr-filter` with
|
|
400
400
|
`value: ''` before the clear transaction finishes.
|
|
401
401
|
`lr-show` and `lr-hide` report the start of listbox visibility transitions. `lr-show` is a
|
|
402
|
-
cancelable veto point; `lr-hide` is cancelable
|
|
403
|
-
non-cancelable because
|
|
402
|
+
cancelable veto point; `lr-hide` is cancelable for ordinary connected dismissal, but closes after
|
|
403
|
+
disconnect or a positioning runtime failure are non-cancelable because they cannot honour a veto.
|
|
404
|
+
Vetoing an ordinary connected close
|
|
404
405
|
is atomic: the filter query, active option, async result rows, reflected `open` state, and overlay
|
|
405
406
|
ownership remain unchanged, so the host can defer dismissal without reconstructing the search.
|
|
406
407
|
`lr-after-show` and
|
|
@@ -64,7 +64,7 @@ accessor/inherited/malformed rows and invalid optional fields are omitted while
|
|
|
64
64
|
remain usable. Step ids and headings are bounded to 256 and 4,096 characters, target selector
|
|
65
65
|
strings to 8,192, and body content to 65,536. Per-step spotlight padding is finite, non-negative,
|
|
66
66
|
and capped at 10,000px. Provider mutation after assignment cannot change rendering or event detail.
|
|
67
|
-
`LyraTourEndReason = 'completed' | 'skip' | 'escape' | 'api' | 'unmount' | (string & {})`.
|
|
67
|
+
`LyraTourEndReason = 'completed' | 'skip' | 'escape' | 'api' | 'unmount' | 'unavailable' | (string & {})`.
|
|
68
68
|
|
|
69
69
|
**Methods:** `start(index = 0)` (clamps, opens, emits `lr-tour-start`), `next()` (on the last step
|
|
70
70
|
ends with `'completed'` instead), `back()` (no-op on the first step), `goToStep(index)` (clamped),
|
|
@@ -76,7 +76,9 @@ ends with `'completed'` instead), `back()` (no-op on the first step), `goToStep(
|
|
|
76
76
|
departure from `lr-carousel`'s non-cancelable `lr-slide-change`); `lr-tour-end-request`
|
|
77
77
|
(`detail: { reason }`, cancelable before ordinary completion); `lr-tour-end`
|
|
78
78
|
(`detail: { reason }`, non-cancelable after closing). Forced removal still notifies with reason
|
|
79
|
-
`unmount`, without a request because removal cannot be vetoed.
|
|
79
|
+
`unmount`, without a request because removal cannot be vetoed. If deferred placement fails, the
|
|
80
|
+
hidden panel closes with reason `unavailable`, also without a request; the host can use
|
|
81
|
+
`lr-tour-end` to clear its own open state. Migrate old raw-detail reads to
|
|
80
82
|
`detail.reason` and move end vetoes to `lr-tour-end-request`.
|
|
81
83
|
`lr-tour-target-missing` (`detail: { index, step }`, informational — the tour does **not** auto-end,
|
|
82
84
|
it renders that step viewport-centered with no spotlight).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aceshooting/lyra-ui",
|
|
3
|
-
"version": "25.
|
|
3
|
+
"version": "25.1.0",
|
|
4
4
|
"description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"web-components",
|