@aceshooting/lyra-ui 9.1.0 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +246 -0
- package/README.md +7 -0
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.styles.js +2 -2
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
- package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +2 -2
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/bar-chart.class.js +1 -1
- package/dist/components/charts/chart/bubble-chart.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/line-chart.class.js +1 -1
- package/dist/components/charts/chart/pie-chart.class.js +1 -1
- package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
- package/dist/components/charts/chart/radar-chart.class.js +1 -1
- package/dist/components/charts/chart/scatter-chart.class.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
- package/dist/components/conversation/chat-message/chat-message.styles.js +6 -0
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
- package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.styles.js +9 -0
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.js +1 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +3 -1
- package/dist/components/layout/card/card.styles.js +2 -2
- package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.styles.js +29 -9
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +2 -2
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +2 -0
- package/dist/components/overlays/callout/callout.styles.js +2 -2
- package/dist/components/overlays/kbd/kbd.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/popup/popup.class.js +2 -2
- package/dist/components/overlays/spinner/spinner.styles.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +11 -0
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +7 -0
- package/dist/internal/dev-mode-attribute-warning.js +1 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/llms/components/lr-attachment-trigger.md +2 -2
- package/llms/components/lr-heatmap.md +1 -1
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/llms/shared.md +13 -0
- package/llms-full.txt +16 -3
- package/package.json +3 -3
- package/vscode-html-data.json +1 -1
- package/web-types.json +2 -2
|
@@ -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.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;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()}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,this.anchorPositioned=!1;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(),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,popup?.setAttribute("data-hidden","");return}if(anchor!==this.positionedAnchor&&(this.anchorPositioned=!1,popup.setAttribute("data-hidden","")),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,this.open&&this.resolveAnchor()===anchor&&popup.removeAttribute("data-hidden");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)}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(),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{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.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;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()}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,this.anchorPositioned=!1;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(),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)}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(),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>
|
|
@@ -14,4 +14,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
14
14
|
</span>
|
|
15
15
|
${this.rendersArrow?html`<span part="arrow base__arrow arrow-${this.resolvedSide}"></span>`:nothing}
|
|
16
16
|
</div>
|
|
17
|
-
`}}__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"open",null),__decorate([property()],LyraTooltip.prototype,"trigger",void 0),__decorate([property({type:Boolean})],LyraTooltip.prototype,"manual",void 0),__decorate([property({type:Number,attribute:"show-delay"})],LyraTooltip.prototype,"showDelay",void 0),__decorate([property({type:Number,attribute:"hide-delay"})],LyraTooltip.prototype,"hideDelay",void 0),__decorate([property({reflect:!0})],LyraTooltip.prototype,"placement",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"distance",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"skidding",void 0),__decorate([property({reflect:!0,converter:omittedEmptyStringConverter})],LyraTooltip.prototype,"for",null),__decorate([property({attribute:!1})],LyraTooltip.prototype,"anchor",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"hoist",void 0),__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter,reflect:!0})],LyraTooltip.prototype,"arrow",void 0),__decorate([property({type:Boolean,attribute:"without-arrow",reflect:!0})],LyraTooltip.prototype,"withoutArrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraTooltip.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraTooltip.prototype,"arrowPadding",void 0),__decorate([property()],LyraTooltip.prototype,"content",void 0),__decorate([property({attribute:"aria-label"})],LyraTooltip.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTooltip.prototype,"interactiveContent",void 0),__decorate([state()],LyraTooltip.prototype,"resolvedSide",void 0);export{LyraTooltip};
|
|
17
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"open",null),__decorate([property()],LyraTooltip.prototype,"trigger",void 0),__decorate([property({type:Boolean})],LyraTooltip.prototype,"manual",void 0),__decorate([property({type:Number,attribute:"show-delay"})],LyraTooltip.prototype,"showDelay",void 0),__decorate([property({type:Number,attribute:"hide-delay"})],LyraTooltip.prototype,"hideDelay",void 0),__decorate([property({reflect:!0})],LyraTooltip.prototype,"placement",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"distance",void 0),__decorate([property({type:Number})],LyraTooltip.prototype,"skidding",void 0),__decorate([property({reflect:!0,converter:omittedEmptyStringConverter})],LyraTooltip.prototype,"for",null),__decorate([property({attribute:!1})],LyraTooltip.prototype,"anchor",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraTooltip.prototype,"hoist",void 0),__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter,reflect:!0})],LyraTooltip.prototype,"arrow",void 0),__decorate([property({type:Boolean,attribute:"without-arrow",reflect:!0})],LyraTooltip.prototype,"withoutArrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraTooltip.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraTooltip.prototype,"arrowPadding",void 0),__decorate([property()],LyraTooltip.prototype,"content",void 0),__decorate([property({attribute:"aria-label"})],LyraTooltip.prototype,"accessibleLabel",void 0),__decorate([state()],LyraTooltip.prototype,"interactiveContent",void 0),__decorate([state()],LyraTooltip.prototype,"resolvedSide",void 0),__decorate([state()],LyraTooltip.prototype,"anchorPositioned",void 0);export{LyraTooltip};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{applyOverlayArrow}from"../overlay/overlay-arrow.js";import{observeOverlayAnchorIdentity}from"../overlay/overlay-shared.js";import{styles}from"./popup.styles.js";const PLACEMENTS=new Set(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),AUTO_SIZE_AXES=new Set(["horizontal","vertical","both"]),SYNC_AXES=new Set(["width","height","both"]);class LyraPopup extends LyraElement{constructor(){super(...arguments),this.active=!1,this.for="",this.anchor=null,this.placement="top",this.strategy="absolute",this.distance=0,this.skidding=0,this.flip=!1,this.flipFallbackPlacements="",this.flipFallbackStrategy="best-fit",this.boundary="viewport",this.flipBoundary=null,this.flipPadding=0,this.shift=!1,this.shiftBoundary=null,this.shiftPadding=0,this.padding=0,this.autoSize=null,this.autoSizeBoundary=null,this.autoSizePadding=0,this.sync=null,this.hoverBridge=!1,this.arrow=!1,this.arrowPlacement="anchor",this.arrowPadding=10,this.virtualAnchor=null,this.anchorPositioned=!1,this.resolvedPlacement="top",this.onAnchorSlotChange=()=>{if(!this.active)return;const nextIdentity=this.resolveAnchor()?.identity,currentIdentity=this.placingAnchorIdentity??this.positionedAnchorIdentity;nextIdentity!==currentIdentity&&this.reposition()},this.onForwardedAnchorSlotChange=event=>{event.target?.localName==="slot"&&this.onAnchorSlotChange()}}static{this.styles=[LyraElement.styles,styles]}get popup(){return this.renderRoot?.querySelector('[part~="popup"]')}set popup(_next){}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onForwardedAnchorSlotChange),this.syncAnchorIdentityObservation(),this.hasUpdated&&this.active&&this.reposition()}disconnectedCallback(){this.removeEventListener("slotchange",this.onForwardedAnchorSlotChange),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.teardown(),this.positionedAnchorIdentity=void 0,this.setPositioned(!1),super.disconnectedCallback()}updated(changed){super.updated(changed),this.reposition()}reposition(){this.syncAnchorIdentityObservation();const anchor=this.isConnected&&this.active?this.resolveAnchor():null,previousIdentity=this.placingAnchorIdentity??this.positionedAnchorIdentity;if(this.teardown(),!this.isConnected||!this.active||!this.popup||!anchor){this.positionedAnchorIdentity=void 0,this.setPositioned(!1);return}anchor.identity!==previousIdentity&&(this.positionedAnchorIdentity=void 0,this.setPositioned(!1)),this.placingAnchorIdentity=anchor.identity;const arrowPadding=Math.max(0,finiteNumber(this.arrowPadding,0));this.stopPlacing=place(anchor.target,this.popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.strategy==="absolute"?"absolute":"fixed",offset:finiteNumber(this.distance,0),skidding:finiteNumber(this.skidding,0),boundary:this.boundary==="scroll"?void 0:[],flip:this.flip,flipFallbackPlacements:this.parsedFlipFallbackPlacements,flipFallbackStrategy:this.flipFallbackStrategy==="initial"||this.flipFallbackStrategy==="initial-placement"?"initial-placement":"best-fit",flipBoundary:this.flipBoundary??void 0,flipPadding:Math.max(0,finiteNumber(this.flipPadding,0)),shift:this.shift,shiftBoundary:this.shiftBoundary??void 0,shiftPadding:Math.max(0,finiteNumber(this.shiftPadding,0)),padding:Math.max(0,finiteNumber(this.padding,0)),autoSize:AUTO_SIZE_AXES.has(this.autoSize)?this.autoSize:void 0,autoSizeBoundary:this.autoSizeBoundary??void 0,autoSizePadding:Math.max(0,finiteNumber(this.autoSizePadding,0)),sync:SYNC_AXES.has(this.sync)?this.sync:void 0,arrow:this.arrow?this.arrowElement:void 0,arrowPadding,hoverBridge:this.hoverBridge?this.hoverBridgeElement:void 0,onPlaced:({placement,arrow})=>{const currentAnchor=this.resolveAnchor();if(!this.isConnected||!this.active||currentAnchor?.identity!==anchor.identity){this.setPositioned(!1);return}this.placingAnchorIdentity=void 0,this.positionedAnchorIdentity=anchor.identity,this.setPositioned(!0),this.popup.style.setProperty("--auto-size-available-width",this.popup.style.getPropertyValue("--lr-positioner-available-inline-size")),this.popup.style.setProperty("--auto-size-available-height",this.popup.style.getPropertyValue("--lr-positioner-available-block-size"));const side=applyOverlayArrow(this.arrowElement??null,{placement,coords:arrow,enabled:this.arrow,arrowPlacement:this.arrowPlacement,arrowPadding,rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-popup-arrow-size"});this.applyArrowSidePart(side),placement!==this.resolvedPlacement&&(this.resolvedPlacement=placement,this.applySidePart(placement)),this.emit("lr-reposition",{placement})}})}get parsedFlipFallbackPlacements(){const raw=(this.flipFallbackPlacements??"").trim();if(!raw)return;const parsed=raw.split(/[\s,]+/).filter(token=>PLACEMENTS.has(token));return parsed.length?parsed:void 0}teardown(){this.stopPlacing?.(),this.stopPlacing=void 0,this.placingAnchorIdentity=void 0}resolveAnchor(){if(this.virtualAnchor){const candidate=this.virtualAnchor;if(typeof candidate.getBoundingClientRect=="function")return{target:candidate,identity:candidate};const rect=this.virtualAnchor,width=rect.width??0,height=rect.height??0;return[rect.x,rect.y,width,height].every(Number.isFinite)?{target:virtualAnchorFromRect({x:rect.x,y:rect.y,width:Math.max(0,width),height:Math.max(0,height)}),identity:rect}:null}if(this.anchor){if(typeof this.anchor=="string"){const target2=this.getRootNode().getElementById?.(this.anchor)??null;if(target2)return{target:target2,identity:target2}}else if(typeof this.anchor.getBoundingClientRect=="function"&&(!this.isElementAnchor(this.anchor)||this.anchor.isConnected))return{target:this.anchor,identity:this.anchor}}if(this.for){const target2=this.getRootNode().getElementById?.(this.for)??null;if(target2)return{target:target2,identity:target2}}const target=this.anchorSlotWrapper?.querySelector("slot")?.assignedElements({flatten:!0})[0]??null;return target?.isConnected?{target,identity:target}:null}isElementAnchor(anchor){const candidate=anchor,ElementCtor=candidate.ownerDocument?.defaultView?.Element;return ElementCtor?candidate instanceof ElementCtor:candidate.nodeType===1}syncAnchorIdentityObservation(){if(this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,!this.isConnected||!this.active||this.virtualAnchor)return;const directAnchor=this.anchor&&typeof this.anchor!="string"&&this.isElementAnchor(this.anchor)?this.anchor:void 0;if(!(typeof this.anchor=="string"||!!this.for||!!directAnchor))return;const onIdentityChange=()=>{const nextIdentity=this.resolveAnchor()?.identity,currentIdentity=this.placingAnchorIdentity??this.positionedAnchorIdentity;nextIdentity!==currentIdentity&&this.reposition()},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()}}setPositioned(positioned){this.anchorPositioned=positioned
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place,virtualAnchorFromRect}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteNumber}from"../../../internal/numbers.js";import{applyOverlayArrow}from"../overlay/overlay-arrow.js";import{observeOverlayAnchorIdentity}from"../overlay/overlay-shared.js";import{styles}from"./popup.styles.js";const PLACEMENTS=new Set(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),AUTO_SIZE_AXES=new Set(["horizontal","vertical","both"]),SYNC_AXES=new Set(["width","height","both"]);class LyraPopup extends LyraElement{constructor(){super(...arguments),this.active=!1,this.for="",this.anchor=null,this.placement="top",this.strategy="absolute",this.distance=0,this.skidding=0,this.flip=!1,this.flipFallbackPlacements="",this.flipFallbackStrategy="best-fit",this.boundary="viewport",this.flipBoundary=null,this.flipPadding=0,this.shift=!1,this.shiftBoundary=null,this.shiftPadding=0,this.padding=0,this.autoSize=null,this.autoSizeBoundary=null,this.autoSizePadding=0,this.sync=null,this.hoverBridge=!1,this.arrow=!1,this.arrowPlacement="anchor",this.arrowPadding=10,this.virtualAnchor=null,this.anchorPositioned=!1,this.resolvedPlacement="top",this.onAnchorSlotChange=()=>{if(!this.active)return;const nextIdentity=this.resolveAnchor()?.identity,currentIdentity=this.placingAnchorIdentity??this.positionedAnchorIdentity;nextIdentity!==currentIdentity&&this.reposition()},this.onForwardedAnchorSlotChange=event=>{event.target?.localName==="slot"&&this.onAnchorSlotChange()}}static{this.styles=[LyraElement.styles,styles]}get popup(){return this.renderRoot?.querySelector('[part~="popup"]')}set popup(_next){}connectedCallback(){super.connectedCallback(),this.addEventListener("slotchange",this.onForwardedAnchorSlotChange),this.syncAnchorIdentityObservation(),this.hasUpdated&&this.active&&this.reposition()}disconnectedCallback(){this.removeEventListener("slotchange",this.onForwardedAnchorSlotChange),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.teardown(),this.positionedAnchorIdentity=void 0,this.setPositioned(!1),super.disconnectedCallback()}updated(changed){super.updated(changed),this.reposition()}reposition(){this.syncAnchorIdentityObservation();const anchor=this.isConnected&&this.active?this.resolveAnchor():null,previousIdentity=this.placingAnchorIdentity??this.positionedAnchorIdentity;if(this.teardown(),!this.isConnected||!this.active||!this.popup||!anchor){this.positionedAnchorIdentity=void 0,this.setPositioned(!1);return}anchor.identity!==previousIdentity&&(this.positionedAnchorIdentity=void 0,this.setPositioned(!1)),this.placingAnchorIdentity=anchor.identity;const arrowPadding=Math.max(0,finiteNumber(this.arrowPadding,0));this.stopPlacing=place(anchor.target,this.popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.strategy==="absolute"?"absolute":"fixed",offset:finiteNumber(this.distance,0),skidding:finiteNumber(this.skidding,0),boundary:this.boundary==="scroll"?void 0:[],flip:this.flip,flipFallbackPlacements:this.parsedFlipFallbackPlacements,flipFallbackStrategy:this.flipFallbackStrategy==="initial"||this.flipFallbackStrategy==="initial-placement"?"initial-placement":"best-fit",flipBoundary:this.flipBoundary??void 0,flipPadding:Math.max(0,finiteNumber(this.flipPadding,0)),shift:this.shift,shiftBoundary:this.shiftBoundary??void 0,shiftPadding:Math.max(0,finiteNumber(this.shiftPadding,0)),padding:Math.max(0,finiteNumber(this.padding,0)),autoSize:AUTO_SIZE_AXES.has(this.autoSize)?this.autoSize:void 0,autoSizeBoundary:this.autoSizeBoundary??void 0,autoSizePadding:Math.max(0,finiteNumber(this.autoSizePadding,0)),sync:SYNC_AXES.has(this.sync)?this.sync:void 0,arrow:this.arrow?this.arrowElement:void 0,arrowPadding,hoverBridge:this.hoverBridge?this.hoverBridgeElement:void 0,onPlaced:({placement,arrow})=>{const currentAnchor=this.resolveAnchor();if(!this.isConnected||!this.active||currentAnchor?.identity!==anchor.identity){this.setPositioned(!1);return}this.placingAnchorIdentity=void 0,this.positionedAnchorIdentity=anchor.identity,this.setPositioned(!0),this.popup.style.setProperty("--auto-size-available-width",this.popup.style.getPropertyValue("--lr-positioner-available-inline-size")),this.popup.style.setProperty("--auto-size-available-height",this.popup.style.getPropertyValue("--lr-positioner-available-block-size"));const side=applyOverlayArrow(this.arrowElement??null,{placement,coords:arrow,enabled:this.arrow,arrowPlacement:this.arrowPlacement,arrowPadding,rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-popup-arrow-size"});this.applyArrowSidePart(side),placement!==this.resolvedPlacement&&(this.resolvedPlacement=placement,this.applySidePart(placement)),this.emit("lr-reposition",{placement})}})}get parsedFlipFallbackPlacements(){const raw=(this.flipFallbackPlacements??"").trim();if(!raw)return;const parsed=raw.split(/[\s,]+/).filter(token=>PLACEMENTS.has(token));return parsed.length?parsed:void 0}teardown(){this.stopPlacing?.(),this.stopPlacing=void 0,this.placingAnchorIdentity=void 0}resolveAnchor(){if(this.virtualAnchor){const candidate=this.virtualAnchor;if(typeof candidate.getBoundingClientRect=="function")return{target:candidate,identity:candidate};const rect=this.virtualAnchor,width=rect.width??0,height=rect.height??0;return[rect.x,rect.y,width,height].every(Number.isFinite)?{target:virtualAnchorFromRect({x:rect.x,y:rect.y,width:Math.max(0,width),height:Math.max(0,height)}),identity:rect}:null}if(this.anchor){if(typeof this.anchor=="string"){const target2=this.getRootNode().getElementById?.(this.anchor)??null;if(target2)return{target:target2,identity:target2}}else if(typeof this.anchor.getBoundingClientRect=="function"&&(!this.isElementAnchor(this.anchor)||this.anchor.isConnected))return{target:this.anchor,identity:this.anchor}}if(this.for){const target2=this.getRootNode().getElementById?.(this.for)??null;if(target2)return{target:target2,identity:target2}}const target=this.anchorSlotWrapper?.querySelector("slot")?.assignedElements({flatten:!0})[0]??null;return target?.isConnected?{target,identity:target}:null}isElementAnchor(anchor){const candidate=anchor,ElementCtor=candidate.ownerDocument?.defaultView?.Element;return ElementCtor?candidate instanceof ElementCtor:candidate.nodeType===1}syncAnchorIdentityObservation(){if(this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,!this.isConnected||!this.active||this.virtualAnchor)return;const directAnchor=this.anchor&&typeof this.anchor!="string"&&this.isElementAnchor(this.anchor)?this.anchor:void 0;if(!(typeof this.anchor=="string"||!!this.for||!!directAnchor))return;const onIdentityChange=()=>{const nextIdentity=this.resolveAnchor()?.identity,currentIdentity=this.placingAnchorIdentity??this.positionedAnchorIdentity;nextIdentity!==currentIdentity&&this.reposition()},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()}}setPositioned(positioned){this.anchorPositioned=positioned}applySidePart(placement){const side=placement.split("-")[0]??"bottom";this.popup?.setAttribute("part",`popup ${side}`)}applyArrowSidePart(side){this.arrowElement?.setAttribute("part",`arrow arrow-${side}`)}render(){const side=this.resolvedPlacement.split("-")[0],paints=this.active&&this.anchorPositioned,awaitsPosition=this.active&&!this.anchorPositioned;return html`
|
|
2
2
|
${this.hoverBridge?html`<span part="hover-bridge" ?data-active=${paints}></span>`:nothing}
|
|
3
3
|
<span part="anchor"><slot name="anchor" @slotchange=${this.onAnchorSlotChange}></slot></span>
|
|
4
4
|
<div part="popup ${side}" ?data-active=${paints} ?data-awaits-position=${awaitsPosition}>
|
|
5
5
|
<slot></slot>
|
|
6
6
|
${this.arrow?html`<span part="arrow arrow-${side}"></span>`:nothing}
|
|
7
7
|
</div>
|
|
8
|
-
`}}__decorate([property({type:Boolean,reflect:!0})],LyraPopup.prototype,"active",void 0),__decorate([property({reflect:!0})],LyraPopup.prototype,"for",void 0),__decorate([property()],LyraPopup.prototype,"anchor",void 0),__decorate([property({reflect:!0})],LyraPopup.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraPopup.prototype,"strategy",void 0),__decorate([property({type:Number})],LyraPopup.prototype,"distance",void 0),__decorate([property({type:Number})],LyraPopup.prototype,"skidding",void 0),__decorate([property({type:Boolean})],LyraPopup.prototype,"flip",void 0),__decorate([property({attribute:"flip-fallback-placements"})],LyraPopup.prototype,"flipFallbackPlacements",void 0),__decorate([property({attribute:"flip-fallback-strategy"})],LyraPopup.prototype,"flipFallbackStrategy",void 0),__decorate([property()],LyraPopup.prototype,"boundary",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"flipBoundary",void 0),__decorate([property({type:Number,attribute:"flip-padding"})],LyraPopup.prototype,"flipPadding",void 0),__decorate([property({type:Boolean})],LyraPopup.prototype,"shift",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"shiftBoundary",void 0),__decorate([property({type:Number,attribute:"shift-padding"})],LyraPopup.prototype,"shiftPadding",void 0),__decorate([property({type:Number})],LyraPopup.prototype,"padding",void 0),__decorate([property({attribute:"auto-size"})],LyraPopup.prototype,"autoSize",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"autoSizeBoundary",void 0),__decorate([property({type:Number,attribute:"auto-size-padding"})],LyraPopup.prototype,"autoSizePadding",void 0),__decorate([property()],LyraPopup.prototype,"sync",void 0),__decorate([property({type:Boolean,attribute:"hover-bridge"})],LyraPopup.prototype,"hoverBridge",void 0),__decorate([property({type:Boolean})],LyraPopup.prototype,"arrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraPopup.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraPopup.prototype,"arrowPadding",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"virtualAnchor",void 0),__decorate([query('[part~="arrow"]')],LyraPopup.prototype,"arrowElement",void 0),__decorate([query('[part~="hover-bridge"]')],LyraPopup.prototype,"hoverBridgeElement",void 0),__decorate([query('[part="anchor"]')],LyraPopup.prototype,"anchorSlotWrapper",void 0);export{LyraPopup};
|
|
8
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraPopup.prototype,"active",void 0),__decorate([property({reflect:!0})],LyraPopup.prototype,"for",void 0),__decorate([property()],LyraPopup.prototype,"anchor",void 0),__decorate([property({reflect:!0})],LyraPopup.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraPopup.prototype,"strategy",void 0),__decorate([property({type:Number})],LyraPopup.prototype,"distance",void 0),__decorate([property({type:Number})],LyraPopup.prototype,"skidding",void 0),__decorate([property({type:Boolean})],LyraPopup.prototype,"flip",void 0),__decorate([property({attribute:"flip-fallback-placements"})],LyraPopup.prototype,"flipFallbackPlacements",void 0),__decorate([property({attribute:"flip-fallback-strategy"})],LyraPopup.prototype,"flipFallbackStrategy",void 0),__decorate([property()],LyraPopup.prototype,"boundary",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"flipBoundary",void 0),__decorate([property({type:Number,attribute:"flip-padding"})],LyraPopup.prototype,"flipPadding",void 0),__decorate([property({type:Boolean})],LyraPopup.prototype,"shift",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"shiftBoundary",void 0),__decorate([property({type:Number,attribute:"shift-padding"})],LyraPopup.prototype,"shiftPadding",void 0),__decorate([property({type:Number})],LyraPopup.prototype,"padding",void 0),__decorate([property({attribute:"auto-size"})],LyraPopup.prototype,"autoSize",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"autoSizeBoundary",void 0),__decorate([property({type:Number,attribute:"auto-size-padding"})],LyraPopup.prototype,"autoSizePadding",void 0),__decorate([property()],LyraPopup.prototype,"sync",void 0),__decorate([property({type:Boolean,attribute:"hover-bridge"})],LyraPopup.prototype,"hoverBridge",void 0),__decorate([property({type:Boolean})],LyraPopup.prototype,"arrow",void 0),__decorate([property({attribute:"arrow-placement"})],LyraPopup.prototype,"arrowPlacement",void 0),__decorate([property({type:Number,attribute:"arrow-padding"})],LyraPopup.prototype,"arrowPadding",void 0),__decorate([property({attribute:!1})],LyraPopup.prototype,"virtualAnchor",void 0),__decorate([query('[part~="arrow"]')],LyraPopup.prototype,"arrowElement",void 0),__decorate([query('[part~="hover-bridge"]')],LyraPopup.prototype,"hoverBridgeElement",void 0),__decorate([query('[part="anchor"]')],LyraPopup.prototype,"anchorSlotWrapper",void 0),__decorate([state()],LyraPopup.prototype,"anchorPositioned",void 0);export{LyraPopup};
|
|
@@ -13,8 +13,8 @@ import{css}from"lit";const styles=css`
|
|
|
13
13
|
/* 'after' renders the slotted label in flow next to the spinner; 'none' keeps it sr-only
|
|
14
14
|
(still hit by the [hidden] attribute set in spinner.class.ts, but scoping the clip here too
|
|
15
15
|
keeps this rule self-consistent if that attribute is ever dropped). */
|
|
16
|
-
:host([label-placement='after']) [part='label'] { display: inline-flex; flex: 1 1 auto; align-items: center; min-inline-size: 0; max-inline-size: 100%; overflow: hidden; overflow-wrap:
|
|
17
|
-
:host([label-placement='after']) [part='label'] ::slotted(*) { min-inline-size: 0; max-inline-size: 100%; overflow-wrap:
|
|
16
|
+
:host([label-placement='after']) [part='label'] { display: inline-flex; flex: 1 1 auto; align-items: center; min-inline-size: 0; max-inline-size: 100%; overflow: hidden; overflow-wrap: break-word; margin-inline-start: var(--lr-space-2xs); color: var(--lr-color-text); font-size: var(--lr-font-size-sm); }
|
|
17
|
+
:host([label-placement='after']) [part='label'] ::slotted(*) { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: break-word; }
|
|
18
18
|
:host([label-placement='none']) [part='label'] { position: absolute; inline-size: var(--lr-size-1px); block-size: var(--lr-size-1px); overflow: hidden; clip-path: inset(50%); }
|
|
19
19
|
@keyframes lr-spin { to { transform: rotate(1turn); } }
|
|
20
20
|
@media (prefers-reduced-motion: reduce) { [part~='spinner-indicator'] { animation: none; } }
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./citation-badge.styles.js";import{LYRA_DEFAULT_citation,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_citationUnverified,LYRA_DEFAULT_citationVerified,LYRA_DEFAULT_citationWithCustomLabel,LYRA_DEFAULT_citationWithStatus,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_MESSAGE_KEY={default:null,high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence",verified:"citationVerified",unverified:"citationUnverified"},HIDE_DELAY_MS=200;function isRealPreviewNode(n){return n.nodeType===Node.ELEMENT_NODE?!n.hasAttribute("slot"):(n.textContent??"").trim().length>0}class LyraCitationBadge extends LyraElement{constructor(){super(...arguments),this._index=1,this.status="default",this.sourceId="",this.href="",this.label="",this.hasPreviewSlot=!1,this.popoverOpen=!1,this.popoverId=nextId("citation-badge-popover"),this.hovering=!1,this.focused=!1,this.onSlotChange=e=>{this.hasPreviewSlot=e.target.assignedNodes({flatten:!0}).some(isRealPreviewNode),this.hasPreviewSlot||this.hidePreviewNow()},this.onPointerEnter=()=>{this.hovering=!0,this.showPreview()},this.onPointerLeave=()=>{this.hovering=!1,this.scheduleHidePreview()},this.onFocusIn=()=>{this.focused=!0,this.showPreview()},this.onFocusOut=()=>{this.focused=!1,!this.hovering&&this.hidePreviewNow()},this.onKeyDown=e=>{if(e.key==="Escape"&&this.popoverOpen){e.stopPropagation(),this.hidePreviewNow();return}e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{this.emit("lr-citation-activate",{sourceId:this.sourceId,index:this.index})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,citation:LYRA_DEFAULT_citation,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,citationUnverified:LYRA_DEFAULT_citationUnverified,citationVerified:LYRA_DEFAULT_citationVerified,citationWithCustomLabel:LYRA_DEFAULT_citationWithCustomLabel,citationWithStatus:LYRA_DEFAULT_citationWithStatus,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get index(){return this._index}set index(value){const old=this._index;this._index=finiteInteger(value,1,1),this.requestUpdate("index",old)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasPreviewSlot=Array.from(this.childNodes).some(isRealPreviewNode))}updated(changed){super.updated(changed),changed.has("popoverOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.popoverOpen&&this.buttonEl&&this.popoverEl&&(this.cleanupPositioner=place(this.buttonEl,this.popoverEl,{placement:"top-start"})))}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen=!1,this.hovering=!1,this.focused=!1}get accessibleLabel(){const index=getNumberFormat(this.effectiveLocale).format(this.index);if(this.label)return this.localize("citationWithCustomLabel",void 0,{index,label:this.label});const key=STATUS_MESSAGE_KEY[this.status],statusText=key?this.localize(key):"",citationLabel=this.localize("citation",void 0,{index});return statusText?this.localize("citationWithStatus",void 0,{index,status:statusText}):citationLabel}showPreview(){this.hasPreviewSlot&&(clearTimeout(this.hideTimer),this.hideTimer=void 0,!this.popoverOpen&&(this.popoverOpen=!0))}scheduleHidePreview(){!this.popoverOpen||this.hovering||this.focused||(clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{this.hideTimer=void 0,this.popoverOpen=!1},HIDE_DELAY_MS))}hidePreviewNow(){clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen&&(this.popoverOpen=!1)}emitOpen(){this.emit("lr-citation-open",{sourceId:this.sourceId,index:this.index,href:this.href||void 0})}render(){const formattedIndex=getNumberFormat(this.effectiveLocale).format(this.index);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,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./citation-badge.styles.js";import{LYRA_DEFAULT_citation,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_citationUnverified,LYRA_DEFAULT_citationVerified,LYRA_DEFAULT_citationWithCustomLabel,LYRA_DEFAULT_citationWithStatus,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_MESSAGE_KEY={default:null,high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence",verified:"citationVerified",unverified:"citationUnverified"},HIDE_DELAY_MS=200;function isRealPreviewNode(n){return n.nodeType===Node.ELEMENT_NODE?!n.hasAttribute("slot"):(n.textContent??"").trim().length>0}class LyraCitationBadge extends LyraElement{constructor(){super(...arguments),this._index=1,this.status="default",this.sourceId="",this.href="",this.label="",this.hasPreviewSlot=!1,this.popoverOpen=!1,this.popoverId=nextId("citation-badge-popover"),this.hovering=!1,this.focused=!1,this.onSlotChange=e=>{this.hasPreviewSlot=e.target.assignedNodes({flatten:!0}).some(isRealPreviewNode),this.hasPreviewSlot||this.hidePreviewNow()},this.onPointerEnter=()=>{this.hovering=!0,this.showPreview()},this.onPointerLeave=()=>{this.hovering=!1,this.scheduleHidePreview()},this.onFocusIn=()=>{this.focused=!0,this.showPreview()},this.onFocusOut=()=>{this.focused=!1,!this.hovering&&this.hidePreviewNow()},this.onKeyDown=e=>{if(e.key==="Escape"&&this.popoverOpen){e.stopPropagation(),this.hidePreviewNow();return}e.key===" "&&!e.repeat&&e.target===this.buttonEl&&(e.preventDefault(),this.emitOpen())},this.onClick=()=>{this.emit("lr-citation-activate",{sourceId:this.sourceId,index:this.index})},this.onDblClick=()=>{this.emitOpen()}}static{this.defaultStrings={...super.defaultStrings,citation:LYRA_DEFAULT_citation,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,citationUnverified:LYRA_DEFAULT_citationUnverified,citationVerified:LYRA_DEFAULT_citationVerified,citationWithCustomLabel:LYRA_DEFAULT_citationWithCustomLabel,citationWithStatus:LYRA_DEFAULT_citationWithStatus,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get index(){return this._index}set index(value){const old=this._index;this._index=finiteInteger(value,1,1),this.requestUpdate("index",old)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasPreviewSlot=Array.from(this.childNodes).some(isRealPreviewNode))}updated(changed){super.updated(changed),changed.has("popoverOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.popoverOpen&&this.buttonEl&&this.popoverEl&&(this.cleanupPositioner=place(this.buttonEl,this.popoverEl,{placement:"top-start"})))}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen=!1,this.hovering=!1,this.focused=!1}get accessibleLabel(){const index=getNumberFormat(this.effectiveLocale).format(this.index);if(this.label)return this.localize("citationWithCustomLabel",void 0,{index,label:this.label});const key=STATUS_MESSAGE_KEY[this.status],statusText=key?this.localize(key):"",citationLabel=this.localize("citation",void 0,{index});return statusText?this.localize("citationWithStatus",void 0,{index,status:statusText}):citationLabel}showPreview(){this.hasPreviewSlot&&(clearTimeout(this.hideTimer),this.hideTimer=void 0,!this.popoverOpen&&(this.popoverOpen=!0))}scheduleHidePreview(){!this.popoverOpen||this.hovering||this.focused||(clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>{this.hideTimer=void 0,this.popoverOpen=!1},HIDE_DELAY_MS))}hidePreviewNow(){clearTimeout(this.hideTimer),this.hideTimer=void 0,this.popoverOpen&&(this.popoverOpen=!1)}emitOpen(){this.emit("lr-citation-open",{sourceId:this.sourceId,index:this.index,href:this.href||void 0})}render(){const formattedIndex=getNumberFormat(this.effectiveLocale).format(this.index);return html`
|
|
2
2
|
<span
|
|
3
3
|
class="wrapper"
|
|
4
4
|
@pointerenter=${this.onPointerEnter}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteRange}from"../../../internal/numbers.js";import"../../overlays/badge/badge.class.js";import"../../overlays/empty/empty.class.js";import"../citation-badge/citation-badge.class.js";import{styles}from"./claim-evidence.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_claimEvidenceConfidence,LYRA_DEFAULT_claimEvidenceContradicted,LYRA_DEFAULT_claimEvidenceEmpty,LYRA_DEFAULT_claimEvidenceLabel,LYRA_DEFAULT_claimEvidencePartiallySupported,LYRA_DEFAULT_claimEvidenceSupported,LYRA_DEFAULT_claimEvidenceUnsupported,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_VARIANT={supported:"success","partially-supported":"warning",unsupported:"danger",contradicted:"danger"};class LyraClaimEvidence extends LyraElement{constructor(){super(...arguments),this.claims=[],this.citations=[],this.selectedClaimId="",this.label="",this.compact=!1,this.frame="card"}static{this.defaultStrings={...super.defaultStrings,claimEvidenceConfidence:LYRA_DEFAULT_claimEvidenceConfidence,claimEvidenceContradicted:LYRA_DEFAULT_claimEvidenceContradicted,claimEvidenceEmpty:LYRA_DEFAULT_claimEvidenceEmpty,claimEvidenceLabel:LYRA_DEFAULT_claimEvidenceLabel,claimEvidencePartiallySupported:LYRA_DEFAULT_claimEvidencePartiallySupported,claimEvidenceSupported:LYRA_DEFAULT_claimEvidenceSupported,claimEvidenceUnsupported:LYRA_DEFAULT_claimEvidenceUnsupported,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["claims","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-claim-select","lr-citation-select"])}get normalizedClaims(){return firstByRetrievalIdentity(Array.isArray(this.claims)?this.claims:[],claim=>claim.id)}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}statusLabel(status){switch(status){case"supported":return this.localize("claimEvidenceSupported");case"partially-supported":return this.localize("claimEvidencePartiallySupported");case"unsupported":return this.localize("claimEvidenceUnsupported");case"contradicted":return this.localize("claimEvidenceContradicted")}}confidenceLabel(value){const percent=getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1));return this.localize("claimEvidenceConfidence",void 0,{percent})}resolvedCitations(claim,citations){const ids=new Set(claim.citationIds);return citations.filter(citation=>ids.has(citation.id))}renderClaim(claim,allCitations){const selected=claim.id===this.selectedClaimId,citations=this.resolvedCitations(claim,allCitations);return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteRange}from"../../../internal/numbers.js";import"../../overlays/badge/badge.class.js";import"../../overlays/empty/empty.class.js";import"../citation-badge/citation-badge.class.js";import{styles}from"./claim-evidence.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_claimEvidenceConfidence,LYRA_DEFAULT_claimEvidenceContradicted,LYRA_DEFAULT_claimEvidenceEmpty,LYRA_DEFAULT_claimEvidenceLabel,LYRA_DEFAULT_claimEvidencePartiallySupported,LYRA_DEFAULT_claimEvidenceSupported,LYRA_DEFAULT_claimEvidenceUnsupported,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STATUS_VARIANT={supported:"success","partially-supported":"warning",unsupported:"danger",contradicted:"danger"};class LyraClaimEvidence extends LyraElement{constructor(){super(...arguments),this.claims=[],this.citations=[],this.selectedClaimId="",this.label="",this.compact=!1,this.frame="card"}static{this.defaultStrings={...super.defaultStrings,claimEvidenceConfidence:LYRA_DEFAULT_claimEvidenceConfidence,claimEvidenceContradicted:LYRA_DEFAULT_claimEvidenceContradicted,claimEvidenceEmpty:LYRA_DEFAULT_claimEvidenceEmpty,claimEvidenceLabel:LYRA_DEFAULT_claimEvidenceLabel,claimEvidencePartiallySupported:LYRA_DEFAULT_claimEvidencePartiallySupported,claimEvidenceSupported:LYRA_DEFAULT_claimEvidenceSupported,claimEvidenceUnsupported:LYRA_DEFAULT_claimEvidenceUnsupported,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["claims","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-claim-select","lr-citation-select"])}get normalizedClaims(){return firstByRetrievalIdentity(Array.isArray(this.claims)?this.claims:[],claim=>claim.id)}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}statusLabel(status){switch(status){case"supported":return this.localize("claimEvidenceSupported");case"partially-supported":return this.localize("claimEvidencePartiallySupported");case"unsupported":return this.localize("claimEvidenceUnsupported");case"contradicted":return this.localize("claimEvidenceContradicted")}}confidenceLabel(value){const percent=getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1));return this.localize("claimEvidenceConfidence",void 0,{percent})}resolvedCitations(claim,citations){const ids=new Set(claim.citationIds);return citations.filter(citation=>ids.has(citation.id))}renderClaim(claim,allCitations){const selected=claim.id===this.selectedClaimId,citations=this.resolvedCitations(claim,allCitations);return html`
|
|
2
2
|
<li part=${selected?"claim claim-selected":"claim"} aria-current=${selected?"true":"false"}>
|
|
3
3
|
<button
|
|
4
4
|
part="claim-trigger"
|
|
@@ -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{hostAriaLabel}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../entity-card/entity-card.class.js";import"../neighbor-list/neighbor-list.class.js";import"../chunk-inspector/chunk-inspector.class.js";import"../provenance-panel/provenance-panel.class.js";import"../../data/stat/stat.class.js";import"../../layout/tab-group/tab-group.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./entity-dossier.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_chunkInspectorLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_provenancePanelLabel,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraEntityDossier extends LyraElement{constructor(){super(...arguments),this.entity=null,this.types=[],this.communityLabel="",this.showFocusButton=!0,this.confidence=null,this.neighbors=[],this.groupByRelation=!1,this.expandable=!1,this.chunks=[],this.thresholds={high:.75,medium:.5},this.provenance=null,this.accessibleLabel=null,this.activeTab="relationships",this.onTabsChange=e=>{e.stopPropagation();const tabId=e.detail.name;this.activeTab=tabId,this.emit("lr-tab-show",{tabId})}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,neighborListLabel:LYRA_DEFAULT_neighborListLabel,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,provenancePanelLabel:LYRA_DEFAULT_provenancePanelLabel,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["entity","confidence","types","neighbors","chunks","provenance"])}static{this.styles=[LyraElement.styles,styles]}render(){if(!this.entity)return html`<div part="base">
|
|
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{hostAriaLabel}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../entity-card/entity-card.class.js";import"../neighbor-list/neighbor-list.class.js";import"../chunk-inspector/chunk-inspector.class.js";import"../provenance-panel/provenance-panel.class.js";import"../../data/stat/stat.class.js";import"../../layout/tab-group/tab-group.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./entity-dossier.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_chunkInspectorLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_neighborListLabel,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_provenancePanelLabel,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraEntityDossier extends LyraElement{constructor(){super(...arguments),this.entity=null,this.types=[],this.communityLabel="",this.showFocusButton=!0,this.confidence=null,this.neighbors=[],this.groupByRelation=!1,this.expandable=!1,this.chunks=[],this.thresholds={high:.75,medium:.5},this.provenance=null,this.accessibleLabel=null,this.activeTab="relationships",this.onTabsChange=e=>{e.stopPropagation();const tabId=e.detail.name;this.activeTab=tabId,this.emit("lr-tab-show",{tabId})}}static{this.defaultStrings={...super.defaultStrings,chunkInspectorLabel:LYRA_DEFAULT_chunkInspectorLabel,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,neighborListLabel:LYRA_DEFAULT_neighborListLabel,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,provenancePanelLabel:LYRA_DEFAULT_provenancePanelLabel,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["entity","confidence","types","neighbors","chunks","provenance"])}static{this.styles=[LyraElement.styles,styles]}render(){if(!this.entity)return html`<div part="base">
|
|
2
2
|
<lr-empty part="empty" heading=${this.localize("noData")}></lr-empty>
|
|
3
3
|
</div>`;const entity=this.entity,c=this.confidence,tabsLabel=hostAriaLabel(this)===null?this.accessibleLabel??nothing:nothing;return html`
|
|
4
4
|
<div part="base">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import"../../data/stat/stat.class.js";import"../citation-badge/citation-badge.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./grounding-summary.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import"../claim-evidence/claim-evidence.class.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_groundingSummaryConfidenceLabel,LYRA_DEFAULT_groundingSummaryCoverageLabel,LYRA_DEFAULT_groundingSummaryEmpty,LYRA_DEFAULT_groundingSummaryEvidenceHeading,LYRA_DEFAULT_groundingSummaryEvidenceSpan,LYRA_DEFAULT_groundingSummaryLabel,LYRA_DEFAULT_groundingSummarySupportedLabel,LYRA_DEFAULT_groundingSummaryUnsupportedLabel,LYRA_DEFAULT_groundingSummaryWarningsHeading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraGroundingSummary extends LyraElement{constructor(){super(...arguments),this.assessment=null,this.citations=[],this.thresholds={high:.8,medium:.5},this.showClaims=!0,this.headingLevel="3",this.renderEvidenceItem=(citation,index)=>{const numberFormat=getNumberFormat(this.effectiveLocale),spanText=citation.span?this.localize("groundingSummaryEvidenceSpan",void 0,{start:numberFormat.format(finiteCount(citation.span.start)),end:numberFormat.format(finiteCount(citation.span.end))}):"";return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import"../../data/stat/stat.class.js";import"../citation-badge/citation-badge.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./grounding-summary.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import"../claim-evidence/claim-evidence.class.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_groundingSummaryConfidenceLabel,LYRA_DEFAULT_groundingSummaryCoverageLabel,LYRA_DEFAULT_groundingSummaryEmpty,LYRA_DEFAULT_groundingSummaryEvidenceHeading,LYRA_DEFAULT_groundingSummaryEvidenceSpan,LYRA_DEFAULT_groundingSummaryLabel,LYRA_DEFAULT_groundingSummarySupportedLabel,LYRA_DEFAULT_groundingSummaryUnsupportedLabel,LYRA_DEFAULT_groundingSummaryWarningsHeading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraGroundingSummary extends LyraElement{constructor(){super(...arguments),this.assessment=null,this.citations=[],this.thresholds={high:.8,medium:.5},this.showClaims=!0,this.headingLevel="3",this.renderEvidenceItem=(citation,index)=>{const numberFormat=getNumberFormat(this.effectiveLocale),spanText=citation.span?this.localize("groundingSummaryEvidenceSpan",void 0,{start:numberFormat.format(finiteCount(citation.span.start)),end:numberFormat.format(finiteCount(citation.span.end))}):"";return html`
|
|
2
2
|
<li part="evidence-item">
|
|
3
3
|
<lr-citation-badge
|
|
4
4
|
index=${index+1}
|
|
@@ -11,7 +11,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
11
11
|
${citation.label?html`<span part="evidence-label">${citation.label}</span>`:nothing}
|
|
12
12
|
${spanText?html`<span part="evidence-span">${spanText}</span>`:nothing}
|
|
13
13
|
</li>
|
|
14
|
-
`}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,groundingSummaryConfidenceLabel:LYRA_DEFAULT_groundingSummaryConfidenceLabel,groundingSummaryCoverageLabel:LYRA_DEFAULT_groundingSummaryCoverageLabel,groundingSummaryEmpty:LYRA_DEFAULT_groundingSummaryEmpty,groundingSummaryEvidenceHeading:LYRA_DEFAULT_groundingSummaryEvidenceHeading,groundingSummaryEvidenceSpan:LYRA_DEFAULT_groundingSummaryEvidenceSpan,groundingSummaryLabel:LYRA_DEFAULT_groundingSummaryLabel,groundingSummarySupportedLabel:LYRA_DEFAULT_groundingSummarySupportedLabel,groundingSummaryUnsupportedLabel:LYRA_DEFAULT_groundingSummaryUnsupportedLabel,groundingSummaryWarningsHeading:LYRA_DEFAULT_groundingSummaryWarningsHeading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["assessment","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-citation-select","lr-claim-select"])}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}normalizedClaims(assessment){return firstByRetrievalIdentity(Array.isArray(assessment.claims)?assessment.claims:[],claim=>claim.id)}sectionHeading(part,text){switch(resolveHeadingLevel(this.headingLevel)){case"1":return html`<h1 part=${part}>${text}</h1>`;case"2":return html`<h2 part=${part}>${text}</h2>`;case"4":return html`<h4 part=${part}>${text}</h4>`;case"5":return html`<h5 part=${part}>${text}</h5>`;case"6":return html`<h6 part=${part}>${text}</h6>`;case"3":return html`<h3 part=${part}>${text}</h3>`;default:return html`<span part=${part}>${text}</span>`}}tone(value){return value>=this.thresholds.high?"success":value>=this.thresholds.medium?"warning":"danger"}formatPercent(value){return getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1))}onCitationSelect(citation,event){event.stopPropagation(),this.emit("lr-citation-select",{citation})}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("groundingSummaryLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),a=this.assessment;if(!a)return html`<div
|
|
14
|
+
`}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,groundingSummaryConfidenceLabel:LYRA_DEFAULT_groundingSummaryConfidenceLabel,groundingSummaryCoverageLabel:LYRA_DEFAULT_groundingSummaryCoverageLabel,groundingSummaryEmpty:LYRA_DEFAULT_groundingSummaryEmpty,groundingSummaryEvidenceHeading:LYRA_DEFAULT_groundingSummaryEvidenceHeading,groundingSummaryEvidenceSpan:LYRA_DEFAULT_groundingSummaryEvidenceSpan,groundingSummaryLabel:LYRA_DEFAULT_groundingSummaryLabel,groundingSummarySupportedLabel:LYRA_DEFAULT_groundingSummarySupportedLabel,groundingSummaryUnsupportedLabel:LYRA_DEFAULT_groundingSummaryUnsupportedLabel,groundingSummaryWarningsHeading:LYRA_DEFAULT_groundingSummaryWarningsHeading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["assessment","citations"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-citation-select","lr-claim-select"])}get normalizedCitations(){return firstByRetrievalIdentity(Array.isArray(this.citations)?this.citations:[],citation=>citation.id)}normalizedClaims(assessment){return firstByRetrievalIdentity(Array.isArray(assessment.claims)?assessment.claims:[],claim=>claim.id)}sectionHeading(part,text){switch(resolveHeadingLevel(this.headingLevel)){case"1":return html`<h1 part=${part}>${text}</h1>`;case"2":return html`<h2 part=${part}>${text}</h2>`;case"4":return html`<h4 part=${part}>${text}</h4>`;case"5":return html`<h5 part=${part}>${text}</h5>`;case"6":return html`<h6 part=${part}>${text}</h6>`;case"3":return html`<h3 part=${part}>${text}</h3>`;default:return html`<span part=${part}>${text}</span>`}}tone(value){return value>=this.thresholds.high?"success":value>=this.thresholds.medium?"warning":"danger"}formatPercent(value){return getNumberFormat(this.effectiveLocale,{style:"percent"}).format(finiteRange(value,0,0,1))}onCitationSelect(citation,event){event.stopPropagation(),this.emit("lr-citation-select",{citation})}render(){const groupLabel=retrievalSemanticLabel(this,this.label==null?this.localize("groundingSummaryLabel"):this.label),groupRole=retrievalSemanticRole(this,"group"),a=this.assessment;if(!a)return html`<div
|
|
15
15
|
part="base"
|
|
16
16
|
role=${groupRole??nothing}
|
|
17
17
|
aria-label=${groupLabel??nothing}
|
package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js
CHANGED
|
@@ -81,6 +81,17 @@ import{css}from"lit";const styles=css`
|
|
|
81
81
|
color: var(--lr-color-text-quiet);
|
|
82
82
|
font-size: var(--lr-font-size-sm);
|
|
83
83
|
}
|
|
84
|
+
/* Type filters are a consumer-data-driven list (nodeTypes) with no library-imposed size limit --
|
|
85
|
+
without a cap it floors at its full content height (browser-default flex-item min-height:
|
|
86
|
+
auto) and starves 100% of the shrinkage onto [part='graph'] below, even though that part is
|
|
87
|
+
explicitly set up to be the one that shrinks. Same max-block-size + overflow-y pattern as
|
|
88
|
+
[part='search-results'] above. */
|
|
89
|
+
[part='legend'] {
|
|
90
|
+
flex: 0 1 auto;
|
|
91
|
+
max-block-size: var(--lr-size-12rem);
|
|
92
|
+
overflow-y: auto;
|
|
93
|
+
overflow-x: clip;
|
|
94
|
+
}
|
|
84
95
|
/* The one flexible row: it takes whatever the toolbar, search results, pinned row and path strip
|
|
85
96
|
leave over. flex-basis stays auto so an unsized host still gets the graph's intrinsic height,
|
|
86
97
|
while min-block-size: 0 removes the automatic content-based flex minimum that would otherwise
|
|
@@ -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{firstByRetrievalIdentity}from"../retrieval-identity.js";import{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import"../provenance-panel/provenance-panel.class.js";import"../../agent-tools/confirm-bar/confirm-bar.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./memory-panel.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_approve,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_collapse,LYRA_DEFAULT_deny,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_map,LYRA_DEFAULT_memoryPanelAdd,LYRA_DEFAULT_memoryPanelAddWithContext,LYRA_DEFAULT_memoryPanelConfirmAddHeading,LYRA_DEFAULT_memoryPanelConfirmForgetBody,LYRA_DEFAULT_memoryPanelConfirmForgetHeading,LYRA_DEFAULT_memoryPanelConfirmRemoveHeading,LYRA_DEFAULT_memoryPanelForgetAll,LYRA_DEFAULT_memoryPanelLabel,LYRA_DEFAULT_memoryPanelLongTermHeading,LYRA_DEFAULT_memoryPanelShortTermHeading,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showLess,LYRA_DEFAULT_showMore}from"../../../internal/default-strings.generated.js";const CONFIRM_HEADING_KEY={add:"memoryPanelConfirmAddHeading",remove:"memoryPanelConfirmRemoveHeading","forget-all":"memoryPanelConfirmForgetHeading"},TIER_LABEL_KEY={high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence"},TIER_TONE={high:"success",medium:"warning",low:"danger"};class LyraMemoryPanel extends LyraElement{constructor(){super(...arguments),this.shortTerm=[],this.longTerm=[],this.types=[],this.thresholds={high:.75,medium:.5},this.expandedIds=new Set,this.pending=null,this.idBase=nextId("memory-panel")}static{this.defaultStrings={...super.defaultStrings,approve:LYRA_DEFAULT_approve,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,collapse:LYRA_DEFAULT_collapse,deny:LYRA_DEFAULT_deny,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,map:LYRA_DEFAULT_map,memoryPanelAdd:LYRA_DEFAULT_memoryPanelAdd,memoryPanelAddWithContext:LYRA_DEFAULT_memoryPanelAddWithContext,memoryPanelConfirmAddHeading:LYRA_DEFAULT_memoryPanelConfirmAddHeading,memoryPanelConfirmForgetBody:LYRA_DEFAULT_memoryPanelConfirmForgetBody,memoryPanelConfirmForgetHeading:LYRA_DEFAULT_memoryPanelConfirmForgetHeading,memoryPanelConfirmRemoveHeading:LYRA_DEFAULT_memoryPanelConfirmRemoveHeading,memoryPanelForgetAll:LYRA_DEFAULT_memoryPanelForgetAll,memoryPanelLabel:LYRA_DEFAULT_memoryPanelLabel,memoryPanelLongTermHeading:LYRA_DEFAULT_memoryPanelLongTermHeading,memoryPanelShortTermHeading:LYRA_DEFAULT_memoryPanelShortTermHeading,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showLess:LYRA_DEFAULT_showLess,showMore:LYRA_DEFAULT_showMore}}static{this.ownedCollectionProperties=Object.freeze(["shortTerm","longTerm","types"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-add"])}willUpdate(changed){if(super.willUpdate(changed),this.captureControlledFocus(changed),!this.pending)return;if(this.pending.kind==="forget-all"){changed.has("longTerm")&&(this.pending=null);return}if(!changed.has("shortTerm")&&!changed.has("longTerm"))return;this.memoriesForScope(this.pending.scope).includes(this.pending.item)||(this.pending=null)}updated(changed){super.updated(changed);const pending=this.pendingControlledFocus;if(pending!==void 0){if(this.pendingControlledFocus=void 0,pending==="base"){this.renderRoot.querySelector('[part="base"]')?.focus();return}if(pending==="forget-all"){const button=this.renderRoot.querySelector('[part="forget-all-button"]');button?button.focus():this.renderRoot.querySelector('[part="base"]')?.focus();return}this.refocusItem(pending.scope,pending.index)}}captureControlledFocus(changed){if(!changed.has("shortTerm")&&!changed.has("longTerm"))return;const active=activeElementIn(this.shadowRoot);if(!active)return;const row=active.closest('[part="item"]');if(row){const scope=row.dataset.scope;if(!scope)return;const property2=scope==="short-term"?"shortTerm":"longTerm";if(!changed.has(property2))return;const oldIndex=[...this.renderRoot.querySelectorAll(`[part="section"][data-scope="${scope}"] [part="item"]`)].indexOf(row),focusedItem=this.normalizeMemories(changed.get(property2)??[])[oldIndex],nextItems=this.memoriesForScope(scope),survivingIndex=focusedItem?nextItems.findIndex(item=>item.id===focusedItem.id):-1;if(survivingIndex===oldIndex)return;nextItems.length===0&&this.normalizedShortTerm.length===0&&this.normalizedLongTerm.length===0?this.pendingControlledFocus="base":this.pendingControlledFocus={scope,index:survivingIndex>=0?survivingIndex:Math.min(Math.max(oldIndex,0),Math.max(0,nextItems.length-1))};return}if(active.getAttribute("part")==="forget-all-confirm"&&changed.has("longTerm")){this.pendingControlledFocus=this.normalizedLongTerm.length===0?"base":"forget-all";return}active.getAttribute("part")==="forget-all-button"&&changed.has("longTerm")&&this.normalizedLongTerm.length===0&&(this.pendingControlledFocus="base")}normalizeMemories(value){return firstByRetrievalIdentity(Array.isArray(value)?value:[],memory=>memory.id)}get normalizedShortTerm(){return this.normalizeMemories(this.shortTerm)}get normalizedLongTerm(){return this.normalizeMemories(this.longTerm)}memoriesForScope(scope){return scope==="short-term"?this.normalizedShortTerm:this.normalizedLongTerm}itemKey(item,scope){return`${scope}\0${item.id}`}itemBodyId(scope,index){return`${this.idBase}-${scope}-${index}`}tier(score){return score>=this.thresholds.high?"high":score>=this.thresholds.medium?"medium":"low"}toggleExpand(item,scope){const key=this.itemKey(item,scope),next=new Set(this.expandedIds),expanded=!next.has(key);expanded?next.add(key):next.delete(key),this.expandedIds=next,this.emit("lr-expand",{memoryId:item.id,scope,expanded})}startItemPending(kind,item,scope){this.pending={kind,item,scope},this.focusPendingConfirmation()}startForgetAllPending(){this.pending={kind:"forget-all",longTerm:this.longTerm},this.focusPendingConfirmation()}focusPendingConfirmation(){const started=this.pending;this.updateComplete.then(async()=>{const bar=this.renderRoot.querySelector("lr-confirm-bar");if(!bar)return;await bar.updateComplete;const deny=bar.shadowRoot?.querySelector('[part="deny-button"]');await deny?.updateComplete,!(this.pending!==started||!bar.isConnected)&&(deny??bar.shadowRoot?.querySelector('[part="status"]'))?.focus()})}onConfirmKeyDown(event,cancel){if(event.key!=="Escape")return;const before=this.pending;cancel(),this.pending!==before&&event.stopPropagation()}refocusItem(scope,index){this.updateComplete.then(()=>{const rows=[...this.renderRoot.querySelectorAll(`[part="section"][data-scope="${scope}"] [part="item"]`)];(rows[Math.min(index,rows.length-1)]??this.renderRoot.querySelector('[part="item"]')??this.renderRoot.querySelector('[part="base"]'))?.focus()})}resolveItemDecision(p,approved){if(this.pending!==p)return;const index=this.memoriesForScope(p.scope).indexOf(p.item);index<0||(this.pending=null,approved&&(p.kind==="add"?this.emit("lr-add",{memory:p.item}):this.emit("lr-remove",{memoryId:p.item.id,scope:p.scope})),this.refocusItem(p.scope,index))}resolveForgetAllDecision(pending,approved){this.pending!==pending||this.longTerm!==pending.longTerm||(this.pending=null,approved&&this.emit("lr-forget"),this.updateComplete.then(()=>{(this.renderRoot.querySelector('[part="forget-all-button"]')??this.renderRoot.querySelector('[part="item"]'))?.focus()}))}renderConfidence(item){if(item.confidence==null)return nothing;const tier=this.tier(item.confidence);return html`<span part="confidence" data-tone=${TIER_TONE[tier]}
|
|
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{firstByRetrievalIdentity}from"../retrieval-identity.js";import{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import"../provenance-panel/provenance-panel.class.js";import"../../agent-tools/confirm-bar/confirm-bar.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./memory-panel.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_approve,LYRA_DEFAULT_citationHighConfidence,LYRA_DEFAULT_citationLowConfidence,LYRA_DEFAULT_citationMediumConfidence,LYRA_DEFAULT_collapse,LYRA_DEFAULT_deny,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_map,LYRA_DEFAULT_memoryPanelAdd,LYRA_DEFAULT_memoryPanelAddWithContext,LYRA_DEFAULT_memoryPanelConfirmAddHeading,LYRA_DEFAULT_memoryPanelConfirmForgetBody,LYRA_DEFAULT_memoryPanelConfirmForgetHeading,LYRA_DEFAULT_memoryPanelConfirmRemoveHeading,LYRA_DEFAULT_memoryPanelForgetAll,LYRA_DEFAULT_memoryPanelLabel,LYRA_DEFAULT_memoryPanelLongTermHeading,LYRA_DEFAULT_memoryPanelShortTermHeading,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_remove,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showLess,LYRA_DEFAULT_showMore}from"../../../internal/default-strings.generated.js";const CONFIRM_HEADING_KEY={add:"memoryPanelConfirmAddHeading",remove:"memoryPanelConfirmRemoveHeading","forget-all":"memoryPanelConfirmForgetHeading"},TIER_LABEL_KEY={high:"citationHighConfidence",medium:"citationMediumConfidence",low:"citationLowConfidence"},TIER_TONE={high:"success",medium:"warning",low:"danger"};class LyraMemoryPanel extends LyraElement{constructor(){super(...arguments),this.shortTerm=[],this.longTerm=[],this.types=[],this.thresholds={high:.75,medium:.5},this.expandedIds=new Set,this.pending=null,this.idBase=nextId("memory-panel")}static{this.defaultStrings={...super.defaultStrings,approve:LYRA_DEFAULT_approve,citationHighConfidence:LYRA_DEFAULT_citationHighConfidence,citationLowConfidence:LYRA_DEFAULT_citationLowConfidence,citationMediumConfidence:LYRA_DEFAULT_citationMediumConfidence,collapse:LYRA_DEFAULT_collapse,deny:LYRA_DEFAULT_deny,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,map:LYRA_DEFAULT_map,memoryPanelAdd:LYRA_DEFAULT_memoryPanelAdd,memoryPanelAddWithContext:LYRA_DEFAULT_memoryPanelAddWithContext,memoryPanelConfirmAddHeading:LYRA_DEFAULT_memoryPanelConfirmAddHeading,memoryPanelConfirmForgetBody:LYRA_DEFAULT_memoryPanelConfirmForgetBody,memoryPanelConfirmForgetHeading:LYRA_DEFAULT_memoryPanelConfirmForgetHeading,memoryPanelConfirmRemoveHeading:LYRA_DEFAULT_memoryPanelConfirmRemoveHeading,memoryPanelForgetAll:LYRA_DEFAULT_memoryPanelForgetAll,memoryPanelLabel:LYRA_DEFAULT_memoryPanelLabel,memoryPanelLongTermHeading:LYRA_DEFAULT_memoryPanelLongTermHeading,memoryPanelShortTermHeading:LYRA_DEFAULT_memoryPanelShortTermHeading,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,remove:LYRA_DEFAULT_remove,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showLess:LYRA_DEFAULT_showLess,showMore:LYRA_DEFAULT_showMore}}static{this.ownedCollectionProperties=Object.freeze(["shortTerm","longTerm","types"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-add"])}willUpdate(changed){if(super.willUpdate(changed),this.captureControlledFocus(changed),!this.pending)return;if(this.pending.kind==="forget-all"){changed.has("longTerm")&&(this.pending=null);return}if(!changed.has("shortTerm")&&!changed.has("longTerm"))return;this.memoriesForScope(this.pending.scope).includes(this.pending.item)||(this.pending=null)}updated(changed){super.updated(changed);const pending=this.pendingControlledFocus;if(pending!==void 0){if(this.pendingControlledFocus=void 0,pending==="base"){this.renderRoot.querySelector('[part="base"]')?.focus();return}if(pending==="forget-all"){const button=this.renderRoot.querySelector('[part="forget-all-button"]');button?button.focus():this.renderRoot.querySelector('[part="base"]')?.focus();return}this.refocusItem(pending.scope,pending.index)}}captureControlledFocus(changed){if(!changed.has("shortTerm")&&!changed.has("longTerm"))return;const active=activeElementIn(this.shadowRoot);if(!active)return;const row=active.closest('[part="item"]');if(row){const scope=row.dataset.scope;if(!scope)return;const property2=scope==="short-term"?"shortTerm":"longTerm";if(!changed.has(property2))return;const oldIndex=[...this.renderRoot.querySelectorAll(`[part="section"][data-scope="${scope}"] [part="item"]`)].indexOf(row),focusedItem=this.normalizeMemories(changed.get(property2)??[])[oldIndex],nextItems=this.memoriesForScope(scope),survivingIndex=focusedItem?nextItems.findIndex(item=>item.id===focusedItem.id):-1;if(survivingIndex===oldIndex)return;nextItems.length===0&&this.normalizedShortTerm.length===0&&this.normalizedLongTerm.length===0?this.pendingControlledFocus="base":this.pendingControlledFocus={scope,index:survivingIndex>=0?survivingIndex:Math.min(Math.max(oldIndex,0),Math.max(0,nextItems.length-1))};return}if(active.getAttribute("part")==="forget-all-confirm"&&changed.has("longTerm")){this.pendingControlledFocus=this.normalizedLongTerm.length===0?"base":"forget-all";return}active.getAttribute("part")==="forget-all-button"&&changed.has("longTerm")&&this.normalizedLongTerm.length===0&&(this.pendingControlledFocus="base")}normalizeMemories(value){return firstByRetrievalIdentity(Array.isArray(value)?value:[],memory=>memory.id)}get normalizedShortTerm(){return this.normalizeMemories(this.shortTerm)}get normalizedLongTerm(){return this.normalizeMemories(this.longTerm)}memoriesForScope(scope){return scope==="short-term"?this.normalizedShortTerm:this.normalizedLongTerm}itemKey(item,scope){return`${scope}\0${item.id}`}itemBodyId(scope,index){return`${this.idBase}-${scope}-${index}`}tier(score){return score>=this.thresholds.high?"high":score>=this.thresholds.medium?"medium":"low"}toggleExpand(item,scope){const key=this.itemKey(item,scope),next=new Set(this.expandedIds),expanded=!next.has(key);expanded?next.add(key):next.delete(key),this.expandedIds=next,this.emit("lr-expand",{memoryId:item.id,scope,expanded})}startItemPending(kind,item,scope){this.pending={kind,item,scope},this.focusPendingConfirmation()}startForgetAllPending(){this.pending={kind:"forget-all",longTerm:this.longTerm},this.focusPendingConfirmation()}focusPendingConfirmation(){const started=this.pending;this.updateComplete.then(async()=>{const bar=this.renderRoot.querySelector("lr-confirm-bar");if(!bar)return;await bar.updateComplete;const deny=bar.shadowRoot?.querySelector('[part="deny-button"]');await deny?.updateComplete,!(this.pending!==started||!bar.isConnected)&&(deny??bar.shadowRoot?.querySelector('[part="status"]'))?.focus()})}onConfirmKeyDown(event,cancel){if(event.key!=="Escape")return;const before=this.pending;cancel(),this.pending!==before&&event.stopPropagation()}refocusItem(scope,index){this.updateComplete.then(()=>{const rows=[...this.renderRoot.querySelectorAll(`[part="section"][data-scope="${scope}"] [part="item"]`)];(rows[Math.min(index,rows.length-1)]??this.renderRoot.querySelector('[part="item"]')??this.renderRoot.querySelector('[part="base"]'))?.focus()})}resolveItemDecision(p,approved){if(this.pending!==p)return;const index=this.memoriesForScope(p.scope).indexOf(p.item);index<0||(this.pending=null,approved&&(p.kind==="add"?this.emit("lr-add",{memory:p.item}):this.emit("lr-remove",{memoryId:p.item.id,scope:p.scope})),this.refocusItem(p.scope,index))}resolveForgetAllDecision(pending,approved){this.pending!==pending||this.longTerm!==pending.longTerm||(this.pending=null,approved&&this.emit("lr-forget"),this.updateComplete.then(()=>{(this.renderRoot.querySelector('[part="forget-all-button"]')??this.renderRoot.querySelector('[part="item"]'))?.focus()}))}renderConfidence(item){if(item.confidence==null)return nothing;const tier=this.tier(item.confidence);return html`<span part="confidence" data-tone=${TIER_TONE[tier]}
|
|
2
2
|
>${this.localize(TIER_LABEL_KEY[tier])}</span
|
|
3
3
|
>`}renderItemConfirm(p){return html`
|
|
4
4
|
<lr-confirm-bar
|
|
@@ -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{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import"../entity-chip/entity-chip.class.js";import"../path-strip/path-strip.class.js";import"../community-card/community-card.class.js";import"../chunk-inspector/chunk-inspector.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./provenance-panel.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_provenanceChunks,LYRA_DEFAULT_provenanceCommunities,LYRA_DEFAULT_provenanceEmpty,LYRA_DEFAULT_provenanceEntities,LYRA_DEFAULT_provenancePanelLabel,LYRA_DEFAULT_provenanceRelationships,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraProvenancePanel extends LyraElement{constructor(){super(...arguments),this.provenance=null,this.types=[],this.thresholds={high:.75,medium:.5},this.expandedSections={entities:!0,relationships:!0,communities:!0,chunks:!0},this.sectionIdBase=nextId("provenance-panel")}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,provenanceChunks:LYRA_DEFAULT_provenanceChunks,provenanceCommunities:LYRA_DEFAULT_provenanceCommunities,provenanceEmpty:LYRA_DEFAULT_provenanceEmpty,provenanceEntities:LYRA_DEFAULT_provenanceEntities,provenancePanelLabel:LYRA_DEFAULT_provenancePanelLabel,provenanceRelationships:LYRA_DEFAULT_provenanceRelationships,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["provenance","types"])}static{this.styles=[LyraElement.styles,styles]}toggleSection(section){const expanded=!this.expandedSections[section];this.expandedSections={...this.expandedSections,[section]:expanded},this.emit("lr-toggle",{section,expanded})}renderSection(section,titleKey,count,body){if(count===0)return nothing;const expanded=this.expandedSections[section],bodyId=`${this.sectionIdBase}-${section}`;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{nextId}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import"../entity-chip/entity-chip.class.js";import"../path-strip/path-strip.class.js";import"../community-card/community-card.class.js";import"../chunk-inspector/chunk-inspector.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./provenance-panel.styles.js";import{retrievalSemanticLabel,retrievalSemanticRole}from"../retrieval-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_provenanceChunks,LYRA_DEFAULT_provenanceCommunities,LYRA_DEFAULT_provenanceEmpty,LYRA_DEFAULT_provenanceEntities,LYRA_DEFAULT_provenancePanelLabel,LYRA_DEFAULT_provenanceRelationships,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraProvenancePanel extends LyraElement{constructor(){super(...arguments),this.provenance=null,this.types=[],this.thresholds={high:.75,medium:.5},this.expandedSections={entities:!0,relationships:!0,communities:!0,chunks:!0},this.sectionIdBase=nextId("provenance-panel")}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,provenanceChunks:LYRA_DEFAULT_provenanceChunks,provenanceCommunities:LYRA_DEFAULT_provenanceCommunities,provenanceEmpty:LYRA_DEFAULT_provenanceEmpty,provenanceEntities:LYRA_DEFAULT_provenanceEntities,provenancePanelLabel:LYRA_DEFAULT_provenancePanelLabel,provenanceRelationships:LYRA_DEFAULT_provenanceRelationships,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["provenance","types"])}static{this.styles=[LyraElement.styles,styles]}toggleSection(section){const expanded=!this.expandedSections[section];this.expandedSections={...this.expandedSections,[section]:expanded},this.emit("lr-toggle",{section,expanded})}renderSection(section,titleKey,count,body){if(count===0)return nothing;const expanded=this.expandedSections[section],bodyId=`${this.sectionIdBase}-${section}`;return html`
|
|
2
2
|
<div part="section">
|
|
3
3
|
<button
|
|
4
4
|
part="header"
|
|
@@ -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{nextId}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import"../../agent-tools/span-waterfall/span-waterfall.class.js";import"../chunk-inspector/chunk-inspector.class.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{styles}from"./retrieval-trace.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_retrievalStageEmbed,LYRA_DEFAULT_retrievalStageFilter,LYRA_DEFAULT_retrievalStageQueryRewrite,LYRA_DEFAULT_retrievalStageRerank,LYRA_DEFAULT_retrievalStageRetrieve,LYRA_DEFAULT_retrievalTraceEvidenceToggle,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STAGE_SPAN_KIND={"query-rewrite":"llm",embed:"embedding",retrieve:"retriever",rerank:"tool",filter:"tool"},STAGE_LABEL={"query-rewrite":{key:"retrievalStageQueryRewrite"},embed:{key:"retrievalStageEmbed"},retrieve:{key:"retrievalStageRetrieve"},rerank:{key:"retrievalStageRerank"},filter:{key:"retrievalStageFilter"}};function hasEvidence(evidence){return evidence?!!evidence.text||!!(evidence.chunks&&evidence.chunks.length>0)||!!(evidence.metadata&&Object.keys(evidence.metadata).length>0):!1}function toLyraChunk(chunk){return{id:chunk.id,text:chunk.text,score:chunk.score,sourceId:chunk.source.id,title:chunk.source.name,...chunk.locator?{anchor:chunk.locator}:{},...chunk.locator?.kind==="page"?{page:chunk.locator.page}:{}}}class LyraRetrievalTrace extends LyraElement{constructor(){super(...arguments),this.stages=[],this.activeStageId=null,this.label="",this.expandedStageIds=new Set,this.evidenceDomIdPrefix=nextId("retrieval-trace-evidence"),this.onStageSelect=e=>{e.stopPropagation();const{spanId:stageId}=e.detail;this.emit("lr-stage-select",{stageId});const stage=this.normalizedStages.find(s=>s.id===stageId);if(stage&&hasEvidence(stage.evidence)&&!this.expandedStageIds.has(stageId)){const next=new Set(this.expandedStageIds);next.add(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded:!0})}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,retrievalStageEmbed:LYRA_DEFAULT_retrievalStageEmbed,retrievalStageFilter:LYRA_DEFAULT_retrievalStageFilter,retrievalStageQueryRewrite:LYRA_DEFAULT_retrievalStageQueryRewrite,retrievalStageRerank:LYRA_DEFAULT_retrievalStageRerank,retrievalStageRetrieve:LYRA_DEFAULT_retrievalStageRetrieve,retrievalTraceEvidenceToggle:LYRA_DEFAULT_retrievalTraceEvidenceToggle,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["stages"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-stage-chunk-action"])}get normalizedStages(){return firstByRetrievalIdentity(Array.isArray(this.stages)?this.stages:[],stage=>stage.id)}stageLabel(stage){return stage.label?stage.label:this.localize(STAGE_LABEL[stage.kind].key)}toSpans(){return this.normalizedStages.map(stage=>({id:stage.id,name:this.stageLabel(stage),kind:STAGE_SPAN_KIND[stage.kind],startMs:stage.startMs,endMs:stage.endMs,status:stage.status,detail:stage.detail}))}toggleEvidence(stageId){const expanded=!this.expandedStageIds.has(stageId),next=new Set(this.expandedStageIds);expanded?next.add(stageId):next.delete(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded})}willUpdate(changed){if(super.willUpdate(changed),changed.has("stages")){const ids=new Set(this.normalizedStages.map(s=>s.id));let pruned=null;for(const id of this.expandedStageIds)ids.has(id)||(pruned??=new Set(this.expandedStageIds),pruned.delete(id));pruned&&(this.expandedStageIds=pruned)}}renderEvidenceBody(stage){const evidence=stage.evidence,chunks=evidence.chunks&&evidence.chunks.length>0?evidence.chunks.map(toLyraChunk):[],metaEntries=evidence.metadata?Object.entries(evidence.metadata):[];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{nextId}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import"../../agent-tools/span-waterfall/span-waterfall.class.js";import"../chunk-inspector/chunk-inspector.class.js";import{firstByRetrievalIdentity}from"../retrieval-identity.js";import{styles}from"./retrieval-trace.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_retrievalStageEmbed,LYRA_DEFAULT_retrievalStageFilter,LYRA_DEFAULT_retrievalStageQueryRewrite,LYRA_DEFAULT_retrievalStageRerank,LYRA_DEFAULT_retrievalStageRetrieve,LYRA_DEFAULT_retrievalTraceEvidenceToggle,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const STAGE_SPAN_KIND={"query-rewrite":"llm",embed:"embedding",retrieve:"retriever",rerank:"tool",filter:"tool"},STAGE_LABEL={"query-rewrite":{key:"retrievalStageQueryRewrite"},embed:{key:"retrievalStageEmbed"},retrieve:{key:"retrievalStageRetrieve"},rerank:{key:"retrievalStageRerank"},filter:{key:"retrievalStageFilter"}};function hasEvidence(evidence){return evidence?!!evidence.text||!!(evidence.chunks&&evidence.chunks.length>0)||!!(evidence.metadata&&Object.keys(evidence.metadata).length>0):!1}function toLyraChunk(chunk){return{id:chunk.id,text:chunk.text,score:chunk.score,sourceId:chunk.source.id,title:chunk.source.name,...chunk.locator?{anchor:chunk.locator}:{},...chunk.locator?.kind==="page"?{page:chunk.locator.page}:{}}}class LyraRetrievalTrace extends LyraElement{constructor(){super(...arguments),this.stages=[],this.activeStageId=null,this.label="",this.expandedStageIds=new Set,this.evidenceDomIdPrefix=nextId("retrieval-trace-evidence"),this.onStageSelect=e=>{e.stopPropagation();const{spanId:stageId}=e.detail;this.emit("lr-stage-select",{stageId});const stage=this.normalizedStages.find(s=>s.id===stageId);if(stage&&hasEvidence(stage.evidence)&&!this.expandedStageIds.has(stageId)){const next=new Set(this.expandedStageIds);next.add(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded:!0})}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,retrievalStageEmbed:LYRA_DEFAULT_retrievalStageEmbed,retrievalStageFilter:LYRA_DEFAULT_retrievalStageFilter,retrievalStageQueryRewrite:LYRA_DEFAULT_retrievalStageQueryRewrite,retrievalStageRerank:LYRA_DEFAULT_retrievalStageRerank,retrievalStageRetrieve:LYRA_DEFAULT_retrievalStageRetrieve,retrievalTraceEvidenceToggle:LYRA_DEFAULT_retrievalTraceEvidenceToggle,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["stages"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-stage-chunk-action"])}get normalizedStages(){return firstByRetrievalIdentity(Array.isArray(this.stages)?this.stages:[],stage=>stage.id)}stageLabel(stage){return stage.label?stage.label:this.localize(STAGE_LABEL[stage.kind].key)}toSpans(){return this.normalizedStages.map(stage=>({id:stage.id,name:this.stageLabel(stage),kind:STAGE_SPAN_KIND[stage.kind],startMs:stage.startMs,endMs:stage.endMs,status:stage.status,detail:stage.detail}))}toggleEvidence(stageId){const expanded=!this.expandedStageIds.has(stageId),next=new Set(this.expandedStageIds);expanded?next.add(stageId):next.delete(stageId),this.expandedStageIds=next,this.emit("lr-stage-toggle",{stageId,expanded})}willUpdate(changed){if(super.willUpdate(changed),changed.has("stages")){const ids=new Set(this.normalizedStages.map(s=>s.id));let pruned=null;for(const id of this.expandedStageIds)ids.has(id)||(pruned??=new Set(this.expandedStageIds),pruned.delete(id));pruned&&(this.expandedStageIds=pruned)}}renderEvidenceBody(stage){const evidence=stage.evidence,chunks=evidence.chunks&&evidence.chunks.length>0?evidence.chunks.map(toLyraChunk):[],metaEntries=evidence.metadata?Object.entries(evidence.metadata):[];return html`
|
|
2
2
|
${evidence.text?html`<p part="evidence-text">${evidence.text}</p>`:nothing}
|
|
3
3
|
${chunks.length>0?html`<lr-chunk-inspector
|
|
4
4
|
part="chunk-inspector"
|
|
@@ -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{styleMap}from"lit/directives/style-map.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64;class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.showSelectAll=!0,this.searchable=!0,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-sources-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sources&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sources,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=source.children??[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sources,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedSourceIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>this.selectedSourceIds.includes(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return this.searchable&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds();(normalized.length!==this.selectedSourceIds.length||normalized.some((id,index)=>id!==this.selectedSourceIds[index]))&&(this.selectedSourceIds=normalized)}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(activeElementIn(this.shadowRoot)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sources.length===0||!this.searchable?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,count===0&&this.announcementSink?.announce(this.localize("noMatches")))}commitSelection(next){this.selectedSourceIds=next,this.emit("lr-sources-change",{selectedSourceIds:next})}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),willSelect=this.checkedState(entry)!=="true",set=new Set(this.selectedSourceIds);for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}toggleSelectAll(){const all=this.allLeafIds(),allSelected=all.length>0&&all.every(id=>this.selectedSourceIds.includes(id));this.commitSelection(allSelected?[]:all)}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active){const state2=this.checkedState(row.entry),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());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{styleMap}from"lit/directives/style-map.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64;class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.showSelectAll=!0,this.searchable=!0,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-sources-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sources&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sources,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=source.children??[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sources,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedSourceIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>this.selectedSourceIds.includes(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return this.searchable&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds();(normalized.length!==this.selectedSourceIds.length||normalized.some((id,index)=>id!==this.selectedSourceIds[index]))&&(this.selectedSourceIds=normalized)}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(activeElementIn(this.shadowRoot)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sources.length===0||!this.searchable?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,count===0&&this.announcementSink?.announce(this.localize("noMatches")))}commitSelection(next){this.selectedSourceIds=next,this.emit("lr-sources-change",{selectedSourceIds:next})}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),willSelect=this.checkedState(entry)!=="true",set=new Set(this.selectedSourceIds);for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}toggleSelectAll(){const all=this.allLeafIds(),allSelected=all.length>0&&all.every(id=>this.selectedSourceIds.includes(id));this.commitSelection(allSelected?[]:all)}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active){const state2=this.checkedState(row.entry),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
|
|
2
2
|
<div
|
|
3
3
|
part="item"
|
|
4
4
|
role="treeitem"
|