@aceshooting/lyra-ui 30.1.0 → 30.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 +21 -0
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/chart-prepared-data.d.ts +3 -1
- package/dist/components/charts/chart/chart-prepared-data.js +1 -1
- package/dist/components/charts/chart/chart.class.js +2 -2
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +2 -2
- package/dist/components/forms/combobox/option.class.d.ts +1 -1
- package/dist/components/forms/combobox/option.class.js +2 -2
- package/dist/components/forms/radio/radio.class.d.ts +1 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +11 -11
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/internal/accessible-text-controller.js +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/default-label-forwarding.js +1 -0
- package/dist/internal/hierarchy-summary-source.js +1 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.d.ts +8 -0
- package/dist/internal/positioner.js +1 -1
- package/llms/components/lr-map.md +7 -6
- package/llms/components/lr-pptx-viewer.md +9 -5
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/package.json +6 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{subscribeInheritedAttributes}from"../../../internal/inherited-attribute-hub.js";import{composedParentElement}from"../../../internal/active-element.js";import{html,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{markOptionSelectedDirty,notifyOptionSelectedWrite,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{styles}from"./option.styles.js";const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{subscribeInheritedAttributes}from"../../../internal/inherited-attribute-hub.js";import{composedParentElement}from"../../../internal/active-element.js";import{html,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{markOptionSelectedDirty,notifyOptionSelectedWrite,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{styles}from"./option.styles.js";const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{subscribeInheritedAttributes}from"../../../
|
|
|
11
11
|
aria-hidden="true"
|
|
12
12
|
focusable="false"
|
|
13
13
|
><polyline points="5 12.5 10 17.5 19 6.5"></polyline></svg>
|
|
14
|
-
`}class LyraOption extends LyraElement{constructor(){super(...arguments),this.slotPresence=new SlotPresenceController(this),this.optionInternals=attachInternalsSafely(this),this.hasHover=!1,this.hasCurrent=!1,this._label="",this.selectedValue=!1,this.defaultSelectedValue=!1,this.selectedDirty=!1,this.value="",this.disabled=!1,this.title="",this.group="",this.searchText="",this.sub="",this.dotColor="",this.labelTextObserver=new AccessibleTextController(this,[],records=>this.handleLabelRecords([...records]),["slot","title"],!0,!1,()=>this
|
|
14
|
+
`}class LyraOption extends LyraElement{constructor(){super(...arguments),this.slotPresence=new SlotPresenceController(this),this.optionInternals=attachInternalsSafely(this),this.hasHover=!1,this.hasCurrent=!1,this._label="",this.selectedValue=!1,this.defaultSelectedValue=!1,this.selectedDirty=!1,this.value="",this.disabled=!1,this.title="",this.group="",this.searchText="",this.sub="",this.dotColor="",this.labelTextObserver=new AccessibleTextController(this,[],records=>this.handleLabelRecords([...records]),["slot","title"],!0,!1,()=>defaultLabelForwardingSlots(this).length>0),this.observedDefaultLabel="",this.handlePointerEnter=()=>{this.hasHover=!0,this.syncOptionState()},this.handlePointerLeave=()=>{this.hasHover=!1,this.syncOptionState()},this.handleFocusIn=()=>{this.hasCurrent=!0,this.syncOptionState()},this.handleFocusOut=()=>{this.hasCurrent=!1,this.syncOptionState()},this.handleLabelMutation=(presentationChanged=!1)=>{const next=this.defaultLabel;next===this.observedDefaultLabel&&!presentationChanged||(this.observedDefaultLabel=next,this.requestUpdate(),this.emit("lr-option-change"))},this.handleLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!defaultLabelForwardingSlots(this).includes(target)||(this.cachedDefaultLabel=void 0,this.labelTextObserver.bind(),this.handleLabelMutation())},this.inertAncestorReleases=[]}static{this.styles=[LyraElement.styles,styles]}get selected(){return this.selectedValue}set selected(next){this.setLiveSelected(next,!0),notifyOptionSelectedWrite(this,()=>this.emit("lr-option-change"))}get defaultSelected(){return this.defaultSelectedValue}set defaultSelected(next){const normalized=!!next,old=this.defaultSelectedValue;old!==normalized&&(this.defaultSelectedValue=normalized,this.selectedDirty||this.setLiveSelected(normalized,!1),this.requestUpdate("defaultSelected",old))}setLiveSelected(next,dirty){dirty&&(this.selectedDirty=!0,markOptionSelectedDirty(this,!0));const normalized=!!next,old=this.selectedValue;old!==normalized&&(this.selectedValue=normalized,this.requestUpdate("selected",old))}[SET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty||markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}[RESET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty=!1,markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}get label(){return this._label.trim()||this.defaultLabel}set label(next){const normalized=String(next??""),old=this._label;old!==normalized&&(this._label=normalized,this.requestUpdate("label",old))}get defaultLabel(){if(!("childNodes"in this))return"";const pending=this.labelTextObserver.takeRecords();if(pending.length){this.cachedDefaultLabel=void 0;const ownerDocument=this.ownerDocument;queueMicrotask(()=>{this.isConnected&&this.ownerDocument===ownerDocument&&this.handleLabelRecords(pending)})}return this.isConnected?this.cachedDefaultLabel??=this.computeDefaultLabel():this.computeDefaultLabel()}computeDefaultLabel(){const roots=Array.from(this.childNodes??[]).filter(node=>isDefaultLabelNode(node));return composedAccessibilityText(roots,{requireRendered:!1,shouldPruneNode:node=>!this.contains(node)&&!this.isSourceLabelVisible(node),skipRootAncestorValidation:!0}).replace(/\s+/g," ").trim()}sourceParentForLabelNode(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root&&root.host.nodeType===1?root.host:null}isClosedSourceDetailsBranch(details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;const summary=Array.from(details.children).find(child=>child.localName==="summary");return branch!==summary}isSourceLabelVisible(node){const target=node.nodeType===1?node:this.sourceParentForLabelNode(node);if(!target?.isConnected||isAccessibilitySubtreeExcluded(target)||isAccessibilityVisibilityHidden(target))return!1;let branch=target,ancestor=this.sourceParentForLabelNode(target);for(;ancestor;){if(isAccessibilitySubtreeExcluded(ancestor)||this.isClosedSourceDetailsBranch(ancestor,branch))return!1;branch=ancestor,ancestor=this.sourceParentForLabelNode(ancestor)}return!0}bindInertAncestors(){for(const release of this.inertAncestorReleases.splice(0))release();const roots=new Map;for(let ancestor=composedParentElement(this);ancestor;ancestor=composedParentElement(ancestor)){const root=ancestor.getRootNode();let elements=roots.get(root);elements||roots.set(root,elements=new Set),elements.add(ancestor)}for(const[root,ancestors]of roots){const release=subscribeInheritedAttributes(root,this.ownerDocument.defaultView?.MutationObserver,{attributes:["inert"],changed:records=>{!defaultLabelForwardingSlots(this).length&&records.some(record=>ancestors.has(record.target))&&this.emit("lr-option-change")}});release&&this.inertAncestorReleases.push(release)}}connectedCallback(){super.connectedCallback(),this.addEventListener("pointerenter",this.handlePointerEnter),this.addEventListener("pointerleave",this.handlePointerLeave),this.addEventListener("focusin",this.handleFocusIn),this.addEventListener("focusout",this.handleFocusOut),this.syncOptionState(),this.addEventListener("slotchange",this.handleLabelSlotChange),this.cachedDefaultLabel=void 0,this.observedDefaultLabel=this.defaultLabel,this.bindInertAncestors()}disconnectedCallback(){for(const release of this.inertAncestorReleases.splice(0))release();this.removeEventListener("pointerenter",this.handlePointerEnter),this.removeEventListener("pointerleave",this.handlePointerLeave),this.removeEventListener("focusin",this.handleFocusIn),this.removeEventListener("focusout",this.handleFocusOut),this.removeEventListener("slotchange",this.handleLabelSlotChange),this.hasHover=!1,this.hasCurrent=!1,this.syncOptionState(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cachedDefaultLabel=void 0,this.labelTextObserver.adopted(),this.isConnected&&this.bindInertAncestors()}handleLabelRecords(records){this.cachedDefaultLabel=void 0;const presentationChanged=records.some(record=>{if(record.type==="attributes"&&record.attributeName==="inert"||record.type==="attributes"&&record.attributeName==="slot"&&this.contains(record.target))return!0;let node=record.target;for(;node&&node!==this&&node.parentNode!==this;)node=node.parentNode;return node&&node!==this&&!isDefaultLabelNode(node)?!0:record.type==="childList"&&record.target===this&&[...record.addedNodes,...record.removedNodes].some(child=>!isDefaultLabelNode(child))});this.handleLabelMutation(presentationChanged)}shouldUpdate(changed){return this.hasUpdated&&changed.size===1&&changed.has("label")&&!this.labelTextObserver.hasDrainedRecords()?(queueMicrotask(()=>this.emit("lr-option-change")),!1):super.shouldUpdate(changed)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&!changed.has("label")&&!changed.has("slot")&&this.labelTextObserver.preserveBindingForNextUpdate()}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&(this.hasCurrent=!1),this.syncOptionState(),(changed.has("value")||changed.has("disabled")||changed.has("group")||changed.has("title")||changed.has("searchText")||changed.has("sub")||changed.has("dotColor")||changed.has("label")||changed.has("defaultSelected")||changed.has("data"))&&this.emit("lr-option-change")}syncOptionState(){this.optionInternals.role="option",this.optionInternals.ariaSelected=this.selected?"true":"false",this.optionInternals.ariaDisabled=this.disabled?"true":"false",setCustomState(this.optionInternals,"current",this.hasCurrent&&!this.disabled),setCustomState(this.optionInternals,"selected",this.selected),setCustomState(this.optionInternals,"disabled",this.disabled),setCustomState(this.optionInternals,"hover",this.hasHover&&!this.disabled)}getTextLabel(){return this.defaultLabel}render(){const hasStart=this.slotPresence.has("start")||this.slotPresence.has("prefix"),hasEnd=this.slotPresence.has("end")||this.slotPresence.has("suffix");return html`
|
|
15
15
|
<div part="base">
|
|
16
16
|
<span part="checked-icon" aria-hidden="true" inert ?hidden=${!this.selected}>
|
|
17
17
|
${checkmarkGlyph()}
|
|
@@ -164,4 +164,4 @@ setCustomValidity(message:string):void;private applyCustomValidity;private refle
|
|
|
164
164
|
/** Clears consumer-supplied validity on the standalone radio or its owning group.*/
|
|
165
165
|
resetValidity():void;click():void;focus(options?:FocusOptions):void;blur():void;private currentGroup;private group;private select;private uncheckSameNameRadios;
|
|
166
166
|
/** Actual contiguous button-run position. Standalone and non-adjacent controls stay rounded.*/
|
|
167
|
-
protected get buttonRunPosition():RadioButtonRunPosition;private isNestedInteractiveEvent;protected onClick:()=>void;protected onKeyDown:(event:KeyboardEvent)=>void;protected onFocus:(event:FocusEvent)=>void;protected onBlur:(event:FocusEvent)=>void;private
|
|
167
|
+
protected get buttonRunPosition():RadioButtonRunPosition;private isNestedInteractiveEvent;protected onClick:()=>void;protected onKeyDown:(event:KeyboardEvent)=>void;protected onFocus:(event:FocusEvent)=>void;protected onBlur:(event:FocusEvent)=>void;private recomputeHasLabel;private assignedAdornmentNodes;private recomputeButtonAdornments;private handleLabelSlotChange;private onLabelSlotChange;private onSlotChange;private onAdornmentSlotChange;private get invalid();render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-radio':LyraRadio;}}export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings/forms.generated.js";installFormControlLabelSupport();class LyraRadioBase extends LyraElement{}class LyraRadio extends CheckedFormAssociated(LyraRadioBase){constructor(){super(...arguments),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.recomputeHasLabel(),this.recomputeButtonAdornments()},["slot"]),this.swappingControl=!1,this.committingCustomError=!1,this.resettingCustomError=!1,this._radioName="",this._radioValue="on",this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this.onClick=event=>{if(event&&this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.select()},this.onKeyDown=event=>{if(this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{!this.effectiveDisabled&&!this.matches(":disabled")&&!this.swappingControl&&this.setInteracted(!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.labelTextObserver.bind(),this.recomputeButtonAdornments()}}static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}static{this.properties={appearance:{reflect:!0,converter:declaredDefaultConverter("default")},pill:{type:Boolean,reflect:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")}}}get name(){return this._radioName}set name(value){const old=this._radioName,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._radioName=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._radioValue}set value(value){const old=this._radioValue,next=value??"on";old!==next&&(this._radioValue=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}radioCustomMessage(){return this.currentGroup()?.customError??this.validityController.customValidityMessage}get customError(){return this.radioCustomMessage()||null}set customError(next){this.setCustomValidity(next??"")}acceptsCheckedWrite(previous,next){return previous!==next}checkedWritten(previous){this.isConnected&&this.group()?.radioCheckedChanged?.(this)}isDisabledByOwner(){return!!this.currentGroup()&&this._groupDisabled}reportsRequired(){return this.effectiveRequired}requiredMessage(){return this.localize("radioRequired")}commitFormValue(value){this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?value:null,this.checked?"checked":"unchecked")}updateValidity(){const owned=!!this.currentGroup(),violates=!this.isBarredFromValidation()&&!owned&&this.effectiveRequired&&!this.checked;this[SET_ANCHORED_VALIDITY](violates?{valueMissing:!0}:{},this.requiredMessage())}formResetCallback(){this.currentGroup()||super.formResetCallback()}formStateRestoreCallback(state2,reason){this.currentGroup()||(this.checked=state2==="checked")}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}syncFormState(){this.commitFormValue(this.value),this.updateValidity()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}willUpdate(changed){super.willUpdate(changed),this.swappingControl=this.hasUpdated&&changed.has("appearance")}updated(changed){super.updated(changed),this.swappingControl=!1,this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),super.disconnectedCallback()}resetFromGroup(){this.setInteracted(!1),this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}setCustomValidity(message){if(this.committingCustomError){this.resettingCustomError&&this.applyCustomValidity(message??"");return}const old=this.radioCustomMessage()||null;this.committingCustomError=!0;try{this.applyCustomValidity(message??""),this.reflectCustomError(this.radioCustomMessage())}finally{this.committingCustomError=!1}this.requestUpdate("customError",old)}applyCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message);return}this.validityController.setCustomValidity(message),this.syncValidityStates(),this.requestUpdate()}reflectCustomError(message){message?this.getAttribute("custom-error")!==message&&this.setAttribute("custom-error",message):this.hasAttribute("custom-error")&&this.removeAttribute("custom-error")}resetValidity(){if(this.committingCustomError)return;const old=this.radioCustomMessage()||null;this.committingCustomError=!0,this.resettingCustomError=!0;try{this.applyCustomValidity(""),this.reflectCustomError(this.radioCustomMessage())}finally{this.resettingCustomError=!1,this.committingCustomError=!1}this.requestUpdate("customError",old)}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!this.effectiveDisabled){if(this.checked||this.setInteracted(!0),group){group.selectRadio?.(this);return}this.checked||(this.checked=!0,this.uncheckSameNameRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})),this.emit("lr-activate",{value:this.value})}}uncheckSameNameRadios(){if(this.name)for(const other of this.getRootNode().querySelectorAll(`${tag("radio")},${tag("radio-button")}`))other!==this&&other.name===this.name&&other.form===this.form&&!other.currentGroup()&&(other.checked=!1)}get buttonRunPosition(){return this._buttonRunPosition}isNestedInteractiveEvent(event){const currentTarget=event.currentTarget;for(const entry of event.composedPath()){if(entry===currentTarget)break;if(entry&&typeof entry=="object"&&entry.nodeType===1&&isActionableElement(entry))return!0}return!1}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes??[]).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabel())}renderButtonContent(){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings/forms.generated.js";installFormControlLabelSupport();class LyraRadioBase extends LyraElement{}class LyraRadio extends CheckedFormAssociated(LyraRadioBase){constructor(){super(...arguments),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.recomputeHasLabel(),this.recomputeButtonAdornments()},["slot"]),this.swappingControl=!1,this.committingCustomError=!1,this.resettingCustomError=!1,this._radioName="",this._radioValue="on",this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this.onClick=event=>{if(event&&this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.select()},this.onKeyDown=event=>{if(this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{!this.effectiveDisabled&&!this.matches(":disabled")&&!this.swappingControl&&this.setInteracted(!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.labelTextObserver.bind(),this.recomputeButtonAdornments()}}static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}static{this.properties={appearance:{reflect:!0,converter:declaredDefaultConverter("default")},pill:{type:Boolean,reflect:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")}}}get name(){return this._radioName}set name(value){const old=this._radioName,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._radioName=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._radioValue}set value(value){const old=this._radioValue,next=value??"on";old!==next&&(this._radioValue=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}radioCustomMessage(){return this.currentGroup()?.customError??this.validityController.customValidityMessage}get customError(){return this.radioCustomMessage()||null}set customError(next){this.setCustomValidity(next??"")}acceptsCheckedWrite(previous,next){return previous!==next}checkedWritten(previous){this.isConnected&&this.group()?.radioCheckedChanged?.(this)}isDisabledByOwner(){return!!this.currentGroup()&&this._groupDisabled}reportsRequired(){return this.effectiveRequired}requiredMessage(){return this.localize("radioRequired")}commitFormValue(value){this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?value:null,this.checked?"checked":"unchecked")}updateValidity(){const owned=!!this.currentGroup(),violates=!this.isBarredFromValidation()&&!owned&&this.effectiveRequired&&!this.checked;this[SET_ANCHORED_VALIDITY](violates?{valueMissing:!0}:{},this.requiredMessage())}formResetCallback(){this.currentGroup()||super.formResetCallback()}formStateRestoreCallback(state2,reason){this.currentGroup()||(this.checked=state2==="checked")}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}syncFormState(){this.commitFormValue(this.value),this.updateValidity()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}willUpdate(changed){super.willUpdate(changed),this.swappingControl=this.hasUpdated&&changed.has("appearance")}updated(changed){super.updated(changed),this.swappingControl=!1,this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),super.disconnectedCallback()}resetFromGroup(){this.setInteracted(!1),this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}setCustomValidity(message){if(this.committingCustomError){this.resettingCustomError&&this.applyCustomValidity(message??"");return}const old=this.radioCustomMessage()||null;this.committingCustomError=!0;try{this.applyCustomValidity(message??""),this.reflectCustomError(this.radioCustomMessage())}finally{this.committingCustomError=!1}this.requestUpdate("customError",old)}applyCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message);return}this.validityController.setCustomValidity(message),this.syncValidityStates(),this.requestUpdate()}reflectCustomError(message){message?this.getAttribute("custom-error")!==message&&this.setAttribute("custom-error",message):this.hasAttribute("custom-error")&&this.removeAttribute("custom-error")}resetValidity(){if(this.committingCustomError)return;const old=this.radioCustomMessage()||null;this.committingCustomError=!0,this.resettingCustomError=!0;try{this.applyCustomValidity(""),this.reflectCustomError(this.radioCustomMessage())}finally{this.resettingCustomError=!1,this.committingCustomError=!1}this.requestUpdate("customError",old)}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!this.effectiveDisabled){if(this.checked||this.setInteracted(!0),group){group.selectRadio?.(this);return}this.checked||(this.checked=!0,this.uncheckSameNameRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})),this.emit("lr-activate",{value:this.value})}}uncheckSameNameRadios(){if(this.name)for(const other of this.getRootNode().querySelectorAll(`${tag("radio")},${tag("radio-button")}`))other!==this&&other.name===this.name&&other.form===this.form&&!other.currentGroup()&&(other.checked=!1)}get buttonRunPosition(){return this._buttonRunPosition}isNestedInteractiveEvent(event){const currentTarget=event.currentTarget;for(const entry of event.composedPath()){if(entry===currentTarget)break;if(entry&&typeof entry=="object"&&entry.nodeType===1&&isActionableElement(entry))return!0}return!1}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes??[]).filter(node=>isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!defaultLabelForwardingSlots(this).includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabel())}renderButtonContent(){return html`
|
|
2
2
|
<span part="start prefix" ?hidden=${!this.hasStart}>
|
|
3
3
|
<slot name="start" @slotchange=${this.onAdornmentSlotChange}></slot>
|
|
4
4
|
<slot name="prefix" @slotchange=${this.onAdornmentSlotChange}></slot>
|
|
@@ -164,4 +164,4 @@ click():void;
|
|
|
164
164
|
/** Moves focus to the internal switch control.*/
|
|
165
165
|
focus(options?:FocusOptions):void;
|
|
166
166
|
/** Removes focus from the internal switch control.*/
|
|
167
|
-
blur():void;private externalDescriptionLease?;private syncExternalDescription;protected updated(changed:PropertyValues):void;private releaseExternalDescription;connectedCallback():void;adoptedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;private setFromUser;private onClick;private onBlur;private onFocus;private onKeyDown;private
|
|
167
|
+
blur():void;private externalDescriptionLease?;private syncExternalDescription;protected updated(changed:PropertyValues):void;private releaseExternalDescription;connectedCallback():void;adoptedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;private setFromUser;private onClick;private onBlur;private onFocus;private onKeyDown;private recomputeHasLabelSlot;private handleLabelSlotChange;private onLabelSlotChange;private onSlotChange;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-switch':LyraSwitch;}}export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_switchRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraSwitchBase extends LyraElement{}class LyraSwitch extends CheckedFormAssociated(LyraSwitchBase){constructor(){super(...arguments),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.slotPresence=new SlotPresenceController(this),this.labelTextObserver=new AccessibleTextController(this,[""],()=>this.recomputeHasLabelSlot(),["slot"]),this.toggleGuard=new VetoWriteGuard,this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.setFromUser(!this.checked)},this.onBlur=event=>{this.liveDisabled||this.setInteracted(!0),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onKeyDown=e=>{if(!this.liveDisabled&&!e.repeat){if(e.key===" "||e.key==="Spacebar"){e.preventDefault(),this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}}},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event)}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,switchRequired:LYRA_DEFAULT_switchRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={size:{reflect:!0}}}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}checkedWritten(previous){markVetoGuardWrite(this.toggleGuard)}requiredMessage(){return this.localize("switchRequired")}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".switch-owner")??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}updated(changed){super.updated(changed),this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated?this.recomputeHasLabelSlot():this.seedFirstRenderState(()=>this.recomputeHasLabelSlot())}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}setFromUser(next){this.liveDisabled||this.checked!==next&&requestThenCommit({requestDetail:{checked:next,value:this.value},emitRequest:(detail,init)=>this.emit("lr-switch-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.setInteracted(!0),this.checked=next,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:this.checked,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked,value:this.value})}})}
|
|
1
|
+
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_switchRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraSwitchBase extends LyraElement{}class LyraSwitch extends CheckedFormAssociated(LyraSwitchBase){constructor(){super(...arguments),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.slotPresence=new SlotPresenceController(this),this.labelTextObserver=new AccessibleTextController(this,[""],()=>this.recomputeHasLabelSlot(),["slot"]),this.toggleGuard=new VetoWriteGuard,this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.setFromUser(!this.checked)},this.onBlur=event=>{this.liveDisabled||this.setInteracted(!0),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onKeyDown=e=>{if(!this.liveDisabled&&!e.repeat){if(e.key===" "||e.key==="Spacebar"){e.preventDefault(),this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}}},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event)}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,switchRequired:LYRA_DEFAULT_switchRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={size:{reflect:!0}}}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}checkedWritten(previous){markVetoGuardWrite(this.toggleGuard)}requiredMessage(){return this.localize("switchRequired")}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".switch-owner")??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}updated(changed){super.updated(changed),this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated?this.recomputeHasLabelSlot():this.seedFirstRenderState(()=>this.recomputeHasLabelSlot())}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}setFromUser(next){this.liveDisabled||this.checked!==next&&requestThenCommit({requestDetail:{checked:next,value:this.value},emitRequest:(detail,init)=>this.emit("lr-switch-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.setInteracted(!0),this.checked=next,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:this.checked,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked,value:this.value})}})}recomputeHasLabelSlot(){const renderRoot=this.renderRoot,childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(childNodes).filter(node=>isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}handleLabelSlotChange(event){const target=event.target;if(!(target?.nodeType!==1||target.localName!=="slot")){if(target.getRootNode()===this.renderRoot){if((target.getAttribute("name")??"")!=="")return}else if(!defaultLabelForwardingSlots(this).includes(target))return;this.labelTextObserver.bind(),this.recomputeHasLabelSlot()}}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||(this.hint??"").length>0||(this.helpText??"").length>0,hasError=this.hasErrorSlot||(this.errorText??"").length>0,describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" "),invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<span class="switch-layout" part="row" @click=${this.onClick}>
|
|
4
4
|
<span
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{finiteRange}from"../../../internal/numbers.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";const escapeOwners=new Set,rankings=new WeakMap,RANK="--_lr-map-anchor-rank",LIMIT=16;let raises=0,insertions=0;class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[],this.raisedAt=0,this.order=0,this.fresh=!0,this.listening=!1}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}stop(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0;const cleanup=this.cleanup;this.cleanup=void 0,cleanup?.(),this.overlay?.suspend()}schedule(){if(this.stop(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,wrapper=host.wrapper();return host.element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!host.pending()&&this.placedCoordinates===host.request()&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request()||!this.isOpen())return!1;this.closingState=!0;try{host.retire()}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&host.request()===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=restore&&wrapper?this.repairFrom(wrapper):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request())return;this.stop(),wrapper&&(wrapper.hidden=!0),rankings.get(host.element)?.delete(this)&&(wrapper?.style.removeProperty(RANK),MapAnchorController.rank(host.element)),host.placed?.(!1);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,this.fresh=!0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&this.repair(repair)}capture(){const wrapper=this.host.wrapper();return wrapper?this.repairFrom(wrapper):null}repair(snapshot){if(!snapshot)return;const repair=snapshot;applyComposedFocusRepair(repair,[repair.candidate,this.host.fallback?.()])}repairFrom(wrapper){const host=this.host,document=wrapper.ownerDocument,lost=host.lost?.(),active=deepActiveElement(document),candidate=()=>this.returnTarget??host.fallback?.()??null,target=lost&&(!active||active===document.body||active===document.documentElement)?candidate():null;return captureComposedFocusRepair(wrapper,candidate)??(lost&&target?{activeElement:lost,candidate:target,document,owner:wrapper}:null)}raise(escape=!0){!rankings.get(this.host.element)?.has(this)||!this.ranked()||(this.raisedAt=++raises,MapAnchorController.rank(this.host.element),escape&&this.reRegister())}ranked(){return!!this.host.child||[...rankings.get(this.host.element)??[]].some(member=>member.host.child)}enter(wrapper){const host=this.host,members=rankings.get(host.element)??new Set;rankings.set(host.element,members);const joined=!members.has(this);if(members.add(this),host.placed?.(!0),!host.child&&!this.listening&&(this.listening=!0,wrapper.addEventListener("pointerdown",()=>{this.raise()}),wrapper.addEventListener("focusout",()=>{queueMicrotask(()=>{this.focusOut()})})),!this.fresh){joined&&MapAnchorController.rank(host.element);return}if(this.fresh=!1,this.raise(!1),!(!host.autofocus?.()||composedContains(wrapper,deepActiveElement(wrapper.ownerDocument)))){for(const target of collectAutofocusElements(wrapper))if(focusFirstAvailable(target)||focusFirstAvailable(collectFocusableElements(target)))break}}static rank(map){const members=[...rankings.get(map)??[]],ranked=members.some(member=>member.host.child),active=deepActiveElement(map.ownerDocument),keys=new Map;for(const member of members){const wrapper=member.host.wrapper();keys.set(member,wrapper&&composedContains(wrapper,active)?raises+1:member.raisedAt)}return members.sort((a,b)=>keys.get(a)-keys.get(b)),members.forEach((member,index)=>{const style=member.host.wrapper()?.style;ranked?style?.setProperty(RANK,String(index)):style?.removeProperty(RANK)}),members}focusOut(){if(!this.ranked())return;[...MapAnchorController.rank(this.host.element)].reverse().find(member=>member.host.closable()&&member.isOpen())?.reRegister()}reRegister(){const host=this.host,overlay=this.overlay,wrapper=host.wrapper();if(!overlay||overlay.isTopmost()||!wrapper)return;let entries=[];observeOverlayStack(host.element.ownerDocument,snapshot=>{entries=snapshot.entries})();const index=entries.findIndex(entry=>entry.host===host.overlayHost),anchored=other=>[...escapeOwners].some(owner=>{const panel=owner.host.wrapper();return owner!==this&&(owner.host.overlayHost===other||!!panel&&composedContains(panel,other))});index<0||entries.slice(index+1).some(entry=>composedContains(wrapper,entry.host)||!anchored(entry.host))||(this.overlay=this.activate())}activate(below=!1){const host=this.host,document=host.element.ownerDocument,focused=below?[...escapeOwners].find(owner=>{const wrapper=owner.host.wrapper();return owner!==this&&owner.ranked()&&!!wrapper&&composedContains(wrapper,deepActiveElement(document))}):void 0,order=this.order=focused?focused.order-1/(++insertions+1):reserveOverlayOrder(document)(document);return activateNonmodalOverlay({host:host.overlayHost,panel:()=>host.wrapper()??null,onEscape:()=>{host.escape?host.escape():this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,orderReservation:destination=>destination===document?order:void 0})}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}syncOverlay(wrapper){const host=this.host,element=host.element;if(!host.closable()){const overlay=this.overlay;this.overlay=void 0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=this.activate(this.ranked());epoch===this.epoch&&this.placed&&element.isConnected&&host.closable()&&!this.overlay?(this.overlay=overlay,escapeOwners.add(this)):overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.content()?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(wrapper&&view&&!(previous instanceof view.Element&&composedContains(wrapper,previous))&&this.raise(),!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.request(),container=host.container();if(!container||!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90)return;const point=host.element.project([lng,lat]);if(!point)return;const[x,y]=point;return x>=0&&y>=0&&x<=container.clientWidth&&y<=container.clientHeight?point:void 0}sync(){const host=this.host,element=host.element;if(host.updateActive()){const[generation,connection]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style,current2]=host.generations();element.isConnected&¤t2===connection&&style===generation&&host.map()===map2&&this.sync()},`${host.key}-${connection}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}this.stop();const epoch=this.epoch,map=host.map(),coordinates=host.request(),boundary=host.boundary(),safeArea=host.safeArea(),direction=host.direction(),current=()=>element.isConnected&&host.map()===map&&host.styleLoaded()&&epoch===this.epoch&&host.request()===coordinates&&host.boundary()===boundary&&host.safeArea()===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0),edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`,host.child&&(fence.style.direction=direction);const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const placement=place(virtualAnchorFromRect({x:rect.left+point[0],y:rect.top+point[1],contextElement:container}),wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,shiftCrossAxis:!0,onPlaced:()=>{if(!current()||!this.hasContent())return;const first=!this.placed;first&&this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper),first&¤t()&&this.enter(wrapper))}});if(!current()){placement();return}this.cleanup=placement,placement.ready.then(ready=>{!ready&¤t()&&this.hide()})}catch{current()&&this.hide()}}}const CHILD_EVENTS=["focusin","focusout","pointerdown"];class MapAnchorChildren{constructor(host,anchors){this.host=host,this.entries=new Map,this.serial=0;for(const anchor of anchors)this.attach(anchor)}run(anchor,operation,value){const entry=this.entries.get(anchor);switch(operation){case"attach":this.sync(this.attach(anchor));return;case"detach":if(entry){for(const type of CHILD_EVENTS)anchor.removeEventListener(type,entry.listener);this.entries.delete(anchor),entry.controller.dispose(),this.sync(entry)}return;case"capture":return entry?.controller.capture();case"retire":entry&&(entry.open=!1,entry.focused=void 0,entry.controller.hide(!1,!0));return;case"repair":if(value){const repair=value;applyComposedFocusRepair(repair,[repair.candidate,this.host.canvas()])}return;case"focus":return entry?.controller.focus()??!1;default:entry&&this.sync(entry);return}}sync(only){this.each(only,controller=>{controller.sync()})}schedule(){this.each(void 0,controller=>{controller.schedule()})}stop(){for(const{controller}of this.entries.values())controller.stop()}hide(){for(const{controller,open}of this.entries.values())open&&controller.hide()}dispose(){for(const{controller}of this.entries.values())controller.dispose()}each(only,place2){const changed=this.admit();for(const[anchor,entry]of this.entries)only&&entry!==only&&!changed.has(entry)||(anchor.open?(entry.open=!0,place2(entry.controller)):entry.open&&(entry.open=!1,entry.controller.hide(!0,!0)))}admit(){const open=[...this.entries.keys()].filter(anchor=>anchor.open).sort((a,b)=>a.compareDocumentPosition(b)&2?1:-1);open.length>LIMIT&&devWarnOnce("lyra-map-anchor-limit",`<${this.host.element.localName}>: only the first ${LIMIT} open <${open[LIMIT].localName}> children are placed; later ones stay hidden until one closes.`);const changed=new Set;for(const[anchor,entry]of this.entries){const admitted=open.indexOf(anchor)<LIMIT&&anchor.open;admitted!==entry.admitted&&(entry.admitted=admitted,changed.add(entry))}return changed}attach(anchor){const existing=this.entries.get(anchor);if(existing)return existing;const host=this.host,shadow=selector=>anchor.shadowRoot?.querySelector(selector)??void 0,controller=new MapAnchorController({...host,key:`map-anchor-child-${++this.serial}`,overlayHost:anchor,child:!0,wrapper:()=>shadow('[part~="base"]'),fence:()=>shadow(".fence"),content:()=>anchor.shadowRoot?.querySelector("slot:not([name])"),styleLoaded:()=>host.engineReady(),request:()=>anchor.open&&entry.admitted&&!anchor.hidden?anchor.lngLat:null,boundary:()=>anchor.boundary===void 0?host.element.anchorBoundary:anchor.boundary,safeArea:()=>anchor.safeArea===void 0?host.element.anchorSafeArea:anchor.safeArea,closable:()=>anchor.closable,pending:()=>anchor.isUpdatePending,retire:()=>{},emitClose:()=>{},escape:()=>{anchor[MAP_ANCHOR_SEAM]("escape")},fallback:()=>host.canvas(),lost:()=>entry.focused,placed:placed=>{anchor[MAP_ANCHOR_SEAM](placed?"placed":"unplaced")},autofocus:()=>anchor[MAP_ANCHOR_SEAM]("autofocus")}),entry={controller,admitted:!1,open:!1,listener:event=>{if(event.type==="pointerdown"){controller.raise();return}const focus=event,next=focus.relatedTarget;event.type==="focusout"&&queueMicrotask(()=>{controller.focusOut()}),event.type==="focusin"?(entry.focused=focus.composedPath()[0],controller.focusIn(focus)):next?composedContains(anchor,next)||(entry.focused=void 0):queueMicrotask(()=>{anchor.isConnected&&entry.focused?.isConnected&&!composedContains(anchor,deepActiveElement(anchor.ownerDocument))&&(entry.focused=void 0)})}};for(const type of CHILD_EVENTS)anchor.addEventListener(type,entry.listener);return this.entries.set(anchor,entry),entry}}export{MapAnchorChildren,MapAnchorController};
|
|
1
|
+
import{deferredPlaceSession as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{finiteRange}from"../../../internal/numbers.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";const escapeOwners=new Set,rankings=new WeakMap,RANK="--_lr-map-anchor-rank",LIMIT=16;let raises=0,insertions=0;class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[],this.raisedAt=0,this.order=0,this.fresh=!0,this.listening=!1}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}invalidate(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0,this.placement?.handle?.invalidate(),this.overlay?.suspend()}stop(){this.invalidate();const placement=this.placement;this.placement=void 0,placement?.handle?.()}schedule(){if(this.invalidate(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,wrapper=host.wrapper();return host.element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!host.pending()&&this.placedCoordinates===host.request()&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request()||!this.isOpen())return!1;this.closingState=!0;try{host.retire()}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&host.request()===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=restore&&wrapper?this.repairFrom(wrapper):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request())return;this.stop(),wrapper&&(wrapper.hidden=!0),rankings.get(host.element)?.delete(this)&&(wrapper?.style.removeProperty(RANK),MapAnchorController.rank(host.element)),host.placed?.(!1);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,this.fresh=!0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&this.repair(repair)}capture(){const wrapper=this.host.wrapper();return wrapper?this.repairFrom(wrapper):null}repair(snapshot){if(!snapshot)return;const repair=snapshot;applyComposedFocusRepair(repair,[repair.candidate,this.host.fallback?.()])}repairFrom(wrapper){const host=this.host,document=wrapper.ownerDocument,lost=host.lost?.(),active=deepActiveElement(document),candidate=()=>this.returnTarget??host.fallback?.()??null,target=lost&&(!active||active===document.body||active===document.documentElement)?candidate():null;return captureComposedFocusRepair(wrapper,candidate)??(lost&&target?{activeElement:lost,candidate:target,document,owner:wrapper}:null)}raise(escape=!0){!rankings.get(this.host.element)?.has(this)||!this.ranked()||(this.raisedAt=++raises,MapAnchorController.rank(this.host.element),escape&&this.reRegister())}ranked(){return!!this.host.child||[...rankings.get(this.host.element)??[]].some(member=>member.host.child)}enter(wrapper){const host=this.host,members=rankings.get(host.element)??new Set;rankings.set(host.element,members);const joined=!members.has(this);if(members.add(this),host.placed?.(!0),!host.child&&!this.listening&&(this.listening=!0,wrapper.addEventListener("pointerdown",()=>{this.raise()}),wrapper.addEventListener("focusout",()=>{queueMicrotask(()=>{this.focusOut()})})),!this.fresh){joined&&MapAnchorController.rank(host.element);return}if(this.fresh=!1,this.raise(!1),!(!host.autofocus?.()||composedContains(wrapper,deepActiveElement(wrapper.ownerDocument)))){for(const target of collectAutofocusElements(wrapper))if(focusFirstAvailable(target)||focusFirstAvailable(collectFocusableElements(target)))break}}static rank(map){const members=[...rankings.get(map)??[]],ranked=members.some(member=>member.host.child),active=deepActiveElement(map.ownerDocument),keys=new Map;for(const member of members){const wrapper=member.host.wrapper();keys.set(member,wrapper&&composedContains(wrapper,active)?raises+1:member.raisedAt)}return members.sort((a,b)=>keys.get(a)-keys.get(b)),members.forEach((member,index)=>{const style=member.host.wrapper()?.style;ranked?style?.setProperty(RANK,String(index)):style?.removeProperty(RANK)}),members}focusOut(){if(!this.ranked())return;[...MapAnchorController.rank(this.host.element)].reverse().find(member=>member.host.closable()&&member.isOpen())?.reRegister()}reRegister(){const host=this.host,overlay=this.overlay,wrapper=host.wrapper();if(!overlay||overlay.isTopmost()||!wrapper)return;let entries=[];observeOverlayStack(host.element.ownerDocument,snapshot=>{entries=snapshot.entries})();const index=entries.findIndex(entry=>entry.host===host.overlayHost),anchored=other=>[...escapeOwners].some(owner=>{const panel=owner.host.wrapper();return owner!==this&&(owner.host.overlayHost===other||!!panel&&composedContains(panel,other))});index<0||entries.slice(index+1).some(entry=>composedContains(wrapper,entry.host)||!anchored(entry.host))||(this.overlay=this.activate())}activate(below=!1){const host=this.host,document=host.element.ownerDocument,focused=below?[...escapeOwners].find(owner=>{const wrapper=owner.host.wrapper();return owner!==this&&owner.ranked()&&!!wrapper&&composedContains(wrapper,deepActiveElement(document))}):void 0,order=this.order=focused?focused.order-1/(++insertions+1):reserveOverlayOrder(document)(document);return activateNonmodalOverlay({host:host.overlayHost,panel:()=>host.wrapper()??null,onEscape:()=>{host.escape?host.escape():this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,orderReservation:destination=>destination===document?order:void 0})}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}suspendAdmission(){this.cancelFrame(),this.hide(),!(this.placement||this.placed)&&(this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[])}syncOverlay(wrapper){const host=this.host,element=host.element;if(!host.closable()){const overlay=this.overlay;this.overlay=void 0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=this.activate(this.ranked());epoch===this.epoch&&this.placed&&element.isConnected&&host.closable()&&!this.overlay?(this.overlay=overlay,escapeOwners.add(this)):overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.content()?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(wrapper&&view&&!(previous instanceof view.Element&&composedContains(wrapper,previous))&&this.raise(),!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.request();if(!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(!(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90))return host.element.project([lng,lat])}sync(){const host=this.host,element=host.element;if(this.invalidate(),host.updateActive()){const[generation,connection2]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style2,current2]=host.generations();element.isConnected&¤t2===connection2&&style2===generation&&host.map()===map2&&this.sync()},`${host.key}-${connection2}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}const epoch=this.epoch,map=host.map(),coordinates=host.request(),document=element.ownerDocument,[style,connection]=host.generations(),boundary=host.boundary(),safeArea=host.safeArea(),direction=host.direction(),current=()=>element.isConnected&&element.ownerDocument===document&&host.map()===map&&host.styleLoaded()&&host.generations()[0]===style&&host.generations()[1]===connection&&host.wrapper()===wrapper&&host.container()===container&&host.fence()===fence&&epoch===this.epoch&&host.request()===coordinates&&host.boundary()===boundary&&host.safeArea()===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0);if(!current())return;const edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||!(point[0]>=0&&point[1]>=0&&point[0]<=width&&point[1]<=height)||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`,host.child&&(fence.style.direction=direction);const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const pointRect=virtualAnchorFromRect({x:rect.left+point[0],y:rect.top+point[1]}).getBoundingClientRect(),publish=()=>{if(!current()||!this.hasContent())return;const first=!this.placed;first&&this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper),first&¤t()&&this.enter(wrapper))},previous=this.placement;if(previous?.handle?.isActive()&&previous.document===document&&previous.map===map&&previous.wrapper===wrapper&&previous.container===container&&previous.fence===fence&&previous.direction===direction&&previous.style===style&&previous.connection===connection&&previous.boundaries.length===admitted.boundaries.length&&previous.boundaries.every((value,index)=>value===admitted.boundaries[index])&&previous.safeArea.blockStart===edges.blockStart&&previous.safeArea.blockEnd===edges.blockEnd&&previous.safeArea.inlineStart===edges.inlineStart&&previous.safeArea.inlineEnd===edges.inlineEnd){previous.rect=pointRect,previous.current=current,previous.publish=publish,previous.handle?.update();return}if(this.placement=void 0,previous?.handle?.(),!current())return;const placement={document,map,wrapper,container,fence,direction,style,connection,boundaries:admitted.boundaries,safeArea:edges,rect:pointRect,current,publish};this.placement=placement;const handle=place({contextElement:container,getBoundingClientRect:()=>placement.rect},wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,shiftCrossAxis:!0,onPlaced:()=>{this.placement===placement&&placement.publish()}});if(!current()||this.placement!==placement){this.placement===placement&&(this.placement=void 0),handle();return}placement.handle=handle,handle.ready.then(ready=>{!ready&&this.placement===placement&&placement.current()&&this.hide()})}catch{current()&&this.hide()}}}const CHILD_EVENTS=["focusin","focusout","pointerdown"];class MapAnchorChildren{constructor(host,anchors){this.host=host,this.entries=new Map,this.admittedControllers=new Set,this.serial=0;for(const anchor of anchors)this.attach(anchor)}run(anchor,operation,value){const entry=this.entries.get(anchor);switch(operation){case"attach":this.sync(this.attach(anchor));return;case"detach":if(entry){for(const type of CHILD_EVENTS)anchor.removeEventListener(type,entry.listener);this.entries.delete(anchor),entry.controller.dispose(),this.sync(entry)}return;case"capture":return entry?.controller.capture();case"retire":entry&&(entry.open=!1,entry.focused=void 0,entry.controller.hide(!1,!0));return;case"repair":if(value){const repair=value;applyComposedFocusRepair(repair,[repair.candidate,this.host.canvas()])}return;case"focus":return entry?.controller.focus()??!1;default:entry&&this.sync(entry);return}}sync(only){this.each(only,controller=>{controller.sync()})}schedule(){this.each(void 0,controller=>{controller.schedule()})}invalidate(){for(const controller of this.admittedControllers)controller.invalidate()}stop(){for(const{controller}of this.entries.values())controller.stop()}hide(){for(const{controller,open}of this.entries.values())open&&controller.hide()}dispose(){for(const{controller}of this.entries.values())controller.dispose()}each(only,place2){const changed=this.admit();for(const[anchor,entry]of this.entries)only&&entry!==only&&!changed.has(entry)||(anchor.open?(entry.open=!0,entry.admitted?place2(entry.controller):changed.has(entry)&&entry.controller.suspendAdmission()):entry.open&&(entry.open=!1,entry.controller.hide(!0,!0)))}admit(){const first=[];let open=0,overflow;for(const anchor of this.entries.keys()){if(!anchor.open||(++open>LIMIT&&(overflow??=anchor),first.length===LIMIT&&anchor.compareDocumentPosition(first[LIMIT-1])&2))continue;let low=0,high=first.length;for(;low<high;){const middle=low+high>>>1;anchor.compareDocumentPosition(first[middle])&2?low=middle+1:high=middle}first.splice(low,0,anchor),first.length>LIMIT&&first.pop()}overflow&&devWarnOnce("lyra-map-anchor-limit",`<${this.host.element.localName}>: only the first ${LIMIT} open <${overflow.localName}> children are placed; later ones stay hidden until one closes.`);const selected=new Set(first),changed=new Set;this.admittedControllers.clear();for(const[anchor,entry]of this.entries){const admitted=selected.has(anchor);admitted!==entry.admitted&&(entry.admitted=admitted,changed.add(entry)),admitted&&this.admittedControllers.add(entry.controller)}return changed}attach(anchor){const existing=this.entries.get(anchor);if(existing)return existing;const host=this.host,shadow=selector=>anchor.shadowRoot?.querySelector(selector)??void 0,controller=new MapAnchorController({...host,key:`map-anchor-child-${++this.serial}`,overlayHost:anchor,child:!0,wrapper:()=>shadow('[part~="base"]'),fence:()=>shadow(".fence"),content:()=>anchor.shadowRoot?.querySelector("slot:not([name])"),styleLoaded:()=>host.engineReady(),request:()=>anchor.open&&entry.admitted&&!anchor.hidden?anchor.lngLat:null,boundary:()=>anchor.boundary===void 0?host.element.anchorBoundary:anchor.boundary,safeArea:()=>anchor.safeArea===void 0?host.element.anchorSafeArea:anchor.safeArea,closable:()=>anchor.closable,pending:()=>anchor.isUpdatePending,retire:()=>{},emitClose:()=>{},escape:()=>{anchor[MAP_ANCHOR_SEAM]("escape")},fallback:()=>host.canvas(),lost:()=>entry.focused,placed:placed=>{anchor[MAP_ANCHOR_SEAM](placed?"placed":"unplaced")},autofocus:()=>anchor[MAP_ANCHOR_SEAM]("autofocus")}),entry={controller,admitted:!1,open:!1,listener:event=>{if(event.type==="pointerdown"){controller.raise();return}const focus=event,next=focus.relatedTarget;event.type==="focusout"&&queueMicrotask(()=>{controller.focusOut()}),event.type==="focusin"?(entry.focused=focus.composedPath()[0],controller.focusIn(focus)):next?composedContains(anchor,next)||(entry.focused=void 0):queueMicrotask(()=>{anchor.isConnected&&entry.focused?.isConnected&&!composedContains(anchor,deepActiveElement(anchor.ownerDocument))&&(entry.focused=void 0)})}};for(const type of CHILD_EVENTS)anchor.addEventListener(type,entry.listener);return this.entries.set(anchor,entry),entry}}export{MapAnchorChildren,MapAnchorController};
|