@aceshooting/lyra-ui 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +188 -17
  2. package/custom-elements.json +1 -1
  3. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  4. package/dist/components/agent-tools/terminal/terminal.class.js +2 -2
  5. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -0
  6. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  7. package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
  8. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  9. package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
  10. package/dist/components/data/query-builder/query-builder.class.js +2 -2
  11. package/dist/components/data/table/table.class.js +2 -2
  12. package/dist/components/data/table/table.styles.js +8 -3
  13. package/dist/components/data/tree/tree-item.styles.js +11 -3
  14. package/dist/components/data/tree/tree.class.d.ts +11 -0
  15. package/dist/components/data/tree/tree.class.js +1 -1
  16. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  17. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -0
  18. package/dist/components/forms/locale-picker/locale-picker.class.js +4 -3
  19. package/dist/components/forms/locale-picker/locale-picker.styles.js +4 -0
  20. package/dist/components/forms/switch/switch.styles.js +9 -0
  21. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  22. package/dist/components/media/avatar/avatar.class.js +2 -2
  23. package/dist/components/media/flag/flag.class.js +2 -2
  24. package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
  25. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  26. package/dist/components/utility/icon/icon.class.js +1 -1
  27. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  28. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  29. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +3 -2
  30. package/dist/components/viewers/page-rail/page-rail.class.js +2 -0
  31. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  32. package/dist/internal/anchor-target.js +1 -1
  33. package/dist/internal/package-metadata.d.ts +1 -1
  34. package/dist/internal/package-metadata.js +1 -1
  35. package/dist/internal/safe-svg.d.ts +13 -0
  36. package/dist/internal/safe-svg.js +1 -0
  37. package/dist/testing/happy-dom-shims.d.ts +4 -0
  38. package/dist/testing/happy-dom-shims.js +1 -1
  39. package/llms/components/lr-attachment-chip.md +18 -10
  40. package/llms/components/lr-locale-picker.md +6 -4
  41. package/llms/peers.md +3 -3
  42. package/llms-full.txt +23 -13
  43. package/package.json +8 -7
  44. package/vscode-html-data.json +7 -7
  45. 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,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)??{}:{},...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
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&&current!==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&&current.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&&current!==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&&current.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"
@@ -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);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
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;
@@ -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{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.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_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,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}}}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,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},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.locales=[];this.showFlags=true;this.label="";this.hint="";this.errorText="";this.open=false;this.size="m";this.activeIndex=-1;this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.registryTick=0;this.listId=nextId("locale-picker-list");this.controlId=nextId("locale-picker-control");this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{event.stopPropagation();this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onTriggerFocus=event=>{event.stopPropagation();this.emit("focus")};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onKeyDown=e=>{const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commit(activeRow.tag)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const tag=optionEl?.dataset["value"];if(tag===void 0)return;this.commit(tag)};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));this.internals.setFormValue("")}focus(options){this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.triggerElement?.click()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1});if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.stopRegistrySubscription?.();this.stopRegistrySubscription=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label")}}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",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._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){if(this.isBarred()){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("localePickerRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid);this.requestUpdate()}get normalizedEntries(){const raw=this.locales;if(raw&&raw.length>0){return raw.map(entry=>typeof entry==="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country})}return getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}labelFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)?.label??localeNativeName(tag)}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.cleanup?.();this.cleanup=void 0;if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.cleanup=place(anchor,listbox)}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick"));if(reposition){this.syncPopup()}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}commit(tag){const previousValue=this._value;this.value=tag;this.hide();const event=this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:true});if(!event.defaultPrevented)setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag;const currentIndex=rows.findIndex(r=>r.tag===currentTag);const n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else{this.commit(row.tag)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.tag===this._value;return html`<div
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{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.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_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,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}}}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,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},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.locales=[];this.showFlags=true;this.label="";this.hint="";this.errorText="";this.open=false;this.size="m";this.activeIndex=-1;this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.registryTick=0;this.listId=nextId("locale-picker-list");this.controlId=nextId("locale-picker-control");this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{event.stopPropagation();this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onTriggerFocus=event=>{event.stopPropagation();this.emit("focus")};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onKeyDown=e=>{const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commit(activeRow.tag)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const tag=optionEl?.dataset["value"];if(tag===void 0)return;this.commit(tag)};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));this.internals.setFormValue("")}focus(options){this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.triggerElement?.click()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1});if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.stopRegistrySubscription?.();this.stopRegistrySubscription=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label")}}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",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._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){if(this.isBarred()){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("localePickerRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid);this.requestUpdate()}get normalizedEntries(){const raw=this.locales;if(raw&&raw.length>0){return raw.map(entry=>typeof entry==="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country})}return getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.cleanup?.();this.cleanup=void 0;if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.cleanup=place(anchor,listbox)}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick"));if(reposition){this.syncPopup()}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}commit(tag){const previousValue=this._value;this.value=tag;this.hide();const event=this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:true});if(!event.defaultPrevented)setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag;const currentIndex=rows.findIndex(r=>r.tag===currentTag);const n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else{this.commit(row.tag)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.tag===this._value;return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
11
11
  <span>${entry.label}</span>
12
12
  <span part="option-tag">${entry.tag}</span>
13
13
  </span>
14
- </div>`})}render(){const rows=this.normalizedEntries;const activeId=this.activeIndex>=0&&rows[this.activeIndex]?`${this.listId}-opt-${this.activeIndex}`:"";const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"locale-picker-error":"",hasHint?"locale-picker-hint":""].filter(Boolean).join(" ");return html`
14
+ </div>`})}render(){const rows=this.normalizedEntries;const activeId=this.activeIndex>=0&&rows[this.activeIndex]?`${this.listId}-opt-${this.activeIndex}`:"";const previewTag=this.previewTag;const previewEntry=this.entryFor(previewTag);const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"locale-picker-error":"",hasHint?"locale-picker-hint":""].filter(Boolean).join(" ");return html`
15
15
  <div part="form-control">
16
16
  <label part="form-control-label" for=${this.controlId} ?hidden=${!hasLabel}>
17
17
  ${this.label}<slot name="label" @slotchange=${this.onLabelSlotChange}></slot>
@@ -35,7 +35,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
35
35
  @focus=${this.onTriggerFocus}
36
36
  @blur=${this.onTriggerBlur}
37
37
  >
38
- <span class="trigger-label">${this.labelFor(this.previewTag)}</span>
38
+ ${this.showFlags?previewEntry?.country?html`<lr-flag part="trigger-flag" country=${previewEntry.country} variant="compact" aria-hidden="true"></lr-flag>`:html`<lr-flag part="trigger-flag" language=${previewTag} variant="compact" aria-hidden="true"></lr-flag>`:""}
39
+ <span class="trigger-label">${this.labelFor(previewTag)}</span>
39
40
  <span part="expand-icon" aria-hidden="true">${chevronIcon()}</span>
40
41
  </button>
41
42
  <div
@@ -103,6 +103,10 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
103
103
  cursor: not-allowed;
104
104
  }
105
105
 
106
+ [part='trigger-flag'] {
107
+ flex: 0 0 auto;
108
+ }
109
+
106
110
  .trigger-label {
107
111
  flex: 1 1 auto;
108
112
  min-inline-size: 0;
@@ -51,6 +51,15 @@ import{css}from"lit";const styles=css`
51
51
  [part~='track'] {
52
52
  position: relative;
53
53
  flex: 0 0 auto;
54
+ /* content-box, not the library-wide border-box default: the thumb is absolutely positioned
55
+ against this element's padding box, and its own size/travel math (below) is derived from
56
+ these same declared dimensions. Under border-box, a consumer-added ::part(track) border
57
+ would eat into the padding box without the thumb shrinking to match, breaking clearance
58
+ symmetry on the far edge. content-box keeps the padding box exactly this declared size
59
+ regardless of any border width, so an added border grows the track's outer footprint
60
+ instead -- the same "sits outside, doesn't touch the fill" effect the docs already point
61
+ consumers wanting a rim toward via outline. */
62
+ box-sizing: content-box;
54
63
  inline-size: var(--width, var(--lr-switch-track-inline-size));
55
64
  block-size: var(--height, var(--lr-switch-track-block-size));
56
65
  border-radius: var(--lr-radius-pill);
@@ -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,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24";const ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
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,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24";const ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
11
11
  aria-hidden="true"
12
12
  focusable="false"
13
13
  ><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
14
- `}function statusText(status,uploadingText,uploadFailedLabel){if(status==="error")return uploadFailedLabel;if(status==="uploading")return uploadingText;return""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments);this.name="";this.bytes=0;this.mimeType="";this.thumbnailSrc="";this.previewSrc="";this.previewable=true;this.status="pending";this.progress=0;this.removable=true;this.compact=false;this.thumbnailOnly=false;this.removeLabel="Remove";this.retryLabel="Retry";this.uploadingLabel="Uploading";this.uploadFailedLabel="Upload failed";this.untitledLabel="Untitled file";this.previewOpen=false;this.fallbackId=nextId("attachment-chip");this.onRemoveClick=()=>{this.emit("lr-remove",{id:this.resolvedId})};this.onRetryClick=()=>{this.emit("lr-retry",{id:this.resolvedId})};this.onPreviewClick=()=>{if(!this.effectivePreviewSrc)return;this.previewOpen=true;this.emit("lr-preview",{id:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})};this.onViewerClose=()=>{this.previewOpen=false}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext}}static{this.styles=[LyraElement.styles,styles]}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?this.file.size:finiteRange(this.bytes,0,0)}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){if(this.id)return this.id;if(this.file)return`${this.file.name}:${this.file.size}:${this.file.lastModified}`;return this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}ensureObjectUrl(file){if(this.objectUrlFile===file&&this.objectUrl)return this.objectUrl;this.revokeObjectUrl();this.objectUrl=URL.createObjectURL(file);this.objectUrlFile=file;return this.objectUrl}revokeObjectUrl(){if(this.objectUrl)URL.revokeObjectURL(this.objectUrl);this.objectUrl=void 0;this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback();this.syncAnnouncementSink();if(this.hasUpdated)this.requestUpdate()}adoptedCallback(){this.releaseAnnouncementSink();this.syncAnnouncementSink()}syncAnnouncementSink(){if(!this.isConnected)return;if(this.sink?.element.ownerDocument===this.ownerDocument)return;this.releaseAnnouncementSink();this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseAnnouncementSink(){this.sink?.release();this.sink=void 0}willUpdate(changed){if(this.hasUpdated&&(changed.has("file")||changed.has("previewSrc")||changed.has("mimeType")||changed.has("name"))){this.previewOpen=false}if(this.hasUpdated&&changed.has("status")&&this.status==="error"){this.sink?.announce(this.localizedUploadFailedLabel)}if(this.file&&(this.file.type.startsWith("image/")||this.previewable))this.ensureObjectUrl(this.file);else if(this.objectUrlFile)this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback();this.previewOpen=false;this.revokeObjectUrl();this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.localize("attachmentUploadFailed",this.uploadFailedLabel==="Upload failed"?void 0:this.uploadFailedLabel)}renderThumbnail(){if(this.file){return this.effectiveMimeType.startsWith("image/")?html`<img src=${this.objectUrl??nothing} alt="" />`:html`${fileIcon()}`}return this.thumbnailSrc?html`<img src=${this.thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName;const untitledLabel=this.localize("attachmentUntitledFile",this.untitledLabel==="Untitled file"?void 0:this.untitledLabel);const displayName=name||untitledLabel;const sizeText=this.effectiveSize>0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"";const uploadFailedLabel=this.localizedUploadFailedLabel;const progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress));const uploadingText=this.hasNumericProgress?this.localize("attachmentUploadingProgress",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel} {percent}%`,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel}\u2026`);const uploadingWithContext=this.localize("attachmentUploadingWithContext",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel} {label}`,{label:displayName});const retryWithContext=this.localize("attachmentRetryWithContext",this.retryLabel==="Retry"?void 0:`${this.retryLabel} {label}`,{label:displayName});const removeWithContext=this.localize("removeWithContext",this.removeLabel==="Remove"?void 0:`${this.removeLabel} {label}`,{label:displayName});const text=statusText(this.status,uploadingText,uploadFailedLabel);const uploading=this.status==="uploading";return html`
14
+ `}function statusText(status,uploadingText,uploadFailedLabel){if(status==="error")return uploadFailedLabel;if(status==="uploading")return uploadingText;return""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments);this.name="";this.bytes=0;this.mimeType="";this.thumbnailSrc="";this.previewSrc="";this.previewable=true;this.status="pending";this.progress=0;this.removable=true;this.compact=false;this.thumbnailOnly=false;this.removeLabel="Remove";this.retryLabel="Retry";this.uploadingLabel="Uploading";this.uploadFailedLabel="Upload failed";this.untitledLabel="Untitled file";this.previewOpen=false;this.fallbackId=nextId("attachment-chip");this.onRemoveClick=()=>{this.emit("lr-remove",{id:this.resolvedId})};this.onRetryClick=()=>{this.emit("lr-retry",{id:this.resolvedId})};this.onPreviewClick=()=>{if(!this.effectivePreviewSrc)return;this.previewOpen=true;this.emit("lr-preview",{id:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})};this.onViewerClose=()=>{this.previewOpen=false}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext}}static{this.styles=[LyraElement.styles,styles]}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?this.file.size:finiteRange(this.bytes,0,0)}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){if(this.id)return this.id;if(this.file)return`${this.file.name}:${this.file.size}:${this.file.lastModified}`;return this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}ensureObjectUrl(file){if(this.objectUrlFile===file&&this.objectUrl)return this.objectUrl;this.revokeObjectUrl();this.objectUrl=URL.createObjectURL(file);this.objectUrlFile=file;return this.objectUrl}revokeObjectUrl(){if(this.objectUrl)URL.revokeObjectURL(this.objectUrl);this.objectUrl=void 0;this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback();this.syncAnnouncementSink();if(this.hasUpdated)this.requestUpdate()}adoptedCallback(){this.releaseAnnouncementSink();this.syncAnnouncementSink()}syncAnnouncementSink(){if(!this.isConnected)return;if(this.sink?.element.ownerDocument===this.ownerDocument)return;this.releaseAnnouncementSink();this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseAnnouncementSink(){this.sink?.release();this.sink=void 0}willUpdate(changed){if(this.hasUpdated&&(changed.has("file")||changed.has("previewSrc")||changed.has("mimeType")||changed.has("name"))){this.previewOpen=false}if(this.hasUpdated&&changed.has("status")&&this.status==="error"){this.sink?.announce(this.localizedUploadFailedLabel)}if(this.file&&(this.file.type.startsWith("image/")||this.previewable))this.ensureObjectUrl(this.file);else if(this.objectUrlFile)this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback();this.previewOpen=false;this.revokeObjectUrl();this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.localize("attachmentUploadFailed",this.uploadFailedLabel==="Upload failed"?void 0:this.uploadFailedLabel)}renderThumbnail(){if(this.file){const fileImageSrc=this.objectUrl?safeMediaSrc(this.objectUrl):null;return this.effectiveMimeType.startsWith("image/")?fileImageSrc?html`<img src=${fileImageSrc} alt="" />`:html`${fileIcon()}`:html`${fileIcon()}`}const thumbnailSrc=safeMediaSrc(this.thumbnailSrc);return thumbnailSrc?html`<img src=${thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName;const untitledLabel=this.localize("attachmentUntitledFile",this.untitledLabel==="Untitled file"?void 0:this.untitledLabel);const displayName=name||untitledLabel;const sizeText=this.effectiveSize>0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"";const uploadFailedLabel=this.localizedUploadFailedLabel;const progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress));const uploadingText=this.hasNumericProgress?this.localize("attachmentUploadingProgress",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel} {percent}%`,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel}\u2026`);const uploadingWithContext=this.localize("attachmentUploadingWithContext",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel} {label}`,{label:displayName});const retryWithContext=this.localize("attachmentRetryWithContext",this.retryLabel==="Retry"?void 0:`${this.retryLabel} {label}`,{label:displayName});const removeWithContext=this.localize("removeWithContext",this.removeLabel==="Remove"?void 0:`${this.removeLabel} {label}`,{label:displayName});const text=statusText(this.status,uploadingText,uploadFailedLabel);const uploading=this.status==="uploading";return html`
15
15
  <div part="base">
16
16
  <span part="thumbnail" aria-hidden="true">${this.renderThumbnail()}</span>
17
17
  <span
@@ -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{styles}from"./avatar.styles.js";class LyraAvatar extends LyraElement{constructor(){super(...arguments);this.initials="";this.image="";this.label="";this.alt="";this.loading="eager";this.size="medium";this.shape="circle";this.variant="neutral";this.hasIcon=false;this.hasIconSlot=false;this.onImageError=event=>{const image=event.currentTarget;const failedSrc=image?.getAttribute("src");if(failedSrc)this.failedSrc=failedSrc;this.emit("lr-error",{image:failedSrc??this.image??""})};this.onIconSlotChange=e=>{this.hasIcon=this.hasDefaultSlotContent(e.target.assignedNodes({flatten:true}))};this.onNamedIconSlotChange=e=>{this.hasIconSlot=e.target.assignedNodes({flatten:true}).length>0}}static{this.styles=[LyraElement.styles,styles]}hasDefaultSlotContent(nodes){return Array.from(nodes).some(node=>{if(node.nodeType===1)return!node.hasAttribute("slot");return node.nodeType===3&&(node.textContent?.trim().length??0)>0})}hasIconSlotContent(nodes){return Array.from(nodes).some(node=>node.nodeType===1&&node.getAttribute("slot")==="icon")}willUpdate(changed){super.willUpdate(changed);if(changed.has("image"))this.failedSrc=void 0;this.seedFirstRenderState(()=>{this.hasIcon=this.hasDefaultSlotContent(this.childNodes);this.hasIconSlot=this.hasIconSlotContent(this.childNodes)})}render(){const showImage=!this.hasIcon&&!!this.image&&this.image!==this.failedSrc;const showIconSlot=!this.hasIcon&&!showImage&&this.hasIconSlot;const showGlyph=this.hasIcon||showIconSlot;const showInitials=!showGlyph&&!showImage;const hostLabel=this.getAttribute("aria-label");const accessibleName=hostLabel===null?this.label||this.alt:hostLabel;const hasAccessibleFallback=(showGlyph||showInitials)&&accessibleName;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{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./avatar.styles.js";class LyraAvatar extends LyraElement{constructor(){super(...arguments);this.initials="";this.image="";this.label="";this.alt="";this.loading="eager";this.size="medium";this.shape="circle";this.variant="neutral";this.hasIcon=false;this.hasIconSlot=false;this.onImageError=event=>{const image=event.currentTarget;const failedSrc=image?.getAttribute("src");if(failedSrc)this.failedSrc=failedSrc;this.emit("lr-error",{image:failedSrc??this.image??""})};this.onIconSlotChange=e=>{this.hasIcon=this.hasDefaultSlotContent(e.target.assignedNodes({flatten:true}))};this.onNamedIconSlotChange=e=>{this.hasIconSlot=e.target.assignedNodes({flatten:true}).length>0}}static{this.styles=[LyraElement.styles,styles]}hasDefaultSlotContent(nodes){return Array.from(nodes).some(node=>{if(node.nodeType===1)return!node.hasAttribute("slot");return node.nodeType===3&&(node.textContent?.trim().length??0)>0})}hasIconSlotContent(nodes){return Array.from(nodes).some(node=>node.nodeType===1&&node.getAttribute("slot")==="icon")}willUpdate(changed){super.willUpdate(changed);if(changed.has("image"))this.failedSrc=void 0;this.seedFirstRenderState(()=>{this.hasIcon=this.hasDefaultSlotContent(this.childNodes);this.hasIconSlot=this.hasIconSlotContent(this.childNodes)})}render(){const safeImage=safeMediaSrc(this.image);const showImage=!this.hasIcon&&!!safeImage&&safeImage!==this.failedSrc;const showIconSlot=!this.hasIcon&&!showImage&&this.hasIconSlot;const showGlyph=this.hasIcon||showIconSlot;const showInitials=!showGlyph&&!showImage;const hostLabel=this.getAttribute("aria-label");const accessibleName=hostLabel===null?this.label||this.alt:hostLabel;const hasAccessibleFallback=(showGlyph||showInitials)&&accessibleName;return html`
2
2
  <span
3
3
  part="base"
4
4
  role=${hasAccessibleFallback?"img":nothing}
@@ -10,7 +10,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
10
10
  ></span>
11
11
  ${showImage?html`<img
12
12
  part="image"
13
- src=${this.image}
13
+ src=${safeImage}
14
14
  alt=${accessibleName}
15
15
  loading=${this.loading}
16
16
  @error=${this.onImageError}
@@ -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}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError";async function loadFlagUrl(importFlags){try{return(await importFlags()).flagUrl}catch{console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`.");return null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver;let testFlagUrlResolver;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value)}function loadFlagUrlResolver(){if(testFlagUrlResolver)return testFlagUrlResolver;if(!flagUrlResolver){flagUrlResolver=Promise.resolve(null)}return flagUrlResolver}function __setFlagUrlResolverForTesting(value){testFlagUrlResolver=value}class LyraFlag extends LyraElement{constructor(){super(...arguments);this.accessibleLabel=null;this.round=false;this.loading=true;this.loadError=false;this.resolveToken=0}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}get effectiveVariant(){return this.variant??"standard"}get code(){if(this.country){return ALPHA2_RE.test(this.country)?this.country.toLowerCase():void 0}if(this.language)return languageToCountry(this.language);return void 0}connectedCallback(){super.connectedCallback();this.syncErrorAnnouncementSink()}disconnectedCallback(){this.releaseErrorAnnouncementSink();super.disconnectedCallback()}adoptedCallback(){this.releaseErrorAnnouncementSink();this.syncErrorAnnouncementSink()}syncErrorAnnouncementSink(){if(!this.isConnected)return;if(this.errorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseErrorAnnouncementSink();this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}willUpdate(changed){super.willUpdate(changed);if(this.hasUpdated&&!changed.has("country")&&!changed.has("language")&&!changed.has("src")&&!changed.has("variant")){return}const token=++this.resolveToken;if(this.src){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}const code=this.code;if(!code){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}this.resolvedSrc=void 0;this.loadError=false;this.loading=true;const variant=this.effectiveVariant;void loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken)return;if(!resolve){this.loadError=true;this.loading=false;this.announceLoadError();return}const url=await resolve(code,variant==="standard"?void 0:{variant});if(token!==this.resolveToken)return;this.resolvedSrc=url;this.loadError=false;this.loading=false}).catch(err=>{if(token!==this.resolveToken)return;console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err);this.resolvedSrc=void 0;this.loadError=true;this.loading=false;this.announceLoadError()})}updated(changed){super.updated(changed);this.setAttribute("aria-busy",String(this.loading))}render(){if(this.loading){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}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError";async function loadFlagUrl(importFlags){try{return(await importFlags()).flagUrl}catch{console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`.");return null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver;let testFlagUrlResolver;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value)}function loadFlagUrlResolver(){if(testFlagUrlResolver)return testFlagUrlResolver;if(!flagUrlResolver){flagUrlResolver=Promise.resolve(null)}return flagUrlResolver}function __setFlagUrlResolverForTesting(value){testFlagUrlResolver=value}class LyraFlag extends LyraElement{constructor(){super(...arguments);this.accessibleLabel=null;this.round=false;this.loading=true;this.loadError=false;this.resolveToken=0}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}get effectiveVariant(){return this.variant??"standard"}get code(){if(this.country){return ALPHA2_RE.test(this.country)?this.country.toLowerCase():void 0}if(this.language)return languageToCountry(this.language);return void 0}connectedCallback(){super.connectedCallback();this.syncErrorAnnouncementSink()}disconnectedCallback(){this.releaseErrorAnnouncementSink();super.disconnectedCallback()}adoptedCallback(){this.releaseErrorAnnouncementSink();this.syncErrorAnnouncementSink()}syncErrorAnnouncementSink(){if(!this.isConnected)return;if(this.errorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseErrorAnnouncementSink();this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}willUpdate(changed){super.willUpdate(changed);if(this.hasUpdated&&!changed.has("country")&&!changed.has("language")&&!changed.has("src")&&!changed.has("variant")){return}const token=++this.resolveToken;if(this.src){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}const code=this.code;if(!code){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}this.resolvedSrc=void 0;this.loadError=false;this.loading=true;const variant=this.effectiveVariant;void loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken)return;if(!resolve){this.loadError=true;this.loading=false;this.announceLoadError();return}const url=await resolve(code,variant==="standard"?void 0:{variant});if(token!==this.resolveToken)return;this.resolvedSrc=url;this.loadError=false;this.loading=false}).catch(err=>{if(token!==this.resolveToken)return;console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err);this.resolvedSrc=void 0;this.loadError=true;this.loading=false;this.announceLoadError()})}updated(changed){super.updated(changed);this.setAttribute("aria-busy",String(this.loading))}render(){if(this.loading){return html`
2
2
  <span class="sr-only">${this.localize("loading")}</span>
3
3
  <lr-skeleton variant="rect" .announce=${false}></lr-skeleton>
4
- `}if(this.loadError){return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`}const url=this.src??this.resolvedSrc;if(!url)return html``;const code=this.code;const alt=this.accessibleLabel??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`<img part="image" src=${url} alt=${alt} loading="lazy" decoding="async" />`}}__decorate([property()],LyraFlag.prototype,"country",void 0);__decorate([property()],LyraFlag.prototype,"language",void 0);__decorate([property()],LyraFlag.prototype,"src",void 0);__decorate([property({attribute:"aria-label"})],LyraFlag.prototype,"accessibleLabel",void 0);__decorate([property()],LyraFlag.prototype,"label",void 0);__decorate([property({type:Boolean,reflect:true})],LyraFlag.prototype,"round",void 0);__decorate([property()],LyraFlag.prototype,"variant",void 0);__decorate([state()],LyraFlag.prototype,"resolvedSrc",void 0);__decorate([state()],LyraFlag.prototype,"loading",void 0);__decorate([state()],LyraFlag.prototype,"loadError",void 0);export{LyraFlag,__setFlagUrlResolverForTesting,loadFlagUrl,setFlagUrlResolver};
4
+ `}if(this.loadError){return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`}const url=safeMediaSrc(this.src??this.resolvedSrc);if(!url)return html``;const code=this.code;const alt=this.accessibleLabel??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`<img part="image" src=${url} alt=${alt} loading="lazy" decoding="async" />`}}__decorate([property()],LyraFlag.prototype,"country",void 0);__decorate([property()],LyraFlag.prototype,"language",void 0);__decorate([property()],LyraFlag.prototype,"src",void 0);__decorate([property({attribute:"aria-label"})],LyraFlag.prototype,"accessibleLabel",void 0);__decorate([property()],LyraFlag.prototype,"label",void 0);__decorate([property({type:Boolean,reflect:true})],LyraFlag.prototype,"round",void 0);__decorate([property()],LyraFlag.prototype,"variant",void 0);__decorate([state()],LyraFlag.prototype,"resolvedSrc",void 0);__decorate([state()],LyraFlag.prototype,"loading",void 0);__decorate([state()],LyraFlag.prototype,"loadError",void 0);export{LyraFlag,__setFlagUrlResolverForTesting,loadFlagUrl,setFlagUrlResolver};
@@ -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}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./entity-card.styles.js";import"../../agent-tools/result-card/result-field.class.js";import"../../overlays/badge/badge.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import"../../overlays/empty/empty.class.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_entityCommunity,LYRA_DEFAULT_entityDegree,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_focusInGraph,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_untitledEntity}from"../../../internal/default-strings.generated.js";function sanitizeTypeColor(color){return color!=null&&!/[;{}]/.test(color)?color:void 0}function typeBadgeStyle(color){const safe=sanitizeTypeColor(color);if(!safe)return{};return{"--lr-badge-color":safe,"--lr-badge-background":`color-mix(in srgb, ${safe} 8%, var(--lr-color-surface))`,"--lr-badge-border":safe}}class LyraEntityCard extends LyraElement{constructor(){super(...arguments);this.entity=null;this.types=[];this.communityLabel="";this.showFocusButton=true;this.compact=false;this.frame="card";this.onFocusClick=()=>{if(this.entity)this.emit("lr-entity-activate",{id:this.entity.id})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,entityCommunity:LYRA_DEFAULT_entityCommunity,entityDegree:LYRA_DEFAULT_entityDegree,fieldRequired:LYRA_DEFAULT_fieldRequired,focusInGraph:LYRA_DEFAULT_focusInGraph,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,untitledEntity:LYRA_DEFAULT_untitledEntity}}static{this.styles=[LyraElement.styles,styles]}resolvedType(type){return this.types.find(t=>t.id===type)}render(){if(!this.entity){return html`<div part="base"><lr-empty part="empty" heading=${this.localize("noData")}></lr-empty></div>`}const entity=this.entity;const titleText=entity.label||this.localize("untitledEntity");const resolved=entity.type?this.resolvedType(entity.type):void 0;const badgeLabel=resolved?.label??entity.type;const properties=Object.entries(entity.properties??{});const ariaLevel=this.getAttribute("aria-level")||"3";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}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./entity-card.styles.js";import"../../agent-tools/result-card/result-field.class.js";import"../../overlays/badge/badge.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import"../../overlays/empty/empty.class.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_entityCommunity,LYRA_DEFAULT_entityDegree,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_focusInGraph,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_untitledEntity}from"../../../internal/default-strings.generated.js";function typeBadgeStyle(color){const safe=color!=null?sanitizeCssColor(color):void 0;if(!safe)return{};return{"--lr-badge-color":safe,"--lr-badge-background":`color-mix(in srgb, ${safe} 8%, var(--lr-color-surface))`,"--lr-badge-border":safe}}class LyraEntityCard extends LyraElement{constructor(){super(...arguments);this.entity=null;this.types=[];this.communityLabel="";this.showFocusButton=true;this.compact=false;this.frame="card";this.onFocusClick=()=>{if(this.entity)this.emit("lr-entity-activate",{id:this.entity.id})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,entityCommunity:LYRA_DEFAULT_entityCommunity,entityDegree:LYRA_DEFAULT_entityDegree,fieldRequired:LYRA_DEFAULT_fieldRequired,focusInGraph:LYRA_DEFAULT_focusInGraph,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,untitledEntity:LYRA_DEFAULT_untitledEntity}}static{this.styles=[LyraElement.styles,styles]}resolvedType(type){return this.types.find(t=>t.id===type)}render(){if(!this.entity){return html`<div part="base"><lr-empty part="empty" heading=${this.localize("noData")}></lr-empty></div>`}const entity=this.entity;const titleText=entity.label||this.localize("untitledEntity");const resolved=entity.type?this.resolvedType(entity.type):void 0;const badgeLabel=resolved?.label??entity.type;const properties=Object.entries(entity.properties??{});const ariaLevel=this.getAttribute("aria-level")||"3";return html`
2
2
  <div part="base">
3
3
  <div part="header">
4
4
  ${badgeLabel?html`<lr-badge part="type-badge" style=${styleMap(typeBadgeStyle(resolved?.color))}
@@ -17,7 +17,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
17
17
  </div>
18
18
  ${matches?html`
19
19
  <div part="search-results" role="list" aria-label=${this.localize("graphExplorerSearchResultsLabel")}>
20
- ${matches.length===0?html`<div part="search-empty">${this.localize("viewerSearchNoMatches")}</div>`:matches.map(n=>html`
20
+ ${matches.length===0?html`<div part="search-empty" role="listitem">${this.localize("viewerSearchNoMatches")}</div>`:matches.map(n=>html`
21
21
  <div part="search-result" role="listitem">
22
22
  <button type="button" @click=${()=>void this.activateEntity(n.id)}>${n.label||n.id}</button>
23
23
  </div>