@aceshooting/lyra-ui 9.1.0 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +246 -0
- package/README.md +7 -0
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.styles.js +2 -2
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
- package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +2 -2
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/bar-chart.class.js +1 -1
- package/dist/components/charts/chart/bubble-chart.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/line-chart.class.js +1 -1
- package/dist/components/charts/chart/pie-chart.class.js +1 -1
- package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
- package/dist/components/charts/chart/radar-chart.class.js +1 -1
- package/dist/components/charts/chart/scatter-chart.class.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
- package/dist/components/conversation/chat-message/chat-message.styles.js +6 -0
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
- package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.styles.js +9 -0
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.js +1 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +3 -1
- package/dist/components/layout/card/card.styles.js +2 -2
- package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.styles.js +29 -9
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +2 -2
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +2 -0
- package/dist/components/overlays/callout/callout.styles.js +2 -2
- package/dist/components/overlays/kbd/kbd.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/popup/popup.class.js +2 -2
- package/dist/components/overlays/spinner/spinner.styles.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +11 -0
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +7 -0
- package/dist/internal/dev-mode-attribute-warning.js +1 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-attachment-trigger.md +2 -2
- package/llms/components/lr-heatmap.md +1 -1
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/llms/shared.md +13 -0
- package/llms-full.txt +16 -3
- package/package.json +3 -3
- package/vscode-html-data.json +1 -1
- package/web-types.json +2 -2
|
@@ -171,21 +171,31 @@ import{css}from"lit";const styles=css`
|
|
|
171
171
|
outline-offset: var(--lr-focus-ring-offset);
|
|
172
172
|
}
|
|
173
173
|
/* The divider adjacent to a rail/floating-collapsed pane (see multi-split.class.ts's
|
|
174
|
-
isDividerDisabled()) —
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
174
|
+
isDividerDisabled()) — the collapsing panel's own live flex/order/inline-size
|
|
175
|
+
are set inline by updated() (see the floating rule below for why); this only
|
|
176
|
+
covers the divider's own drag/hover affordance and the floating panel's
|
|
177
|
+
elevation, which read more naturally as stylesheet rules than one-off inline
|
|
178
|
+
styles. */
|
|
179
179
|
[part="divider"][aria-disabled="true"] {
|
|
180
180
|
cursor: default;
|
|
181
181
|
pointer-events: none;
|
|
182
182
|
}
|
|
183
|
-
/* The 'floating' collapse state's overlay "card" look
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
183
|
+
/* The 'floating' collapse state's overlay "card" look. inline-size (and
|
|
184
|
+
flex/order) stay inline, set by multi-split.class.ts's updated(): it's the
|
|
185
|
+
panel's own live, draggable sizes[i] percent -- the exact value it renders at
|
|
186
|
+
in the 'wide' state too, by design (see updated()'s comment), so there's no
|
|
187
|
+
visual size jump the moment it un-floats. position/inset-block/the
|
|
188
|
+
inset-inline-* edge below are a fixed, config-driven default -- always the
|
|
189
|
+
same literal values, never per-render computed data -- so they live here
|
|
190
|
+
instead, as ordinary stylesheet rules a consumer's own CSS can override at
|
|
191
|
+
normal specificity, no !important fight required. (Only inline-size is
|
|
192
|
+
genuinely live; a consumer wanting a different floating width should set
|
|
193
|
+
.sizes instead of overriding this rule -- overriding it here would fight
|
|
194
|
+
the live sync back on every drag/resize.) z-index is above [part="backdrop"]
|
|
187
195
|
(below), so the drawer renders on top of its own scrim. */
|
|
188
196
|
::slotted([data-collapse-state="floating"]) {
|
|
197
|
+
position: absolute;
|
|
198
|
+
inset-block: 0;
|
|
189
199
|
z-index: var(--lr-layer-content);
|
|
190
200
|
background: var(--lr-color-surface);
|
|
191
201
|
border-radius: var(--lr-radius);
|
|
@@ -193,6 +203,16 @@ import{css}from"lit";const styles=css`
|
|
|
193
203
|
an anchored popup, so it takes the modal tier. */
|
|
194
204
|
box-shadow: var(--lr-shadow-l);
|
|
195
205
|
}
|
|
206
|
+
/* Which edge the floating drawer anchors to mirrors collapse ('start'/'end'
|
|
207
|
+
LOGICAL positions -- see the collapse property doc), already reflected onto
|
|
208
|
+
the host, so it needs no separate per-panel marker. Exactly one of these two
|
|
209
|
+
ever matches at a time (collapse is never both). */
|
|
210
|
+
:host([collapse="start"]) ::slotted([data-collapse-state="floating"]) {
|
|
211
|
+
inset-inline-start: 0;
|
|
212
|
+
}
|
|
213
|
+
:host([collapse="end"]) ::slotted([data-collapse-state="floating"]) {
|
|
214
|
+
inset-inline-end: 0;
|
|
215
|
+
}
|
|
196
216
|
/* The 'floating' drawer's scrim -- only rendered while collapseState is
|
|
197
217
|
'floating' and open (see multi-split.class.ts's render()). Scoped to [part="base"]
|
|
198
218
|
(position: absolute against its position: relative ancestor) rather than
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
11
11
|
aria-hidden="true"
|
|
12
12
|
focusable="false"
|
|
13
13
|
><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
|
|
14
|
-
`}function statusText(status,uploadingText,uploadFailedLabel){return status==="error"?uploadFailedLabel:status==="uploading"?uploadingText:""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments),this.name="",this.attachmentId="",this.mimeType="",this.thumbnailSrc="",this.previewSrc="",this.previewable=!0,this.status="pending",this.progress=0,this.removable=!0,this.compact=!1,this.thumbnailOnly=!1,this.fallbackId=nextId("attachment-chip"),this.onRemoveClick=()=>{this.emit("lr-remove",{attachmentId:this.resolvedId})},this.onRetryClick=()=>{this.emit("lr-retry",{attachmentId:this.resolvedId})},this.onPreviewClick=()=>{this.effectivePreviewSrc&&this.emit("lr-preview-request",{attachmentId:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc},{cancelable:!0})}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get bytes(){return this._bytes}set bytes(value){const old=this._bytes;this._bytes=typeof value=="number"&&Number.isFinite(value)&&value>=0?finiteRange(value,0,0):void 0,this.requestUpdate("bytes",old)}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?Number.isFinite(this.file.size)&&this.file.size>=0?finiteRange(this.file.size,0,0):void 0:this.bytes}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){return this.attachmentId.trim().length>0?this.attachmentId:this.file?`${this.file.name}:${this.file.size}:${this.file.lastModified}`:this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}get effectiveStatus(){return this.status==="uploading"||this.status==="error"||this.status==="success"?this.status:"pending"}ensureObjectUrl(file){return this.objectUrlFile===file&&this.objectUrl?this.objectUrl:(this.revokeObjectUrl(),this.objectUrl=URL.createObjectURL(file),this.objectUrlFile=file,this.objectUrl)}revokeObjectUrl(){this.objectUrl&&URL.revokeObjectURL(this.objectUrl),this.objectUrl=void 0,this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.requestUpdate()}adoptedCallback(){super.adoptedCallback(),this.releaseAnnouncementSink(),this.syncAnnouncementSink()}syncAnnouncementSink(){this.isConnected&&this.sink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.sink?.release(),this.sink=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("status")&&this.status!==this.effectiveStatus&&(this.status=this.effectiveStatus),this.hasUpdated&&changed.has("status")&&this.status==="error"&&this.sink?.announce(this.localizedUploadFailedLabel),this.isConnected&&this.file&&(this.file.type.startsWith("image/")||this.previewable)?this.ensureObjectUrl(this.file):this.objectUrlFile&&this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback(),this.revokeObjectUrl(),this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.uploadFailedLabel??this.localize("attachmentUploadFailed")}renderThumbnail(){if(this.file){const fileImageSrc=this.objectUrl?safeMediaSrc(this.objectUrl):null;return this.effectiveMimeType.startsWith("image/")?fileImageSrc?html`<img src=${fileImageSrc} alt="" />`:html`${fileIcon()}`:html`${fileIcon()}`}const thumbnailSrc=safeMediaSrc(this.thumbnailSrc);return thumbnailSrc?html`<img src=${thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName,untitledLabel=this.untitledLabel??this.localize("attachmentUntitledFile"),displayName=name||untitledLabel,sizeText=this.effectiveSize!==void 0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"",uploadFailedLabel=this.localizedUploadFailedLabel,progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress)),uploadingText=this.uploadingLabel!==void 0?this.uploadingLabel:this.hasNumericProgress?this.localize("attachmentUploadingProgress",void 0,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate"),uploadingWithContext=this.uploadingLabel??this.localize("attachmentUploadingWithContext",void 0,{label:displayName}),retryWithContext=this.retryLabel??this.localize("attachmentRetryWithContext",void 0,{label:displayName}),removeWithContext=this.removeLabel??this.localize("removeWithContext",void 0,{label:displayName}),status=this.effectiveStatus,text=statusText(status,uploadingText,uploadFailedLabel),uploading=status==="uploading";return html`
|
|
14
|
+
`}function statusText(status,uploadingText,uploadFailedLabel){return status==="error"?uploadFailedLabel:status==="uploading"?uploadingText:""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments),this.name="",this.attachmentId="",this.mimeType="",this.thumbnailSrc="",this.previewSrc="",this.previewable=!0,this.status="pending",this.progress=0,this.removable=!0,this.compact=!1,this.thumbnailOnly=!1,this.fallbackId=nextId("attachment-chip"),this.onRemoveClick=()=>{this.emit("lr-remove",{attachmentId:this.resolvedId})},this.onRetryClick=()=>{this.emit("lr-retry",{attachmentId:this.resolvedId})},this.onPreviewClick=()=>{this.effectivePreviewSrc&&this.emit("lr-preview-request",{attachmentId:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc},{cancelable:!0})}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get bytes(){return this._bytes}set bytes(value){const old=this._bytes;this._bytes=typeof value=="number"&&Number.isFinite(value)&&value>=0?finiteRange(value,0,0):void 0,this.requestUpdate("bytes",old)}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?Number.isFinite(this.file.size)&&this.file.size>=0?finiteRange(this.file.size,0,0):void 0:this.bytes}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){return this.attachmentId.trim().length>0?this.attachmentId:this.file?`${this.file.name}:${this.file.size}:${this.file.lastModified}`:this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}get effectiveStatus(){return this.status==="uploading"||this.status==="error"||this.status==="success"?this.status:"pending"}ensureObjectUrl(file){return this.objectUrlFile===file&&this.objectUrl?this.objectUrl:(this.revokeObjectUrl(),this.objectUrl=URL.createObjectURL(file),this.objectUrlFile=file,this.objectUrl)}revokeObjectUrl(){this.objectUrl&&URL.revokeObjectURL(this.objectUrl),this.objectUrl=void 0,this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.requestUpdate()}adoptedCallback(){super.adoptedCallback(),this.releaseAnnouncementSink(),this.syncAnnouncementSink()}syncAnnouncementSink(){this.isConnected&&this.sink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.sink?.release(),this.sink=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("status")&&this.status!==this.effectiveStatus&&(this.status=this.effectiveStatus),this.hasUpdated&&changed.has("status")&&this.status==="error"&&this.sink?.announce(this.localizedUploadFailedLabel),this.isConnected&&this.file&&(this.file.type.startsWith("image/")||this.previewable)?this.ensureObjectUrl(this.file):this.objectUrlFile&&this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback(),this.revokeObjectUrl(),this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.uploadFailedLabel??this.localize("attachmentUploadFailed")}renderThumbnail(){if(this.file){const fileImageSrc=this.objectUrl?safeMediaSrc(this.objectUrl):null;return this.effectiveMimeType.startsWith("image/")?fileImageSrc?html`<img src=${fileImageSrc} alt="" />`:html`${fileIcon()}`:html`${fileIcon()}`}const thumbnailSrc=safeMediaSrc(this.thumbnailSrc);return thumbnailSrc?html`<img src=${thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName,untitledLabel=this.untitledLabel??this.localize("attachmentUntitledFile"),displayName=name||untitledLabel,sizeText=this.effectiveSize!==void 0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"",uploadFailedLabel=this.localizedUploadFailedLabel,progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress)),uploadingText=this.uploadingLabel!==void 0?this.uploadingLabel:this.hasNumericProgress?this.localize("attachmentUploadingProgress",void 0,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate"),uploadingWithContext=this.uploadingLabel??this.localize("attachmentUploadingWithContext",void 0,{label:displayName}),retryWithContext=this.retryLabel??this.localize("attachmentRetryWithContext",void 0,{label:displayName}),removeWithContext=this.removeLabel??this.localize("removeWithContext",void 0,{label:displayName}),status=this.effectiveStatus,text=statusText(status,uploadingText,uploadFailedLabel),uploading=status==="uploading";return html`
|
|
15
15
|
<div part="base">
|
|
16
16
|
<span part="thumbnail" aria-hidden="true"
|
|
17
17
|
>${this.renderThumbnail()}</span
|
|
@@ -18,7 +18,7 @@ export interface LyraAttachmentTriggerEventMap {
|
|
|
18
18
|
}
|
|
19
19
|
/**
|
|
20
20
|
* `<lr-attachment-trigger>` — a compact attach affordance designed for a
|
|
21
|
-
* chat composer's
|
|
21
|
+
* chat composer's start slot (see `<lr-chat-composer>`'s own `start`
|
|
22
22
|
* slot, which this drops straight into, though this component has no code
|
|
23
23
|
* dependency on it). Its shape adapts to how many attachment `capabilities`
|
|
24
24
|
* are configured:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -25,7 +25,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
25
25
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
26
26
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
27
27
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
28
|
-
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]);function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,4);for(let index=0;index<length;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
28
|
+
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]);function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,4);for(let index=0;index<length;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
29
29
|
<input
|
|
30
30
|
part="hidden-input"
|
|
31
31
|
type="file"
|
|
@@ -3,7 +3,7 @@ import{css}from"lit";const styles=css`
|
|
|
3
3
|
visible/clickable surface is entirely the rendered button (or, in the
|
|
4
4
|
multi-capability case, lr-dropdown's trigger wrapper
|
|
5
5
|
around that same button), so this host never contributes a stray box a
|
|
6
|
-
composer's
|
|
6
|
+
composer's start slot would otherwise have to fight with margin/
|
|
7
7
|
inline-block quirks to line up against the textarea. */
|
|
8
8
|
:host {
|
|
9
9
|
display: contents;
|
|
@@ -35,7 +35,7 @@ import{css}from"lit";const styles=css`
|
|
|
35
35
|
box-sizing: border-box;
|
|
36
36
|
/* Compact per the class doc -- capped well below the library's general
|
|
37
37
|
--lr-icon-button-size (meant for a standalone icon-only button) so
|
|
38
|
-
this sits comfortably inside a composer's
|
|
38
|
+
this sits comfortably inside a composer's start slot alongside a
|
|
39
39
|
textarea, matching lr-combobox's clear-button / lr-select's
|
|
40
40
|
toggle sizing convention. */
|
|
41
41
|
min-inline-size: min(var(--lr-icon-button-size), var(--lr-size-1-75rem));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}willUpdate(changed){super.willUpdate(changed)}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:renderedLabel,size:sizeText}):renderedLabel,accessibleLabel=hostAriaLabel(this)??fallbackLabel,descriptionId=metadata.provenance==="consumer"&&metadata.description?"metadata-description":void 0;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}willUpdate(changed){super.willUpdate(changed)}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:renderedLabel,size:sizeText}):renderedLabel,accessibleLabel=hostAriaLabel(this)??fallbackLabel,descriptionId=metadata.provenance==="consumer"&&metadata.description?"metadata-description":void 0;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="base"
|
|
4
4
|
role=${this.decorative?"presentation":"img"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -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}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():void 0;if(this.language)return languageToCountry(this.language)}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading"))}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
|
|
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}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():void 0;if(this.language)return languageToCountry(this.language)}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading"))}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
|
|
2
2
|
${state2.status==="loading"?html`
|
|
3
3
|
<span class="sr-only">${this.localize("loading")}</span>
|
|
4
4
|
<lr-skeleton shape="rect" .announce=${!1}></lr-skeleton>
|
|
@@ -193,6 +193,8 @@ import{css}from"lit";const styles=css`
|
|
|
193
193
|
flex: 0 0 auto;
|
|
194
194
|
margin: 0;
|
|
195
195
|
max-inline-size: 100%;
|
|
196
|
+
max-block-size: var(--lr-size-8rem);
|
|
197
|
+
overflow-y: auto;
|
|
196
198
|
align-self: center;
|
|
197
199
|
padding: var(--lr-space-xs) var(--lr-space-s);
|
|
198
200
|
border-radius: var(--lr-radius);
|
|
@@ -67,8 +67,8 @@ import{css}from"lit";const styles=css`
|
|
|
67
67
|
[part='icon'] ::slotted(*) { max-inline-size: 100%; }
|
|
68
68
|
[part='icon'][hidden], [part='close-button'][hidden] { display: none; }
|
|
69
69
|
[part='heading'] { margin-block-end: var(--lr-space-xs); font-weight: var(--lr-font-weight-semibold); }
|
|
70
|
-
[part='content'] { grid-column: 2; min-inline-size: 0; overflow-wrap:
|
|
71
|
-
[part='message'] { min-inline-size: 0; overflow-wrap:
|
|
70
|
+
[part='content'] { grid-column: 2; min-inline-size: 0; overflow-wrap: break-word; }
|
|
71
|
+
[part='message'] { min-inline-size: 0; overflow-wrap: break-word; }
|
|
72
72
|
/* The interactive hit target meets the shared minimum tappable size (--lr-icon-button-size)
|
|
73
73
|
in both the default panel and the compact [inline] variant below -- the *visible* "×" glyph
|
|
74
74
|
is what shrinks for [inline] instead, rendered on the separate [part='close-icon'] child and
|
|
@@ -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{detectPlatform}from"../../../internal/platform.js";import{hasRealContent,hostAriaLabel}from"../../../internal/a11y.js";import{styles}from"./kbd.styles.js";import{LYRA_DEFAULT_kbdAltWord,LYRA_DEFAULT_kbdArrowDownWord,LYRA_DEFAULT_kbdArrowLeftWord,LYRA_DEFAULT_kbdArrowRightWord,LYRA_DEFAULT_kbdArrowUpWord,LYRA_DEFAULT_kbdBackspaceWord,LYRA_DEFAULT_kbdCommandWord,LYRA_DEFAULT_kbdControlVisual,LYRA_DEFAULT_kbdControlWord,LYRA_DEFAULT_kbdDeleteVisual,LYRA_DEFAULT_kbdDeleteWord,LYRA_DEFAULT_kbdEndWord,LYRA_DEFAULT_kbdEnterWord,LYRA_DEFAULT_kbdEscapeVisual,LYRA_DEFAULT_kbdEscapeWord,LYRA_DEFAULT_kbdHomeWord,LYRA_DEFAULT_kbdMinusWord,LYRA_DEFAULT_kbdOptionWord,LYRA_DEFAULT_kbdPageDownVisual,LYRA_DEFAULT_kbdPageDownWord,LYRA_DEFAULT_kbdPageUpVisual,LYRA_DEFAULT_kbdPageUpWord,LYRA_DEFAULT_kbdPlusWord,LYRA_DEFAULT_kbdShiftWord,LYRA_DEFAULT_kbdSpaceWord,LYRA_DEFAULT_kbdTabWord}from"../../../internal/default-strings.generated.js";const NAMED_KEY_LABELS={enter:{visual:"\u21B5",word:"Enter",wordKey:"kbdEnterWord"},esc:{visual:"Esc",visualKey:"kbdEscapeVisual",word:"Escape",wordKey:"kbdEscapeWord"},escape:{visual:"Esc",visualKey:"kbdEscapeVisual",word:"Escape",wordKey:"kbdEscapeWord"},tab:{visual:"Tab",visualKey:"kbdTabWord",word:"Tab",wordKey:"kbdTabWord"},space:{visual:"Space",visualKey:"kbdSpaceWord",word:"Space",wordKey:"kbdSpaceWord"},backspace:{visual:"\u232B",word:"Backspace",wordKey:"kbdBackspaceWord"},delete:{visual:"Del",visualKey:"kbdDeleteVisual",word:"Delete",wordKey:"kbdDeleteWord"},home:{visual:"Home",visualKey:"kbdHomeWord",word:"Home",wordKey:"kbdHomeWord"},end:{visual:"End",visualKey:"kbdEndWord",word:"End",wordKey:"kbdEndWord"},pageup:{visual:"PgUp",visualKey:"kbdPageUpVisual",word:"Page Up",wordKey:"kbdPageUpWord"},pagedown:{visual:"PgDn",visualKey:"kbdPageDownVisual",word:"Page Down",wordKey:"kbdPageDownWord"},arrowup:{visual:"\u2191",word:"Arrow Up",wordKey:"kbdArrowUpWord"},arrowdown:{visual:"\u2193",word:"Arrow Down",wordKey:"kbdArrowDownWord"},arrowleft:{visual:"\u2190",word:"Arrow Left",wordKey:"kbdArrowLeftWord"},arrowright:{visual:"\u2192",word:"Arrow Right",wordKey:"kbdArrowRightWord"},plus:{visual:"+",word:"Plus",wordKey:"kbdPlusWord"},minus:{visual:"\u2212",word:"Minus",wordKey:"kbdMinusWord"}};function shortcutTokenLabel(rawToken,isMac,localize){const token=rawToken.trim(),lower=token.toLowerCase(),resolve=(key,fallback)=>key&&localize?localize(key,fallback):fallback;if(lower==="mod")return isMac?{visual:"\u2318",word:resolve("kbdCommandWord","Command")}:{visual:resolve("kbdControlVisual","Ctrl"),word:resolve("kbdControlWord","Control")};if(lower==="ctrl"||lower==="control")return{visual:resolve("kbdControlVisual","Ctrl"),word:resolve("kbdControlWord","Control")};if(lower==="alt")return isMac?{visual:"\u2325",word:resolve("kbdOptionWord","Option")}:{visual:resolve("kbdAltWord","Alt"),word:resolve("kbdAltWord","Alt")};if(lower==="shift")return{visual:"\u21E7",word:resolve("kbdShiftWord","Shift")};const named=NAMED_KEY_LABELS[lower];if(named)return{visual:resolve(named.visualKey,named.visual),word:resolve(named.wordKey,named.word)};if(token.length===1){const upper=token.toUpperCase();return{visual:upper,word:upper}}return{visual:token,word:token}}function parseShortcut(keys,isMac,localize){return keys.split("+").map(t=>t.trim()).filter(t=>t.length>0).map(t=>shortcutTokenLabel(t,isMac,localize))}const AUTO_PLATFORM=detectPlatform();function isEffectivePlatform(value){return value==="mac"||value==="windows"||value==="linux"}class LyraKbd extends LyraElement{constructor(){super(...arguments),this.keys="",this.platform="auto",this.autoPlatform=AUTO_PLATFORM,this.hasCustomContent=!1,this.onSlotChange=e=>{this.hasCustomContent=hasRealContent(e.target.assignedNodes({flatten:!0}))}}static{this.defaultStrings={...super.defaultStrings,kbdAltWord:LYRA_DEFAULT_kbdAltWord,kbdArrowDownWord:LYRA_DEFAULT_kbdArrowDownWord,kbdArrowLeftWord:LYRA_DEFAULT_kbdArrowLeftWord,kbdArrowRightWord:LYRA_DEFAULT_kbdArrowRightWord,kbdArrowUpWord:LYRA_DEFAULT_kbdArrowUpWord,kbdBackspaceWord:LYRA_DEFAULT_kbdBackspaceWord,kbdCommandWord:LYRA_DEFAULT_kbdCommandWord,kbdControlVisual:LYRA_DEFAULT_kbdControlVisual,kbdControlWord:LYRA_DEFAULT_kbdControlWord,kbdDeleteVisual:LYRA_DEFAULT_kbdDeleteVisual,kbdDeleteWord:LYRA_DEFAULT_kbdDeleteWord,kbdEndWord:LYRA_DEFAULT_kbdEndWord,kbdEnterWord:LYRA_DEFAULT_kbdEnterWord,kbdEscapeVisual:LYRA_DEFAULT_kbdEscapeVisual,kbdEscapeWord:LYRA_DEFAULT_kbdEscapeWord,kbdHomeWord:LYRA_DEFAULT_kbdHomeWord,kbdMinusWord:LYRA_DEFAULT_kbdMinusWord,kbdOptionWord:LYRA_DEFAULT_kbdOptionWord,kbdPageDownVisual:LYRA_DEFAULT_kbdPageDownVisual,kbdPageDownWord:LYRA_DEFAULT_kbdPageDownWord,kbdPageUpVisual:LYRA_DEFAULT_kbdPageUpVisual,kbdPageUpWord:LYRA_DEFAULT_kbdPageUpWord,kbdPlusWord:LYRA_DEFAULT_kbdPlusWord,kbdShiftWord:LYRA_DEFAULT_kbdShiftWord,kbdSpaceWord:LYRA_DEFAULT_kbdSpaceWord,kbdTabWord:LYRA_DEFAULT_kbdTabWord}}static{this.styles=[LyraElement.styles,styles]}get effectivePlatform(){return this.platform==="auto"?this.autoPlatform:this.platform}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated&&this.platform==="auto"){const serialized=this.renderRoot?.querySelector("[data-effective-platform]")?.getAttribute("data-effective-platform")??null;isEffectivePlatform(serialized)&&(this.autoPlatform=serialized)}this.seedFirstRenderState(()=>{this.hasCustomContent=hasRealContent(this.childNodes)})}render(){const explicitLabel=hostAriaLabel(this),tokens=this.hasCustomContent?[]:parseShortcut(this.keys,this.effectivePlatform==="mac",key=>this.localize(key)),ariaLabel=explicitLabel??tokens.map(t=>t.word).join("+"),hasAriaLabel=explicitLabel!==null||tokens.length>0;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{detectPlatform}from"../../../internal/platform.js";import{hasRealContent,hostAriaLabel}from"../../../internal/a11y.js";import{styles}from"./kbd.styles.js";import{LYRA_DEFAULT_kbdAltWord,LYRA_DEFAULT_kbdArrowDownWord,LYRA_DEFAULT_kbdArrowLeftWord,LYRA_DEFAULT_kbdArrowRightWord,LYRA_DEFAULT_kbdArrowUpWord,LYRA_DEFAULT_kbdBackspaceWord,LYRA_DEFAULT_kbdCommandWord,LYRA_DEFAULT_kbdControlVisual,LYRA_DEFAULT_kbdControlWord,LYRA_DEFAULT_kbdDeleteVisual,LYRA_DEFAULT_kbdDeleteWord,LYRA_DEFAULT_kbdEndWord,LYRA_DEFAULT_kbdEnterWord,LYRA_DEFAULT_kbdEscapeVisual,LYRA_DEFAULT_kbdEscapeWord,LYRA_DEFAULT_kbdHomeWord,LYRA_DEFAULT_kbdMinusWord,LYRA_DEFAULT_kbdOptionWord,LYRA_DEFAULT_kbdPageDownVisual,LYRA_DEFAULT_kbdPageDownWord,LYRA_DEFAULT_kbdPageUpVisual,LYRA_DEFAULT_kbdPageUpWord,LYRA_DEFAULT_kbdPlusWord,LYRA_DEFAULT_kbdShiftWord,LYRA_DEFAULT_kbdSpaceWord,LYRA_DEFAULT_kbdTabWord,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const NAMED_KEY_LABELS={enter:{visual:"\u21B5",word:"Enter",wordKey:"kbdEnterWord"},esc:{visual:"Esc",visualKey:"kbdEscapeVisual",word:"Escape",wordKey:"kbdEscapeWord"},escape:{visual:"Esc",visualKey:"kbdEscapeVisual",word:"Escape",wordKey:"kbdEscapeWord"},tab:{visual:"Tab",visualKey:"kbdTabWord",word:"Tab",wordKey:"kbdTabWord"},space:{visual:"Space",visualKey:"kbdSpaceWord",word:"Space",wordKey:"kbdSpaceWord"},backspace:{visual:"\u232B",word:"Backspace",wordKey:"kbdBackspaceWord"},delete:{visual:"Del",visualKey:"kbdDeleteVisual",word:"Delete",wordKey:"kbdDeleteWord"},home:{visual:"Home",visualKey:"kbdHomeWord",word:"Home",wordKey:"kbdHomeWord"},end:{visual:"End",visualKey:"kbdEndWord",word:"End",wordKey:"kbdEndWord"},pageup:{visual:"PgUp",visualKey:"kbdPageUpVisual",word:"Page Up",wordKey:"kbdPageUpWord"},pagedown:{visual:"PgDn",visualKey:"kbdPageDownVisual",word:"Page Down",wordKey:"kbdPageDownWord"},arrowup:{visual:"\u2191",word:"Arrow Up",wordKey:"kbdArrowUpWord"},arrowdown:{visual:"\u2193",word:"Arrow Down",wordKey:"kbdArrowDownWord"},arrowleft:{visual:"\u2190",word:"Arrow Left",wordKey:"kbdArrowLeftWord"},arrowright:{visual:"\u2192",word:"Arrow Right",wordKey:"kbdArrowRightWord"},plus:{visual:"+",word:"Plus",wordKey:"kbdPlusWord"},minus:{visual:"\u2212",word:"Minus",wordKey:"kbdMinusWord"}};function shortcutTokenLabel(rawToken,isMac,localize){const token=rawToken.trim(),lower=token.toLowerCase(),resolve=(key,fallback)=>key&&localize?localize(key,fallback):fallback;if(lower==="mod")return isMac?{visual:"\u2318",word:resolve("kbdCommandWord","Command")}:{visual:resolve("kbdControlVisual","Ctrl"),word:resolve("kbdControlWord","Control")};if(lower==="ctrl"||lower==="control")return{visual:resolve("kbdControlVisual","Ctrl"),word:resolve("kbdControlWord","Control")};if(lower==="alt")return isMac?{visual:"\u2325",word:resolve("kbdOptionWord","Option")}:{visual:resolve("kbdAltWord","Alt"),word:resolve("kbdAltWord","Alt")};if(lower==="shift")return{visual:"\u21E7",word:resolve("kbdShiftWord","Shift")};const named=NAMED_KEY_LABELS[lower];if(named)return{visual:resolve(named.visualKey,named.visual),word:resolve(named.wordKey,named.word)};if(token.length===1){const upper=token.toUpperCase();return{visual:upper,word:upper}}return{visual:token,word:token}}function parseShortcut(keys,isMac,localize){return keys.split("+").map(t=>t.trim()).filter(t=>t.length>0).map(t=>shortcutTokenLabel(t,isMac,localize))}const AUTO_PLATFORM=detectPlatform();function isEffectivePlatform(value){return value==="mac"||value==="windows"||value==="linux"}class LyraKbd extends LyraElement{constructor(){super(...arguments),this.keys="",this.platform="auto",this.autoPlatform=AUTO_PLATFORM,this.hasCustomContent=!1,this.onSlotChange=e=>{this.hasCustomContent=hasRealContent(e.target.assignedNodes({flatten:!0}))}}static{this.defaultStrings={...super.defaultStrings,kbdAltWord:LYRA_DEFAULT_kbdAltWord,kbdArrowDownWord:LYRA_DEFAULT_kbdArrowDownWord,kbdArrowLeftWord:LYRA_DEFAULT_kbdArrowLeftWord,kbdArrowRightWord:LYRA_DEFAULT_kbdArrowRightWord,kbdArrowUpWord:LYRA_DEFAULT_kbdArrowUpWord,kbdBackspaceWord:LYRA_DEFAULT_kbdBackspaceWord,kbdCommandWord:LYRA_DEFAULT_kbdCommandWord,kbdControlVisual:LYRA_DEFAULT_kbdControlVisual,kbdControlWord:LYRA_DEFAULT_kbdControlWord,kbdDeleteVisual:LYRA_DEFAULT_kbdDeleteVisual,kbdDeleteWord:LYRA_DEFAULT_kbdDeleteWord,kbdEndWord:LYRA_DEFAULT_kbdEndWord,kbdEnterWord:LYRA_DEFAULT_kbdEnterWord,kbdEscapeVisual:LYRA_DEFAULT_kbdEscapeVisual,kbdEscapeWord:LYRA_DEFAULT_kbdEscapeWord,kbdHomeWord:LYRA_DEFAULT_kbdHomeWord,kbdMinusWord:LYRA_DEFAULT_kbdMinusWord,kbdOptionWord:LYRA_DEFAULT_kbdOptionWord,kbdPageDownVisual:LYRA_DEFAULT_kbdPageDownVisual,kbdPageDownWord:LYRA_DEFAULT_kbdPageDownWord,kbdPageUpVisual:LYRA_DEFAULT_kbdPageUpVisual,kbdPageUpWord:LYRA_DEFAULT_kbdPageUpWord,kbdPlusWord:LYRA_DEFAULT_kbdPlusWord,kbdShiftWord:LYRA_DEFAULT_kbdShiftWord,kbdSpaceWord:LYRA_DEFAULT_kbdSpaceWord,kbdTabWord:LYRA_DEFAULT_kbdTabWord,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get effectivePlatform(){return this.platform==="auto"?this.autoPlatform:this.platform}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated&&this.platform==="auto"){const serialized=this.renderRoot?.querySelector("[data-effective-platform]")?.getAttribute("data-effective-platform")??null;isEffectivePlatform(serialized)&&(this.autoPlatform=serialized)}this.seedFirstRenderState(()=>{this.hasCustomContent=hasRealContent(this.childNodes)})}render(){const explicitLabel=hostAriaLabel(this),tokens=this.hasCustomContent?[]:parseShortcut(this.keys,this.effectivePlatform==="mac",key=>this.localize(key)),ariaLabel=explicitLabel??tokens.map(t=>t.word).join("+"),hasAriaLabel=explicitLabel!==null||tokens.length>0;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="base"
|
|
4
4
|
data-effective-platform=${this.effectivePlatform}
|
|
@@ -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{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;class LyraPopover extends LyraElement{constructor(){super(...arguments),this._open=!1,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.accessibleLabel="",this._popupRole="dialog",this.resolvedSide="bottom",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=typeof this.attachInternals=="function"?this.attachInternals():void 0,this.onTriggerSlotChange=event=>{const next=event.target.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())},this.onTriggerClick=()=>{this.virtualAnchor||(this.syncTriggerA11y(),this.open?this.hide():this.show())},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get popupRole(){return this._popupRole}set popupRole(next){if(next===this._popupRole)return;const old=this._popupRole;this._popupRole=next,this.requestUpdate("popupRole",old)}get defaultDistance(){return DEFAULT_DISTANCE}get positioningStrategy(){return"fixed"}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return this.arrow&&!this.withoutArrow}get canOpen(){return!0}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){return path.includes(this)}onPopupPositioned(){this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1})}updated(changed){super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),(changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole"))&&(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.positionPopup(),changed.has("open")&&(this.open?this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay()):(this.positionedAnchor=void 0,this.anchorPositioned=!1,this.stopLightDismiss(),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger())),this.isConnected&&this.syncTriggerA11y())}connectedCallback(){if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.positionPopup()}}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.trigger?.removeEventListener("click",this.onTriggerClick),this.releaseTriggerA11y(),this.trigger=void 0,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.trigger){this.syncTriggerA11y();return}if(this.trigger?.removeEventListener("click",this.onTriggerClick),this.trigger=next,this.trigger&&this.trigger!==this.slottedTrigger&&this.trigger.addEventListener("click",this.onTriggerClick),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger,modal:!1,trapFocus:!1}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.trigger})}positionPopup(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1,popup?.setAttribute("data-hidden","");return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1,popup.setAttribute("data-hidden","")),this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.positioningStrategy,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),onPlaced:({placement,arrow})=>{const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0,this.open&&this.resolveAnchor()===anchor&&(popup.removeAttribute("data-hidden"),becamePositioned&&this.onPopupPositioned());const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}syncTriggerA11y(){const trigger=this.trigger??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.trigger?resolveAccessibleTrigger(this.trigger):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;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{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;class LyraPopover extends LyraElement{constructor(){super(...arguments),this._open=!1,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.accessibleLabel="",this._popupRole="dialog",this.resolvedSide="bottom",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=typeof this.attachInternals=="function"?this.attachInternals():void 0,this.onTriggerSlotChange=event=>{const next=event.target.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())},this.onTriggerClick=()=>{this.virtualAnchor||(this.syncTriggerA11y(),this.open?this.hide():this.show())},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get popupRole(){return this._popupRole}set popupRole(next){if(next===this._popupRole)return;const old=this._popupRole;this._popupRole=next,this.requestUpdate("popupRole",old)}get defaultDistance(){return DEFAULT_DISTANCE}get positioningStrategy(){return"fixed"}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return this.arrow&&!this.withoutArrow}get canOpen(){return!0}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){return path.includes(this)}onPopupPositioned(){this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1})}updated(changed){super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),(changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole"))&&(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.positionPopup(),changed.has("open")&&(this.open?this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay()):(this.positionedAnchor=void 0,this.anchorPositioned=!1,this.stopLightDismiss(),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger())),this.isConnected&&this.syncTriggerA11y())}connectedCallback(){if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.positionPopup()}}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.trigger?.removeEventListener("click",this.onTriggerClick),this.releaseTriggerA11y(),this.trigger=void 0,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.trigger){this.syncTriggerA11y();return}if(this.trigger?.removeEventListener("click",this.onTriggerClick),this.trigger=next,this.trigger&&this.trigger!==this.slottedTrigger&&this.trigger.addEventListener("click",this.onTriggerClick),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger,modal:!1,trapFocus:!1}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.trigger})}positionPopup(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.positioningStrategy,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),onPlaced:({placement,arrow})=>{const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0,becamePositioned&&this.updateComplete.then(()=>{this.open&&this.resolveAnchor()===anchor&&this.onPopupPositioned()});const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}syncTriggerA11y(){const trigger=this.trigger??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.trigger?resolveAccessibleTrigger(this.trigger):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
|
|
2
2
|
<span part="trigger" @click=${this.onTriggerClick} @keydown=${this.onTriggerKeyDown}>
|
|
3
3
|
<slot name="trigger" @slotchange=${this.onTriggerSlotChange}></slot>
|
|
4
4
|
</span>
|
|
@@ -9,4 +9,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
9
9
|
<div part=${this.contentPartNames}>${this.renderPopupContent()}</div>
|
|
10
10
|
${this.rendersArrow?html`<span part="arrow popup__arrow arrow-${this.resolvedSide}"></span>`:nothing}
|
|
11
11
|
</div>
|
|
12
|
-
`}}__decorate([property({type:Boolean,reflect:!0})],LyraPopover.prototype,"open",null),__decorate([property({reflect:!0})],LyraPopover.prototype,"placement",void 0),__decorate([property({type:Number})],LyraPopover.prototype,"distance",void 0),__decorate([property({type:Number})],LyraPopover.prototype,"skidding",void 0),__decorate([property({reflect:!0,converter:omittedEmptyStringConverter})],LyraPopover.prototype,"for",null),__decorate([property({attribute:!1})],LyraPopover.prototype,"anchor",void 0),__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter,reflect:!0})],LyraPopover.prototype,"arrow",void 0),__decorate([property({type:Boolean,attribute:"without-arrow",reflect:!0})],LyraPopover.prototype,"withoutArrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraPopover.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraPopover.prototype,"arrowPadding",void 0),__decorate([property({attribute:"aria-label"})],LyraPopover.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"popup-role"})],LyraPopover.prototype,"popupRole",null),__decorate([state()],LyraPopover.prototype,"resolvedSide",void 0);export{LyraPopover};
|
|
12
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraPopover.prototype,"open",null),__decorate([property({reflect:!0})],LyraPopover.prototype,"placement",void 0),__decorate([property({type:Number})],LyraPopover.prototype,"distance",void 0),__decorate([property({type:Number})],LyraPopover.prototype,"skidding",void 0),__decorate([property({reflect:!0,converter:omittedEmptyStringConverter})],LyraPopover.prototype,"for",null),__decorate([property({attribute:!1})],LyraPopover.prototype,"anchor",void 0),__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter,reflect:!0})],LyraPopover.prototype,"arrow",void 0),__decorate([property({type:Boolean,attribute:"without-arrow",reflect:!0})],LyraPopover.prototype,"withoutArrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraPopover.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraPopover.prototype,"arrowPadding",void 0),__decorate([property({attribute:"aria-label"})],LyraPopover.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"popup-role"})],LyraPopover.prototype,"popupRole",null),__decorate([state()],LyraPopover.prototype,"resolvedSide",void 0),__decorate([state()],LyraPopover.prototype,"anchorPositioned",void 0);export{LyraPopover};
|