@aceshooting/lyra-ui 11.1.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (153) hide show
  1. package/CHANGELOG.md +456 -0
  2. package/README.md +19 -8
  3. package/custom-elements.json +1 -1
  4. package/dist/all.d.ts +1 -0
  5. package/dist/all.js +1 -1
  6. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  7. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  8. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  9. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  10. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  11. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  12. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  13. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  14. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  15. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  16. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  17. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +1 -0
  18. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  19. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  20. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  21. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  22. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  23. package/dist/components/charts/chart/chart.class.d.ts +13 -1
  24. package/dist/components/charts/chart/chart.class.js +1 -1
  25. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  26. package/dist/components/charts/chart/histogram.class.js +1 -1
  27. package/dist/components/charts/chart/line-chart.class.js +1 -1
  28. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  29. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  30. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  31. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  32. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  33. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  34. package/dist/components/conversation/model-select/model-select.class.d.ts +1 -0
  35. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  36. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  37. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -0
  38. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  39. package/dist/components/data/funnel/funnel.class.d.ts +92 -0
  40. package/dist/components/data/funnel/funnel.class.js +25 -0
  41. package/dist/components/data/funnel/funnel.d.ts +1 -0
  42. package/dist/components/data/funnel/funnel.js +1 -0
  43. package/dist/components/data/funnel/funnel.styles.d.ts +1 -0
  44. package/dist/components/data/funnel/funnel.styles.js +127 -0
  45. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
  46. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  47. package/dist/components/data/heatmap/heatmap.class.d.ts +222 -5
  48. package/dist/components/data/heatmap/heatmap.class.js +30 -22
  49. package/dist/components/data/heatmap/heatmap.styles.js +36 -0
  50. package/dist/components/data/index.d.ts +1 -0
  51. package/dist/components/data/index.js +1 -1
  52. package/dist/components/data/table/table.class.js +1 -1
  53. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
  54. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  55. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
  56. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  57. package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
  58. package/dist/components/forms/combobox/combobox.class.js +1 -1
  59. package/dist/components/forms/date-picker/date-input.class.d.ts +23 -0
  60. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  61. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
  62. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  63. package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
  64. package/dist/components/forms/radio/radio-group.class.js +1 -1
  65. package/dist/components/forms/radio/radio.class.d.ts +1 -0
  66. package/dist/components/forms/radio/radio.class.js +1 -1
  67. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
  68. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  69. package/dist/components/forms/select/select.class.d.ts +1 -0
  70. package/dist/components/forms/select/select.class.js +1 -1
  71. package/dist/components/forms/slider/slider.class.d.ts +1 -0
  72. package/dist/components/forms/slider/slider.class.js +1 -1
  73. package/dist/components/forms/switch/switch.class.d.ts +1 -0
  74. package/dist/components/forms/switch/switch.class.js +1 -1
  75. package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
  76. package/dist/components/forms/time-range/time-range.class.js +1 -1
  77. package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
  78. package/dist/components/forms/token-input/token-input.class.js +1 -1
  79. package/dist/components/layout/app-rail/app-rail-item.class.d.ts +16 -0
  80. package/dist/components/layout/app-rail/app-rail-item.class.js +4 -4
  81. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +32 -3
  82. package/dist/components/layout/filter-bar/filter-bar.class.js +2 -1
  83. package/dist/components/layout/widget/widget.class.d.ts +16 -0
  84. package/dist/components/layout/widget/widget.class.js +2 -2
  85. package/dist/components/lr-funnel.d.ts +1 -0
  86. package/dist/components/lr-funnel.js +1 -0
  87. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  88. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  89. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  90. package/dist/components/media/file-input/file-input.class.d.ts +1 -0
  91. package/dist/components/media/file-input/file-input.class.js +1 -1
  92. package/dist/components/media/flag/flag-peer-bulk-standard.d.ts +25 -0
  93. package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -0
  94. package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
  95. package/dist/components/media/flag/flag-peer-bulk.js +1 -0
  96. package/dist/components/media/flag/flag.class.d.ts +36 -0
  97. package/dist/components/media/flag/flag.class.js +2 -2
  98. package/dist/components/media/map/map.class.d.ts +196 -15
  99. package/dist/components/media/map/map.class.js +1 -1
  100. package/dist/components/overlays/chip/chip-group.class.d.ts +16 -0
  101. package/dist/components/overlays/chip/chip-group.class.js +10 -3
  102. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  103. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  104. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  105. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  106. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  107. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  108. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  109. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  110. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  111. package/dist/custom-elements-jsx.d.ts +12 -4
  112. package/dist/events.d.ts +7 -0
  113. package/dist/internal/autoloader-manifest.js +1 -1
  114. package/dist/internal/autoloader-tags.d.ts +1 -1
  115. package/dist/internal/autoloader-tags.js +1 -1
  116. package/dist/internal/form-associated.d.ts +1 -0
  117. package/dist/internal/form-associated.js +1 -1
  118. package/dist/internal/form-control-labels.js +1 -1
  119. package/dist/internal/lyra-element.d.ts +7 -1
  120. package/dist/internal/lyra-element.js +1 -1
  121. package/dist/internal/package-metadata.d.ts +1 -1
  122. package/dist/internal/package-metadata.js +1 -1
  123. package/dist/internal/root-registration-allowlist.d.ts +1 -1
  124. package/dist/internal/root-registration-allowlist.js +1 -1
  125. package/dist/lyra.d.ts +4 -2
  126. package/dist/lyra.js +1 -1
  127. package/dist/ssr/all.d.ts +1 -0
  128. package/dist/ssr/all.js +1 -1
  129. package/dist/ssr.d.ts +4 -4
  130. package/dist/styles/tokens-root.css +488 -0
  131. package/dist/svelte.d.ts +13 -4
  132. package/dist/vue.d.ts +12 -4
  133. package/llms/components/lr-app-rail-item.md +8 -1
  134. package/llms/components/lr-app-rail.md +6 -0
  135. package/llms/components/lr-chip-group.md +7 -0
  136. package/llms/components/lr-chip.md +7 -0
  137. package/llms/components/lr-date-input.md +19 -1
  138. package/llms/components/lr-date-picker.md +19 -1
  139. package/llms/components/lr-filter-bar.md +50 -1
  140. package/llms/components/lr-flag.md +38 -1
  141. package/llms/components/lr-funnel.md +122 -0
  142. package/llms/components/lr-heatmap.md +64 -8
  143. package/llms/components/lr-map.md +65 -8
  144. package/llms/components/lr-widget.md +7 -1
  145. package/llms/index.md +3 -2
  146. package/llms/peers.md +2 -2
  147. package/llms/shared.md +129 -1
  148. package/llms-full.txt +526 -20
  149. package/llms.txt +1 -1
  150. package/package.json +28 -9
  151. package/vscode-css-data.json +42 -0
  152. package/vscode-html-data.json +96 -17
  153. package/web-types.json +32714 -317
@@ -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{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{nextId}from"../../../internal/a11y.js";import{bindAccessibleTextObserver,composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.collapsed=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.compact=!1,this.effectiveViews=Object.freeze([]),this.activeViewId="",this.hasActionsSlot=!1,this.hasIconSlot=!1,this.hasLabelSlot=!1,this.hasSublabelSlot=!1,this.labelSlotObserverGeneration=0,this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onIconSlotChange=e=>{this.hasIconSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.onSublabelSlotChange=e=>{this.hasSublabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.setActiveView=viewId=>{viewId===this.activeViewId||this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented||(this.activeViewId=viewId,this.emit("lr-view-change",{viewId}))},this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,styles]}get views(){return this.effectiveViews}set views(value){const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.hasIconSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="icon");const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.hasLabelSlot=labelChildren.length>0,this.labelSlotText=this.readLabelSlotText(labelChildren),this.hasSublabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="sublabel");const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;views.some(view=>view.viewId===this.activeViewId)||(this.activeViewId=views[0]?.viewId??"")}}updated(changed){super.updated(changed);const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>this.overlayHandle?.focusInitial())),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){super.disconnectedCallback(),this.overlayHandle?.suspend(),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetLabelSlotObserver()}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}syncLabelSlot(assigned){if(this.hasLabelSlot=assigned.length>0,this.labelSlotText=this.readLabelSlotText(assigned),this.resetLabelSlotObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.labelSlotObserverGeneration,observer=new MutationObserverCtor(()=>{this.labelSlotObserver!==observer||this.labelSlotObserverDocument!==ownerDocument||this.labelSlotObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.labelSlotText=this.readLabelSlotText(assigned))});this.labelSlotObserver=observer,this.labelSlotObserverDocument=ownerDocument,bindAccessibleTextObserver(observer,this,["alt","aria-labelledby","slot"]);for(const element of assigned)observer.observe(element,{attributes:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","inert","style"],childList:!0,characterData:!0,subtree:!0})}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}resetLabelSlotObserver(){this.labelSlotObserverGeneration+=1,this.labelSlotObserver?.disconnect(),this.labelSlotObserver=void 0,this.labelSlotObserverDocument=void 0}requestCollapse(next){this.emit("lr-collapse-request",{collapsed:next},{cancelable:!0}).defaultPrevented||(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}))}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=this.label.length>0,hasSublabel=this.sublabel.length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{nextId}from"../../../internal/a11y.js";import{bindAccessibleTextObserver,composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.collapsed=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.compact=!1,this.effectiveViews=Object.freeze([]),this.activeViewId="",this.activeView="",this.hasActionsSlot=!1,this.hasIconSlot=!1,this.hasLabelSlot=!1,this.hasSublabelSlot=!1,this.labelSlotObserverGeneration=0,this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onIconSlotChange=e=>{this.hasIconSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.onSublabelSlotChange=e=>{this.hasSublabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.setActiveView=viewId=>{viewId===this.activeViewId||this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented||(this.activeViewId=viewId,this.emit("lr-view-change",{viewId}))},this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,styles]}get views(){return this.effectiveViews}set views(value){const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.hasIconSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="icon");const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.hasLabelSlot=labelChildren.length>0,this.labelSlotText=this.readLabelSlotText(labelChildren),this.hasSublabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="sublabel");const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("activeView")&&this.activeView!==""&&(this.activeViewId=this.activeView),changed.has("views")||changed.has("activeViewId")||changed.has("activeView")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;views.some(view=>view.viewId===this.activeViewId)||(this.activeViewId=views[0]?.viewId??"")}}updated(changed){super.updated(changed);const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>this.overlayHandle?.focusInitial())),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){super.disconnectedCallback(),this.overlayHandle?.suspend(),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetLabelSlotObserver()}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}syncLabelSlot(assigned){if(this.hasLabelSlot=assigned.length>0,this.labelSlotText=this.readLabelSlotText(assigned),this.resetLabelSlotObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.labelSlotObserverGeneration,observer=new MutationObserverCtor(()=>{this.labelSlotObserver!==observer||this.labelSlotObserverDocument!==ownerDocument||this.labelSlotObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.labelSlotText=this.readLabelSlotText(assigned))});this.labelSlotObserver=observer,this.labelSlotObserverDocument=ownerDocument,bindAccessibleTextObserver(observer,this,["alt","aria-labelledby","slot"]);for(const element of assigned)observer.observe(element,{attributes:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","inert","style"],childList:!0,characterData:!0,subtree:!0})}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}resetLabelSlotObserver(){this.labelSlotObserverGeneration+=1,this.labelSlotObserver?.disconnect(),this.labelSlotObserver=void 0,this.labelSlotObserverDocument=void 0}requestCollapse(next){this.emit("lr-collapse-request",{collapsed:next},{cancelable:!0}).defaultPrevented||(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}))}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=this.label.length>0,hasSublabel=this.sublabel.length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return html`
2
2
  ${this.fullscreen?html`<div
3
3
  part="backdrop"
4
4
  style=${backdropInset?styleMap({"--lr-widget-backdrop-inset":backdropInset}):nothing}
@@ -82,4 +82,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
82
82
  </div>`)}
83
83
  </div>
84
84
  </div>
85
- `}}__decorate([property()],LyraWidget.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraWidget.prototype,"accessibleLabel",void 0),__decorate([property()],LyraWidget.prototype,"sublabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsed",void 0),__decorate([property({attribute:"storage-key"})],LyraWidget.prototype,"storageKey",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"expandable",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"fullscreen",void 0),__decorate([property({attribute:"fullscreen-inset"})],LyraWidget.prototype,"fullscreenInset",void 0),__decorate([property({attribute:"backdrop-inset"})],LyraWidget.prototype,"backdropInset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"compact",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"views",null),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeViewId",void 0),__decorate([state()],LyraWidget.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasIconSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraWidget.prototype,"labelSlotText",void 0),__decorate([state()],LyraWidget.prototype,"hasSublabelSlot",void 0);export{LyraWidget};
85
+ `}}__decorate([property()],LyraWidget.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraWidget.prototype,"accessibleLabel",void 0),__decorate([property()],LyraWidget.prototype,"sublabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsed",void 0),__decorate([property({attribute:"storage-key"})],LyraWidget.prototype,"storageKey",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"expandable",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"fullscreen",void 0),__decorate([property({attribute:"fullscreen-inset"})],LyraWidget.prototype,"fullscreenInset",void 0),__decorate([property({attribute:"backdrop-inset"})],LyraWidget.prototype,"backdropInset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"compact",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"views",null),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeViewId",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeView",void 0),__decorate([state()],LyraWidget.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasIconSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraWidget.prototype,"labelSlotText",void 0),__decorate([state()],LyraWidget.prototype,"hasSublabelSlot",void 0);export{LyraWidget};
@@ -0,0 +1 @@
1
+ export * from './data/funnel/funnel.js';
@@ -0,0 +1 @@
1
+ export*from"./data/funnel/funnel.js";
@@ -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,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
11
11
  aria-hidden="true"
12
12
  focusable="false"
13
13
  ><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
14
- `}function statusText(status,uploadingText,uploadFailedLabel){return status==="error"?uploadFailedLabel:status==="uploading"?uploadingText:""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments),this.name="",this.attachmentId="",this.mimeType="",this.thumbnailSrc="",this.previewSrc="",this.previewable=!0,this.status="pending",this.progress=0,this.removable=!0,this.compact=!1,this.thumbnailOnly=!1,this.fallbackId=nextId("attachment-chip"),this.onRemoveClick=()=>{this.emit("lr-remove",{attachmentId:this.resolvedId})},this.onRetryClick=()=>{this.emit("lr-retry",{attachmentId:this.resolvedId})},this.onPreviewClick=()=>{this.effectivePreviewSrc&&this.emit("lr-preview-request",{attachmentId:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get bytes(){return this._bytes}set bytes(value){const old=this._bytes;this._bytes=typeof value=="number"&&Number.isFinite(value)&&value>=0?finiteRange(value,0,0):void 0,this.requestUpdate("bytes",old)}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?Number.isFinite(this.file.size)&&this.file.size>=0?finiteRange(this.file.size,0,0):void 0:this.bytes}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){return this.attachmentId.trim().length>0?this.attachmentId:this.file?`${this.file.name}:${this.file.size}:${this.file.lastModified}`:this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}get effectiveStatus(){return this.status==="uploading"||this.status==="error"||this.status==="success"?this.status:"pending"}ensureObjectUrl(file){return this.objectUrlFile===file&&this.objectUrl?this.objectUrl:(this.revokeObjectUrl(),this.objectUrl=URL.createObjectURL(file),this.objectUrlFile=file,this.objectUrl)}revokeObjectUrl(){this.objectUrl&&URL.revokeObjectURL(this.objectUrl),this.objectUrl=void 0,this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.requestUpdate()}adoptedCallback(){super.adoptedCallback(),this.releaseAnnouncementSink(),this.syncAnnouncementSink()}syncAnnouncementSink(){this.isConnected&&this.sink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.sink?.release(),this.sink=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("status")&&this.status!==this.effectiveStatus&&(this.status=this.effectiveStatus),this.hasUpdated&&changed.has("status")&&this.status==="error"&&this.sink?.announce(this.localizedUploadFailedLabel),this.isConnected&&this.file&&(this.file.type.startsWith("image/")||this.previewable)?this.ensureObjectUrl(this.file):this.objectUrlFile&&this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback(),this.revokeObjectUrl(),this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.uploadFailedLabel??this.localize("attachmentUploadFailed")}renderThumbnail(){if(this.file){const fileImageSrc=this.objectUrl?safeMediaSrc(this.objectUrl):null;return this.effectiveMimeType.startsWith("image/")?fileImageSrc?html`<img src=${fileImageSrc} alt="" />`:html`${fileIcon()}`:html`${fileIcon()}`}const thumbnailSrc=safeMediaSrc(this.thumbnailSrc);return thumbnailSrc?html`<img src=${thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName,untitledLabel=this.untitledLabel??this.localize("attachmentUntitledFile"),displayName=name||untitledLabel,sizeText=this.effectiveSize!==void 0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"",uploadFailedLabel=this.localizedUploadFailedLabel,progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress)),uploadingText=this.uploadingLabel!==void 0?this.uploadingLabel:this.hasNumericProgress?this.localize("attachmentUploadingProgress",void 0,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate"),uploadingWithContext=this.uploadingLabel??this.localize("attachmentUploadingWithContext",void 0,{label:displayName}),retryWithContext=this.retryLabel??this.localize("attachmentRetryWithContext",void 0,{label:displayName}),removeWithContext=this.removeLabel??this.localize("removeWithContext",void 0,{label:displayName}),status=this.effectiveStatus,text=statusText(status,uploadingText,uploadFailedLabel),uploading=status==="uploading";return html`
14
+ `}function statusText(status,uploadingText,uploadFailedLabel){return status==="error"?uploadFailedLabel:status==="uploading"?uploadingText:""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments),this.name="",this.attachmentId="",this.mimeType="",this.thumbnailSrc="",this.previewSrc="",this.previewable=!0,this.status="pending",this.progress=0,this.removable=!0,this.compact=!1,this.thumbnailOnly=!1,this.fallbackId=nextId("attachment-chip"),this.onRemoveClick=()=>{this.emit("lr-remove",{attachmentId:this.resolvedId})},this.onRetryClick=()=>{this.emit("lr-retry",{attachmentId:this.resolvedId})},this.onPreviewClick=()=>{this.effectivePreviewSrc&&this.emit("lr-preview-request",{attachmentId:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,removeWithContext:LYRA_DEFAULT_removeWithContext,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get bytes(){return this._bytes}set bytes(value){const old=this._bytes;this._bytes=typeof value=="number"&&Number.isFinite(value)&&value>=0?finiteRange(value,0,0):void 0,this.requestUpdate("bytes",old)}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?Number.isFinite(this.file.size)&&this.file.size>=0?finiteRange(this.file.size,0,0):void 0:this.bytes}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){return this.attachmentId.trim().length>0?this.attachmentId:this.file?`${this.file.name}:${this.file.size}:${this.file.lastModified}`:this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}get effectiveStatus(){return this.status==="uploading"||this.status==="error"||this.status==="success"?this.status:"pending"}ensureObjectUrl(file){return this.objectUrlFile===file&&this.objectUrl?this.objectUrl:(this.revokeObjectUrl(),this.objectUrl=URL.createObjectURL(file),this.objectUrlFile=file,this.objectUrl)}revokeObjectUrl(){this.objectUrl&&URL.revokeObjectURL(this.objectUrl),this.objectUrl=void 0,this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.requestUpdate()}adoptedCallback(){super.adoptedCallback(),this.releaseAnnouncementSink(),this.syncAnnouncementSink()}syncAnnouncementSink(){this.isConnected&&this.sink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.sink?.release(),this.sink=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("status")&&this.status!==this.effectiveStatus&&(this.status=this.effectiveStatus),this.hasUpdated&&changed.has("status")&&this.status==="error"&&this.sink?.announce(this.localizedUploadFailedLabel),this.isConnected&&this.file&&(this.file.type.startsWith("image/")||this.previewable)?this.ensureObjectUrl(this.file):this.objectUrlFile&&this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback(),this.revokeObjectUrl(),this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.uploadFailedLabel??this.localize("attachmentUploadFailed")}renderThumbnail(){if(this.file){const fileImageSrc=this.objectUrl?safeMediaSrc(this.objectUrl):null;return this.effectiveMimeType.startsWith("image/")?fileImageSrc?html`<img src=${fileImageSrc} alt="" />`:html`${fileIcon()}`:html`${fileIcon()}`}const thumbnailSrc=safeMediaSrc(this.thumbnailSrc);return thumbnailSrc?html`<img src=${thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName,untitledLabel=this.untitledLabel??this.localize("attachmentUntitledFile"),displayName=name||untitledLabel,sizeText=this.effectiveSize!==void 0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"",uploadFailedLabel=this.localizedUploadFailedLabel,progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress)),uploadingText=this.uploadingLabel!==void 0?this.uploadingLabel:this.hasNumericProgress?this.localize("attachmentUploadingProgress",void 0,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate"),uploadingWithContext=this.uploadingLabel??this.localize("attachmentUploadingWithContext",void 0,{label:displayName}),retryWithContext=this.retryLabel??this.localize("attachmentRetryWithContext",void 0,{label:displayName}),removeWithContext=this.removeLabel??this.localize("removeWithContext",void 0,{label:displayName}),status=this.effectiveStatus,text=statusText(status,uploadingText,uploadFailedLabel),uploading=status==="uploading";return html`
15
15
  <div part="base">
16
16
  <span part="thumbnail" aria-hidden="true"
17
17
  >${this.renderThumbnail()}</span
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -25,7 +25,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
25
25
  <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
26
26
  <line x1="12" y1="19" x2="12" y2="23"></line>
27
27
  <line x1="8" y1="23" x2="16" y2="23"></line>
28
- `)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]);function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,4);for(let index=0;index<length;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
28
+ `)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]);function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,4);for(let index=0;index<length;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
29
29
  <input
30
30
  part="hidden-input"
31
31
  type="file"
@@ -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}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:renderedLabel,size:sizeText}):renderedLabel,accessibleLabel=hostAriaLabel(this)??fallbackLabel,descriptionId=metadata.provenance==="consumer"&&metadata.description?"metadata-description":void 0;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:renderedLabel,size:sizeText}):renderedLabel,accessibleLabel=hostAriaLabel(this)??fallbackLabel,descriptionId=metadata.provenance==="consumer"&&metadata.description?"metadata-description":void 0;return html`
2
2
  <span
3
3
  part="base"
4
4
  role=${this.decorative?"presentation":"img"}
@@ -1,5 +1,6 @@
1
1
  import { type PropertyValues, type TemplateResult } from 'lit';
2
2
  import { LyraElement } from '../../../internal/lyra-element.js';
3
+ import '../../../internal/form-control-labels.js';
3
4
  import { type FormOwnerValue } from '../../../internal/form-associated.js';
4
5
  import type { LyraSize } from '../../../internal/variants.js';
5
6
  export type LyraFileInputCapture = '' | 'user' | 'environment';
@@ -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{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,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";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,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-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},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)),this.internals.setFormValue(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}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of 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")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;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"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},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;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}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.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
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{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,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";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,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-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},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)),this.internals.setFormValue(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}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of 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")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;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"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},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;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}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.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
2
2
  <span part="file-thumbnail" aria-hidden="true">
3
3
  ${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
4
4
  </span>
@@ -0,0 +1,25 @@
1
+ import { type LyraFlagUrlResolver } from './flag.js';
2
+ /**
3
+ * Register the bulk-resolution `@aceshooting/lyra-flags` resolver through that package's
4
+ * tier-committed `./standard` entry — the pairing of `flag-peer-bulk.js`'s one-shared-fetch
5
+ * batching with `./standard`'s one-tier module graph. Import this entry **instead of**
6
+ * `flag-peer.js` or `flag-peer-bulk.js`, never alongside either: each `setFlagUrlResolver()` call
7
+ * simply replaces the previous resolver, so importing two entries just makes whichever loaded last
8
+ * win.
9
+ *
10
+ * Use it when both conditions hold: the page renders most or all flags at once (a country table, a
11
+ * full locale picker), *and* every `<lr-flag>` stays on the default `fidelity="standard"`.
12
+ * `flag-peer-bulk.js` reaches the same batching through the peer package's root entry, which
13
+ * statically imports all three fidelity tiers' generated loader maps so its `flagUrl()` can honour
14
+ * a per-call variant — so a bundler emits the detailed and compact tiers' whole lazy-chunk graph
15
+ * even though bulk resolution only ever reads the standard-tier eager map. On a real production
16
+ * build with a 156-country flag column, that difference was +15.8MB of emitted assets (+65 detailed
17
+ * SVGs, +31 compact WebPs) that no route rendered.
18
+ *
19
+ * The tradeoff this entry makes in exchange: it is committed to one tier, so `fidelity="compact"`
20
+ * or `fidelity="detailed"` on an individual element resolves to that code's *standard* asset
21
+ * rather than reaching for a tier the registered resolver deliberately does not ship. That is a
22
+ * silent visual no-op, not an error — for per-instance fidelity, import `flag-peer-bulk.js` (bulk,
23
+ * all three tiers) or `flag-peer.js` (per-code lazy, all three tiers) instead.
24
+ */
25
+ export declare function registerLyraFlagStandardBulkPeer(): Promise<LyraFlagUrlResolver | null>;
@@ -0,0 +1 @@
1
+ import{loadBulkFlagUrl,setFlagUrlResolver}from"./flag.js";const peerResolver=loadBulkFlagUrl(()=>import("@aceshooting/lyra-flags/standard"));setFlagUrlResolver(peerResolver);async function registerLyraFlagStandardBulkPeer(){return peerResolver}registerLyraFlagStandardBulkPeer();export{registerLyraFlagStandardBulkPeer};
@@ -0,0 +1,12 @@
1
+ import { type LyraFlagUrlResolver } from './flag.js';
2
+ /**
3
+ * Register a bulk-resolution `@aceshooting/lyra-flags` resolver, backed by one shared
4
+ * `flagUrls()` fetch instead of `flag-peer.js`'s per-code lazy resolution. Import this **instead
5
+ * of** `flag-peer.js` — never both; the second `setFlagUrlResolver()` call simply replaces the
6
+ * first — and only when the page renders most or all flags at once (a country table, a full
7
+ * locale picker). A page rendering only a few flags pays an unneeded 249-entry fetch for no
8
+ * benefit; use `flag-peer.js` there instead. `fidelity="compact"/"detailed"` on individual
9
+ * `<lr-flag>` elements still resolves correctly (see `createFlagUrlResolver()`'s own doc in
10
+ * `@aceshooting/lyra-flags`) — only the default (`"standard"`) tier is bulk-fetched.
11
+ */
12
+ export declare function registerLyraFlagBulkPeer(): Promise<LyraFlagUrlResolver | null>;
@@ -0,0 +1 @@
1
+ import{loadBulkFlagUrl,setFlagUrlResolver}from"./flag.js";const peerResolver=loadBulkFlagUrl(()=>import("@aceshooting/lyra-flags"));setFlagUrlResolver(peerResolver);async function registerLyraFlagBulkPeer(){return peerResolver}registerLyraFlagBulkPeer();export{registerLyraFlagBulkPeer};
@@ -14,6 +14,14 @@ export type LyraFlagUrlResolver = (code: string, options?: {
14
14
  * actually uninstall the package.
15
15
  */
16
16
  export declare function loadFlagUrl(importFlags: () => Promise<unknown>): Promise<LyraFlagUrlResolver | null>;
17
+ /**
18
+ * Resolves `@aceshooting/lyra-flags`'s `createFlagUrlResolver` via the given importer and calls
19
+ * it once, the bulk-resolution twin of `loadFlagUrl()` above. Backs `flag-peer-bulk.js` — the
20
+ * opt-in alternative to `flag-peer.js` for a page that renders most/all flags at once, where one
21
+ * shared `flagUrls()` fetch beats resolving every `<lr-flag>` instance independently. Same
22
+ * dependency-injectable, uncached shape as `loadFlagUrl()`, for the same testability reason.
23
+ */
24
+ export declare function loadBulkFlagUrl(importFlags: () => Promise<unknown>): Promise<LyraFlagUrlResolver | null>;
17
25
  /** Install an optional flag resolver supplied by a peer-registration entry. */
18
26
  export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<LyraFlagUrlResolver | null> | null): void;
19
27
  /**
@@ -35,12 +43,40 @@ export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<
35
43
  * `flagUrl(code)`, which lazily fetches one requested flag at runtime. A
36
44
  * bundler may still emit the complete reachable lazy-chunk graph; use a
37
45
  * literal asset subpath import when the deployment artifact must be pruned.
46
+ * If every `<lr-flag>` in your app is pinned to the same `fidelity` (no
47
+ * per-instance switching), register `@aceshooting/lyra-flags/standard`/`/compact`/`/detailed` with
48
+ * `setFlagUrlResolver()` instead of importing `flag-peer.js` (which always registers the full
49
+ * three-tier resolver) — the tier-specific entry excludes the other two tiers' generated loader
50
+ * maps from the reachable graph; see that package's README for the exact shape.
38
51
  * If you already
39
52
  * have a flag's URL at build time (e.g. from your own literal
40
53
  * `import frUrl from '@aceshooting/lyra-flags/flags/fr.svg?url'`), pass it as
41
54
  * `src` instead to skip the peer-package round trip (and its loading-skeleton
42
55
  * flash) entirely.
43
56
  *
57
+ * **Rendering many flags at once** (a country table, a picker listing every locale): resolve every
58
+ * code up front with `@aceshooting/lyra-flags`'s `flagUrls()` (one call, returns `{code: url}` for
59
+ * all 249 flags) and pass results through `src`, instead of letting each `<lr-flag>` instance
60
+ * independently call `flagUrl()` — this skips one peer-resolution round trip per instance. Image
61
+ * fetches themselves are unaffected either way (each flag is a distinct asset; there is no sprite).
62
+ * Or import `flag-peer-bulk.js` instead of `flag-peer.js` (never both) to get this automatically,
63
+ * registering a resolver backed by one shared `flagUrls()` call — worthwhile only when the page
64
+ * renders most/all flags; a page with a handful pays an unneeded 249-entry fetch.
65
+ * When that page ALSO leaves every `<lr-flag>` on the default `fidelity="standard"`, import
66
+ * `flag-peer-bulk-standard.js` instead: it registers the same bulk resolver through the peer
67
+ * package's tier-committed `@aceshooting/lyra-flags/standard` entry, so the detailed and compact
68
+ * tiers' lazy-chunk graphs never become reachable (measured at +15.8MB of emitted assets on a real
69
+ * production build with a 156-country flag column). It is committed to one tier, so
70
+ * `fidelity="compact"/"detailed"` on an individual element resolves to that code's standard asset
71
+ * — a silent no-op, not an error; use `flag-peer-bulk.js` when per-instance fidelity must be
72
+ * honoured.
73
+ *
74
+ * **Sizing:** the host has no intrinsic `width` — it sizes from `font-size` (`block-size: 1em`,
75
+ * `inline-size` derived from `--lr-flag-aspect-ratio` via CSS `aspect-ratio`), so `<lr-flag>` scales
76
+ * naturally with surrounding text (e.g. `style="font-size: 2rem"`). Do not set `width`/`inline-size`
77
+ * directly: making both axes definite defeats `aspect-ratio` (which only participates when at most
78
+ * one axis is definite per the CSS sizing spec), squashing the image instead of scaling it.
79
+ *
44
80
  * The ~65 flags whose design includes a detailed coat of arms/seal/emblem (e.g. `es`, `pt`) ship
45
81
  * three fidelity tiers; choose one with `fidelity`: `"compact"` (a tiny WebP raster for icon-scale
46
82
  * use — menu items, language selectors, dense lists), the default `"standard"` (icon-optimized
@@ -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{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
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{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}function warnFlagPeerMissing(){console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`.")}function warnFlagPeerIncapable(capability){console.warn(`<lr-flag> loaded '@aceshooting/lyra-flags' but it does not expose \`${capability}\`. The package is installed, so this is a version mismatch rather than a missing dependency: upgrade it to a release that provides that capability, and check the peer range in <lr-flag>'s own package metadata for the floor it expects.`)}async function loadFlagUrl(importFlags){let peerModule;try{peerModule=await importFlags()}catch{return warnFlagPeerMissing(),null}try{const resolver=resolverFromModule(peerModule);if(resolver)return resolver}catch{}return warnFlagPeerIncapable("flagUrl"),null}function resolverFactoryFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.createFlagUrlResolver;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.createFlagUrlResolver;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadBulkFlagUrl(importFlags){let peerModule;try{peerModule=await importFlags()}catch{return warnFlagPeerMissing(),null}const factory=resolverFactoryFromModule(peerModule);if(!factory)return warnFlagPeerIncapable("createFlagUrlResolver"),null;try{return factory()}catch{return warnFlagPeerIncapable("createFlagUrlResolver"),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
2
2
  >${this.fallback?html`<img part="fallback-image" src=${this.fallback} alt=${this.label??""} />`:nothing}</slot
3
3
  >`;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
4
4
  ${state2.status==="loading"?html`
@@ -15,4 +15,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
15
15
  @load=${event=>this.onImageLoad(event,state2.identity,url,request)}
16
16
  @error=${event=>this.onImageError(event,state2.identity,request)}
17
17
  />`):null}
18
- `}}__decorate([property()],LyraFlag.prototype,"country",void 0),__decorate([property()],LyraFlag.prototype,"fallback",void 0),__decorate([property()],LyraFlag.prototype,"language",void 0),__decorate([property()],LyraFlag.prototype,"src",void 0),__decorate([property()],LyraFlag.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraFlag.prototype,"shape",null),__decorate([property({reflect:!0})],LyraFlag.prototype,"fidelity",null),__decorate([state()],LyraFlag.prototype,"sourceState",void 0),__decorate([state()],LyraFlag.prototype,"resolverGeneration",void 0);export{LyraFlag,loadFlagUrl,setFlagUrlResolver};
18
+ `}}__decorate([property()],LyraFlag.prototype,"country",void 0),__decorate([property()],LyraFlag.prototype,"fallback",void 0),__decorate([property()],LyraFlag.prototype,"language",void 0),__decorate([property()],LyraFlag.prototype,"src",void 0),__decorate([property()],LyraFlag.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraFlag.prototype,"shape",null),__decorate([property({reflect:!0})],LyraFlag.prototype,"fidelity",null),__decorate([state()],LyraFlag.prototype,"sourceState",void 0),__decorate([state()],LyraFlag.prototype,"resolverGeneration",void 0);export{LyraFlag,loadBulkFlagUrl,loadFlagUrl,setFlagUrlResolver};