@aceshooting/lyra-ui 11.0.0 → 11.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +151 -0
- package/README.md +8 -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-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/span-waterfall/span-waterfall.class.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-param-form/tool-param-form.class.d.ts +1 -0
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- 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/lite-chart.class.d.ts +32 -0
- package/dist/components/charts/chart/lite-chart.class.js +17 -4
- package/dist/components/charts/chart/lite-chart.styles.js +29 -0
- 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-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +1 -0
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -0
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +36 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +19 -0
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-input.class.js +4 -2
- package/dist/components/forms/date-picker/date-picker.class.d.ts +30 -4
- package/dist/components/forms/date-picker/date-picker.class.js +4 -4
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.d.ts +1 -0
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +1 -0
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +1 -0
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +1 -0
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +1 -0
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
- package/dist/components/media/flag/flag-peer-bulk.js +1 -0
- package/dist/components/media/flag/flag.class.d.ts +28 -0
- package/dist/components/media/flag/flag.class.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/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.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/components/viewers/email-viewer/email-viewer.class.js +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/custom-elements-jsx.d.ts +5 -3
- package/dist/events.d.ts +7 -0
- package/dist/internal/canvas.js +1 -1
- package/dist/internal/form-associated.d.ts +1 -0
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/form-control-labels.js +1 -1
- 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/dist/lyra.d.ts +1 -1
- package/dist/svelte.d.ts +5 -3
- package/dist/theme.css +32 -0
- package/dist/vue.d.ts +5 -3
- package/llms/components/lr-agent-eval-dashboard.md +1 -1
- package/llms/components/lr-agent-workspace.md +1 -1
- package/llms/components/lr-box-plot.md +2 -2
- package/llms/components/lr-chart.md +1 -1
- package/llms/components/lr-chunk-inspector.md +1 -1
- package/llms/components/lr-combobox.md +3 -3
- package/llms/components/lr-date-input.md +22 -6
- package/llms/components/lr-date-picker.md +21 -5
- package/llms/components/lr-entity-dossier.md +1 -1
- package/llms/components/lr-eval-run.md +1 -1
- package/llms/components/lr-flag.md +24 -1
- package/llms/components/lr-grounding-summary.md +1 -1
- package/llms/components/lr-heatmap.md +18 -6
- package/llms/components/lr-lite-chart.md +19 -3
- package/llms/components/lr-map.md +2 -2
- package/llms/components/lr-memory-panel.md +1 -1
- package/llms/components/lr-option.md +3 -3
- package/llms/components/lr-popover.md +1 -1
- package/llms/components/lr-provenance-panel.md +1 -1
- package/llms/components/lr-rag-answer.md +1 -1
- package/llms/components/lr-rag-eval-dashboard.md +1 -1
- package/llms/components/lr-retrieval-results.md +1 -1
- package/llms/components/lr-retrieval-trace.md +1 -1
- package/llms/peers.md +10 -10
- package/llms/shared.md +19 -0
- package/llms/tokens.md +12 -0
- package/llms-full.txt +109 -21
- package/package.json +6 -6
- package/vscode-css-data.json +14 -0
- package/vscode-html-data.json +17 -3
- package/web-types.json +30 -4
|
@@ -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{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{isRtl}from"../../../internal/rtl.js";import{decimalPlaces,finiteAdd,finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.js";import{styles}from"./time-range.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{activeElementIn}from"../../../internal/active-element.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rangeEnd,LYRA_DEFAULT_rangeStart}from"../../../internal/default-strings.generated.js";const PAGE_STEP_MULTIPLIER=10;function createInternalsSafely(host){if(typeof host.attachInternals!="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue(){},setValidity(){},checkValidity(){return!0},reportValidity(){return!0},states:new Set}}class LyraTimeRange extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rangeEnd:LYRA_DEFAULT_rangeEnd,rangeStart:LYRA_DEFAULT_rangeStart}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get presets(){return this._presets}set presets(next){const previous=this._presets,snapshots=[];if(Array.isArray(next))for(let index=0;index<Math.min(next.length,256);index+=1)try{const raw=next[index];if(raw===null||typeof raw!="object"||typeof raw.label!="string"||typeof raw.start!="number"||typeof raw.end!="number")continue;snapshots.push(Object.freeze({label:raw.label,start:raw.start,end:raw.end}))}catch{}this._presets=Object.freeze(snapshots),this.requestUpdate("presets",previous)}constructor(){super(),this.min=0,this.max=100,this.start=0,this.end=100,this.step=1,this.size="m",this._presets=Object.freeze([]),this._disabled=!1,this._fieldsetDisabled=!1,this.drags=new Map,this.keyboardChanged=!1,this.hasInteracted=!1,this.markInteracted=()=>{this.liveDisabled||this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.onHandleFocus=event=>{relayNativeEvent(this,event)},this.onHandleBlur=event=>{this.finishKeyboardGesture(),relayNativeEvent(this,event)},this.onKeyDown=(handle,e)=>{if(this.liveDisabled)return;const current=handle==="start"?finiteRange(this.start,this.domain().lo):finiteRange(this.end,this.domain().hi),step=finiteRange(this.step,0,0),move=(direction,multiplier=1)=>{const delta=finiteRange(step*multiplier,Number.MAX_VALUE,0,Number.MAX_VALUE);delta!==0&&(this.keyboardChanged=this.setValue(handle,finiteAdd(current,direction*delta,current),!1)||this.keyboardChanged)},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";e.key===forwardKey||e.key==="ArrowUp"?(e.preventDefault(),move(1)):e.key===backwardKey||e.key==="ArrowDown"?(e.preventDefault(),move(-1)):e.key==="PageUp"?(e.preventDefault(),move(1,PAGE_STEP_MULTIPLIER)):e.key==="PageDown"?(e.preventDefault(),move(-1,PAGE_STEP_MULTIPLIER)):e.key==="Home"?(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).min,!1)||this.keyboardChanged):e.key==="End"&&(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).max,!1)||this.keyboardChanged)},this.onKeyUp=e=>{isSliderKey(e.key)&&this.finishKeyboardGesture()},this.onPointerDown=(handle,e)=>{this.beginDrag(handle,e,e.target)},this.onBasePointerDown=e=>{if(this.liveDisabled)return;const handles=Array.from(this.renderRoot.querySelectorAll('[part="handle-start"],[part="handle-end"]'));if(handles.length===0||handles.includes(e.target))return;const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const rect=base.getBoundingClientRect();if(rect.width===0)return;const target=this.valueAtPointer(e.clientX,rect,isRtl(this)),handle=this.nearestHandle(target),handleEl=this.renderRoot.querySelector(`[part="handle-${handle}"]`);if(!handleEl)return;const drag=this.beginDrag(handle,e,handleEl);drag&&(this.setValue(handle,target,!1)&&(drag.changed=!0),handleEl.focus())},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(drag===void 0)return;if(this.liveDisabled){this.endDrag(e.pointerId,!1);return}const value=this.valueAtPointer(e.clientX,drag.rect,drag.rtl);drag.changed=this.setValue(drag.handle,value,!1)||drag.changed},this.onPointerUp=e=>{this.endDrag(e.pointerId,e.type==="pointerup"&&!this.liveDisabled)},this.internals=createInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("focusout",this.markInteracted),this.reflectValidityStates()}get liveDisabled(){return this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled")}emitInput(){dispatchNativeEvent(this,"input"),this.emit("lr-input",{start:this.start,end:this.end})}emitChange(){dispatchNativeEvent(this,"change"),this.emit("lr-change",{start:this.start,end:this.end})}reflectValidityStates(){syncValidityStates(this.internals,{required:!1,hasInteracted:this.hasInteracted,barred:isBarredFromValidation(this,this.internals)})}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="handle-start"]')??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this._disabled&&this.abortActiveGestures(),this.toggleAttribute("disabled",this._disabled),this.reflectValidityStates(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.abortActiveGestures(),this.reflectValidityStates(),this.requestUpdate()}declaredHandleValue(handle,fallback){const declared=this.getAttribute(handle);return declared===null?fallback:finiteNumber(Number(declared),fallback)}formResetCallback(){const{lo,hi}=this.domain(),declaredStart=this.declaredHandleValue("start",lo),declaredEnd=this.declaredHandleValue("end",hi),start=finiteRange(declaredStart,lo,lo,hi),end=finiteRange(declaredEnd,hi,lo,hi);this.start=Math.min(start,end),this.end=Math.max(start,end),this.abortActiveGestures(),this.hasInteracted=!1,this.reflectValidityStates()}disconnectedCallback(){super.disconnectedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}adoptedCallback(){super.adoptedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}click(){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.click()}focus(options){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.focus(options)}blur(){const active=activeElementIn(this.shadowRoot);active?.nodeType===1&&typeof active.matches=="function"&&typeof active.blur=="function"&&active.matches('[part^="handle-"]')?active.blur():this.renderRoot?.querySelector('[part="handle-start"]')?.blur()}domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}percentOf(value){const{lo,hi}=this.domain(),safeValue=finiteRange(value,lo,lo,hi);return finiteRatio(safeValue,lo,hi)*100}reachableBounds(handle){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo,lo,hi),end=finiteRange(this.end,hi,lo,hi);return handle==="start"?{min:lo,max:end}:{min:start,max:hi}}clamp(handle,value){const{lo,hi}=this.domain();let stepped=finiteNumber(value,lo);const step=finiteRange(this.step,0,0);if(Number.isFinite(step)&&step>0){const stepsFromLo=Math.round((stepped-lo)/step);if(Number.isFinite(stepsFromLo)){const candidate=lo+stepsFromLo*step,factor=10**Math.min(decimalPlaces(step),15);Number.isFinite(candidate)&&(stepped=Number.isFinite(candidate*factor)?Math.round(candidate*factor)/factor:candidate)}}const bounded=Math.min(hi,Math.max(lo,stepped));return handle==="start"?Math.min(bounded,finiteRange(this.end,hi,lo,hi)):Math.max(bounded,finiteRange(this.start,lo,lo,hi))}setValue(handle,value,commit){const clamped=this.clamp(handle,value),previous=handle==="start"?this.start:this.end;return clamped===previous?!1:(handle==="start"?this.start=clamped:this.end=clamped,this.markInteracted(),this.emitInput(),commit&&this.emitChange(),!0)}applyPreset(preset){if(this.liveDisabled)return;const{start:nextStart,end:nextEnd}=this.normalizePreset(preset);nextStart===this.start&&nextEnd===this.end||(this.start=nextStart,this.end=nextEnd,this.markInteracted(),this.emitInput(),this.emitChange())}normalizePreset(preset){const{lo,hi}=this.domain(),start=finiteRange(preset.start,lo,lo,hi),end=finiteRange(preset.end,hi,lo,hi);return{start:Math.min(start,end),end:Math.max(start,end)}}finishKeyboardGesture(){this.keyboardChanged&&(this.keyboardChanged=!1,this.liveDisabled||this.emitChange())}beginDrag(handle,e,captureTarget){if(this.liveDisabled)return;const base=this.renderRoot.querySelector('[part="base"]'),dragWindow=base?.ownerDocument.defaultView;if(!base||!this.isConnected||!dragWindow)return;const firstDrag=this.drags.size===0;if(!firstDrag&&this.dragWindow!==dragWindow)return;captureTarget.setPointerCapture?.(e.pointerId);const drag={handle,changed:!1,rect:base.getBoundingClientRect(),rtl:isRtl(this)};return this.drags.set(e.pointerId,drag),firstDrag&&(this.dragWindow=dragWindow,dragWindow.addEventListener("pointermove",this.onPointerMove),dragWindow.addEventListener("pointerup",this.onPointerUp),dragWindow.addEventListener("pointercancel",this.onPointerUp),dragWindow.addEventListener("lostpointercapture",this.onPointerUp)),drag}valueAtPointer(clientX,rect,rtl){const raw=rect.width===0?0:(clientX-rect.left)/rect.width,ratio=Math.min(1,Math.max(0,rtl?1-raw:raw)),{lo,hi}=this.domain();return finiteInterpolate(lo,hi,ratio)}nearestHandle(target){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo),end=finiteRange(this.end,hi),toStart=Math.abs(target-start),toEnd=Math.abs(target-end);return toStart<toEnd?"start":toEnd<toStart?"end":target<start?"start":"end"}abortActiveGestures(){this.keyboardChanged=!1;for(const pointerId of[...this.drags.keys()])this.endDrag(pointerId,!1)}endDrag(pointerId,commit){const drag=this.drags.get(pointerId);drag&&(this.drags.delete(pointerId),commit&&drag.changed&&this.emitChange(),this.drags.size===0&&this.teardownDragWindow())}teardownDragWindow(){const dragWindow=this.dragWindow;this.dragWindow=void 0,dragWindow?.removeEventListener("pointermove",this.onPointerMove),dragWindow?.removeEventListener("pointerup",this.onPointerUp),dragWindow?.removeEventListener("pointercancel",this.onPointerUp),dragWindow?.removeEventListener("lostpointercapture",this.onPointerUp)}willUpdate(changed){if(super.willUpdate(changed),changed.has("start")||changed.has("end")||changed.has("min")||changed.has("max")){const{lo,hi}=this.domain(),start=Number.isFinite(this.start)?finiteRange(this.start,lo,lo,hi):this.start,end=Number.isFinite(this.end)?finiteRange(this.end,hi,lo,hi):this.end;if(changed.has("start")&&changed.has("end")&&Number.isFinite(start)&&Number.isFinite(end)){this.start=Math.min(start,end),this.end=Math.max(start,end);return}Number.isFinite(start)&&(this.start=start),Number.isFinite(end)&&(this.end=end)}(changed.has("start")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.start=Math.min(this.start,this.end)),(changed.has("end")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.end=Math.max(this.end,this.start))}render(){const startPct=this.percentOf(this.start),endPct=this.percentOf(this.end),startBounds=this.reachableBounds("start"),endBounds=this.reachableBounds("end"),startValue=Number.isFinite(this.start)?finiteRange(this.start,startBounds.min,startBounds.min,startBounds.max):void 0,endValue=Number.isFinite(this.end)?finiteRange(this.end,endBounds.min,endBounds.min,endBounds.max):void 0,startValueText=startValue===void 0?void 0:this.valueFormatter?.(startValue,"start"),endValueText=endValue===void 0?void 0:this.valueFormatter?.(endValue,"end");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{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{isRtl}from"../../../internal/rtl.js";import{decimalPlaces,finiteAdd,finiteInterpolate,finiteNumber,finiteRange,finiteRatio,isSliderKey}from"../../../internal/numbers.js";import{styles}from"./time-range.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{activeElementIn}from"../../../internal/active-element.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rangeEnd,LYRA_DEFAULT_rangeStart}from"../../../internal/default-strings.generated.js";const PAGE_STEP_MULTIPLIER=10;function createInternalsSafely(host){if(typeof host.attachInternals!="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue(){},setValidity(){},checkValidity(){return!0},reportValidity(){return!0},states:new Set}}class LyraTimeRange extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rangeEnd:LYRA_DEFAULT_rangeEnd,rangeStart:LYRA_DEFAULT_rangeStart}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get presets(){return this._presets}set presets(next){const previous=this._presets,snapshots=[];if(Array.isArray(next))for(let index=0;index<Math.min(next.length,256);index+=1)try{const raw=next[index];if(raw===null||typeof raw!="object"||typeof raw.label!="string"||typeof raw.start!="number"||typeof raw.end!="number")continue;snapshots.push(Object.freeze({label:raw.label,start:raw.start,end:raw.end}))}catch{}this._presets=Object.freeze(snapshots),this.requestUpdate("presets",previous)}constructor(){super(),this.min=0,this.max=100,this.start=0,this.end=100,this.step=1,this.size="m",this._presets=Object.freeze([]),this._disabled=!1,this._fieldsetDisabled=!1,this.drags=new Map,this.keyboardChanged=!1,this.hasInteracted=!1,this.markInteracted=()=>{this.liveDisabled||this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.onHandleFocus=event=>{relayNativeEvent(this,event)},this.onHandleBlur=event=>{this.finishKeyboardGesture(),relayNativeEvent(this,event)},this.onKeyDown=(handle,e)=>{if(this.liveDisabled)return;const current=handle==="start"?finiteRange(this.start,this.domain().lo):finiteRange(this.end,this.domain().hi),step=finiteRange(this.step,0,0),move=(direction,multiplier=1)=>{const delta=finiteRange(step*multiplier,Number.MAX_VALUE,0,Number.MAX_VALUE);delta!==0&&(this.keyboardChanged=this.setValue(handle,finiteAdd(current,direction*delta,current),!1)||this.keyboardChanged)},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";e.key===forwardKey||e.key==="ArrowUp"?(e.preventDefault(),move(1)):e.key===backwardKey||e.key==="ArrowDown"?(e.preventDefault(),move(-1)):e.key==="PageUp"?(e.preventDefault(),move(1,PAGE_STEP_MULTIPLIER)):e.key==="PageDown"?(e.preventDefault(),move(-1,PAGE_STEP_MULTIPLIER)):e.key==="Home"?(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).min,!1)||this.keyboardChanged):e.key==="End"&&(e.preventDefault(),this.keyboardChanged=this.setValue(handle,this.reachableBounds(handle).max,!1)||this.keyboardChanged)},this.onKeyUp=e=>{isSliderKey(e.key)&&this.finishKeyboardGesture()},this.onPointerDown=(handle,e)=>{this.beginDrag(handle,e,e.target)},this.onBasePointerDown=e=>{if(this.liveDisabled)return;const handles=Array.from(this.renderRoot.querySelectorAll('[part="handle-start"],[part="handle-end"]'));if(handles.length===0||handles.includes(e.target))return;const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const rect=base.getBoundingClientRect();if(rect.width===0)return;const target=this.valueAtPointer(e.clientX,rect,isRtl(this)),handle=this.nearestHandle(target),handleEl=this.renderRoot.querySelector(`[part="handle-${handle}"]`);if(!handleEl)return;const drag=this.beginDrag(handle,e,handleEl);drag&&(this.setValue(handle,target,!1)&&(drag.changed=!0),handleEl.focus())},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(drag===void 0)return;if(this.liveDisabled){this.endDrag(e.pointerId,!1);return}const value=this.valueAtPointer(e.clientX,drag.rect,drag.rtl);drag.changed=this.setValue(drag.handle,value,!1)||drag.changed},this.onPointerUp=e=>{this.endDrag(e.pointerId,e.type==="pointerup"&&!this.liveDisabled)},this.internals=createInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("focusout",this.markInteracted),this.reflectValidityStates()}get liveDisabled(){return this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled")}emitInput(){dispatchNativeEvent(this,"input"),this.emit("lr-input",{start:this.start,end:this.end})}emitChange(){dispatchNativeEvent(this,"change"),this.emit("lr-change",{start:this.start,end:this.end})}reflectValidityStates(){syncValidityStates(this.internals,{required:!1,hasInteracted:this.hasInteracted,barred:isBarredFromValidation(this,this.internals)})}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="handle-start"]')??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this._disabled&&this.abortActiveGestures(),this.toggleAttribute("disabled",this._disabled),this.reflectValidityStates(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.abortActiveGestures(),this.reflectValidityStates(),this.requestUpdate()}declaredHandleValue(handle,fallback){const declared=this.getAttribute(handle);return declared===null?fallback:finiteNumber(Number(declared),fallback)}formResetCallback(){const{lo,hi}=this.domain(),declaredStart=this.declaredHandleValue("start",lo),declaredEnd=this.declaredHandleValue("end",hi),start=finiteRange(declaredStart,lo,lo,hi),end=finiteRange(declaredEnd,hi,lo,hi);this.start=Math.min(start,end),this.end=Math.max(start,end),this.abortActiveGestures(),this.hasInteracted=!1,this.reflectValidityStates()}disconnectedCallback(){super.disconnectedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}adoptedCallback(){super.adoptedCallback(),this.drags.clear(),this.keyboardChanged=!1,this.teardownDragWindow()}click(){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.click()}focus(options){this.liveDisabled||this.renderRoot?.querySelector('[part="handle-start"]')?.focus(options)}blur(){const active=activeElementIn(this.shadowRoot);active?.nodeType===1&&typeof active.matches=="function"&&typeof active.blur=="function"&&active.matches('[part^="handle-"]')?active.blur():this.renderRoot?.querySelector('[part="handle-start"]')?.blur()}domain(){const min=finiteNumber(this.min,0),max=finiteNumber(this.max,100);return{lo:Math.min(min,max),hi:Math.max(min,max)}}percentOf(value){const{lo,hi}=this.domain(),safeValue=finiteRange(value,lo,lo,hi);return finiteRatio(safeValue,lo,hi)*100}reachableBounds(handle){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo,lo,hi),end=finiteRange(this.end,hi,lo,hi);return handle==="start"?{min:lo,max:end}:{min:start,max:hi}}clamp(handle,value){const{lo,hi}=this.domain();let stepped=finiteNumber(value,lo);const step=finiteRange(this.step,0,0);if(Number.isFinite(step)&&step>0){const stepsFromLo=Math.round((stepped-lo)/step);if(Number.isFinite(stepsFromLo)){const candidate=lo+stepsFromLo*step,factor=10**Math.min(decimalPlaces(step),15);Number.isFinite(candidate)&&(stepped=Number.isFinite(candidate*factor)?Math.round(candidate*factor)/factor:candidate)}}const bounded=Math.min(hi,Math.max(lo,stepped));return handle==="start"?Math.min(bounded,finiteRange(this.end,hi,lo,hi)):Math.max(bounded,finiteRange(this.start,lo,lo,hi))}setValue(handle,value,commit){const clamped=this.clamp(handle,value),previous=handle==="start"?this.start:this.end;return clamped===previous?!1:(handle==="start"?this.start=clamped:this.end=clamped,this.markInteracted(),this.emitInput(),commit&&this.emitChange(),!0)}applyPreset(preset){if(this.liveDisabled)return;const{start:nextStart,end:nextEnd}=this.normalizePreset(preset);nextStart===this.start&&nextEnd===this.end||(this.start=nextStart,this.end=nextEnd,this.markInteracted(),this.emitInput(),this.emitChange())}normalizePreset(preset){const{lo,hi}=this.domain(),start=finiteRange(preset.start,lo,lo,hi),end=finiteRange(preset.end,hi,lo,hi);return{start:Math.min(start,end),end:Math.max(start,end)}}finishKeyboardGesture(){this.keyboardChanged&&(this.keyboardChanged=!1,this.liveDisabled||this.emitChange())}beginDrag(handle,e,captureTarget){if(this.liveDisabled)return;const base=this.renderRoot.querySelector('[part="base"]'),dragWindow=base?.ownerDocument.defaultView;if(!base||!this.isConnected||!dragWindow)return;const firstDrag=this.drags.size===0;if(!firstDrag&&this.dragWindow!==dragWindow)return;captureTarget.setPointerCapture?.(e.pointerId);const drag={handle,changed:!1,rect:base.getBoundingClientRect(),rtl:isRtl(this)};return this.drags.set(e.pointerId,drag),firstDrag&&(this.dragWindow=dragWindow,dragWindow.addEventListener("pointermove",this.onPointerMove),dragWindow.addEventListener("pointerup",this.onPointerUp),dragWindow.addEventListener("pointercancel",this.onPointerUp),dragWindow.addEventListener("lostpointercapture",this.onPointerUp)),drag}valueAtPointer(clientX,rect,rtl){const raw=rect.width===0?0:(clientX-rect.left)/rect.width,ratio=Math.min(1,Math.max(0,rtl?1-raw:raw)),{lo,hi}=this.domain();return finiteInterpolate(lo,hi,ratio)}nearestHandle(target){const{lo,hi}=this.domain(),start=finiteRange(this.start,lo),end=finiteRange(this.end,hi),toStart=Math.abs(target-start),toEnd=Math.abs(target-end);return toStart<toEnd?"start":toEnd<toStart?"end":target<start?"start":"end"}abortActiveGestures(){this.keyboardChanged=!1;for(const pointerId of[...this.drags.keys()])this.endDrag(pointerId,!1)}endDrag(pointerId,commit){const drag=this.drags.get(pointerId);drag&&(this.drags.delete(pointerId),commit&&drag.changed&&this.emitChange(),this.drags.size===0&&this.teardownDragWindow())}teardownDragWindow(){const dragWindow=this.dragWindow;this.dragWindow=void 0,dragWindow?.removeEventListener("pointermove",this.onPointerMove),dragWindow?.removeEventListener("pointerup",this.onPointerUp),dragWindow?.removeEventListener("pointercancel",this.onPointerUp),dragWindow?.removeEventListener("lostpointercapture",this.onPointerUp)}willUpdate(changed){if(super.willUpdate(changed),changed.has("start")||changed.has("end")||changed.has("min")||changed.has("max")){const{lo,hi}=this.domain(),start=Number.isFinite(this.start)?finiteRange(this.start,lo,lo,hi):this.start,end=Number.isFinite(this.end)?finiteRange(this.end,hi,lo,hi):this.end;if(changed.has("start")&&changed.has("end")&&Number.isFinite(start)&&Number.isFinite(end)){this.start=Math.min(start,end),this.end=Math.max(start,end);return}Number.isFinite(start)&&(this.start=start),Number.isFinite(end)&&(this.end=end)}(changed.has("start")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.start=Math.min(this.start,this.end)),(changed.has("end")||changed.has("min")||changed.has("max"))&&Number.isFinite(this.start)&&Number.isFinite(this.end)&&(this.end=Math.max(this.end,this.start))}render(){const startPct=this.percentOf(this.start),endPct=this.percentOf(this.end),startBounds=this.reachableBounds("start"),endBounds=this.reachableBounds("end"),startValue=Number.isFinite(this.start)?finiteRange(this.start,startBounds.min,startBounds.min,startBounds.max):void 0,endValue=Number.isFinite(this.end)?finiteRange(this.end,endBounds.min,endBounds.min,endBounds.max):void 0,startValueText=startValue===void 0?void 0:this.valueFormatter?.(startValue,"start"),endValueText=endValue===void 0?void 0:this.valueFormatter?.(endValue,"end");return html`
|
|
2
2
|
${this.presets.length>0?html`<div part="presets">
|
|
3
3
|
${this.presets.map(preset=>{const normalized=this.normalizePreset(preset),active=normalized.start===this.start&&normalized.end===this.end;return html`<button
|
|
4
4
|
part="preset-button"
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
+
import '../../../internal/form-control-labels.js';
|
|
3
4
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
4
5
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
5
6
|
export interface LyraTokenInputEventMap {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activeElementIn}from"../../../internal/active-element.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon}from"../../../internal/icons.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./token-input.styles.js";import{attachInternalsSafely,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_tokenInputEditWithContext,LYRA_DEFAULT_tokenInputRequired}from"../../../internal/default-strings.generated.js";const delimiterConverter={fromAttribute:value=>value===null?",":value===""||value==="none"?null:value,toAttribute:value=>value===null?"none":value};function normalizeStringArray(value){if(!Array.isArray(value))return Object.freeze([]);try{const normalized=[];for(const entry of value)typeof entry=="string"&&normalized.push(entry);return Object.freeze(normalized)}catch{return Object.freeze([])}}const stringArrayConverter={fromAttribute:value=>{if(value===null)return null;try{const parsed=JSON.parse(value);return normalizeStringArray(parsed)}catch{return[]}},toAttribute:value=>value==null?null:JSON.stringify(value)};class LyraTokenInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,removeWithContext:LYRA_DEFAULT_removeWithContext,tokenInputEditWithContext:LYRA_DEFAULT_tokenInputEditWithContext,tokenInputRequired:LYRA_DEFAULT_tokenInputRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,converter:stringArrayConverter,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get editable(){return this._editable}set editable(next){const old=this._editable;this._editable=!!next,this._editable||this.discardTransientState(!1),this.requestUpdate("editable",old)}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0);const normalized=normalizeStringArray(next);this.captureTokenFocusRepair(normalized),this.editingIndex>=0&&normalized!==old&&(this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1),this._value=normalized,this.requestUpdate("value",old),this.internals&&this.syncValidity()}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=normalizeStringArray(next),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("value"):this.setAttribute("value",JSON.stringify(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncValidity(),this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled,wasEffectivelyDisabled=this.effectiveDisabled;this._disabled=!!next,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.toggleAttribute("disabled",this._disabled),this.syncValidity(),this.requestUpdate("disabled",old)}constructor(){super(),this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.accessibleLabel="",this.size="m",this.pill=!1,this.allowDuplicates=!1,this._editable=!1,this.delimiter=",",this.draft="",this.touched=!1,this.editingIndex=-1,this.editDraft="",this.rovingIndex=0,this.focusEditorPending=!1,this.focusTokenPending=-1,this.editorBlurRelayed=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.labelId=nextId("token-input-label"),this.hintId=nextId("token-input-hint"),this.errorId=nextId("token-input-error"),this._value=Object.freeze([]),this._defaultValue=Object.freeze([]),this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this.onEditInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.editDraft=event.target.value)},this.onEditFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.editorBlurRelayed=!1,relayNativeEvent(this,event)},this.onEditKeyDown=event=>{event.key==="Enter"?(event.preventDefault(),this.commitEdit(!0)):event.key==="Escape"&&(event.preventDefault(),event.stopPropagation(),this.cancelEdit())},this.onEditBlur=event=>{if(this.editorBlurRelayed){event.stopPropagation();return}this.editorBlurRelayed=!0,event.stopPropagation(),queueMicrotask(()=>{!this.isConnected||!this.editable||this.liveDisabled?this.discardTransientState(!1):this.commitEdit(!1),relayNativeEvent(this,event)})},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.draft=event.target.value)},this.onKeyDown=event=>{this.liveDisabled||(event.key==="Enter"||this.delimiter!==null&&event.key===this.delimiter?this.draft.trim()?(event.preventDefault(),this.addDraft()):event.key==="Enter"&&submitOnEnter(this,event):event.key==="Tab"?this.draft.trim()&&this.addDraft():event.key==="Backspace"&&!this.draft&&this.value.length&&this.editingIndex<0&&this.removeToken(this.value.length-1))},this.onBlur=event=>{this.liveDisabled||(this.draft.trim()&&this.addDraft(),this.touched=!0),this.syncValidity(),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},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))}connectedCallback(){super.connectedCallback(),this.syncValidity()}disconnectedCallback(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0),super.disconnectedCallback()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){const wasEffectivelyDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.syncValidity(),this.requestUpdate()}[VALIDITY_ANCHOR](){return this.inputEl??this.renderRoot?.querySelector('[part="input-wrapper"]')??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncValidity(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidity()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.inputEl?.focus()}select(){this.inputEl?.select()}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection??"none")}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.draft=input.value)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end"))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidity(){const barred=this.barredFromValidation,missing=!barred&&this.required&&this.value.length===0;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("tokenInputRequired"):""),this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred});const data=new FormData;this.name&&this.value.forEach(token=>data.append(this.name,token)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,this.value))}updateValue(next){this.value=next,this.syncValidity(),dispatchNativeInputEvent(this),this.emit("lr-input",Object.freeze({value:Object.freeze([...this.value])})),dispatchNativeEvent(this,"change"),this.emit("lr-change",Object.freeze({value:Object.freeze([...this.value])}))}addDraft(){if(this.liveDisabled)return;const candidates=(this.delimiter?this.draft.split(this.delimiter):[this.draft]).map(token=>token.trim()).filter(Boolean),next=[...this.value],seen=this.allowDuplicates?null:new Set(next),added=[];for(const token of candidates)seen?.has(token)||(seen?.add(token),next.push(token),added.push(token));if(added.length===0){this.draft="";return}this.emit("lr-add",Object.freeze({value:added[added.length-1],values:Object.freeze([...added])}),{cancelable:!0}).defaultPrevented||(this.updateValue(next),this.draft="")}discardTransientState(clearDraft){this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1,this.focusTokenPending=-1,clearDraft&&(this.draft="",this.inputEl&&(this.inputEl.value=""))}retireDisabledInteraction(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0);const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}captureTokenFocusRepair(next){this.tokenFocusRepairPending=void 0;const tokens=[...this.renderRoot?.querySelectorAll('[part~="token"]')??[]];if(next.length>=tokens.length)return;const active=activeElementIn(this.shadowRoot),token=active?.closest('[part~="token"]');if(!active||!token)return;const index=tokens.indexOf(token);if(index<0)return;const repair=captureComposedFocusRepair(this,active);if(!repair)return;const targetIndex=Math.min(index,Math.max(0,next.length-1));this.rovingIndex=targetIndex,this.tokenFocusRepairPending={index:targetIndex,surface:active.matches('[part~="remove"]')?"remove":"label",repair}}removeToken(index){if(this.liveDisabled)return;const removed=this.value[index];removed===void 0||this.emit("lr-remove",{value:removed,index},{cancelable:!0}).defaultPrevented||(this.editingIndex>=0&&(this.editingIndex=-1,this.editDraft=""),this.updateValue(this.value.filter((_token,i)=>i!==index)))}get activeTokenIndex(){return this.value.length?Math.min(Math.max(this.rovingIndex,0),this.value.length-1):-1}startEdit(index){this.liveDisabled||!this.editable||index<0||index>=this.value.length||(this.editingIndex=index,this.editDraft=this.value[index],this.rovingIndex=index,this.editorBlurRelayed=!1,this.focusEditorPending=!0)}cancelEdit(){this.editingIndex<0||(this.focusTokenPending=this.editingIndex,this.editingIndex=-1,this.editDraft="")}commitEdit(restoreFocus){if(this.liveDisabled){this.discardTransientState(!1);return}const index=this.editingIndex;if(index<0)return;const previousValue=this.value[index],next=this.editDraft.trim();if(previousValue===void 0||!next||next===previousValue||!this.allowDuplicates&&this.value.some((token,i)=>i!==index&&token===next)){restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="";return}this.emit("lr-token-edit",{value:next,previousValue,index},{cancelable:!0}).defaultPrevented||(restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="",this.updateValue(this.value.map((token,i)=>i===index?next:token)))}moveRovingFocus(index){if(!this.value.length)return;const clamped=Math.min(Math.max(index,0),this.value.length-1);this.rovingIndex=clamped,this.focusTokenPending=clamped}onTokenKeyDown(event,index){if(this.liveDisabled)return;const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";event.key==="Enter"||event.key===" "||event.key==="F2"?(event.preventDefault(),this.startEdit(index)):event.key===forward?(event.preventDefault(),this.moveRovingFocus(index+1)):event.key===backward?(event.preventDefault(),this.moveRovingFocus(index-1)):event.key==="Home"?(event.preventDefault(),this.moveRovingFocus(0)):event.key==="End"&&(event.preventDefault(),this.moveRovingFocus(this.value.length-1))}stopInternalChange(event){event.stopPropagation()}formResetCallback(){this.restoreLiveValueFromDefault(),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=[...this._defaultValue]}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=readStringArrayFormDataState(state2),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}updated(changed){if(super.updated(changed),this.focusEditorPending){this.focusEditorPending=!1;const editor=this.renderRoot?.querySelector('[part="token-editor"]');editor?.focus(),editor?.select()}if(this.focusTokenPending>=0){const index=this.focusTokenPending;this.focusTokenPending=-1;const label=this.renderRoot?.querySelectorAll('[part="token-label"]')?.[index];label?.focus(),label?.scrollIntoView({block:"nearest",inline:"nearest"})}const pending=this.tokenFocusRepairPending;if(this.tokenFocusRepairPending=void 0,pending){const token=[...this.renderRoot.querySelectorAll('[part~="token"]')][pending.index],target=(pending.surface==="remove"?token?.querySelector('[part~="remove"]'):token?.querySelector('[part~="token-label"]'))??token?.querySelector('[part~="remove"]')??this.inputEl??null;applyComposedFocusRepair(pending.repair,target)&&target?.scrollIntoView({block:"nearest",inline:"nearest"})}}renderRemoveButton(token,index){return html`<button
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{activeElementIn}from"../../../internal/active-element.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon}from"../../../internal/icons.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./token-input.styles.js";import{attachInternalsSafely,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_tokenInputEditWithContext,LYRA_DEFAULT_tokenInputRequired}from"../../../internal/default-strings.generated.js";const delimiterConverter={fromAttribute:value=>value===null?",":value===""||value==="none"?null:value,toAttribute:value=>value===null?"none":value};function normalizeStringArray(value){if(!Array.isArray(value))return Object.freeze([]);try{const normalized=[];for(const entry of value)typeof entry=="string"&&normalized.push(entry);return Object.freeze(normalized)}catch{return Object.freeze([])}}const stringArrayConverter={fromAttribute:value=>{if(value===null)return null;try{const parsed=JSON.parse(value);return normalizeStringArray(parsed)}catch{return[]}},toAttribute:value=>value==null?null:JSON.stringify(value)};class LyraTokenInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,removeWithContext:LYRA_DEFAULT_removeWithContext,tokenInputEditWithContext:LYRA_DEFAULT_tokenInputEditWithContext,tokenInputRequired:LYRA_DEFAULT_tokenInputRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,converter:stringArrayConverter,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get editable(){return this._editable}set editable(next){const old=this._editable;this._editable=!!next,this._editable||this.discardTransientState(!1),this.requestUpdate("editable",old)}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0);const normalized=normalizeStringArray(next);this.captureTokenFocusRepair(normalized),this.editingIndex>=0&&normalized!==old&&(this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1),this._value=normalized,this.requestUpdate("value",old),this.internals&&this.syncValidity()}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=normalizeStringArray(next),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("value"):this.setAttribute("value",JSON.stringify(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncValidity(),this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled,wasEffectivelyDisabled=this.effectiveDisabled;this._disabled=!!next,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.toggleAttribute("disabled",this._disabled),this.syncValidity(),this.requestUpdate("disabled",old)}constructor(){super(),this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.accessibleLabel="",this.size="m",this.pill=!1,this.allowDuplicates=!1,this._editable=!1,this.delimiter=",",this.draft="",this.touched=!1,this.editingIndex=-1,this.editDraft="",this.rovingIndex=0,this.focusEditorPending=!1,this.focusTokenPending=-1,this.editorBlurRelayed=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.labelId=nextId("token-input-label"),this.hintId=nextId("token-input-hint"),this.errorId=nextId("token-input-error"),this._value=Object.freeze([]),this._defaultValue=Object.freeze([]),this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this.onEditInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.editDraft=event.target.value)},this.onEditFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.editorBlurRelayed=!1,relayNativeEvent(this,event)},this.onEditKeyDown=event=>{event.key==="Enter"?(event.preventDefault(),this.commitEdit(!0)):event.key==="Escape"&&(event.preventDefault(),event.stopPropagation(),this.cancelEdit())},this.onEditBlur=event=>{if(this.editorBlurRelayed){event.stopPropagation();return}this.editorBlurRelayed=!0,event.stopPropagation(),queueMicrotask(()=>{!this.isConnected||!this.editable||this.liveDisabled?this.discardTransientState(!1):this.commitEdit(!1),relayNativeEvent(this,event)})},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.draft=event.target.value)},this.onKeyDown=event=>{this.liveDisabled||(event.key==="Enter"||this.delimiter!==null&&event.key===this.delimiter?this.draft.trim()?(event.preventDefault(),this.addDraft()):event.key==="Enter"&&submitOnEnter(this,event):event.key==="Tab"?this.draft.trim()&&this.addDraft():event.key==="Backspace"&&!this.draft&&this.value.length&&this.editingIndex<0&&this.removeToken(this.value.length-1))},this.onBlur=event=>{this.liveDisabled||(this.draft.trim()&&this.addDraft(),this.touched=!0),this.syncValidity(),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},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))}connectedCallback(){super.connectedCallback(),this.syncValidity()}disconnectedCallback(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0),super.disconnectedCallback()}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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formDisabledCallback(disabled){const wasEffectivelyDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,!wasEffectivelyDisabled&&this.effectiveDisabled&&this.retireDisabledInteraction(),this.syncValidity(),this.requestUpdate()}[VALIDITY_ANCHOR](){return this.inputEl??this.renderRoot?.querySelector('[part="input-wrapper"]')??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncValidity(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidity()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.inputEl?.focus()}select(){this.inputEl?.select()}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection??"none")}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.draft=input.value)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end"))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidity(){const barred=this.barredFromValidation,missing=!barred&&this.required&&this.value.length===0;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("tokenInputRequired"):""),this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred});const data=new FormData;this.name&&this.value.forEach(token=>data.append(this.name,token)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,this.value))}updateValue(next){this.value=next,this.syncValidity(),dispatchNativeInputEvent(this),this.emit("lr-input",Object.freeze({value:Object.freeze([...this.value])})),dispatchNativeEvent(this,"change"),this.emit("lr-change",Object.freeze({value:Object.freeze([...this.value])}))}addDraft(){if(this.liveDisabled)return;const candidates=(this.delimiter?this.draft.split(this.delimiter):[this.draft]).map(token=>token.trim()).filter(Boolean),next=[...this.value],seen=this.allowDuplicates?null:new Set(next),added=[];for(const token of candidates)seen?.has(token)||(seen?.add(token),next.push(token),added.push(token));if(added.length===0){this.draft="";return}this.emit("lr-add",Object.freeze({value:added[added.length-1],values:Object.freeze([...added])}),{cancelable:!0}).defaultPrevented||(this.updateValue(next),this.draft="")}discardTransientState(clearDraft){this.editingIndex=-1,this.editDraft="",this.focusEditorPending=!1,this.focusTokenPending=-1,clearDraft&&(this.draft="",this.inputEl&&(this.inputEl.value=""))}retireDisabledInteraction(){this.tokenFocusRepairPending=void 0,this.discardTransientState(!0);const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}captureTokenFocusRepair(next){this.tokenFocusRepairPending=void 0;const tokens=[...this.renderRoot?.querySelectorAll('[part~="token"]')??[]];if(next.length>=tokens.length)return;const active=activeElementIn(this.shadowRoot),token=active?.closest('[part~="token"]');if(!active||!token)return;const index=tokens.indexOf(token);if(index<0)return;const repair=captureComposedFocusRepair(this,active);if(!repair)return;const targetIndex=Math.min(index,Math.max(0,next.length-1));this.rovingIndex=targetIndex,this.tokenFocusRepairPending={index:targetIndex,surface:active.matches('[part~="remove"]')?"remove":"label",repair}}removeToken(index){if(this.liveDisabled)return;const removed=this.value[index];removed===void 0||this.emit("lr-remove",{value:removed,index},{cancelable:!0}).defaultPrevented||(this.editingIndex>=0&&(this.editingIndex=-1,this.editDraft=""),this.updateValue(this.value.filter((_token,i)=>i!==index)))}get activeTokenIndex(){return this.value.length?Math.min(Math.max(this.rovingIndex,0),this.value.length-1):-1}startEdit(index){this.liveDisabled||!this.editable||index<0||index>=this.value.length||(this.editingIndex=index,this.editDraft=this.value[index],this.rovingIndex=index,this.editorBlurRelayed=!1,this.focusEditorPending=!0)}cancelEdit(){this.editingIndex<0||(this.focusTokenPending=this.editingIndex,this.editingIndex=-1,this.editDraft="")}commitEdit(restoreFocus){if(this.liveDisabled){this.discardTransientState(!1);return}const index=this.editingIndex;if(index<0)return;const previousValue=this.value[index],next=this.editDraft.trim();if(previousValue===void 0||!next||next===previousValue||!this.allowDuplicates&&this.value.some((token,i)=>i!==index&&token===next)){restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="";return}this.emit("lr-token-edit",{value:next,previousValue,index},{cancelable:!0}).defaultPrevented||(restoreFocus&&(this.focusTokenPending=index),this.editingIndex=-1,this.editDraft="",this.updateValue(this.value.map((token,i)=>i===index?next:token)))}moveRovingFocus(index){if(!this.value.length)return;const clamped=Math.min(Math.max(index,0),this.value.length-1);this.rovingIndex=clamped,this.focusTokenPending=clamped}onTokenKeyDown(event,index){if(this.liveDisabled)return;const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";event.key==="Enter"||event.key===" "||event.key==="F2"?(event.preventDefault(),this.startEdit(index)):event.key===forward?(event.preventDefault(),this.moveRovingFocus(index+1)):event.key===backward?(event.preventDefault(),this.moveRovingFocus(index-1)):event.key==="Home"?(event.preventDefault(),this.moveRovingFocus(0)):event.key==="End"&&(event.preventDefault(),this.moveRovingFocus(this.value.length-1))}stopInternalChange(event){event.stopPropagation()}formResetCallback(){this.restoreLiveValueFromDefault(),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=[...this._defaultValue]}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=readStringArrayFormDataState(state2),this.discardTransientState(!0),this.rovingIndex=0,this.touched=!1,this.syncValidity()}updated(changed){if(super.updated(changed),this.focusEditorPending){this.focusEditorPending=!1;const editor=this.renderRoot?.querySelector('[part="token-editor"]');editor?.focus(),editor?.select()}if(this.focusTokenPending>=0){const index=this.focusTokenPending;this.focusTokenPending=-1;const label=this.renderRoot?.querySelectorAll('[part="token-label"]')?.[index];label?.focus(),label?.scrollIntoView({block:"nearest",inline:"nearest"})}const pending=this.tokenFocusRepairPending;if(this.tokenFocusRepairPending=void 0,pending){const token=[...this.renderRoot.querySelectorAll('[part~="token"]')][pending.index],target=(pending.surface==="remove"?token?.querySelector('[part~="remove"]'):token?.querySelector('[part~="token-label"]'))??token?.querySelector('[part~="remove"]')??this.inputEl??null;applyComposedFocusRepair(pending.repair,target)&&target?.scrollIntoView({block:"nearest",inline:"nearest"})}}renderRemoveButton(token,index){return html`<button
|
|
2
2
|
part="remove"
|
|
3
3
|
type="button"
|
|
4
4
|
aria-label=${this.localize("removeWithContext",void 0,{label:token})}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{closeIcon,expandIcon,fileIcon}from"../../../internal/icons.js";import{finiteRange}from"../../../internal/numbers.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./attachment-chip.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"./file-size.js";import{LYRA_DEFAULT_attachmentPreviewFile,LYRA_DEFAULT_attachmentPreviewName,LYRA_DEFAULT_attachmentRetryWithContext,LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_attachmentUploadFailed,LYRA_DEFAULT_attachmentUploadingIndeterminate,LYRA_DEFAULT_attachmentUploadingProgress,LYRA_DEFAULT_attachmentUploadingWithContext,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";import{FILE_SIZE_UNIT_KEYS as FILE_SIZE_UNIT_KEYS2,formatFileSize as formatFileSize2}from"./file-size.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
11
11
|
aria-hidden="true"
|
|
12
12
|
focusable="false"
|
|
13
13
|
><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
|
|
14
|
-
`}function statusText(status,uploadingText,uploadFailedLabel){return status==="error"?uploadFailedLabel:status==="uploading"?uploadingText:""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments),this.name="",this.attachmentId="",this.mimeType="",this.thumbnailSrc="",this.previewSrc="",this.previewable=!0,this.status="pending",this.progress=0,this.removable=!0,this.compact=!1,this.thumbnailOnly=!1,this.fallbackId=nextId("attachment-chip"),this.onRemoveClick=()=>{this.emit("lr-remove",{attachmentId:this.resolvedId})},this.onRetryClick=()=>{this.emit("lr-retry",{attachmentId:this.resolvedId})},this.onPreviewClick=()=>{this.effectivePreviewSrc&&this.emit("lr-preview-request",{attachmentId:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,
|
|
14
|
+
`}function statusText(status,uploadingText,uploadFailedLabel){return status==="error"?uploadFailedLabel:status==="uploading"?uploadingText:""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments),this.name="",this.attachmentId="",this.mimeType="",this.thumbnailSrc="",this.previewSrc="",this.previewable=!0,this.status="pending",this.progress=0,this.removable=!0,this.compact=!1,this.thumbnailOnly=!1,this.fallbackId=nextId("attachment-chip"),this.onRemoveClick=()=>{this.emit("lr-remove",{attachmentId:this.resolvedId})},this.onRetryClick=()=>{this.emit("lr-retry",{attachmentId:this.resolvedId})},this.onPreviewClick=()=>{this.effectivePreviewSrc&&this.emit("lr-preview-request",{attachmentId:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})}}static{this.defaultStrings={...super.defaultStrings,attachmentPreviewFile:LYRA_DEFAULT_attachmentPreviewFile,attachmentPreviewName:LYRA_DEFAULT_attachmentPreviewName,attachmentRetryWithContext:LYRA_DEFAULT_attachmentRetryWithContext,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,attachmentUploadFailed:LYRA_DEFAULT_attachmentUploadFailed,attachmentUploadingIndeterminate:LYRA_DEFAULT_attachmentUploadingIndeterminate,attachmentUploadingProgress:LYRA_DEFAULT_attachmentUploadingProgress,attachmentUploadingWithContext:LYRA_DEFAULT_attachmentUploadingWithContext,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,removeWithContext:LYRA_DEFAULT_removeWithContext,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get bytes(){return this._bytes}set bytes(value){const old=this._bytes;this._bytes=typeof value=="number"&&Number.isFinite(value)&&value>=0?finiteRange(value,0,0):void 0,this.requestUpdate("bytes",old)}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?Number.isFinite(this.file.size)&&this.file.size>=0?finiteRange(this.file.size,0,0):void 0:this.bytes}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){return this.attachmentId.trim().length>0?this.attachmentId:this.file?`${this.file.name}:${this.file.size}:${this.file.lastModified}`:this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}get effectiveStatus(){return this.status==="uploading"||this.status==="error"||this.status==="success"?this.status:"pending"}ensureObjectUrl(file){return this.objectUrlFile===file&&this.objectUrl?this.objectUrl:(this.revokeObjectUrl(),this.objectUrl=URL.createObjectURL(file),this.objectUrlFile=file,this.objectUrl)}revokeObjectUrl(){this.objectUrl&&URL.revokeObjectURL(this.objectUrl),this.objectUrl=void 0,this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.requestUpdate()}adoptedCallback(){super.adoptedCallback(),this.releaseAnnouncementSink(),this.syncAnnouncementSink()}syncAnnouncementSink(){this.isConnected&&this.sink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.sink?.release(),this.sink=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("status")&&this.status!==this.effectiveStatus&&(this.status=this.effectiveStatus),this.hasUpdated&&changed.has("status")&&this.status==="error"&&this.sink?.announce(this.localizedUploadFailedLabel),this.isConnected&&this.file&&(this.file.type.startsWith("image/")||this.previewable)?this.ensureObjectUrl(this.file):this.objectUrlFile&&this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback(),this.revokeObjectUrl(),this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.uploadFailedLabel??this.localize("attachmentUploadFailed")}renderThumbnail(){if(this.file){const fileImageSrc=this.objectUrl?safeMediaSrc(this.objectUrl):null;return this.effectiveMimeType.startsWith("image/")?fileImageSrc?html`<img src=${fileImageSrc} alt="" />`:html`${fileIcon()}`:html`${fileIcon()}`}const thumbnailSrc=safeMediaSrc(this.thumbnailSrc);return thumbnailSrc?html`<img src=${thumbnailSrc} alt="" />`:html`${fileIcon()}`}render(){const name=this.effectiveName,untitledLabel=this.untitledLabel??this.localize("attachmentUntitledFile"),displayName=name||untitledLabel,sizeText=this.effectiveSize!==void 0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"",uploadFailedLabel=this.localizedUploadFailedLabel,progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress)),uploadingText=this.uploadingLabel!==void 0?this.uploadingLabel:this.hasNumericProgress?this.localize("attachmentUploadingProgress",void 0,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate"),uploadingWithContext=this.uploadingLabel??this.localize("attachmentUploadingWithContext",void 0,{label:displayName}),retryWithContext=this.retryLabel??this.localize("attachmentRetryWithContext",void 0,{label:displayName}),removeWithContext=this.removeLabel??this.localize("removeWithContext",void 0,{label:displayName}),status=this.effectiveStatus,text=statusText(status,uploadingText,uploadFailedLabel),uploading=status==="uploading";return html`
|
|
15
15
|
<div part="base">
|
|
16
16
|
<span part="thumbnail" aria-hidden="true"
|
|
17
17
|
>${this.renderThumbnail()}</span
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -25,7 +25,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
25
25
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
26
26
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
27
27
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
28
|
-
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]);function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,4);for(let index=0;index<length;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,
|
|
28
|
+
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]);function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,4);for(let index=0;index<length;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
29
29
|
<input
|
|
30
30
|
part="hidden-input"
|
|
31
31
|
type="file"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:renderedLabel,size:sizeText}):renderedLabel,accessibleLabel=hostAriaLabel(this)??fallbackLabel,descriptionId=metadata.provenance==="consumer"&&metadata.description?"metadata-description":void 0;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="base"
|
|
4
4
|
role=${this.decorative?"presentation":"img"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
+
import '../../../internal/form-control-labels.js';
|
|
3
4
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
4
5
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
5
6
|
export type LyraFileInputCapture = '' | 'user' | 'environment';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type LyraFlagUrlResolver } from './flag.js';
|
|
2
|
+
/**
|
|
3
|
+
* Register a bulk-resolution `@aceshooting/lyra-flags` resolver, backed by one shared
|
|
4
|
+
* `flagUrls()` fetch instead of `flag-peer.js`'s per-code lazy resolution. Import this **instead
|
|
5
|
+
* of** `flag-peer.js` — never both; the second `setFlagUrlResolver()` call simply replaces the
|
|
6
|
+
* first — and only when the page renders most or all flags at once (a country table, a full
|
|
7
|
+
* locale picker). A page rendering only a few flags pays an unneeded 249-entry fetch for no
|
|
8
|
+
* benefit; use `flag-peer.js` there instead. `fidelity="compact"/"detailed"` on individual
|
|
9
|
+
* `<lr-flag>` elements still resolves correctly (see `createFlagUrlResolver()`'s own doc in
|
|
10
|
+
* `@aceshooting/lyra-flags`) — only the default (`"standard"`) tier is bulk-fetched.
|
|
11
|
+
*/
|
|
12
|
+
export declare function registerLyraFlagBulkPeer(): Promise<LyraFlagUrlResolver | null>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loadBulkFlagUrl,setFlagUrlResolver}from"./flag.js";const peerResolver=loadBulkFlagUrl(()=>import("@aceshooting/lyra-flags"));setFlagUrlResolver(peerResolver);async function registerLyraFlagBulkPeer(){return peerResolver}registerLyraFlagBulkPeer();export{registerLyraFlagBulkPeer};
|
|
@@ -14,6 +14,14 @@ export type LyraFlagUrlResolver = (code: string, options?: {
|
|
|
14
14
|
* actually uninstall the package.
|
|
15
15
|
*/
|
|
16
16
|
export declare function loadFlagUrl(importFlags: () => Promise<unknown>): Promise<LyraFlagUrlResolver | null>;
|
|
17
|
+
/**
|
|
18
|
+
* Resolves `@aceshooting/lyra-flags`'s `createFlagUrlResolver` via the given importer and calls
|
|
19
|
+
* it once, the bulk-resolution twin of `loadFlagUrl()` above. Backs `flag-peer-bulk.js` — the
|
|
20
|
+
* opt-in alternative to `flag-peer.js` for a page that renders most/all flags at once, where one
|
|
21
|
+
* shared `flagUrls()` fetch beats resolving every `<lr-flag>` instance independently. Same
|
|
22
|
+
* dependency-injectable, uncached shape as `loadFlagUrl()`, for the same testability reason.
|
|
23
|
+
*/
|
|
24
|
+
export declare function loadBulkFlagUrl(importFlags: () => Promise<unknown>): Promise<LyraFlagUrlResolver | null>;
|
|
17
25
|
/** Install an optional flag resolver supplied by a peer-registration entry. */
|
|
18
26
|
export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<LyraFlagUrlResolver | null> | null): void;
|
|
19
27
|
/**
|
|
@@ -35,12 +43,32 @@ export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<
|
|
|
35
43
|
* `flagUrl(code)`, which lazily fetches one requested flag at runtime. A
|
|
36
44
|
* bundler may still emit the complete reachable lazy-chunk graph; use a
|
|
37
45
|
* literal asset subpath import when the deployment artifact must be pruned.
|
|
46
|
+
* If every `<lr-flag>` in your app is pinned to the same `fidelity` (no
|
|
47
|
+
* per-instance switching), register `@aceshooting/lyra-flags/standard`/`/compact`/`/detailed` with
|
|
48
|
+
* `setFlagUrlResolver()` instead of importing `flag-peer.js` (which always registers the full
|
|
49
|
+
* three-tier resolver) — the tier-specific entry excludes the other two tiers' generated loader
|
|
50
|
+
* maps from the reachable graph; see that package's README for the exact shape.
|
|
38
51
|
* If you already
|
|
39
52
|
* have a flag's URL at build time (e.g. from your own literal
|
|
40
53
|
* `import frUrl from '@aceshooting/lyra-flags/flags/fr.svg?url'`), pass it as
|
|
41
54
|
* `src` instead to skip the peer-package round trip (and its loading-skeleton
|
|
42
55
|
* flash) entirely.
|
|
43
56
|
*
|
|
57
|
+
* **Rendering many flags at once** (a country table, a picker listing every locale): resolve every
|
|
58
|
+
* code up front with `@aceshooting/lyra-flags`'s `flagUrls()` (one call, returns `{code: url}` for
|
|
59
|
+
* all 249 flags) and pass results through `src`, instead of letting each `<lr-flag>` instance
|
|
60
|
+
* independently call `flagUrl()` — this skips one peer-resolution round trip per instance. Image
|
|
61
|
+
* fetches themselves are unaffected either way (each flag is a distinct asset; there is no sprite).
|
|
62
|
+
* Or import `flag-peer-bulk.js` instead of `flag-peer.js` (never both) to get this automatically,
|
|
63
|
+
* registering a resolver backed by one shared `flagUrls()` call — worthwhile only when the page
|
|
64
|
+
* renders most/all flags; a page with a handful pays an unneeded 249-entry fetch.
|
|
65
|
+
*
|
|
66
|
+
* **Sizing:** the host has no intrinsic `width` — it sizes from `font-size` (`block-size: 1em`,
|
|
67
|
+
* `inline-size` derived from `--lr-flag-aspect-ratio` via CSS `aspect-ratio`), so `<lr-flag>` scales
|
|
68
|
+
* naturally with surrounding text (e.g. `style="font-size: 2rem"`). Do not set `width`/`inline-size`
|
|
69
|
+
* directly: making both axes definite defeats `aspect-ratio` (which only participates when at most
|
|
70
|
+
* one axis is definite per the CSS sizing spec), squashing the image instead of scaling it.
|
|
71
|
+
*
|
|
44
72
|
* The ~65 flags whose design includes a detailed coat of arms/seal/emblem (e.g. `es`, `pt`) ship
|
|
45
73
|
* three fidelity tiers; choose one with `fidelity`: `"compact"` (a tiny WebP raster for icon-scale
|
|
46
74
|
* use — menu items, language selectors, dense lists), the default `"standard"` (icon-optimized
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}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 resolverFactoryFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.createFlagUrlResolver;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.createFlagUrlResolver;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadBulkFlagUrl(importFlags){try{const factory=resolverFactoryFromModule(await importFlags());if(factory)return factory();throw new TypeError("The flag peer does not expose a callable createFlagUrlResolver capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
|
|
2
2
|
>${this.fallback?html`<img part="fallback-image" src=${this.fallback} alt=${this.label??""} />`:nothing}</slot
|
|
3
3
|
>`;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
|
|
4
4
|
${state2.status==="loading"?html`
|
|
@@ -15,4 +15,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
15
15
|
@load=${event=>this.onImageLoad(event,state2.identity,url,request)}
|
|
16
16
|
@error=${event=>this.onImageError(event,state2.identity,request)}
|
|
17
17
|
/>`):null}
|
|
18
|
-
`}}__decorate([property()],LyraFlag.prototype,"country",void 0),__decorate([property()],LyraFlag.prototype,"fallback",void 0),__decorate([property()],LyraFlag.prototype,"language",void 0),__decorate([property()],LyraFlag.prototype,"src",void 0),__decorate([property()],LyraFlag.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraFlag.prototype,"shape",null),__decorate([property({reflect:!0})],LyraFlag.prototype,"fidelity",null),__decorate([state()],LyraFlag.prototype,"sourceState",void 0),__decorate([state()],LyraFlag.prototype,"resolverGeneration",void 0);export{LyraFlag,loadFlagUrl,setFlagUrlResolver};
|
|
18
|
+
`}}__decorate([property()],LyraFlag.prototype,"country",void 0),__decorate([property()],LyraFlag.prototype,"fallback",void 0),__decorate([property()],LyraFlag.prototype,"language",void 0),__decorate([property()],LyraFlag.prototype,"src",void 0),__decorate([property()],LyraFlag.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraFlag.prototype,"shape",null),__decorate([property({reflect:!0})],LyraFlag.prototype,"fidelity",null),__decorate([state()],LyraFlag.prototype,"sourceState",void 0),__decorate([state()],LyraFlag.prototype,"resolverGeneration",void 0);export{LyraFlag,loadBulkFlagUrl,loadFlagUrl,setFlagUrlResolver};
|