@aceshooting/lyra-ui 8.0.0 → 8.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 +199 -17
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
- package/dist/components/agent-tools/terminal/terminal.class.js +2 -2
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +5 -0
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -0
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/query-builder/query-builder.class.js +2 -2
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +8 -3
- package/dist/components/data/tree/tree-item.styles.js +11 -3
- package/dist/components/data/tree/tree.class.d.ts +11 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +3 -0
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -0
- package/dist/components/forms/locale-picker/locale-picker.class.js +4 -3
- package/dist/components/forms/locale-picker/locale-picker.styles.js +4 -0
- package/dist/components/forms/radio/radio-group.class.d.ts +3 -0
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +3 -0
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +9 -0
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/avatar/avatar.class.js +2 -2
- package/dist/components/media/flag/flag.class.js +2 -2
- package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +3 -2
- package/dist/components/viewers/page-rail/page-rail.class.js +2 -0
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/internal/anchor-target.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/safe-svg.d.ts +13 -0
- package/dist/internal/safe-svg.js +1 -0
- package/dist/testing/happy-dom-shims.d.ts +4 -0
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-attachment-chip.md +18 -10
- package/llms/components/lr-checkbox-group.md +2 -0
- package/llms/components/lr-graph-query-builder.md +3 -1
- package/llms/components/lr-locale-picker.md +6 -4
- package/llms/components/lr-radio-group.md +3 -1
- package/llms/components/lr-rubric-form.md +2 -0
- package/llms/components/lr-tool-param-form.md +3 -0
- package/llms/peers.md +3 -3
- package/llms-full.txt +36 -15
- package/package.json +9 -8
- package/vscode-html-data.json +7 -7
- package/web-types.json +8 -8
|
@@ -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--)if(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{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";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:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.locales=[];this.showFlags=true;this.label="";this.hint="";this.errorText="";this.open=false;this.size="m";this.activeIndex=-1;this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.registryTick=0;this.listId=nextId("locale-picker-list");this.controlId=nextId("locale-picker-control");this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{event.stopPropagation();this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onTriggerFocus=event=>{event.stopPropagation();this.emit("focus")};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onKeyDown=e=>{const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commit(activeRow.tag)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const tag=optionEl?.dataset["value"];if(tag===void 0)return;this.commit(tag)};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",void 0,init));this.internals.setFormValue("")}focus(options){this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.triggerElement?.click()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1});if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.stopRegistrySubscription?.();this.stopRegistrySubscription=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){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.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label")}}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){if(this.isBarred()){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("localePickerRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid);this.requestUpdate()}get normalizedEntries(){const raw=this.locales;if(raw&&raw.length>0){return raw.map(entry=>typeof entry==="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country})}return getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}labelFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)?.label??localeNativeName(tag)}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.cleanup?.();this.cleanup=void 0;if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.cleanup=place(anchor,listbox)}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick"));if(reposition){this.syncPopup()}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}commit(tag){const previousValue=this._value;this.value=tag;this.hide();const event=this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:true});if(!event.defaultPrevented)setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag;const currentIndex=rows.findIndex(r=>r.tag===currentTag);const n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else{this.commit(row.tag)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.tag===this._value;return html`<div
|
|
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--)if(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{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";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:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.locales=[];this.showFlags=true;this.label="";this.hint="";this.errorText="";this.open=false;this.size="m";this.activeIndex=-1;this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.registryTick=0;this.listId=nextId("locale-picker-list");this.controlId=nextId("locale-picker-control");this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{event.stopPropagation();this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onTriggerFocus=event=>{event.stopPropagation();this.emit("focus")};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onKeyDown=e=>{const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commit(activeRow.tag)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const tag=optionEl?.dataset["value"];if(tag===void 0)return;this.commit(tag)};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",void 0,init));this.internals.setFormValue("")}focus(options){this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.triggerElement?.click()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1});if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.stopRegistrySubscription?.();this.stopRegistrySubscription=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){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.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label")}}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){if(this.isBarred()){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("localePickerRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid);this.requestUpdate()}get normalizedEntries(){const raw=this.locales;if(raw&&raw.length>0){return raw.map(entry=>typeof entry==="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country})}return getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.cleanup?.();this.cleanup=void 0;if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.cleanup=place(anchor,listbox)}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick"));if(reposition){this.syncPopup()}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}commit(tag){const previousValue=this._value;this.value=tag;this.hide();const event=this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:true});if(!event.defaultPrevented)setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag;const currentIndex=rows.findIndex(r=>r.tag===currentTag);const n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else{this.commit(row.tag)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
11
11
|
<span>${entry.label}</span>
|
|
12
12
|
<span part="option-tag">${entry.tag}</span>
|
|
13
13
|
</span>
|
|
14
|
-
</div>`})}render(){const rows=this.normalizedEntries;const activeId=this.activeIndex>=0&&rows[this.activeIndex]?`${this.listId}-opt-${this.activeIndex}`:"";const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"locale-picker-error":"",hasHint?"locale-picker-hint":""].filter(Boolean).join(" ");return html`
|
|
14
|
+
</div>`})}render(){const rows=this.normalizedEntries;const activeId=this.activeIndex>=0&&rows[this.activeIndex]?`${this.listId}-opt-${this.activeIndex}`:"";const previewTag=this.previewTag;const previewEntry=this.entryFor(previewTag);const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"locale-picker-error":"",hasHint?"locale-picker-hint":""].filter(Boolean).join(" ");return html`
|
|
15
15
|
<div part="form-control">
|
|
16
16
|
<label part="form-control-label" for=${this.controlId} ?hidden=${!hasLabel}>
|
|
17
17
|
${this.label}<slot name="label" @slotchange=${this.onLabelSlotChange}></slot>
|
|
@@ -35,7 +35,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
35
35
|
@focus=${this.onTriggerFocus}
|
|
36
36
|
@blur=${this.onTriggerBlur}
|
|
37
37
|
>
|
|
38
|
-
|
|
38
|
+
${this.showFlags?previewEntry?.country?html`<lr-flag part="trigger-flag" country=${previewEntry.country} variant="compact" aria-hidden="true"></lr-flag>`:html`<lr-flag part="trigger-flag" language=${previewTag} variant="compact" aria-hidden="true"></lr-flag>`:""}
|
|
39
|
+
<span class="trigger-label">${this.labelFor(previewTag)}</span>
|
|
39
40
|
<span part="expand-icon" aria-hidden="true">${chevronIcon()}</span>
|
|
40
41
|
</button>
|
|
41
42
|
<div
|
|
@@ -193,6 +193,9 @@ export declare class LyraRadioGroup extends LyraElement<LyraRadioGroupEventMap>
|
|
|
193
193
|
private onRadioSlotChange;
|
|
194
194
|
/** Moves focus to the selected enabled option, or the first enabled option when empty. */
|
|
195
195
|
focus(options?: FocusOptions): void;
|
|
196
|
+
/** Activates the selected/first enabled option, matching host click semantics on the internal
|
|
197
|
+
* radio collection rather than leaving `<lr-radio-group>` a no-op. */
|
|
198
|
+
click(): void;
|
|
196
199
|
private syncFormState;
|
|
197
200
|
/** Shared with every other form control: disabled (own or fieldset-cascaded) bars validation. */
|
|
198
201
|
private get barredFromValidation();
|
|
@@ -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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_radioRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,radioRequired:LYRA_DEFAULT_radioRequired,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},customError:{attribute:"custom-error",reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},orientation:{reflect:true},form:{noAccessor:true}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.syncFormState();this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=true;this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty){this.selectValue(this._defaultValue);this._valueDirty=false}this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){if(this.reflectingCustomError)return;const old=this.customError;const message=next??"";this.reflectingCustomError=true;try{if(next==null)this.removeAttribute("custom-error");else this.setAttribute("custom-error",message)}finally{this.reflectingCustomError=false}this.setCustomValidity(message);this.requestUpdate("customError",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.syncRadios();this.updateValidity();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.syncRadios();this.updateValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}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}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.helpText="";this.shoelaceDefaultValue="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.labelId=nextId("radio-group-label");this.hintId=nextId("radio-group-hint");this.errorId=nextId("radio-group-error");this.managedRadios=new Set;this.authorNames=new Map;this.syncingRadios=false;this.membershipObserverGeneration=0;this._name="";this._value="";this._defaultValue="";this._valueDirty=false;this.reflectingDefaultValue=false;this.reflectingCustomError=false;this._required=false;this._disabled=false;this._fieldsetDisabled=false;this.hasInteracted=false;this.hadShoelaceDefaultValue=false;this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target))){return}const alias=this.emit("lr-invalid",void 0,{cancelable:true});if(alias.defaultPrevented)event.preventDefault()};this.onKeyDown=event=>{const arrows=this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"];if(![...arrows,"Home","End"].includes(event.key))return;if(this.effectiveDisabled)return;const radios=this.radios().filter(radio=>!radio.effectiveDisabled);const current=event.target;if(current.effectiveDisabled)return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl";const forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight";const backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft";const nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index;const next=radios[nextIndex];next.focus();next.activateFromGroup()};this.onSlotChange=event=>{const slot=event.target;const elements=slot.assignedElements({flatten:true});if(slot.name==="label")this.hasLabelSlot=elements.length>0;if(slot.name==="hint")this.hasHintSlot=elements.length>0;if(slot.name==="help-text")this.hasHelpTextSlot=elements.length>0;if(slot.name==="error")this.hasErrorSlot=elements.length>0};this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument;const generation=this.membershipObserverGeneration;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;ownerWindow.queueMicrotask(()=>{if(this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument){this.syncRadios()}})};this.internals=attachInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());this.addEventListener("invalid",this.onInvalid,true);this.syncFormState();this.updateValidity()}connectedCallback(){super.connectedCallback();this.syncSupportSlots();this.syncRadios();this.armMembershipObserver()}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument.defaultView;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration;const observer=new MutationObserverCtor(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}ownerWindow.queueMicrotask(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.syncRadios()})});this.membershipObserver=observer;this.membershipObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["slot","checked","disabled","value","size"]})}disconnectedCallback(){this.resetMembershipObserver();this.releaseRadios(this.managedRadios);this.managedRadios.clear();super.disconnectedCallback()}adoptedCallback(){this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1;this.membershipObserver?.disconnect();this.membershipObserver=void 0;this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)){this.defaultValue=this.shoelaceDefaultValue;this.hadShoelaceDefaultValue=this.hasAttribute("default-value")}}updated(changed){super.updated(changed);this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner==="function")}selectValue(next){const desired=next??"";const radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired;this.pendingSelection=desired;this.syncFormState();this.updateValidity();this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=true;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=false}this.pendingSelection=void 0;this.syncRadios(match)}syncRadios(preferred){if(this.syncingRadios)return;this.syncingRadios=true;try{const radios=this.radios();const current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios){radio.setGroupOwner(this);if(!this.managedRadios.has(radio)){this.authorNames.set(radio,radio.name)}}this.managedRadios=current;for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>!radio.effectiveDisabled);let checked=radios.filter(radio=>radio.checked);let checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked=radio===checkedRadio;checked=checkedRadio?[checkedRadio]:[];this.pendingSelection=void 0}else{checkedRadio=preferred?.checked&¤t.has(preferred)?preferred:checked[checked.length-1]}for(const radio of checked){if(radio!==checkedRadio)radio.checked=false}const tabbableRadio=checkedRadio&&!checkedRadio.effectiveDisabled?checkedRadio:enabled[0];for(const radio of radios){radio.name=this.name||this.authorNames.get(radio)||"";radio.size=this.size;radio.setGroupRequired(this.required&&!this.effectiveDisabled);radio.setGroupTabbable(radio===tabbableRadio)}const oldValue=this._value;this._value=checkedRadio?.value??"";this.syncFormState();this.updateValidity();if(oldValue!==this._value)this.requestUpdate("value",oldValue)}finally{this.syncingRadios=false}}releaseRadios(radios){for(const radio of radios){const authorName=this.authorNames.get(radio)??radio.name;this.authorNames.delete(radio);radio.releaseGroupOwner(this,authorName)}}reconcileRadio(radio){if(!this.ownsRadio(radio))return false;this.syncRadios(radio.checked?radio:void 0);return true}releaseRadio(radio){if(!this.managedRadios.has(radio)&&!this.authorNames.has(radio))return;this.releaseRadios([radio]);this.managedRadios.delete(radio);this.syncRadios()}radioCheckedChanged(radio){if(this.syncingRadios||!this.ownsRadio(radio))return;this._valueDirty=true;this.syncRadios(radio.checked?radio:void 0)}selectRadio(radio){if(this.effectiveDisabled||radio.effectiveDisabled||!this.ownsRadio(radio))return false;this._valueDirty=true;this.hasInteracted=true;this.syncingRadios=true;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=false}this.syncRadios();dispatchNativeInputEvent(this);this.emit("lr-input",{value:radio.value,radio});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:radio.value,radio});return true}focus(options){const enabled=this.radios().filter(radio=>!radio.effectiveDisabled);(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){if(!this.internals)return;this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:true}:{},missing?this.localize("radioRequired"):"");this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.updateValidity();return this.internals.reportValidity()}setCustomValidity(message=""){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity();this.requestUpdate()}formResetCallback(){this._valueDirty=false;this.pendingSelection=void 0;this.syncingRadios=true;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=false}if(this.defaultValue)this.pendingSelection=this.defaultValue;this.hasInteracted=false;this.syncRadios()}formStateRestoreCallback(state2,reason){void reason;this._valueDirty=true;this.hasInteracted=false;this.pendingSelection=typeof state2==="string"?state2:"";this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncRadios();this.updateValidity();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText)||this.withHint;const hasError=this.hasErrorSlot||Boolean(this.errorText);const described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_radioRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,radioRequired:LYRA_DEFAULT_radioRequired,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},customError:{attribute:"custom-error",reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},orientation:{reflect:true},form:{noAccessor:true}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.syncFormState();this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=true;this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty){this.selectValue(this._defaultValue);this._valueDirty=false}this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){if(this.reflectingCustomError)return;const old=this.customError;const message=next??"";this.reflectingCustomError=true;try{if(next==null)this.removeAttribute("custom-error");else this.setAttribute("custom-error",message)}finally{this.reflectingCustomError=false}this.setCustomValidity(message);this.requestUpdate("customError",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.syncRadios();this.updateValidity();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.syncRadios();this.updateValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}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}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.helpText="";this.shoelaceDefaultValue="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.labelId=nextId("radio-group-label");this.hintId=nextId("radio-group-hint");this.errorId=nextId("radio-group-error");this.managedRadios=new Set;this.authorNames=new Map;this.syncingRadios=false;this.membershipObserverGeneration=0;this._name="";this._value="";this._defaultValue="";this._valueDirty=false;this.reflectingDefaultValue=false;this.reflectingCustomError=false;this._required=false;this._disabled=false;this._fieldsetDisabled=false;this.hasInteracted=false;this.hadShoelaceDefaultValue=false;this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target))){return}const alias=this.emit("lr-invalid",void 0,{cancelable:true});if(alias.defaultPrevented)event.preventDefault()};this.onKeyDown=event=>{const arrows=this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"];if(![...arrows,"Home","End"].includes(event.key))return;if(this.effectiveDisabled)return;const radios=this.radios().filter(radio=>!radio.effectiveDisabled);const current=event.target;if(current.effectiveDisabled)return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl";const forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight";const backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft";const nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index;const next=radios[nextIndex];next.focus();next.activateFromGroup()};this.onSlotChange=event=>{const slot=event.target;const elements=slot.assignedElements({flatten:true});if(slot.name==="label")this.hasLabelSlot=elements.length>0;if(slot.name==="hint")this.hasHintSlot=elements.length>0;if(slot.name==="help-text")this.hasHelpTextSlot=elements.length>0;if(slot.name==="error")this.hasErrorSlot=elements.length>0};this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument;const generation=this.membershipObserverGeneration;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;ownerWindow.queueMicrotask(()=>{if(this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument){this.syncRadios()}})};this.internals=attachInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());this.addEventListener("invalid",this.onInvalid,true);this.syncFormState();this.updateValidity()}connectedCallback(){super.connectedCallback();this.syncSupportSlots();this.syncRadios();this.armMembershipObserver()}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument.defaultView;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration;const observer=new MutationObserverCtor(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}ownerWindow.queueMicrotask(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.syncRadios()})});this.membershipObserver=observer;this.membershipObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["slot","checked","disabled","value","size"]})}disconnectedCallback(){this.resetMembershipObserver();this.releaseRadios(this.managedRadios);this.managedRadios.clear();super.disconnectedCallback()}adoptedCallback(){this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1;this.membershipObserver?.disconnect();this.membershipObserver=void 0;this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)){this.defaultValue=this.shoelaceDefaultValue;this.hadShoelaceDefaultValue=this.hasAttribute("default-value")}}updated(changed){super.updated(changed);this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner==="function")}selectValue(next){const desired=next??"";const radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired;this.pendingSelection=desired;this.syncFormState();this.updateValidity();this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=true;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=false}this.pendingSelection=void 0;this.syncRadios(match)}syncRadios(preferred){if(this.syncingRadios)return;this.syncingRadios=true;try{const radios=this.radios();const current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios){radio.setGroupOwner(this);if(!this.managedRadios.has(radio)){this.authorNames.set(radio,radio.name)}}this.managedRadios=current;for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>!radio.effectiveDisabled);let checked=radios.filter(radio=>radio.checked);let checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked=radio===checkedRadio;checked=checkedRadio?[checkedRadio]:[];this.pendingSelection=void 0}else{checkedRadio=preferred?.checked&¤t.has(preferred)?preferred:checked[checked.length-1]}for(const radio of checked){if(radio!==checkedRadio)radio.checked=false}const tabbableRadio=checkedRadio&&!checkedRadio.effectiveDisabled?checkedRadio:enabled[0];for(const radio of radios){radio.name=this.name||this.authorNames.get(radio)||"";radio.size=this.size;radio.setGroupRequired(this.required&&!this.effectiveDisabled);radio.setGroupTabbable(radio===tabbableRadio)}const oldValue=this._value;this._value=checkedRadio?.value??"";this.syncFormState();this.updateValidity();if(oldValue!==this._value)this.requestUpdate("value",oldValue)}finally{this.syncingRadios=false}}releaseRadios(radios){for(const radio of radios){const authorName=this.authorNames.get(radio)??radio.name;this.authorNames.delete(radio);radio.releaseGroupOwner(this,authorName)}}reconcileRadio(radio){if(!this.ownsRadio(radio))return false;this.syncRadios(radio.checked?radio:void 0);return true}releaseRadio(radio){if(!this.managedRadios.has(radio)&&!this.authorNames.has(radio))return;this.releaseRadios([radio]);this.managedRadios.delete(radio);this.syncRadios()}radioCheckedChanged(radio){if(this.syncingRadios||!this.ownsRadio(radio))return;this._valueDirty=true;this.syncRadios(radio.checked?radio:void 0)}selectRadio(radio){if(this.effectiveDisabled||radio.effectiveDisabled||!this.ownsRadio(radio))return false;this._valueDirty=true;this.hasInteracted=true;this.syncingRadios=true;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=false}this.syncRadios();dispatchNativeInputEvent(this);this.emit("lr-input",{value:radio.value,radio});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:radio.value,radio});return true}focus(options){const enabled=this.radios().filter(radio=>!radio.effectiveDisabled);(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}click(){if(this.effectiveDisabled)return;const enabled=this.radios().filter(radio=>!radio.effectiveDisabled);(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){if(!this.internals)return;this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:true}:{},missing?this.localize("radioRequired"):"");this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.updateValidity();return this.internals.reportValidity()}setCustomValidity(message=""){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity();this.requestUpdate()}formResetCallback(){this._valueDirty=false;this.pendingSelection=void 0;this.syncingRadios=true;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=false}if(this.defaultValue)this.pendingSelection=this.defaultValue;this.hasInteracted=false;this.syncRadios()}formStateRestoreCallback(state2,reason){void reason;this._valueDirty=true;this.hasInteracted=false;this.pendingSelection=typeof state2==="string"?state2:"";this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncRadios();this.updateValidity();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText)||this.withHint;const hasError=this.hasErrorSlot||Boolean(this.errorText);const described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`
|
|
2
2
|
<div part="base" role="radiogroup"
|
|
3
3
|
aria-label=${this.accessibleLabel||nothing}
|
|
4
4
|
aria-labelledby=${!this.accessibleLabel&&hasLabel?this.labelId:nothing}
|
|
@@ -258,6 +258,9 @@ export declare class LyraRubricForm extends LyraElement<LyraRubricFormEventMap>
|
|
|
258
258
|
private submit;
|
|
259
259
|
private skip;
|
|
260
260
|
private focusFirstControl;
|
|
261
|
+
/** Forwards host clicks to the first rendered field, so programmatic and `<label>`-driven
|
|
262
|
+
* interactions target the active rubric field. */
|
|
263
|
+
click(): void;
|
|
261
264
|
protected updated(changed: PropertyValues): void;
|
|
262
265
|
private renderScoreControl;
|
|
263
266
|
private renderCategoryControl;
|
|
@@ -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--)if(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{state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[];const EMPTY_VALUE={};class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},keys:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},itemId:{attribute:"item-id",reflect:true,noAccessor:true},hasNext:{type:Boolean,attribute:"has-next",noAccessor:true},skippable:{type:Boolean,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this.touchedFields=new Set;this.baseId=nextId("rubric-form");this._fieldsetDisabled=false;this._name="";this._keys=EMPTY_KEYS;this._value=EMPTY_VALUE;this._itemId="";this._hasNext=false;this._skippable=false;this._disabled=false;this.pendingFocusFirst=false;this.onFormKeyDown=e=>{if(e.key==="Enter"&&(e.ctrlKey||e.metaKey)){e.preventDefault();this.submit()}};this.stopChildEvent=event=>{event.stopPropagation()};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.addEventListener("keydown",this.onFormKeyDown);this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}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 keys(){return this._keys}set keys(next){const old=this._keys;this._keys=next??EMPTY_KEYS;this.syncFormState();this.requestUpdate("keys",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??EMPTY_VALUE;this.syncFormState();this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"";if(old!==this._itemId){this.touchedFields=new Set;if(this.hasUpdated)this.pendingFocusFirst=true}if(this._itemId)this.setAttribute("item-id",this._itemId);else this.removeAttribute("item-id");this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=Boolean(next);this.toggleAttribute("has-next",this._hasNext);this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=Boolean(next);this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}fieldElement(key){const root=this.renderRoot;const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape==="function"){try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];if(!firstInvalidKey||!this.renderRoot)return void 0;const field=this.fieldElement(firstInvalidKey);return field?.querySelector(".control")??void 0}isSegmentedScore(k){const min=k.min??0;const max=k.max??5;const step=k.step??1;if(step<=0||!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return false;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}scoreValues(k){if(!this.isSegmentedScore(k))return[];const min=k.min??0;const max=k.max??5;const step=k.step??1;const count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={};const flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){errors[k.key]=this.localize("unsupportedFieldType",void 0,{type:String(k.type)});flags.customError=true;continue}if(!k.required)continue;const v=this._value[k.key];const present=k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="";if(!present){errors[k.key]=this.localize("fieldRequired");flags.valueMissing=true}}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>Boolean(key.required)),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]);this.syncCustomStates()}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.requestUpdate()}formResetCallback(){this.value={};this.touchedFields=new Set;this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))restored=parsed}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}setFieldValue(key,val){if(this.effectiveDisabled)return;this.value={...this._value,[key]:val};this.emit("lr-input",{value:{...this._value}})}markTouched(key){if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key);this.syncCustomStates()}submit(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-submit",{value:{...this._value},itemId:this.itemId})}skip(){if(this.effectiveDisabled)return;this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const field=this.fieldElement(firstKey.key);const control=field?.querySelector(".control");if(!control)return;if(firstKey.type==="score"&&this.isSegmentedScore(firstKey)){control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus()}else if(firstKey.type==="score"){control.shadowRoot?.querySelector('[part="thumb"]')?.focus()}else if(firstKey.type==="category"&&firstKey.multiple){control.querySelector("lr-checkbox")?.focus()}else{control.focus()}}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("keys")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}if(this.pendingFocusFirst){this.pendingFocusFirst=false;this.focusFirstControl()}}renderScoreControl(k,fieldId,current,hasError){const min=k.min??0;const max=k.max??5;const step=k.step??1;const disabled=this.effectiveDisabled;const accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>Boolean(value)).join(". ");if(this.isSegmentedScore(k)){const items=this.scoreValues(k).map(score=>({value:String(score),label:String(score),disabled}));const value=typeof current==="number"?String(current):"";return html`<lr-segmented
|
|
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--)if(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{state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[];const EMPTY_VALUE={};class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},keys:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},itemId:{attribute:"item-id",reflect:true,noAccessor:true},hasNext:{type:Boolean,attribute:"has-next",noAccessor:true},skippable:{type:Boolean,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this.touchedFields=new Set;this.baseId=nextId("rubric-form");this._fieldsetDisabled=false;this._name="";this._keys=EMPTY_KEYS;this._value=EMPTY_VALUE;this._itemId="";this._hasNext=false;this._skippable=false;this._disabled=false;this.pendingFocusFirst=false;this.onFormKeyDown=e=>{if(e.key==="Enter"&&(e.ctrlKey||e.metaKey)){e.preventDefault();this.submit()}};this.stopChildEvent=event=>{event.stopPropagation()};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.addEventListener("keydown",this.onFormKeyDown);this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}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 keys(){return this._keys}set keys(next){const old=this._keys;this._keys=next??EMPTY_KEYS;this.syncFormState();this.requestUpdate("keys",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??EMPTY_VALUE;this.syncFormState();this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"";if(old!==this._itemId){this.touchedFields=new Set;if(this.hasUpdated)this.pendingFocusFirst=true}if(this._itemId)this.setAttribute("item-id",this._itemId);else this.removeAttribute("item-id");this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=Boolean(next);this.toggleAttribute("has-next",this._hasNext);this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=Boolean(next);this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}fieldElement(key){const root=this.renderRoot;const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape==="function"){try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];if(!firstInvalidKey||!this.renderRoot)return void 0;const field=this.fieldElement(firstInvalidKey);return field?.querySelector(".control")??void 0}isSegmentedScore(k){const min=k.min??0;const max=k.max??5;const step=k.step??1;if(step<=0||!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return false;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}scoreValues(k){if(!this.isSegmentedScore(k))return[];const min=k.min??0;const max=k.max??5;const step=k.step??1;const count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={};const flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){errors[k.key]=this.localize("unsupportedFieldType",void 0,{type:String(k.type)});flags.customError=true;continue}if(!k.required)continue;const v=this._value[k.key];const present=k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="";if(!present){errors[k.key]=this.localize("fieldRequired");flags.valueMissing=true}}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>Boolean(key.required)),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]);this.syncCustomStates()}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.requestUpdate()}formResetCallback(){this.value={};this.touchedFields=new Set;this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))restored=parsed}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}setFieldValue(key,val){if(this.effectiveDisabled)return;this.value={...this._value,[key]:val};this.emit("lr-input",{value:{...this._value}})}markTouched(key){if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key);this.syncCustomStates()}submit(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-submit",{value:{...this._value},itemId:this.itemId})}skip(){if(this.effectiveDisabled)return;this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const field=this.fieldElement(firstKey.key);const control=field?.querySelector(".control");if(!control)return;if(firstKey.type==="score"&&this.isSegmentedScore(firstKey)){control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus()}else if(firstKey.type==="score"){control.shadowRoot?.querySelector('[part="thumb"]')?.focus()}else if(firstKey.type==="category"&&firstKey.multiple){control.querySelector("lr-checkbox")?.focus()}else{control.focus()}}click(){if(this.effectiveDisabled)return;this.focusFirstControl()}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("keys")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}if(this.pendingFocusFirst){this.pendingFocusFirst=false;this.focusFirstControl()}}renderScoreControl(k,fieldId,current,hasError){const min=k.min??0;const max=k.max??5;const step=k.step??1;const disabled=this.effectiveDisabled;const accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>Boolean(value)).join(". ");if(this.isSegmentedScore(k)){const items=this.scoreValues(k).map(score=>({value:String(score),label:String(score),disabled}));const value=typeof current==="number"?String(current):"";return html`<lr-segmented
|
|
2
2
|
id=${fieldId}
|
|
3
3
|
class="control"
|
|
4
4
|
part="scale"
|
|
@@ -51,6 +51,15 @@ import{css}from"lit";const styles=css`
|
|
|
51
51
|
[part~='track'] {
|
|
52
52
|
position: relative;
|
|
53
53
|
flex: 0 0 auto;
|
|
54
|
+
/* content-box, not the library-wide border-box default: the thumb is absolutely positioned
|
|
55
|
+
against this element's padding box, and its own size/travel math (below) is derived from
|
|
56
|
+
these same declared dimensions. Under border-box, a consumer-added ::part(track) border
|
|
57
|
+
would eat into the padding box without the thumb shrinking to match, breaking clearance
|
|
58
|
+
symmetry on the far edge. content-box keeps the padding box exactly this declared size
|
|
59
|
+
regardless of any border width, so an added border grows the track's outer footprint
|
|
60
|
+
instead -- the same "sits outside, doesn't touch the fill" effect the docs already point
|
|
61
|
+
consumers wanting a rim toward via outline. */
|
|
62
|
+
box-sizing: content-box;
|
|
54
63
|
inline-size: var(--width, var(--lr-switch-track-inline-size));
|
|
55
64
|
block-size: var(--height, var(--lr-switch-track-block-size));
|
|
56
65
|
border-radius: var(--lr-radius-pill);
|
|
@@ -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--)if(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,state}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{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_open,LYRA_DEFAULT_removeWithContext}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";const ICON_STROKE_WIDTH="1.75";function retryIcon(){return svg`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(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,state}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_open,LYRA_DEFAULT_removeWithContext}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";const 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){if(status==="error")return uploadFailedLabel;if(status==="uploading")return uploadingText;return""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments);this.name="";this.bytes=0;this.mimeType="";this.thumbnailSrc="";this.previewSrc="";this.previewable=true;this.status="pending";this.progress=0;this.removable=true;this.compact=false;this.thumbnailOnly=false;this.removeLabel="Remove";this.retryLabel="Retry";this.uploadingLabel="Uploading";this.uploadFailedLabel="Upload failed";this.untitledLabel="Untitled file";this.previewOpen=false;this.fallbackId=nextId("attachment-chip");this.onRemoveClick=()=>{this.emit("lr-remove",{id:this.resolvedId})};this.onRetryClick=()=>{this.emit("lr-retry",{id:this.resolvedId})};this.onPreviewClick=()=>{if(!this.effectivePreviewSrc)return;this.previewOpen=true;this.emit("lr-preview",{id:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})};this.onViewerClose=()=>{this.previewOpen=false}}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,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext}}static{this.styles=[LyraElement.styles,styles]}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?this.file.size:finiteRange(this.bytes,0,0)}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){if(this.id)return this.id;if(this.file)return`${this.file.name}:${this.file.size}:${this.file.lastModified}`;return this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}ensureObjectUrl(file){if(this.objectUrlFile===file&&this.objectUrl)return this.objectUrl;this.revokeObjectUrl();this.objectUrl=URL.createObjectURL(file);this.objectUrlFile=file;return this.objectUrl}revokeObjectUrl(){if(this.objectUrl)URL.revokeObjectURL(this.objectUrl);this.objectUrl=void 0;this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback();this.syncAnnouncementSink();if(this.hasUpdated)this.requestUpdate()}adoptedCallback(){this.releaseAnnouncementSink();this.syncAnnouncementSink()}syncAnnouncementSink(){if(!this.isConnected)return;if(this.sink?.element.ownerDocument===this.ownerDocument)return;this.releaseAnnouncementSink();this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseAnnouncementSink(){this.sink?.release();this.sink=void 0}willUpdate(changed){if(this.hasUpdated&&(changed.has("file")||changed.has("previewSrc")||changed.has("mimeType")||changed.has("name"))){this.previewOpen=false}if(this.hasUpdated&&changed.has("status")&&this.status==="error"){this.sink?.announce(this.localizedUploadFailedLabel)}if(this.file&&(this.file.type.startsWith("image/")||this.previewable))this.ensureObjectUrl(this.file);else if(this.objectUrlFile)this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback();this.previewOpen=false;this.revokeObjectUrl();this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.localize("attachmentUploadFailed",this.uploadFailedLabel==="Upload failed"?void 0:this.uploadFailedLabel)}renderThumbnail(){if(this.file){return this.effectiveMimeType.startsWith("image/")?html`<img src=${
|
|
14
|
+
`}function statusText(status,uploadingText,uploadFailedLabel){if(status==="error")return uploadFailedLabel;if(status==="uploading")return uploadingText;return""}class LyraAttachmentChip extends LyraElement{constructor(){super(...arguments);this.name="";this.bytes=0;this.mimeType="";this.thumbnailSrc="";this.previewSrc="";this.previewable=true;this.status="pending";this.progress=0;this.removable=true;this.compact=false;this.thumbnailOnly=false;this.removeLabel="Remove";this.retryLabel="Retry";this.uploadingLabel="Uploading";this.uploadFailedLabel="Upload failed";this.untitledLabel="Untitled file";this.previewOpen=false;this.fallbackId=nextId("attachment-chip");this.onRemoveClick=()=>{this.emit("lr-remove",{id:this.resolvedId})};this.onRetryClick=()=>{this.emit("lr-retry",{id:this.resolvedId})};this.onPreviewClick=()=>{if(!this.effectivePreviewSrc)return;this.previewOpen=true;this.emit("lr-preview",{id:this.resolvedId,name:this.effectiveName,mimeType:this.effectiveMimeType,src:this.effectivePreviewSrc})};this.onViewerClose=()=>{this.previewOpen=false}}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,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext}}static{this.styles=[LyraElement.styles,styles]}get effectiveName(){return this.file?this.file.name:this.name}get effectiveSize(){return this.file?this.file.size:finiteRange(this.bytes,0,0)}get effectiveMimeType(){return this.file?this.file.type:this.mimeType}get effectivePreviewSrc(){return this.file?this.objectUrl??"":this.previewSrc}get resolvedId(){if(this.id)return this.id;if(this.file)return`${this.file.name}:${this.file.size}:${this.file.lastModified}`;return this.fallbackId}get hasNumericProgress(){return this.status==="uploading"&&this.clampedProgress>0}get clampedProgress(){return finiteRange(this.progress,0,0,100)}ensureObjectUrl(file){if(this.objectUrlFile===file&&this.objectUrl)return this.objectUrl;this.revokeObjectUrl();this.objectUrl=URL.createObjectURL(file);this.objectUrlFile=file;return this.objectUrl}revokeObjectUrl(){if(this.objectUrl)URL.revokeObjectURL(this.objectUrl);this.objectUrl=void 0;this.objectUrlFile=void 0}connectedCallback(){super.connectedCallback();this.syncAnnouncementSink();if(this.hasUpdated)this.requestUpdate()}adoptedCallback(){this.releaseAnnouncementSink();this.syncAnnouncementSink()}syncAnnouncementSink(){if(!this.isConnected)return;if(this.sink?.element.ownerDocument===this.ownerDocument)return;this.releaseAnnouncementSink();this.sink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseAnnouncementSink(){this.sink?.release();this.sink=void 0}willUpdate(changed){if(this.hasUpdated&&(changed.has("file")||changed.has("previewSrc")||changed.has("mimeType")||changed.has("name"))){this.previewOpen=false}if(this.hasUpdated&&changed.has("status")&&this.status==="error"){this.sink?.announce(this.localizedUploadFailedLabel)}if(this.file&&(this.file.type.startsWith("image/")||this.previewable))this.ensureObjectUrl(this.file);else if(this.objectUrlFile)this.revokeObjectUrl()}disconnectedCallback(){super.disconnectedCallback();this.previewOpen=false;this.revokeObjectUrl();this.releaseAnnouncementSink()}get localizedUploadFailedLabel(){return this.localize("attachmentUploadFailed",this.uploadFailedLabel==="Upload failed"?void 0:this.uploadFailedLabel)}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;const untitledLabel=this.localize("attachmentUntitledFile",this.untitledLabel==="Untitled file"?void 0:this.untitledLabel);const displayName=name||untitledLabel;const sizeText=this.effectiveSize>0?formatFileSize(this.effectiveSize,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value)):"";const uploadFailedLabel=this.localizedUploadFailedLabel;const progressPercent=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0}).format(Math.round(this.clampedProgress));const uploadingText=this.hasNumericProgress?this.localize("attachmentUploadingProgress",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel} {percent}%`,{percent:progressPercent}):this.localize("attachmentUploadingIndeterminate",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel}\u2026`);const uploadingWithContext=this.localize("attachmentUploadingWithContext",this.uploadingLabel==="Uploading"?void 0:`${this.uploadingLabel} {label}`,{label:displayName});const retryWithContext=this.localize("attachmentRetryWithContext",this.retryLabel==="Retry"?void 0:`${this.retryLabel} {label}`,{label:displayName});const removeWithContext=this.localize("removeWithContext",this.removeLabel==="Remove"?void 0:`${this.removeLabel} {label}`,{label:displayName});const text=statusText(this.status,uploadingText,uploadFailedLabel);const uploading=this.status==="uploading";return html`
|
|
15
15
|
<div part="base">
|
|
16
16
|
<span part="thumbnail" aria-hidden="true">${this.renderThumbnail()}</span>
|
|
17
17
|
<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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./avatar.styles.js";class LyraAvatar extends LyraElement{constructor(){super(...arguments);this.initials="";this.image="";this.label="";this.alt="";this.loading="eager";this.size="medium";this.shape="circle";this.variant="neutral";this.hasIcon=false;this.hasIconSlot=false;this.onImageError=event=>{const image=event.currentTarget;const failedSrc=image?.getAttribute("src");if(failedSrc)this.failedSrc=failedSrc;this.emit("lr-error",{image:failedSrc??this.image??""})};this.onIconSlotChange=e=>{this.hasIcon=this.hasDefaultSlotContent(e.target.assignedNodes({flatten:true}))};this.onNamedIconSlotChange=e=>{this.hasIconSlot=e.target.assignedNodes({flatten:true}).length>0}}static{this.styles=[LyraElement.styles,styles]}hasDefaultSlotContent(nodes){return Array.from(nodes).some(node=>{if(node.nodeType===1)return!node.hasAttribute("slot");return node.nodeType===3&&(node.textContent?.trim().length??0)>0})}hasIconSlotContent(nodes){return Array.from(nodes).some(node=>node.nodeType===1&&node.getAttribute("slot")==="icon")}willUpdate(changed){super.willUpdate(changed);if(changed.has("image"))this.failedSrc=void 0;this.seedFirstRenderState(()=>{this.hasIcon=this.hasDefaultSlotContent(this.childNodes);this.hasIconSlot=this.hasIconSlotContent(this.childNodes)})}render(){const showImage=!this.hasIcon&&!!
|
|
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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./avatar.styles.js";class LyraAvatar extends LyraElement{constructor(){super(...arguments);this.initials="";this.image="";this.label="";this.alt="";this.loading="eager";this.size="medium";this.shape="circle";this.variant="neutral";this.hasIcon=false;this.hasIconSlot=false;this.onImageError=event=>{const image=event.currentTarget;const failedSrc=image?.getAttribute("src");if(failedSrc)this.failedSrc=failedSrc;this.emit("lr-error",{image:failedSrc??this.image??""})};this.onIconSlotChange=e=>{this.hasIcon=this.hasDefaultSlotContent(e.target.assignedNodes({flatten:true}))};this.onNamedIconSlotChange=e=>{this.hasIconSlot=e.target.assignedNodes({flatten:true}).length>0}}static{this.styles=[LyraElement.styles,styles]}hasDefaultSlotContent(nodes){return Array.from(nodes).some(node=>{if(node.nodeType===1)return!node.hasAttribute("slot");return node.nodeType===3&&(node.textContent?.trim().length??0)>0})}hasIconSlotContent(nodes){return Array.from(nodes).some(node=>node.nodeType===1&&node.getAttribute("slot")==="icon")}willUpdate(changed){super.willUpdate(changed);if(changed.has("image"))this.failedSrc=void 0;this.seedFirstRenderState(()=>{this.hasIcon=this.hasDefaultSlotContent(this.childNodes);this.hasIconSlot=this.hasIconSlotContent(this.childNodes)})}render(){const safeImage=safeMediaSrc(this.image);const showImage=!this.hasIcon&&!!safeImage&&safeImage!==this.failedSrc;const showIconSlot=!this.hasIcon&&!showImage&&this.hasIconSlot;const showGlyph=this.hasIcon||showIconSlot;const showInitials=!showGlyph&&!showImage;const hostLabel=this.getAttribute("aria-label");const accessibleName=hostLabel===null?this.label||this.alt:hostLabel;const hasAccessibleFallback=(showGlyph||showInitials)&&accessibleName;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="base"
|
|
4
4
|
role=${hasAccessibleFallback?"img":nothing}
|
|
@@ -10,7 +10,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
10
10
|
></span>
|
|
11
11
|
${showImage?html`<img
|
|
12
12
|
part="image"
|
|
13
|
-
src=${
|
|
13
|
+
src=${safeImage}
|
|
14
14
|
alt=${accessibleName}
|
|
15
15
|
loading=${this.loading}
|
|
16
16
|
@error=${this.onImageError}
|
|
@@ -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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError";async function loadFlagUrl(importFlags){try{return(await importFlags()).flagUrl}catch{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`.");return null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver;let testFlagUrlResolver;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value)}function loadFlagUrlResolver(){if(testFlagUrlResolver)return testFlagUrlResolver;if(!flagUrlResolver){flagUrlResolver=Promise.resolve(null)}return flagUrlResolver}function __setFlagUrlResolverForTesting(value){testFlagUrlResolver=value}class LyraFlag extends LyraElement{constructor(){super(...arguments);this.accessibleLabel=null;this.round=false;this.loading=true;this.loadError=false;this.resolveToken=0}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}get effectiveVariant(){return this.variant??"standard"}get code(){if(this.country){return ALPHA2_RE.test(this.country)?this.country.toLowerCase():void 0}if(this.language)return languageToCountry(this.language);return void 0}connectedCallback(){super.connectedCallback();this.syncErrorAnnouncementSink()}disconnectedCallback(){this.releaseErrorAnnouncementSink();super.disconnectedCallback()}adoptedCallback(){this.releaseErrorAnnouncementSink();this.syncErrorAnnouncementSink()}syncErrorAnnouncementSink(){if(!this.isConnected)return;if(this.errorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;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))}willUpdate(changed){super.willUpdate(changed);if(this.hasUpdated&&!changed.has("country")&&!changed.has("language")&&!changed.has("src")&&!changed.has("variant")){return}const token=++this.resolveToken;if(this.src){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}const code=this.code;if(!code){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}this.resolvedSrc=void 0;this.loadError=false;this.loading=true;const variant=this.effectiveVariant;void loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken)return;if(!resolve){this.loadError=true;this.loading=false;this.announceLoadError();return}const url=await resolve(code,variant==="standard"?void 0:{variant});if(token!==this.resolveToken)return;this.resolvedSrc=url;this.loadError=false;this.loading=false}).catch(err=>{if(token!==this.resolveToken)return;console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err);this.resolvedSrc=void 0;this.loadError=true;this.loading=false;this.announceLoadError()})}updated(changed){super.updated(changed);this.setAttribute("aria-busy",String(this.loading))}render(){if(this.loading){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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError";async function loadFlagUrl(importFlags){try{return(await importFlags()).flagUrl}catch{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`.");return null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver;let testFlagUrlResolver;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value)}function loadFlagUrlResolver(){if(testFlagUrlResolver)return testFlagUrlResolver;if(!flagUrlResolver){flagUrlResolver=Promise.resolve(null)}return flagUrlResolver}function __setFlagUrlResolverForTesting(value){testFlagUrlResolver=value}class LyraFlag extends LyraElement{constructor(){super(...arguments);this.accessibleLabel=null;this.round=false;this.loading=true;this.loadError=false;this.resolveToken=0}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}get effectiveVariant(){return this.variant??"standard"}get code(){if(this.country){return ALPHA2_RE.test(this.country)?this.country.toLowerCase():void 0}if(this.language)return languageToCountry(this.language);return void 0}connectedCallback(){super.connectedCallback();this.syncErrorAnnouncementSink()}disconnectedCallback(){this.releaseErrorAnnouncementSink();super.disconnectedCallback()}adoptedCallback(){this.releaseErrorAnnouncementSink();this.syncErrorAnnouncementSink()}syncErrorAnnouncementSink(){if(!this.isConnected)return;if(this.errorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;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))}willUpdate(changed){super.willUpdate(changed);if(this.hasUpdated&&!changed.has("country")&&!changed.has("language")&&!changed.has("src")&&!changed.has("variant")){return}const token=++this.resolveToken;if(this.src){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}const code=this.code;if(!code){this.resolvedSrc=void 0;this.loadError=false;this.loading=false;return}this.resolvedSrc=void 0;this.loadError=false;this.loading=true;const variant=this.effectiveVariant;void loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken)return;if(!resolve){this.loadError=true;this.loading=false;this.announceLoadError();return}const url=await resolve(code,variant==="standard"?void 0:{variant});if(token!==this.resolveToken)return;this.resolvedSrc=url;this.loadError=false;this.loading=false}).catch(err=>{if(token!==this.resolveToken)return;console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err);this.resolvedSrc=void 0;this.loadError=true;this.loading=false;this.announceLoadError()})}updated(changed){super.updated(changed);this.setAttribute("aria-busy",String(this.loading))}render(){if(this.loading){return html`
|
|
2
2
|
<span class="sr-only">${this.localize("loading")}</span>
|
|
3
3
|
<lr-skeleton variant="rect" .announce=${false}></lr-skeleton>
|
|
4
|
-
`}if(this.loadError){return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`}const url=this.src??this.resolvedSrc;if(!url)return html``;const code=this.code;const alt=this.accessibleLabel??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`<img part="image" src=${url} alt=${alt} loading="lazy" decoding="async" />`}}__decorate([property()],LyraFlag.prototype,"country",void 0);__decorate([property()],LyraFlag.prototype,"language",void 0);__decorate([property()],LyraFlag.prototype,"src",void 0);__decorate([property({attribute:"aria-label"})],LyraFlag.prototype,"accessibleLabel",void 0);__decorate([property()],LyraFlag.prototype,"label",void 0);__decorate([property({type:Boolean,reflect:true})],LyraFlag.prototype,"round",void 0);__decorate([property()],LyraFlag.prototype,"variant",void 0);__decorate([state()],LyraFlag.prototype,"resolvedSrc",void 0);__decorate([state()],LyraFlag.prototype,"loading",void 0);__decorate([state()],LyraFlag.prototype,"loadError",void 0);export{LyraFlag,__setFlagUrlResolverForTesting,loadFlagUrl,setFlagUrlResolver};
|
|
4
|
+
`}if(this.loadError){return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`}const url=safeMediaSrc(this.src??this.resolvedSrc);if(!url)return html``;const code=this.code;const alt=this.accessibleLabel??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`<img part="image" src=${url} alt=${alt} loading="lazy" decoding="async" />`}}__decorate([property()],LyraFlag.prototype,"country",void 0);__decorate([property()],LyraFlag.prototype,"language",void 0);__decorate([property()],LyraFlag.prototype,"src",void 0);__decorate([property({attribute:"aria-label"})],LyraFlag.prototype,"accessibleLabel",void 0);__decorate([property()],LyraFlag.prototype,"label",void 0);__decorate([property({type:Boolean,reflect:true})],LyraFlag.prototype,"round",void 0);__decorate([property()],LyraFlag.prototype,"variant",void 0);__decorate([state()],LyraFlag.prototype,"resolvedSrc",void 0);__decorate([state()],LyraFlag.prototype,"loading",void 0);__decorate([state()],LyraFlag.prototype,"loadError",void 0);export{LyraFlag,__setFlagUrlResolverForTesting,loadFlagUrl,setFlagUrlResolver};
|
|
@@ -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--)if(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./entity-card.styles.js";import"../../agent-tools/result-card/result-field.class.js";import"../../overlays/badge/badge.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import"../../overlays/empty/empty.class.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_entityCommunity,LYRA_DEFAULT_entityDegree,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_focusInGraph,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_untitledEntity}from"../../../internal/default-strings.generated.js";function
|
|
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--)if(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./entity-card.styles.js";import"../../agent-tools/result-card/result-field.class.js";import"../../overlays/badge/badge.class.js";import"../../overlays/chip/chip.class.js";import"../../forms/button/button.class.js";import"../../overlays/empty/empty.class.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_entityCommunity,LYRA_DEFAULT_entityDegree,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_focusInGraph,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_untitledEntity}from"../../../internal/default-strings.generated.js";function typeBadgeStyle(color){const safe=color!=null?sanitizeCssColor(color):void 0;if(!safe)return{};return{"--lr-badge-color":safe,"--lr-badge-background":`color-mix(in srgb, ${safe} 8%, var(--lr-color-surface))`,"--lr-badge-border":safe}}class LyraEntityCard extends LyraElement{constructor(){super(...arguments);this.entity=null;this.types=[];this.communityLabel="";this.showFocusButton=true;this.compact=false;this.frame="card";this.onFocusClick=()=>{if(this.entity)this.emit("lr-entity-activate",{id:this.entity.id})}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,entityCommunity:LYRA_DEFAULT_entityCommunity,entityDegree:LYRA_DEFAULT_entityDegree,fieldRequired:LYRA_DEFAULT_fieldRequired,focusInGraph:LYRA_DEFAULT_focusInGraph,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,untitledEntity:LYRA_DEFAULT_untitledEntity}}static{this.styles=[LyraElement.styles,styles]}resolvedType(type){return this.types.find(t=>t.id===type)}render(){if(!this.entity){return html`<div part="base"><lr-empty part="empty" heading=${this.localize("noData")}></lr-empty></div>`}const entity=this.entity;const titleText=entity.label||this.localize("untitledEntity");const resolved=entity.type?this.resolvedType(entity.type):void 0;const badgeLabel=resolved?.label??entity.type;const properties=Object.entries(entity.properties??{});const ariaLevel=this.getAttribute("aria-level")||"3";return html`
|
|
2
2
|
<div part="base">
|
|
3
3
|
<div part="header">
|
|
4
4
|
${badgeLabel?html`<lr-badge part="type-badge" style=${styleMap(typeBadgeStyle(resolved?.color))}
|
package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js
CHANGED
|
@@ -17,7 +17,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
17
17
|
</div>
|
|
18
18
|
${matches?html`
|
|
19
19
|
<div part="search-results" role="list" aria-label=${this.localize("graphExplorerSearchResultsLabel")}>
|
|
20
|
-
${matches.length===0?html`<div part="search-empty">${this.localize("viewerSearchNoMatches")}</div>`:matches.map(n=>html`
|
|
20
|
+
${matches.length===0?html`<div part="search-empty" role="listitem">${this.localize("viewerSearchNoMatches")}</div>`:matches.map(n=>html`
|
|
21
21
|
<div part="search-result" role="listitem">
|
|
22
22
|
<button type="button" @click=${()=>void this.activateEntity(n.id)}>${n.label||n.id}</button>
|
|
23
23
|
</div>
|
|
@@ -1 +1 @@
|
|
|
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--)if(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,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge,LYRA_DEFAULT_loading,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments);this._name="";this.path="";this.label="";this.library="default";this.family="";this.variant="";this._src="";this.rotate=0;this.autoWidth=false;this.swapOpacity=false;this.fixedWidth=false;this.fetchState={kind:"idle"};this.generation=0;this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge,loading:LYRA_DEFAULT_loading,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"";this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"";this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback();this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this});this.stopLibrarySubscription??=subscribeIconLibrary(name=>{if(name===this.library)void this.load()});if(this.hasUpdated){queueMicrotask(()=>{if(this.isConnected)this.syncCustomNodes()});if(this.hasRemoteSource())this.scheduleAfterUpdate(()=>void this.load())}}disconnectedCallback(){this.generation++;this.releaseResourceLease();this.stopLibrarySubscription?.();this.stopLibrarySubscription=void 0;this.customContentObserver?.disconnect();this.customContentObserver=void 0;this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0;if(this.fetchState.kind!=="idle")this.fetchState={kind:"idle"};super.disconnectedCallback()}updated(changed){super.updated(changed);if(changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);if(angle)this.style.setProperty("--lr-icon-rotate",`${angle}deg`);else this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y();this.syncCustomNodes();if(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant")){this.scheduleAfterUpdate(()=>void this.load())}}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove());this.customContentObserver?.disconnect();const slot=this.customSlot;if(!slot)return;for(const node of slot.assignedNodes({flatten:true})){const copy=this.cloneSvgNode(node);if(!copy)continue;copy.setAttribute("data-lr-custom-copy","");svgEl.append(copy)}this.observeCustomContent(slot)}observeCustomContent(slot){this.customContentObserver?.disconnect();if(!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;this.customContentObserver??=new MutationObserverCtor(()=>{if(this.isConnected)this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:true})){if(node.nodeType===1){this.customContentObserver.observe(node,{attributes:true,childList:true,subtree:true})}}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-"))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes){copy.setAttribute(attribute.name,attribute.value)}for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);if(childCopy)copy.append(childCopy);else if(child.nodeType===3){copy.append(this.ownerDocument.createTextNode(child.textContent??""))}}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return Boolean(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release();this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){if(this.fetchState.kind!=="idle")this.fetchState={kind:"idle"};return}this.fetchState={kind:"loading"};let source=this.src;try{if(library){source=await library.resolver(this.name,this.family,this.variant);if(!this.isConnected||generation!==this.generation)return;if(typeof source!=="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){if(this.isConnected&&generation===this.generation)this.fetchState={kind:"idle"};return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget);this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){this.fetchState={kind:"empty"};await this.updateComplete;if(!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,true);library?.mutator?.(node);this.fetchState={kind:"loaded",node};await this.updateComplete;if(!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{if(this.resourceLease===lease)this.resourceLease=void 0;lease?.release()}}async fail(reason,generation,src,error){if(!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",reason};await this.updateComplete;if(!this.isConnected||generation!==this.generation)return;if(isAccessibilityVisible(this)){this.errorAnnouncementSink?.announce(this.errorMessage(reason))}this.emit("lr-error",{src,error})}errorMessage(reason){if(reason==="sanitizer")return this.localize("iconSanitizerMissing");if(reason==="too-large")return this.localize("iconTooLarge");return this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind!=="loaded")return;const label=this.accessibleLabel();state2.node.setAttribute("part","svg");state2.node.setAttribute("focusable","false");state2.node.setAttribute("aria-hidden",label?"false":"true");if(label)state2.node.setAttribute("aria-label",label);else state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use");use.setAttribute("part",[...parts].join(" "))}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";const accessibleLabel=this.accessibleLabel();return html`<svg part="svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden=${accessibleLabel?"false":"true"} aria-label=${accessibleLabel||nothing} focusable="false">${path?svg`<path d=${path}></path>`:nothing}</svg>${path?nothing:html`<slot @slotchange=${this.onCustomSlotChange}></slot>`}`}render(){const state2=this.fetchState;switch(state2.kind){case"loaded":return html`${state2.node}`;case"error":return html`<span part="error" class="sr-only" aria-hidden="true">${this.errorMessage(state2.reason)}</span>`;case"empty":return html`<span part="empty" aria-hidden="true"></span>`;case"loading":return html``;case"idle":default:return this.renderBuiltIn()}}}__decorate([property({reflect:true,useDefault:true})],LyraIcon.prototype,"name",null);__decorate([property()],LyraIcon.prototype,"path",void 0);__decorate([property()],LyraIcon.prototype,"label",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"library",void 0);__decorate([property({reflect:true,useDefault:true})],LyraIcon.prototype,"family",void 0);__decorate([property({reflect:true,useDefault:true})],LyraIcon.prototype,"variant",void 0);__decorate([property()],LyraIcon.prototype,"src",null);__decorate([property({type:Number,reflect:true,useDefault:true})],LyraIcon.prototype,"rotate",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"flip",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"canvas",void 0);__decorate([property({type:Boolean,reflect:true,attribute:"auto-width"})],LyraIcon.prototype,"autoWidth",void 0);__decorate([property({type:Boolean,reflect:true,attribute:"swap-opacity"})],LyraIcon.prototype,"swapOpacity",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"animation",void 0);__decorate([property({type:Boolean,reflect:true,attribute:"fixed-width"})],LyraIcon.prototype,"fixedWidth",void 0);__decorate([state()],LyraIcon.prototype,"fetchState",void 0);__decorate([query("svg")],LyraIcon.prototype,"svgEl",void 0);__decorate([query("slot")],LyraIcon.prototype,"customSlot",void 0);export{LyraIcon};
|
|
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--)if(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,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge,LYRA_DEFAULT_loading,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments);this._name="";this.path="";this.label="";this.library="default";this.family="";this.variant="";this._src="";this.rotate=0;this.autoWidth=false;this.swapOpacity=false;this.fixedWidth=false;this.fetchState={kind:"idle"};this.generation=0;this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge,loading:LYRA_DEFAULT_loading,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"";this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"";this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback();this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this});this.stopLibrarySubscription??=subscribeIconLibrary(name=>{if(name===this.library)void this.load()});if(this.hasUpdated){queueMicrotask(()=>{if(this.isConnected)this.syncCustomNodes()});if(this.hasRemoteSource())this.scheduleAfterUpdate(()=>void this.load())}}disconnectedCallback(){this.generation++;this.releaseResourceLease();this.stopLibrarySubscription?.();this.stopLibrarySubscription=void 0;this.customContentObserver?.disconnect();this.customContentObserver=void 0;this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0;if(this.fetchState.kind!=="idle")this.fetchState={kind:"idle"};super.disconnectedCallback()}updated(changed){super.updated(changed);if(changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);if(angle)this.style.setProperty("--lr-icon-rotate",`${angle}deg`);else this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y();this.syncCustomNodes();if(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant")){this.scheduleAfterUpdate(()=>void this.load())}}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove());this.customContentObserver?.disconnect();const slot=this.customSlot;if(!slot)return;for(const node of slot.assignedNodes({flatten:true})){const copy=this.cloneSvgNode(node);if(!copy)continue;copy.setAttribute("data-lr-custom-copy","");svgEl.append(copy)}this.observeCustomContent(slot)}observeCustomContent(slot){this.customContentObserver?.disconnect();if(!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;this.customContentObserver??=new MutationObserverCtor(()=>{if(this.isConnected)this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:true})){if(node.nodeType===1){this.customContentObserver.observe(node,{attributes:true,childList:true,subtree:true})}}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-"))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes){if(isUnsafeSvgCloneAttribute(attribute.name))continue;copy.setAttribute(attribute.name,attribute.value)}for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);if(childCopy)copy.append(childCopy);else if(child.nodeType===3){copy.append(this.ownerDocument.createTextNode(child.textContent??""))}}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return Boolean(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release();this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){if(this.fetchState.kind!=="idle")this.fetchState={kind:"idle"};return}this.fetchState={kind:"loading"};let source=this.src;try{if(library){source=await library.resolver(this.name,this.family,this.variant);if(!this.isConnected||generation!==this.generation)return;if(typeof source!=="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){if(this.isConnected&&generation===this.generation)this.fetchState={kind:"idle"};return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget);this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){this.fetchState={kind:"empty"};await this.updateComplete;if(!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,true);library?.mutator?.(node);this.fetchState={kind:"loaded",node};await this.updateComplete;if(!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{if(this.resourceLease===lease)this.resourceLease=void 0;lease?.release()}}async fail(reason,generation,src,error){if(!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",reason};await this.updateComplete;if(!this.isConnected||generation!==this.generation)return;if(isAccessibilityVisible(this)){this.errorAnnouncementSink?.announce(this.errorMessage(reason))}this.emit("lr-error",{src,error})}errorMessage(reason){if(reason==="sanitizer")return this.localize("iconSanitizerMissing");if(reason==="too-large")return this.localize("iconTooLarge");return this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind!=="loaded")return;const label=this.accessibleLabel();state2.node.setAttribute("part","svg");state2.node.setAttribute("focusable","false");state2.node.setAttribute("aria-hidden",label?"false":"true");if(label)state2.node.setAttribute("aria-label",label);else state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use");use.setAttribute("part",[...parts].join(" "))}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";const accessibleLabel=this.accessibleLabel();return html`<svg part="svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden=${accessibleLabel?"false":"true"} aria-label=${accessibleLabel||nothing} focusable="false">${path?svg`<path d=${path}></path>`:nothing}</svg>${path?nothing:html`<slot @slotchange=${this.onCustomSlotChange}></slot>`}`}render(){const state2=this.fetchState;switch(state2.kind){case"loaded":return html`${state2.node}`;case"error":return html`<span part="error" class="sr-only" aria-hidden="true">${this.errorMessage(state2.reason)}</span>`;case"empty":return html`<span part="empty" aria-hidden="true"></span>`;case"loading":return html``;case"idle":default:return this.renderBuiltIn()}}}__decorate([property({reflect:true,useDefault:true})],LyraIcon.prototype,"name",null);__decorate([property()],LyraIcon.prototype,"path",void 0);__decorate([property()],LyraIcon.prototype,"label",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"library",void 0);__decorate([property({reflect:true,useDefault:true})],LyraIcon.prototype,"family",void 0);__decorate([property({reflect:true,useDefault:true})],LyraIcon.prototype,"variant",void 0);__decorate([property()],LyraIcon.prototype,"src",null);__decorate([property({type:Number,reflect:true,useDefault:true})],LyraIcon.prototype,"rotate",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"flip",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"canvas",void 0);__decorate([property({type:Boolean,reflect:true,attribute:"auto-width"})],LyraIcon.prototype,"autoWidth",void 0);__decorate([property({type:Boolean,reflect:true,attribute:"swap-opacity"})],LyraIcon.prototype,"swapOpacity",void 0);__decorate([property({reflect:true})],LyraIcon.prototype,"animation",void 0);__decorate([property({type:Boolean,reflect:true,attribute:"fixed-width"})],LyraIcon.prototype,"fixedWidth",void 0);__decorate([state()],LyraIcon.prototype,"fetchState",void 0);__decorate([query("svg")],LyraIcon.prototype,"svgEl",void 0);__decorate([query("slot")],LyraIcon.prototype,"customSlot",void 0);export{LyraIcon};
|
|
@@ -1 +1 @@
|
|
|
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--)if(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{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{buildQuoteAnchor,normalizeQuoteText,resolveTextQuote,scopeFromElement}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{loadArchiveLibraryCached}from"./archive-loader.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_archiveViewerUnavailable,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4;const MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function measureArchiveEntry(file,remainingBytes,isCurrent){const stream=file.internalStream?.("uint8array");if(!stream){return Promise.reject(new LyraResourceLimitError("The archive entry size cannot be measured safely."))}return new Promise((resolve,reject)=>{let total=0;let settled=false;const fail=error=>{if(settled)return;settled=true;stream.pause?.();reject(error)};stream.on("data",chunk=>{if(!isCurrent()){const error=new Error("The operation was aborted.");error.name="AbortError";fail(error);return}total+=chunk.length;if(total>remainingBytes){fail(new LyraResourceLimitError("The expanded archive is too large."))}}).on("error",fail).on("end",()=>{if(settled)return;if(!isCurrent()){const error=new Error("The operation was aborted.");error.name="AbortError";fail(error);return}settled=true;resolve(total)});stream.resume()})}function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument;const view=document.defaultView;const nestedRoot=contentRoot.getRootNode();const outerRoot=viewer.shadowRoot;const ShadowRootCtor=view?.ShadowRoot;const shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index);const globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();range.setStart(composed.startContainer,composed.startOffset);range.setEnd(composed.endContainer,composed.endOffset);return range}}const nestedSelection=nestedRoot.getSelection?.();const selection=nestedSelection??globalSelection??null;if(!selection||selection.rangeCount===0||selection.isCollapsed)return null;return selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments);this.src="";this.name="";this.fetchState={kind:"idle"};this.archiveSearchMatches=[];this.archiveSearchActiveIndex=-1;this.generation=0;this.archiveSearchQuery="";this.loadLibrary=loadArchiveLibraryCached;this.archiveSelectionRoot=null;this.styledVirtualListRoot=null;this.archiveNestedUpdatePending=false;this.archiveEntryKey=item=>item.name;this.announcements=new ViewerAnnouncementController(this);this.renderEntry=item=>{const entry=item;const kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span id=${entry.name} part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,archiveViewerUnavailable:LYRA_DEFAULT_archiveViewerUnavailable,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}async search(query){this.archiveSearchQuery=query;this.recomputeArchiveSearch();await this.updateComplete;this.scrollActiveArchiveMatch();return this.archiveSearchMatches.length}async searchNext(){if(!this.archiveSearchMatches.length)return false;this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length;this.emitArchiveSearchChange();await this.updateComplete;this.scrollActiveArchiveMatch();return true}async searchPrevious(){if(!this.archiveSearchMatches.length)return false;this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length;this.emitArchiveSearchChange();await this.updateComplete;this.scrollActiveArchiveMatch();return true}clearSearch(){this.archiveSearchQuery="";this.archiveSearchMatches=[];this.archiveSearchActiveIndex=-1;this.emitArchiveSearchChange()}updated(changed){super.updated(changed);this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument"));this.syncArchiveNestedRoot();if(changed.has("src"))this.scheduleAfterUpdate(()=>{void this.load()})}connectedCallback(){super.connectedCallback();this.announcements.connect();if(this.hasUpdated&&this.src)this.scheduleAfterUpdate(()=>{void this.load()})}disconnectedCallback(){this.generation++;this.archiveSelectionCleanup?.();this.archiveSelectionCleanup=void 0;this.archiveSelectionRoot=null;this.announcements.disconnect();super.disconnectedCallback()}adoptedCallback(){this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return false;let index=-1;if(anchor.kind==="fragment"){index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id)}else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span");index=this.fetchState.entries.findIndex(entry=>{probe.textContent=entry.name;return resolveTextQuote(scopeFromElement(probe),anchor,this.effectiveLocale)!==null})}if(index<0)return false;const list=this.archiveVirtualList();if(!list)return false;list.scrollToIndex(index,{align:"auto",behavior:"auto"});if(!await this.waitForArchiveRow(list,index))return false;this.requestUpdate();await this.updateComplete;const applyTextAnchor=ArchiveTextViewerTargetBase.prototype.applyAnchor;return applyTextAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;const element=node.nodeType===elementNode?node:node.parentElement;return element?.closest('[part~="entry-name"]')??null};const start=entryName(range.startContainer);const end=entryName(range.endContainer);if(!start||start!==end)return null;return buildQuoteAnchor(range,scopeFromElement(start))}async load(){const generation=++this.generation;const signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new Error("Unsafe archive source URL");this.fetchState={kind:"error",message:this.localize("documentPreviewUrlNotAllowed")};this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const library=await this.loadLibrary();if(!this.isConnected||generation!==this.generation)return;if(!library){const error=new Error("Archive renderer unavailable");this.fetchState={kind:"error",message:this.localize("archiveViewerUnavailable")};this.emit("lr-render-error",{error});return}const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const zip=await library.loadAsync(buffer);if(!this.isConnected||generation!==this.generation)return;const entries=[];const fallbackSizes=[];let totalUncompressed=0;zip.forEach((_path,file)=>{if(entries.length>=MAX_ARCHIVE_ENTRIES)throw new LyraResourceLimitError;const declaredSize=file._data?.uncompressedSize;const hasDeclaredSize=Number.isFinite(declaredSize);if(hasDeclaredSize&&declaredSize>MAX_ARCHIVE_UNCOMPRESSED_BYTES)throw new LyraResourceLimitError;totalUncompressed+=hasDeclaredSize?declaredSize:0;if(totalUncompressed>MAX_ARCHIVE_UNCOMPRESSED_BYTES)throw new LyraResourceLimitError;const entry={name:file.name,dir:file.dir,size:hasDeclaredSize?declaredSize:0};entries.push(entry);if(!file.dir&&!hasDeclaredSize)fallbackSizes.push({entry,file})});for(const fallback of fallbackSizes){const size=await measureArchiveEntry(fallback.file,MAX_ARCHIVE_UNCOMPRESSED_BYTES-totalUncompressed,()=>this.isConnected&&generation===this.generation);if(!this.isConnected||generation!==this.generation)return;fallback.entry.size=size;totalUncompressed+=size;if(totalUncompressed>MAX_ARCHIVE_UNCOMPRESSED_BYTES)throw new LyraResourceLimitError}this.fetchState={kind:"loaded",entries};if(this.archiveSearchQuery)this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")};this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation();if(this.archiveNestedUpdatePending)return;this.archiveNestedUpdatePending=true;queueMicrotask(()=>{this.archiveNestedUpdatePending=false;if(this.isConnected)this.requestUpdate()})}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){await list.updateComplete;if(list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return true;if(!view)return false;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return false}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot){this.unbindTextSelection();this.archiveSelectionCleanup?.();this.archiveSelectionCleanup=void 0;this.archiveSelectionRoot=root;if(root){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=normalizeQuoteText(range.toString());if(!text)return;const anchor=this.computeSelectionAnchor(range);const rects=Array.from(range.getClientRects());this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection);root.addEventListener("keyup",emitSelection);this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection);root.removeEventListener("keyup",emitSelection)}}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot){const existing=listRoot.querySelector("style[data-lr-archive-highlight-styles]");if(existing){this.styledVirtualListRoot=listRoot}else{const style=this.ownerDocument.createElement("style");style.dataset["lrArchiveHighlightStyles"]="";style.textContent=virtualListHighlightStyles.cssText;listRoot.append(style);this.styledVirtualListRoot=listRoot}}if(root){for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]")){if(!mark.hasAttribute("part"))mark.setAttribute("part","highlight")}}}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[];const query=this.archiveSearchQuery.trim().toLocaleLowerCase(this.effectiveLocale);this.archiveSearchMatches=query?entries.filter(entry=>entry.name.toLocaleLowerCase(this.effectiveLocale).includes(query)):[];this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1;this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match);const list=this.renderRoot.querySelector("lr-virtual-list");if(index>=0)list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-changed=${this.stopVirtualListEvent} @lr-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;case"loading":return html`<div part="spinner"><span class="sr-only">${this.localize("loadingDocument")}</span></div>`;case"error":return html`<div part="error">${this.fetchState.message}</div>`;case"idle":default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}render(){const label=this.getAttribute("aria-label")||this.name;return label?html`<div part="base" role="region" aria-label=${label}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`:html`<div part="base"><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0);__decorate([property()],LyraArchiveViewer.prototype,"name",void 0);__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0);__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0);__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
|
|
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--)if(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{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{buildQuoteAnchor,normalizeQuoteText,resolveTextQuote,scopeFromElement}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{loadArchiveLibraryCached}from"./archive-loader.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_archiveViewerUnavailable,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4;const MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function measureArchiveEntry(file,remainingBytes,isCurrent){const stream=file.internalStream?.("uint8array");if(!stream){return Promise.reject(new LyraResourceLimitError("The archive entry size cannot be measured safely."))}return new Promise((resolve,reject)=>{let total=0;let settled=false;const fail=error=>{if(settled)return;settled=true;stream.pause?.();reject(error)};stream.on("data",chunk=>{if(!isCurrent()){const error=new Error("The operation was aborted.");error.name="AbortError";fail(error);return}total+=chunk.length;if(total>remainingBytes){fail(new LyraResourceLimitError("The expanded archive is too large."))}}).on("error",fail).on("end",()=>{if(settled)return;if(!isCurrent()){const error=new Error("The operation was aborted.");error.name="AbortError";fail(error);return}settled=true;resolve(total)});stream.resume()})}function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument;const view=document.defaultView;const nestedRoot=contentRoot.getRootNode();const outerRoot=viewer.shadowRoot;const ShadowRootCtor=view?.ShadowRoot;const shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index);const globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();range.setStart(composed.startContainer,composed.startOffset);range.setEnd(composed.endContainer,composed.endOffset);return range}}const nestedSelection=nestedRoot.getSelection?.();const selection=nestedSelection??globalSelection??null;if(!selection||selection.rangeCount===0||selection.isCollapsed)return null;return selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments);this.src="";this.name="";this.fetchState={kind:"idle"};this.archiveSearchMatches=[];this.archiveSearchActiveIndex=-1;this.generation=0;this.archiveSearchQuery="";this.loadLibrary=loadArchiveLibraryCached;this.archiveSelectionRoot=null;this.styledVirtualListRoot=null;this.archiveNestedUpdatePending=false;this.archiveEntryKey=item=>item.name;this.announcements=new ViewerAnnouncementController(this);this.renderEntry=item=>{const entry=item;const kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,archiveViewerUnavailable:LYRA_DEFAULT_archiveViewerUnavailable,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles,srOnly]}async search(query){this.archiveSearchQuery=query;this.recomputeArchiveSearch();await this.updateComplete;this.scrollActiveArchiveMatch();return this.archiveSearchMatches.length}async searchNext(){if(!this.archiveSearchMatches.length)return false;this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length;this.emitArchiveSearchChange();await this.updateComplete;this.scrollActiveArchiveMatch();return true}async searchPrevious(){if(!this.archiveSearchMatches.length)return false;this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length;this.emitArchiveSearchChange();await this.updateComplete;this.scrollActiveArchiveMatch();return true}clearSearch(){this.archiveSearchQuery="";this.archiveSearchMatches=[];this.archiveSearchActiveIndex=-1;this.emitArchiveSearchChange()}updated(changed){super.updated(changed);this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument"));this.syncArchiveNestedRoot();if(changed.has("src"))this.scheduleAfterUpdate(()=>{void this.load()})}connectedCallback(){super.connectedCallback();this.announcements.connect();if(this.hasUpdated&&this.src)this.scheduleAfterUpdate(()=>{void this.load()})}disconnectedCallback(){this.generation++;this.archiveSelectionCleanup?.();this.archiveSelectionCleanup=void 0;this.archiveSelectionRoot=null;this.announcements.disconnect();super.disconnectedCallback()}adoptedCallback(){this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return false;let index=-1;let resolvedName;if(anchor.kind==="fragment"){index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id);resolvedName=this.fetchState.entries[index]?.name}else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span");index=this.fetchState.entries.findIndex(entry=>{probe.textContent=entry.name;return resolveTextQuote(scopeFromElement(probe),anchor,this.effectiveLocale)!==null})}if(index<0)return false;const list=this.archiveVirtualList();if(!list)return false;list.scrollToIndex(index,{align:"auto",behavior:"auto"});if(!await this.waitForArchiveRow(list,index))return false;this.requestUpdate();await this.updateComplete;if(anchor.kind==="fragment"){const root=this.textContentRoot();const target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;target?.scrollIntoView?.({block:"nearest",behavior:"auto"});return true}const applyTextAnchor=ArchiveTextViewerTargetBase.prototype.applyAnchor;return applyTextAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;const element=node.nodeType===elementNode?node:node.parentElement;return element?.closest('[part~="entry-name"]')??null};const start=entryName(range.startContainer);const end=entryName(range.endContainer);if(!start||start!==end)return null;return buildQuoteAnchor(range,scopeFromElement(start))}async load(){const generation=++this.generation;const signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new Error("Unsafe archive source URL");this.fetchState={kind:"error",message:this.localize("documentPreviewUrlNotAllowed")};this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const library=await this.loadLibrary();if(!this.isConnected||generation!==this.generation)return;if(!library){const error=new Error("Archive renderer unavailable");this.fetchState={kind:"error",message:this.localize("archiveViewerUnavailable")};this.emit("lr-render-error",{error});return}const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const zip=await library.loadAsync(buffer);if(!this.isConnected||generation!==this.generation)return;const entries=[];const fallbackSizes=[];let totalUncompressed=0;zip.forEach((_path,file)=>{if(entries.length>=MAX_ARCHIVE_ENTRIES)throw new LyraResourceLimitError;const declaredSize=file._data?.uncompressedSize;const hasDeclaredSize=Number.isFinite(declaredSize);if(hasDeclaredSize&&declaredSize>MAX_ARCHIVE_UNCOMPRESSED_BYTES)throw new LyraResourceLimitError;totalUncompressed+=hasDeclaredSize?declaredSize:0;if(totalUncompressed>MAX_ARCHIVE_UNCOMPRESSED_BYTES)throw new LyraResourceLimitError;const entry={name:file.name,dir:file.dir,size:hasDeclaredSize?declaredSize:0};entries.push(entry);if(!file.dir&&!hasDeclaredSize)fallbackSizes.push({entry,file})});for(const fallback of fallbackSizes){const size=await measureArchiveEntry(fallback.file,MAX_ARCHIVE_UNCOMPRESSED_BYTES-totalUncompressed,()=>this.isConnected&&generation===this.generation);if(!this.isConnected||generation!==this.generation)return;fallback.entry.size=size;totalUncompressed+=size;if(totalUncompressed>MAX_ARCHIVE_UNCOMPRESSED_BYTES)throw new LyraResourceLimitError}this.fetchState={kind:"loaded",entries};if(this.archiveSearchQuery)this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")};this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation();if(this.archiveNestedUpdatePending)return;this.archiveNestedUpdatePending=true;queueMicrotask(()=>{this.archiveNestedUpdatePending=false;if(this.isConnected)this.requestUpdate()})}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){await list.updateComplete;if(list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return true;if(!view)return false;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return false}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot){this.unbindTextSelection();this.archiveSelectionCleanup?.();this.archiveSelectionCleanup=void 0;this.archiveSelectionRoot=root;if(root){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=normalizeQuoteText(range.toString());if(!text)return;const anchor=this.computeSelectionAnchor(range);const rects=Array.from(range.getClientRects());this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection);root.addEventListener("keyup",emitSelection);this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection);root.removeEventListener("keyup",emitSelection)}}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot){const existing=listRoot.querySelector("style[data-lr-archive-highlight-styles]");if(existing){this.styledVirtualListRoot=listRoot}else{const style=this.ownerDocument.createElement("style");style.dataset["lrArchiveHighlightStyles"]="";style.textContent=virtualListHighlightStyles.cssText;listRoot.append(style);this.styledVirtualListRoot=listRoot}}if(root){for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]")){if(!mark.hasAttribute("part"))mark.setAttribute("part","highlight")}}}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[];const query=this.archiveSearchQuery.trim().toLocaleLowerCase(this.effectiveLocale);this.archiveSearchMatches=query?entries.filter(entry=>entry.name.toLocaleLowerCase(this.effectiveLocale).includes(query)):[];this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1;this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match);const list=this.renderRoot.querySelector("lr-virtual-list");if(index>=0)list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-changed=${this.stopVirtualListEvent} @lr-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;case"loading":return html`<div part="spinner"><span class="sr-only">${this.localize("loadingDocument")}</span></div>`;case"error":return html`<div part="error">${this.fetchState.message}</div>`;case"idle":default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}render(){const label=this.getAttribute("aria-label")||this.name;return label?html`<div part="base" role="region" aria-label=${label}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`:html`<div part="base"><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0);__decorate([property()],LyraArchiveViewer.prototype,"name",void 0);__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0);__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0);__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
|