@aceshooting/lyra-ui 18.3.0 → 19.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 (51) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/cli/migration-contract.json +1 -1
  4. package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +6 -2
  5. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  6. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
  7. package/dist/components/charts/chart/chart.class.d.ts +11 -2
  8. package/dist/components/charts/chart/chart.class.js +1 -1
  9. package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +2 -2
  10. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +3 -3
  11. package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
  12. package/dist/components/forms/date-picker/calendar-core.js +1 -1
  13. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  14. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  15. package/dist/components/media/file-input/file-input.class.d.ts +6 -5
  16. package/dist/components/media/file-input/file-input.class.js +1 -1
  17. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  18. package/dist/components/media/lightbox/lightbox.class.d.ts +1 -1
  19. package/dist/components/media/pan-zoom/pan-zoom.class.d.ts +1 -1
  20. package/dist/components/media/pan-zoom/pan-zoom.d.ts +1 -1
  21. package/dist/components/overlays/dialog/dialog.class.d.ts +12 -6
  22. package/dist/components/overlays/dialog/dialog.class.js +3 -6
  23. package/dist/components/retrieval/retrieval-search/retrieval-search.class.d.ts +3 -4
  24. package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +2 -2
  25. package/dist/components/utility/copy-button/copy-button.class.d.ts +9 -6
  26. package/dist/components/utility/copy-button/copy-button.class.js +1 -1
  27. package/dist/components/utility/export-button/export-button.class.d.ts +12 -0
  28. package/dist/components/utility/export-button/export-button.styles.js +1 -1
  29. package/dist/components/utility/icon/icon.class.d.ts +3 -2
  30. package/dist/components/utility/icon/icon.class.js +1 -1
  31. package/dist/custom-elements-jsx.d.ts +1 -1
  32. package/dist/internal/overlay-stack.js +1 -1
  33. package/dist/internal/package-metadata.d.ts +1 -1
  34. package/dist/internal/package-metadata.js +1 -1
  35. package/dist/internal/safe-svg.d.ts +15 -11
  36. package/dist/internal/safe-svg.js +1 -1
  37. package/dist/svelte.d.ts +1 -1
  38. package/dist/vue.d.ts +1 -1
  39. package/llms/components/lr-agent-workspace.md +2 -2
  40. package/llms/components/lr-chart.md +13 -6
  41. package/llms/components/lr-copy-button.md +6 -6
  42. package/llms/components/lr-dialog.md +5 -3
  43. package/llms/components/lr-export-button.md +11 -3
  44. package/llms/components/lr-file-input.md +3 -2
  45. package/llms/components/lr-mcp-app.md +5 -0
  46. package/llms/components/lr-retrieval-search.md +2 -2
  47. package/llms-full.txt +47 -23
  48. package/package.json +2 -2
  49. package/vscode-css-data.json +1 -1
  50. package/vscode-html-data.json +1 -1
  51. package/web-types.json +1 -1
@@ -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{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount}from"../../../internal/numbers.js";import{normalizeChatComposerStatus}from"../chat-composer/chat-composer.class.js";import{styles}from"./agent-workspace.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_agentWorkspaceContext,LYRA_DEFAULT_agentWorkspaceConversation,LYRA_DEFAULT_agentWorkspaceDetails,LYRA_DEFAULT_agentWorkspaceEmpty,LYRA_DEFAULT_agentWorkspaceGrounding,LYRA_DEFAULT_agentWorkspaceLabel,LYRA_DEFAULT_agentWorkspaceRetrieval,LYRA_DEFAULT_agentWorkspaceRun,LYRA_DEFAULT_agentWorkspaceTools,LYRA_DEFAULT_composerPlaceholder,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";const MAX_RENDERED_MESSAGES=500;function firstByWorkspaceIdentity(items,identity){const result=[],seen=new Set;for(const item of items){let id;try{id=identity(item)}catch{continue}typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),result.push(item))}return result}class LyraAgentWorkspace extends LyraElement{constructor(){super(...arguments),this.label="",this.accessibleLabel=null,this.messages=[],this.run=null,this.metrics=[],this.tools=[],this.retrievalChunks=[],this.selectedRetrievalChunkIds=[],this.retrievalLoading=!1,this.retrievalHasMore=!1,this.retrievalErrorText="",this.groundingAssessment=null,this.citations=[],this.contextSegments=[],this.contextTotal=0,this.follow=!0,this.unreadStartIndex=null,this.showDetails=!0,this.showComposer=!0,this.composerValue="",this.composerStatusValue="idle",this.composerPlaceholder="",this.composerMinRows=1,this.composerMaxRows=8,this.onRetrievalSelect=event=>{event.stopPropagation(),this.emit("lr-retrieval-select",event.detail)},this.onMessageRetry=event=>{event.stopPropagation(),event.detail.messageId&&this.emit("lr-message-retry",{messageId:event.detail.messageId})},this.onNamedSlotChange=()=>{this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,agentWorkspaceContext:LYRA_DEFAULT_agentWorkspaceContext,agentWorkspaceConversation:LYRA_DEFAULT_agentWorkspaceConversation,agentWorkspaceDetails:LYRA_DEFAULT_agentWorkspaceDetails,agentWorkspaceEmpty:LYRA_DEFAULT_agentWorkspaceEmpty,agentWorkspaceGrounding:LYRA_DEFAULT_agentWorkspaceGrounding,agentWorkspaceLabel:LYRA_DEFAULT_agentWorkspaceLabel,agentWorkspaceRetrieval:LYRA_DEFAULT_agentWorkspaceRetrieval,agentWorkspaceRun:LYRA_DEFAULT_agentWorkspaceRun,agentWorkspaceTools:LYRA_DEFAULT_agentWorkspaceTools,composerPlaceholder:LYRA_DEFAULT_composerPlaceholder,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.immutableEventDetails=Object.freeze(["lr-retrieval-select"])}static{this.ownedCollectionProperties=Object.freeze(["messages","run","metrics","tools","retrievalChunks","selectedRetrievalChunkIds","groundingAssessment","citations","contextSegments"])}static{this.styles=[LyraElement.styles,styles]}get composerStatus(){return this.composerStatusValue}set composerStatus(value){const previous=this.composerStatusValue;this.composerStatusValue=normalizeChatComposerStatus(value),this.requestUpdate("composerStatus",previous)}hasSlotted(name){return Array.from(this.children).some(element=>element.getAttribute("slot")===name)}get safeContextTotal(){return finiteCount(this.contextTotal)}get effectiveTools(){return firstByWorkspaceIdentity(this.tools,entry=>{const id=entry.id;if(typeof id!="string"||id.trim()==="")return;const sourceKey=entry.sourceKey;return`${typeof sourceKey=="string"?sourceKey:""}\0${id}`})}get effectiveRetrievalChunks(){return firstByWorkspaceIdentity(this.retrievalChunks,chunk=>chunk.id)}get effectiveCitations(){return firstByWorkspaceIdentity(this.citations,citation=>citation.id)}get effectiveContextSegments(){return firstByWorkspaceIdentity(this.contextSegments,segment=>segment.id)}get effectiveMessages(){const source=this.messages,seen=new Set,messages=[];for(let sourceIndex=0;sourceIndex<source.length;sourceIndex++){const message=source[sourceIndex];if(!message)continue;const id=message?.id;typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),messages.push({message,sourceIndex}))}return messages}get safeUnreadStartIndex(){if(this.unreadStartIndex==null)return null;const normalized=finiteCount(this.unreadStartIndex);if(this.hasSlotted("messages"))return normalized;const messages=this.effectiveMessages,effectiveIndex=messages.filter(({sourceIndex})=>sourceIndex<normalized).length;return Math.max(0,effectiveIndex-this.messageWindowOffsetFor(messages))}get safeComposerMinRows(){return Math.max(1,finiteCount(this.composerMinRows,1))}get safeComposerMaxRows(){return Math.max(this.safeComposerMinRows,finiteCount(this.composerMaxRows,8))}stopOwnedEvent(event){event.stopPropagation()}renderMessage(message){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{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount}from"../../../internal/numbers.js";import{normalizeChatComposerStatus}from"../chat-composer/chat-composer.class.js";import{styles}from"./agent-workspace.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_agentWorkspaceContext,LYRA_DEFAULT_agentWorkspaceConversation,LYRA_DEFAULT_agentWorkspaceDetails,LYRA_DEFAULT_agentWorkspaceEmpty,LYRA_DEFAULT_agentWorkspaceGrounding,LYRA_DEFAULT_agentWorkspaceLabel,LYRA_DEFAULT_agentWorkspaceRetrieval,LYRA_DEFAULT_agentWorkspaceRun,LYRA_DEFAULT_agentWorkspaceTools,LYRA_DEFAULT_composerPlaceholder,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";const MAX_RENDERED_MESSAGES=500;function firstByWorkspaceIdentity(items,identity){const result=[],seen=new Set;for(const item of items){let id;try{id=identity(item)}catch{continue}typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),result.push(item))}return result}class LyraAgentWorkspace extends LyraElement{constructor(){super(...arguments),this.accessibleLabel=null,this.messages=[],this.run=null,this.metrics=[],this.tools=[],this.retrievalChunks=[],this.selectedRetrievalChunkIds=[],this.retrievalLoading=!1,this.retrievalHasMore=!1,this.retrievalErrorText="",this.groundingAssessment=null,this.citations=[],this.contextSegments=[],this.contextTotal=0,this.follow=!0,this.unreadStartIndex=null,this.showDetails=!0,this.showComposer=!0,this.composerValue="",this.composerStatusValue="idle",this.composerMinRows=1,this.composerMaxRows=8,this.onRetrievalSelect=event=>{event.stopPropagation(),this.emit("lr-retrieval-select",event.detail)},this.onMessageRetry=event=>{event.stopPropagation(),event.detail.messageId&&this.emit("lr-message-retry",{messageId:event.detail.messageId})},this.onNamedSlotChange=()=>{this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,agentWorkspaceContext:LYRA_DEFAULT_agentWorkspaceContext,agentWorkspaceConversation:LYRA_DEFAULT_agentWorkspaceConversation,agentWorkspaceDetails:LYRA_DEFAULT_agentWorkspaceDetails,agentWorkspaceEmpty:LYRA_DEFAULT_agentWorkspaceEmpty,agentWorkspaceGrounding:LYRA_DEFAULT_agentWorkspaceGrounding,agentWorkspaceLabel:LYRA_DEFAULT_agentWorkspaceLabel,agentWorkspaceRetrieval:LYRA_DEFAULT_agentWorkspaceRetrieval,agentWorkspaceRun:LYRA_DEFAULT_agentWorkspaceRun,agentWorkspaceTools:LYRA_DEFAULT_agentWorkspaceTools,composerPlaceholder:LYRA_DEFAULT_composerPlaceholder,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.immutableEventDetails=Object.freeze(["lr-retrieval-select"])}static{this.ownedCollectionProperties=Object.freeze(["messages","run","metrics","tools","retrievalChunks","selectedRetrievalChunkIds","groundingAssessment","citations","contextSegments"])}static{this.styles=[LyraElement.styles,styles]}get composerStatus(){return this.composerStatusValue}set composerStatus(value){const previous=this.composerStatusValue;this.composerStatusValue=normalizeChatComposerStatus(value),this.requestUpdate("composerStatus",previous)}hasSlotted(name){return Array.from(this.children).some(element=>element.getAttribute("slot")===name)}get safeContextTotal(){return finiteCount(this.contextTotal)}get effectiveTools(){return firstByWorkspaceIdentity(this.tools,entry=>{const id=entry.id;if(typeof id!="string"||id.trim()==="")return;const sourceKey=entry.sourceKey;return`${typeof sourceKey=="string"?sourceKey:""}\0${id}`})}get effectiveRetrievalChunks(){return firstByWorkspaceIdentity(this.retrievalChunks,chunk=>chunk.id)}get effectiveCitations(){return firstByWorkspaceIdentity(this.citations,citation=>citation.id)}get effectiveContextSegments(){return firstByWorkspaceIdentity(this.contextSegments,segment=>segment.id)}get effectiveMessages(){const source=this.messages,seen=new Set,messages=[];for(let sourceIndex=0;sourceIndex<source.length;sourceIndex++){const message=source[sourceIndex];if(!message)continue;const id=message?.id;typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),messages.push({message,sourceIndex}))}return messages}get safeUnreadStartIndex(){if(this.unreadStartIndex==null)return null;const normalized=finiteCount(this.unreadStartIndex);if(this.hasSlotted("messages"))return normalized;const messages=this.effectiveMessages,effectiveIndex=messages.filter(({sourceIndex})=>sourceIndex<normalized).length;return Math.max(0,effectiveIndex-this.messageWindowOffsetFor(messages))}get safeComposerMinRows(){return Math.max(1,finiteCount(this.composerMinRows,1))}get safeComposerMaxRows(){return Math.max(this.safeComposerMinRows,finiteCount(this.composerMaxRows,8))}stopOwnedEvent(event){event.stopPropagation()}renderMessage(message){return html`
2
2
  <lr-chat-message
3
3
  part="messages message"
4
4
  .messageRole=${message.role}
@@ -52,7 +52,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
52
52
  ></lr-context-inspector>
53
53
  </section>`:nothing}
54
54
  </div>
55
- `}get hasBuiltInDetails(){return!!(this.run||this.effectiveTools.length>0||this.effectiveRetrievalChunks.length>0||this.retrievalLoading||this.retrievalErrorText||this.groundingAssessment||this.effectiveCitations.length>0||this.effectiveContextSegments.length>0)}render(){const label=this.accessibleLabel??(this.label||this.localize("agentWorkspaceLabel")),heading=this.label||this.localize("agentWorkspaceLabel"),hasDetails=this.hasSlotted("details")||this.showDetails&&this.hasBuiltInDetails,hasSlottedComposer=this.hasSlotted("composer");return html`
55
+ `}get hasBuiltInDetails(){return!!(this.run||this.effectiveTools.length>0||this.effectiveRetrievalChunks.length>0||this.retrievalLoading||this.retrievalErrorText||this.groundingAssessment||this.effectiveCitations.length>0||this.effectiveContextSegments.length>0)}render(){const label=this.accessibleLabel??(this.label==null?this.localize("agentWorkspaceLabel"):this.label),heading=this.label==null?this.localize("agentWorkspaceLabel"):this.label,hasDetails=this.hasSlotted("details")||this.showDetails&&this.hasBuiltInDetails,hasSlottedComposer=this.hasSlotted("composer");return html`
56
56
  <div part="base" role="region" aria-label=${label}>
57
57
  <div part="header">
58
58
  <h2 part="heading">${heading}</h2>
@@ -90,7 +90,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
90
90
  .status=${this.composerStatus}
91
91
  .minRows=${this.safeComposerMinRows}
92
92
  .maxRows=${this.safeComposerMaxRows}
93
- placeholder=${this.composerPlaceholder||this.localize("composerPlaceholder")}
93
+ placeholder=${this.composerPlaceholder==null?this.localize("composerPlaceholder"):this.composerPlaceholder}
94
94
  ></lr-chat-composer>`:nothing}
95
95
  </slot>
96
96
  </div>
@@ -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
  ><path d="M6 3h12a1 1 0 0 1 1 1v16l-7-4-7 4V4a1 1 0 0 1 1-1Z"></path></svg>
14
- `}function defaultFormatTimestamp(date,locale){return getDateTimeFormat(locale||"en",{hour:"numeric",minute:"2-digit"}).format(date)}class LyraCheckpoint extends LyraElement{constructor(){super(...arguments),this.checkpointId="",this.label="",this.restorable=!0,this.confirmRestore=!0,this.restoring=!1,this.confirming=!1,this.confirmPromptId=nextId("checkpoint-confirm-prompt"),this.focusGeneration=0,this.onRestoreClick=()=>{if(!this.restorable||this.restoring||this.confirming)return;if(!this.confirmRestore){this.fireRestore();return}this.confirming=!0;const generation=++this.focusGeneration;this.updateComplete.then(()=>{generation!==this.focusGeneration||!this.isConnected||!this.confirming||this.renderRoot.querySelector('[part="confirm-button"]')?.focus()})},this.onConfirmClick=()=>{if(!this.confirming||!this.restorable||!this.confirmRestore||this.restoring){this.revertToRestore(!1);return}this.revertToRestore(!0),this.fireRestore()},this.onCancelClick=()=>this.revertToRestore(!0),this.onConfirmGroupKeyDown=e=>{e.key==="Escape"&&this.confirming&&(e.stopPropagation(),this.revertToRestore(!0))},this.onConfirmGroupFocusOut=e=>{const next=e.relatedTarget,group=this.renderRoot.querySelector('[part="confirm-group"]');group&&(!next||!group.contains(next))&&this.revertToRestore(!1)}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,checkpointConfirmPrompt:LYRA_DEFAULT_checkpointConfirmPrompt,checkpointLabel:LYRA_DEFAULT_checkpointLabel,checkpointRestore:LYRA_DEFAULT_checkpointRestore,checkpointRestoreWithContext:LYRA_DEFAULT_checkpointRestoreWithContext,checkpointRestoring:LYRA_DEFAULT_checkpointRestoring,confirm:LYRA_DEFAULT_confirm}}static{this.styles=[LyraElement.styles,styles]}get computedLabel(){return this.label||this.localize("checkpointLabel")}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}fireRestore(){this.emit("lr-restore",{checkpointId:this.checkpointId,label:this.computedLabel})}revertToRestore(refocus){if(!this.confirming)return;this.confirming=!1;const generation=++this.focusGeneration;refocus&&this.updateComplete.then(()=>{generation!==this.focusGeneration||!this.isConnected||this.confirming||!this.restorable||this.renderRoot.querySelector('[part="restore-button"]')?.focus()})}willUpdate(changed){super.willUpdate(changed),this.confirming&&(changed.has("restorable")||changed.has("confirmRestore")||changed.has("restoring"))&&(!this.restorable||!this.confirmRestore||this.restoring)&&(this.confirming=!1,this.focusGeneration++)}disconnectedCallback(){this.confirming=!1,this.focusGeneration++,super.disconnectedCallback()}click(){!this.restorable||this.restoring||this.confirming||this.renderRoot.querySelector('[part="restore-button"]')?.click()}render(){const label=this.computedLabel,ariaLabel=this.getAttribute("aria-label")??label,ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>defaultFormatTimestamp(date,this.effectiveLocale));return html`
14
+ `}function defaultFormatTimestamp(date,locale){return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit"}).format(date)}class LyraCheckpoint extends LyraElement{constructor(){super(...arguments),this.checkpointId="",this.label="",this.restorable=!0,this.confirmRestore=!0,this.restoring=!1,this.confirming=!1,this.confirmPromptId=nextId("checkpoint-confirm-prompt"),this.focusGeneration=0,this.onRestoreClick=()=>{if(!this.restorable||this.restoring||this.confirming)return;if(!this.confirmRestore){this.fireRestore();return}this.confirming=!0;const generation=++this.focusGeneration;this.updateComplete.then(()=>{generation!==this.focusGeneration||!this.isConnected||!this.confirming||this.renderRoot.querySelector('[part="confirm-button"]')?.focus()})},this.onConfirmClick=()=>{if(!this.confirming||!this.restorable||!this.confirmRestore||this.restoring){this.revertToRestore(!1);return}this.revertToRestore(!0),this.fireRestore()},this.onCancelClick=()=>this.revertToRestore(!0),this.onConfirmGroupKeyDown=e=>{e.key==="Escape"&&this.confirming&&(e.stopPropagation(),this.revertToRestore(!0))},this.onConfirmGroupFocusOut=e=>{const next=e.relatedTarget,group=this.renderRoot.querySelector('[part="confirm-group"]');group&&(!next||!group.contains(next))&&this.revertToRestore(!1)}}static{this.defaultStrings={...super.defaultStrings,cancel:LYRA_DEFAULT_cancel,checkpointConfirmPrompt:LYRA_DEFAULT_checkpointConfirmPrompt,checkpointLabel:LYRA_DEFAULT_checkpointLabel,checkpointRestore:LYRA_DEFAULT_checkpointRestore,checkpointRestoreWithContext:LYRA_DEFAULT_checkpointRestoreWithContext,checkpointRestoring:LYRA_DEFAULT_checkpointRestoring,confirm:LYRA_DEFAULT_confirm}}static{this.styles=[LyraElement.styles,styles]}get computedLabel(){return this.label||this.localize("checkpointLabel")}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}fireRestore(){this.emit("lr-restore",{checkpointId:this.checkpointId,label:this.computedLabel})}revertToRestore(refocus){if(!this.confirming)return;this.confirming=!1;const generation=++this.focusGeneration;refocus&&this.updateComplete.then(()=>{generation!==this.focusGeneration||!this.isConnected||this.confirming||!this.restorable||this.renderRoot.querySelector('[part="restore-button"]')?.focus()})}willUpdate(changed){super.willUpdate(changed),this.confirming&&(changed.has("restorable")||changed.has("confirmRestore")||changed.has("restoring"))&&(!this.restorable||!this.confirmRestore||this.restoring)&&(this.confirming=!1,this.focusGeneration++)}disconnectedCallback(){this.confirming=!1,this.focusGeneration++,super.disconnectedCallback()}click(){!this.restorable||this.restoring||this.confirming||this.renderRoot.querySelector('[part="restore-button"]')?.click()}render(){const label=this.computedLabel,ariaLabel=this.getAttribute("aria-label")??label,ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>defaultFormatTimestamp(date,this.effectiveLocale));return html`
15
15
  <div part="base" role="group" aria-label=${ariaLabel}>
16
16
  <span part="line" aria-hidden="true"></span>
17
17
  <span part="icon" aria-hidden="true">${bookmarkIcon()}</span>
@@ -1 +1 @@
1
- import{getDateTimeFormat}from"../../../internal/intl-cache.js";function normalizeCalendarMonths(value){const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)?Math.min(2,Math.max(1,Math.trunc(numeric))):1}function normalizeWeekdayFormat(value){return value==="narrow"||value==="long"?value:"short"}function normalizeCalendarMode(value){return value==="range"?"range":"single"}function dateTimeFormat(locale,options){try{return getDateTimeFormat(typeof locale=="string"&&locale?locale:void 0,{calendar:"gregory",...options})}catch{return getDateTimeFormat(void 0,{calendar:"gregory",...options})}}function localDate(year,month=0,day=1){const date=new Date(0);return date.setHours(0,0,0,0),date.setFullYear(year,month,day),date}function utcDate(year,month=0,day=1){const date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month,day),date}function parseISO(s){if(!s)return null;const m=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s.trim());if(!m)return null;const year=Number(m[1]),month=Number(m[2]),day=Number(m[3]),d=localDate(year,month-1,day);return isNaN(d.getTime())||d.getFullYear()!==year||d.getMonth()!==month-1||d.getDate()!==day?null:d}function formatISO(d){if(!Number.isFinite(d.getTime())||d.getFullYear()<0||d.getFullYear()>9999)return"";const mm=String(d.getMonth()+1).padStart(2,"0"),dd=String(d.getDate()).padStart(2,"0");return`${String(d.getFullYear()).padStart(4,"0")}-${mm}-${dd}`}function isSameDay(a,b){return a.getFullYear()===b.getFullYear()&&a.getMonth()===b.getMonth()&&a.getDate()===b.getDate()}function addMonths(d,n){return localDate(d.getFullYear(),d.getMonth()+n,1)}function addMonthsClampingDay(d,n){const targetMonth=d.getMonth()+n,lastDayOfTargetMonth=localDate(d.getFullYear(),targetMonth+1,0).getDate();return localDate(d.getFullYear(),targetMonth,Math.min(d.getDate(),lastDayOfTargetMonth))}function clampDate(d,min,max){return min&&d<min?min:max&&d>max?max:d}function monthMatrix(year,month,firstDayOfWeek=0){const offset=(localDate(year,month,1).getDay()-firstDayOfWeek+7)%7,cursor=localDate(year,month,1-offset),weeks=[];for(let w=0;w<6;w++){const row=[];for(let d=0;d<7;d++)row.push(new Date(cursor)),cursor.setDate(cursor.getDate()+1);weeks.push(row)}return weeks}function weekdayLabels(firstDayOfWeek=0,format="short",locale){const numericFirstDay=Number(firstDayOfWeek),start=Number.isFinite(numericFirstDay)?(Math.trunc(numericFirstDay)%7+7)%7:0,fmt=dateTimeFormat(locale,{weekday:normalizeWeekdayFormat(format)}),labels=[];for(let i=0;i<7;i++){const day=(start+i)%7;labels.push(fmt.format(new Date(2021,7,1+day)))}return labels}function monthTitle(year,month,locale){return dateTimeFormat(locale,{month:"long",year:"numeric"}).format(localDate(year,month,1))}const FDOW={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6};function localeFirstDayOfWeek(locale){try{const l=new Intl.Locale(locale),firstDay=l.weekInfo?.firstDay??l.getWeekInfo?.().firstDay;return firstDay?firstDay%7:null}catch{return null}}function resolveFirstDayOfWeek(value,locale){return!value||value==="auto"?(locale?localeFirstDayOfWeek(locale):null)??0:typeof value=="string"?FDOW[value.toLowerCase()]??0:0}export{addMonths,addMonthsClampingDay,clampDate,dateTimeFormat,formatISO,isSameDay,localDate,monthMatrix,monthTitle,normalizeCalendarMode,normalizeCalendarMonths,normalizeWeekdayFormat,parseISO,resolveFirstDayOfWeek,utcDate,weekdayLabels};
1
+ import{getDateTimeFormat}from"../../../internal/intl-cache.js";function normalizeCalendarMonths(value){const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)?Math.min(2,Math.max(1,Math.trunc(numeric))):1}function normalizeWeekdayFormat(value){return value==="narrow"||value==="long"?value:"short"}function normalizeCalendarMode(value){return value==="range"?"range":"single"}function dateTimeFormat(locale,options){try{return getDateTimeFormat(typeof locale=="string"&&locale?locale:void 0,{calendar:"gregory",...options})}catch{return getDateTimeFormat(void 0,{calendar:"gregory",...options})}}function localDate(year,month=0,day=1){const date=new Date(0);return date.setHours(0,0,0,0),date.setFullYear(year,month,day),date}function utcDate(year,month=0,day=1){const date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month,day),date}function parseISO(s){if(!s)return null;const m=/^(\d{4})-(\d{2})-(\d{2})$/.exec(s.trim());if(!m)return null;const year=Number(m[1]),month=Number(m[2]),day=Number(m[3]),d=localDate(year,month-1,day);return!Number.isFinite(d.getTime())||d.getFullYear()!==year||d.getMonth()!==month-1||d.getDate()!==day?null:d}function formatISO(d){if(!Number.isFinite(d.getTime())||d.getFullYear()<0||d.getFullYear()>9999)return"";const mm=String(d.getMonth()+1).padStart(2,"0"),dd=String(d.getDate()).padStart(2,"0");return`${String(d.getFullYear()).padStart(4,"0")}-${mm}-${dd}`}function isSameDay(a,b){return a.getFullYear()===b.getFullYear()&&a.getMonth()===b.getMonth()&&a.getDate()===b.getDate()}function addMonths(d,n){return localDate(d.getFullYear(),d.getMonth()+n,1)}function addMonthsClampingDay(d,n){const targetMonth=d.getMonth()+n,lastDayOfTargetMonth=localDate(d.getFullYear(),targetMonth+1,0).getDate();return localDate(d.getFullYear(),targetMonth,Math.min(d.getDate(),lastDayOfTargetMonth))}function clampDate(d,min,max){return min&&d<min?min:max&&d>max?max:d}function monthMatrix(year,month,firstDayOfWeek=0){const offset=(localDate(year,month,1).getDay()-firstDayOfWeek+7)%7,cursor=localDate(year,month,1-offset),weeks=[];for(let w=0;w<6;w++){const row=[];for(let d=0;d<7;d++)row.push(new Date(cursor)),cursor.setDate(cursor.getDate()+1);weeks.push(row)}return weeks}function weekdayLabels(firstDayOfWeek=0,format="short",locale){const numericFirstDay=Number(firstDayOfWeek),start=Number.isFinite(numericFirstDay)?(Math.trunc(numericFirstDay)%7+7)%7:0,fmt=dateTimeFormat(locale,{weekday:normalizeWeekdayFormat(format)}),labels=[];for(let i=0;i<7;i++){const day=(start+i)%7;labels.push(fmt.format(new Date(2021,7,1+day)))}return labels}function monthTitle(year,month,locale){return dateTimeFormat(locale,{month:"long",year:"numeric"}).format(localDate(year,month,1))}const FDOW={sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6};function localeFirstDayOfWeek(locale){try{const l=new Intl.Locale(locale),firstDay=l.weekInfo?.firstDay??l.getWeekInfo?.().firstDay;return firstDay?firstDay%7:null}catch{return null}}function resolveFirstDayOfWeek(value,locale){return!value||value==="auto"?(locale?localeFirstDayOfWeek(locale):null)??0:typeof value=="string"?FDOW[value.toLowerCase()]??0:0}export{addMonths,addMonthsClampingDay,clampDate,dateTimeFormat,formatISO,isSameDay,localDate,monthMatrix,monthTitle,normalizeCalendarMode,normalizeCalendarMonths,normalizeWeekdayFormat,parseISO,resolveFirstDayOfWeek,utcDate,weekdayLabels};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{syncAriaControlsElements,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute}from"../../../internal/safe-svg.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_iconButtonLabel}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]),SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-"))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)isUnsafeSvgCloneAttribute(attribute.name)||copy.setAttribute(attribute.name,attribute.value);for(const child of node.childNodes)if(child.nodeType===3)copy.append(child.cloneNode(!0));else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);childCopy&&copy.append(childCopy)}return copy}class LyraIconButton extends LyraElement{constructor(){super(...arguments),this._disabled=!1,this.toolbarAction=this.createToolbarAction(),this.icon="",this.accessibleLabel="",this.triggerHasPopup=null,this.triggerExpanded=null,this.triggerControls=null,this.triggerDescribedBy=null,this.triggerPressed=null,this.triggerCurrent=null,this.label="",this.hasBareGeometry=!1,this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{relayNativeEvent(this,event)},this.onSlotChange=e=>{this.onSlotChangeFromSlot(e.target)}}static{this.defaultStrings={...super.defaultStrings,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled}get name(){return this.icon}set name(next){this.icon=next??""}get resolvedRel(){const authored=(this.rel??"").split(/\s+/).filter(token=>token!==""&&token.toLowerCase()!=="opener"),tokens=new Set(authored);return this.target&&(tokens.add("noopener"),tokens.add("noreferrer")),tokens.size>0?[...tokens].join(" "):void 0}get control(){return this.baseEl??null}click(){this.effectiveDisabled||this.baseEl?.click()}focus(options){this.effectiveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}onSlotChangeFromSlot(slot){const assigned=slot.assignedElements({flatten:!0});this.hasBareGeometry=assigned.some(el=>needsSvgNamespaceFallback(el))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.slotEl;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onSlotChangeFromSlot(s))})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}updated(changed){super.updated(changed),this.syncFallbackGeometry(),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements()}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"),this.externalLabelLease?this.externalLabelLease.update(target):this.externalLabelLease=acquireResolvedAriaRelationship(this,target,"aria-labelledby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0,this.externalLabelLease?.release(),this.externalLabelLease=void 0}getToolbarActions(){return[this.toolbarAction]}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1;const releaseTabIndex=()=>{const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"icon-button",get disabled(){return host.effectiveDisabled||!host.baseEl},focus(options){host.focus(options)},setTabIndex(tabIndex){const trigger=host.baseEl;if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const control=host.baseEl;return path.includes(host)||control!=null&&path.includes(control)}}}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:!0})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);copy&&svgEl.append(copy)}}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,label=this.accessibleLabel||this.label||this.localize("iconButtonLabel"),content=html`${this.icon||this.src?html`<lr-icon
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{syncAriaControlsElements,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_iconButtonLabel}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]),SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-")||isUnsafeSvgCloneElement(node.localName))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value)||copy.setAttribute(attribute.name,attribute.value);for(const child of node.childNodes)if(child.nodeType===3)copy.append(child.cloneNode(!0));else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);childCopy&&copy.append(childCopy)}return copy}class LyraIconButton extends LyraElement{constructor(){super(...arguments),this._disabled=!1,this.toolbarAction=this.createToolbarAction(),this.icon="",this.accessibleLabel="",this.triggerHasPopup=null,this.triggerExpanded=null,this.triggerControls=null,this.triggerDescribedBy=null,this.triggerPressed=null,this.triggerCurrent=null,this.label="",this.hasBareGeometry=!1,this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{relayNativeEvent(this,event)},this.onSlotChange=e=>{this.onSlotChangeFromSlot(e.target)}}static{this.defaultStrings={...super.defaultStrings,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled}get name(){return this.icon}set name(next){this.icon=next??""}get resolvedRel(){const authored=(this.rel??"").split(/\s+/).filter(token=>token!==""&&token.toLowerCase()!=="opener"),tokens=new Set(authored);return this.target&&(tokens.add("noopener"),tokens.add("noreferrer")),tokens.size>0?[...tokens].join(" "):void 0}get control(){return this.baseEl??null}click(){this.effectiveDisabled||this.baseEl?.click()}focus(options){this.effectiveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}onSlotChangeFromSlot(slot){const assigned=slot.assignedElements({flatten:!0});this.hasBareGeometry=assigned.some(el=>needsSvgNamespaceFallback(el))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.slotEl;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onSlotChangeFromSlot(s))})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}updated(changed){super.updated(changed),this.syncFallbackGeometry(),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements()}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"),this.externalLabelLease?this.externalLabelLease.update(target):this.externalLabelLease=acquireResolvedAriaRelationship(this,target,"aria-labelledby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0,this.externalLabelLease?.release(),this.externalLabelLease=void 0}getToolbarActions(){return[this.toolbarAction]}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1;const releaseTabIndex=()=>{const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"icon-button",get disabled(){return host.effectiveDisabled||!host.baseEl},focus(options){host.focus(options)},setTabIndex(tabIndex){const trigger=host.baseEl;if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const control=host.baseEl;return path.includes(host)||control!=null&&path.includes(control)}}}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:!0})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);copy&&svgEl.append(copy)}}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,label=this.accessibleLabel||this.label||this.localize("iconButtonLabel"),content=html`${this.icon||this.src?html`<lr-icon
2
2
  name=${this.icon||nothing}
3
3
  library=${this.library||nothing}
4
4
  src=${this.src||nothing}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AggregateFileLimitTracker}from"../../../internal/aggregate-file-limits.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{fileIcon}from"../../../internal/icons.js";import{DropSessionController}from"../../../internal/drop-session-controller.js";import{matchesAccept}from"../file-input/accept.js";import{styles}from"./drop-zone.styles.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType}from"../../../internal/default-strings.generated.js";const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,DEFAULT_MAX_FILES=100,DEFAULT_MAX_TOTAL_SIZE_BYTES=250*1024*1024;class LyraDropZone extends LyraElement{static{this.defaultStrings={...super.defaultStrings,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.styles=[LyraElement.styles,styles,srOnly]}constructor(){super(),this.disabled=!1,this.multiple=!0,this.accept="",this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.dragState="default",this.rejectedFiles=Object.freeze([]),this.resultStatus="",this.announcementsArmed=!1,this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>{const drop=this.dropSession.beginDrop(e);if(!drop)return;const{token,files,folders,overLimit}=drop;if(overLimit&&this.multiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.multiple){this.dropSession.readFolders(folders,token).then(result=>{if(!this.dropSession.isCurrent(token)||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.internals=attachInternalsSafely(this),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.disabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,setCustomState(this.internals,"dragging",this.dropSession.dragging)}})}get dragging(){return this.dragState!=="default"}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropSession.reset()}connectedCallback(){super.connectedCallback(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.overlayText()),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}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}get effectiveMaxFiles(){const maxFiles=this.maxFiles;return maxFiles===0||maxFiles===1/0?null:finiteRange(maxFiles>0?maxFiles:NaN,DEFAULT_MAX_FILES,1)}get effectiveMaxTotalSize(){const maxTotalSize=this.maxTotalSize;return maxTotalSize===0||maxTotalSize===1/0?null:finiteRange(maxTotalSize>0?maxTotalSize:NaN,DEFAULT_MAX_TOTAL_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(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){const limits={maxFiles:this.effectiveMaxFiles,maxTotalSize:this.effectiveMaxTotalSize},tracker=new AggregateFileLimitTracker(finiteCount(this.heldFileCount,0),finiteCount(this.heldTotalSize,0));if(!this.multiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"})),...tracker.allowance(limits)};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason!=="ok"){rejected.push({file:f,reason});continue}const limitReason=tracker.evaluate(f,limits);if(limitReason){rejected.push({file:f,reason:limitReason});continue}files.push(f)}return{files,rejected,...tracker.allowance(limits)}}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});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",void 0,{filename})}}emitFiles(fileList,additionalRejected=[]){const{files,rejected,remainingFiles,remainingTotalSize}=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.localize(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",void 0,{count:numberFormat.format(files.length)})),rejected.length&&messages.push(this.localize(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",void 0,{count:numberFormat.format(rejected.length)})),this.resultStatus=messages.filter(message=>message.length>0).join(" "),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot,remainingFiles,remainingTotalSize}))}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}overlayText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}statusText(){return this.dragState==="default"?this.resultStatus:this.overlayText()}render(){return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AggregateFileLimitTracker}from"../../../internal/aggregate-file-limits.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{fileIcon}from"../../../internal/icons.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{DropSessionController}from"../../../internal/drop-session-controller.js";import{matchesAccept}from"../file-input/accept.js";import{styles}from"./drop-zone.styles.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType}from"../../../internal/default-strings.generated.js";const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,DEFAULT_MAX_FILES=100,DEFAULT_MAX_TOTAL_SIZE_BYTES=250*1024*1024;class LyraDropZone extends LyraElement{static{this.defaultStrings={...super.defaultStrings,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.styles=[LyraElement.styles,styles,srOnly]}constructor(){super(),this.disabled=!1,this.multiple=!0,this.accept="",this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.dragState="default",this.rejectedFiles=Object.freeze([]),this.resultStatus="",this.announcementsArmed=!1,this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>{const drop=this.dropSession.beginDrop(e);if(!drop)return;const{token,files,folders,overLimit}=drop;if(overLimit&&this.multiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.multiple){this.dropSession.readFolders(folders,token).then(result=>{if(!this.dropSession.isCurrent(token)||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.internals=attachInternalsSafely(this),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.disabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,setCustomState(this.internals,"dragging",this.dropSession.dragging)}})}get dragging(){return this.dragState!=="default"}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropSession.reset()}connectedCallback(){super.connectedCallback(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.overlayText()),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}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}get effectiveMaxFiles(){const maxFiles=this.maxFiles;return maxFiles===0||maxFiles===1/0?null:finiteRange(maxFiles>0?maxFiles:NaN,DEFAULT_MAX_FILES,1)}get effectiveMaxTotalSize(){const maxTotalSize=this.maxTotalSize;return maxTotalSize===0||maxTotalSize===1/0?null:finiteRange(maxTotalSize>0?maxTotalSize:NaN,DEFAULT_MAX_TOTAL_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(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){const limits={maxFiles:this.effectiveMaxFiles,maxTotalSize:this.effectiveMaxTotalSize},tracker=new AggregateFileLimitTracker(finiteCount(this.heldFileCount,0),finiteCount(this.heldTotalSize,0));if(!this.multiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"})),...tracker.allowance(limits)};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason!=="ok"){rejected.push({file:f,reason});continue}const limitReason=tracker.evaluate(f,limits);if(limitReason){rejected.push({file:f,reason:limitReason});continue}files.push(f)}return{files,rejected,...tracker.allowance(limits)}}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});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",void 0,{filename})}}emitFiles(fileList,additionalRejected=[]){const{files,rejected,remainingFiles,remainingTotalSize}=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.localize(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",void 0,{count:numberFormat.format(files.length)})),rejected.length&&messages.push(this.localize(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",void 0,{count:numberFormat.format(rejected.length)})),this.resultStatus=messages.filter(message=>message.length>0).join(" "),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot,remainingFiles,remainingTotalSize}))}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}overlayText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}statusText(){return this.dragState==="default"?this.resultStatus:this.overlayText()}render(){return html`
2
2
  <div
3
3
  part="base"
4
4
  @dragenter=${this.onDragEnter}
@@ -20,4 +20,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
20
20
  </ul>
21
21
  </div>
22
22
  `:nothing}
23
- `}}__decorate([property({type:Boolean,reflect:!0})],LyraDropZone.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDropZone.prototype,"multiple",void 0),__decorate([property()],LyraDropZone.prototype,"accept",void 0),__decorate([property({type:Number,attribute:"max-file-size"})],LyraDropZone.prototype,"maxFileSize",void 0),__decorate([property({type:Number,attribute:"max-files"})],LyraDropZone.prototype,"maxFiles",void 0),__decorate([property({type:Number,attribute:"max-total-size"})],LyraDropZone.prototype,"maxTotalSize",void 0),__decorate([property({type:Number,attribute:"held-file-count"})],LyraDropZone.prototype,"heldFileCount",void 0),__decorate([property({type:Number,attribute:"held-total-size"})],LyraDropZone.prototype,"heldTotalSize",void 0),__decorate([state()],LyraDropZone.prototype,"dragState",void 0),__decorate([state()],LyraDropZone.prototype,"rejectedFiles",void 0),__decorate([state()],LyraDropZone.prototype,"resultStatus",void 0);export{LyraDropZone};
23
+ `}}__decorate([property({type:Boolean,reflect:!0})],LyraDropZone.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0,converter:trueDefaultBooleanConverter})],LyraDropZone.prototype,"multiple",void 0),__decorate([property()],LyraDropZone.prototype,"accept",void 0),__decorate([property({type:Number,attribute:"max-file-size"})],LyraDropZone.prototype,"maxFileSize",void 0),__decorate([property({type:Number,attribute:"max-files"})],LyraDropZone.prototype,"maxFiles",void 0),__decorate([property({type:Number,attribute:"max-total-size"})],LyraDropZone.prototype,"maxTotalSize",void 0),__decorate([property({type:Number,attribute:"held-file-count"})],LyraDropZone.prototype,"heldFileCount",void 0),__decorate([property({type:Number,attribute:"held-total-size"})],LyraDropZone.prototype,"heldTotalSize",void 0),__decorate([state()],LyraDropZone.prototype,"dragState",void 0),__decorate([state()],LyraDropZone.prototype,"rejectedFiles",void 0),__decorate([state()],LyraDropZone.prototype,"resultStatus",void 0);export{LyraDropZone};
@@ -210,8 +210,9 @@ directory:boolean;
210
210
  /** Enables files pasted from the clipboard into the dropzone. `true`-defaulting, so a plain
211
211
  * `paste="false"` attribute (not just a `.paste=${false}` property binding) actually disables it. */
212
212
  paste:boolean;
213
- /** Form-control label. Empty or removed leaves the localized dropzone instruction as the visible fallback. */
214
- label:string;
213
+ /** Form-control label. When omitted, the localized dropzone instruction is used; an explicit
214
+ * empty string intentionally suppresses that fallback. */
215
+ label?:string;
215
216
  /** Optional hint copy. Removing the attribute removes its text and description association. */
216
217
  hint:string;
217
218
  /** Plain-text validation error. A custom-validity message is shown when this is empty. */
@@ -339,7 +340,7 @@ focus(options?:FocusOptions):void;
339
340
  blur():void;
340
341
  /** Opens the native picker, matching a user click on the semantic dropzone. */
341
342
  click():void;private onDragEnter;private onDragOver;private onDragLeave;private onDrop;private folderFailure;private onPaste;private onInputChange;private onFocus;private onBlur;private onKeyDown;private onDropzoneClick;private onVisibleLabelClick;private statusText;private dragStatusText;
342
- /** Resolves `label`'s effective text: an explicit override wins verbatim; left at the
343
- * built-in default it instead routes through `this.localize()` so a locale/`.strings`
344
- * override applies without requiring `label` itself to be set. */
343
+ /** Resolves `label`'s effective text: an explicit override wins verbatim; omission routes
344
+ * through `this.localize()` so a locale/`.strings` override applies without requiring
345
+ * `label` itself to be set. */
345
346
  private get effectiveLabel();private removeFile;private fileSize;private renderFile;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-file-input':LyraFileInput;}}
@@ -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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AggregateFileLimitTracker}from"../../../internal/aggregate-file-limits.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController}from"../../../internal/drop-session-controller.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_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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,DEFAULT_MAX_FILES=100,DEFAULT_MAX_TOTAL_SIZE_BYTES=250*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,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,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.hasSyncedDescribedByElements=!1,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.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>{const drop=this.dropSession.beginDrop(e);if(!drop)return;const{token,files,folders,overLimit}=drop;if(overLimit&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){this.dropSession.readFolders(folders,token).then(result=>{if(!this.dropSession.isCurrent(token)||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)),installInteractionOnInvalid(this,this.markInteracted),this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}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=[...valid];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.dropSession.reset(),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")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):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.disconnectValidatorAttributeObserver(),this.dropSession.reset();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()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),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.hasEffectiveValue&&(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()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),withStaticValidityCheck(this,()=>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.dropSession.reset(),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)}get effectiveMaxFiles(){const maxFiles=this.maxFiles;return maxFiles===0||maxFiles===1/0?null:finiteRange(maxFiles>0?maxFiles:NaN,DEFAULT_MAX_FILES,1)}get effectiveMaxTotalSize(){const maxTotalSize=this.maxTotalSize;return maxTotalSize===0||maxTotalSize===1/0?null:finiteRange(maxTotalSize>0?maxTotalSize:NaN,DEFAULT_MAX_TOTAL_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"}totalFileSize(files){let total=0;for(const file of files){const size=file.size;Number.isFinite(size)&&(total+=size)}return total}classify(fileList,isPreview=!1){const limits={maxFiles:this.effectiveMaxFiles,maxTotalSize:this.effectiveMaxTotalSize},tracker=new AggregateFileLimitTracker((this.nonRetaining?0:this._files.length)+finiteCount(this.heldFileCount,0),(this.nonRetaining?0:this.totalFileSize(this._files))+finiteCount(this.heldTotalSize,0));if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"})),...tracker.allowance(limits)};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason!=="ok"){rejected.push({file:f,reason});continue}const limitReason=tracker.evaluate(f,limits);if(limitReason){rejected.push({file:f,reason:limitReason});continue}files.push(f)}return{files,rejected,...tracker.allowance(limits)}}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});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",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,remainingFiles,remainingTotalSize}=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.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot,remainingFiles,remainingTotalSize}))}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()}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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AggregateFileLimitTracker}from"../../../internal/aggregate-file-limits.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController}from"../../../internal/drop-session-controller.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_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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,DEFAULT_MAX_FILES=100,DEFAULT_MAX_TOTAL_SIZE_BYTES=250*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,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.paste=!0,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.hasSyncedDescribedByElements=!1,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.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>{const drop=this.dropSession.beginDrop(e);if(!drop)return;const{token,files,folders,overLimit}=drop;if(overLimit&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){this.dropSession.readFolders(folders,token).then(result=>{if(!this.dropSession.isCurrent(token)||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)),installInteractionOnInvalid(this,this.markInteracted),this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}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=[...valid];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.dropSession.reset(),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")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):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.disconnectValidatorAttributeObserver(),this.dropSession.reset();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()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),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.hasEffectiveValue&&(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()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),withStaticValidityCheck(this,()=>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.dropSession.reset(),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)}get effectiveMaxFiles(){const maxFiles=this.maxFiles;return maxFiles===0||maxFiles===1/0?null:finiteRange(maxFiles>0?maxFiles:NaN,DEFAULT_MAX_FILES,1)}get effectiveMaxTotalSize(){const maxTotalSize=this.maxTotalSize;return maxTotalSize===0||maxTotalSize===1/0?null:finiteRange(maxTotalSize>0?maxTotalSize:NaN,DEFAULT_MAX_TOTAL_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"}totalFileSize(files){let total=0;for(const file of files){const size=file.size;Number.isFinite(size)&&(total+=size)}return total}classify(fileList,isPreview=!1){const limits={maxFiles:this.effectiveMaxFiles,maxTotalSize:this.effectiveMaxTotalSize},tracker=new AggregateFileLimitTracker((this.nonRetaining?0:this._files.length)+finiteCount(this.heldFileCount,0),(this.nonRetaining?0:this.totalFileSize(this._files))+finiteCount(this.heldTotalSize,0));if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"})),...tracker.allowance(limits)};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason!=="ok"){rejected.push({file:f,reason});continue}const limitReason=tracker.evaluate(f,limits);if(limitReason){rejected.push({file:f,reason:limitReason});continue}files.push(f)}return{files,rejected,...tracker.allowance(limits)}}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});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",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,remainingFiles,remainingTotalSize}=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.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot,remainingFiles,remainingTotalSize}))}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()}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==null?this.localize("fileInputDefaultLabel"):this.label}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>
@@ -1,4 +1,4 @@
1
- import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAnchor,LyraAnchorKind,HighlightActivateDetail,AnchorResultDetail}from'../../viewers/document-viewer/anchors.js';export type LyraImageFit='contain'|'width'|'actual';export type LyraImageRotation=0|90|180|270;
1
+ import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraAnchor,LyraAnchorKind,HighlightActivateDetail,AnchorResultDetail}from'../../viewers/document-viewer/anchors.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export type{LyraImageFit}from'../../../internal/image-fit.js';export type LyraImageRotation=0|90|180|270;
2
2
  /** Finite percentage coordinates. Negative widths/heights are rejected when rendered. */
3
3
  export interface LyraImageRegionRect{x:number;y:number;width:number;height:number;}
4
4
  /** Maximum region buttons projected at once. An active region beyond the leading window replaces
@@ -139,4 +139,4 @@ zoomIn:()=>void;
139
139
  /** Decreases the embedded pan/zoom scale by one configured step. */
140
140
  zoomOut:()=>void;
141
141
  /** Restores the embedded pan/zoom scale and translation. */
142
- resetZoom:()=>void;rotate():void;protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private onImgLoad;private onImgError;connectedCallback():void;adoptedCallback():void;private disconnectGeometryObserver;private updateMediaLayoutSize;private scheduleMediaLayoutSize;private syncGeometryObserver;private syncErrorAnnouncementSink;private releaseErrorAnnouncementSink;private announceLoadError;private onFrameZoomChange;private onHighlightActivate;private toggleAnnotatable;private onFitChange;private announceDraftPosition;private onWrapperKeyDown;private commitDraft;private pointerDraftId;private pointerOrigin;private cancelPointerDraft;private onWrapperPointerDown;private onWrapperPointerMove;private onWrapperPointerUp;private canonicalRegionHighlights;private boundedRegionHighlights;private onHighlightFocus;private onHighlightKeyDown;private renderHighlights;private renderDraft;private renderRevealTarget;private renderBody;render():TemplateResult;disconnectedCallback():void;}declare global{interface HTMLElementTagNameMap{'lr-image-viewer':LyraImageViewer;}}export{};
142
+ resetZoom:()=>void;rotate():void;protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;private onImgLoad;private onImgError;connectedCallback():void;adoptedCallback():void;private disconnectGeometryObserver;private updateMediaLayoutSize;private scheduleMediaLayoutSize;private syncGeometryObserver;private syncErrorAnnouncementSink;private releaseErrorAnnouncementSink;private announceLoadError;private onFrameZoomChange;private onHighlightActivate;private toggleAnnotatable;private onFitChange;private announceDraftPosition;private onWrapperKeyDown;private commitDraft;private pointerDraftId;private pointerOrigin;private cancelPointerDraft;private onWrapperPointerDown;private onWrapperPointerMove;private onWrapperPointerUp;private canonicalRegionHighlights;private boundedRegionHighlights;private onHighlightFocus;private onHighlightKeyDown;private renderHighlights;private renderDraft;private renderRevealTarget;private renderBody;render():TemplateResult;disconnectedCallback():void;}declare global{interface HTMLElementTagNameMap{'lr-image-viewer':LyraImageViewer;}}
@@ -1,4 +1,4 @@
1
- import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';import'../pan-zoom/pan-zoom.class.js';
1
+ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';import'../pan-zoom/pan-zoom.class.js';export type{LyraImageFit}from'../../../internal/image-fit.js';
2
2
  /** One image in the set `<lr-lightbox>` browses. `alt`/`caption` are caller-supplied data
3
3
  * (like a filename), not routed through `localize()` -- only the component's own chrome
4
4
  * strings are. */
@@ -1,4 +1,4 @@
1
- import{type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export interface LyraPanZoomEventMap{'lr-zoom-change':CustomEvent<{zoom:number;}>;blur:FocusEvent;focus:FocusEvent;}
1
+ import{type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraImageFit}from'../../../internal/image-fit.js';export type{LyraImageFit}from'../../../internal/image-fit.js';export interface LyraPanZoomEventMap{'lr-zoom-change':CustomEvent<{zoom:number;}>;blur:FocusEvent;focus:FocusEvent;}
2
2
  /**
3
3
  * `<lr-pan-zoom>` — a scrollable frame for inspecting slotted or image content at a bounded zoom
4
4
  * level. This is the intentionally renamed home of the original Lyra `lr-zoomable-frame`
@@ -1 +1 @@
1
- export{LyraPanZoom}from'./pan-zoom.class.js';export type{LyraPanZoomEventMap}from'./pan-zoom.class.js';
1
+ export{LyraPanZoom}from'./pan-zoom.class.js';export type{LyraPanZoomEventMap}from'./pan-zoom.class.js';export type{LyraImageFit}from'./pan-zoom.class.js';
@@ -60,11 +60,12 @@ export interface LyraDialogModalController{activateExternal():void;deactivateExt
60
60
  * no heading text, if neither `heading` nor the `label` slot is set) that closes the dialog via
61
61
  * the same `close()` path as Escape/backdrop-dismiss, with reason `'close-button'`.
62
62
  *
63
- * The `body` part is the element that scrolls, so it carries `tabindex="-1"`: a dialog holding
64
- * only prose, a table, or a rendered document would otherwise have no keyboard stop at all and
65
- * its content would be readable by mouse alone. It joins the Tab order only while it actually
66
- * overflows, sorts behind any control inside it for initial focus, and shows the standard focus
67
- * ring on `::part(body)` when it takes focus.
63
+ * The `body` part is the element that scrolls, so it carries `tabindex="0"` only while it
64
+ * actually overflows; a short body keeps `tabindex="-1"`. A dialog holding only prose, a table,
65
+ * or a rendered document would otherwise have no keyboard stop at all and its content would be
66
+ * readable by mouse alone. It joins the Tab order only while it actually overflows, sorts behind
67
+ * any control inside it for initial focus, and shows the standard focus ring on `::part(body)` when
68
+ * it takes focus.
68
69
  *
69
70
  * Stacking: opening one `<lr-dialog>` while another is already open (e.g. a
70
71
  * `confirm()` launched from within an already-open dialog) is supported --
@@ -261,7 +262,7 @@ lightDismiss:boolean;private hasFooterSlot;private hasLabelSlot;private hasHeade
261
262
  /** Set by `deactivateOverlay()` when a close defers releasing the scroll lock. Flushed once the
262
263
  * exit animation actually finishes (`settleTransition()`'s `'lr-after-hide'` branch), or right
263
264
  * away on disconnect/reopen, since nothing is left to visually protect in either case. */
264
- private pendingScrollLockRelease?;private headingObserver?;private headingObserverDocument?;private headingObserverGeneration;
265
+ private pendingScrollLockRelease?;private headingObserver?;private headingObserverDocument?;private headingObserverGeneration;private bodyOverflowObserver?;private bodyOverflowObservedBody?;
265
266
  /** Invalidates any in-flight `lr-after-show`/`lr-after-hide` wait, so a lifecycle interrupted by
266
267
  * the opposite transition (or by a disconnect) never announces a completion that never
267
268
  * happened. */
@@ -278,6 +279,11 @@ protected get modalSurface():boolean;protected willUpdate(changed:PropertyValues
278
279
  * first. Safe to call unconditionally -- a no-op once already flushed or when nothing is
279
280
  * pending. */
280
281
  private flushPendingScrollLockRelease;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private armHeadingObserver;private resetHeadingObserver;
282
+ /** Keep the scroll surface in native sequential focus order only while it has scrollable content.
283
+ * The overlay trap also measures live overflow so it can account for browsers' scroll-region
284
+ * differences; this reflected DOM state additionally satisfies the platform's accessible
285
+ * scroll-region contract and keeps short bodies out of the Tab order. */
286
+ private syncBodyTabIndex;private armBodyOverflowObserver;private resetBodyOverflowObserver;private defaultSlotElements;
281
287
  /** Whether an external-removal hide request can preserve open state for a later reconnect. */
282
288
  protected get disconnectHideCancelable():boolean;private onDefaultSlotChange;private onFooterSlotChange;private detectLightDomChrome;
283
289
  /**
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{activateOverlay,collectFocusableElements}from"../../../internal/overlay-manager.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{closeIcon}from"../../../internal/icons.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{styles}from"./dialog.styles.js";import{LYRA_DEFAULT_close}from"../../../internal/default-strings.generated.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]';class LyraDialog extends LyraElement{constructor(){super(...arguments),this._open=!1,this.label="",this.headingLevel="3",this.closable=!0,this.withoutHeader=!1,this.noHeader=!1,this.withFooter=!1,this.size="m",this.accessibleLabel="",this.hostAriaLabel=null,this.lightDismiss=!1,this.hasFooterSlot=!1,this.hasLabelSlot=!1,this.hasHeaderActionsSlot=!1,this.headingObserverGeneration=0,this.transitionToken=0,this.transitionAnimations=[],this.headingId=nextId("dialog-heading"),this.externalModalDepth=0,this.modal={activateExternal:()=>{this.externalModalDepth++,this.externalModalDepth===1&&this.overlay?.suspend()},deactivateExternal:()=>{this.externalModalDepth!==0&&(this.externalModalDepth--,this.externalModalDepth===0&&this.open&&this.modalSurface&&(this.overlay?.resume(),queueMicrotask(()=>this.focusInitial())))}},this.onDefaultSlotChange=()=>{this.detectLightDomChrome()},this.onFooterSlotChange=()=>{this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")},this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part~="close-button"]')??this;this.requestClose("close-button","close-button",button)}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get modalSurface(){return!0}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer"),this.detectLightDomChrome()),changed.has("open")&&(this.flushPendingScrollLockRelease(),this.open?this.isConnected&&this.modalSurface&&this.activateOverlay():this.pendingScrollLockRelease=this.deactivateOverlay({deferScrollLockRelease:!0}))}flushPendingScrollLockRelease(){const release=this.pendingScrollLockRelease;this.pendingScrollLockRelease=void 0,release?.()}updated(changed){super.updated(changed),changed.has("open")&&this.open&&this.isConnected&&this.modalSurface&&(this.enterTopLayer(),this.focusInitial())}connectedCallback(){super.connectedCallback(),this.armHeadingObserver(),this.hasUpdated&&this.open&&this.modalSurface&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),this.enterTopLayer(),queueMicrotask(()=>this.focusInitial()))}disconnectedCallback(){this.resetHeadingObserver(),super.disconnectedCallback(),this.overlay?.suspend(),this.transitionToken++,this.flushPendingScrollLockRelease(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.open&&queueMicrotask(()=>{if(!this.isConnected&&this.open){if(this.emit("lr-hide",{source:this},{cancelable:this.disconnectHideCancelable}).defaultPrevented){this.syncOpenAttribute();return}this.applyOpenState(!1),this.emit("lr-close","unmount"),this.emit("lr-after-hide")}})}adoptedCallback(){super.adoptedCallback(),this.resetHeadingObserver()}armHeadingObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.headingObserver&&this.headingObserverDocument===ownerDocument)return;this.resetHeadingObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headingObserverGeneration,observer=new MutationObserverCtor(()=>{this.headingObserver!==observer||this.headingObserverDocument!==ownerDocument||this.headingObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.detectLightDomChrome()});this.headingObserver=observer,this.headingObserverDocument=ownerDocument,observer.observe(this,{childList:!0,characterData:!0,subtree:!0,attributes:!0,attributeFilter:["aria-label","aria-labelledby","aria-hidden","hidden","inert","class","style","slot"]})}resetHeadingObserver(){this.headingObserverGeneration+=1,this.headingObserver?.disconnect(),this.headingObserver=void 0,this.headingObserverDocument=void 0}get disconnectHideCancelable(){return!1}detectLightDomChrome(){const children=Array.from(this.children),heading=children.find(el=>el.getAttribute("slot")===null&&el.matches(HEADING_SELECTOR));!heading||isAccessibilitySubtreeExcluded(heading)?this.headingText=void 0:heading.hasAttribute("aria-label")?this.headingText=heading.getAttribute("aria-label")??"":heading.hasAttribute("aria-labelledby")?this.headingText=composedAccessibilityText(heading,{ancestorBoundary:this}).trim()||void 0:this.headingText=composedAccessibilityText(Array.from(heading.childNodes),{ancestorBoundary:heading}).trim()||void 0,this.hasLabelSlot=children.some(el=>el.getAttribute("slot")==="label"),this.hasHeaderActionsSlot=children.some(el=>el.getAttribute("slot")==="header-actions")}show(){if(this.coalesceOpenRequest(!0)||this._open)return Promise.resolve();this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);return this.finishOpenRequest(),prevented||superseded?(this.syncOpenAttribute(),Promise.resolve()):(this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show"))}hide(){return this.close("api")}close(reason="api"){return this.closeFrom(reason,this)}closeFrom(reason,source){return this.coalesceOpenRequest(!1)||!this._open?Promise.resolve():(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):this.emit("lr-close",reason,{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):(this.finishOpenRequest(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")))}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,next&&(this.initialFocusDecision=void 0),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}panelAnimationName(showing){return showing?"dialog.show":"dialog.hide"}overlayAnimationName(showing){return showing?"dialog.overlay.show":"dialog.overlay.hide"}panelAnimationSpec(showing){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}overlayAnimationSpec(showing){return{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-backdrop-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const root=this.renderRoot,panel=root.querySelector('[part~="panel"]'),backdrop=root.querySelector('[part~="backdrop"]'),showing=event==="lr-after-show",animations=[panel?animateRegistered(this,panel,this.panelAnimationName(showing),this.effectiveDirection,this.panelAnimationSpec(showing)):void 0,this.modalSurface&&backdrop?animateRegistered(this,backdrop,this.overlayAnimationName(showing),this.effectiveDirection,this.overlayAnimationSpec(showing)):void 0].filter(animation=>animation!==void 0);if(this.transitionAnimations=animations,await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return;this.cancelTransitionAnimations()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.leaveTopLayer(),this.flushPendingScrollLockRelease()),this.emit(event)}}enterTopLayer(){if(!(!this.isConnected||typeof this.showPopover!="function")){this.getAttribute("popover")!=="manual"&&this.setAttribute("popover","manual");try{this.isTopLayer()||this.showPopover()}catch{}}}leaveTopLayer(){if(typeof this.hidePopover=="function")try{this.isTopLayer()&&this.hidePopover()}catch{}}isTopLayer(){try{return this.matches(":popover-open")}catch{return!1}}requestClose(source,reason,sourceElement){this.emit("lr-request-close",{source},{cancelable:!0}).defaultPrevented||this.closeFrom(reason,sourceElement)}focusInitial(){this.overlay?.focusInitial()}activateOverlay(){!this.isConnected||this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part~="backdrop"]')??this;this.requestClose("overlay","backdrop",backdrop)},preferredInitialFocus:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]'),body=this.renderRoot.querySelector('[part="body"]'),stops=body?collectFocusableElements(body):[];return stops.find(stop=>stop!==body)??stops[0]??panel},beforeInitialFocus:()=>(this.initialFocusDecision===void 0&&(this.initialFocusDecision=!this.emit("lr-initial-focus",null,{cancelable:!0}).defaultPrevented),this.initialFocusDecision),lockScroll:!0,suspendWhenUnrendered:!0}),this.externalModalDepth>0&&this.overlay.suspend())}deactivateOverlay(options){const overlay=this.overlay;return this.overlay=void 0,overlay?.deactivate(options)}render(){const suppressHeader=this.withoutHeader||this.noHeader,renderHeading=!suppressHeader&&!this.headingText&&(this.hasLabelSlot||(this.label??"").length>0||!!this.heading),hasHostName=this.hostAriaLabel!==null,explicitName=hasHostName?this.hostAriaLabel:this.accessibleLabel||this.headingText,hasExplicitName=hasHostName||!!explicitName,useHeadingForName=!hasExplicitName&&renderHeading,showHeader=!suppressHeader&&(renderHeading||this.hasHeaderActionsSlot||this.closable),headingLevel=resolveHeadingLevel(this.headingLevel);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{LyraElement}from"../../../internal/lyra-element.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{activateOverlay,collectFocusableElements}from"../../../internal/overlay-manager.js";import{nextId}from"../../../internal/a11y.js";import{composedAccessibilityText,isAccessibilitySubtreeExcluded}from"../../../internal/accessibility-visibility.js";import{closeIcon}from"../../../internal/icons.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{styles}from"./dialog.styles.js";import{LYRA_DEFAULT_close}from"../../../internal/default-strings.generated.js";const HEADING_SELECTOR='h1, h2, h3, h4, h5, h6, [role="heading"]';class LyraDialog extends LyraElement{constructor(){super(...arguments),this._open=!1,this.label="",this.headingLevel="3",this.closable=!0,this.withoutHeader=!1,this.noHeader=!1,this.withFooter=!1,this.size="m",this.accessibleLabel="",this.hostAriaLabel=null,this.lightDismiss=!1,this.hasFooterSlot=!1,this.hasLabelSlot=!1,this.hasHeaderActionsSlot=!1,this.headingObserverGeneration=0,this.transitionToken=0,this.transitionAnimations=[],this.headingId=nextId("dialog-heading"),this.externalModalDepth=0,this.modal={activateExternal:()=>{this.externalModalDepth++,this.externalModalDepth===1&&this.overlay?.suspend()},deactivateExternal:()=>{this.externalModalDepth!==0&&(this.externalModalDepth--,this.externalModalDepth===0&&this.open&&this.modalSurface&&(this.overlay?.resume(),queueMicrotask(()=>this.focusInitial())))}},this.onDefaultSlotChange=()=>{this.detectLightDomChrome(),this.syncBodyTabIndex(),this.resetBodyOverflowObserver(),this.armBodyOverflowObserver()},this.onFooterSlotChange=()=>{this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer")},this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part~="close-button"]')??this;this.requestClose("close-button","close-button",button)}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get modalSurface(){return!0}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFooterSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="footer"),this.detectLightDomChrome()),changed.has("open")&&(this.flushPendingScrollLockRelease(),this.open?this.isConnected&&this.modalSurface&&this.activateOverlay():this.pendingScrollLockRelease=this.deactivateOverlay({deferScrollLockRelease:!0}))}flushPendingScrollLockRelease(){const release=this.pendingScrollLockRelease;this.pendingScrollLockRelease=void 0,release?.()}updated(changed){super.updated(changed),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),changed.has("open")&&this.open&&this.isConnected&&this.modalSurface&&(this.enterTopLayer(),this.focusInitial())}connectedCallback(){super.connectedCallback(),this.armHeadingObserver(),this.syncBodyTabIndex(),this.armBodyOverflowObserver(),this.hasUpdated&&this.open&&this.modalSurface&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),this.enterTopLayer(),queueMicrotask(()=>this.focusInitial()))}disconnectedCallback(){this.resetHeadingObserver(),this.resetBodyOverflowObserver(),super.disconnectedCallback(),this.overlay?.suspend(),this.transitionToken++,this.flushPendingScrollLockRelease(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.open&&queueMicrotask(()=>{if(!this.isConnected&&this.open){if(this.emit("lr-hide",{source:this},{cancelable:this.disconnectHideCancelable}).defaultPrevented){this.syncOpenAttribute();return}this.applyOpenState(!1),this.emit("lr-close","unmount"),this.emit("lr-after-hide")}})}adoptedCallback(){super.adoptedCallback(),this.resetHeadingObserver(),this.resetBodyOverflowObserver(),this.isConnected&&(this.armHeadingObserver(),this.armBodyOverflowObserver(),this.syncBodyTabIndex())}armHeadingObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.headingObserver&&this.headingObserverDocument===ownerDocument)return;this.resetHeadingObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.headingObserverGeneration,observer=new MutationObserverCtor(()=>{this.headingObserver!==observer||this.headingObserverDocument!==ownerDocument||this.headingObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.detectLightDomChrome(),this.syncBodyTabIndex())});this.headingObserver=observer,this.headingObserverDocument=ownerDocument,observer.observe(this,{childList:!0,characterData:!0,subtree:!0,attributes:!0,attributeFilter:["aria-label","aria-labelledby","aria-hidden","hidden","inert","class","style","slot"]})}resetHeadingObserver(){this.headingObserverGeneration+=1,this.headingObserver?.disconnect(),this.headingObserver=void 0,this.headingObserverDocument=void 0}syncBodyTabIndex(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body)return;const next=this.open&&(body.scrollHeight>body.clientHeight&&body.scrollHeight>0||body.scrollWidth>body.clientWidth&&body.scrollWidth>0)?0:-1;body.tabIndex!==next&&(body.tabIndex=next)}armBodyOverflowObserver(){const body=this.renderRoot?.querySelector('[part="body"]');if(!body||!this.isConnected||this.bodyOverflowObservedBody===body)return;this.resetBodyOverflowObserver();const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{this.bodyOverflowObserver!==observer||this.bodyOverflowObservedBody!==body||!this.isConnected||this.syncBodyTabIndex()});this.bodyOverflowObserver=observer,this.bodyOverflowObservedBody=body,observer.observe(body);for(const element of this.defaultSlotElements())observer.observe(element)}resetBodyOverflowObserver(){this.bodyOverflowObserver?.disconnect(),this.bodyOverflowObserver=void 0,this.bodyOverflowObservedBody=void 0}defaultSlotElements(){return this.renderRoot?.querySelector('[part="body"] slot:not([name])')?.assignedElements({flatten:!0})??[]}get disconnectHideCancelable(){return!1}detectLightDomChrome(){const children=Array.from(this.children),heading=children.find(el=>el.getAttribute("slot")===null&&el.matches(HEADING_SELECTOR));!heading||isAccessibilitySubtreeExcluded(heading)?this.headingText=void 0:heading.hasAttribute("aria-label")?this.headingText=heading.getAttribute("aria-label")??"":heading.hasAttribute("aria-labelledby")?this.headingText=composedAccessibilityText(heading,{ancestorBoundary:this}).trim()||void 0:this.headingText=composedAccessibilityText(Array.from(heading.childNodes),{ancestorBoundary:heading}).trim()||void 0,this.hasLabelSlot=children.some(el=>el.getAttribute("slot")==="label"),this.hasHeaderActionsSlot=children.some(el=>el.getAttribute("slot")==="header-actions")}show(){if(this.coalesceOpenRequest(!0)||this._open)return Promise.resolve();this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);return this.finishOpenRequest(),prevented||superseded?(this.syncOpenAttribute(),Promise.resolve()):(this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show"))}hide(){return this.close("api")}close(reason="api"){return this.closeFrom(reason,this)}closeFrom(reason,source){return this.coalesceOpenRequest(!1)||!this._open?Promise.resolve():(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):this.emit("lr-close",reason,{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)?(this.finishOpenRequest(),this.syncOpenAttribute(),Promise.resolve()):(this.finishOpenRequest(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")))}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,next&&(this.initialFocusDecision=void 0),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}panelAnimationName(showing){return showing?"dialog.show":"dialog.hide"}overlayAnimationName(showing){return showing?"dialog.overlay.show":"dialog.overlay.hide"}panelAnimationSpec(showing){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}overlayAnimationSpec(showing){return{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?"--show-duration":"--hide-duration","--lr-dialog-backdrop-duration","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const root=this.renderRoot,panel=root.querySelector('[part~="panel"]'),backdrop=root.querySelector('[part~="backdrop"]'),showing=event==="lr-after-show",animations=[panel?animateRegistered(this,panel,this.panelAnimationName(showing),this.effectiveDirection,this.panelAnimationSpec(showing)):void 0,this.modalSurface&&backdrop?animateRegistered(this,backdrop,this.overlayAnimationName(showing),this.effectiveDirection,this.overlayAnimationSpec(showing)):void 0].filter(animation=>animation!==void 0);if(this.transitionAnimations=animations,await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return;this.cancelTransitionAnimations()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.leaveTopLayer(),this.flushPendingScrollLockRelease()),this.emit(event)}}enterTopLayer(){if(!(!this.isConnected||typeof this.showPopover!="function")){this.getAttribute("popover")!=="manual"&&this.setAttribute("popover","manual");try{this.isTopLayer()||this.showPopover()}catch{}}}leaveTopLayer(){if(typeof this.hidePopover=="function")try{this.isTopLayer()&&this.hidePopover()}catch{}}isTopLayer(){try{return this.matches(":popover-open")}catch{return!1}}requestClose(source,reason,sourceElement){this.emit("lr-request-close",{source},{cancelable:!0}).defaultPrevented||this.closeFrom(reason,sourceElement)}focusInitial(){this.overlay?.focusInitial()}activateOverlay(){!this.isConnected||this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.requestClose("keyboard","escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part~="backdrop"]')??this;this.requestClose("overlay","backdrop",backdrop)},preferredInitialFocus:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]'),body=this.renderRoot.querySelector('[part="body"]'),stops=body?collectFocusableElements(body):[];return stops.find(stop=>stop!==body)??stops[0]??panel},beforeInitialFocus:()=>(this.initialFocusDecision===void 0&&(this.initialFocusDecision=!this.emit("lr-initial-focus",null,{cancelable:!0}).defaultPrevented),this.initialFocusDecision),lockScroll:!0,suspendWhenUnrendered:!0}),this.externalModalDepth>0&&this.overlay.suspend())}deactivateOverlay(options){const overlay=this.overlay;return this.overlay=void 0,overlay?.deactivate(options)}render(){const suppressHeader=this.withoutHeader||this.noHeader,renderHeading=!suppressHeader&&!this.headingText&&(this.hasLabelSlot||(this.label??"").length>0||!!this.heading),hasHostName=this.hostAriaLabel!==null,explicitName=hasHostName?this.hostAriaLabel:this.accessibleLabel||this.headingText,hasExplicitName=hasHostName||!!explicitName,useHeadingForName=!hasExplicitName&&renderHeading,showHeader=!suppressHeader&&(renderHeading||this.hasHeaderActionsSlot||this.closable),headingLevel=resolveHeadingLevel(this.headingLevel);return html`
2
2
  <div part="base">
3
3
  <div part="backdrop overlay" @click=${this.onBackdropClick}></div>
4
4
  <div
@@ -31,11 +31,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
31
31
  `:nothing}
32
32
  </div>
33
33
  `:nothing}
34
- <!-- tabindex keeps the scrolling body reachable: it is the element that overflows, so a
35
- dialog holding only prose, a table, or a rendered document would otherwise be
36
- mouse-scrollable with no keyboard way in at all. -1 keeps it out of the page's
37
- sequential order; the overlay manager promotes it to a stop only while it actually
38
- scrolls (see isOverflowingAndTabbable in internal/overlay-manager.ts). -->
34
+ <!-- The owner sets tabindex to 0 only while this scrolling surface actually overflows;
35
+ short bodies stay out of the sequential order. -->
39
36
  <div part="body" tabindex="-1">
40
37
  <slot @slotchange=${this.onDefaultSlotChange}></slot>
41
38
  </div>
@@ -120,10 +120,9 @@ empty:boolean;
120
120
  * it is set -- otherwise the initial state is announced twice, through the native role and
121
121
  * again through the shared sink. */
122
122
  announce:boolean;
123
- /** Placeholder for the query field. Empty string (the default) falls back to the localized
124
- * generic "Search" placeholder, which also becomes that field's accessible name (mirroring
125
- * `<lr-input>`'s own placeholder-as-label fallback). */
126
- placeholder:string;
123
+ /** Placeholder for the query field. When omitted, the localized generic "Search" placeholder
124
+ * is used; an explicit empty string intentionally suppresses that fallback. */
125
+ placeholder?:string;
127
126
  /** Accessible name for the inner search landmark when the host has no `aria-label`. Omitting it
128
127
  * falls back to the localized default; an explicit empty string clears it. */
129
128
  label?:string;