@aceshooting/lyra-ui 9.1.0 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +246 -0
- package/README.md +7 -0
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.styles.js +2 -2
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
- package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +2 -2
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/bar-chart.class.js +1 -1
- package/dist/components/charts/chart/bubble-chart.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/line-chart.class.js +1 -1
- package/dist/components/charts/chart/pie-chart.class.js +1 -1
- package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
- package/dist/components/charts/chart/radar-chart.class.js +1 -1
- package/dist/components/charts/chart/scatter-chart.class.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
- package/dist/components/conversation/chat-message/chat-message.styles.js +6 -0
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
- package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.styles.js +9 -0
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.js +1 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +3 -1
- package/dist/components/layout/card/card.styles.js +2 -2
- package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.styles.js +29 -9
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +2 -2
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +2 -0
- package/dist/components/overlays/callout/callout.styles.js +2 -2
- package/dist/components/overlays/kbd/kbd.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/popup/popup.class.js +2 -2
- package/dist/components/overlays/spinner/spinner.styles.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +11 -0
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +7 -0
- package/dist/internal/dev-mode-attribute-warning.js +1 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-attachment-trigger.md +2 -2
- package/llms/components/lr-heatmap.md +1 -1
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/llms/shared.md +13 -0
- package/llms-full.txt +16 -3
- package/package.json +3 -3
- package/vscode-html-data.json +1 -1
- package/web-types.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{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{literalSetConverter,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_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_search,LYRA_DEFAULT_select,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,MAX_SKELETON_ROWS=20,DEFAULT_PAGE_SIZE=100,MAX_PAGE_SIZE=500,LOW_PRIORITY_MAX_INLINE_SIZE=899.98,MEDIUM_PRIORITY_MAX_INLINE_SIZE=639.98,MAX_TABLE_COLLECTION_ENTRIES=1e4,UNBOUNDED_RESIZE_ARIA_MAX=Number.MAX_SAFE_INTEGER;function frozenArray(values){const snapshot=[];try{for(const value of values)if(snapshot.push(value),snapshot.length>=MAX_TABLE_COLLECTION_ENTRIES)break}catch{}return Object.freeze(snapshot)}function keySet(values){const snapshot=new Set;try{for(const value of values){if(typeof value=="string"){if(value.trim().length===0)continue}else if(typeof value!="number")continue;if(snapshot.add(value),snapshot.size>=MAX_TABLE_COLLECTION_ENTRIES)break}}catch{}return snapshot}function readonlyKeySet(values){const snapshot=keySet(values);let facade;return facade={get size(){return snapshot.size},has:value=>snapshot.has(value),entries:()=>snapshot.entries(),keys:()=>snapshot.keys(),values:()=>snapshot.values(),[Symbol.iterator]:()=>snapshot[Symbol.iterator](),forEach(callback,thisArg){snapshot.forEach(value=>callback.call(thisArg,value,value,facade))}},Object.freeze(facade)}const UNSAFE_CSS_STRUCTURE=/[;{}]/,URL_FUNCTION=/url\s*\(/i,SAFE_STYLE_PROPERTY=/^-?[_a-zA-Z][\w-]*$|^--[a-zA-Z0-9_-]+$/,optionalBooleanConverter={fromAttribute(value){if(value!==null)return value!=="false"},toAttribute(value){return value===void 0?null:value?"":"false"}};function isDevelopmentRuntime(){const nodeEnv=globalThis.process?.env?.NODE_ENV;if(nodeEnv==="production")return!1;if(nodeEnv==="development")return!0;const viteEnv=import.meta.env;return typeof viteEnv?.DEV=="boolean"?viteEnv.DEV:viteEnv?.MODE==="development"}const TABLE_LAYOUT=literalSetConverter(["auto","fixed"],"auto"),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==="start"||sticky==="end")return sticky}function sanitizeCellStyle(cellStyle){if(cellStyle===void 0)return{};const safe={};for(const[rawProperty,rawValue]of Object.entries(cellStyle)){const property2=sanitizeCellStyleProperty(rawProperty),value=sanitizeCellStyleValue(rawValue);if(property2===void 0||value===void 0)continue;const normalizedProperty=normalizeStyleProperty(property2);(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 normalized}function normalizeStyleProperty(property2){return property2.startsWith("--")?property2:property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function sanitizeCellStyleValue(value){if(typeof value!="string")return;const normalized=value.trim();if(!(!normalized||UNSAFE_CSS_STRUCTURE.test(normalized)||URL_FUNCTION.test(normalized)))return normalized}function cssSupports(property2,value){return typeof CSS>"u"||typeof CSS.supports!="function"?!0:CSS.supports(property2,value)}function normalizedEditTrigger(editTrigger){if(editTrigger==="always"||editTrigger==="double-click")return editTrigger}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 asElement(value){return typeof value!="object"||!("nodeType"in value)||value.nodeType!==1||!("matches"in value)?null:value}function eventInteractiveTarget(event,boundary){for(const value of event.composedPath()){if(value===boundary)break;const element=asElement(value);if(element!==null&&(element.matches("[data-table-interactive]")||element.matches(INTERACTIVE_SELECTOR)&&!element.matches("[data-row-key], th[data-col-key]")))return element}return null}class LyraTable extends LyraElement{constructor(){super(...arguments),this._columns=Object.freeze([]),this._rows=Object.freeze([]),this._layout="auto",this.sortKey="",this.sortDir="asc",this.sortMode="client",this.defaultSortDir="asc",this.caption="",this.captionId=nextId("lr-table-caption"),this.selectionMode="none",this._selectedKeys=new Set,this.filterable=!1,this.filterText="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.loading=!1,this.loadingAppearance="spinner",this.skeletonRows=0,this.pageSize=DEFAULT_PAGE_SIZE,this.page=1,this.totalItems=-1,this.paginationMode="client",this._expandedKeys=new Set,this.hasMore=!1,this.emptyDescription="",this.noColumnsDescription="",this.hasHiddenPriorityColumns=!1,this.priorityColumnsToggleAvailable=!1,this.priorityColumnsVisible=!1,this.persistReady=!1,this.loadingAnnouncementsReady=!1,this.activeColKey=null,this.activeRowKey=null,this.editingCell=null,this.focusedEditorCell=null,this.editorHadFocusBeforeUpdate=!1,this.rovingFocusSnapshot=null,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,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0,header=handle.closest("th[data-col-key]"),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)},handle.toggleAttribute("data-resizing",!0),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,width=Math.min(state2.maxWidth,Math.max(state2.minWidth,state2.startWidth+delta));this.resizedColumnWidths.get(state2.key)!==width&&(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(state2.key,width),this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width})))},this.onResizeKeyDown=event=>{const handle=event.currentTarget,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0;if(!column)return;const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),currentWidth=this.currentResizeWidth(column,handle),step=event.shiftKey?50:10;let requestedWidth;event.key==="Home"?requestedWidth=minWidth:event.key==="End"&&Number.isFinite(maxWidth)?requestedWidth=maxWidth:event.key==="ArrowLeft"?requestedWidth=currentWidth+(isRtl(this)?step:-step):event.key==="ArrowRight"&&(requestedWidth=currentWidth+(isRtl(this)?-step:step)),requestedWidth!==void 0&&(event.preventDefault(),event.stopPropagation(),this.resizeColumnTo(column,requestedWidth))},this.onResizePointerEnd=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;if(state2.handle.removeAttribute("data-resizing"),event.type==="pointerup")try{state2.handle.releasePointerCapture?.(event.pointerId)}catch{}if(this.resizeState=void 0,this.detachResizePointerListeners(),event.type!=="pointerup"){const reverted2=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted2.delete(state2.key):reverted2.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted2;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth||!this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width:committedWidth}),{cancelable:!0}).defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):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(()=>{this.layoutFrame===frame&&(this.layoutFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.recomputeHiddenPriorityColumns(),this.applyStickyOffsets(),this.syncResizeHandleValues()))}),this.layoutFrame=frame},this.cachedCanonicalRowEntries=null,this.canonicalRowEntriesInputs=null,this.cachedMatchingEntries=null,this.matchingEntriesInputs=null,this.cachedSortedEntries=null,this.sortedEntriesInputs=null,this.onFilterInput=event=>{event.stopPropagation();const input=event.currentTarget;this.filterText=input.value,this.emit("lr-filter-change",Object.freeze({text:this.filterText}))},this.stopOwnedEvent=event=>{event.stopPropagation()},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.paginationMode==="client"&&(this.page=page),this.emit("lr-page-change",Object.freeze({page}))},this.onTableFocusIn=event=>{const target=event.target,cell=target?.closest?.("td[data-col-key]"),row=target?.closest?.("[data-row-key]"),columnKey=cell?.dataset.colKey,rowKey=row?.dataset.rowKey;this.focusedEditorCell=target?.getAttribute("part")==="cell-editor"&&columnKey!==void 0&&rowKey!==void 0&&normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always"?{rowKey,columnKey}:null},this.onEditorKeyDown=(event,rowKey,columnKey)=>{event.stopPropagation();const alwaysOn=normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always";event.key==="Enter"?(event.preventDefault(),this.commitEdit(event,rowKey,columnKey)):event.key==="Escape"&&!alwaysOn&&(event.preventDefault(),this.editingCell=null)},this.onTableDoubleClick=event=>{const target=event.target,table=event.currentTarget;if(eventInteractiveTarget(event,table))return;const cell=target.closest('[part="cell"][data-col-key]'),row=target.closest("[data-row-key]");cell&&row?.dataset.rowKey&&cell.dataset.colKey&&this.startEditing(row.dataset.rowKey,cell.dataset.colKey)},this.toggleColumns=()=>{this.priorityColumnsVisible=!this.priorityColumnsVisible,this.emit("lr-priority-columns-visibility-change",Object.freeze({visible:this.priorityColumnsVisible}))},this.onTableClick=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,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]");tr&&this.activateRow(tr.dataset.rowKey)},this.onTableKeyDown=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,table))return;const th=target.closest("th[data-col-key]");if(th)return this.onHeaderKeyDown(e,th);const tr=target.closest("[data-row-key]");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,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,resizeColumn:LYRA_DEFAULT_resizeColumn,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,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 columns(){return this._columns}set columns(value){const previous=this._columns,columns=[],seen=new Set;let length=0;try{if(Array.isArray(value)){const descriptor=Object.getOwnPropertyDescriptor(value,"length"),sourceLength=descriptor&&"value"in descriptor?descriptor.value:0;typeof sourceLength=="number"&&Number.isSafeInteger(sourceLength)&&sourceLength>=0&&(length=Math.min(sourceLength,MAX_TABLE_COLLECTION_ENTRIES))}}catch{length=0}for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const column=descriptor.value;try{const key=column?.key;if(typeof key!="string"||key.trim().length===0||seen.has(key))continue;seen.add(key),columns.push(column)}catch{}}this._columns=frozenArray(columns),this.requestUpdate("columns",previous)}get rows(){return this._rows}set rows(value){const previous=this._rows;this._rows=frozenArray(Array.isArray(value)?value:[]),this.requestUpdate("rows",previous)}get layout(){return this._layout}set layout(next){const normalized=TABLE_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get selectedRowKeys(){return readonlyKeySet(this._selectedKeys)}set selectedRowKeys(value){const previous=this._selectedKeys;this._selectedKeys=keySet(value??[]),this.requestUpdate("selectedRowKeys",previous)}get expandedRowKeys(){return readonlyKeySet(this._expandedKeys)}set expandedRowKeys(value){const previous=this._expandedKeys;this._expandedKeys=keySet(value??[]),this.requestUpdate("expandedRowKeys",previous)}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}parsePixelLength(value){if(!value)return;const trimmed=value.trim();if(!trimmed.endsWith("px"))return;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,hostStyle=ownerWindow?.getComputedStyle(this),themed=hostStyle?.getPropertyValue("--lr-table-resize-min-width").trim()||hostStyle?.getPropertyValue("--_lr-table-resize-min-width-default").trim()||"",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),maxWidth=this.maximumResizeWidth(column,minWidth),width=Math.min(maxWidth,Math.max(minWidth,requestedWidth)),previousWidth=this.resizedColumnWidths.get(column.key);if(previousWidth===width||(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width),!this.emit("lr-column-resize",Object.freeze({columnKey:column.key,width}),{cancelable:!0}).defaultPrevented))return;const reverted=new Map(this.resizedColumnWidths);previousWidth===void 0?reverted.delete(column.key):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),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--)(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{literalSetConverter,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_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_search,LYRA_DEFAULT_select,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,MAX_SKELETON_ROWS=20,DEFAULT_PAGE_SIZE=100,MAX_PAGE_SIZE=500,LOW_PRIORITY_MAX_INLINE_SIZE=899.98,MEDIUM_PRIORITY_MAX_INLINE_SIZE=639.98,MAX_TABLE_COLLECTION_ENTRIES=1e4,UNBOUNDED_RESIZE_ARIA_MAX=Number.MAX_SAFE_INTEGER;function frozenArray(values){const snapshot=[];try{for(const value of values)if(snapshot.push(value),snapshot.length>=MAX_TABLE_COLLECTION_ENTRIES)break}catch{}return Object.freeze(snapshot)}function keySet(values){const snapshot=new Set;try{for(const value of values){if(typeof value=="string"){if(value.trim().length===0)continue}else if(typeof value!="number")continue;if(snapshot.add(value),snapshot.size>=MAX_TABLE_COLLECTION_ENTRIES)break}}catch{}return snapshot}function readonlyKeySet(values){const snapshot=keySet(values);let facade;return facade={get size(){return snapshot.size},has:value=>snapshot.has(value),entries:()=>snapshot.entries(),keys:()=>snapshot.keys(),values:()=>snapshot.values(),[Symbol.iterator]:()=>snapshot[Symbol.iterator](),forEach(callback,thisArg){snapshot.forEach(value=>callback.call(thisArg,value,value,facade))}},Object.freeze(facade)}const UNSAFE_CSS_STRUCTURE=/[;{}]/,URL_FUNCTION=/url\s*\(/i,SAFE_STYLE_PROPERTY=/^-?[_a-zA-Z][\w-]*$|^--[a-zA-Z0-9_-]+$/,optionalBooleanConverter={fromAttribute(value){if(value!==null)return value!=="false"},toAttribute(value){return value===void 0?null:value?"":"false"}};function isDevelopmentRuntime(){const nodeEnv=globalThis.process?.env?.NODE_ENV;if(nodeEnv==="production")return!1;if(nodeEnv==="development")return!0;const viteEnv=import.meta.env;return typeof viteEnv?.DEV=="boolean"?viteEnv.DEV:viteEnv?.MODE==="development"}const TABLE_LAYOUT=literalSetConverter(["auto","fixed"],"auto"),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==="start"||sticky==="end")return sticky}function sanitizeCellStyle(cellStyle){if(cellStyle===void 0)return{};const safe={};for(const[rawProperty,rawValue]of Object.entries(cellStyle)){const property2=sanitizeCellStyleProperty(rawProperty),value=sanitizeCellStyleValue(rawValue);if(property2===void 0||value===void 0)continue;const normalizedProperty=normalizeStyleProperty(property2);(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 normalized}function normalizeStyleProperty(property2){return property2.startsWith("--")?property2:property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function sanitizeCellStyleValue(value){if(typeof value!="string")return;const normalized=value.trim();if(!(!normalized||UNSAFE_CSS_STRUCTURE.test(normalized)||URL_FUNCTION.test(normalized)))return normalized}function cssSupports(property2,value){return typeof CSS>"u"||typeof CSS.supports!="function"?!0:CSS.supports(property2,value)}function normalizedEditTrigger(editTrigger){if(editTrigger==="always"||editTrigger==="double-click")return editTrigger}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 asElement(value){return typeof value!="object"||!("nodeType"in value)||value.nodeType!==1||!("matches"in value)?null:value}function eventInteractiveTarget(event,boundary){for(const value of event.composedPath()){if(value===boundary)break;const element=asElement(value);if(element!==null&&(element.matches("[data-table-interactive]")||element.matches(INTERACTIVE_SELECTOR)&&!element.matches("[data-row-key], th[data-col-key]")))return element}return null}class LyraTable extends LyraElement{constructor(){super(...arguments),this._columns=Object.freeze([]),this._rows=Object.freeze([]),this._layout="auto",this.sortKey="",this.sortDir="asc",this.sortMode="client",this.defaultSortDir="asc",this.caption="",this.captionId=nextId("lr-table-caption"),this.selectionMode="none",this._selectedKeys=new Set,this.filterable=!1,this.filterText="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.loading=!1,this.loadingAppearance="spinner",this.skeletonRows=0,this.pageSize=DEFAULT_PAGE_SIZE,this.page=1,this.totalItems=-1,this.paginationMode="client",this._expandedKeys=new Set,this.hasMore=!1,this.emptyDescription="",this.noColumnsDescription="",this.hasHiddenPriorityColumns=!1,this.priorityColumnsToggleAvailable=!1,this.priorityColumnsVisible=!1,this.persistReady=!1,this.loadingAnnouncementsReady=!1,this.activeColKey=null,this.activeRowKey=null,this.editingCell=null,this.focusedEditorCell=null,this.editorHadFocusBeforeUpdate=!1,this.rovingFocusSnapshot=null,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,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0,header=handle.closest("th[data-col-key]"),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)},handle.toggleAttribute("data-resizing",!0),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,width=Math.min(state2.maxWidth,Math.max(state2.minWidth,state2.startWidth+delta));this.resizedColumnWidths.get(state2.key)!==width&&(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(state2.key,width),this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width})))},this.onResizeKeyDown=event=>{const handle=event.currentTarget,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0;if(!column)return;const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),currentWidth=this.currentResizeWidth(column,handle),step=event.shiftKey?50:10;let requestedWidth;event.key==="Home"?requestedWidth=minWidth:event.key==="End"&&Number.isFinite(maxWidth)?requestedWidth=maxWidth:event.key==="ArrowLeft"?requestedWidth=currentWidth+(isRtl(this)?step:-step):event.key==="ArrowRight"&&(requestedWidth=currentWidth+(isRtl(this)?-step:step)),requestedWidth!==void 0&&(event.preventDefault(),event.stopPropagation(),this.resizeColumnTo(column,requestedWidth))},this.onResizePointerEnd=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;if(state2.handle.removeAttribute("data-resizing"),event.type==="pointerup")try{state2.handle.releasePointerCapture?.(event.pointerId)}catch{}if(this.resizeState=void 0,this.detachResizePointerListeners(),event.type!=="pointerup"){const reverted2=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted2.delete(state2.key):reverted2.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted2;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth||!this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width:committedWidth}),{cancelable:!0}).defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):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(()=>{this.layoutFrame===frame&&(this.layoutFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.recomputeHiddenPriorityColumns(),this.applyStickyOffsets(),this.syncResizeHandleValues()))}),this.layoutFrame=frame},this.cachedCanonicalRowEntries=null,this.canonicalRowEntriesInputs=null,this.cachedMatchingEntries=null,this.matchingEntriesInputs=null,this.cachedSortedEntries=null,this.sortedEntriesInputs=null,this.onFilterInput=event=>{event.stopPropagation();const input=event.currentTarget;this.filterText=input.value,this.emit("lr-filter-change",Object.freeze({text:this.filterText}))},this.stopOwnedEvent=event=>{event.stopPropagation()},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.paginationMode==="client"&&(this.page=page),this.emit("lr-page-change",Object.freeze({page}))},this.onTableFocusIn=event=>{const target=event.target,cell=target?.closest?.("td[data-col-key]"),row=target?.closest?.("[data-row-key]"),columnKey=cell?.dataset.colKey,rowKey=row?.dataset.rowKey;this.focusedEditorCell=target?.getAttribute("part")==="cell-editor"&&columnKey!==void 0&&rowKey!==void 0&&normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always"?{rowKey,columnKey}:null},this.onEditorKeyDown=(event,rowKey,columnKey)=>{event.stopPropagation();const alwaysOn=normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always";event.key==="Enter"?(event.preventDefault(),this.commitEdit(event,rowKey,columnKey)):event.key==="Escape"&&!alwaysOn&&(event.preventDefault(),this.editingCell=null)},this.onTableDoubleClick=event=>{const target=event.target,table=event.currentTarget;if(eventInteractiveTarget(event,table))return;const cell=target.closest('[part="cell"][data-col-key]'),row=target.closest("[data-row-key]");cell&&row?.dataset.rowKey&&cell.dataset.colKey&&this.startEditing(row.dataset.rowKey,cell.dataset.colKey)},this.toggleColumns=()=>{this.priorityColumnsVisible=!this.priorityColumnsVisible,this.emit("lr-priority-columns-visibility-change",Object.freeze({visible:this.priorityColumnsVisible}))},this.onTableClick=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,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]");tr&&this.activateRow(tr.dataset.rowKey)},this.onTableKeyDown=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,table))return;const th=target.closest("th[data-col-key]");if(th)return this.onHeaderKeyDown(e,th);const tr=target.closest("[data-row-key]");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,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,resizeColumn:LYRA_DEFAULT_resizeColumn,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,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 columns(){return this._columns}set columns(value){const previous=this._columns,columns=[],seen=new Set;let length=0;try{if(Array.isArray(value)){const descriptor=Object.getOwnPropertyDescriptor(value,"length"),sourceLength=descriptor&&"value"in descriptor?descriptor.value:0;typeof sourceLength=="number"&&Number.isSafeInteger(sourceLength)&&sourceLength>=0&&(length=Math.min(sourceLength,MAX_TABLE_COLLECTION_ENTRIES))}}catch{length=0}for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const column=descriptor.value;try{const key=column?.key;if(typeof key!="string"||key.trim().length===0||seen.has(key))continue;seen.add(key),columns.push(column)}catch{}}this._columns=frozenArray(columns),this.requestUpdate("columns",previous)}get rows(){return this._rows}set rows(value){const previous=this._rows;this._rows=frozenArray(Array.isArray(value)?value:[]),this.requestUpdate("rows",previous)}get layout(){return this._layout}set layout(next){const normalized=TABLE_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get selectedRowKeys(){return readonlyKeySet(this._selectedKeys)}set selectedRowKeys(value){const previous=this._selectedKeys;this._selectedKeys=keySet(value??[]),this.requestUpdate("selectedRowKeys",previous)}get expandedRowKeys(){return readonlyKeySet(this._expandedKeys)}set expandedRowKeys(value){const previous=this._expandedKeys;this._expandedKeys=keySet(value??[]),this.requestUpdate("expandedRowKeys",previous)}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}parsePixelLength(value){if(!value)return;const trimmed=value.trim();if(!trimmed.endsWith("px"))return;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,hostStyle=ownerWindow?.getComputedStyle(this),themed=hostStyle?.getPropertyValue("--lr-table-resize-min-width").trim()||hostStyle?.getPropertyValue("--_lr-table-resize-min-width-default").trim()||"",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),maxWidth=this.maximumResizeWidth(column,minWidth),width=Math.min(maxWidth,Math.max(minWidth,requestedWidth)),previousWidth=this.resizedColumnWidths.get(column.key);if(previousWidth===width||(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width),!this.emit("lr-column-resize",Object.freeze({columnKey:column.key,width}),{cancelable:!0}).defaultPrevented))return;const reverted=new Map(this.resizedColumnWidths);previousWidth===void 0?reverted.delete(column.key):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),maxWidth=this.maximumResizeWidth(column,minWidth);return html`<span
|
|
2
2
|
part="resize-handle"
|
|
3
3
|
data-col-key=${column.key}
|
|
4
4
|
role="separator"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{attachInternalsSafely,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.touched=!1,this.hasInteracted=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this._warnedDuplicateValues=new Set,this.childObserverGeneration=0,this.childControllers=new Map,this.authoredChildSizes=new Map,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const detail=()=>Object.freeze({value:this.value});this.emit("input",detail()),this.emit("change",detail()),this.emit("lr-change",detail())},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label"),this.hasHintSlot=this.hasDirectSupportSlot("hint"),this.hasErrorSlot=this.hasDirectSupportSlot("error"),this.reconcileChildControllers(),this.applyPendingRestore()||this.sync(),this.propagateDisabled(),this.propagateSize()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}this._warnedDuplicateValues.has(value)||(this._warnedDuplicateValues.add(value),warnDuplicateValue(this,value))}}sync(){const next=this.readValue();this.warnOnDuplicateValues();const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}notifyCheckboxStateChange(checkbox){this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.sync()}};box.addController(controller),this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children??[]).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on",index=remaining.indexOf(value);box.checked=index>=0,index>=0&&remaining.splice(index,1)}return this.touched=!1,this.hasInteracted=!1,this.sync(),!0}connectedCallback(){super.connectedCallback(),this.addEventListener("input",this.onChildEvent),this.addEventListener("change",this.onChildEvent),this.addEventListener("lr-change",this.onChildEvent),this.onSlotChange(),this.armChildObserver(),this.hasUpdated&&this.syncRequiredDescription()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseRequiredDescription(),this.removeEventListener("input",this.onChildEvent),this.removeEventListener("change",this.onChildEvent),this.removeEventListener("lr-change",this.onChildEvent),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.touched=!0,this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription()}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup()),this.touched=!1,this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.propagateDisabled(),this.sync(),this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.touched&&!this.internals.validity.valid;return html`<fieldset
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{attachInternalsSafely,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.touched=!1,this.hasInteracted=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this._warnedDuplicateValues=new Set,this.childObserverGeneration=0,this.childControllers=new Map,this.authoredChildSizes=new Map,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const detail=()=>Object.freeze({value:this.value});this.emit("input",detail()),this.emit("change",detail()),this.emit("lr-change",detail())},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label"),this.hasHintSlot=this.hasDirectSupportSlot("hint"),this.hasErrorSlot=this.hasDirectSupportSlot("error"),this.reconcileChildControllers(),this.applyPendingRestore()||this.sync(),this.propagateDisabled(),this.propagateSize()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}this._warnedDuplicateValues.has(value)||(this._warnedDuplicateValues.add(value),warnDuplicateValue(this,value))}}sync(){const next=this.readValue();this.warnOnDuplicateValues();const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}notifyCheckboxStateChange(checkbox){this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.sync()}};box.addController(controller),this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children??[]).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on",index=remaining.indexOf(value);box.checked=index>=0,index>=0&&remaining.splice(index,1)}return this.touched=!1,this.hasInteracted=!1,this.sync(),!0}connectedCallback(){super.connectedCallback(),this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.onSlotChange(),this.armChildObserver(),this.hasUpdated&&this.syncRequiredDescription()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseRequiredDescription(),this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.touched=!0,this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription()}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup()),this.touched=!1,this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.propagateDisabled(),this.sync(),this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.touched&&!this.internals.validity.valid;return html`<fieldset
|
|
2
2
|
part="form-control"
|
|
3
3
|
?disabled=${this.effectiveDisabled}
|
|
4
4
|
aria-label=${this.accessibleLabel||nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...source.icon===void 0?{}:{icon:source.icon},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-change","input","change"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.appearance="outlined",this.placement="bottom",this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceToken=0,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._rowsByValue=new Map,this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.closeCleanupPending=!1,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.collectOptions=e=>{const slot=e.target,previous=new Set(this.options);if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.normalizeActiveIndex(),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.value=next:this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.value=next;return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()},this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.restoreFocusOnClose=!1,this.hide(),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(this.liveDisabled)return;const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValue(this._selected[this._selected.length-1]);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.target.closest("button")||(e.preventDefault(),this.renderRoot.querySelector('[part="combobox-input"]')?.focus(),this.show())},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const value=e.target.closest('[part="option"]')?.dataset.value;if(value===void 0)return;const row=this._rowsByValue.get(value);row&&this.pickRow(row)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback(),this.syncSourceErrorAnnouncementSink(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.releaseSourceErrorAnnouncementSink(),this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){this.isConnected&&this.sourceErrorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseSourceErrorAnnouncementSink(),this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release(),this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty){const old=this._selected;dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);row&&this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null).map(row=>({...row}))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.value=this.multiple?selected:selected[0]??"",this._restoredStateActive=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.transitionToken++,this.releaseSourceErrorAnnouncementSink(),this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",!1)}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){return this.source?this.asyncRows:this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}))).some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows,create=this.createRow,sourceOverflow=this.source?Math.max(0,this._sourceTotal-all.length):0;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:sourceOverflow};const originalIndex=new Map(all.map((r,i)=>[r,i])),capped=all.slice(0,this.maxRender),cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=!1;for(const v of this._selected)if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);selectedRow&&(capped.push(selectedRow),appendedOutOfCap=!0)}return appendedOutOfCap&&capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b)),create&&capped.push(create),{rows:capped,overflow:all.length-capped.length+(create?1:0)+sourceOverflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}show(){if(this.open||this.liveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.inputEl??null,modal:!1,trapFocus:!1}),this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`}))}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}updated(changed){super.updated(changed),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")&&this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){this.emit("input",{value:this.value}),this.emit("change",{value:this.value}),this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.liveDisabled||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue),this.value=inputValue,this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){if(this.liveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row)),this.value=[...set],this.query="",this.explicitInputValue=!1}else this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row),this.value=row.value,this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents()}removeValue(value){if(this.liveDisabled)return;const next=this._selected.filter(v=>v!==value);next.length!==this._selected.length&&(this.value=next,this.emitValueEvents())}clear(){if(this.liveDisabled)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.value=[]),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.loading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.normalizeActiveIndex();const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError")),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.loading=!1)})},this._sourceDelay),this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this._selected),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...source.icon===void 0?{}:{icon:source.icon},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-change","input","change"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.appearance="outlined",this.placement="bottom",this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceToken=0,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._rowsByValue=new Map,this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.closeCleanupPending=!1,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.collectOptions=e=>{const slot=e.target,previous=new Set(this.options);if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.normalizeActiveIndex(),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.value=next:this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.value=next;return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()},this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.restoreFocusOnClose=!1,this.hide(),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(this.liveDisabled)return;const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValue(this._selected[this._selected.length-1]);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.target.closest("button")||(e.preventDefault(),this.renderRoot.querySelector('[part="combobox-input"]')?.focus(),this.show())},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const value=e.target.closest('[part="option"]')?.dataset.value;if(value===void 0)return;const row=this._rowsByValue.get(value);row&&this.pickRow(row)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback(),this.syncSourceErrorAnnouncementSink(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.releaseSourceErrorAnnouncementSink(),this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){this.isConnected&&this.sourceErrorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseSourceErrorAnnouncementSink(),this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release(),this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty){const old=this._selected;dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);row&&this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null).map(row=>({...row}))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.value=this.multiple?selected:selected[0]??"",this._restoredStateActive=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.transitionToken++,this.releaseSourceErrorAnnouncementSink(),this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",!1)}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){return this.source?this.asyncRows:this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}))).some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows,create=this.createRow,sourceOverflow=this.source?Math.max(0,this._sourceTotal-all.length):0;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:sourceOverflow};const originalIndex=new Map(all.map((r,i)=>[r,i])),capped=all.slice(0,this.maxRender),cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=!1;for(const v of this._selected)if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);selectedRow&&(capped.push(selectedRow),appendedOutOfCap=!0)}return appendedOutOfCap&&capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b)),create&&capped.push(create),{rows:capped,overflow:all.length-capped.length+(create?1:0)+sourceOverflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}show(){if(this.open||this.liveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.inputEl??null,modal:!1,trapFocus:!1}),this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`}))}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}updated(changed){super.updated(changed),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")&&this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){this.emit("input",{value:this.value}),this.emit("change",{value:this.value}),this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.liveDisabled||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue),this.value=inputValue,this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){if(this.liveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row)),this.value=[...set],this.query="",this.explicitInputValue=!1}else this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row),this.value=row.value,this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents()}removeValue(value){if(this.liveDisabled)return;const next=this._selected.filter(v=>v!==value);next.length!==this._selected.length&&(this.value=next,this.emitValueEvents())}clear(){if(this.liveDisabled)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.value=[]),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.loading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.normalizeActiveIndex();const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError")),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.loading=!1)})},this._sourceDelay),this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this._selected),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
|
|
2
2
|
<div id=${labelId} part="group-label" class="group-label">${currentGroup}</div>
|
|
3
3
|
${currentGroupRows}
|
|
4
4
|
</div>`)}else out.push(...currentGroupRows);currentGroupRows=[]}};return rows.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,selected=selectedSet.has(o.value);currentGroupRows.push(html`<div
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{nextId}from"../../../internal/a11y.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_emojiPickerEmpty,LYRA_DEFAULT_emojiPickerGridLabel,LYRA_DEFAULT_emojiPickerGroupActivities,LYRA_DEFAULT_emojiPickerGroupAnimalsNature,LYRA_DEFAULT_emojiPickerGroupComponent,LYRA_DEFAULT_emojiPickerGroupFlags,LYRA_DEFAULT_emojiPickerGroupFoodDrink,LYRA_DEFAULT_emojiPickerGroupObjects,LYRA_DEFAULT_emojiPickerGroupPeopleBody,LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,LYRA_DEFAULT_emojiPickerGroupSymbols,LYRA_DEFAULT_emojiPickerGroupTravelPlaces,LYRA_DEFAULT_emojiPickerLoadError,LYRA_DEFAULT_emojiPickerSearchLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const VIRTUALIZE_AT=200,ITEM_SIZE_FALLBACK=40,GAP_FALLBACK=2,VIRTUAL_ROW_HEIGHT_FALLBACK=56,MAX_VIRTUAL_COLUMNS=20,BUILT_IN_GROUP_LABEL_KEYS={0:"emojiPickerGroupSmileysEmotion",1:"emojiPickerGroupPeopleBody",2:"emojiPickerGroupComponent",3:"emojiPickerGroupAnimalsNature",4:"emojiPickerGroupFoodDrink",5:"emojiPickerGroupTravelPlaces",6:"emojiPickerGroupActivities",7:"emojiPickerGroupObjects",8:"emojiPickerGroupSymbols",9:"emojiPickerGroupFlags"},MAX_EMOJI_GROUPS=64,MAX_EMOJIS=2e4,MAX_SHORTCODES_PER_EMOJI=64;function snapshotEmojiGroups(source,itemSnapshots){if(!Array.isArray(source))return Object.freeze([]);const groups=[];let remaining=MAX_EMOJIS;for(let groupIndex=0;groupIndex<Math.min(source.length,MAX_EMOJI_GROUPS)&&remaining>0;groupIndex+=1)try{const rawGroup=source[groupIndex];if(rawGroup===null||typeof rawGroup!="object")continue;const group=rawGroup,key=group.key,label=group.label,rawEmojis=group.emojis;if(typeof key!="string"||typeof label!="string"||!Array.isArray(rawEmojis))continue;const emojis=[],length=Math.min(rawEmojis.length,remaining);for(let itemIndex=0;itemIndex<length;itemIndex+=1)try{const rawItem=rawEmojis[itemIndex];if(rawItem===null||typeof rawItem!="object")continue;const cached=itemSnapshots.get(rawItem);if(cached){emojis.push(cached);continue}const item=rawItem,emoji=item.emoji,name=item.name,rawShortcodes=item.shortcodes;if(typeof emoji!="string"||typeof name!="string"||rawShortcodes!==void 0&&!Array.isArray(rawShortcodes))continue;const shortcodes=rawShortcodes===void 0?void 0:Object.freeze(rawShortcodes.slice(0,MAX_SHORTCODES_PER_EMOJI).filter(entry=>typeof entry=="string")),snapshot=Object.freeze({emoji,name,...shortcodes===void 0?{}:{shortcodes}});itemSnapshots.set(rawItem,snapshot),emojis.push(snapshot)}catch{}remaining-=emojis.length,groups.push(Object.freeze({key,label,emojis:Object.freeze(emojis)}))}catch{}return Object.freeze(groups)}function probePixels(probe,fallback,allowZero=!1){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);return!Number.isFinite(px)||px<0?fallback:px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments),this._groups=Object.freeze([]),this.itemSnapshots=new WeakMap,this.builtInGroups=new WeakSet,this.groupsWereSet=!1,this.peerLoadFailed=!1,this.accessibleLabel="",this.size="m",this.label="",this.hint="",this.errorText="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.labelId=nextId("emoji-picker-label"),this.hintId=nextId("emoji-picker-hint"),this.errorId=nextId("emoji-picker-error"),this.loadGroups=loadEmojiDataCached,this.queryText="",this.activeIndex=0,this.virtualScrollTop=0,this.observedGridVirtualized=!1,this.liveGeometryReady=!1,this.ownerRealmGeneration=0,this.gridId=nextId("emoji-picker-grid"),this.haystacks=new WeakMap,this.onGeometryResize=()=>{const previous=this.geometryCache;if(this.geometryCache=void 0,!previous)return;const next=this.geometry();next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight||this.requestUpdate()},this.onSearchInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.pendingGridFocus=void 0,this.queryText=event.target.value,this.activeIndex=0)},this.onSearchFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedElements({flatten:!0}).length>0},this.onNavigationKeyDown=event=>{if(this.liveDisabled)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl,forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let target;if(event.key===forwardKey)target=this.activeIndex+1;else if(event.key===backwardKey)target=this.activeIndex-1;else if(event.key==="ArrowDown")target=this.activeIndex+this.columnsPerRow();else if(event.key==="ArrowUp")target=this.activeIndex-this.columnsPerRow();else if(event.key==="Home"&&!inSearch)target=0;else if(event.key==="End"&&!inSearch)target=items.length-1;else if(event.key==="Enter"||event.key===" "&&!inSearch){event.preventDefault();const item=items[this.activeIndex];item&&this.pick(item);return}else return;event.preventDefault(),inSearch&&(this.pendingGridFocus=void 0),this.setActiveIndex(target,!inSearch)},this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button")return;const option=button,indexed=Number(option.dataset.index),index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);this.pendingGridFocus||(this.focusedGridItem=this.flatItems[index],index>=0&&index!==this.activeIndex&&this.setActiveIndex(index,!1))},this.onEmojiPointerEnter=itemIndex=>{this.pendingGridFocus=void 0,this.setActiveIndex(itemIndex,!1)},this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument)return;this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0,this.requestUpdate())}),this.virtualScrollRaf=handle,this.virtualScrollRafWindow=ownerWindow,this.virtualScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,emojiPickerEmpty:LYRA_DEFAULT_emojiPickerEmpty,emojiPickerGridLabel:LYRA_DEFAULT_emojiPickerGridLabel,emojiPickerGroupActivities:LYRA_DEFAULT_emojiPickerGroupActivities,emojiPickerGroupAnimalsNature:LYRA_DEFAULT_emojiPickerGroupAnimalsNature,emojiPickerGroupComponent:LYRA_DEFAULT_emojiPickerGroupComponent,emojiPickerGroupFlags:LYRA_DEFAULT_emojiPickerGroupFlags,emojiPickerGroupFoodDrink:LYRA_DEFAULT_emojiPickerGroupFoodDrink,emojiPickerGroupObjects:LYRA_DEFAULT_emojiPickerGroupObjects,emojiPickerGroupPeopleBody:LYRA_DEFAULT_emojiPickerGroupPeopleBody,emojiPickerGroupSmileysEmotion:LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,emojiPickerGroupSymbols:LYRA_DEFAULT_emojiPickerGroupSymbols,emojiPickerGroupTravelPlaces:LYRA_DEFAULT_emojiPickerGroupTravelPlaces,emojiPickerLoadError:LYRA_DEFAULT_emojiPickerLoadError,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups,focused=this.shadowRoot?.activeElement,focusedIndex=Number(focused?.dataset.index);this.pendingGridFocus=focused?.getAttribute("part")?.split(/\s+/).includes("emoji")&&Number.isInteger(focusedIndex)?{item:this.focusedGridItem??this.flatItems[focusedIndex],index:focusedIndex}:void 0,this.groupsWereSet=!0,this.peerLoadFailed=!1,this.builtInGroups=new WeakSet,this._groups=snapshotEmojiGroups(value,this.itemSnapshots),this.requestUpdate("groups",old)}connectedCallback(){if(super.connectedCallback(),this.hasUpdated&&this.syncGeometryProbe(),this.observeGeometryProbe(),this.syncGridObserver(),this.groupsWereSet)return;const ownerDocument=this.ownerDocument,generation=this.ownerRealmGeneration;this.loadGroups().then(loaded=>{if(!(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.groupsWereSet)){if(!loaded){this.peerLoadFailed=!0,this.announcePeerLoadFailure();return}this.groups=loaded,this.builtInGroups=new WeakSet(this._groups)}})}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.searchEl?.focus(options)}blur(){const active=deepActiveElementIn(this.shadowRoot);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.searchEl?.click()}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);return(cached===void 0||cached.locale!==locale)&&(cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)},this.haystacks.set(item,cached)),cached.value}projection(){const locale=this.effectiveLocale,query2=this.queryText.trim().toLocaleLowerCase(locale),cached=this.projectionCache;if(cached?.source===this._groups&&cached.query===query2&&cached.locale===locale)return cached;const groups=query2?this._groups.map(group=>({...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(query2))})).filter(group=>group.emojis.length>0):this._groups,next={source:this._groups,query:query2,locale,groups,items:groups.flatMap(group=>group.emojis)};return this.projectionCache=next,next}get filteredGroups(){return this.projection().groups}get flatItems(){return this.projection().items}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;return probe?(this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,!0),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)},this.geometryCache):{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized||!this.ownerDocument)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");return probe.dataset.probe=name,probe},root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item"),gap=makeProbe("gap"),row=makeProbe("row");root.append(item,gap,row),this.renderRoot.append(root),this.geometryProbe={root,item,gap,row},this.geometry(),root.remove(),this.geometryProbe=void 0}bindRenderedGeometryProbe(){const root=this.renderRoot?.querySelector('[data-probe="root"]'),item=root?.querySelector('[data-probe="item"]'),gap=root?.querySelector('[data-probe="gap"]'),row=root?.querySelector('[data-probe="row"]');if(!root||!item||!gap||!row)return;if(this.geometryProbe?.root===root){this.observeGeometryProbe();return}const prior=this.geometryCache??{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK};this.geometryProbe={root,item,gap,row},this.geometryCache=void 0;const next=this.geometry();this.liveGeometryReady=!0,this.observeGeometryProbe(),(prior.itemSize!==next.itemSize||prior.gap!==next.gap||prior.rowHeight!==next.rowHeight)&&this.ownerDocument.defaultView?.requestAnimationFrame(()=>{this.isConnected&&this.geometryProbe?.root===root&&this.requestUpdate()})}observeGeometryProbe(){const probe=this.geometryProbe,ownerDocument=this.ownerDocument;if(!probe||!this.isConnected||this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root)return;this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onGeometryResize()});this.geometryObserver=observer,this.geometryObserverDocument=ownerDocument,this.geometryObserverRoot=probe.root,observer.observe(probe.item),observer.observe(probe.gap),observer.observe(probe.row)}resetGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.geometryObserverDocument=void 0,this.geometryObserverRoot=void 0}groupLabel(group){const labelKey=this.builtInGroups.has(group)?BUILT_IN_GROUP_LABEL_KEYS[group.key]:void 0;return labelKey?this.localize(labelKey):group.label}virtualRows(){const projection=this.projection(),columns=this.columnsPerRow();if(this.rowCache?.projection===projection&&this.rowCache.columns===columns)return this.rowCache.rows;let index=0;const rows=[];for(const group of projection.groups)for(let offset=0;offset<group.emojis.length;offset+=columns)rows.push({label:offset===0?this.groupLabel(group):void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))});return this.rowCache={projection,columns,rows},rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}get selectedIndex(){return this.value?this.flatItems.findIndex(item=>item.emoji===this.value):-1}syncSelectedProjection(){const selectedIndex=this.selectedIndex;for(const button of this.optionButtons())button.setAttribute("aria-selected",Number(button.dataset.index)===selectedIndex?"true":"false")}columnsPerRow(){if(this.isVirtualized){const width=(this.liveGeometryReady?this.renderRoot?.querySelector('[part="grid"]'):void 0)?.clientWidth??0,{itemSize,gap}=this.geometry();return Math.min(MAX_VIRTUAL_COLUMNS,Math.max(1,Math.floor((Math.max(width,itemSize)+gap)/(itemSize+gap))))}const buttons=this.optionButtons();if(buttons.length===0)return 1;const firstTop=buttons[0].offsetTop;let columns=0;for(const button of buttons){if(button.offsetTop!==firstTop)break;columns+=1}return Math.max(1,columns)}setActiveIndex(next,focusTarget){const buttons=this.optionButtons();if(buttons.length===0&&!this.isVirtualized)return;this.activeIndex=Math.max(0,Math.min(next,this.flatItems.length-1)),focusTarget&&(this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex});const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex],previous=this.renderRoot.querySelector('[part="emoji"][data-active]');if(previous&&previous!==target&&(previous.tabIndex=-1,previous.removeAttribute("data-active")),target)target.tabIndex=0,target.setAttribute("data-active",""),this.searchEl?.setAttribute("aria-activedescendant",target.id),target.scrollIntoView({block:"nearest"});else if(this.isVirtualized){this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex)),grid=this.renderRoot.querySelector('[part="grid"]');rowIndex>=0&&grid&&(grid.scrollTop=rowIndex*this.geometry().rowHeight,this.virtualScrollTop=grid.scrollTop,this.requestUpdate())}focusTarget&&target&&(this.pendingGridFocus=void 0,target.focus())}pick(item){this.liveDisabled||(this.value=item.emoji,this.syncSelectedProjection(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:item.emoji}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:item.emoji}))}cancelVirtualScrollFrame(){this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow?.cancelAnimationFrame(this.virtualScrollRaf),this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0}syncGridObserver(){const grid=this.renderRoot?.querySelector('[part="grid"]'),virtualized=this.isVirtualized,ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)||(this.resetGridObserver(),!this.isConnected)||(this.observedGrid=grid??void 0,this.observedGridVirtualized=virtualized,!grid||!virtualized))return;grid.addEventListener("scroll",this.onGridScroll,{passive:!0});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.requestUpdate()});this.gridResizeObserver=observer,this.gridResizeObserverDocument=ownerDocument,observer.observe(grid)}resetGridObserver(){this.observedGrid?.removeEventListener("scroll",this.onGridScroll),this.gridResizeObserver?.disconnect(),this.gridResizeObserver=void 0,this.gridResizeObserverDocument=void 0,this.observedGrid=void 0,this.observedGridVirtualized=!1,this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed),this.isVirtualized&&this.geometryProbe&&(this.geometryCache=void 0),this.syncGeometryProbe(),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error")})}updated(changed){if(super.updated(changed),this.bindRenderedGeometryProbe(),this.syncGridObserver(),!changed.has("queryText")&&!changed.has("groups")){this.restorePendingGridFocus();return}const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant"),this.pendingGridFocus&&(this.pendingGridFocus=void 0,this.searchEl?.focus());return}if(this.pendingGridFocus){const retainedIndex=this.pendingGridFocus.item?this.flatItems.indexOf(this.pendingGridFocus.item):-1;this.activeIndex=retainedIndex>=0?retainedIndex:Math.max(0,Math.min(this.pendingGridFocus.index,this.flatItems.length-1)),this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex}}else!this.isVirtualized&&this.activeIndex>=buttons.length&&(this.activeIndex=0);this.setActiveIndex(this.activeIndex,!1),this.syncSelectedProjection(),this.restorePendingGridFocus()}restorePendingGridFocus(){if(!this.pendingGridFocus)return;const target=this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`);target&&(this.pendingGridFocus=void 0,target.focus())}disconnectedCallback(){super.disconnectedCallback(),this.releasePeerErrorAnnouncementSink(),this.resetOwnerRealmResources()}announcePeerLoadFailure(){this.isConnected&&(this.peerErrorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releasePeerErrorAnnouncementSink(),this.peerErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})),this.peerErrorAnnouncementSink?.announce(this.localize("emojiPickerLoadError")))}releasePeerErrorAnnouncementSink(){this.peerErrorAnnouncementSink?.release(),this.peerErrorAnnouncementSink=void 0}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmResources()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1,this.pendingGridFocus=void 0,this.resetGridObserver(),this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total,selectedIndex){return html`<button
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{nextId}from"../../../internal/a11y.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_emojiPickerEmpty,LYRA_DEFAULT_emojiPickerGridLabel,LYRA_DEFAULT_emojiPickerGroupActivities,LYRA_DEFAULT_emojiPickerGroupAnimalsNature,LYRA_DEFAULT_emojiPickerGroupComponent,LYRA_DEFAULT_emojiPickerGroupFlags,LYRA_DEFAULT_emojiPickerGroupFoodDrink,LYRA_DEFAULT_emojiPickerGroupObjects,LYRA_DEFAULT_emojiPickerGroupPeopleBody,LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,LYRA_DEFAULT_emojiPickerGroupSymbols,LYRA_DEFAULT_emojiPickerGroupTravelPlaces,LYRA_DEFAULT_emojiPickerLoadError,LYRA_DEFAULT_emojiPickerSearchLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const VIRTUALIZE_AT=200,ITEM_SIZE_FALLBACK=40,GAP_FALLBACK=2,VIRTUAL_ROW_HEIGHT_FALLBACK=56,MAX_VIRTUAL_COLUMNS=20,BUILT_IN_GROUP_LABEL_KEYS={0:"emojiPickerGroupSmileysEmotion",1:"emojiPickerGroupPeopleBody",2:"emojiPickerGroupComponent",3:"emojiPickerGroupAnimalsNature",4:"emojiPickerGroupFoodDrink",5:"emojiPickerGroupTravelPlaces",6:"emojiPickerGroupActivities",7:"emojiPickerGroupObjects",8:"emojiPickerGroupSymbols",9:"emojiPickerGroupFlags"},MAX_EMOJI_GROUPS=64,MAX_EMOJIS=2e4,MAX_SHORTCODES_PER_EMOJI=64;function snapshotEmojiGroups(source,itemSnapshots){if(!Array.isArray(source))return Object.freeze([]);const groups=[];let remaining=MAX_EMOJIS;for(let groupIndex=0;groupIndex<Math.min(source.length,MAX_EMOJI_GROUPS)&&remaining>0;groupIndex+=1)try{const rawGroup=source[groupIndex];if(rawGroup===null||typeof rawGroup!="object")continue;const group=rawGroup,key=group.key,label=group.label,rawEmojis=group.emojis;if(typeof key!="string"||typeof label!="string"||!Array.isArray(rawEmojis))continue;const emojis=[],length=Math.min(rawEmojis.length,remaining);for(let itemIndex=0;itemIndex<length;itemIndex+=1)try{const rawItem=rawEmojis[itemIndex];if(rawItem===null||typeof rawItem!="object")continue;const cached=itemSnapshots.get(rawItem);if(cached){emojis.push(cached);continue}const item=rawItem,emoji=item.emoji,name=item.name,rawShortcodes=item.shortcodes;if(typeof emoji!="string"||typeof name!="string"||rawShortcodes!==void 0&&!Array.isArray(rawShortcodes))continue;const shortcodes=rawShortcodes===void 0?void 0:Object.freeze(rawShortcodes.slice(0,MAX_SHORTCODES_PER_EMOJI).filter(entry=>typeof entry=="string")),snapshot=Object.freeze({emoji,name,...shortcodes===void 0?{}:{shortcodes}});itemSnapshots.set(rawItem,snapshot),emojis.push(snapshot)}catch{}remaining-=emojis.length,groups.push(Object.freeze({key,label,emojis:Object.freeze(emojis)}))}catch{}return Object.freeze(groups)}function probePixels(probe,fallback,allowZero=!1){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);return!Number.isFinite(px)||px<0?fallback:px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments),this._groups=Object.freeze([]),this.itemSnapshots=new WeakMap,this.builtInGroups=new WeakSet,this.groupsWereSet=!1,this.peerLoadFailed=!1,this.accessibleLabel="",this.size="m",this.label="",this.hint="",this.errorText="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.labelId=nextId("emoji-picker-label"),this.hintId=nextId("emoji-picker-hint"),this.errorId=nextId("emoji-picker-error"),this.loadGroups=loadEmojiDataCached,this.queryText="",this.activeIndex=0,this.virtualScrollTop=0,this.observedGridVirtualized=!1,this.liveGeometryReady=!1,this.ownerRealmGeneration=0,this.gridId=nextId("emoji-picker-grid"),this.haystacks=new WeakMap,this.onGeometryResize=()=>{const previous=this.geometryCache;if(this.geometryCache=void 0,!previous)return;const next=this.geometry();next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight||this.requestUpdate()},this.onSearchInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.pendingGridFocus=void 0,this.queryText=event.target.value,this.activeIndex=0)},this.onSearchFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedElements({flatten:!0}).length>0},this.onNavigationKeyDown=event=>{if(this.liveDisabled)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl,forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let target;if(event.key===forwardKey)target=this.activeIndex+1;else if(event.key===backwardKey)target=this.activeIndex-1;else if(event.key==="ArrowDown")target=this.activeIndex+this.columnsPerRow();else if(event.key==="ArrowUp")target=this.activeIndex-this.columnsPerRow();else if(event.key==="Home"&&!inSearch)target=0;else if(event.key==="End"&&!inSearch)target=items.length-1;else if(event.key==="Enter"||event.key===" "&&!inSearch){event.preventDefault();const item=items[this.activeIndex];item&&this.pick(item);return}else return;event.preventDefault(),inSearch&&(this.pendingGridFocus=void 0),this.setActiveIndex(target,!inSearch)},this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button")return;const option=button,indexed=Number(option.dataset.index),index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);this.pendingGridFocus||(this.focusedGridItem=this.flatItems[index],index>=0&&index!==this.activeIndex&&this.setActiveIndex(index,!1))},this.onEmojiPointerEnter=itemIndex=>{this.pendingGridFocus=void 0,this.setActiveIndex(itemIndex,!1)},this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument)return;this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0,this.requestUpdate())}),this.virtualScrollRaf=handle,this.virtualScrollRafWindow=ownerWindow,this.virtualScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,emojiPickerEmpty:LYRA_DEFAULT_emojiPickerEmpty,emojiPickerGridLabel:LYRA_DEFAULT_emojiPickerGridLabel,emojiPickerGroupActivities:LYRA_DEFAULT_emojiPickerGroupActivities,emojiPickerGroupAnimalsNature:LYRA_DEFAULT_emojiPickerGroupAnimalsNature,emojiPickerGroupComponent:LYRA_DEFAULT_emojiPickerGroupComponent,emojiPickerGroupFlags:LYRA_DEFAULT_emojiPickerGroupFlags,emojiPickerGroupFoodDrink:LYRA_DEFAULT_emojiPickerGroupFoodDrink,emojiPickerGroupObjects:LYRA_DEFAULT_emojiPickerGroupObjects,emojiPickerGroupPeopleBody:LYRA_DEFAULT_emojiPickerGroupPeopleBody,emojiPickerGroupSmileysEmotion:LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,emojiPickerGroupSymbols:LYRA_DEFAULT_emojiPickerGroupSymbols,emojiPickerGroupTravelPlaces:LYRA_DEFAULT_emojiPickerGroupTravelPlaces,emojiPickerLoadError:LYRA_DEFAULT_emojiPickerLoadError,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups,focused=this.shadowRoot?.activeElement,focusedIndex=Number(focused?.dataset.index);this.pendingGridFocus=focused?.getAttribute("part")?.split(/\s+/).includes("emoji")&&Number.isInteger(focusedIndex)?{item:this.focusedGridItem??this.flatItems[focusedIndex],index:focusedIndex}:void 0,this.groupsWereSet=!0,this.peerLoadFailed=!1,this.builtInGroups=new WeakSet,this._groups=snapshotEmojiGroups(value,this.itemSnapshots),this.requestUpdate("groups",old)}connectedCallback(){if(super.connectedCallback(),this.hasUpdated&&this.syncGeometryProbe(),this.observeGeometryProbe(),this.syncGridObserver(),this.groupsWereSet)return;const ownerDocument=this.ownerDocument,generation=this.ownerRealmGeneration;this.loadGroups().then(loaded=>{if(!(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.groupsWereSet)){if(!loaded){this.peerLoadFailed=!0,this.announcePeerLoadFailure();return}this.groups=loaded,this.builtInGroups=new WeakSet(this._groups)}})}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.searchEl?.focus(options)}blur(){const active=deepActiveElementIn(this.shadowRoot);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.searchEl?.click()}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);return(cached===void 0||cached.locale!==locale)&&(cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)},this.haystacks.set(item,cached)),cached.value}projection(){const locale=this.effectiveLocale,query2=this.queryText.trim().toLocaleLowerCase(locale),cached=this.projectionCache;if(cached?.source===this._groups&&cached.query===query2&&cached.locale===locale)return cached;const groups=query2?this._groups.map(group=>({...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(query2))})).filter(group=>group.emojis.length>0):this._groups,next={source:this._groups,query:query2,locale,groups,items:groups.flatMap(group=>group.emojis)};return this.projectionCache=next,next}get filteredGroups(){return this.projection().groups}get flatItems(){return this.projection().items}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;return probe?(this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,!0),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)},this.geometryCache):{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized||!this.ownerDocument)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");return probe.dataset.probe=name,probe},root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item"),gap=makeProbe("gap"),row=makeProbe("row");root.append(item,gap,row),this.renderRoot.append(root),this.geometryProbe={root,item,gap,row},this.geometry(),root.remove(),this.geometryProbe=void 0}bindRenderedGeometryProbe(){const root=this.renderRoot?.querySelector('[data-probe="root"]'),item=root?.querySelector('[data-probe="item"]'),gap=root?.querySelector('[data-probe="gap"]'),row=root?.querySelector('[data-probe="row"]');if(!root||!item||!gap||!row)return;if(this.geometryProbe?.root===root){this.observeGeometryProbe();return}const prior=this.geometryCache??{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK};this.geometryProbe={root,item,gap,row},this.geometryCache=void 0;const next=this.geometry();this.liveGeometryReady=!0,this.observeGeometryProbe(),(prior.itemSize!==next.itemSize||prior.gap!==next.gap||prior.rowHeight!==next.rowHeight)&&this.ownerDocument.defaultView?.requestAnimationFrame(()=>{this.isConnected&&this.geometryProbe?.root===root&&this.requestUpdate()})}observeGeometryProbe(){const probe=this.geometryProbe,ownerDocument=this.ownerDocument;if(!probe||!this.isConnected||this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root)return;this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onGeometryResize()});this.geometryObserver=observer,this.geometryObserverDocument=ownerDocument,this.geometryObserverRoot=probe.root,observer.observe(probe.item),observer.observe(probe.gap),observer.observe(probe.row)}resetGeometryObserver(){this.geometryObserver?.disconnect(),this.geometryObserver=void 0,this.geometryObserverDocument=void 0,this.geometryObserverRoot=void 0}groupLabel(group){const labelKey=this.builtInGroups.has(group)?BUILT_IN_GROUP_LABEL_KEYS[group.key]:void 0;return labelKey?this.localize(labelKey):group.label}virtualRows(){const projection=this.projection(),columns=this.columnsPerRow();if(this.rowCache?.projection===projection&&this.rowCache.columns===columns)return this.rowCache.rows;let index=0;const rows=[];for(const group of projection.groups)for(let offset=0;offset<group.emojis.length;offset+=columns)rows.push({label:offset===0?this.groupLabel(group):void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))});return this.rowCache={projection,columns,rows},rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}get selectedIndex(){return this.value?this.flatItems.findIndex(item=>item.emoji===this.value):-1}syncSelectedProjection(){const selectedIndex=this.selectedIndex;for(const button of this.optionButtons())button.setAttribute("aria-selected",Number(button.dataset.index)===selectedIndex?"true":"false")}columnsPerRow(){if(this.isVirtualized){const width=(this.liveGeometryReady?this.renderRoot?.querySelector('[part="grid"]'):void 0)?.clientWidth??0,{itemSize,gap}=this.geometry();return Math.min(MAX_VIRTUAL_COLUMNS,Math.max(1,Math.floor((Math.max(width,itemSize)+gap)/(itemSize+gap))))}const buttons=this.optionButtons();if(buttons.length===0)return 1;const firstTop=buttons[0].offsetTop;let columns=0;for(const button of buttons){if(button.offsetTop!==firstTop)break;columns+=1}return Math.max(1,columns)}setActiveIndex(next,focusTarget){const buttons=this.optionButtons();if(buttons.length===0&&!this.isVirtualized)return;this.activeIndex=Math.max(0,Math.min(next,this.flatItems.length-1)),focusTarget&&(this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex});const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex],previous=this.renderRoot.querySelector('[part="emoji"][data-active]');if(previous&&previous!==target&&(previous.tabIndex=-1,previous.removeAttribute("data-active")),target)target.tabIndex=0,target.setAttribute("data-active",""),this.searchEl?.setAttribute("aria-activedescendant",target.id),target.scrollIntoView({block:"nearest"});else if(this.isVirtualized){this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex)),grid=this.renderRoot.querySelector('[part="grid"]');rowIndex>=0&&grid&&(grid.scrollTop=rowIndex*this.geometry().rowHeight,this.virtualScrollTop=grid.scrollTop,this.requestUpdate())}focusTarget&&target&&(this.pendingGridFocus=void 0,target.focus())}pick(item){this.liveDisabled||(this.value=item.emoji,this.syncSelectedProjection(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:item.emoji}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:item.emoji}))}cancelVirtualScrollFrame(){this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow?.cancelAnimationFrame(this.virtualScrollRaf),this.virtualScrollRaf=void 0,this.virtualScrollRafWindow=void 0,this.virtualScrollRafDocument=void 0}syncGridObserver(){const grid=this.renderRoot?.querySelector('[part="grid"]'),virtualized=this.isVirtualized,ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)||(this.resetGridObserver(),!this.isConnected)||(this.observedGrid=grid??void 0,this.observedGridVirtualized=virtualized,!grid||!virtualized))return;grid.addEventListener("scroll",this.onGridScroll,{passive:!0});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration,observer=new ResizeObserverCtor(()=>{this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.requestUpdate()});this.gridResizeObserver=observer,this.gridResizeObserverDocument=ownerDocument,observer.observe(grid)}resetGridObserver(){this.observedGrid?.removeEventListener("scroll",this.onGridScroll),this.gridResizeObserver?.disconnect(),this.gridResizeObserver=void 0,this.gridResizeObserverDocument=void 0,this.observedGrid=void 0,this.observedGridVirtualized=!1,this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed),this.isVirtualized&&this.geometryProbe&&(this.geometryCache=void 0),this.syncGeometryProbe(),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error")})}updated(changed){if(super.updated(changed),this.bindRenderedGeometryProbe(),this.syncGridObserver(),!changed.has("queryText")&&!changed.has("groups")){this.restorePendingGridFocus();return}const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant"),this.pendingGridFocus&&(this.pendingGridFocus=void 0,this.searchEl?.focus());return}if(this.pendingGridFocus){const retainedIndex=this.pendingGridFocus.item?this.flatItems.indexOf(this.pendingGridFocus.item):-1;this.activeIndex=retainedIndex>=0?retainedIndex:Math.max(0,Math.min(this.pendingGridFocus.index,this.flatItems.length-1)),this.pendingGridFocus={item:this.flatItems[this.activeIndex],index:this.activeIndex}}else!this.isVirtualized&&this.activeIndex>=buttons.length&&(this.activeIndex=0);this.setActiveIndex(this.activeIndex,!1),this.syncSelectedProjection(),this.restorePendingGridFocus()}restorePendingGridFocus(){if(!this.pendingGridFocus)return;const target=this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`);target&&(this.pendingGridFocus=void 0,target.focus())}disconnectedCallback(){super.disconnectedCallback(),this.releasePeerErrorAnnouncementSink(),this.resetOwnerRealmResources()}announcePeerLoadFailure(){this.isConnected&&(this.peerErrorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releasePeerErrorAnnouncementSink(),this.peerErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})),this.peerErrorAnnouncementSink?.announce(this.localize("emojiPickerLoadError")))}releasePeerErrorAnnouncementSink(){this.peerErrorAnnouncementSink?.release(),this.peerErrorAnnouncementSink=void 0}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmResources()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1,this.pendingGridFocus=void 0,this.resetGridObserver(),this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total,selectedIndex){return html`<button
|
|
2
2
|
type="button"
|
|
3
3
|
part="emoji"
|
|
4
4
|
id=${`${this.gridId}-item-${itemIndex}`}
|