@aceshooting/lyra-ui 12.0.0 → 12.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/custom-elements.json +1 -1
- package/dist/autoloader.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
- package/dist/components/charts/chart/histogram-bin.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
- package/dist/components/charts/chart/lite-chart.class.js +6 -6
- package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +4 -1
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/table/table.class.d.ts +18 -4
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +2 -1
- package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
- package/dist/components/data/timeline/timeline-cluster.js +1 -0
- package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
- package/dist/components/data/timeline/timeline-item.class.js +13 -2
- package/dist/components/data/timeline/timeline-item.styles.js +65 -0
- package/dist/components/data/timeline/timeline.class.d.ts +83 -27
- package/dist/components/data/timeline/timeline.class.js +3 -3
- package/dist/components/data/timeline/timeline.d.ts +1 -0
- package/dist/components/data/timeline/timeline.js +1 -1
- package/dist/components/data/timeline/timeline.styles.js +14 -0
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
- package/dist/components/forms/combobox/combobox.class.js +3 -2
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/time-input-shared.d.ts +2 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
- package/dist/components/forms/radio/radio-button.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.d.ts +0 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +0 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +0 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +0 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
- package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
- package/dist/components/layout/details/accordion-owner.d.ts +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/menu-item.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/av-player/av-metadata.d.ts +0 -2
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +0 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +4 -1
- package/dist/components/media/map/map.class.d.ts +50 -12
- package/dist/components/media/map/map.class.js +2 -2
- package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
- package/dist/components/overlays/progress/progress-shared.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
- package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/utility/format/format-options.d.ts +0 -2
- package/dist/components/utility/format/format-options.js +1 -1
- package/dist/components/utility/icon/icon-resource.d.ts +0 -2
- package/dist/components/utility/icon/icon-resource.js +1 -1
- package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
- package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
- package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
- package/dist/custom-elements-jsx.d.ts +4 -4
- package/dist/events.d.ts +15 -0
- package/dist/internal/accessibility-visibility.d.ts +1 -1
- package/dist/internal/anchor-target.d.ts +1 -3
- package/dist/internal/anchor-target.js +2 -2
- package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
- package/dist/internal/anchored-overlay-runtime.js +1 -0
- package/dist/internal/announcement-text.d.ts +1 -1
- package/dist/internal/ansi.d.ts +0 -4
- package/dist/internal/ansi.js +1 -1
- package/dist/internal/aria-ownership.d.ts +2 -1
- package/dist/internal/default-strings.generated.d.ts +1 -0
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/focus-navigation.d.ts +3 -2
- package/dist/internal/form-associated.d.ts +0 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/form-control-labels.d.ts +0 -3
- package/dist/internal/form-control-labels.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +0 -13
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
- package/dist/internal/nonmodal-overlay-manager.js +1 -0
- package/dist/internal/overlay-manager.d.ts +4 -20
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.d.ts +66 -0
- package/dist/internal/overlay-stack.js +1 -0
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/lyra.d.ts +2 -3
- package/dist/svelte.d.ts +4 -4
- package/dist/translations/ar.js +1 -1
- package/dist/translations/de.js +1 -1
- package/dist/translations/es.js +1 -1
- package/dist/translations/fa.js +1 -1
- package/dist/translations/fr.js +1 -1
- package/dist/translations/he.js +1 -1
- package/dist/translations/ja.js +1 -1
- package/dist/translations/pt-BR.js +1 -1
- package/dist/translations/ru.js +1 -1
- package/dist/translations/zh-CN.js +1 -1
- package/dist/utilities/localization.js +1 -1
- package/dist/vue.d.ts +4 -4
- package/llms/components/lr-combobox.md +42 -0
- package/llms/components/lr-date-input.md +1 -1
- package/llms/components/lr-date-picker.md +1 -1
- package/llms/components/lr-filter-bar.md +2 -2
- package/llms/components/lr-heatmap.md +4 -1
- package/llms/components/lr-lite-chart.md +20 -8
- package/llms/components/lr-map.md +52 -22
- package/llms/components/lr-option.md +42 -0
- package/llms/components/lr-popover.md +39 -0
- package/llms/components/lr-table.md +7 -3
- package/llms/components/lr-timeline-item.md +49 -24
- package/llms/components/lr-timeline.md +49 -24
- package/llms-full.txt +224 -60
- package/package.json +3 -4
- package/vscode-css-data.json +21 -0
- package/vscode-html-data.json +12 -6
- package/web-types.json +47 -16
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;class LyraPopover extends LyraElement{constructor(){super(...arguments),this._open=!1,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.accessibleLabel="",this._popupRole="dialog",this._disabled=!1,this.resolvedSide="bottom",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=typeof this.attachInternals=="function"?this.attachInternals():void 0,this.onTriggerSlotChange=event=>{const next=event.target.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())},this.onTriggerClick=()=>{this.virtualAnchor||(this.syncTriggerA11y(),this.open?this.hide():this.show())},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get popupRole(){return this._popupRole}set popupRole(next){if(next===this._popupRole)return;const old=this._popupRole;this._popupRole=next,this.requestUpdate("popupRole",old)}get disabled(){return this._disabled}set disabled(next){const normalized=!!next;if(normalized===this._disabled)return;const old=this._disabled;this._disabled=normalized,this.requestUpdate("disabled",old),normalized&&this.open&&(this.hasUpdated?this.hide():this.open=!1)}get defaultDistance(){return DEFAULT_DISTANCE}get positioningStrategy(){return"fixed"}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole==="none"?void 0:this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return this.arrow&&!this.withoutArrow}get canOpen(){return!this.disabled}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){return path.includes(this)}onPopupPositioned(){this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1}),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),(changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole"))&&(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.positionPopup(),changed.has("open")&&(this.open?this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay()):(this.positionedAnchor=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger())),this.isConnected&&this.syncTriggerA11y())}connectedCallback(){if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.positionPopup()}}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.trigger?.removeEventListener("click",this.onTriggerClick),this.releaseTriggerA11y(),this.trigger=void 0,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.trigger){this.syncTriggerA11y();return}if(this.trigger?.removeEventListener("click",this.onTriggerClick),this.trigger=next,this.trigger&&this.trigger!==this.slottedTrigger&&this.trigger.addEventListener("click",this.onTriggerClick),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger,modal:!1,trapFocus:!1}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.trigger})}positionPopup(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.positioningStrategy,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),onPlaced:({placement,arrow})=>{const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0,becamePositioned&&this.updateComplete.then(()=>{this.open&&this.resolveAnchor()===anchor&&this.onPopupPositioned()});const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}syncTriggerA11y(){const trigger=this.trigger??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole==="none"?null:this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.trigger?resolveAccessibleTrigger(this.trigger):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.cleanup?.(),this.cleanup=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{loadAnchoredOverlayRuntime}from"../../../internal/anchored-overlay-runtime.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;class LyraPopover extends LyraElement{constructor(){super(...arguments),this._open=!1,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.accessibleLabel="",this._popupRole="dialog",this._disabled=!1,this.resolvedSide="bottom",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=typeof this.attachInternals=="function"?this.attachInternals():void 0,this.onTriggerSlotChange=event=>{const next=event.target.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())},this.onTriggerClick=()=>{this.virtualAnchor||(this.syncTriggerA11y(),this.open?this.hide():this.show())},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())}}static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,styles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get popupRole(){return this._popupRole}set popupRole(next){if(next===this._popupRole)return;const old=this._popupRole;this._popupRole=next,this.requestUpdate("popupRole",old)}get disabled(){return this._disabled}set disabled(next){const normalized=!!next;if(normalized===this._disabled)return;const old=this._disabled;this._disabled=normalized,this.requestUpdate("disabled",old),normalized&&this.open&&(this.hasUpdated?this.hide():this.open=!1)}get defaultDistance(){return DEFAULT_DISTANCE}get positioningStrategy(){return"fixed"}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole==="none"?void 0:this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return this.arrow&&!this.withoutArrow}get canOpen(){return!this.disabled}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){return path.includes(this)}onPopupPositioned(){this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1}),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),(changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole"))&&(this.open&&this.isConnected?this.positionPopup():changed.has("open")&&this.invalidatePositioning(),changed.has("open")&&(this.open?this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay()):(this.positionedAnchor=void 0,this.stopLightDismiss(),this.overlayHandle?.deactivate(),this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger())),this.isConnected&&this.syncTriggerA11y())}connectedCallback(){if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.positionPopup()}}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.invalidatePositioning(),this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.trigger?.removeEventListener("click",this.onTriggerClick),this.releaseTriggerA11y(),this.trigger=void 0,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.trigger){this.syncTriggerA11y();return}if(this.trigger?.removeEventListener("click",this.onTriggerClick),this.trigger=next,this.trigger&&this.trigger!==this.slottedTrigger&&this.trigger.addEventListener("click",this.onTriggerClick),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo,bounds=new DOMRect(normalizedRect.x,normalizedRect.y,normalizedRect.width,normalizedRect.height);if(this.virtualAnchor={getBoundingClientRect:()=>bounds,contextElement:normalizedRect.contextElement},this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.trigger})}positionPopup(){this.invalidatePositioning();const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1);const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startPositioning(generation,anchor,popup,arrowElement)}invalidatePositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startPositioning(generation,anchor,popup,arrowElement){try{const{place}=await loadAnchoredOverlayRuntime();if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.resolveAnchor()!==anchor||this.renderRoot.querySelector('[part~="popup"]')!==popup)return;const cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.positioningStrategy,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),onPlaced:({placement,arrow})=>{if(generation!==this.positioningGeneration)return;const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side),this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveAnchor()!==anchor||(this.resolveCurrentPositioning(!0),becamePositioned&&this.onPopupPositioned())})}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration)return;this.resolveCurrentPositioning(!1),this.forceClose({focusTrigger:!1})}}syncTriggerA11y(){const trigger=this.trigger??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole==="none"?null:this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.trigger?resolveAccessibleTrigger(this.trigger):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.invalidatePositioning(),this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open&&!this.anchorPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady)return}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
|
|
2
2
|
<span part="trigger" @click=${this.onTriggerClick} @keydown=${this.onTriggerKeyDown}>
|
|
3
3
|
<slot name="trigger" @slotchange=${this.onTriggerSlotChange}></slot>
|
|
4
4
|
</span>
|
|
@@ -184,6 +184,7 @@ export declare class LyraTooltip extends LyraElement<LyraTooltipEventMap> {
|
|
|
184
184
|
private readonly descriptionId;
|
|
185
185
|
private descriptionProxy?;
|
|
186
186
|
private contentObserver?;
|
|
187
|
+
private triggerSyncGeneration;
|
|
187
188
|
private stopLabelReferenceIdentityObservation?;
|
|
188
189
|
private readonly contentSlotListeners;
|
|
189
190
|
/** While an open tooltip contains a rootless custom element, rescan for a bounded initialization
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{composedAccessibilityTextResult}from"../../../internal/accessibility-visibility.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{tooltipStyles}from"./overlay.styles.js";import{LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_SHOW_DELAY=150,DEFAULT_HIDE_DELAY=0,DEFAULT_DISTANCE=8,MAX_SHADOW_CONTENT_SCAN_FRAMES=4;class LyraTooltip extends LyraElement{constructor(){super(...arguments),this._open=!1,this.trigger="hover focus",this.manual=!1,this.showDelay=150,this.hideDelay=0,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.disabled=!1,this.hoist=!1,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.content="",this.accessibleLabel="",this.namedTriggerMode=!0,this.interactiveContent=!1,this.resolvedSide="top",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.restoreFocusOnClose=!1,this.suppressTriggerFocusOpen=!1,this.openedByPointer=!1,this.tooltipId=nextId("tooltip"),this.descriptionId=nextId("tooltip-description"),this.contentSlotListeners=new Set,this.shadowContentScanAttempts=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.onTriggerSlotChange=event=>{this.syncNamedTriggerMode();const slot=event.target;this.slottedTriggerElement=slot.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()},this.onEnter=event=>{if(!this.disabled){if(this.syncTriggerA11y(),event.type==="focusin"){if(this.suppressTriggerFocusOpen||!this.opensOn("focus"))return}else if(!this.opensOn("hover"))return;event.type!=="focusin"&&(this.openedByPointer=!0),this.requestTransition(!0)}},this.onLeave=event=>{if(event.type==="focusout"?!this.opensOn("focus"):!this.opensOn("hover"))return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&this.triggerElement&&composedContains(this.triggerElement,next)||this.interactiveContent&&this.isPopupTarget(next)||this.requestTransition(!1)},this.onTriggerClick=()=>{this.disabled||this.opensOn("click")&&(this.syncTriggerA11y(),this._open?this.hide():this.show())},this.onPopupEnter=()=>{!this.interactiveContent||this.isManual||(this.cancelPendingTransition(),this.show())},this.onPopupLeave=event=>{if(!this.interactiveContent||this.isManual)return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&(this.triggerElement&&composedContains(this.triggerElement,next)||this.isPopupTarget(next))||this.requestTransition(!1)},this.onContentSlotChange=event=>{event.target?.localName==="slot"&&this.updateInteractiveContent()},this.onTriggerKeyDown=event=>{this.isManual||!this.open||event.key!=="Escape"||!this.overlayHandle?.isTopmost()||(event.preventDefault(),this.hide())}}static{this.defaultStrings={...super.defaultStrings,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,tooltipStyles]}get open(){return this._open}set open(next){const normalized=!!next;if(normalized||this.cancelPendingTransition(),normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get rendersArrow(){return this.arrow&&!this.withoutArrow}get activeContentSlot(){const selector=this.namedTriggerMode?'[part~="body"] slot:not([name])':'[part~="body"] slot[name="content"]';return(this.renderRoot??this.shadowRoot)?.querySelector(selector)??null}syncNamedTriggerMode(schedule=!0){const children=Array.from(this.children),hasNamedTrigger=children.some(child=>child.getAttribute("slot")==="trigger"),hasShoelaceContent=this.content.length>0||children.some(child=>child.getAttribute("slot")==="content"),next=hasNamedTrigger||!hasShoelaceContent;if(next===this.namedTriggerMode)return;const old=this.namedTriggerMode;this.namedTriggerMode=next,schedule&&this.hasUpdated&&this.requestUpdate("namedTriggerMode",old)}get triggerKeywords(){return new Set(String(this.trigger??"").trim().split(/\s+/).filter(Boolean))}get isManual(){const keywords=this.triggerKeywords;return this.manual||keywords.size===0||keywords.has("manual")}opensOn(keyword){return!this.isManual&&this.triggerKeywords.has(keyword)}willUpdate(changed){super.willUpdate(changed),this.syncNamedTriggerMode(!1),(changed.has("manual")||changed.has("trigger"))&&this.isManual&&this.cancelPendingTransition(),changed.has("disabled")&&this.disabled&&(this.cancelPendingTransition(),this._open&&(this.hasUpdated?this.hide():this.applyOpenState(!1))),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose(),changed.has("showDelay")&&this.pendingDirection==="show"&&this.requestTransition(!0),changed.has("hideDelay")&&this.pendingDirection==="hide"&&this.requestTransition(!1),changed.has("for")&&this.syncInteractionTrigger(),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){if(super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("hoist")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("interactiveContent")){if(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.position(),changed.has("open"))if(this.open)this.updateInteractiveContent(),this.isConnected&&this.requiresOverlayManager&&this.activateTooltipOverlay();else{this.positionedAnchor=void 0;const restoreFocus=this.restoreFocusOnClose;this.suppressTriggerFocusOpen=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.suppressTriggerFocusOpen=!1}this.overlayHandle=void 0,this.restoreFocusOnClose=!1,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger()}else changed.has("interactiveContent")&&this.open&&this.isConnected&&(this.requiresOverlayManager?this.activateTooltipOverlay():(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0));this.syncTriggerA11y()}(changed.has("content")||changed.has("accessibleLabel"))&&this.updateDescriptionProxy()}connectedCallback(){super.connectedCallback(),this.syncAnchorIdentityObservation(),this.ensureDescriptionProxy(),this.contentObserver?.disconnect();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.contentObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.syncNamedTriggerMode(),this.updateInteractiveContent()}):void 0,this.updateInteractiveContent(),this.syncInteractionTrigger(),this.hasUpdated&&this.open&&(this.position(),this.requiresOverlayManager&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateTooltipOverlay()))}disconnectedCallback(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cancelPendingTransition(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.suspend(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.releaseTriggerA11y(),this.triggerElement=void 0,this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.cancelShadowContentScan(),this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cancelPendingTransition(),this.cancelShadowContentScan(),this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose();return}nextAnchor!==this.positionedAnchor&&this.position()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTriggerElement??this.resolveForTrigger();this.adoptTrigger(next)}activateTooltipOverlay(){if(!this.isConnected)return;const restoreFocusTarget=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(restoreFocusTarget);return}this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>this.hide({restoreFocus:this.shouldRestoreFocusAfterEscape()}),restoreFocusTo:restoreFocusTarget,modal:!1,trapFocus:!1}),this.overlayHandle.focusAutofocus()}shouldRestoreFocusAfterEscape(){if(this.virtualAnchor)return this.returnFocusTo!==void 0;const active=this.ownerDocument.activeElement;return active!==null&&composedContains(this,active)}get requiresOverlayManager(){return this.open}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.activateTooltipOverlay(),this.position();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}show(){return this.cancelPendingTransition(),this.disabled||this._open?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emit("lr-show",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show")})}hide(options){return this.cancelPendingTransition(),this._open?this.transitionGate.request(!1,()=>{if(this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return options?.restoreFocus&&(this.restoreFocusOnClose=!0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")}):Promise.resolve()}forceClose(){return this.cancelPendingTransition(),this._open?(this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}applyOpenState(next){const old=this._open;this._open=next,next||this.cancelShadowContentScan(),next||(this.openedByPointer=!1),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",animation=popup?animateRegistered(this,popup,`tooltip.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:["--lr-transition-fast","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emit(event)}}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.triggerElement})}position(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}if(anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.open&&anchor&&popup){const arrowPadding=Math.max(0,finiteNumber(this.arrowPadding,0));this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute",offset:finiteNumber(this.distance,DEFAULT_DISTANCE),skidding:finiteNumber(this.skidding,0),arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding,onPlaced:({placement,arrow})=>{this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding,rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-tooltip-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}}syncTriggerA11y(){const trigger=this.triggerElement??null,proxy=this.open?this.descriptionProxy:void 0,contribution={descriptions:proxy?[proxy]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.triggerElement?resolveAccessibleTrigger(this.triggerElement):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}requestTransition(next){if(this.cancelPendingTransition(),this.disabled)return;const delay=this.interactionDelay(next);if(delay<=0){next?this.show():this.hide();return}this.pendingDirection=next?"show":"hide";const view=this.ownerDocument.defaultView;if(!view){this.pendingDirection=void 0;return}this.timerView=view;const timer=view.setTimeout(()=>{this.timerView!==view||this.timer!==timer||(this.timer=void 0,this.timerView=void 0,this.pendingDirection=void 0,next?this.show():this.hide())},delay);this.timer=timer}interactionDelay(showing){const value=showing?this.showDelay:this.hideDelay,fallback=showing?DEFAULT_SHOW_DELAY:DEFAULT_HIDE_DELAY,attribute=showing?"show-delay":"hide-delay";if(this.hasAttribute(attribute)||value!==fallback)return finiteDuration(value,fallback);const property2=showing?"--show-delay":"--hide-delay",match=(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(property2).trim()??"").match(/^(-?(?:\d+\.?\d*|\.\d+))(ms|s)$/i);if(!match)return fallback;const amount=Number(match[1]),milliseconds=match[2]?.toLowerCase()==="s"?amount*1e3:amount;return finiteDuration(milliseconds,fallback)}cancelPendingTransition(){this.timer!==void 0&&this.timerView?.clearTimeout(this.timer),this.timer=void 0,this.timerView=void 0,this.pendingDirection=void 0}bindTrigger(trigger){trigger.addEventListener("mouseenter",this.onEnter),trigger.addEventListener("mouseleave",this.onLeave),trigger.addEventListener("focusin",this.onEnter),trigger.addEventListener("focusout",this.onLeave),trigger.addEventListener("click",this.onTriggerClick),trigger.addEventListener("keydown",this.onTriggerKeyDown)}unbindTrigger(trigger){trigger.removeEventListener("mouseenter",this.onEnter),trigger.removeEventListener("mouseleave",this.onLeave),trigger.removeEventListener("focusin",this.onEnter),trigger.removeEventListener("focusout",this.onLeave),trigger.removeEventListener("click",this.onTriggerClick),trigger.removeEventListener("keydown",this.onTriggerKeyDown)}isTriggerHeld(trigger){try{if(trigger.matches(":hover"))return!0}catch{}const active=trigger.ownerDocument.activeElement;return active!==null&&composedContains(trigger,active)}adoptTrigger(next){if(next===this.triggerElement){this.syncTriggerA11y();return}const hadTrigger=this.triggerElement!==void 0;if(this.cancelPendingTransition(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.triggerElement=next,!this.triggerElement){this.syncTriggerA11y(),hadTrigger&&this.open&&!this.resolveAnchor()&&this.forceClose();return}this.bindTrigger(this.triggerElement),this.syncTriggerA11y(),hadTrigger&&this._open&&this.openedByPointer&&!this.isTriggerHeld(this.triggerElement)&&this.forceClose(),this.open&&this.position(),this.open&&this.interactiveContent&&this.activateTooltipOverlay()}isPopupTarget(target){if(target===null||target.nodeType!==1)return!1;const element=target,slot=this.activeContentSlot;return this.renderRoot.querySelector('[part~="popup"]')?.contains(element)===!0||slot?.assignedElements({flatten:!0}).some(root=>composedContains(root,element))===!0}clearContentSlotListeners(){for(const slot of this.contentSlotListeners)slot.removeEventListener("slotchange",this.onContentSlotChange);this.contentSlotListeners.clear()}syncContentSlotListeners(slots){const activeSlot=this.activeContentSlot;for(const slot of this.contentSlotListeners)slots.has(slot)&&slot!==activeSlot||(slot.removeEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.delete(slot));for(const slot of slots)slot===activeSlot||this.contentSlotListeners.has(slot)||(slot.addEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.add(slot))}inspectContent(){const snapshot={actionable:!1,assigned:!1,awaitingShadowRoot:!1,labelReferenceRoots:new Set,text:"",externalRoots:new Set,shadowRoots:new Set,forwardingSlots:new Set,composedAncestors:new Set},activeSlot=this.activeContentSlot;if(!activeSlot)return snapshot;snapshot.assigned=activeSlot.assignedNodes().length>0;const popup=this.renderRoot.querySelector('[part~="popup"]'),bypassClosedVisibility=popup?.hasAttribute("data-hidden")===!0,previousVisibility=popup?.style.getPropertyValue("visibility")??"",previousVisibilityPriority=popup?.style.getPropertyPriority("visibility")??"";if(popup&&bypassClosedVisibility){const hostVisibility=this.ownerDocument.defaultView?.getComputedStyle(this).visibility??"visible";popup.style.setProperty("visibility",hostVisibility)}try{const visitedContentElements=new Set,accessibilityText=composedAccessibilityTextResult(activeSlot,{shouldPruneNode:node=>{if(node.getRootNode()!==this.renderRoot&&!this.contains(node)&&snapshot.externalRoots.add(node),node.nodeType!==1)return!1;const element=node;return visitedContentElements.add(element),!isAccessibilitySubtreeExcluded(element)&&!isAccessibilityVisibilityHidden(element)&&isActionableElement(element)&&(snapshot.actionable=!0),element.localName==="slot"&&snapshot.forwardingSlots.add(element),element.shadowRoot?snapshot.shadowRoots.add(element.shadowRoot):element.localName.includes("-")&&(snapshot.awaitingShadowRoot=!0),!1},isSubtreeExcluded:element=>(!visitedContentElements.has(element)&&element!==this&&snapshot.composedAncestors.add(element),isAccessibilitySubtreeExcluded(element))});snapshot.text=accessibilityText.text.replace(/\s+/g," ").trim();for(const root of accessibilityText.labelReferenceRoots)snapshot.labelReferenceRoots.add(root);for(const reference of accessibilityText.referencedElements)snapshot.externalRoots.add(reference)}finally{popup&&bypassClosedVisibility&&(previousVisibility?popup.style.setProperty("visibility",previousVisibility,previousVisibilityPriority):popup.style.removeProperty("visibility"))}return snapshot}observeContentNode(node){if(this.contentObserver){if(node.nodeType===3){this.contentObserver.observe(node,{characterData:!0});return}node.nodeType!==1&&node.nodeType!==11||this.contentObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","aria-labelledby","alt","class","contenteditable","hidden","href","inert","open","role","slot","style","tabindex"],childList:!0,characterData:!0,subtree:!0})}}bindContentObservation(snapshot){if(this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.isConnected&&snapshot.labelReferenceRoots.size>0){const cleanups=[...snapshot.labelReferenceRoots].map(root=>observeOverlayAnchorIdentity(root,()=>this.updateInteractiveContent()));this.stopLabelReferenceIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}if(this.contentObserver){this.contentObserver.disconnect();for(const ancestor of snapshot.composedAncestors)ancestor===this||ancestor.getRootNode()===this.renderRoot||snapshot.externalRoots.has(ancestor)||this.contentObserver.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","inert","style"]});this.observeContentNode(this);for(const root of snapshot.externalRoots)this.observeContentNode(root);for(const root of snapshot.shadowRoots)this.observeContentNode(root)}}updateInteractiveContent(fromShadowContentScan=!1){fromShadowContentScan||(this.shadowContentScanAttempts=0);const snapshot=this.inspectContent();this.interactiveContent=snapshot.actionable,this.syncContentSlotListeners(snapshot.forwardingSlots),this.bindContentObservation(snapshot),this.scheduleShadowContentScan(snapshot.awaitingShadowRoot),this.updateDescriptionProxy(snapshot.text,snapshot.assigned)}scheduleShadowContentScan(awaitingShadowRoot){if(this.cancelShadowContentScan(!1),!awaitingShadowRoot||!this.open||!this.isConnected||this.shadowContentScanAttempts>=MAX_SHADOW_CONTENT_SCAN_FRAMES)return;const view=this.ownerDocument.defaultView;view&&(this.shadowContentScanView=view,this.shadowContentScanFrame=view.requestAnimationFrame(()=>{this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,this.shadowContentScanAttempts++,this.updateInteractiveContent(!0)}))}cancelShadowContentScan(resetAttempts=!0){this.shadowContentScanFrame!==void 0&&this.shadowContentScanView?.cancelAnimationFrame(this.shadowContentScanFrame),this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,resetAttempts&&(this.shadowContentScanAttempts=0)}ensureDescriptionProxy(){this.descriptionProxy||(this.descriptionProxy=this.ownerDocument.createElement("span"),this.descriptionProxy.id=this.descriptionId,this.descriptionProxy.slot="__lr-tooltip-description",this.descriptionProxy.hidden=!0,this.descriptionProxy.dataset.lyraTooltipDescription=""),this.descriptionProxy.parentElement!==this&&this.append(this.descriptionProxy),this.updateDescriptionProxy()}updateDescriptionProxy(contentText,assigned){if(!this.descriptionProxy)return;const hostLabel=this.getAttribute("aria-label"),snapshot=contentText===void 0||assigned===void 0?this.inspectContent():void 0,visibleContent=contentText??snapshot?.text??"",hasAssignment=assigned??snapshot?.assigned??!1,description=hostLabel!==null?hostLabel.trim():(this.accessibleLabel||visibleContent||(hasAssignment?"":this.content)).trim();this.descriptionProxy.textContent!==description&&(this.descriptionProxy.textContent=description)}render(){const hostLabel=this.getAttribute("aria-label"),propertyLabel=this.accessibleLabel??"",hasExplicitLabel=hostLabel!==null||propertyLabel.length>0,label=hostLabel!==null?hostLabel:propertyLabel,popupLabel=this.interactiveContent?hasExplicitLabel?label:this.localize("popover"):hasExplicitLabel?label: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--)(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{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{omittedEmptyStringConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{composedAccessibilityTextResult}from"../../../internal/accessibility-visibility.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{tooltipStyles}from"./overlay.styles.js";import{LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_SHOW_DELAY=150,DEFAULT_HIDE_DELAY=0,DEFAULT_DISTANCE=8,MAX_SHADOW_CONTENT_SCAN_FRAMES=4;class LyraTooltip extends LyraElement{constructor(){super(...arguments),this._open=!1,this.trigger="hover focus",this.manual=!1,this.showDelay=150,this.hideDelay=0,this.placement="top",this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.disabled=!1,this.hoist=!1,this.arrow=!0,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this.content="",this.accessibleLabel="",this.namedTriggerMode=!0,this.interactiveContent=!1,this.resolvedSide="top",this.anchorPositioned=!1,this.observedDirectAnchorWasConnected=!1,this.restoreFocusOnClose=!1,this.suppressTriggerFocusOpen=!1,this.openedByPointer=!1,this.tooltipId=nextId("tooltip"),this.descriptionId=nextId("tooltip-description"),this.triggerSyncGeneration=0,this.contentSlotListeners=new Set,this.shadowContentScanAttempts=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.onTriggerSlotChange=event=>{this.syncNamedTriggerMode();const slot=event.target;this.slottedTriggerElement=slot.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()},this.onEnter=event=>{if(!this.disabled){if(this.syncTriggerA11y(),event.type==="focusin"){if(this.suppressTriggerFocusOpen||!this.opensOn("focus"))return}else if(!this.opensOn("hover"))return;event.type!=="focusin"&&(this.openedByPointer=!0),this.requestTransition(!0)}},this.onLeave=event=>{if(event.type==="focusout"?!this.opensOn("focus"):!this.opensOn("hover"))return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&this.triggerElement&&composedContains(this.triggerElement,next)||this.interactiveContent&&this.isPopupTarget(next)||this.requestTransition(!1)},this.onTriggerClick=()=>{this.disabled||this.opensOn("click")&&(this.syncTriggerA11y(),this._open?this.hide():this.show())},this.onPopupEnter=()=>{!this.interactiveContent||this.isManual||(this.cancelPendingTransition(),this.show())},this.onPopupLeave=event=>{if(!this.interactiveContent||this.isManual)return;const next=event.relatedTarget;next!==null&&next.nodeType===1&&(this.triggerElement&&composedContains(this.triggerElement,next)||this.isPopupTarget(next))||this.requestTransition(!1)},this.onContentSlotChange=event=>{event.target?.localName==="slot"&&this.updateInteractiveContent()},this.onTriggerKeyDown=event=>{this.isManual||!this.open||event.key!=="Escape"||!this.overlayHandle?.isTopmost()||(event.preventDefault(),this.hide())}}static{this.defaultStrings={...super.defaultStrings,popover:LYRA_DEFAULT_popover}}static{this.styles=[LyraElement.styles,tooltipStyles]}get open(){return this._open}set open(next){const normalized=!!next;if(normalized||this.cancelPendingTransition(),normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.hide()}}get for(){return this._for}set for(next){this._for=next??""}get rendersArrow(){return this.arrow&&!this.withoutArrow}get activeContentSlot(){const selector=this.namedTriggerMode?'[part~="body"] slot:not([name])':'[part~="body"] slot[name="content"]';return(this.renderRoot??this.shadowRoot)?.querySelector(selector)??null}syncNamedTriggerMode(schedule=!0){const children=Array.from(this.children),hasNamedTrigger=children.some(child=>child.getAttribute("slot")==="trigger"),hasShoelaceContent=this.content.length>0||children.some(child=>child.getAttribute("slot")==="content"),next=hasNamedTrigger||!hasShoelaceContent;if(next===this.namedTriggerMode)return;const old=this.namedTriggerMode;this.namedTriggerMode=next,schedule&&this.hasUpdated&&this.requestUpdate("namedTriggerMode",old)}get triggerKeywords(){return new Set(String(this.trigger??"").trim().split(/\s+/).filter(Boolean))}get isManual(){const keywords=this.triggerKeywords;return this.manual||keywords.size===0||keywords.has("manual")}opensOn(keyword){return!this.isManual&&this.triggerKeywords.has(keyword)}willUpdate(changed){super.willUpdate(changed),this.syncNamedTriggerMode(!1),(changed.has("manual")||changed.has("trigger"))&&this.isManual&&this.cancelPendingTransition(),changed.has("disabled")&&this.disabled&&(this.cancelPendingTransition(),this._open&&(this.hasUpdated?this.hide():this.applyOpenState(!1))),changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose(),changed.has("showDelay")&&this.pendingDirection==="show"&&this.requestTransition(!0),changed.has("hideDelay")&&this.pendingDirection==="hide"&&this.requestTransition(!1),changed.has("for")&&this.syncInteractionTrigger(),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){if(super.updated(changed),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("open")||changed.has("placement")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("hoist")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("interactiveContent")){if(this.cleanup?.(),this.cleanup=void 0,this.open&&this.isConnected&&this.position(),changed.has("open"))if(this.open)this.updateInteractiveContent(),this.isConnected&&this.requiresOverlayManager&&this.activateTooltipOverlay();else{this.positionedAnchor=void 0;const restoreFocus=this.restoreFocusOnClose;this.suppressTriggerFocusOpen=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.suppressTriggerFocusOpen=!1}this.overlayHandle=void 0,this.restoreFocusOnClose=!1,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.syncInteractionTrigger()}else changed.has("interactiveContent")&&this.open&&this.isConnected&&(this.requiresOverlayManager?this.activateTooltipOverlay():(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0));this.syncTriggerA11y()}(changed.has("content")||changed.has("accessibleLabel"))&&this.updateDescriptionProxy()}connectedCallback(){super.connectedCallback();const triggerSyncGeneration=++this.triggerSyncGeneration,triggerSyncDocument=this.ownerDocument;this.syncAnchorIdentityObservation(),this.ensureDescriptionProxy(),this.contentObserver?.disconnect();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.contentObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.syncNamedTriggerMode(),this.updateInteractiveContent()}):void 0,this.updateInteractiveContent(),this.syncInteractionTrigger(),this.updateComplete.then(()=>{if(triggerSyncGeneration!==this.triggerSyncGeneration||!this.isConnected||this.ownerDocument!==triggerSyncDocument)return;const slot=this.renderRoot.querySelector('[part="trigger"] > slot');this.slottedTriggerElement=slot?.assignedElements({flatten:!0})[0],this.syncInteractionTrigger()}),this.hasUpdated&&this.open&&(this.position(),this.requiresOverlayManager&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateTooltipOverlay()))}disconnectedCallback(){this.triggerSyncGeneration++,this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cancelPendingTransition(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.suspend(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.releaseTriggerA11y(),this.triggerElement=void 0,this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.cancelShadowContentScan(),this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.triggerSyncGeneration++,this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.cancelPendingTransition(),this.cancelShadowContentScan(),this.contentObserver?.disconnect(),this.contentObserver=void 0,this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.clearContentSlotListeners(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose();return}nextAnchor!==this.positionedAnchor&&this.position()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTriggerElement??this.resolveForTrigger();this.adoptTrigger(next)}activateTooltipOverlay(){if(!this.isConnected)return;const restoreFocusTarget=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(restoreFocusTarget);return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>this.hide({restoreFocus:this.shouldRestoreFocusAfterEscape()}),restoreFocusTo:restoreFocusTarget}),this.overlayHandle.focusAutofocus()}shouldRestoreFocusAfterEscape(){if(this.virtualAnchor)return this.returnFocusTo!==void 0;const active=this.ownerDocument.activeElement;return active!==null&&composedContains(this,active)}get requiresOverlayManager(){return this.open}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo;if(this.virtualAnchor=virtualAnchorFromRect(normalizedRect),this.returnFocusTo=options?.returnFocusTo,this.syncInteractionTrigger(),this.open){this.activateTooltipOverlay(),this.position();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.syncInteractionTrigger())}show(){return this.cancelPendingTransition(),this.disabled||this._open?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emit("lr-show",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.applyOpenState(!0),this.settleTransition("lr-after-show")})}hide(options){return this.cancelPendingTransition(),this._open?this.transitionGate.request(!1,()=>{if(this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented){this.syncOpenAttribute();return}return options?.restoreFocus&&(this.restoreFocusOnClose=!0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")}):Promise.resolve()}forceClose(){return this.cancelPendingTransition(),this._open?(this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.applyOpenState(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}applyOpenState(next){const old=this._open;this._open=next,next||this.cancelShadowContentScan(),next||(this.openedByPointer=!1),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",animation=popup?animateRegistered(this,popup,`tooltip.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:["--lr-transition-fast","--lr-duration-fast"],easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&this.removeAttribute("data-closing"),this.emit(event)}}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.triggerElement})}position(){this.cleanup?.(),this.cleanup=void 0;const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}if(anchor!==this.positionedAnchor&&(this.anchorPositioned=!1),this.open&&anchor&&popup){const arrowPadding=Math.max(0,finiteNumber(this.arrowPadding,0));this.cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute",offset:finiteNumber(this.distance,DEFAULT_DISTANCE),skidding:finiteNumber(this.skidding,0),arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding,onPlaced:({placement,arrow})=>{this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding,rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-tooltip-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side)}})}}syncTriggerA11y(){const trigger=this.triggerElement??null,proxy=this.open?this.descriptionProxy:void 0,contribution={descriptions:proxy?[proxy]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.triggerElement?resolveAccessibleTrigger(this.triggerElement):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}requestTransition(next){if(this.cancelPendingTransition(),this.disabled)return;const delay=this.interactionDelay(next);if(delay<=0){next?this.show():this.hide();return}this.pendingDirection=next?"show":"hide";const view=this.ownerDocument.defaultView;if(!view){this.pendingDirection=void 0;return}this.timerView=view;const timer=view.setTimeout(()=>{this.timerView!==view||this.timer!==timer||(this.timer=void 0,this.timerView=void 0,this.pendingDirection=void 0,next?this.show():this.hide())},delay);this.timer=timer}interactionDelay(showing){const value=showing?this.showDelay:this.hideDelay,fallback=showing?DEFAULT_SHOW_DELAY:DEFAULT_HIDE_DELAY,attribute=showing?"show-delay":"hide-delay";if(this.hasAttribute(attribute)||value!==fallback)return finiteDuration(value,fallback);const property2=showing?"--show-delay":"--hide-delay",match=(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(property2).trim()??"").match(/^(-?(?:\d+\.?\d*|\.\d+))(ms|s)$/i);if(!match)return fallback;const amount=Number(match[1]),milliseconds=match[2]?.toLowerCase()==="s"?amount*1e3:amount;return finiteDuration(milliseconds,fallback)}cancelPendingTransition(){this.timer!==void 0&&this.timerView?.clearTimeout(this.timer),this.timer=void 0,this.timerView=void 0,this.pendingDirection=void 0}bindTrigger(trigger){trigger.addEventListener("mouseenter",this.onEnter),trigger.addEventListener("mouseleave",this.onLeave),trigger.addEventListener("focusin",this.onEnter),trigger.addEventListener("focusout",this.onLeave),trigger.addEventListener("click",this.onTriggerClick),trigger.addEventListener("keydown",this.onTriggerKeyDown)}unbindTrigger(trigger){trigger.removeEventListener("mouseenter",this.onEnter),trigger.removeEventListener("mouseleave",this.onLeave),trigger.removeEventListener("focusin",this.onEnter),trigger.removeEventListener("focusout",this.onLeave),trigger.removeEventListener("click",this.onTriggerClick),trigger.removeEventListener("keydown",this.onTriggerKeyDown)}isTriggerHeld(trigger){try{if(trigger.matches(":hover"))return!0}catch{}const active=trigger.ownerDocument.activeElement;return active!==null&&composedContains(trigger,active)}adoptTrigger(next){if(next===this.triggerElement){this.syncTriggerA11y();return}const hadTrigger=this.triggerElement!==void 0;if(this.cancelPendingTransition(),this.triggerElement&&this.unbindTrigger(this.triggerElement),this.triggerElement=next,!this.triggerElement){this.syncTriggerA11y(),hadTrigger&&this.open&&!this.resolveAnchor()&&this.forceClose();return}this.bindTrigger(this.triggerElement),this.syncTriggerA11y(),hadTrigger&&this._open&&this.openedByPointer&&!this.isTriggerHeld(this.triggerElement)&&this.forceClose(),this.open&&this.position(),this.open&&this.interactiveContent&&this.activateTooltipOverlay()}isPopupTarget(target){if(target===null||target.nodeType!==1)return!1;const element=target,slot=this.activeContentSlot;return this.renderRoot.querySelector('[part~="popup"]')?.contains(element)===!0||slot?.assignedElements({flatten:!0}).some(root=>composedContains(root,element))===!0}clearContentSlotListeners(){for(const slot of this.contentSlotListeners)slot.removeEventListener("slotchange",this.onContentSlotChange);this.contentSlotListeners.clear()}syncContentSlotListeners(slots){const activeSlot=this.activeContentSlot;for(const slot of this.contentSlotListeners)slots.has(slot)&&slot!==activeSlot||(slot.removeEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.delete(slot));for(const slot of slots)slot===activeSlot||this.contentSlotListeners.has(slot)||(slot.addEventListener("slotchange",this.onContentSlotChange),this.contentSlotListeners.add(slot))}inspectContent(){const snapshot={actionable:!1,assigned:!1,awaitingShadowRoot:!1,labelReferenceRoots:new Set,text:"",externalRoots:new Set,shadowRoots:new Set,forwardingSlots:new Set,composedAncestors:new Set},activeSlot=this.activeContentSlot;if(!activeSlot)return snapshot;snapshot.assigned=activeSlot.assignedNodes().length>0;const popup=this.renderRoot.querySelector('[part~="popup"]'),bypassClosedVisibility=popup?.hasAttribute("data-hidden")===!0,previousVisibility=popup?.style.getPropertyValue("visibility")??"",previousVisibilityPriority=popup?.style.getPropertyPriority("visibility")??"";if(popup&&bypassClosedVisibility){const hostVisibility=this.ownerDocument.defaultView?.getComputedStyle(this).visibility??"visible";popup.style.setProperty("visibility",hostVisibility)}try{const visitedContentElements=new Set,accessibilityText=composedAccessibilityTextResult(activeSlot,{shouldPruneNode:node=>{if(node.getRootNode()!==this.renderRoot&&!this.contains(node)&&snapshot.externalRoots.add(node),node.nodeType!==1)return!1;const element=node;return visitedContentElements.add(element),!isAccessibilitySubtreeExcluded(element)&&!isAccessibilityVisibilityHidden(element)&&isActionableElement(element)&&(snapshot.actionable=!0),element.localName==="slot"&&snapshot.forwardingSlots.add(element),element.shadowRoot?snapshot.shadowRoots.add(element.shadowRoot):element.localName.includes("-")&&(snapshot.awaitingShadowRoot=!0),!1},isSubtreeExcluded:element=>(!visitedContentElements.has(element)&&element!==this&&snapshot.composedAncestors.add(element),isAccessibilitySubtreeExcluded(element))});snapshot.text=accessibilityText.text.replace(/\s+/g," ").trim();for(const root of accessibilityText.labelReferenceRoots)snapshot.labelReferenceRoots.add(root);for(const reference of accessibilityText.referencedElements)snapshot.externalRoots.add(reference)}finally{popup&&bypassClosedVisibility&&(previousVisibility?popup.style.setProperty("visibility",previousVisibility,previousVisibilityPriority):popup.style.removeProperty("visibility"))}return snapshot}observeContentNode(node){if(this.contentObserver){if(node.nodeType===3){this.contentObserver.observe(node,{characterData:!0});return}node.nodeType!==1&&node.nodeType!==11||this.contentObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","aria-labelledby","alt","class","contenteditable","hidden","href","inert","open","role","slot","style","tabindex"],childList:!0,characterData:!0,subtree:!0})}}bindContentObservation(snapshot){if(this.stopLabelReferenceIdentityObservation?.(),this.stopLabelReferenceIdentityObservation=void 0,this.isConnected&&snapshot.labelReferenceRoots.size>0){const cleanups=[...snapshot.labelReferenceRoots].map(root=>observeOverlayAnchorIdentity(root,()=>this.updateInteractiveContent()));this.stopLabelReferenceIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}if(this.contentObserver){this.contentObserver.disconnect();for(const ancestor of snapshot.composedAncestors)ancestor===this||ancestor.getRootNode()===this.renderRoot||snapshot.externalRoots.has(ancestor)||this.contentObserver.observe(ancestor,{attributes:!0,attributeFilter:["aria-hidden","class","hidden","inert","style"]});this.observeContentNode(this);for(const root of snapshot.externalRoots)this.observeContentNode(root);for(const root of snapshot.shadowRoots)this.observeContentNode(root)}}updateInteractiveContent(fromShadowContentScan=!1){fromShadowContentScan||(this.shadowContentScanAttempts=0);const snapshot=this.inspectContent();this.interactiveContent=snapshot.actionable,this.syncContentSlotListeners(snapshot.forwardingSlots),this.bindContentObservation(snapshot),this.scheduleShadowContentScan(snapshot.awaitingShadowRoot),this.updateDescriptionProxy(snapshot.text,snapshot.assigned)}scheduleShadowContentScan(awaitingShadowRoot){if(this.cancelShadowContentScan(!1),!awaitingShadowRoot||!this.open||!this.isConnected||this.shadowContentScanAttempts>=MAX_SHADOW_CONTENT_SCAN_FRAMES)return;const view=this.ownerDocument.defaultView;view&&(this.shadowContentScanView=view,this.shadowContentScanFrame=view.requestAnimationFrame(()=>{this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,this.shadowContentScanAttempts++,this.updateInteractiveContent(!0)}))}cancelShadowContentScan(resetAttempts=!0){this.shadowContentScanFrame!==void 0&&this.shadowContentScanView?.cancelAnimationFrame(this.shadowContentScanFrame),this.shadowContentScanFrame=void 0,this.shadowContentScanView=void 0,resetAttempts&&(this.shadowContentScanAttempts=0)}ensureDescriptionProxy(){this.descriptionProxy||(this.descriptionProxy=this.ownerDocument.createElement("span"),this.descriptionProxy.id=this.descriptionId,this.descriptionProxy.slot="__lr-tooltip-description",this.descriptionProxy.hidden=!0,this.descriptionProxy.dataset.lyraTooltipDescription=""),this.descriptionProxy.parentElement!==this&&this.append(this.descriptionProxy),this.updateDescriptionProxy()}updateDescriptionProxy(contentText,assigned){if(!this.descriptionProxy)return;const hostLabel=this.getAttribute("aria-label"),snapshot=contentText===void 0||assigned===void 0?this.inspectContent():void 0,visibleContent=contentText??snapshot?.text??"",hasAssignment=assigned??snapshot?.assigned??!1,description=hostLabel!==null?hostLabel.trim():(this.accessibleLabel||visibleContent||(hasAssignment?"":this.content)).trim();this.descriptionProxy.textContent!==description&&(this.descriptionProxy.textContent=description)}render(){const hostLabel=this.getAttribute("aria-label"),propertyLabel=this.accessibleLabel??"",hasExplicitLabel=hostLabel!==null||propertyLabel.length>0,label=hostLabel!==null?hostLabel:propertyLabel,popupLabel=this.interactiveContent?hasExplicitLabel?label:this.localize("popover"):hasExplicitLabel?label:nothing;return html`
|
|
2
2
|
<span part="trigger">
|
|
3
3
|
${this.namedTriggerMode?html`<slot name="trigger" @slotchange=${this.onTriggerSlotChange}></slot>`:html`<slot @slotchange=${this.onTriggerSlotChange}></slot>`}
|
|
4
4
|
</span>
|
|
@@ -13,8 +13,6 @@
|
|
|
13
13
|
* values onto a string or number, so nothing needs the element's lifecycle.
|
|
14
14
|
*/
|
|
15
15
|
import { type ComposedAccessibilityTextOptions } from '../../../internal/accessibility-visibility.js';
|
|
16
|
-
/** Fallback `max` for both progress components, and the value a non-positive `max` falls back to. */
|
|
17
|
-
export declare const PROGRESS_DEFAULT_MAX = 100;
|
|
18
16
|
/** `max`, normalized to a finite number and guarded against `<= 0` -- which would otherwise
|
|
19
17
|
* divide-by-zero in `progressPercent()` -- falling back to `PROGRESS_DEFAULT_MAX`. */
|
|
20
18
|
export declare function progressSafeMax(max: number): number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{hostAriaLabel}from"../../../internal/a11y.js";import{composedAccessibilityText,composedAccessibleVisibleText}from"../../../internal/accessibility-visibility.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteRange}from"../../../internal/numbers.js";const PROGRESS_DEFAULT_MAX=100;function progressSafeMax(max){const normalized=finiteRange(max,PROGRESS_DEFAULT_MAX,0);return normalized>0?normalized:PROGRESS_DEFAULT_MAX}function progressSafeValue(value,safeMax){return finiteRange(value,0,0,safeMax)}function progressPercent(safeValue,safeMax){return safeValue/safeMax*100}function formatProgressPercent(locale,percent){return getNumberFormat(locale,{style:"percent",maximumFractionDigits:0}).format(percent/100)}function primeVisibilityCascade(nodes){const stack=[...nodes].reverse();let remaining=256;for(;stack.length>0&&remaining>0;){const node=stack.pop();if(!node||node.nodeType!==1)continue;const element=node;remaining--;try{element.ownerDocument.defaultView?.getComputedStyle(element).visibility}catch{}const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[],children=assigned.length>0?assigned:Array.from(element.childNodes);for(let index=children.length-1;index>=0;index--){const child=children[index];child&&stack.push(child)}}}function joinAccessibleVisibleText(nodes,options){const boundedRoots=Array.from(nodes).slice(0,256);return primeVisibilityCascade(boundedRoots),(options?composedAccessibilityText(boundedRoots,options):boundedRoots.map(composedAccessibleVisibleText).join(" ")).replace(/\s+/g," ").trim()}function resolveProgressLabel(host,parts){const authored=hostAriaLabel(host);return authored!==null?authored:parts.label||parts.accessibleLabel||parts.visibleText||parts.localizedFallback}export{
|
|
1
|
+
import{hostAriaLabel}from"../../../internal/a11y.js";import{composedAccessibilityText,composedAccessibleVisibleText}from"../../../internal/accessibility-visibility.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteRange}from"../../../internal/numbers.js";const PROGRESS_DEFAULT_MAX=100;function progressSafeMax(max){const normalized=finiteRange(max,PROGRESS_DEFAULT_MAX,0);return normalized>0?normalized:PROGRESS_DEFAULT_MAX}function progressSafeValue(value,safeMax){return finiteRange(value,0,0,safeMax)}function progressPercent(safeValue,safeMax){return safeValue/safeMax*100}function formatProgressPercent(locale,percent){return getNumberFormat(locale,{style:"percent",maximumFractionDigits:0}).format(percent/100)}function primeVisibilityCascade(nodes){const stack=[...nodes].reverse();let remaining=256;for(;stack.length>0&&remaining>0;){const node=stack.pop();if(!node||node.nodeType!==1)continue;const element=node;remaining--;try{element.ownerDocument.defaultView?.getComputedStyle(element).visibility}catch{}const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[],children=assigned.length>0?assigned:Array.from(element.childNodes);for(let index=children.length-1;index>=0;index--){const child=children[index];child&&stack.push(child)}}}function joinAccessibleVisibleText(nodes,options){const boundedRoots=Array.from(nodes).slice(0,256);return primeVisibilityCascade(boundedRoots),(options?composedAccessibilityText(boundedRoots,options):boundedRoots.map(composedAccessibleVisibleText).join(" ")).replace(/\s+/g," ").trim()}function resolveProgressLabel(host,parts){const authored=hostAriaLabel(host);return authored!==null?authored:parts.label||parts.accessibleLabel||parts.visibleText||parts.localizedFallback}export{formatProgressPercent,joinAccessibleVisibleText,progressPercent,progressSafeMax,progressSafeValue,resolveProgressLabel};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{normalizeSize}from"../../../internal/variants.js";import{styles}from"./rating.styles.js";import{dispatchNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{EXTERNAL_LABEL_HOST_SEMANTICS}from"../../../internal/form-control-labels.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rating}from"../../../internal/default-strings.generated.js";const DEFAULT_MAX=5,MAX_STARS=100,DEFAULT_PRECISION=1,MANAGED_ARIA_LABEL_ATTRIBUTE="data-lr-rating-managed-label",MIN_PRECISION=.01,STAR_POINTS="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2";function starOutline(){return svg`<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linejoin="round" aria-hidden="true" focusable="false"><polygon points=${STAR_POINTS}></polygon></svg>`}function starSolid(){return svg`<svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor" stroke="none" aria-hidden="true" focusable="false"><polygon points=${STAR_POINTS}></polygon></svg>`}class LyraRating extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rating:LYRA_DEFAULT_rating}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","max")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},value:{attribute:"value",type:Number,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},max:{type:Number,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get effectiveSize(){const value=this.size;return["2xs","xs","s","m","l","xl","small","medium","large"].includes(value)?normalizeSize(value):"m"}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=finiteNumber(next??0,0)}get rating(){return this.renderRoot.querySelector('[part~="rating"]')}constructor(){super(),this.precision=1,this.readonly=!1,this.accessibleLabel="",this.label="",this.size="m",this.hoverValue=0,this.hovering=!1,this._value=0,this._max=DEFAULT_MAX,this._name="",this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this._defaultValue=0,this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._hasInteracted=!1,this.authorAriaLabel=null,this.syncingHostSemantics=!1,this.externalLabelNameActive=!1,this.markInteracted=()=>{this._hasInteracted||(this._hasInteracted=!0,this.syncValidityStates())},this.onClick=event=>{const next=this.pointerValue(event);next!==null&&this.setValue(next)},this.onPointerEnter=event=>{this.interactive&&(this.hovering=!0,this.hoverValue=this.pointerValue(event)??this.hoverValue,this.emit("lr-hover",{phase:"start",value:this.hoverValue}))},this.onPointerMove=event=>{if(!this.interactive)return;const next=this.pointerValue(event);if(next!==null){if(!this.hovering){this.hovering=!0,this.hoverValue=next,this.emit("lr-hover",{phase:"start",value:next});return}next!==this.hoverValue&&(this.hoverValue=next,this.emit("lr-hover",{phase:"move",value:next}))}},this.onPointerEnd=()=>{this.hovering&&(this.hovering=!1,this.emit("lr-hover",{phase:"end",value:this.hoverValue}))},this.onKeyDown=event=>{const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";(event.key===forwardKey||event.key==="ArrowUp")&&(event.preventDefault(),this.setValue(this.safeValue+this.safePrecision)),(event.key===backwardKey||event.key==="ArrowDown")&&(event.preventDefault(),this.setValue(this.safeValue-this.safePrecision)),event.key==="Home"&&(event.preventDefault(),this.setValue(0)),event.key==="End"&&(event.preventDefault(),this.setValue(this.safeMax))},this.onHostKeyDown=event=>{event.composedPath()[0]===this&&this.onKeyDown(event)},this.onBlur=event=>{event.target===this&&this.markInteracted()},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),this.internals.setFormValue("0"),this.addEventListener("focusout",this.markInteracted),this.addEventListener("keydown",this.onHostKeyDown),this.addEventListener("blur",this.onBlur),this.syncValidityStates()}attributeChangedCallback(name,oldValue,value){if(!(this.syncingHostSemantics&&(name==="aria-label"||name==="role"))){if(super.attributeChangedCallback(name,oldValue,value),name==="aria-label"){const managed=this.getAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE),rehydratedManagedName=oldValue===null&&managed!==null&&managed===value;if(this.authorAriaLabel=rehydratedManagedName?null:value,!rehydratedManagedName){this.syncingHostSemantics=!0;try{this.removeAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE)}finally{this.syncingHostSemantics=!1}}}if(name==="role"&&value!=="slider"){this.syncingHostSemantics=!0;try{this.setAttribute("role","slider")}finally{this.syncingHostSemantics=!1}}}}[EXTERNAL_LABEL_HOST_SEMANTICS](operation){if(operation.type==="has-authored-name")return this.authorAriaLabel!==null;if(operation.type==="apply"){this.externalLabelNameActive=!0,this.syncingHostSemantics=!0;try{this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,operation.name),this.getAttribute("aria-label")!==operation.name&&this.setAttribute("aria-label",operation.name)}finally{this.syncingHostSemantics=!1}return}this.externalLabelNameActive=!1,this.syncingHostSemantics=!0;try{if(this.getAttribute("aria-label")===operation.appliedName)if(operation.hadPrevious){const previous=operation.previous??"";this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,previous),this.setAttribute("aria-label",previous)}else this.removeAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE),this.removeAttribute("aria-label")}finally{this.syncingHostSemantics=!1}this.authorAriaLabel===null&&this.syncHostSemantics()}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=typeof next=="number"?next:Number(next),this.syncFormValue(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next==null?0:typeof next=="number"?next:Number(next),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("default-value"):this.setAttribute("default-value",String(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get max(){return this._max}set max(next){const old=this._max;this._max=typeof next=="number"?next:Number(next),this.syncFormValue(),this.requestUpdate("max",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.resetHover(),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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.updateValidity(),this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityStates()}resetValidity(){this.setCustomValidity("")}formResetCallback(){this.resetHover(),this.restoreLiveValueFromDefault(),this._hasInteracted=!1,this.syncValidityStates()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?finiteNumber(Number(state2),0):0}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formDisabledCallback(fieldsetDisabled){this._fieldsetDisabled=fieldsetDisabled,fieldsetDisabled&&this.resetHover(),this.updateValidity(),this.requestUpdate()}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.syncHostSemantics()}disconnectedCallback(){super.disconnectedCallback(),this.resetHover()}get safeMax(){return finiteCount(this.max,DEFAULT_MAX,MAX_STARS)}get safeValue(){return finiteRange(this.value,0,0,this.safeMax)}get safePrecision(){const precision=finiteRange(this.precision,DEFAULT_PRECISION,MIN_PRECISION,this.safeMax);return precision>0?precision:DEFAULT_PRECISION}get interactive(){return!this.effectiveDisabled&&!this.readonly}syncFormValue(){this.internals&&(this.internals.setFormValue(String(this.safeValue)),this.updateValidity())}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.validityController&&(this.barredFromValidation?this.validityController.setValidity({}):this.required&&this.safeValue<=0?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.syncValidityStates())}syncValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this._hasInteracted,barred:this.barredFromValidation})}setValue(next){if(!this.interactive)return;this.markInteracted();const precision=this.safePrecision,clamped=Math.max(0,Math.min(this.safeMax,Math.round(next/precision)*precision));clamped!==this.value&&(this.value=clamped,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}pointerValue(event){const target=event.target?.closest?.("[data-value]");if(!target)return null;const star=Number(target.dataset.value);if(!Number.isFinite(star))return null;const rect=target.getBoundingClientRect(),precision=this.safePrecision;if(rect.width<=0)return Math.max(0,Math.min(this.safeMax,star));const physicalFraction=Math.max(0,Math.min(1,(event.clientX-rect.left)/rect.width)),logicalFraction=this.effectiveDirection==="rtl"?1-physicalFraction:physicalFraction,rawValue=star-1+logicalFraction;return Math.max(precision,Math.min(this.safeMax,Math.ceil(rawValue/precision)*precision))}resetHover(){this.hovering=!1,this.hoverValue=0}focus(options){this.effectiveDisabled||super.focus(options)}blur(){super.blur()}click(){this.effectiveDisabled||super.click()}captureHostNameProvenance(){if(this.externalLabelNameActive||this.authorAriaLabel!==null)return;const current=this.getAttribute("aria-label");if(current===null)return;const managed=this.getAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE);if(managed!==current&&(this.authorAriaLabel=current,managed!==null)){this.syncingHostSemantics=!0;try{this.removeAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE)}finally{this.syncingHostSemantics=!1}}}syncHostSemantics(){this.captureHostNameProvenance();const safeMax=this.safeMax,safeValue=this.safeValue,generatedLabel=this.accessibleLabel||this.label||this.localize("rating");this.syncingHostSemantics=!0;try{this.setAttribute("role","slider"),this.setAttribute("tabindex",this.effectiveDisabled?"-1":"0"),this.setAttribute("aria-valuemin","0"),this.setAttribute("aria-valuemax",String(safeMax)),this.setAttribute("aria-valuenow",String(safeValue)),this.setAttribute("aria-valuetext",getNumberFormat(this.effectiveLocale).format(safeValue)),this.setAttribute("aria-disabled",this.effectiveDisabled?"true":"false"),this.setAttribute("aria-readonly",this.readonly?"true":"false"),this.setAttribute("aria-required",this.required?"true":"false"),this.setAttribute("data-effective-size",this.effectiveSize),!this.externalLabelNameActive&&this.authorAriaLabel===null&&this.getAttribute("aria-label")!==generatedLabel?(this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,generatedLabel),this.setAttribute("aria-label",generatedLabel)):!this.externalLabelNameActive&&this.authorAriaLabel===null&&this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,generatedLabel)}finally{this.syncingHostSemantics=!1}}willUpdate(changed){super.willUpdate(changed),changed.has("readonly")&&!this.interactive&&this.resetHover(),this.syncHostSemantics()}updated(changed){super.updated(changed),changed.has("readonly")&&this.updateValidity()}symbol(star,selected){return this.getSymbol?this.getSymbol(star,selected):selected?starSolid():starOutline()}renderSymbol(star,selected){return html`<span aria-hidden="true" inert style="pointer-events: none"
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{normalizeSize}from"../../../internal/variants.js";import{styles}from"./rating.styles.js";import{dispatchNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{EXTERNAL_LABEL_HOST_SEMANTICS,installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_rating}from"../../../internal/default-strings.generated.js";const DEFAULT_MAX=5,MAX_STARS=100,DEFAULT_PRECISION=1,MANAGED_ARIA_LABEL_ATTRIBUTE="data-lr-rating-managed-label",MIN_PRECISION=.01,STAR_POINTS="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2";function starOutline(){return svg`<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linejoin="round" aria-hidden="true" focusable="false"><polygon points=${STAR_POINTS}></polygon></svg>`}function starSolid(){return svg`<svg width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor" stroke="none" aria-hidden="true" focusable="false"><polygon points=${STAR_POINTS}></polygon></svg>`}class LyraRating extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,rating:LYRA_DEFAULT_rating}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","max")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},value:{attribute:"value",type:Number,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},max:{type:Number,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get effectiveSize(){const value=this.size;return["2xs","xs","s","m","l","xl","small","medium","large"].includes(value)?normalizeSize(value):"m"}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=finiteNumber(next??0,0)}get rating(){return this.renderRoot.querySelector('[part~="rating"]')}constructor(){super(),this.precision=1,this.readonly=!1,this.accessibleLabel="",this.label="",this.size="m",this.hoverValue=0,this.hovering=!1,this._value=0,this._max=DEFAULT_MAX,this._name="",this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this._defaultValue=0,this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this._hasInteracted=!1,this.authorAriaLabel=null,this.syncingHostSemantics=!1,this.externalLabelNameActive=!1,this.markInteracted=()=>{this._hasInteracted||(this._hasInteracted=!0,this.syncValidityStates())},this.onClick=event=>{const next=this.pointerValue(event);next!==null&&this.setValue(next)},this.onPointerEnter=event=>{this.interactive&&(this.hovering=!0,this.hoverValue=this.pointerValue(event)??this.hoverValue,this.emit("lr-hover",{phase:"start",value:this.hoverValue}))},this.onPointerMove=event=>{if(!this.interactive)return;const next=this.pointerValue(event);if(next!==null){if(!this.hovering){this.hovering=!0,this.hoverValue=next,this.emit("lr-hover",{phase:"start",value:next});return}next!==this.hoverValue&&(this.hoverValue=next,this.emit("lr-hover",{phase:"move",value:next}))}},this.onPointerEnd=()=>{this.hovering&&(this.hovering=!1,this.emit("lr-hover",{phase:"end",value:this.hoverValue}))},this.onKeyDown=event=>{const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";(event.key===forwardKey||event.key==="ArrowUp")&&(event.preventDefault(),this.setValue(this.safeValue+this.safePrecision)),(event.key===backwardKey||event.key==="ArrowDown")&&(event.preventDefault(),this.setValue(this.safeValue-this.safePrecision)),event.key==="Home"&&(event.preventDefault(),this.setValue(0)),event.key==="End"&&(event.preventDefault(),this.setValue(this.safeMax))},this.onHostKeyDown=event=>{event.composedPath()[0]===this&&this.onKeyDown(event)},this.onBlur=event=>{event.target===this&&this.markInteracted()},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),this.internals.setFormValue("0"),this.addEventListener("focusout",this.markInteracted),this.addEventListener("keydown",this.onHostKeyDown),this.addEventListener("blur",this.onBlur),this.syncValidityStates()}attributeChangedCallback(name,oldValue,value){if(!(this.syncingHostSemantics&&(name==="aria-label"||name==="role"))){if(super.attributeChangedCallback(name,oldValue,value),name==="aria-label"){const managed=this.getAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE),rehydratedManagedName=oldValue===null&&managed!==null&&managed===value;if(this.authorAriaLabel=rehydratedManagedName?null:value,!rehydratedManagedName){this.syncingHostSemantics=!0;try{this.removeAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE)}finally{this.syncingHostSemantics=!1}}}if(name==="role"&&value!=="slider"){this.syncingHostSemantics=!0;try{this.setAttribute("role","slider")}finally{this.syncingHostSemantics=!1}}}}[EXTERNAL_LABEL_HOST_SEMANTICS](operation){if(operation.type==="has-authored-name")return this.authorAriaLabel!==null;if(operation.type==="apply"){this.externalLabelNameActive=!0,this.syncingHostSemantics=!0;try{this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,operation.name),this.getAttribute("aria-label")!==operation.name&&this.setAttribute("aria-label",operation.name)}finally{this.syncingHostSemantics=!1}return}this.externalLabelNameActive=!1,this.syncingHostSemantics=!0;try{if(this.getAttribute("aria-label")===operation.appliedName)if(operation.hadPrevious){const previous=operation.previous??"";this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,previous),this.setAttribute("aria-label",previous)}else this.removeAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE),this.removeAttribute("aria-label")}finally{this.syncingHostSemantics=!1}this.authorAriaLabel===null&&this.syncHostSemantics()}get value(){return this._value}set value(next){const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=typeof next=="number"?next:Number(next),this.syncFormValue(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next==null?0:typeof next=="number"?next:Number(next),this.reflectingDefaultValue=!0;try{next==null?this.removeAttribute("default-value"):this.setAttribute("default-value",String(this._defaultValue))}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get max(){return this._max}set max(next){const old=this._max;this._max=typeof next=="number"?next:Number(next),this.syncFormValue(),this.requestUpdate("max",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.resetHover(),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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.updateValidity(),this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityStates()}resetValidity(){this.setCustomValidity("")}formResetCallback(){this.resetHover(),this.restoreLiveValueFromDefault(),this._hasInteracted=!1,this.syncValidityStates()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?finiteNumber(Number(state2),0):0}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formDisabledCallback(fieldsetDisabled){this._fieldsetDisabled=fieldsetDisabled,fieldsetDisabled&&this.resetHover(),this.updateValidity(),this.requestUpdate()}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.syncHostSemantics()}disconnectedCallback(){super.disconnectedCallback(),this.resetHover()}get safeMax(){return finiteCount(this.max,DEFAULT_MAX,MAX_STARS)}get safeValue(){return finiteRange(this.value,0,0,this.safeMax)}get safePrecision(){const precision=finiteRange(this.precision,DEFAULT_PRECISION,MIN_PRECISION,this.safeMax);return precision>0?precision:DEFAULT_PRECISION}get interactive(){return!this.effectiveDisabled&&!this.readonly}syncFormValue(){this.internals&&(this.internals.setFormValue(String(this.safeValue)),this.updateValidity())}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.validityController&&(this.barredFromValidation?this.validityController.setValidity({}):this.required&&this.safeValue<=0?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.syncValidityStates())}syncValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this._hasInteracted,barred:this.barredFromValidation})}setValue(next){if(!this.interactive)return;this.markInteracted();const precision=this.safePrecision,clamped=Math.max(0,Math.min(this.safeMax,Math.round(next/precision)*precision));clamped!==this.value&&(this.value=clamped,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}pointerValue(event){const target=event.target?.closest?.("[data-value]");if(!target)return null;const star=Number(target.dataset.value);if(!Number.isFinite(star))return null;const rect=target.getBoundingClientRect(),precision=this.safePrecision;if(rect.width<=0)return Math.max(0,Math.min(this.safeMax,star));const physicalFraction=Math.max(0,Math.min(1,(event.clientX-rect.left)/rect.width)),logicalFraction=this.effectiveDirection==="rtl"?1-physicalFraction:physicalFraction,rawValue=star-1+logicalFraction;return Math.max(precision,Math.min(this.safeMax,Math.ceil(rawValue/precision)*precision))}resetHover(){this.hovering=!1,this.hoverValue=0}focus(options){this.effectiveDisabled||super.focus(options)}blur(){super.blur()}click(){this.effectiveDisabled||super.click()}captureHostNameProvenance(){if(this.externalLabelNameActive||this.authorAriaLabel!==null)return;const current=this.getAttribute("aria-label");if(current===null)return;const managed=this.getAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE);if(managed!==current&&(this.authorAriaLabel=current,managed!==null)){this.syncingHostSemantics=!0;try{this.removeAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE)}finally{this.syncingHostSemantics=!1}}}syncHostSemantics(){this.captureHostNameProvenance();const safeMax=this.safeMax,safeValue=this.safeValue,generatedLabel=this.accessibleLabel||this.label||this.localize("rating");this.syncingHostSemantics=!0;try{this.setAttribute("role","slider"),this.setAttribute("tabindex",this.effectiveDisabled?"-1":"0"),this.setAttribute("aria-valuemin","0"),this.setAttribute("aria-valuemax",String(safeMax)),this.setAttribute("aria-valuenow",String(safeValue)),this.setAttribute("aria-valuetext",getNumberFormat(this.effectiveLocale).format(safeValue)),this.setAttribute("aria-disabled",this.effectiveDisabled?"true":"false"),this.setAttribute("aria-readonly",this.readonly?"true":"false"),this.setAttribute("aria-required",this.required?"true":"false"),this.setAttribute("data-effective-size",this.effectiveSize),!this.externalLabelNameActive&&this.authorAriaLabel===null&&this.getAttribute("aria-label")!==generatedLabel?(this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,generatedLabel),this.setAttribute("aria-label",generatedLabel)):!this.externalLabelNameActive&&this.authorAriaLabel===null&&this.setAttribute(MANAGED_ARIA_LABEL_ATTRIBUTE,generatedLabel)}finally{this.syncingHostSemantics=!1}}willUpdate(changed){super.willUpdate(changed),changed.has("readonly")&&!this.interactive&&this.resetHover(),this.syncHostSemantics()}updated(changed){super.updated(changed),changed.has("readonly")&&this.updateValidity()}symbol(star,selected){return this.getSymbol?this.getSymbol(star,selected):selected?starSolid():starOutline()}renderSymbol(star,selected){return html`<span aria-hidden="true" inert style="pointer-events: none"
|
|
2
2
|
>${this.symbol(star,selected)}</span
|
|
3
3
|
>`}render(){const safeMax=this.safeMax,safeValue=this.safeValue,displayValue=this.hovering&&this.interactive?Math.min(this.hoverValue,safeMax):safeValue,count=Math.round(safeMax);return html`<div
|
|
4
4
|
part="base rating"
|
|
@@ -11,11 +11,11 @@ export interface CanvasCamera {
|
|
|
11
11
|
x: number;
|
|
12
12
|
y: number;
|
|
13
13
|
}
|
|
14
|
-
|
|
14
|
+
interface CanvasHull {
|
|
15
15
|
d: string;
|
|
16
16
|
fill: string;
|
|
17
17
|
}
|
|
18
|
-
|
|
18
|
+
interface CanvasLink {
|
|
19
19
|
x1: number;
|
|
20
20
|
y1: number;
|
|
21
21
|
x2: number;
|
|
@@ -27,12 +27,12 @@ export interface CanvasLink {
|
|
|
27
27
|
selected?: boolean;
|
|
28
28
|
dimmed?: boolean;
|
|
29
29
|
}
|
|
30
|
-
|
|
30
|
+
interface CanvasEdgeLabel {
|
|
31
31
|
x: number;
|
|
32
32
|
y: number;
|
|
33
33
|
text: string;
|
|
34
34
|
}
|
|
35
|
-
|
|
35
|
+
interface CanvasNode {
|
|
36
36
|
x: number;
|
|
37
37
|
y: number;
|
|
38
38
|
r: number;
|
|
@@ -41,31 +41,31 @@ export interface CanvasNode {
|
|
|
41
41
|
selected?: boolean;
|
|
42
42
|
dimmed?: boolean;
|
|
43
43
|
}
|
|
44
|
-
|
|
44
|
+
interface CanvasNodeLabel {
|
|
45
45
|
x: number;
|
|
46
46
|
y: number;
|
|
47
47
|
text: string;
|
|
48
48
|
}
|
|
49
|
-
|
|
49
|
+
interface CanvasRing {
|
|
50
50
|
x: number;
|
|
51
51
|
y: number;
|
|
52
52
|
r: number;
|
|
53
53
|
}
|
|
54
|
-
|
|
54
|
+
interface CanvasFocusLink {
|
|
55
55
|
x1: number;
|
|
56
56
|
y1: number;
|
|
57
57
|
x2: number;
|
|
58
58
|
y2: number;
|
|
59
59
|
width: number;
|
|
60
60
|
}
|
|
61
|
-
|
|
61
|
+
interface CanvasFocusHull {
|
|
62
62
|
d: string;
|
|
63
63
|
}
|
|
64
64
|
/** A "+" expand badge to draw at a node's diagonally-upper-right edge -- `x`/`y`/`r` are the
|
|
65
65
|
* owning node's own world-space center and radius, mirroring `graph.class.ts`'s SVG
|
|
66
66
|
* `[part="expand-indicator"]` `<g transform="translate(x,y)">` placement so the badge lands at
|
|
67
67
|
* the identical offset in either renderer. */
|
|
68
|
-
|
|
68
|
+
interface CanvasExpandIndicator {
|
|
69
69
|
x: number;
|
|
70
70
|
y: number;
|
|
71
71
|
r: number;
|
|
@@ -147,3 +147,4 @@ export declare function drawPickingScene(ctx: CanvasRenderingContext2D, camera:
|
|
|
147
147
|
links: PickableLink[];
|
|
148
148
|
nodes: PickableNode[];
|
|
149
149
|
}): void;
|
|
150
|
+
export {};
|
|
@@ -40,10 +40,6 @@ export interface MindMapLayoutResult {
|
|
|
40
40
|
centerX: number;
|
|
41
41
|
centerY: number;
|
|
42
42
|
}
|
|
43
|
-
/** Returns the first occurrence of each nonblank topic identity across the complete hierarchy.
|
|
44
|
-
* Invalid/duplicate roots drop their subtree; duplicate descendants are omitted from the later
|
|
45
|
-
* parent. Retained ids and labels are never trimmed or rewritten. */
|
|
46
|
-
export declare function normalizeMindMapTopics(topics: readonly LyraTopic[]): readonly LyraTopic[];
|
|
47
43
|
/**
|
|
48
44
|
* Lays out `topics` as a radial tree: root at the center, each depth ring at radius `depth *
|
|
49
45
|
* ringGap`, each parent's children dividing its own inherited angular arc proportionally to their
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{minMax}from"../../data/heatmap/heatmap-scale.js";import{isNonBlankIdentity}from"../retrieval-identity.js";function normalizeMindMapTopics(topics){const seen=new Set,normalize=values=>{const source=Array.isArray(values)?values:[],retained=[];for(const topic of source){if(topic===null||typeof topic!="object"||!isNonBlankIdentity(topic.id)||seen.has(topic.id))continue;seen.add(topic.id);const children=normalize(topic.children??[]);retained.push(Object.freeze({...topic,...topic.children===void 0?{}:{children}}))}return Object.freeze(retained)};return normalize(topics)}const LAYOUT_PADDING=60;function syntheticHubIdentity(topics){const ids=new Set,collect=values=>{for(const topic of values)ids.add(topic.id),collect(topic.children??[])};collect(topics);let identity="__hub__";for(;ids.has(identity);)identity=`_${identity}`;return identity}function visibleLeafCount(node,depth,opts){const children=node.children??[];return children.length===0||!opts.isExpanded(node.id,depth)?1:Math.max(1,children.reduce((sum,c)=>sum+visibleLeafCount(c,depth+1,opts),0))}function place(node,depth,angleStart,angleEnd,parentId,cx,cy,opts,out,links){const angle=(angleStart+angleEnd)/2,r=depth*opts.ringGap,dir=opts.rtl?-1:1,x=cx+dir*r*Math.sin(angle),y=cy-r*Math.cos(angle),hasChildren=node.children.length>0,expanded=hasChildren&&opts.isExpanded(node.id,depth);if(out.push({id:node.id,label:node.label,depth,x,y,angle,parentId,hasChildren,expanded}),parentId&&links.push({fromId:parentId,toId:node.id}),!hasChildren||!expanded)return;const counts=node.children.map(c=>visibleLeafCount(c,depth+1,opts)),total=counts.reduce((a,b)=>a+b,0)||1,span=angleEnd-angleStart;let cursor=angleStart;node.children.forEach((child,i)=>{const childSpan=counts[i]/total*span;place({id:child.id,label:child.label,children:child.children??[]},depth+1,cursor,cursor+childSpan,node.id,cx,cy,opts,out,links),cursor+=childSpan})}function layoutMindMap(topics,hubLabel,opts){const normalizedTopics=normalizeMindMapTopics(topics);if(normalizedTopics.length===0)return{placed:[],links:[],width:0,height:0,centerX:0,centerY:0};const root=normalizedTopics.length===1?{id:normalizedTopics[0].id,label:normalizedTopics[0].label,children:normalizedTopics[0].children??[]}:{id:syntheticHubIdentity(normalizedTopics),label:hubLabel,children:normalizedTopics},placed=[],links=[];place(root,0,0,2*Math.PI,null,0,0,opts,placed,links);const[xLo,xHi]=minMax(placed.map(p=>p.x))??[0,0],[yLo,yHi]=minMax(placed.map(p=>p.y))??[0,0],minX=xLo-LAYOUT_PADDING,maxX=xHi+LAYOUT_PADDING,minY=yLo-LAYOUT_PADDING,maxY=yHi+LAYOUT_PADDING;return{placed:placed.map(p=>({...p,x:p.x-minX,y:p.y-minY})),links,width:maxX-minX,height:maxY-minY,centerX:-minX,centerY:-minY}}export{layoutMindMap
|
|
1
|
+
import{minMax}from"../../data/heatmap/heatmap-scale.js";import{isNonBlankIdentity}from"../retrieval-identity.js";function normalizeMindMapTopics(topics){const seen=new Set,normalize=values=>{const source=Array.isArray(values)?values:[],retained=[];for(const topic of source){if(topic===null||typeof topic!="object"||!isNonBlankIdentity(topic.id)||seen.has(topic.id))continue;seen.add(topic.id);const children=normalize(topic.children??[]);retained.push(Object.freeze({...topic,...topic.children===void 0?{}:{children}}))}return Object.freeze(retained)};return normalize(topics)}const LAYOUT_PADDING=60;function syntheticHubIdentity(topics){const ids=new Set,collect=values=>{for(const topic of values)ids.add(topic.id),collect(topic.children??[])};collect(topics);let identity="__hub__";for(;ids.has(identity);)identity=`_${identity}`;return identity}function visibleLeafCount(node,depth,opts){const children=node.children??[];return children.length===0||!opts.isExpanded(node.id,depth)?1:Math.max(1,children.reduce((sum,c)=>sum+visibleLeafCount(c,depth+1,opts),0))}function place(node,depth,angleStart,angleEnd,parentId,cx,cy,opts,out,links){const angle=(angleStart+angleEnd)/2,r=depth*opts.ringGap,dir=opts.rtl?-1:1,x=cx+dir*r*Math.sin(angle),y=cy-r*Math.cos(angle),hasChildren=node.children.length>0,expanded=hasChildren&&opts.isExpanded(node.id,depth);if(out.push({id:node.id,label:node.label,depth,x,y,angle,parentId,hasChildren,expanded}),parentId&&links.push({fromId:parentId,toId:node.id}),!hasChildren||!expanded)return;const counts=node.children.map(c=>visibleLeafCount(c,depth+1,opts)),total=counts.reduce((a,b)=>a+b,0)||1,span=angleEnd-angleStart;let cursor=angleStart;node.children.forEach((child,i)=>{const childSpan=counts[i]/total*span;place({id:child.id,label:child.label,children:child.children??[]},depth+1,cursor,cursor+childSpan,node.id,cx,cy,opts,out,links),cursor+=childSpan})}function layoutMindMap(topics,hubLabel,opts){const normalizedTopics=normalizeMindMapTopics(topics);if(normalizedTopics.length===0)return{placed:[],links:[],width:0,height:0,centerX:0,centerY:0};const root=normalizedTopics.length===1?{id:normalizedTopics[0].id,label:normalizedTopics[0].label,children:normalizedTopics[0].children??[]}:{id:syntheticHubIdentity(normalizedTopics),label:hubLabel,children:normalizedTopics},placed=[],links=[];place(root,0,0,2*Math.PI,null,0,0,opts,placed,links);const[xLo,xHi]=minMax(placed.map(p=>p.x))??[0,0],[yLo,yHi]=minMax(placed.map(p=>p.y))??[0,0],minX=xLo-LAYOUT_PADDING,maxX=xHi+LAYOUT_PADDING,minY=yLo-LAYOUT_PADDING,maxY=yHi+LAYOUT_PADDING;return{placed:placed.map(p=>({...p,x:p.x-minX,y:p.y-minY})),links,width:maxX-minX,height:maxY-minY,centerX:-minX,centerY:-minY}}export{layoutMindMap};
|
|
@@ -14,8 +14,6 @@ export type LyraRelativeTimeNumeric = 'always' | 'auto';
|
|
|
14
14
|
/** Attribute converter shared by date-formatting elements. Numeric markup denotes epoch
|
|
15
15
|
* milliseconds, while every other string remains an ISO/date string for the platform parser. */
|
|
16
16
|
export declare const dateSourceConverter: ComplexAttributeConverter<string | number | Date>;
|
|
17
|
-
/** Runtime guard for public literal-union properties assigned through untyped JS or markup. */
|
|
18
|
-
export declare function closedValue<T extends string>(value: unknown, values: readonly T[], fallback: T): T;
|
|
19
17
|
export interface NumberFormatInputs {
|
|
20
18
|
type: LyraFormatNumberType;
|
|
21
19
|
notation: LyraFormatNumberNotation;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{finiteInteger,finiteRange}from"../../../internal/numbers.js";const NUMBER_TYPES=["currency","decimal","percent"],NUMBER_NOTATIONS=["standard","compact","scientific","engineering"],CURRENCY_DISPLAYS=["symbol","narrowSymbol","code","name"],DISPLAY_STYLES=["long","short","narrow"],BYTE_UNITS=["byte","kilobyte","megabyte","gigabyte","terabyte","petabyte"],BIT_UNITS=["bit","kilobit","megabit","gigabit","terabit","petabit"],DATE_STYLES=["full","long","medium","short"],DATE_TEXT_STYLES=["narrow","short","long"],DATE_NUMERIC_STYLES=["numeric","2-digit"],MONTH_STYLES=["numeric","2-digit","narrow","short","long"],TIME_ZONE_NAME_STYLES=["short","long"],HOUR_FORMATS=["auto","12","24"],NUMERIC_DATE_SOURCE=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,dateSourceConverter={fromAttribute(value){const source=value??"",normalized=source.trim();if(NUMERIC_DATE_SOURCE.test(normalized)){const epoch=Number(normalized);if(Number.isFinite(epoch))return epoch}return source}},MAX_FRACTION_DIGITS=100,MAX_SIGNIFICANT_DIGITS=21;function closedValue(value,values,fallback){return typeof value=="string"&&values.includes(value)?value:fallback}function optionalClosedValue(value,values){return typeof value=="string"&&values.includes(value)?value:void 0}function optionalInteger(value,fallback,minimum,maximum){return value===void 0?void 0:finiteInteger(value,fallback,minimum,maximum)}function orderedDigits(minimum,maximum,minimumFallback,maximumFallback,lowerBound,upperBound){let safeMinimum=optionalInteger(minimum,minimumFallback,lowerBound,upperBound),safeMaximum=optionalInteger(maximum,maximumFallback,lowerBound,upperBound);return safeMinimum!==void 0&&safeMaximum!==void 0&&safeMinimum>safeMaximum&&([safeMinimum,safeMaximum]=[safeMaximum,safeMinimum]),[safeMinimum,safeMaximum]}function numberFormatOptions(input){const type=closedValue(input.type,NUMBER_TYPES,"decimal"),notation=closedValue(input.notation,NUMBER_NOTATIONS,"standard"),currencyDisplay=closedValue(input.currencyDisplay,CURRENCY_DISPLAYS,"symbol"),options={style:type,notation,useGrouping:!(input.withoutGrouping||input.noGrouping)};type==="currency"&&(options.currency=input.currency.trim()||"USD",options.currencyDisplay=currencyDisplay);const minimumIntegerDigits=optionalInteger(input.minimumIntegerDigits,1,1,21),[minimumFractionDigits,maximumFractionDigits]=orderedDigits(input.minimumFractionDigits,input.maximumFractionDigits,0,MAX_FRACTION_DIGITS,0,MAX_FRACTION_DIGITS),[minimumSignificantDigits,maximumSignificantDigits]=orderedDigits(input.minimumSignificantDigits,input.maximumSignificantDigits,1,MAX_SIGNIFICANT_DIGITS,1,MAX_SIGNIFICANT_DIGITS);return minimumIntegerDigits!==void 0&&(options.minimumIntegerDigits=minimumIntegerDigits),minimumFractionDigits!==void 0&&(options.minimumFractionDigits=minimumFractionDigits),maximumFractionDigits!==void 0&&(options.maximumFractionDigits=maximumFractionDigits),minimumSignificantDigits!==void 0&&(options.minimumSignificantDigits=minimumSignificantDigits),maximumSignificantDigits!==void 0&&(options.maximumSignificantDigits=maximumSignificantDigits),options}function dateTimeFormatOptions(input){const dateStyle=optionalClosedValue(input.dateStyle,DATE_STYLES),timeStyle=optionalClosedValue(input.timeStyle,DATE_STYLES),options=dateStyle||timeStyle?{dateStyle,timeStyle}:{weekday:optionalClosedValue(input.weekday,DATE_TEXT_STYLES),era:optionalClosedValue(input.era,DATE_TEXT_STYLES),year:optionalClosedValue(input.year,DATE_NUMERIC_STYLES),month:optionalClosedValue(input.month,MONTH_STYLES),day:optionalClosedValue(input.day,DATE_NUMERIC_STYLES),hour:optionalClosedValue(input.hour,DATE_NUMERIC_STYLES),minute:optionalClosedValue(input.minute,DATE_NUMERIC_STYLES),second:optionalClosedValue(input.second,DATE_NUMERIC_STYLES),timeZoneName:optionalClosedValue(input.timeZoneName,TIME_ZONE_NAME_STYLES)};input.timeZone?.trim()&&(options.timeZone=input.timeZone.trim());const hourFormat=closedValue(input.hourFormat,HOUR_FORMATS,"auto");return hourFormat!=="auto"&&(options.hour12=hourFormat==="12"),options}function byteFormat(value,unit,display,unitStep,decimals){const units=closedValue(unit,["byte","bit"],"byte")==="bit"?BIT_UNITS:BYTE_UNITS,step=finiteRange(unitStep,1e3,1),safeStep=step>1?step:1e3,index=value===0?0:Math.max(0,Math.min(units.length-1,Math.floor(Math.log(Math.abs(value))/Math.log(safeStep))));return{amount:value/safeStep**index,options:{style:"unit",unit:units[index],unitDisplay:closedValue(display,DISPLAY_STYLES,"short"),maximumFractionDigits:finiteInteger(decimals,1,0,10)}}}function relativeTimeFormatOptions(format,numeric){return{style:closedValue(format,DISPLAY_STYLES,"long"),numeric:closedValue(numeric,["always","auto"],"auto")}}export{byteFormat,
|
|
1
|
+
import{finiteInteger,finiteRange}from"../../../internal/numbers.js";const NUMBER_TYPES=["currency","decimal","percent"],NUMBER_NOTATIONS=["standard","compact","scientific","engineering"],CURRENCY_DISPLAYS=["symbol","narrowSymbol","code","name"],DISPLAY_STYLES=["long","short","narrow"],BYTE_UNITS=["byte","kilobyte","megabyte","gigabyte","terabyte","petabyte"],BIT_UNITS=["bit","kilobit","megabit","gigabit","terabit","petabit"],DATE_STYLES=["full","long","medium","short"],DATE_TEXT_STYLES=["narrow","short","long"],DATE_NUMERIC_STYLES=["numeric","2-digit"],MONTH_STYLES=["numeric","2-digit","narrow","short","long"],TIME_ZONE_NAME_STYLES=["short","long"],HOUR_FORMATS=["auto","12","24"],NUMERIC_DATE_SOURCE=/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,dateSourceConverter={fromAttribute(value){const source=value??"",normalized=source.trim();if(NUMERIC_DATE_SOURCE.test(normalized)){const epoch=Number(normalized);if(Number.isFinite(epoch))return epoch}return source}},MAX_FRACTION_DIGITS=100,MAX_SIGNIFICANT_DIGITS=21;function closedValue(value,values,fallback){return typeof value=="string"&&values.includes(value)?value:fallback}function optionalClosedValue(value,values){return typeof value=="string"&&values.includes(value)?value:void 0}function optionalInteger(value,fallback,minimum,maximum){return value===void 0?void 0:finiteInteger(value,fallback,minimum,maximum)}function orderedDigits(minimum,maximum,minimumFallback,maximumFallback,lowerBound,upperBound){let safeMinimum=optionalInteger(minimum,minimumFallback,lowerBound,upperBound),safeMaximum=optionalInteger(maximum,maximumFallback,lowerBound,upperBound);return safeMinimum!==void 0&&safeMaximum!==void 0&&safeMinimum>safeMaximum&&([safeMinimum,safeMaximum]=[safeMaximum,safeMinimum]),[safeMinimum,safeMaximum]}function numberFormatOptions(input){const type=closedValue(input.type,NUMBER_TYPES,"decimal"),notation=closedValue(input.notation,NUMBER_NOTATIONS,"standard"),currencyDisplay=closedValue(input.currencyDisplay,CURRENCY_DISPLAYS,"symbol"),options={style:type,notation,useGrouping:!(input.withoutGrouping||input.noGrouping)};type==="currency"&&(options.currency=input.currency.trim()||"USD",options.currencyDisplay=currencyDisplay);const minimumIntegerDigits=optionalInteger(input.minimumIntegerDigits,1,1,21),[minimumFractionDigits,maximumFractionDigits]=orderedDigits(input.minimumFractionDigits,input.maximumFractionDigits,0,MAX_FRACTION_DIGITS,0,MAX_FRACTION_DIGITS),[minimumSignificantDigits,maximumSignificantDigits]=orderedDigits(input.minimumSignificantDigits,input.maximumSignificantDigits,1,MAX_SIGNIFICANT_DIGITS,1,MAX_SIGNIFICANT_DIGITS);return minimumIntegerDigits!==void 0&&(options.minimumIntegerDigits=minimumIntegerDigits),minimumFractionDigits!==void 0&&(options.minimumFractionDigits=minimumFractionDigits),maximumFractionDigits!==void 0&&(options.maximumFractionDigits=maximumFractionDigits),minimumSignificantDigits!==void 0&&(options.minimumSignificantDigits=minimumSignificantDigits),maximumSignificantDigits!==void 0&&(options.maximumSignificantDigits=maximumSignificantDigits),options}function dateTimeFormatOptions(input){const dateStyle=optionalClosedValue(input.dateStyle,DATE_STYLES),timeStyle=optionalClosedValue(input.timeStyle,DATE_STYLES),options=dateStyle||timeStyle?{dateStyle,timeStyle}:{weekday:optionalClosedValue(input.weekday,DATE_TEXT_STYLES),era:optionalClosedValue(input.era,DATE_TEXT_STYLES),year:optionalClosedValue(input.year,DATE_NUMERIC_STYLES),month:optionalClosedValue(input.month,MONTH_STYLES),day:optionalClosedValue(input.day,DATE_NUMERIC_STYLES),hour:optionalClosedValue(input.hour,DATE_NUMERIC_STYLES),minute:optionalClosedValue(input.minute,DATE_NUMERIC_STYLES),second:optionalClosedValue(input.second,DATE_NUMERIC_STYLES),timeZoneName:optionalClosedValue(input.timeZoneName,TIME_ZONE_NAME_STYLES)};input.timeZone?.trim()&&(options.timeZone=input.timeZone.trim());const hourFormat=closedValue(input.hourFormat,HOUR_FORMATS,"auto");return hourFormat!=="auto"&&(options.hour12=hourFormat==="12"),options}function byteFormat(value,unit,display,unitStep,decimals){const units=closedValue(unit,["byte","bit"],"byte")==="bit"?BIT_UNITS:BYTE_UNITS,step=finiteRange(unitStep,1e3,1),safeStep=step>1?step:1e3,index=value===0?0:Math.max(0,Math.min(units.length-1,Math.floor(Math.log(Math.abs(value))/Math.log(safeStep))));return{amount:value/safeStep**index,options:{style:"unit",unit:units[index],unitDisplay:closedValue(display,DISPLAY_STYLES,"short"),maximumFractionDigits:finiteInteger(decimals,1,0,10)}}}function relativeTimeFormatOptions(format,numeric){return{style:closedValue(format,DISPLAY_STYLES,"long"),numeric:closedValue(numeric,["always","auto"],"auto")}}export{byteFormat,dateSourceConverter,dateTimeFormatOptions,numberFormatOptions,relativeTimeFormatOptions};
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { type OwnerFetchTarget } from '../../../internal/resource-loader.js';
|
|
2
2
|
import { type ResourceCacheLease } from '../../../internal/safe-resource-cache.js';
|
|
3
3
|
export type IconResourceErrorReason = 'load' | 'too-large' | 'sanitizer';
|
|
4
|
-
/** Icons are small documents; this cap is applied before parsing or sanitizing the response. */
|
|
5
|
-
export declare const MAX_ICON_BYTES: number;
|
|
6
4
|
export declare class IconResourceError extends Error {
|
|
7
5
|
readonly reason: IconResourceErrorReason;
|
|
8
6
|
readonly cause?: unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isAbortError,isResourceLimitError,readResponseText}from"../../../internal/resource-loader.js";import{BoundedResourceCache}from"../../../internal/safe-resource-cache.js";import{loadIconSanitizer}from"./dompurify-loader.js";const MAX_ICON_BYTES=1024*1024,ICON_CACHE_ENTRIES=128,SANITIZE_PROFILE="svg-filters-v1",SANITIZE_CONFIG={USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["use"],ADD_ATTR:["href"],RETURN_DOM_FRAGMENT:!0},resources=new BoundedResourceCache(ICON_CACHE_ENTRIES),ownerDocumentIds=new WeakMap;let nextOwnerId=1;const SVG_URL_PRESENTATION_ATTRIBUTES=new Set(["clip-path","cursor","fill","filter","marker","marker-end","marker-mid","marker-start","mask","stroke"]);function isLocalFragment(value){return/^#[^\s"'()<>]+$/.test(value.trim())}function hasUnsafeCssResource(value){if(value.includes("\\"))return!0;const urls=[...value.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/gi)];return urls.length===0?!1:value.replace(/url\(\s*(["']?)(.*?)\1\s*\)/gi,"").trim()!==""||urls.some(match=>!isLocalFragment(match[2]??""))}function stripExternalResourceSinks(svg){svg.querySelectorAll("style, foreignObject").forEach(node=>node.remove());for(const element of[svg,...svg.querySelectorAll("*")])for(const attribute of[...element.attributes]){const name=attribute.localName.toLowerCase(),value=attribute.value;if(name==="style"||name==="src"||name==="poster"){element.removeAttributeNode(attribute);continue}if(name==="href"){(element.localName.toLowerCase()!=="use"||!isLocalFragment(value))&&element.removeAttributeNode(attribute);continue}SVG_URL_PRESENTATION_ATTRIBUTES.has(name)&&hasUnsafeCssResource(value)&&element.removeAttributeNode(attribute)}}class IconResourceError extends Error{constructor(reason,cause){super(`Icon resource failed: ${reason}`),this.reason=reason,this.cause=cause,this.name="IconResourceError"}}function resourceKey(target){const ownerDocument=target.view.document;let ownerId=ownerDocumentIds.get(ownerDocument);return ownerId===void 0&&(ownerId=nextOwnerId++,ownerDocumentIds.set(ownerDocument,ownerId)),JSON.stringify([ownerId,target.url,MAX_ICON_BYTES,SANITIZE_PROFILE])}function acquireSanitizedIconResource(target){return resources.acquire(resourceKey(target),async signal=>{let response;try{response=await target.view.fetch(target.url,signal?{signal}:void 0)}catch(error){throw isAbortError(error)?error:new IconResourceError("load",error)}if(!response.ok)throw new IconResourceError("load",new Error(`${response.status} ${response.statusText}`));let raw;try{raw=await readResponseText(response,MAX_ICON_BYTES)}catch(error){throw isAbortError(error)?error:new IconResourceError(isResourceLimitError(error)?"too-large":"load",error)}if(raw.trim()==="")return null;const sanitizer=await loadIconSanitizer();if(!sanitizer)throw new IconResourceError("sanitizer");const node=sanitizer.sanitize(raw,SANITIZE_CONFIG).firstElementChild;if(!(node instanceof SVGSVGElement))throw new IconResourceError("load",new Error("response is not an SVG document"));return stripExternalResourceSinks(node),node})}function __clearIconResourceCacheForTesting(){resources.clear()}export{IconResourceError,
|
|
1
|
+
import{isAbortError,isResourceLimitError,readResponseText}from"../../../internal/resource-loader.js";import{BoundedResourceCache}from"../../../internal/safe-resource-cache.js";import{loadIconSanitizer}from"./dompurify-loader.js";const MAX_ICON_BYTES=1024*1024,ICON_CACHE_ENTRIES=128,SANITIZE_PROFILE="svg-filters-v1",SANITIZE_CONFIG={USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["use"],ADD_ATTR:["href"],RETURN_DOM_FRAGMENT:!0},resources=new BoundedResourceCache(ICON_CACHE_ENTRIES),ownerDocumentIds=new WeakMap;let nextOwnerId=1;const SVG_URL_PRESENTATION_ATTRIBUTES=new Set(["clip-path","cursor","fill","filter","marker","marker-end","marker-mid","marker-start","mask","stroke"]);function isLocalFragment(value){return/^#[^\s"'()<>]+$/.test(value.trim())}function hasUnsafeCssResource(value){if(value.includes("\\"))return!0;const urls=[...value.matchAll(/url\(\s*(["']?)(.*?)\1\s*\)/gi)];return urls.length===0?!1:value.replace(/url\(\s*(["']?)(.*?)\1\s*\)/gi,"").trim()!==""||urls.some(match=>!isLocalFragment(match[2]??""))}function stripExternalResourceSinks(svg){svg.querySelectorAll("style, foreignObject").forEach(node=>node.remove());for(const element of[svg,...svg.querySelectorAll("*")])for(const attribute of[...element.attributes]){const name=attribute.localName.toLowerCase(),value=attribute.value;if(name==="style"||name==="src"||name==="poster"){element.removeAttributeNode(attribute);continue}if(name==="href"){(element.localName.toLowerCase()!=="use"||!isLocalFragment(value))&&element.removeAttributeNode(attribute);continue}SVG_URL_PRESENTATION_ATTRIBUTES.has(name)&&hasUnsafeCssResource(value)&&element.removeAttributeNode(attribute)}}class IconResourceError extends Error{constructor(reason,cause){super(`Icon resource failed: ${reason}`),this.reason=reason,this.cause=cause,this.name="IconResourceError"}}function resourceKey(target){const ownerDocument=target.view.document;let ownerId=ownerDocumentIds.get(ownerDocument);return ownerId===void 0&&(ownerId=nextOwnerId++,ownerDocumentIds.set(ownerDocument,ownerId)),JSON.stringify([ownerId,target.url,MAX_ICON_BYTES,SANITIZE_PROFILE])}function acquireSanitizedIconResource(target){return resources.acquire(resourceKey(target),async signal=>{let response;try{response=await target.view.fetch(target.url,signal?{signal}:void 0)}catch(error){throw isAbortError(error)?error:new IconResourceError("load",error)}if(!response.ok)throw new IconResourceError("load",new Error(`${response.status} ${response.statusText}`));let raw;try{raw=await readResponseText(response,MAX_ICON_BYTES)}catch(error){throw isAbortError(error)?error:new IconResourceError(isResourceLimitError(error)?"too-large":"load",error)}if(raw.trim()==="")return null;const sanitizer=await loadIconSanitizer();if(!sanitizer)throw new IconResourceError("sanitizer");const node=sanitizer.sanitize(raw,SANITIZE_CONFIG).firstElementChild;if(!(node instanceof SVGSVGElement))throw new IconResourceError("load",new Error("response is not an SVG document"));return stripExternalResourceSinks(node),node})}function __clearIconResourceCacheForTesting(){resources.clear()}export{IconResourceError,__clearIconResourceCacheForTesting,acquireSanitizedIconResource};
|
|
@@ -16,7 +16,7 @@ export interface ZipArchiveGuardOptions {
|
|
|
16
16
|
createInspector?: (entry: ZipEntryInfo) => ZipEntryInspector | undefined;
|
|
17
17
|
}
|
|
18
18
|
/** Immutable central-directory entry metadata safe to expose without an archive peer. */
|
|
19
|
-
|
|
19
|
+
interface ZipArchiveEntryMetadata extends ZipEntryInfo {
|
|
20
20
|
readonly dir: boolean;
|
|
21
21
|
}
|
|
22
22
|
/** Immutable, bounded archive listing produced by the owned ZIP parser. */
|
|
@@ -47,3 +47,4 @@ export declare function assertZipArchiveMetadataWithinLimits(source: ArrayBuffer
|
|
|
47
47
|
* chunk-by-chunk, with an abort/generation boundary immediately after every stream await.
|
|
48
48
|
*/
|
|
49
49
|
export declare function assertZipArchiveWithinLimits(source: ArrayBuffer, options: ZipArchiveGuardOptions): Promise<void>;
|
|
50
|
+
export {};
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
export declare const DEFAULT_MAX_DOCX_ENTRIES = 10000;
|
|
2
|
-
export declare const DEFAULT_MAX_DOCX_UNCOMPRESSED_BYTES: number;
|
|
3
|
-
export declare const DEFAULT_MAX_DOCX_XML_NODES = 250000;
|
|
4
1
|
export interface DocxResourceGuardOptions {
|
|
5
2
|
signal?: AbortSignal;
|
|
6
3
|
maxXmlNodes?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assertZipArchiveWithinLimits,createXmlComplexityInspectorFactory}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_DOCX_ENTRIES=1e4,DEFAULT_MAX_DOCX_UNCOMPRESSED_BYTES=100*1024*1024,DEFAULT_MAX_DOCX_XML_NODES=25e4;function assertDocxArchiveWithinLimits(source,maxEntries=DEFAULT_MAX_DOCX_ENTRIES,maxUncompressedBytes=DEFAULT_MAX_DOCX_UNCOMPRESSED_BYTES,options={}){return assertZipArchiveWithinLimits(source,{description:"DOCX",maxEntries,maxUncompressedBytes,signal:options.signal,createInspector:createXmlComplexityInspectorFactory({includeEntry:name=>/\.(?:xml|rels)$/i.test(name),maxNodes:options.maxXmlNodes??DEFAULT_MAX_DOCX_XML_NODES})})}export{
|
|
1
|
+
import{assertZipArchiveWithinLimits,createXmlComplexityInspectorFactory}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_DOCX_ENTRIES=1e4,DEFAULT_MAX_DOCX_UNCOMPRESSED_BYTES=100*1024*1024,DEFAULT_MAX_DOCX_XML_NODES=25e4;function assertDocxArchiveWithinLimits(source,maxEntries=DEFAULT_MAX_DOCX_ENTRIES,maxUncompressedBytes=DEFAULT_MAX_DOCX_UNCOMPRESSED_BYTES,options={}){return assertZipArchiveWithinLimits(source,{description:"DOCX",maxEntries,maxUncompressedBytes,signal:options.signal,createInspector:createXmlComplexityInspectorFactory({includeEntry:name=>/\.(?:xml|rels)$/i.test(name),maxNodes:options.maxXmlNodes??DEFAULT_MAX_DOCX_XML_NODES})})}export{assertDocxArchiveWithinLimits};
|
|
@@ -22,7 +22,7 @@ export interface EpubLocation {
|
|
|
22
22
|
href?: string;
|
|
23
23
|
};
|
|
24
24
|
}
|
|
25
|
-
|
|
25
|
+
interface EpubAnnotations {
|
|
26
26
|
highlight(cfi: string, data: Record<string, unknown>, callback?: (() => void) | undefined, className?: string, styles?: Record<string, unknown>): unknown;
|
|
27
27
|
remove(cfi: string, type: string): void;
|
|
28
28
|
}
|
|
@@ -49,3 +49,4 @@ export interface EpubBook {
|
|
|
49
49
|
export type EpubFactory = (data: ArrayBuffer) => EpubBook;
|
|
50
50
|
export declare function loadEpubJs(importEpub?: () => Promise<unknown>): Promise<EpubFactory | null>;
|
|
51
51
|
export declare function getEpubJs(): Promise<EpubFactory | null>;
|
|
52
|
+
export {};
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
export declare const DEFAULT_MAX_EPUB_ENTRIES = 10000;
|
|
2
|
-
export declare const DEFAULT_MAX_EPUB_UNCOMPRESSED_BYTES: number;
|
|
3
|
-
export declare const DEFAULT_MAX_EPUB_XML_NODES = 250000;
|
|
4
1
|
export interface EpubResourceGuardOptions {
|
|
5
2
|
signal?: AbortSignal;
|
|
6
3
|
maxXmlNodes?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{assertZipArchiveWithinLimits,createXmlComplexityInspectorFactory}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_EPUB_ENTRIES=1e4,DEFAULT_MAX_EPUB_UNCOMPRESSED_BYTES=100*1024*1024,DEFAULT_MAX_EPUB_XML_NODES=25e4;function assertEpubArchiveWithinLimits(source,maxEntries=DEFAULT_MAX_EPUB_ENTRIES,maxUncompressedBytes=DEFAULT_MAX_EPUB_UNCOMPRESSED_BYTES,options={}){return assertZipArchiveWithinLimits(source,{description:"EPUB",maxEntries,maxUncompressedBytes,signal:options.signal,createInspector:createXmlComplexityInspectorFactory({includeEntry:name=>/\.(?:xhtml?|html?|xml|opf|ncx|rels)$/i.test(name),maxNodes:options.maxXmlNodes??DEFAULT_MAX_EPUB_XML_NODES})})}export{
|
|
1
|
+
import{assertZipArchiveWithinLimits,createXmlComplexityInspectorFactory}from"../archive-viewer/zip-resource-guard.js";const DEFAULT_MAX_EPUB_ENTRIES=1e4,DEFAULT_MAX_EPUB_UNCOMPRESSED_BYTES=100*1024*1024,DEFAULT_MAX_EPUB_XML_NODES=25e4;function assertEpubArchiveWithinLimits(source,maxEntries=DEFAULT_MAX_EPUB_ENTRIES,maxUncompressedBytes=DEFAULT_MAX_EPUB_UNCOMPRESSED_BYTES,options={}){return assertZipArchiveWithinLimits(source,{description:"EPUB",maxEntries,maxUncompressedBytes,signal:options.signal,createInspector:createXmlComplexityInspectorFactory({includeEntry:name=>/\.(?:xhtml?|html?|xml|opf|ncx|rels)$/i.test(name),maxNodes:options.maxXmlNodes??DEFAULT_MAX_EPUB_XML_NODES})})}export{assertEpubArchiveWithinLimits};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
interface PdfRenderTaskApi {
|
|
2
2
|
promise: Promise<void>;
|
|
3
3
|
cancel(): void;
|
|
4
4
|
}
|
|
@@ -29,7 +29,7 @@ export interface PdfDocumentApi {
|
|
|
29
29
|
getPageIndex(reference: unknown): Promise<number>;
|
|
30
30
|
destroy?(): Promise<void> | void;
|
|
31
31
|
}
|
|
32
|
-
|
|
32
|
+
interface PdfTextLayerApi {
|
|
33
33
|
render(): Promise<void>;
|
|
34
34
|
cancel(): void;
|
|
35
35
|
}
|