@aceshooting/lyra-ui 8.0.0 → 8.2.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 +199 -17
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
- package/dist/components/agent-tools/terminal/terminal.class.js +2 -2
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +5 -0
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -0
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/query-builder/query-builder.class.js +2 -2
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +8 -3
- package/dist/components/data/tree/tree-item.styles.js +11 -3
- package/dist/components/data/tree/tree.class.d.ts +11 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +3 -0
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -0
- package/dist/components/forms/locale-picker/locale-picker.class.js +4 -3
- package/dist/components/forms/locale-picker/locale-picker.styles.js +4 -0
- package/dist/components/forms/radio/radio-group.class.d.ts +3 -0
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +3 -0
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +9 -0
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/avatar/avatar.class.js +2 -2
- package/dist/components/media/flag/flag.class.js +2 -2
- package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +3 -2
- package/dist/components/viewers/page-rail/page-rail.class.js +2 -0
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/internal/anchor-target.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/safe-svg.d.ts +13 -0
- package/dist/internal/safe-svg.js +1 -0
- package/dist/testing/happy-dom-shims.d.ts +4 -0
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-attachment-chip.md +18 -10
- package/llms/components/lr-checkbox-group.md +2 -0
- package/llms/components/lr-graph-query-builder.md +3 -1
- package/llms/components/lr-locale-picker.md +6 -4
- package/llms/components/lr-radio-group.md +3 -1
- package/llms/components/lr-rubric-form.md +2 -0
- package/llms/components/lr-tool-param-form.md +3 -0
- package/llms/peers.md +3 -3
- package/llms-full.txt +36 -15
- package/package.json +9 -8
- package/vscode-html-data.json +7 -7
- package/web-types.json +8 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./flow-minimap.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flowMinimapInstructions,LYRA_DEFAULT_flowMinimapLabel,LYRA_DEFAULT_flowMinimapViewport,LYRA_DEFAULT_flowMinimapViewportChanged,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";class LyraFlowMinimap extends LyraElement{constructor(){super(...arguments);this.for="";this.label="";this.snapshot=null;this.liveText="";this.justDraggedViewport=false;this.announceNextSnapshot=false;this.instructionsId=nextId("flow-minimap-instructions");this.onMapClick=e=>{if(this.justDraggedViewport){this.justDraggedViewport=false;return}if(!this.canvasEl||!this.snapshot)return;const point=this.clientToContentPoint(e.currentTarget,e.clientX,e.clientY);const{zoom,width,height}=this.snapshot.viewport;this.canvasEl.setViewport({x:width/2-point.x*zoom,y:height/2-point.y*zoom,zoom})};this.onMapWheel=e=>{if(!this.canvasEl)return;e.preventDefault();if(e.deltaY<0)this.canvasEl.zoomIn();else this.canvasEl.zoomOut()};this.onViewportPointerDown=e=>{const dragEventWindow=this.ownerDocument.defaultView;if(!this.canvasEl||!this.snapshot||!dragEventWindow)return;e.stopPropagation();this.detachViewportDragListeners();this.dragState={pointerId:e.pointerId,startClientX:e.clientX,startClientY:e.clientY,startViewport:{...this.snapshot.viewport}};e.target.setPointerCapture?.(e.pointerId);this.dragEventWindow=dragEventWindow;dragEventWindow.addEventListener("pointermove",this.onViewportPointerMove);dragEventWindow.addEventListener("pointerup",this.onViewportPointerUp);dragEventWindow.addEventListener("pointercancel",this.onViewportPointerUp);dragEventWindow.addEventListener("lostpointercapture",this.onViewportPointerUp)};this.onViewportPointerMove=e=>{const drag=this.dragState;if(!drag||e.pointerId!==drag.pointerId||!this.canvasEl)return;this.justDraggedViewport=true;const svgEl=this.renderRoot.querySelector('[part="map"]');const ctm=svgEl?.getScreenCTM();if(!ctm)return;const scale=ctm.a||1;const dxContent=(e.clientX-drag.startClientX)/scale;const dyContent=(e.clientY-drag.startClientY)/scale;this.canvasEl.setViewport({x:drag.startViewport.x-dxContent*drag.startViewport.zoom,y:drag.startViewport.y-dyContent*drag.startViewport.zoom,zoom:drag.startViewport.zoom})};this.onViewportPointerUp=e=>{if(!this.dragState||e.pointerId!==this.dragState.pointerId)return;this.dragState=void 0;this.detachViewportDragListeners()};this.onViewportKeyDown=e=>{if(!this.canvasEl||!this.snapshot)return;if(e.key==="+"||e.key==="="){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.zoomIn();return}if(e.key==="-"||e.key==="_"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.zoomOut();return}if(e.key==="Enter"||e.key==="Home"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.fit();return}const{x,y,zoom,width,height}=this.snapshot.viewport;const stepX=width*.1;const stepY=height*.1;if(e.key==="ArrowRight"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x:x-stepX,y,zoom})}else if(e.key==="ArrowLeft"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x:x+stepX,y,zoom})}else if(e.key==="ArrowDown"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x,y:y-stepY,zoom})}else if(e.key==="ArrowUp"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x,y:y+stepY,zoom})}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flowMinimapInstructions:LYRA_DEFAULT_flowMinimapInstructions,flowMinimapLabel:LYRA_DEFAULT_flowMinimapLabel,flowMinimapViewport:LYRA_DEFAULT_flowMinimapViewport,flowMinimapViewportChanged:LYRA_DEFAULT_flowMinimapViewportChanged,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}connectedCallback(){super.connectedCallback();this.syncAnnouncementSink();this.watchForCanvas();this.resolveAndAttach()}disconnectedCallback(){super.disconnectedCallback();this.releaseAnnouncementSink();this.announceNextSnapshot=false;this.liveText="";this.unsubscribe?.();this.unsubscribe=void 0;this.canvasEl=void 0;this.canvasWatcher?.disconnect();this.canvasWatcher=void 0;this.dragState=void 0;this.detachViewportDragListeners()}releaseAnnouncementSink(){this.announcementSink?.release();this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}if(this.announcementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseAnnouncementSink();this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}willUpdate(changed){if(this.hasUpdated&&changed.has("for")){this.resolveAndAttach()}}resolveCanvas(){if(this.for){const root=this.getRootNode();const byId=root.getElementById?.(this.for);if(byId&&byId.tagName.toLowerCase()===tag("flow-canvas"))return byId}const ancestor=this.closest(tag("flow-canvas"));return ancestor??null}resolveAndAttach(){const canvas=this.resolveCanvas()??void 0;if(canvas===this.canvasEl)return;this.unsubscribe?.();this.unsubscribe=void 0;this.snapshot=null;this.canvasEl=canvas;if(!canvas)return;this.unsubscribe=canvas.registerCompanion(snapshot=>{this.snapshot=snapshot;if(this.announceNextSnapshot){this.announceNextSnapshot=false;const number=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0});const percent=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:1});const text=this.localize("flowMinimapViewportChanged",void 0,{x:number.format(snapshot.viewport.x),y:number.format(snapshot.viewport.y),zoom:percent.format(snapshot.viewport.zoom)});this.liveText=text;this.announcementSink?.announce(text)}})}watchForCanvas(){if(this.canvasWatcher)return;const root=this.getRootNode();const owner=this.ownerDocument.defaultView;const MutationObserverCtor=owner?.MutationObserver;if(!MutationObserverCtor)return;let observer;observer=new MutationObserverCtor(()=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.canvasWatcher!==observer){return}this.resolveAndAttach()});this.canvasWatcher=observer;observer.observe(root,{childList:true,subtree:true})}contentBounds(){const nodes=this.snapshot?.nodes??[];if(nodes.length===0)return{minX:0,minY:0,maxX:1,maxY:1};let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const n of nodes){minX=Math.min(minX,n.x);minY=Math.min(minY,n.y);maxX=Math.max(maxX,n.x+n.width);maxY=Math.max(maxY,n.y+n.height)}return{minX,minY,maxX,maxY}}viewportRectContent(){const vp=this.snapshot?.viewport;if(!vp||vp.zoom===0)return{x:0,y:0,width:0,height:0};return{x:-vp.x/vp.zoom,y:-vp.y/vp.zoom,width:vp.width/vp.zoom,height:vp.height/vp.zoom}}clientToContentPoint(svgEl,clientX,clientY){const ctm=svgEl.getScreenCTM();if(!ctm)return{x:0,y:0};const pt=svgEl.createSVGPoint();pt.x=clientX;pt.y=clientY;const transformed=pt.matrixTransform(ctm.inverse());return{x:transformed.x,y:transformed.y}}detachViewportDragListeners(){const dragEventWindow=this.dragEventWindow;if(!dragEventWindow)return;dragEventWindow.removeEventListener("pointermove",this.onViewportPointerMove);dragEventWindow.removeEventListener("pointerup",this.onViewportPointerUp);dragEventWindow.removeEventListener("pointercancel",this.onViewportPointerUp);dragEventWindow.removeEventListener("lostpointercapture",this.onViewportPointerUp);this.dragEventWindow=void 0}renderNodes(){return svg`${(this.snapshot?.nodes??[]).map(n=>svg`<rect part="node" data-status=${n.status??nothing} x=${n.x} y=${n.y} width=${n.width} height=${n.height} rx="2"></rect>`)}`}render(){const label=this.getAttribute("aria-label")||this.label||this.localize("flowMinimapLabel");if(!this.canvasEl||!this.snapshot){return html`<div part="base" aria-hidden="true"></div>`}const bounds=this.contentBounds();const padding=20;const vbX=bounds.minX-padding;const vbY=bounds.minY-padding;const vbW=Math.max(1,bounds.maxX-bounds.minX+padding*2);const vbH=Math.max(1,bounds.maxY-bounds.minY+padding*2);const viewportRect=this.viewportRectContent();return html`<div part="base" role="region" aria-label=${label}>
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./flow-minimap.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flowMinimapInstructions,LYRA_DEFAULT_flowMinimapLabel,LYRA_DEFAULT_flowMinimapViewport,LYRA_DEFAULT_flowMinimapViewportChanged,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";class LyraFlowMinimap extends LyraElement{constructor(){super(...arguments);this.for="";this.label="";this.snapshot=null;this.liveText="";this.justDraggedViewport=false;this.announceNextSnapshot=false;this.instructionsId=nextId("flow-minimap-instructions");this.onMapClick=e=>{if(this.justDraggedViewport){this.justDraggedViewport=false;return}if(!this.canvasEl||!this.snapshot||this.canvasEl.locked)return;const point=this.clientToContentPoint(e.currentTarget,e.clientX,e.clientY);const{zoom,width,height}=this.snapshot.viewport;this.canvasEl.setViewport({x:width/2-point.x*zoom,y:height/2-point.y*zoom,zoom})};this.onMapWheel=e=>{if(!this.canvasEl||this.canvasEl.locked)return;e.preventDefault();if(e.deltaY<0)this.canvasEl.zoomIn();else this.canvasEl.zoomOut()};this.onViewportPointerDown=e=>{const dragEventWindow=this.ownerDocument.defaultView;if(!this.canvasEl||!this.snapshot||!dragEventWindow||this.canvasEl.locked)return;e.stopPropagation();this.detachViewportDragListeners();this.dragState={pointerId:e.pointerId,startClientX:e.clientX,startClientY:e.clientY,startViewport:{...this.snapshot.viewport}};e.target.setPointerCapture?.(e.pointerId);this.dragEventWindow=dragEventWindow;dragEventWindow.addEventListener("pointermove",this.onViewportPointerMove);dragEventWindow.addEventListener("pointerup",this.onViewportPointerUp);dragEventWindow.addEventListener("pointercancel",this.onViewportPointerUp);dragEventWindow.addEventListener("lostpointercapture",this.onViewportPointerUp)};this.onViewportPointerMove=e=>{const drag=this.dragState;if(!drag||e.pointerId!==drag.pointerId||!this.canvasEl||this.canvasEl.locked)return;this.justDraggedViewport=true;const svgEl=this.renderRoot.querySelector('[part="map"]');const ctm=svgEl?.getScreenCTM();if(!ctm)return;const scale=ctm.a||1;const dxContent=(e.clientX-drag.startClientX)/scale;const dyContent=(e.clientY-drag.startClientY)/scale;this.canvasEl.setViewport({x:drag.startViewport.x-dxContent*drag.startViewport.zoom,y:drag.startViewport.y-dyContent*drag.startViewport.zoom,zoom:drag.startViewport.zoom})};this.onViewportPointerUp=e=>{if(!this.dragState||e.pointerId!==this.dragState.pointerId)return;this.dragState=void 0;this.detachViewportDragListeners()};this.onViewportKeyDown=e=>{if(!this.canvasEl||!this.snapshot||this.canvasEl.locked)return;if(e.key==="+"||e.key==="="){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.zoomIn();return}if(e.key==="-"||e.key==="_"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.zoomOut();return}if(e.key==="Enter"||e.key==="Home"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.fit();return}const{x,y,zoom,width,height}=this.snapshot.viewport;const stepX=width*.1;const stepY=height*.1;if(e.key==="ArrowRight"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x:x-stepX,y,zoom})}else if(e.key==="ArrowLeft"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x:x+stepX,y,zoom})}else if(e.key==="ArrowDown"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x,y:y-stepY,zoom})}else if(e.key==="ArrowUp"){e.preventDefault();this.announceNextSnapshot=true;this.canvasEl.setViewport({x,y:y+stepY,zoom})}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flowMinimapInstructions:LYRA_DEFAULT_flowMinimapInstructions,flowMinimapLabel:LYRA_DEFAULT_flowMinimapLabel,flowMinimapViewport:LYRA_DEFAULT_flowMinimapViewport,flowMinimapViewportChanged:LYRA_DEFAULT_flowMinimapViewportChanged,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}connectedCallback(){super.connectedCallback();this.syncAnnouncementSink();this.watchForCanvas();this.resolveAndAttach()}disconnectedCallback(){super.disconnectedCallback();this.releaseAnnouncementSink();this.announceNextSnapshot=false;this.liveText="";this.unsubscribe?.();this.unsubscribe=void 0;this.canvasEl=void 0;this.canvasWatcher?.disconnect();this.canvasWatcher=void 0;this.dragState=void 0;this.detachViewportDragListeners()}releaseAnnouncementSink(){this.announcementSink?.release();this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}if(this.announcementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseAnnouncementSink();this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}willUpdate(changed){if(this.hasUpdated&&changed.has("for")){this.resolveAndAttach()}}resolveCanvas(){if(this.for){const root=this.getRootNode();const byId=root.getElementById?.(this.for);if(byId&&byId.tagName.toLowerCase()===tag("flow-canvas"))return byId}const ancestor=this.closest(tag("flow-canvas"));return ancestor??null}resolveAndAttach(){const canvas=this.resolveCanvas()??void 0;if(canvas===this.canvasEl)return;this.unsubscribe?.();this.unsubscribe=void 0;this.snapshot=null;this.canvasEl=canvas;if(!canvas)return;this.unsubscribe=canvas.registerCompanion(snapshot=>{this.snapshot=snapshot;if(this.announceNextSnapshot){this.announceNextSnapshot=false;const number=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0});const percent=getNumberFormat(this.effectiveLocale,{style:"percent",maximumFractionDigits:1});const text=this.localize("flowMinimapViewportChanged",void 0,{x:number.format(snapshot.viewport.x),y:number.format(snapshot.viewport.y),zoom:percent.format(snapshot.viewport.zoom)});this.liveText=text;this.announcementSink?.announce(text)}})}watchForCanvas(){if(this.canvasWatcher)return;const root=this.getRootNode();const owner=this.ownerDocument.defaultView;const MutationObserverCtor=owner?.MutationObserver;if(!MutationObserverCtor)return;let observer;observer=new MutationObserverCtor(()=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.canvasWatcher!==observer){return}this.resolveAndAttach()});this.canvasWatcher=observer;observer.observe(root,{childList:true,subtree:true})}contentBounds(){const nodes=this.snapshot?.nodes??[];if(nodes.length===0)return{minX:0,minY:0,maxX:1,maxY:1};let minX=Infinity;let minY=Infinity;let maxX=-Infinity;let maxY=-Infinity;for(const n of nodes){minX=Math.min(minX,n.x);minY=Math.min(minY,n.y);maxX=Math.max(maxX,n.x+n.width);maxY=Math.max(maxY,n.y+n.height)}return{minX,minY,maxX,maxY}}viewportRectContent(){const vp=this.snapshot?.viewport;if(!vp||vp.zoom===0)return{x:0,y:0,width:0,height:0};return{x:-vp.x/vp.zoom,y:-vp.y/vp.zoom,width:vp.width/vp.zoom,height:vp.height/vp.zoom}}clientToContentPoint(svgEl,clientX,clientY){const ctm=svgEl.getScreenCTM();if(!ctm)return{x:0,y:0};const pt=svgEl.createSVGPoint();pt.x=clientX;pt.y=clientY;const transformed=pt.matrixTransform(ctm.inverse());return{x:transformed.x,y:transformed.y}}detachViewportDragListeners(){const dragEventWindow=this.dragEventWindow;if(!dragEventWindow)return;dragEventWindow.removeEventListener("pointermove",this.onViewportPointerMove);dragEventWindow.removeEventListener("pointerup",this.onViewportPointerUp);dragEventWindow.removeEventListener("pointercancel",this.onViewportPointerUp);dragEventWindow.removeEventListener("lostpointercapture",this.onViewportPointerUp);this.dragEventWindow=void 0}renderNodes(){return svg`${(this.snapshot?.nodes??[]).map(n=>svg`<rect part="node" data-status=${n.status??nothing} x=${n.x} y=${n.y} width=${n.width} height=${n.height} rx="2"></rect>`)}`}render(){const label=this.getAttribute("aria-label")||this.label||this.localize("flowMinimapLabel");if(!this.canvasEl||!this.snapshot){return html`<div part="base" aria-hidden="true"></div>`}const bounds=this.contentBounds();const padding=20;const vbX=bounds.minX-padding;const vbY=bounds.minY-padding;const vbW=Math.max(1,bounds.maxX-bounds.minX+padding*2);const vbH=Math.max(1,bounds.maxY-bounds.minY+padding*2);const viewportRect=this.viewportRectContent();return html`<div part="base" role="region" aria-label=${label}>
|
|
2
2
|
<svg
|
|
3
3
|
part="map"
|
|
4
4
|
viewBox="${vbX} ${vbY} ${vbW} ${vbH}"
|
|
@@ -308,6 +308,10 @@ export declare class LyraGraphQueryBuilder extends LyraElement<LyraGraphQueryBui
|
|
|
308
308
|
formResetCallback(): void;
|
|
309
309
|
formStateRestoreCallback(state: string | File | FormData | null, _mode?: 'restore' | 'autocomplete'): void;
|
|
310
310
|
formDisabledCallback(disabled: boolean): void;
|
|
311
|
+
private focusFirstControl;
|
|
312
|
+
/** Forwards host clicks to the first rendered control so callers can interact with this wrapper
|
|
313
|
+
* as if it exposed a single root control. */
|
|
314
|
+
click(): void;
|
|
311
315
|
private setValue;
|
|
312
316
|
private addRelationshipType;
|
|
313
317
|
private removeRelationshipType;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./graph-query-builder.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_graphQueryBuilderLabel,LYRA_DEFAULT_graphQueryDeleteWithContext,LYRA_DEFAULT_graphQueryDirectionLabel,LYRA_DEFAULT_graphQueryEndLabel,LYRA_DEFAULT_graphQueryHopRangeInvalid,LYRA_DEFAULT_graphQueryLoadWithContext,LYRA_DEFAULT_graphQueryMaxHopsLabel,LYRA_DEFAULT_graphQueryMinHopsLabel,LYRA_DEFAULT_graphQueryNodeTypeLabel,LYRA_DEFAULT_graphQueryRelationshipTypeLabel,LYRA_DEFAULT_graphQueryRun,LYRA_DEFAULT_graphQuerySaveButton,LYRA_DEFAULT_graphQuerySaveNameLabel,LYRA_DEFAULT_graphQuerySavedQueriesLabel,LYRA_DEFAULT_graphQueryStartLabel,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const EMPTY_VALUE={startId:"",endId:"",relationshipTypes:[],nodeTypes:[],direction:"both",minHops:1,maxHops:1};const EMPTY_OPTIONS=[];const EMPTY_SAVED=[];function stringArray(value){if(!Array.isArray(value))return[];return[...new Set(value.filter(entry=>typeof entry==="string"))]}function normalizeGraphQuery(value){const record=value!==null&&typeof value==="object"&&!Array.isArray(value)?value:{};const direction=record["direction"];return{startId:typeof record["startId"]==="string"?record["startId"]:"",endId:typeof record["endId"]==="string"?record["endId"]:"",relationshipTypes:stringArray(record["relationshipTypes"]),nodeTypes:stringArray(record["nodeTypes"]),direction:direction==="out"||direction==="in"||direction==="both"?direction:"both",minHops:finiteInteger(typeof record["minHops"]==="number"?record["minHops"]:EMPTY_VALUE.minHops,EMPTY_VALUE.minHops,1,20),maxHops:finiteInteger(typeof record["maxHops"]==="number"?record["maxHops"]:EMPTY_VALUE.maxHops,EMPTY_VALUE.maxHops,1,20)}}class LyraGraphQueryBuilder extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,graphQueryBuilderLabel:LYRA_DEFAULT_graphQueryBuilderLabel,graphQueryDeleteWithContext:LYRA_DEFAULT_graphQueryDeleteWithContext,graphQueryDirectionLabel:LYRA_DEFAULT_graphQueryDirectionLabel,graphQueryEndLabel:LYRA_DEFAULT_graphQueryEndLabel,graphQueryHopRangeInvalid:LYRA_DEFAULT_graphQueryHopRangeInvalid,graphQueryLoadWithContext:LYRA_DEFAULT_graphQueryLoadWithContext,graphQueryMaxHopsLabel:LYRA_DEFAULT_graphQueryMaxHopsLabel,graphQueryMinHopsLabel:LYRA_DEFAULT_graphQueryMinHopsLabel,graphQueryNodeTypeLabel:LYRA_DEFAULT_graphQueryNodeTypeLabel,graphQueryRelationshipTypeLabel:LYRA_DEFAULT_graphQueryRelationshipTypeLabel,graphQueryRun:LYRA_DEFAULT_graphQueryRun,graphQuerySaveButton:LYRA_DEFAULT_graphQuerySaveButton,graphQuerySaveNameLabel:LYRA_DEFAULT_graphQuerySaveNameLabel,graphQuerySavedQueriesLabel:LYRA_DEFAULT_graphQuerySavedQueriesLabel,graphQueryStartLabel:LYRA_DEFAULT_graphQueryStartLabel,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this.relationshipTypeOptions=EMPTY_OPTIONS;this.nodeTypeOptions=EMPTY_OPTIONS;this.savedQueries=EMPTY_SAVED;this.hopLimit=6;this.label="";this.hint="";this.errorText="";this._errors={};this.touchedFields=new Set;this.saveName="";this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("graph-query-builder-label");this.hintId=nextId("graph-query-builder-hint");this.errorId=nextId("graph-query-builder-error");this._fieldsetDisabled=false;this._name="";this._value=EMPTY_VALUE;this._disabled=false;this.hasInteracted=false;this.onChromeSlotChange=event=>{const slot=event.currentTarget;const hasContent=slot.assignedNodes({flatten:true}).some(node=>node.nodeType===Node.TEXT_NODE?Boolean(node.textContent?.trim()):true);if(slot.name==="hint")this.hasHintSlot=hasContent;else if(slot.name==="error")this.hasErrorSlot=hasContent};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get value(){return this._value}set value(next){const old=this._value;this._value=normalizeGraphQuery(next);this.syncFormState();this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}[VALIDITY_ANCHOR](){const firstInvalidPart=Object.keys(this._errors)[0];if(!firstInvalidPart||!this.renderRoot)return void 0;return this.renderRoot.querySelector(`[part="${firstInvalidPart}"]`)??void 0}computeValidation(){const errors={};const flags={};if(!this._value.startId.trim()){errors["start-input"]=this.localize("fieldRequired");flags.valueMissing=true}if(this._value.minHops>this._value.maxHops){errors["max-hops"]=this.localize("graphQueryHopRangeInvalid");flags.rangeUnderflow=true}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncValidityCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityCustomStates(){syncValidityStates(this.internals,{required:true,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value=EMPTY_VALUE;this.touchedFields=new Set;this.saveName=""}formStateRestoreCallback(state2,_mode){let restored=EMPTY_VALUE;if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=normalizeGraphQuery(parsed)}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}setValue(next){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value=next;this.emit("lr-input",{value:{...this._value}})}addRelationshipType(type){if(!type||this._value.relationshipTypes.includes(type))return;this.setValue({...this._value,relationshipTypes:[...this._value.relationshipTypes,type]})}removeRelationshipType(type){this.setValue({...this._value,relationshipTypes:this._value.relationshipTypes.filter(t=>t!==type)})}addNodeType(type){if(!type||this._value.nodeTypes.includes(type))return;this.setValue({...this._value,nodeTypes:[...this._value.nodeTypes,type]})}removeNodeType(type){this.setValue({...this._value,nodeTypes:this._value.nodeTypes.filter(t=>t!==type)})}markTouched(part){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(part))return;this.touchedFields=new Set(this.touchedFields).add(part)}runQuery(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-query-run",{query:{...this._value}})}saveQuery(){if(this.effectiveDisabled)return;const name=this.saveName.trim();if(!name)return;this.emit("lr-query-save",{name,query:{...this._value}});this.saveName=""}loadQuery(item){if(this.effectiveDisabled)return;this.setValue({...EMPTY_VALUE,...item.query});this.emit("lr-query-load",{id:item.id,query:{...this._value}})}deleteQuery(item){if(this.effectiveDisabled)return;this.emit("lr-query-delete",{id:item.id})}updated(changed){if(changed.has("value")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}}hopOptions(){const limit=finiteInteger(this.hopLimit,6,1,20);const options=new Set(Array.from({length:limit},(_,i)=>i+1));options.add(this._value.minHops);options.add(this._value.maxHops);return[...options].sort((a,b)=>a-b)}labelForType(options,value){return options.find(o=>o.value===value)?.label??value}renderTypeFilter(kind,options,selected,add,remove,disabled){const pickerPart=kind==="relationship"?"relationship-picker":"node-type-picker";const chipsPart=kind==="relationship"?"relationship-chips":"node-type-chips";const pickerLabel=kind==="relationship"?this.localize("graphQueryRelationshipTypeLabel"):this.localize("graphQueryNodeTypeLabel");const available=options.filter(o=>!selected.includes(o.value));return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./graph-query-builder.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_graphQueryBuilderLabel,LYRA_DEFAULT_graphQueryDeleteWithContext,LYRA_DEFAULT_graphQueryDirectionLabel,LYRA_DEFAULT_graphQueryEndLabel,LYRA_DEFAULT_graphQueryHopRangeInvalid,LYRA_DEFAULT_graphQueryLoadWithContext,LYRA_DEFAULT_graphQueryMaxHopsLabel,LYRA_DEFAULT_graphQueryMinHopsLabel,LYRA_DEFAULT_graphQueryNodeTypeLabel,LYRA_DEFAULT_graphQueryRelationshipTypeLabel,LYRA_DEFAULT_graphQueryRun,LYRA_DEFAULT_graphQuerySaveButton,LYRA_DEFAULT_graphQuerySaveNameLabel,LYRA_DEFAULT_graphQuerySavedQueriesLabel,LYRA_DEFAULT_graphQueryStartLabel,LYRA_DEFAULT_neighborDirectionBoth,LYRA_DEFAULT_neighborDirectionIn,LYRA_DEFAULT_neighborDirectionOut,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const EMPTY_VALUE={startId:"",endId:"",relationshipTypes:[],nodeTypes:[],direction:"both",minHops:1,maxHops:1};const EMPTY_OPTIONS=[];const EMPTY_SAVED=[];function stringArray(value){if(!Array.isArray(value))return[];return[...new Set(value.filter(entry=>typeof entry==="string"))]}function normalizeGraphQuery(value){const record=value!==null&&typeof value==="object"&&!Array.isArray(value)?value:{};const direction=record["direction"];return{startId:typeof record["startId"]==="string"?record["startId"]:"",endId:typeof record["endId"]==="string"?record["endId"]:"",relationshipTypes:stringArray(record["relationshipTypes"]),nodeTypes:stringArray(record["nodeTypes"]),direction:direction==="out"||direction==="in"||direction==="both"?direction:"both",minHops:finiteInteger(typeof record["minHops"]==="number"?record["minHops"]:EMPTY_VALUE.minHops,EMPTY_VALUE.minHops,1,20),maxHops:finiteInteger(typeof record["maxHops"]==="number"?record["maxHops"]:EMPTY_VALUE.maxHops,EMPTY_VALUE.maxHops,1,20)}}class LyraGraphQueryBuilder extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,graphQueryBuilderLabel:LYRA_DEFAULT_graphQueryBuilderLabel,graphQueryDeleteWithContext:LYRA_DEFAULT_graphQueryDeleteWithContext,graphQueryDirectionLabel:LYRA_DEFAULT_graphQueryDirectionLabel,graphQueryEndLabel:LYRA_DEFAULT_graphQueryEndLabel,graphQueryHopRangeInvalid:LYRA_DEFAULT_graphQueryHopRangeInvalid,graphQueryLoadWithContext:LYRA_DEFAULT_graphQueryLoadWithContext,graphQueryMaxHopsLabel:LYRA_DEFAULT_graphQueryMaxHopsLabel,graphQueryMinHopsLabel:LYRA_DEFAULT_graphQueryMinHopsLabel,graphQueryNodeTypeLabel:LYRA_DEFAULT_graphQueryNodeTypeLabel,graphQueryRelationshipTypeLabel:LYRA_DEFAULT_graphQueryRelationshipTypeLabel,graphQueryRun:LYRA_DEFAULT_graphQueryRun,graphQuerySaveButton:LYRA_DEFAULT_graphQuerySaveButton,graphQuerySaveNameLabel:LYRA_DEFAULT_graphQuerySaveNameLabel,graphQuerySavedQueriesLabel:LYRA_DEFAULT_graphQuerySavedQueriesLabel,graphQueryStartLabel:LYRA_DEFAULT_graphQueryStartLabel,neighborDirectionBoth:LYRA_DEFAULT_neighborDirectionBoth,neighborDirectionIn:LYRA_DEFAULT_neighborDirectionIn,neighborDirectionOut:LYRA_DEFAULT_neighborDirectionOut,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this.relationshipTypeOptions=EMPTY_OPTIONS;this.nodeTypeOptions=EMPTY_OPTIONS;this.savedQueries=EMPTY_SAVED;this.hopLimit=6;this.label="";this.hint="";this.errorText="";this._errors={};this.touchedFields=new Set;this.saveName="";this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("graph-query-builder-label");this.hintId=nextId("graph-query-builder-hint");this.errorId=nextId("graph-query-builder-error");this._fieldsetDisabled=false;this._name="";this._value=EMPTY_VALUE;this._disabled=false;this.hasInteracted=false;this.onChromeSlotChange=event=>{const slot=event.currentTarget;const hasContent=slot.assignedNodes({flatten:true}).some(node=>node.nodeType===Node.TEXT_NODE?Boolean(node.textContent?.trim()):true);if(slot.name==="hint")this.hasHintSlot=hasContent;else if(slot.name==="error")this.hasErrorSlot=hasContent};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get value(){return this._value}set value(next){const old=this._value;this._value=normalizeGraphQuery(next);this.syncFormState();this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}[VALIDITY_ANCHOR](){const firstInvalidPart=Object.keys(this._errors)[0];if(!firstInvalidPart||!this.renderRoot)return void 0;return this.renderRoot.querySelector(`[part="${firstInvalidPart}"]`)??void 0}computeValidation(){const errors={};const flags={};if(!this._value.startId.trim()){errors["start-input"]=this.localize("fieldRequired");flags.valueMissing=true}if(this._value.minHops>this._value.maxHops){errors["max-hops"]=this.localize("graphQueryHopRangeInvalid");flags.rangeUnderflow=true}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncValidityCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidityCustomStates(){syncValidityStates(this.internals,{required:true,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value=EMPTY_VALUE;this.touchedFields=new Set;this.saveName=""}formStateRestoreCallback(state2,_mode){let restored=EMPTY_VALUE;if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=normalizeGraphQuery(parsed)}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}focusFirstControl(){if(!this.renderRoot||this.effectiveDisabled)return;const control=this.renderRoot.querySelector('[part="start-input"]')||this.renderRoot.querySelector('[part="end-input"]')||this.renderRoot.querySelector('[part="min-hops"]')||this.renderRoot.querySelector('[part="max-hops"]')||this.renderRoot.querySelector('[part="direction"]')||this.renderRoot.querySelector('[part="save-name-input"]');control?.focus()}click(){this.focusFirstControl()}setValue(next){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value=next;this.emit("lr-input",{value:{...this._value}})}addRelationshipType(type){if(!type||this._value.relationshipTypes.includes(type))return;this.setValue({...this._value,relationshipTypes:[...this._value.relationshipTypes,type]})}removeRelationshipType(type){this.setValue({...this._value,relationshipTypes:this._value.relationshipTypes.filter(t=>t!==type)})}addNodeType(type){if(!type||this._value.nodeTypes.includes(type))return;this.setValue({...this._value,nodeTypes:[...this._value.nodeTypes,type]})}removeNodeType(type){this.setValue({...this._value,nodeTypes:this._value.nodeTypes.filter(t=>t!==type)})}markTouched(part){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(part))return;this.touchedFields=new Set(this.touchedFields).add(part)}runQuery(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-query-run",{query:{...this._value}})}saveQuery(){if(this.effectiveDisabled)return;const name=this.saveName.trim();if(!name)return;this.emit("lr-query-save",{name,query:{...this._value}});this.saveName=""}loadQuery(item){if(this.effectiveDisabled)return;this.setValue({...EMPTY_VALUE,...item.query});this.emit("lr-query-load",{id:item.id,query:{...this._value}})}deleteQuery(item){if(this.effectiveDisabled)return;this.emit("lr-query-delete",{id:item.id})}updated(changed){if(changed.has("value")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}}hopOptions(){const limit=finiteInteger(this.hopLimit,6,1,20);const options=new Set(Array.from({length:limit},(_,i)=>i+1));options.add(this._value.minHops);options.add(this._value.maxHops);return[...options].sort((a,b)=>a-b)}labelForType(options,value){return options.find(o=>o.value===value)?.label??value}renderTypeFilter(kind,options,selected,add,remove,disabled){const pickerPart=kind==="relationship"?"relationship-picker":"node-type-picker";const chipsPart=kind==="relationship"?"relationship-chips":"node-type-chips";const pickerLabel=kind==="relationship"?this.localize("graphQueryRelationshipTypeLabel"):this.localize("graphQueryNodeTypeLabel");const available=options.filter(o=>!selected.includes(o.value));return html`
|
|
2
2
|
<div part="filter-group" data-kind=${kind}>
|
|
3
3
|
<lr-select
|
|
4
4
|
part=${pickerPart}
|
|
@@ -110,7 +110,7 @@ import{html,nothing}from"lit";import{LyraElement}from"../../../internal/lyra-ele
|
|
|
110
110
|
icon="trash"
|
|
111
111
|
aria-label=${this.localize("queryBuilderRemoveCondition",void 0,{index:this.formatCount(index+1)})}
|
|
112
112
|
?disabled=${this.disabled}
|
|
113
|
-
@click=${()=>this.removeCondition(condition.id)}
|
|
113
|
+
@click=${event=>this.consumeChildEvent(event,()=>this.removeCondition(condition.id))}
|
|
114
114
|
></lr-icon-button>
|
|
115
115
|
</div>
|
|
116
116
|
`}render(){const hasFields=this._fields.length>0;const value=this._value;return html`
|
|
@@ -123,7 +123,7 @@ import{html,nothing}from"lit";import{LyraElement}from"../../../internal/lyra-ele
|
|
|
123
123
|
appearance="outlined"
|
|
124
124
|
size="s"
|
|
125
125
|
?disabled=${this.disabled}
|
|
126
|
-
@click=${()=>this.addCondition()}
|
|
126
|
+
@click=${event=>this.consumeChildEvent(event,()=>this.addCondition())}
|
|
127
127
|
>
|
|
128
128
|
${this.localize("queryBuilderAddCondition")}
|
|
129
129
|
</lr-button>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{srOnly,nextId}from"../../../internal/a11y.js";import{finiteCount,finiteInteger,finiteRatio}from"../../../internal/numbers.js";import{getCollator}from"../../../internal/intl-cache.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{styles}from"./table.styles.js";import{chevronIcon}from"../../../internal/icons.js";import{minMax}from"../heatmap/heatmap-scale.js";import"../../overlays/empty/empty.class.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_loading,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_showFewerColumns,LYRA_DEFAULT_tableEditCell,LYRA_DEFAULT_tableFilterLabel,LYRA_DEFAULT_tableFilterPlaceholder,LYRA_DEFAULT_tableLoading}from"../../../internal/default-strings.generated.js";const DEFAULT_SKELETON_ROWS=3;const MAX_DERIVED_SKELETON_ROWS=20;const optionalBooleanConverter={fromAttribute(value){if(value===null)return void 0;return value!=="false"},toAttribute(value){if(value===void 0)return null;return value?"":"false"}};function isDevelopmentRuntime(){const nodeEnv=globalThis.process?.env?.NODE_ENV;if(nodeEnv==="production")return false;if(nodeEnv==="development")return true;const viteEnv=import.meta.env;if(typeof viteEnv?.DEV==="boolean")return viteEnv.DEV;return viteEnv?.MODE==="development"}const INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"], [role="option"], [role="radio"], [role="separator"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"], [role="textbox"]';function stickyDirection(sticky){if(sticky===true)return"start";if(sticky==="start"||sticky==="end")return sticky;return void 0}function editTrigger(editable){if(editable==="always")return"always";if(editable===true)return"double-click";return void 0}function encodeKey(key){return`${typeof key}:${key}`}function safeStringifyForFilter(row){const seen=new WeakSet;try{return JSON.stringify(row,(_key,value)=>{if(typeof value==="bigint")return value.toString();if(typeof value==="object"&&value!==null){if(seen.has(value))return"[Circular]";seen.add(value)}return value})??""}catch{return""}}function closestInteractive(target,boundary){let el=target;while(el&&el!==boundary){if(el.matches(INTERACTIVE_SELECTOR)&&!el.matches("[data-row-key], th[data-col-key]")||el.tagName.includes("-"))return el;el=el.parentElement}return null}class LyraTable extends LyraElement{constructor(){super(...arguments);this.columns=[];this.rows=[];this.layout="auto";this.sortKey="";this.sortDir="asc";this.sortMode="client";this.defaultSortDir="asc";this.accessibleLabel="";this.caption="";this.captionId=nextId("lr-table-caption");this.selectedKey=null;this.selectionMode="none";this.selectedKeys=new Set;this.filterable=false;this.filterText="";this.filterLabel="";this.filterPlaceholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.loading=false;this.loadingLabel="";this.loadingAppearance="spinner";this.skeletonRows=0;this.pageSize=0;this.page=1;this.totalItems=-1;this.paginationMode="client";this.expandedKeys=new Set;this.hasMore=false;this.moreLabel="";this.emptyHeading="";this.emptyDescription="";this.noColumnsHeading="";this.noColumnsDescription="";this.revealColumnsLabel="";this.hideColumnsLabel="";this.columnsHidden=false;this.showAllColumns=false;this.persistReady=false;this.loadingAnnouncementsReady=false;this.activeColKey=null;this.activeRowKey=null;this.editingCell=null;this.focusedEditorCell=null;this.editorHadFocusBeforeUpdate=false;this.resizedColumnWidths=new Map;this.rowsByKey=new Map;this.columnsByKey=new Map;this.layoutFrame=null;this.observedHeaders=new Set;this.onResizePointerDown=event=>{const handle=event.currentTarget;const key=handle.dataset["colKey"];const column=key?this.columnsByKey.get(key):void 0;const header=handle.closest("th[data-col-key]");const resizeEventWindow=this.ownerDocument.defaultView;if(!key||!column||!header||!resizeEventWindow)return;const replacedStartWidth=this.resizeState?.key===key?this.resizeState.startWidth:void 0;this.cancelResizeGesture();const minWidth=this.minimumResizeWidth(column);this.resizeState={key,pointerId:event.pointerId,startX:event.clientX,startWidth:replacedStartWidth??header.getBoundingClientRect().width,minWidth,maxWidth:this.maximumResizeWidth(column,minWidth),handle,previousWidth:this.resizedColumnWidths.get(key)};event.preventDefault();event.stopPropagation();handle.setPointerCapture?.(event.pointerId);this.resizeEventWindow=resizeEventWindow;resizeEventWindow.addEventListener("pointermove",this.onResizePointerMove);resizeEventWindow.addEventListener("pointerup",this.onResizePointerEnd);resizeEventWindow.addEventListener("pointercancel",this.onResizePointerEnd);resizeEventWindow.addEventListener("lostpointercapture",this.onResizePointerEnd)};this.onResizePointerMove=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;const delta=isRtl(this)?state2.startX-event.clientX:event.clientX-state2.startX;const width=Math.min(state2.maxWidth,Math.max(state2.minWidth,state2.startWidth+delta));if(this.resizedColumnWidths.get(state2.key)===width)return;this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(state2.key,width);this.emit("lr-column-resize",{key:state2.key,width})};this.onResizeKeyDown=event=>{const handle=event.currentTarget;const key=handle.dataset["colKey"];const column=key?this.columnsByKey.get(key):void 0;if(!column)return;const minWidth=this.minimumResizeWidth(column);const maxWidth=this.maximumResizeWidth(column,minWidth);const currentWidth=this.currentResizeWidth(column,handle);const step=event.shiftKey?50:10;let requestedWidth;if(event.key==="Home")requestedWidth=minWidth;else if(event.key==="End"&&Number.isFinite(maxWidth))requestedWidth=maxWidth;else if(event.key==="ArrowLeft")requestedWidth=currentWidth+(isRtl(this)?step:-step);else if(event.key==="ArrowRight")requestedWidth=currentWidth+(isRtl(this)?-step:step);if(requestedWidth===void 0)return;event.preventDefault();event.stopPropagation();this.resizeColumnTo(column,requestedWidth)};this.onResizePointerEnd=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;if(event.type==="pointerup"){try{state2.handle.releasePointerCapture?.(event.pointerId)}catch{}}this.resizeState=void 0;this.detachResizePointerListeners();if(event.type!=="pointerup"){const reverted2=new Map(this.resizedColumnWidths);if(state2.previousWidth===void 0)reverted2.delete(state2.key);else reverted2.set(state2.key,state2.previousWidth);this.resizedColumnWidths=reverted2;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth)return;const commitEvent=this.emit("lr-column-resize",{key:state2.key,width:committedWidth},{cancelable:true});if(!commitEvent.defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);if(state2.previousWidth===void 0)reverted.delete(state2.key);else reverted.set(state2.key,state2.previousWidth);this.resizedColumnWidths=reverted};this.scheduleLayoutSync=()=>{if(this.layoutFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{if(this.layoutFrame!==frame)return;this.layoutFrame=null;if(!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.recomputeColumnsHidden();this.applyStickyOffsets();this.syncResizeHandleValues()});this.layoutFrame=frame};this.cachedMatchingEntries=null;this.matchingEntriesInputs=null;this.cachedSortedEntries=null;this.sortedEntriesInputs=null;this.onFilterInput=event=>{const input=event.currentTarget;this.filterText=input.value;this.emit("lr-filter-change",{text:this.filterText})};this.onNativeFocus=event=>{event.stopPropagation();this.emit("focus")};this.onNativeBlur=event=>{event.stopPropagation();this.emit("blur")};this.onPaginationChange=event=>{event.stopPropagation();const{page}=event.detail;this.emit("lr-page-change",{page})};this.onTableFocusIn=event=>{const target=event.target;const cell=target?.closest?.("td[data-col-key]");const row=target?.closest?.("[data-row-key]");const columnKey=cell?.dataset["colKey"];const rowKey=row?.dataset["rowKey"];this.focusedEditorCell=target?.getAttribute("part")==="cell-editor"&&columnKey!==void 0&&rowKey!==void 0&&editTrigger(this.columnsByKey.get(columnKey)?.editable)==="always"?{rowKey,columnKey}:null};this.onEditorKeyDown=(event,rowKey,columnKey)=>{event.stopPropagation();const alwaysOn=editTrigger(this.columnsByKey.get(columnKey)?.editable)==="always";if(event.key==="Enter"){event.preventDefault();this.commitEdit(event,rowKey,columnKey)}else if(event.key==="Escape"&&!alwaysOn){event.preventDefault();this.editingCell=null}};this.onTableDoubleClick=event=>{const target=event.target;const table=event.currentTarget;if(closestInteractive(target,table))return;const cell=target.closest('[part="cell"][data-col-key]');const row=target.closest("[data-row-key]");if(cell&&row?.dataset["rowKey"]&&cell.dataset["colKey"]){this.startEditing(row.dataset["rowKey"],cell.dataset["colKey"])}};this.toggleColumns=()=>{this.showAllColumns=!this.showAllColumns;this.emit("lr-columns-revealed",{revealed:this.showAllColumns})};this.onTableClick=e=>{const target=e.target;const table=e.currentTarget;if(closestInteractive(target,table))return;const th=target.closest("th[data-col-key]");if(th)return this.activateColumn(th.dataset["colKey"]);const tr=target.closest("[data-row-key]");if(tr)this.activateRow(tr.dataset["rowKey"])};this.onTableKeyDown=e=>{const target=e.target;const table=e.currentTarget;if(closestInteractive(target,table))return;const th=target.closest("th[data-col-key]");if(th)return this.onHeaderKeyDown(e,th);const tr=target.closest("[data-row-key]");if(tr)this.onRowKeyDown(e,tr)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,resizeColumn:LYRA_DEFAULT_resizeColumn,showAllColumns:LYRA_DEFAULT_showAllColumns,showFewerColumns:LYRA_DEFAULT_showFewerColumns,tableEditCell:LYRA_DEFAULT_tableEditCell,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel,tableFilterPlaceholder:LYRA_DEFAULT_tableFilterPlaceholder,tableLoading:LYRA_DEFAULT_tableLoading}}static{this.styles=[LyraElement.styles,styles,srOnly]}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}parsePixelLength(value){if(!value)return void 0;const trimmed=value.trim();if(!trimmed.endsWith("px"))return void 0;const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)?parsed:void 0}minimumResizeWidth(column){const explicit=this.parsePixelLength(column.minWidth);if(explicit!==void 0)return Math.max(0,explicit);const ownerWindow=this.ownerDocument.defaultView;const hostStyle=ownerWindow?.getComputedStyle(this);const themed=hostStyle?.getPropertyValue("--lr-table-resize-min-width").trim()??"";const value=Number.parseFloat(themed);if(!Number.isFinite(value))return 48;if(themed.endsWith("rem")){const rootFontSize=Number.parseFloat(ownerWindow?.getComputedStyle(this.ownerDocument.documentElement).fontSize??"");return Number.isFinite(rootFontSize)?Math.max(0,value*rootFontSize):48}if(themed.endsWith("em")){const hostFontSize=Number.parseFloat(hostStyle?.fontSize??"");return Number.isFinite(hostFontSize)?Math.max(0,value*hostFontSize):48}return Math.max(0,value)}maximumResizeWidth(column,minWidth){const explicit=this.parsePixelLength(column.maxWidth);return explicit===void 0?Number.POSITIVE_INFINITY:Math.max(minWidth,explicit)}currentResizeWidth(column,handle){const resized=this.resizedColumnWidths.get(column.key);if(resized!==void 0)return resized;const explicit=this.parsePixelLength(column.width);if(explicit!==void 0)return explicit;const rendered=handle?.closest("th[data-col-key]")?.getBoundingClientRect().width;return rendered&&rendered>0?rendered:this.minimumResizeWidth(column)}resizeColumnTo(column,requestedWidth){const minWidth=this.minimumResizeWidth(column);const maxWidth=this.maximumResizeWidth(column,minWidth);const width=Math.min(maxWidth,Math.max(minWidth,requestedWidth));const previousWidth=this.resizedColumnWidths.get(column.key);if(previousWidth===width)return;this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width);const event=this.emit("lr-column-resize",{key:column.key,width},{cancelable:true});if(!event.defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);if(previousWidth===void 0)reverted.delete(column.key);else reverted.set(column.key,previousWidth);this.resizedColumnWidths=reverted}renderedColumnWidth(column){const resized=this.resizedColumnWidths.get(column.key);return resized===void 0?sanitizeCssLength(column.width,"height"):`${resized}px`}renderResizeHandle(column){if(!column.resizable)return nothing;const minWidth=this.minimumResizeWidth(column);const maxWidth=this.maximumResizeWidth(column,minWidth);return html`<span
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{srOnly,nextId}from"../../../internal/a11y.js";import{finiteCount,finiteInteger,finiteRatio}from"../../../internal/numbers.js";import{getCollator}from"../../../internal/intl-cache.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{styles}from"./table.styles.js";import{chevronIcon}from"../../../internal/icons.js";import{minMax}from"../heatmap/heatmap-scale.js";import"../../overlays/empty/empty.class.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_loading,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_showFewerColumns,LYRA_DEFAULT_tableEditCell,LYRA_DEFAULT_tableFilterLabel,LYRA_DEFAULT_tableFilterPlaceholder,LYRA_DEFAULT_tableLoading}from"../../../internal/default-strings.generated.js";const DEFAULT_SKELETON_ROWS=3;const MAX_DERIVED_SKELETON_ROWS=20;const UNSAFE_CSS_STRUCTURE=/[;{}]/;const URL_FUNCTION=/url\s*\(/i;const SAFE_STYLE_PROPERTY=/^-?[_a-zA-Z][\w-]*$|^--[a-zA-Z0-9_-]+$/;const optionalBooleanConverter={fromAttribute(value){if(value===null)return void 0;return value!=="false"},toAttribute(value){if(value===void 0)return null;return value?"":"false"}};function isDevelopmentRuntime(){const nodeEnv=globalThis.process?.env?.NODE_ENV;if(nodeEnv==="production")return false;if(nodeEnv==="development")return true;const viteEnv=import.meta.env;if(typeof viteEnv?.DEV==="boolean")return viteEnv.DEV;return viteEnv?.MODE==="development"}const INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"], [role="option"], [role="radio"], [role="separator"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"], [role="textbox"]';function stickyDirection(sticky){if(sticky===true)return"start";if(sticky==="start"||sticky==="end")return sticky;return void 0}function sanitizeCellStyle(cellStyle){if(cellStyle===void 0)return{};const safe={};for(const[rawProperty,rawValue]of Object.entries(cellStyle)){const property2=sanitizeCellStyleProperty(rawProperty);const value=sanitizeCellStyleValue(rawValue);if(property2===void 0||value===void 0)continue;const normalizedProperty=normalizeStyleProperty(property2);if(normalizedProperty.startsWith("--")||cssSupports(normalizedProperty,value)){safe[normalizedProperty]=value}}return safe}function sanitizeCellStyleProperty(property2){const normalized=property2.trim();if(!normalized||!SAFE_STYLE_PROPERTY.test(normalized))return void 0;return normalized}function normalizeStyleProperty(property2){if(property2.startsWith("--"))return property2;return property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function sanitizeCellStyleValue(value){if(typeof value!=="string")return void 0;const normalized=value.trim();if(!normalized||UNSAFE_CSS_STRUCTURE.test(normalized)||URL_FUNCTION.test(normalized)){return void 0}return normalized}function cssSupports(property2,value){if(typeof CSS==="undefined"||typeof CSS.supports!=="function")return true;return CSS.supports(property2,value)}function editTrigger(editable){if(editable==="always")return"always";if(editable===true)return"double-click";return void 0}function encodeKey(key){return`${typeof key}:${key}`}function safeStringifyForFilter(row){const seen=new WeakSet;try{return JSON.stringify(row,(_key,value)=>{if(typeof value==="bigint")return value.toString();if(typeof value==="object"&&value!==null){if(seen.has(value))return"[Circular]";seen.add(value)}return value})??""}catch{return""}}function closestInteractive(target,boundary){let el=target;while(el&&el!==boundary){if(el.matches(INTERACTIVE_SELECTOR)&&!el.matches("[data-row-key], th[data-col-key]")||el.tagName.includes("-"))return el;el=el.parentElement}return null}class LyraTable extends LyraElement{constructor(){super(...arguments);this.columns=[];this.rows=[];this.layout="auto";this.sortKey="";this.sortDir="asc";this.sortMode="client";this.defaultSortDir="asc";this.accessibleLabel="";this.caption="";this.captionId=nextId("lr-table-caption");this.selectedKey=null;this.selectionMode="none";this.selectedKeys=new Set;this.filterable=false;this.filterText="";this.filterLabel="";this.filterPlaceholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.loading=false;this.loadingLabel="";this.loadingAppearance="spinner";this.skeletonRows=0;this.pageSize=0;this.page=1;this.totalItems=-1;this.paginationMode="client";this.expandedKeys=new Set;this.hasMore=false;this.moreLabel="";this.emptyHeading="";this.emptyDescription="";this.noColumnsHeading="";this.noColumnsDescription="";this.revealColumnsLabel="";this.hideColumnsLabel="";this.columnsHidden=false;this.showAllColumns=false;this.persistReady=false;this.loadingAnnouncementsReady=false;this.activeColKey=null;this.activeRowKey=null;this.editingCell=null;this.focusedEditorCell=null;this.editorHadFocusBeforeUpdate=false;this.resizedColumnWidths=new Map;this.rowsByKey=new Map;this.columnsByKey=new Map;this.layoutFrame=null;this.observedHeaders=new Set;this.onResizePointerDown=event=>{const handle=event.currentTarget;const key=handle.dataset["colKey"];const column=key?this.columnsByKey.get(key):void 0;const header=handle.closest("th[data-col-key]");const resizeEventWindow=this.ownerDocument.defaultView;if(!key||!column||!header||!resizeEventWindow)return;const replacedStartWidth=this.resizeState?.key===key?this.resizeState.startWidth:void 0;this.cancelResizeGesture();const minWidth=this.minimumResizeWidth(column);this.resizeState={key,pointerId:event.pointerId,startX:event.clientX,startWidth:replacedStartWidth??header.getBoundingClientRect().width,minWidth,maxWidth:this.maximumResizeWidth(column,minWidth),handle,previousWidth:this.resizedColumnWidths.get(key)};event.preventDefault();event.stopPropagation();handle.setPointerCapture?.(event.pointerId);this.resizeEventWindow=resizeEventWindow;resizeEventWindow.addEventListener("pointermove",this.onResizePointerMove);resizeEventWindow.addEventListener("pointerup",this.onResizePointerEnd);resizeEventWindow.addEventListener("pointercancel",this.onResizePointerEnd);resizeEventWindow.addEventListener("lostpointercapture",this.onResizePointerEnd)};this.onResizePointerMove=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;const delta=isRtl(this)?state2.startX-event.clientX:event.clientX-state2.startX;const width=Math.min(state2.maxWidth,Math.max(state2.minWidth,state2.startWidth+delta));if(this.resizedColumnWidths.get(state2.key)===width)return;this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(state2.key,width);this.emit("lr-column-resize",{key:state2.key,width})};this.onResizeKeyDown=event=>{const handle=event.currentTarget;const key=handle.dataset["colKey"];const column=key?this.columnsByKey.get(key):void 0;if(!column)return;const minWidth=this.minimumResizeWidth(column);const maxWidth=this.maximumResizeWidth(column,minWidth);const currentWidth=this.currentResizeWidth(column,handle);const step=event.shiftKey?50:10;let requestedWidth;if(event.key==="Home")requestedWidth=minWidth;else if(event.key==="End"&&Number.isFinite(maxWidth))requestedWidth=maxWidth;else if(event.key==="ArrowLeft")requestedWidth=currentWidth+(isRtl(this)?step:-step);else if(event.key==="ArrowRight")requestedWidth=currentWidth+(isRtl(this)?-step:step);if(requestedWidth===void 0)return;event.preventDefault();event.stopPropagation();this.resizeColumnTo(column,requestedWidth)};this.onResizePointerEnd=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;if(event.type==="pointerup"){try{state2.handle.releasePointerCapture?.(event.pointerId)}catch{}}this.resizeState=void 0;this.detachResizePointerListeners();if(event.type!=="pointerup"){const reverted2=new Map(this.resizedColumnWidths);if(state2.previousWidth===void 0)reverted2.delete(state2.key);else reverted2.set(state2.key,state2.previousWidth);this.resizedColumnWidths=reverted2;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth)return;const commitEvent=this.emit("lr-column-resize",{key:state2.key,width:committedWidth},{cancelable:true});if(!commitEvent.defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);if(state2.previousWidth===void 0)reverted.delete(state2.key);else reverted.set(state2.key,state2.previousWidth);this.resizedColumnWidths=reverted};this.scheduleLayoutSync=()=>{if(this.layoutFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{if(this.layoutFrame!==frame)return;this.layoutFrame=null;if(!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.recomputeColumnsHidden();this.applyStickyOffsets();this.syncResizeHandleValues()});this.layoutFrame=frame};this.cachedMatchingEntries=null;this.matchingEntriesInputs=null;this.cachedSortedEntries=null;this.sortedEntriesInputs=null;this.onFilterInput=event=>{const input=event.currentTarget;this.filterText=input.value;this.emit("lr-filter-change",{text:this.filterText})};this.onNativeFocus=event=>{event.stopPropagation();this.emit("focus")};this.onNativeBlur=event=>{event.stopPropagation();this.emit("blur")};this.onPaginationChange=event=>{event.stopPropagation();const{page}=event.detail;this.emit("lr-page-change",{page})};this.onTableFocusIn=event=>{const target=event.target;const cell=target?.closest?.("td[data-col-key]");const row=target?.closest?.("[data-row-key]");const columnKey=cell?.dataset["colKey"];const rowKey=row?.dataset["rowKey"];this.focusedEditorCell=target?.getAttribute("part")==="cell-editor"&&columnKey!==void 0&&rowKey!==void 0&&editTrigger(this.columnsByKey.get(columnKey)?.editable)==="always"?{rowKey,columnKey}:null};this.onEditorKeyDown=(event,rowKey,columnKey)=>{event.stopPropagation();const alwaysOn=editTrigger(this.columnsByKey.get(columnKey)?.editable)==="always";if(event.key==="Enter"){event.preventDefault();this.commitEdit(event,rowKey,columnKey)}else if(event.key==="Escape"&&!alwaysOn){event.preventDefault();this.editingCell=null}};this.onTableDoubleClick=event=>{const target=event.target;const table=event.currentTarget;if(closestInteractive(target,table))return;const cell=target.closest('[part="cell"][data-col-key]');const row=target.closest("[data-row-key]");if(cell&&row?.dataset["rowKey"]&&cell.dataset["colKey"]){this.startEditing(row.dataset["rowKey"],cell.dataset["colKey"])}};this.toggleColumns=()=>{this.showAllColumns=!this.showAllColumns;this.emit("lr-columns-revealed",{revealed:this.showAllColumns})};this.onTableClick=e=>{const target=e.target;const table=e.currentTarget;if(closestInteractive(target,table))return;const th=target.closest("th[data-col-key]");if(th)return this.activateColumn(th.dataset["colKey"]);const tr=target.closest("[data-row-key]");if(tr)this.activateRow(tr.dataset["rowKey"])};this.onTableKeyDown=e=>{const target=e.target;const table=e.currentTarget;if(closestInteractive(target,table))return;const th=target.closest("th[data-col-key]");if(th)return this.onHeaderKeyDown(e,th);const tr=target.closest("[data-row-key]");if(tr)this.onRowKeyDown(e,tr)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,resizeColumn:LYRA_DEFAULT_resizeColumn,showAllColumns:LYRA_DEFAULT_showAllColumns,showFewerColumns:LYRA_DEFAULT_showFewerColumns,tableEditCell:LYRA_DEFAULT_tableEditCell,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel,tableFilterPlaceholder:LYRA_DEFAULT_tableFilterPlaceholder,tableLoading:LYRA_DEFAULT_tableLoading}}static{this.styles=[LyraElement.styles,styles,srOnly]}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}parsePixelLength(value){if(!value)return void 0;const trimmed=value.trim();if(!trimmed.endsWith("px"))return void 0;const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)?parsed:void 0}minimumResizeWidth(column){const explicit=this.parsePixelLength(column.minWidth);if(explicit!==void 0)return Math.max(0,explicit);const ownerWindow=this.ownerDocument.defaultView;const hostStyle=ownerWindow?.getComputedStyle(this);const themed=hostStyle?.getPropertyValue("--lr-table-resize-min-width").trim()??"";const value=Number.parseFloat(themed);if(!Number.isFinite(value))return 48;if(themed.endsWith("rem")){const rootFontSize=Number.parseFloat(ownerWindow?.getComputedStyle(this.ownerDocument.documentElement).fontSize??"");return Number.isFinite(rootFontSize)?Math.max(0,value*rootFontSize):48}if(themed.endsWith("em")){const hostFontSize=Number.parseFloat(hostStyle?.fontSize??"");return Number.isFinite(hostFontSize)?Math.max(0,value*hostFontSize):48}return Math.max(0,value)}maximumResizeWidth(column,minWidth){const explicit=this.parsePixelLength(column.maxWidth);return explicit===void 0?Number.POSITIVE_INFINITY:Math.max(minWidth,explicit)}currentResizeWidth(column,handle){const resized=this.resizedColumnWidths.get(column.key);if(resized!==void 0)return resized;const explicit=this.parsePixelLength(column.width);if(explicit!==void 0)return explicit;const rendered=handle?.closest("th[data-col-key]")?.getBoundingClientRect().width;return rendered&&rendered>0?rendered:this.minimumResizeWidth(column)}resizeColumnTo(column,requestedWidth){const minWidth=this.minimumResizeWidth(column);const maxWidth=this.maximumResizeWidth(column,minWidth);const width=Math.min(maxWidth,Math.max(minWidth,requestedWidth));const previousWidth=this.resizedColumnWidths.get(column.key);if(previousWidth===width)return;this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width);const event=this.emit("lr-column-resize",{key:column.key,width},{cancelable:true});if(!event.defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);if(previousWidth===void 0)reverted.delete(column.key);else reverted.set(column.key,previousWidth);this.resizedColumnWidths=reverted}renderedColumnWidth(column){const resized=this.resizedColumnWidths.get(column.key);return resized===void 0?sanitizeCssLength(column.width,"height"):`${resized}px`}renderResizeHandle(column){if(!column.resizable)return nothing;const minWidth=this.minimumResizeWidth(column);const maxWidth=this.maximumResizeWidth(column,minWidth);return html`<span
|
|
2
2
|
part="resize-handle"
|
|
3
3
|
data-col-key=${column.key}
|
|
4
4
|
role="separator"
|
|
@@ -147,7 +147,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
147
147
|
<span part="row-expand-icon" aria-hidden="true">${chevronIcon()}</span>
|
|
148
148
|
</button>`:nothing}
|
|
149
149
|
</td>`:nothing}
|
|
150
|
-
${this.columns.map(col=>{const heatShare=this.heatShare(col,row,heatDomain);const cellStyle={...col.cellStyle?col.cellStyle(row)??{}:
|
|
150
|
+
${this.columns.map(col=>{const heatShare=this.heatShare(col,row,heatDomain);const cellStyle={...sanitizeCellStyle(col.cellStyle?col.cellStyle(row)??{}:void 0),...heatShare!==null?{"--lr-table-heat-t":heatShare}:{}};const alwaysOn=editTrigger(col.editable)==="always";const editing=alwaysOn||editTrigger(col.editable)==="double-click"&&this.editingCell?.rowKey===encodeKey(key)&&this.editingCell.columnKey===col.key;const cellTitle=editing?void 0:col.cellTitle?.(row);return html`<td
|
|
151
151
|
part="cell"
|
|
152
152
|
role="gridcell"
|
|
153
153
|
data-col-key=${col.key}
|
|
@@ -214,9 +214,6 @@ import{css}from"lit";const styles=css`
|
|
|
214
214
|
[part='row'][data-stripe] {
|
|
215
215
|
background: var(--lr-table-row-stripe-bg, transparent);
|
|
216
216
|
}
|
|
217
|
-
[part='row']:hover {
|
|
218
|
-
background: var(--lr-color-brand-quiet);
|
|
219
|
-
}
|
|
220
217
|
/* Inline var() fallback rather than a :host declaration -- a :host-declared custom property is
|
|
221
218
|
re-declared on every instance and shadows any ancestor value, which would defeat the whole
|
|
222
219
|
point of the override hook. Needed because Shadow Parts forbids an attribute selector after
|
|
@@ -225,6 +222,14 @@ import{css}from"lit";const styles=css`
|
|
|
225
222
|
[part='row'][aria-selected='true'] {
|
|
226
223
|
background: var(--lr-table-row-selected-bg, var(--lr-color-brand-quiet));
|
|
227
224
|
}
|
|
225
|
+
/* MUST stay after the selected-row rule above: both are (0,2,0), so source order alone decides,
|
|
226
|
+
and the selected row is the one a user is most likely to hover next -- put this before and the
|
|
227
|
+
single most common hover in a selectable table would be the one hover with no feedback. Also a
|
|
228
|
+
distinct color-mix step rather than the plain brand-quiet fallback used elsewhere, since the
|
|
229
|
+
selected row's own resting fill already resolves to that same token by default. */
|
|
230
|
+
[part='row']:hover {
|
|
231
|
+
background: color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-hover));
|
|
232
|
+
}
|
|
228
233
|
/* MUST stay after the selected-row rule above: both are (0,2,0), so source order alone decides,
|
|
229
234
|
and the selected row is the one a user presses to DEselect -- put this first and the single
|
|
230
235
|
most common press in a selectable table would be the one press with no feedback. */
|
|
@@ -26,13 +26,21 @@ import{css}from"lit";const styles=css`
|
|
|
26
26
|
cursor: pointer;
|
|
27
27
|
border-radius: var(--lr-radius);
|
|
28
28
|
}
|
|
29
|
-
[part='row']:hover {
|
|
30
|
-
background: var(--lr-color-brand-quiet);
|
|
31
|
-
}
|
|
32
29
|
:host([aria-selected='true']) [part='row'] {
|
|
33
30
|
color: var(--lr-tree-selected-color, var(--lr-color-brand));
|
|
34
31
|
background: var(--lr-tree-selected-bg, var(--lr-color-brand-quiet));
|
|
35
32
|
}
|
|
33
|
+
/* MUST stay after the selected-row rule above, and the second arm exists so it can: a selected
|
|
34
|
+
row is matched at (0,3,0) there, which a bare [part='row']:hover ((0,2,0)) cannot reach, and the
|
|
35
|
+
already-selected item is exactly the row a user is most likely to hover next. Matching it
|
|
36
|
+
through :host() lands both arms at the same specificity as that rule, so source order decides --
|
|
37
|
+
and the :where() keeps the state qualifier itself out of the count. Also a distinct color-mix
|
|
38
|
+
step rather than the plain brand-quiet fallback used elsewhere, since the selected row's own
|
|
39
|
+
resting fill already resolves to that same token by default. */
|
|
40
|
+
[part='row']:hover,
|
|
41
|
+
:host(:where([aria-selected='true'])) [part='row']:hover {
|
|
42
|
+
background: color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-hover));
|
|
43
|
+
}
|
|
36
44
|
/* MUST stay after the selected-row rule above, and the second arm exists so it can: a selected
|
|
37
45
|
row is matched at (0,3,0) there, which a bare [part='row']:active ((0,2,0)) cannot reach, and
|
|
38
46
|
the already-selected item is exactly the row a user presses next. Matching it through :host()
|
|
@@ -323,6 +323,17 @@ export declare class LyraTree extends LyraElement<LyraTreeEventMap> {
|
|
|
323
323
|
* this method's own counterpart, `collapseAll()`) refuse to act on a node
|
|
324
324
|
* that's `!hasChildren`, which would otherwise leave the leaf permanently
|
|
325
325
|
* stuck with a reflected `expanded` attribute nothing can clear.
|
|
326
|
+
*
|
|
327
|
+
* Goes through each node's own `expand()` (rather than assigning `expanded`
|
|
328
|
+
* directly) so a not-yet-loaded `lazy` node is routed through
|
|
329
|
+
* `beginLazyLoad()` exactly as a click would -- `expand()` is the only code
|
|
330
|
+
* path that emits `lr-lazy-load` and waits for children, so assigning
|
|
331
|
+
* `expanded` directly here left a lazy node visually expanded with its
|
|
332
|
+
* content never actually requested. It also keeps `expandAll()`'s
|
|
333
|
+
* `lr-expand`/`lr-node-toggle` emits consistent with `collapseAll()`'s own
|
|
334
|
+
* `collapse()` calls below. A lazy node whose children have not arrived yet
|
|
335
|
+
* has none to recurse into, so `childrenOf(n)` naturally stops the walk
|
|
336
|
+
* there without this method ever waiting on the external response.
|
|
326
337
|
*/
|
|
327
338
|
expandAll(): Promise<void>;
|
|
328
339
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{tag}from"../../../internal/prefix.js";import{isRtl}from"../../../internal/rtl.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import"./tree-item.class.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_treeNodeMoved}from"../../../internal/default-strings.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]);function isInertWithin(node,root){for(let current=node;current&¤t!==root;current=current.parentElement){if(current.hasAttribute("inert"))return true}return false}class LyraTree extends LyraElement{constructor(){super(...arguments);this.data=[];this.label="";this.reorderable=false;this._selection="single";this.activeId=null;this.hasAuthoredItems=false;this.pendingFocusId=null;this.generatedNodes=new WeakSet;this.selectionSyncPending=true;this.dataSyncPending=false;this.inertMutationPending=false;this.lastFocusedNodeId=null;this.onTreeFocusIn=e=>{const item=e.composedPath().find(target=>target.nodeType===1&&target.localName===tag("tree-item"));if(item)this.lastFocusedNodeId=item.nodeId};this.onChildrenChanged=()=>{const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems();if(wasAuthored&&!this.hasAuthoredItems)this.dataSyncPending=true;this.selectionSyncPending=true;this.requestUpdate()};this.childObserverGeneration=0;this.onChildMutations=records=>{if(records.some(record=>record.attributeName==="inert"))this.inertMutationPending=true;this.onChildrenChanged()};this.onNodeActivate=e=>{const id=e.detail.id;const node=this.allNodeElements().find(candidate=>candidate.nodeId===id);if(node&&!node.isDisabled)this.activeId=id};this.onNodeSelect=event=>{const id=event.detail.id;const node=this.allNodeElements().find(candidate=>candidate.nodeId===id);if(!node||node.isDisabled)return;this.activeId=id;if(!this.updateSelectionFrom(node))return;this.emit("lr-selection-change",{selection:this.selectedItems})};this.onTreeKeyDown=e=>{const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId);const current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault();this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}const rtl=isRtl(this);const expandKey=rtl?"ArrowLeft":"ArrowRight";const collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault();this.focusNode(visible[Math.min(visible.length-1,currentIndex+1)]);break;case"ArrowUp":e.preventDefault();this.focusNode(visible[Math.max(0,currentIndex-1)]);break;case"Home":e.preventDefault();this.focusNode(visible[0]);break;case"End":e.preventDefault();this.focusNode(visible[visible.length-1]);break;case expandKey:e.preventDefault();if(!current.hasChildren)break;if(!current.expanded){current.expand()}else{const child=visible[currentIndex+1];if(child&&child.depth>current.depth)this.focusNode(child)}break;case collapseKey:e.preventDefault();if(current.hasChildren&¤t.expanded){current.collapse()}else{for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&sibling.depth<current.depth){this.focusNode(sibling);break}}}break;case"Enter":case" ":e.preventDefault();current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved}}static{this.styles=[LyraElement.styles,styles]}get selection(){return this._selection}set selection(value){const old=this._selection;const normalized=TREE_SELECTIONS.has(value)?value:"single";if(old===normalized)return;this._selection=normalized;this.selectionSyncPending=true;this.requestUpdate("selection",old)}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[];const seen=new Set;const walk=nodes=>{for(const node of nodes){if(seen.has(node))continue;seen.add(node);result.push(node);walk(this.childrenOf(node))}};walk(this.nodeElements);return result}get selectedItems(){return this.allNodeElements().filter(node=>node.selected)}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const context={selection:this.selection,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon")};for(const node of this.allNodeElements())node.setTreeContext(context)}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=false;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);node.setSelectionState(selected,false);if(selected)kept=true}}setBranchSelection(node,selected,leavesOnly){if(node.isDisabled)return;const children=this.childrenOf(node).filter(child=>!child.isDisabled);if(!leavesOnly||children.length===0){node.setSelectionState(leavesOnly&&node.hasChildren?false:selected,false)}else{node.setSelectionState(false,false)}for(const child of children)this.setBranchSelection(child,selected,leavesOnly)}deriveMultipleSelection(node,leavesOnly){if(node.isDisabled){node.setSelectionState(false,false);return"ignored"}const children=this.childrenOf(node).filter(child=>!child.isDisabled);if(children.length===0){if(leavesOnly&&node.hasChildren){node.setSelectionState(false,false);return"none"}node.setSelectionState(node.selected,false);return node.selected?"all":"none"}const states=children.map(child=>this.deriveMultipleSelection(child,leavesOnly)).filter(state2=>state2!=="ignored");if(states.length===0){node.setSelectionState(false,false);return"none"}const all=states.every(state2=>state2==="all");const none=states.every(state2=>state2==="none");node.setSelectionState(all,!all&&!none);return all?"all":none?"none":"some"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements()){if(node.selected&&this.childrenOf(node).length>0){this.setBranchSelection(node,true,leavesOnly)}}for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){if(this.selection==="single"||this.selection==="leaf")this.normalizeSingleSelection();else this.normalizeMultipleSelection()}selectionSignature(){return this.allNodeElements().map(node=>`${node.nodeId}:${node.selected?1:0}:${node.indeterminate?1:0}`).join("|")}updateSelectionFrom(node){if(node.isDisabled)return false;const before=this.selectionSignature();if(this.selection==="single"||this.selection==="leaf"){if(!this.selectableInSingleMode(node))return false;for(const candidate of this.allNodeElements()){candidate.setSelectionState(candidate===node,false)}}else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements){this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}return before!==this.selectionSignature()}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes){if(node.hasAttribute("slot"))node.removeAttribute("slot")}const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored){for(const node of nodes){if(this.generatedNodes.has(node))node.remove()}}this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[];const walk=nodes=>{for(const n of nodes){if(!this.isNavigable(n))continue;acc.push(n);if(n.expanded)walk(this.childrenOf(n))}};walk(this.nodeElements);return acc}findItem(items,id){const stack=[...items].reverse();const seen=new Set;while(stack.length>0){const item=stack.pop();if(seen.has(item))continue;seen.add(item);if(item.id===id)return item;if(item.children){for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];if(child)stack.push(child)}}}return void 0}firstEnabledId(items){const stack=[...items].reverse();const seen=new Set;while(stack.length>0){const item=stack.pop();if(seen.has(item))continue;seen.add(item);if(item.disabled)continue;return item.id}return null}isEnabledReachableId(items,id){const stack=[...items].reverse();const seen=new Set;while(stack.length>0){const item=stack.pop();if(seen.has(item))continue;seen.add(item);if(item.disabled)continue;if(item.id===id)return true;if(item.children){for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];if(child)stack.push(child)}}}return false}findSiblings(id,items=this.data,parentId=null){const stack=[{items,parentId}];const seen=new Set;while(stack.length>0){const current=stack.pop();if(seen.has(current.items))continue;seen.add(current.items);const index=current.items.findIndex(item=>item.id===id);if(index>=0)return{parentId:current.parentId,total:current.items.length,index};for(let i=current.items.length-1;i>=0;i--){const item=current.items[i];if(item?.children)stack.push({items:item.children,parentId:item.id})}}return void 0}findSlottedSiblings(node){const parent=node.parentElement;const parentItem=parent?.localName===tag("tree-item")?parent:null;const siblings=parentItem?parentItem.childItems():this.nodeElements;const index=siblings.indexOf(node);if(index<0)return void 0;return{parentId:parentItem?parentItem.nodeId:null,total:siblings.length,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=false;const visible=this.visibleNodeElements();if(visible.some(node=>node.nodeId===this.activeId))return;const displaced=this.activeId;this.activeId=visible[0]?.nodeId??null;if(!inertMutation||this.activeId==null)return;if(displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument;const active=deepActiveElementIn(ownerDocument);const strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;if(active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced)return;this.pendingFocusId=this.activeId}willUpdate(changed){super.willUpdate(changed);this.refreshAuthoredItems();if(changed.has("data")||changed.has("selection"))this.selectionSyncPending=true;if(this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=false;const focused=this.deepFocusedNode();const focusedId=focused?.nodeId??null;this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;if(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId)){this.activeId=this.firstEnabledId(this.data)}this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}if(this.inertMutationPending)this.resolveActiveFromDom()}updated(changed){super.updated(changed);if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements;const count=this.hasAuthoredItems?nodes.length:this.data.length;nodes.forEach((node,i)=>{node.activeId=this.activeId;node.setSize=count;node.posInSet=i+1;if(this.hasAuthoredItems)node.depth=0})}}connectedCallback(){super.connectedCallback();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{childList:true,subtree:true,attributes:true,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback();this.resetChildObserver()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(node.item)existingById.set(node.item.id,node)}const seen=new Set;let previousSibling=null;for(const item of this.data){const reused=!seen.has(item.id)?existingById.get(item.id):void 0;let node=reused;if(!node){node=this.ownerDocument.createElement(tag("tree-item"));this.generatedNodes.add(node)}node.item=item;node.depth=0;seen.add(item.id);const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;if(targetPosition!==node)this.insertBefore(node,targetPosition);previousSibling=node}for(const[id,node]of existingById){if(!seen.has(id))node.remove()}}focusNode(node){if(!node)return;this.activeId=node.nodeId;node.focus()}async getUpdateComplete(){const result=await super.getUpdateComplete();await cascadeUpdateComplete(this.nodeElements);this.applyTreeContext();if(this.selectionSyncPending){this.selectionSyncPending=false;this.normalizeSelection()}await cascadeUpdateComplete(this.nodeElements);if(this.pendingFocusId!=null){const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}return result}requestReorder(node,delta){const id=node.nodeId;const found=this.hasAuthoredItems?this.findSlottedSiblings(node):this.findSiblings(id);if(!found)return;const{parentId,total,index}=found;const toIndex=index+delta;if(toIndex<0||toIndex>=total)return;this.emit("lr-reorder",{id,parentId,fromIndex:index,toIndex});this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:node.nodeLabel,index:this.formatCount(toIndex+1),total:this.formatCount(total)}),{force:true})}async expandAll(){const setAll=async nodes=>{await Promise.all(nodes.map(async n=>{if(n.isDisabled){n.expanded=false;await n.updateComplete;return}if(n.hasChildren)n.expanded=true;await n.updateComplete;await setAll(this.childrenOf(n))}))};await setAll(this.nodeElements)}collapseAll(){const focused=this.deepFocusedNode();const setAll=nodes=>{for(const n of nodes){setAll(this.childrenOf(n));if(n.isDisabled)n.expanded=false;else n.collapse()}};const topLevel=this.nodeElements;setAll(topLevel);const activeTopLevel=this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId);if(!activeTopLevel){this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)}if(focused)this.pendingFocusId=this.activeId}render(){return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{tag}from"../../../internal/prefix.js";import{isRtl}from"../../../internal/rtl.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import"./tree-item.class.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_treeNodeMoved}from"../../../internal/default-strings.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]);function isInertWithin(node,root){for(let current=node;current&¤t!==root;current=current.parentElement){if(current.hasAttribute("inert"))return true}return false}class LyraTree extends LyraElement{constructor(){super(...arguments);this.data=[];this.label="";this.reorderable=false;this._selection="single";this.activeId=null;this.hasAuthoredItems=false;this.pendingFocusId=null;this.generatedNodes=new WeakSet;this.selectionSyncPending=true;this.dataSyncPending=false;this.inertMutationPending=false;this.lastFocusedNodeId=null;this.onTreeFocusIn=e=>{const item=e.composedPath().find(target=>target.nodeType===1&&target.localName===tag("tree-item"));if(item)this.lastFocusedNodeId=item.nodeId};this.onChildrenChanged=()=>{const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems();if(wasAuthored&&!this.hasAuthoredItems)this.dataSyncPending=true;this.selectionSyncPending=true;this.requestUpdate()};this.childObserverGeneration=0;this.onChildMutations=records=>{if(records.some(record=>record.attributeName==="inert"))this.inertMutationPending=true;this.onChildrenChanged()};this.onNodeActivate=e=>{const id=e.detail.id;const node=this.allNodeElements().find(candidate=>candidate.nodeId===id);if(node&&!node.isDisabled)this.activeId=id};this.onNodeSelect=event=>{const id=event.detail.id;const node=this.allNodeElements().find(candidate=>candidate.nodeId===id);if(!node||node.isDisabled)return;this.activeId=id;if(!this.updateSelectionFrom(node))return;this.emit("lr-selection-change",{selection:this.selectedItems})};this.onTreeKeyDown=e=>{const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId);const current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault();this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}const rtl=isRtl(this);const expandKey=rtl?"ArrowLeft":"ArrowRight";const collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault();this.focusNode(visible[Math.min(visible.length-1,currentIndex+1)]);break;case"ArrowUp":e.preventDefault();this.focusNode(visible[Math.max(0,currentIndex-1)]);break;case"Home":e.preventDefault();this.focusNode(visible[0]);break;case"End":e.preventDefault();this.focusNode(visible[visible.length-1]);break;case expandKey:e.preventDefault();if(!current.hasChildren)break;if(!current.expanded){current.expand()}else{const child=visible[currentIndex+1];if(child&&child.depth>current.depth)this.focusNode(child)}break;case collapseKey:e.preventDefault();if(current.hasChildren&¤t.expanded){current.collapse()}else{for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&sibling.depth<current.depth){this.focusNode(sibling);break}}}break;case"Enter":case" ":e.preventDefault();current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved}}static{this.styles=[LyraElement.styles,styles]}get selection(){return this._selection}set selection(value){const old=this._selection;const normalized=TREE_SELECTIONS.has(value)?value:"single";if(old===normalized)return;this._selection=normalized;this.selectionSyncPending=true;this.requestUpdate("selection",old)}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[];const seen=new Set;const walk=nodes=>{for(const node of nodes){if(seen.has(node))continue;seen.add(node);result.push(node);walk(this.childrenOf(node))}};walk(this.nodeElements);return result}get selectedItems(){return this.allNodeElements().filter(node=>node.selected)}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const context={selection:this.selection,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon")};for(const node of this.allNodeElements())node.setTreeContext(context)}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=false;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);node.setSelectionState(selected,false);if(selected)kept=true}}setBranchSelection(node,selected,leavesOnly){if(node.isDisabled)return;const children=this.childrenOf(node).filter(child=>!child.isDisabled);if(!leavesOnly||children.length===0){node.setSelectionState(leavesOnly&&node.hasChildren?false:selected,false)}else{node.setSelectionState(false,false)}for(const child of children)this.setBranchSelection(child,selected,leavesOnly)}deriveMultipleSelection(node,leavesOnly){if(node.isDisabled){node.setSelectionState(false,false);return"ignored"}const children=this.childrenOf(node).filter(child=>!child.isDisabled);if(children.length===0){if(leavesOnly&&node.hasChildren){node.setSelectionState(false,false);return"none"}node.setSelectionState(node.selected,false);return node.selected?"all":"none"}const states=children.map(child=>this.deriveMultipleSelection(child,leavesOnly)).filter(state2=>state2!=="ignored");if(states.length===0){node.setSelectionState(false,false);return"none"}const all=states.every(state2=>state2==="all");const none=states.every(state2=>state2==="none");node.setSelectionState(all,!all&&!none);return all?"all":none?"none":"some"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements()){if(node.selected&&this.childrenOf(node).length>0){this.setBranchSelection(node,true,leavesOnly)}}for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){if(this.selection==="single"||this.selection==="leaf")this.normalizeSingleSelection();else this.normalizeMultipleSelection()}selectionSignature(){return this.allNodeElements().map(node=>`${node.nodeId}:${node.selected?1:0}:${node.indeterminate?1:0}`).join("|")}updateSelectionFrom(node){if(node.isDisabled)return false;const before=this.selectionSignature();if(this.selection==="single"||this.selection==="leaf"){if(!this.selectableInSingleMode(node))return false;for(const candidate of this.allNodeElements()){candidate.setSelectionState(candidate===node,false)}}else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements){this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}return before!==this.selectionSignature()}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes){if(node.hasAttribute("slot"))node.removeAttribute("slot")}const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored){for(const node of nodes){if(this.generatedNodes.has(node))node.remove()}}this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[];const walk=nodes=>{for(const n of nodes){if(!this.isNavigable(n))continue;acc.push(n);if(n.expanded)walk(this.childrenOf(n))}};walk(this.nodeElements);return acc}findItem(items,id){const stack=[...items].reverse();const seen=new Set;while(stack.length>0){const item=stack.pop();if(seen.has(item))continue;seen.add(item);if(item.id===id)return item;if(item.children){for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];if(child)stack.push(child)}}}return void 0}firstEnabledId(items){const stack=[...items].reverse();const seen=new Set;while(stack.length>0){const item=stack.pop();if(seen.has(item))continue;seen.add(item);if(item.disabled)continue;return item.id}return null}isEnabledReachableId(items,id){const stack=[...items].reverse();const seen=new Set;while(stack.length>0){const item=stack.pop();if(seen.has(item))continue;seen.add(item);if(item.disabled)continue;if(item.id===id)return true;if(item.children){for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];if(child)stack.push(child)}}}return false}findSiblings(id,items=this.data,parentId=null){const stack=[{items,parentId}];const seen=new Set;while(stack.length>0){const current=stack.pop();if(seen.has(current.items))continue;seen.add(current.items);const index=current.items.findIndex(item=>item.id===id);if(index>=0)return{parentId:current.parentId,total:current.items.length,index};for(let i=current.items.length-1;i>=0;i--){const item=current.items[i];if(item?.children)stack.push({items:item.children,parentId:item.id})}}return void 0}findSlottedSiblings(node){const parent=node.parentElement;const parentItem=parent?.localName===tag("tree-item")?parent:null;const siblings=parentItem?parentItem.childItems():this.nodeElements;const index=siblings.indexOf(node);if(index<0)return void 0;return{parentId:parentItem?parentItem.nodeId:null,total:siblings.length,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=false;const visible=this.visibleNodeElements();if(visible.some(node=>node.nodeId===this.activeId))return;const displaced=this.activeId;this.activeId=visible[0]?.nodeId??null;if(!inertMutation||this.activeId==null)return;if(displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument;const active=deepActiveElementIn(ownerDocument);const strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;if(active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced)return;this.pendingFocusId=this.activeId}willUpdate(changed){super.willUpdate(changed);this.refreshAuthoredItems();if(changed.has("data")||changed.has("selection"))this.selectionSyncPending=true;if(this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=false;const focused=this.deepFocusedNode();const focusedId=focused?.nodeId??null;this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;if(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId)){this.activeId=this.firstEnabledId(this.data)}this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}if(this.inertMutationPending)this.resolveActiveFromDom()}updated(changed){super.updated(changed);if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements;const count=this.hasAuthoredItems?nodes.length:this.data.length;nodes.forEach((node,i)=>{node.activeId=this.activeId;node.setSize=count;node.posInSet=i+1;if(this.hasAuthoredItems)node.depth=0})}}connectedCallback(){super.connectedCallback();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{childList:true,subtree:true,attributes:true,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback();this.resetChildObserver()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(node.item)existingById.set(node.item.id,node)}const seen=new Set;let previousSibling=null;for(const item of this.data){const reused=!seen.has(item.id)?existingById.get(item.id):void 0;let node=reused;if(!node){node=this.ownerDocument.createElement(tag("tree-item"));this.generatedNodes.add(node)}node.item=item;node.depth=0;seen.add(item.id);const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;if(targetPosition!==node)this.insertBefore(node,targetPosition);previousSibling=node}for(const[id,node]of existingById){if(!seen.has(id))node.remove()}}focusNode(node){if(!node)return;this.activeId=node.nodeId;node.focus()}async getUpdateComplete(){const result=await super.getUpdateComplete();await cascadeUpdateComplete(this.nodeElements);this.applyTreeContext();if(this.selectionSyncPending){this.selectionSyncPending=false;this.normalizeSelection()}await cascadeUpdateComplete(this.nodeElements);if(this.pendingFocusId!=null){const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}return result}requestReorder(node,delta){const id=node.nodeId;const found=this.hasAuthoredItems?this.findSlottedSiblings(node):this.findSiblings(id);if(!found)return;const{parentId,total,index}=found;const toIndex=index+delta;if(toIndex<0||toIndex>=total)return;this.emit("lr-reorder",{id,parentId,fromIndex:index,toIndex});this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:node.nodeLabel,index:this.formatCount(toIndex+1),total:this.formatCount(total)}),{force:true})}async expandAll(){const setAll=async nodes=>{await Promise.all(nodes.map(async n=>{if(n.isDisabled){n.expanded=false;await n.updateComplete;return}if(n.hasChildren)n.expand();await n.updateComplete;await setAll(this.childrenOf(n))}))};await setAll(this.nodeElements)}collapseAll(){const focused=this.deepFocusedNode();const setAll=nodes=>{for(const n of nodes){setAll(this.childrenOf(n));if(n.isDisabled)n.expanded=false;else n.collapse()}};const topLevel=this.nodeElements;setAll(topLevel);const activeTopLevel=this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId);if(!activeTopLevel){this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)}if(focused)this.pendingFocusId=this.activeId}render(){return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base tree"
|
|
4
4
|
role="tree"
|
|
@@ -229,6 +229,9 @@ export declare class LyraCheckboxGroup extends LyraElement<LyraCheckboxGroupEven
|
|
|
229
229
|
* The message is caller-supplied content, so it is used verbatim and never localized here.
|
|
230
230
|
*/
|
|
231
231
|
setCustomValidity(message: string): void;
|
|
232
|
+
private focusFirstControl;
|
|
233
|
+
/** Forwards host clicks to the first enabled checkbox in the group. */
|
|
234
|
+
click(): void;
|
|
232
235
|
formResetCallback(): void;
|
|
233
236
|
formStateRestoreCallback(state: string | File | FormData | null, _mode?: 'restore' | 'autocomplete'): void;
|
|
234
237
|
formDisabledCallback(disabled: boolean): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}function warnValueAssigned(group){console.warn(`<lr-checkbox-group> \`value\` is derived from its <lr-checkbox> children and is overwritten by the next sync (any child toggle, a slot change, a \`name\`/\`required\` change, blur, or form reset), so assigning it has no lasting effect${group.name?` (name="${group.name}")`:""}. Set \`checked\` on the children instead.`)}function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},orientation:{reflect:true},value:{attribute:false,noAccessor:true}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.sync();this.requestUpdate("name",old)}get value(){return this._value}set value(next){if(!this._writingValue&&!this._warnedValueAssigned){this._warnedValueAssigned=true;warnValueAssigned(this)}const old=this._value;this._value=Array.isArray(next)?next:[];this.requestUpdate("value",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.sync();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.propagateDisabled();this.sync();this.requestUpdate("disabled",old)}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.touched=false;this.hasInteracted=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("checkbox-group-label");this.hintId=nextId("checkbox-group-hint");this.errorId=nextId("checkbox-group-error");this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this._value=[];this._writingValue=false;this._warnedValueAssigned=false;this._warnedDuplicateValues=new Set;this.childObserverGeneration=0;this.childControllers=new Map;this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target))return;event.stopImmediatePropagation();if(event.type!=="change"||this.effectiveDisabled)return;this.hasInteracted=true;this.sync();this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})};this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}if(records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))){this.propagateSize()}if(records.some(record=>this.isOwnedCheckbox(record.target)))this.sync()};this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label");this.hasHintSlot=this.hasDirectSupportSlot("hint");this.hasErrorSlot=this.hasDirectSupportSlot("error");this.reconcileChildControllers();if(!this.applyPendingRestore())this.sync();this.propagateDisabled();this.propagateSize()};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){this.boxes.forEach(box=>{box.size=this.size})}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}if(this._warnedDuplicateValues.has(value))continue;this._warnedDuplicateValues.add(value);warnDuplicateValue(this,value)}}sync(){const next=this.readValue();this.warnOnDuplicateValues();this._writingValue=true;try{this.value=next}finally{this._writingValue=false}const data=new FormData;if(this.name)next.forEach(value=>data.append(this.name,value));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next));if(!this.barredFromValidation&&this.required&&next.length===0)this.validityController.setValidity({valueMissing:true},this.localize("checkboxGroupRequired"));else this.validityController.setValidity({});this.reflectValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller);this.childControllers.delete(box);const nextOwner=this.checkboxGroupOwner(box);if(!nextOwner||nextOwner===this)box.setGroupDisabled?.(false)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!=="function")continue;const controller={hostUpdated:()=>{if(this.isConnected&&this.ownsCheckbox(box))this.sync()}};box.addController(controller);this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return false;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on";const index=remaining.indexOf(value);box.checked=index>=0;if(index>=0)remaining.splice(index,1)}this.touched=false;this.hasInteracted=false;this.sync();return true}connectedCallback(){super.connectedCallback();this.addEventListener("input",this.onChildEvent);this.addEventListener("change",this.onChildEvent);this.addEventListener("lr-change",this.onChildEvent);this.onSlotChange();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.removeEventListener("input",this.onChildEvent);this.removeEventListener("change",this.onChildEvent);this.removeEventListener("lr-change",this.onChildEvent);this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller);box.setGroupDisabled?.(false)}this.childControllers.clear();super.disconnectedCallback()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}firstUpdated(){this.addEventListener("blur",()=>{this.touched=true;this.hasInteracted=true;this.sync()},true)}updated(changed){super.updated(changed);if(changed.has("size"))this.propagateSize()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="options"]')??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup());this.touched=false;this.hasInteracted=false;this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2);this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.propagateDisabled();this.sync();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||Boolean(this.hint)||this.withHint;const described=[hasHint?this.hintId:"",this.hasErrorSlot||this.errorText?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<fieldset
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}function warnValueAssigned(group){console.warn(`<lr-checkbox-group> \`value\` is derived from its <lr-checkbox> children and is overwritten by the next sync (any child toggle, a slot change, a \`name\`/\`required\` change, blur, or form reset), so assigning it has no lasting effect${group.name?` (name="${group.name}")`:""}. Set \`checked\` on the children instead.`)}function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},orientation:{reflect:true},value:{attribute:false,noAccessor:true}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.sync();this.requestUpdate("name",old)}get value(){return this._value}set value(next){if(!this._writingValue&&!this._warnedValueAssigned){this._warnedValueAssigned=true;warnValueAssigned(this)}const old=this._value;this._value=Array.isArray(next)?next:[];this.requestUpdate("value",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.sync();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.propagateDisabled();this.sync();this.requestUpdate("disabled",old)}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.touched=false;this.hasInteracted=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("checkbox-group-label");this.hintId=nextId("checkbox-group-hint");this.errorId=nextId("checkbox-group-error");this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this._value=[];this._writingValue=false;this._warnedValueAssigned=false;this._warnedDuplicateValues=new Set;this.childObserverGeneration=0;this.childControllers=new Map;this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target))return;event.stopImmediatePropagation();if(event.type!=="change"||this.effectiveDisabled)return;this.hasInteracted=true;this.sync();this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})};this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}if(records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))){this.propagateSize()}if(records.some(record=>this.isOwnedCheckbox(record.target)))this.sync()};this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label");this.hasHintSlot=this.hasDirectSupportSlot("hint");this.hasErrorSlot=this.hasDirectSupportSlot("error");this.reconcileChildControllers();if(!this.applyPendingRestore())this.sync();this.propagateDisabled();this.propagateSize()};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){this.boxes.forEach(box=>{box.size=this.size})}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}if(this._warnedDuplicateValues.has(value))continue;this._warnedDuplicateValues.add(value);warnDuplicateValue(this,value)}}sync(){const next=this.readValue();this.warnOnDuplicateValues();this._writingValue=true;try{this.value=next}finally{this._writingValue=false}const data=new FormData;if(this.name)next.forEach(value=>data.append(this.name,value));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next));if(!this.barredFromValidation&&this.required&&next.length===0)this.validityController.setValidity({valueMissing:true},this.localize("checkboxGroupRequired"));else this.validityController.setValidity({});this.reflectValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller);this.childControllers.delete(box);const nextOwner=this.checkboxGroupOwner(box);if(!nextOwner||nextOwner===this)box.setGroupDisabled?.(false)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!=="function")continue;const controller={hostUpdated:()=>{if(this.isConnected&&this.ownsCheckbox(box))this.sync()}};box.addController(controller);this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return false;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on";const index=remaining.indexOf(value);box.checked=index>=0;if(index>=0)remaining.splice(index,1)}this.touched=false;this.hasInteracted=false;this.sync();return true}connectedCallback(){super.connectedCallback();this.addEventListener("input",this.onChildEvent);this.addEventListener("change",this.onChildEvent);this.addEventListener("lr-change",this.onChildEvent);this.onSlotChange();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.removeEventListener("input",this.onChildEvent);this.removeEventListener("change",this.onChildEvent);this.removeEventListener("lr-change",this.onChildEvent);this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller);box.setGroupDisabled?.(false)}this.childControllers.clear();super.disconnectedCallback()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}firstUpdated(){this.addEventListener("blur",()=>{this.touched=true;this.hasInteracted=true;this.sync()},true)}updated(changed){super.updated(changed);if(changed.has("size"))this.propagateSize()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="options"]')??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}focusFirstControl(){const first=this.boxes.find(box=>!box.effectiveDisabled);first?.focus()}click(){this.focusFirstControl()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup());this.touched=false;this.hasInteracted=false;this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2);this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.propagateDisabled();this.sync();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||Boolean(this.hint)||this.withHint;const described=[hasHint?this.hintId:"",this.hasErrorSlot||this.errorText?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<fieldset
|
|
2
2
|
part="form-control"
|
|
3
3
|
?disabled=${this.effectiveDisabled}
|
|
4
4
|
aria-label=${this.accessibleLabel||nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{syncAriaControlsElements,syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{attachInternalsSafely,getFormOwner,setFormOwner}from"../../../internal/form-associated.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{EXTERNAL_LABEL_ACTIVATION}from"../../../internal/form-control-labels.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_iconButtonLabel,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]);const SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-"))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)copy.setAttribute(attribute.name,attribute.value)
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{syncAriaControlsElements,syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{attachInternalsSafely,getFormOwner,setFormOwner}from"../../../internal/form-associated.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute}from"../../../internal/safe-svg.js";import{EXTERNAL_LABEL_ACTIVATION}from"../../../internal/form-control-labels.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_iconButtonLabel,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]);const SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-"))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes){if(isUnsafeSvgCloneAttribute(attribute.name))continue;copy.setAttribute(attribute.name,attribute.value)}for(const child of node.childNodes){if(child.nodeType===3){copy.append(child.cloneNode(true))}else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);if(childCopy)copy.append(childCopy)}}return copy}class LyraIconButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}static{this.formAssociated=true}static{this.properties={disabled:{type:Boolean,reflect:true,noAccessor:true}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get name(){return this.icon}set name(next){this.icon=next??""}constructor(){super();this._disabled=false;this._fieldsetDisabled=false;this.hasSyncedDescribedByElements=false;this.icon="";this.accessibleLabel="";this.triggerHasPopup=null;this.triggerExpanded=null;this.triggerControls=null;this.triggerDescribedBy=null;this.label="";this.type="button";this.hasBareGeometry=false;this.onClick=()=>{if(this.effectiveDisabled)return;if(this.type==="submit"){this.getForm()?.requestSubmit()}else if(this.type==="reset"){this.getForm()?.reset()}};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{relayNativeEvent(this,event);this.emit("lr-blur")};this.onSlotChange=()=>{const assigned=this.slotEl?.assignedElements({flatten:true})??[];this.hasBareGeometry=assigned.some(el=>needsSvgNamespaceFallback(el))};this.internals=attachInternalsSafely(this)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}click(){if(this.effectiveDisabled)return;this.baseEl?.click()}focus(options){if(!this.effectiveDisabled)this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[EXTERNAL_LABEL_ACTIVATION](){return"activate"}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.requestUpdate()}updated(changed){super.updated(changed);this.syncFallbackGeometry();syncAriaControlsElements(this,this.baseEl,this.triggerControls);this.syncDescribedByElements()}syncDescribedByElements(){if(!this.triggerDescribedBy&&!this.hasSyncedDescribedByElements)return;this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,this.triggerDescribedBy)}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:true})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);if(copy)svgEl.append(copy)}}render(){const label=this.accessibleLabel||this.label||this.localize("iconButtonLabel");const content=html`${this.icon||this.src?html`<lr-icon
|
|
2
2
|
name=${this.icon||nothing}
|
|
3
3
|
library=${this.library||nothing}
|
|
4
4
|
src=${this.src||nothing}
|
|
@@ -89,6 +89,8 @@ export interface LyraLocalePickerEventMap {
|
|
|
89
89
|
* @csspart form-control-label - The `<label>` element (only rendered — and only contributes to
|
|
90
90
|
* the accessible name — once `label` is non-empty).
|
|
91
91
|
* @csspart trigger - The trigger button (positioning anchor).
|
|
92
|
+
* @csspart trigger-flag - The trigger's leading `<lr-flag>` for the current value (present only
|
|
93
|
+
* while `showFlags` is on).
|
|
92
94
|
* @csspart listbox - The options popover.
|
|
93
95
|
* @csspart option - An option row.
|
|
94
96
|
* @csspart option-flag - The row's leading `<lr-flag>` (present only while `showFlags` is on).
|
|
@@ -303,6 +305,7 @@ export declare class LyraLocalePicker extends LyraElement<LyraLocalePickerEventM
|
|
|
303
305
|
* of `effectiveLocale` -- never a committed selection, see the class doc's value/preview
|
|
304
306
|
* split. */
|
|
305
307
|
private get previewTag();
|
|
308
|
+
private entryFor;
|
|
306
309
|
private labelFor;
|
|
307
310
|
private show;
|
|
308
311
|
private hide;
|