@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,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{LyraVirtualList}from"../../layout/virtual-list/virtual-list.class.js";import{styles}from"./chat-viewport.styles.js";import{getNumberFormat,getPluralRules}from"../../../internal/intl-cache.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{LYRA_DEFAULT_chatViewportLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_jumpToLatest,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_newMessageCount,LYRA_DEFAULT_newMessages,LYRA_DEFAULT_newMessagesCount,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraChatViewport extends LyraElement{constructor(){super(...arguments),this.follow=!0,this.live="off",this.bottomThreshold=24,this.unreadStartIndex=null,this.label="",this.accessibleLabel=null,this.unreadDividerTop=null,this.pendingUserIntent=!1,this.pendingUserIntentExpiryFrame=null,this.scrollbarDragActive=!1,this.isMounting=!0,this.growthFrame=null,this.armedMode=null,this.armGeneration=0,this.followFocusRepair=null,this.knownProjectedNodes=new WeakSet,this.markUserIntent=()=>{this.pendingUserIntent=!0,this.cancelPendingUserIntentExpiry();const owner=this.ownerDocument.defaultView;if(!owner){this.pendingUserIntent=!1;return}const firstFrame={owner,handle:0};firstFrame.handle=owner.requestAnimationFrame(()=>{if(this.pendingUserIntentExpiryFrame!==firstFrame)return;if(!this.isConnected||this.ownerDocument.defaultView!==owner){this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1;return}const secondFrame={owner,handle:0};secondFrame.handle=owner.requestAnimationFrame(()=>{this.pendingUserIntentExpiryFrame===secondFrame&&(this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1)}),this.pendingUserIntentExpiryFrame=secondFrame}),this.pendingUserIntentExpiryFrame=firstFrame},this.onPointerDown=event=>{const scroll=this.scrollEl;if(!scroll||event.button!==0||event.target!==scroll)return;const computed=getComputedStyle(scroll),borderLeft=Number.parseFloat(computed.borderLeftWidth)||0,borderRight=Number.parseFloat(computed.borderRightWidth)||0,gutter=scroll.offsetWidth-scroll.clientWidth-borderLeft-borderRight;if(gutter<=0)return;const rect=scroll.getBoundingClientRect();if(!(computed.direction==="rtl"?event.clientX<=rect.left+borderLeft+gutter:event.clientX>=rect.right-borderRight-gutter))return;this.scrollbarDragActive=!0;const owner=this.ownerDocument.defaultView;!owner||this.scrollbarDragWindow===owner||(this.releaseScrollbarDragListeners(),this.scrollbarDragWindow=owner,owner.addEventListener("pointerup",this.onPointerUp),owner.addEventListener("pointercancel",this.onPointerUp),owner.addEventListener("lostpointercapture",this.onPointerUp))},this.onPointerUp=()=>{this.scrollbarDragActive=!1,this.releaseScrollbarDragListeners()},this.onKeyDown=e=>{(e.key==="PageUp"||e.key==="ArrowUp"||e.key==="Home")&&this.markUserIntent()},this.onScroll=()=>{const el=this.scrollEl;if(!el)return;if(el.scrollHeight-el.scrollTop-el.clientHeight<=this.effectiveBottomThreshold){this.clearUserIntent(),this.follow||(this.follow=!0);return}(this.consumeUserIntent()||this.scrollbarDragActive)&&this.follow&&(this.follow=!1)},this.onVirtualRangeChanged=e=>{const list=this.virtualListEl;if(!list||e.composedPath()[0]!==list)return;const detail=e.detail;if(!detail||!Number.isFinite(detail.start)||!Number.isFinite(detail.end)||detail.start<0||detail.end<detail.start)return;if(list.items.length>0&&detail.end>=list.items.length-1){this.clearUserIntent(),this.follow||(this.follow=!0);return}if(this.consumeUserIntent()||this.scrollbarDragActive){this.follow&&(this.follow=!1);return}this.follow&&this.performScrollToEnd("auto")},this.onSlotChange=()=>{this.announceNewProjectedNodes();const wasVirtual=this.armedMode==="virtual";this.armObservers(),this.armedMode==="virtual"!==wasVirtual&&this.requestUpdate()},this.onContentMutations=records=>{this.scheduleGrowthTick();const sink=this.announcementSink;if(sink)for(const record of records)for(const node of record.addedNodes){if(this.knownProjectedNodes.has(node)||node instanceof Element&&node.hasAttribute("data-lr-chat-viewport-unread-boundary"))continue;this.knownProjectedNodes.add(node);const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}}static{this.defaultStrings={...super.defaultStrings,chatViewportLabel:LYRA_DEFAULT_chatViewportLabel,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,jumpToLatest:LYRA_DEFAULT_jumpToLatest,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,newMessageCount:LYRA_DEFAULT_newMessageCount,newMessages:LYRA_DEFAULT_newMessages,newMessagesCount:LYRA_DEFAULT_newMessagesCount,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get messageElements(){let elements=this.contentSlot?.assignedElements({flatten:!0})??Array.from(this.children);for(let depth=0;depth<4&&elements.some(element=>element.localName==="slot");depth++)elements=elements.flatMap(element=>element.localName==="slot"?element.assignedElements({flatten:!0}):[element]);return elements.filter(element=>!element.hasAttribute("data-lr-chat-viewport-unread-boundary"))}get virtualListEl(){const children=this.messageElements;return children.length===1&&children[0]instanceof LyraVirtualList?children[0]:null}get effectiveBottomThreshold(){return finiteRange(this.bottomThreshold,24,0)}get effectiveUnreadStartIndex(){return this.unreadStartIndex==null?null:finiteCount(this.unreadStartIndex)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.armObservers()}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.teardownObservers(),this.releaseScrollbarDragListeners(),this.clearUserIntent(),this.scrollbarDragActive=!1,this.followFocusRepair=null,this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||!changed.has("follow")||!this.follow||changed.get("follow")!==!1)return;const pill=this.renderRoot.querySelector('[part="jump-pill"]');this.followFocusRepair=pill?captureComposedFocusRepair(pill,this.transcriptFocusOwner()):null}firstUpdated(changed){super.firstUpdated(changed),this.armObservers()}updated(changed){super.updated(changed),changed.has("live")&&this.syncAnnouncementSink();const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("follow")){if(this.follow){const behavior=wasMounting?"auto":this.pendingScrollBehavior??(prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth");this.pendingScrollBehavior=void 0,this.performScrollToEnd(behavior)}wasMounting||this.emit("lr-follow-change",{following:this.follow})}changed.has("unreadStartIndex")&&!wasMounting&&this.updateUnreadDividerPosition();const focusRepair=this.followFocusRepair;this.followFocusRepair=null,focusRepair&&applyComposedFocusRepair(focusRepair)}transcriptFocusOwner(){const list=this.virtualListEl;return list?collectComposedFocusTargets(list,{includeRoot:!1,mode:"programmatic"}).elements[0]??null:this.scrollEl??null}scrollToBottom(options){const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth";this.follow?this.performScrollToEnd(behavior):(this.pendingScrollBehavior=behavior,this.follow=!0)}scrollToUnread(options){const unreadStartIndex=this.effectiveUnreadStartIndex;if(unreadStartIndex==null)return!1;const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth",list=this.virtualListEl;if(list)return unreadStartIndex>=list.items.length?!1:(list.scrollToIndex(unreadStartIndex,{align:"start",behavior}),!0);const scrollEl=this.scrollEl;return!scrollEl||this.unreadDividerTop==null?!1:(scrollEl.scrollTo({top:this.unreadDividerTop,behavior}),!0)}performScrollToEnd(behavior){const list=this.virtualListEl;if(list){list.items.length>0&&list.scrollToIndex(list.items.length-1,{align:"end",behavior});return}const el=this.scrollEl;el&&el.scrollTo({top:el.scrollHeight,behavior})}get totalCount(){const list=this.virtualListEl;return list?list.items.length:this.messageElements.length}get unreadCount(){const unreadStartIndex=this.effectiveUnreadStartIndex;return unreadStartIndex==null?0:Math.max(0,this.totalCount-unreadStartIndex)}pillLabel(){const count=this.unreadCount;if(count<=0)return this.localize("jumpToLatest");const key=getPluralRules(this.effectiveLocale).select(count)==="one"?"newMessageCount":"newMessagesCount";return this.localize(key,void 0,{count:getNumberFormat(this.effectiveLocale).format(count)})}updateUnreadDividerPosition(){const unreadStartIndex=this.effectiveUnreadStartIndex;if(this.virtualListEl||unreadStartIndex==null){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}const content=this.contentEl,target=this.messageElements[unreadStartIndex];if(!target||!content){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}this.syncSemanticUnreadBoundary(target),this.unreadDividerTop=target.getBoundingClientRect().top-content.getBoundingClientRect().top}syncSemanticUnreadBoundary(target){if(!target||this.virtualListEl){this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0;return}const parent=target.parentNode;if(!parent)return;const boundary=this.unreadBoundaryEl??this.ownerDocument.createElement("div");boundary.setAttribute("data-lr-chat-viewport-unread-boundary",""),boundary.setAttribute("role","separator"),boundary.setAttribute("aria-label",this.localize("newMessages"));const targetSlot=target.getAttribute("slot");targetSlot===null?boundary.removeAttribute("slot"):boundary.setAttribute("slot",targetSlot),(boundary.parentNode!==parent||boundary.nextSibling!==target)&&parent.insertBefore(boundary,target),this.unreadBoundaryEl=boundary,this.knownProjectedNodes.add(boundary)}cancelPendingUserIntentExpiry(){const frame=this.pendingUserIntentExpiryFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.pendingUserIntentExpiryFrame=null}clearUserIntent(){this.pendingUserIntent=!1,this.cancelPendingUserIntentExpiry()}consumeUserIntent(){const wasPending=this.pendingUserIntent;return this.clearUserIntent(),wasPending}releaseScrollbarDragListeners(){const owner=this.scrollbarDragWindow;owner&&(owner.removeEventListener("pointerup",this.onPointerUp),owner.removeEventListener("pointercancel",this.onPointerUp),owner.removeEventListener("lostpointercapture",this.onPointerUp),this.scrollbarDragWindow=void 0)}scheduleGrowthTick(){if(this.growthFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{this.growthFrame===frame&&(this.growthFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.updateUnreadDividerPosition(),this.follow&&this.performScrollToEnd("auto")))}),this.growthFrame=frame}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){const politeness=this.live==="polite"||this.live==="assertive"?this.live:void 0;if(!this.isConnected||politeness===void 0){this.releaseAnnouncementSink();return}this.announcementSink?.politeness===politeness&&this.announcementSink.element.ownerDocument===this.ownerDocument||(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink(politeness,{document:this.ownerDocument,source:this}))}announcementTextFor(node){const primary=composedAccessibilityText(node);if(!(node instanceof Element)||!node.shadowRoot)return primary;const content=composedAccessibilityText(node.childNodes),normalizedPrimary=primary.replace(/\s+/g," ").trim(),normalizedContent=content.replace(/\s+/g," ").trim();return!normalizedContent||normalizedPrimary.includes(normalizedContent)?primary:primary?`${primary} ${content}`:content}announceNewProjectedNodes(){const sink=this.announcementSink;for(const node of this.messageElements){if(this.knownProjectedNodes.has(node)||(this.knownProjectedNodes.add(node),!sink||!this.hasUpdated))continue;const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}armObservers(){const owner=this.ownerDocument.defaultView,list=this.virtualListEl,mode=list?"virtual":"slotted";for(const node of this.messageElements)this.knownProjectedNodes.add(node);if(this.observerWindow===owner&&this.armedMode===mode&&(mode==="slotted"||this.listenedVirtualList===list))return;if(this.teardownObservers(),this.observerWindow=owner??void 0,this.armedMode=mode,list)this.listenedVirtualList=list,list.addEventListener("lr-visible-range-changed",this.onVirtualRangeChanged);else{const content=this.contentEl;if(content){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.scheduleGrowthTick()}}),this.contentResizeObserver=observer,this.contentResizeObserver.observe(content)}}const MutationObserverCtor=owner?.MutationObserver;if(MutationObserverCtor){let observer;observer=new MutationObserverCtor(records=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentMutationObserver!==observer||this.onContentMutations(records)}),this.contentMutationObserver=observer,this.contentMutationObserver.observe(this,{childList:!0})}}const scrollEl=this.scrollEl;if(scrollEl){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.scrollResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.follow&&this.performScrollToEnd("auto")}}),this.scrollResizeObserver=observer,this.scrollResizeObserver.observe(scrollEl)}}const generation=++this.armGeneration;queueMicrotask(()=>{!this.isConnected||generation!==this.armGeneration||this.updateUnreadDividerPosition()})}teardownObservers(){this.scrollResizeObserver?.disconnect(),this.scrollResizeObserver=void 0,this.contentResizeObserver?.disconnect(),this.contentResizeObserver=void 0,this.contentMutationObserver?.disconnect(),this.contentMutationObserver=void 0,this.listenedVirtualList?.removeEventListener("lr-visible-range-changed",this.onVirtualRangeChanged),this.listenedVirtualList=void 0,this.observerWindow=void 0,this.armedMode=null,this.armGeneration++;const frame=this.growthFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.growthFrame=null}render(){const label=this.accessibleLabel??(this.label||this.localize("chatViewportLabel")),virtual=this.virtualListEl!==null;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,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{LyraVirtualList}from"../../layout/virtual-list/virtual-list.class.js";import{styles}from"./chat-viewport.styles.js";import{getNumberFormat,getPluralRules}from"../../../internal/intl-cache.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{LYRA_DEFAULT_chatViewportLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_jumpToLatest,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_newMessageCount,LYRA_DEFAULT_newMessages,LYRA_DEFAULT_newMessagesCount,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraChatViewport extends LyraElement{constructor(){super(...arguments),this.follow=!0,this.live="off",this.bottomThreshold=24,this.unreadStartIndex=null,this.label="",this.accessibleLabel=null,this.unreadDividerTop=null,this.pendingUserIntent=!1,this.pendingUserIntentExpiryFrame=null,this.scrollbarDragActive=!1,this.isMounting=!0,this.growthFrame=null,this.armedMode=null,this.armGeneration=0,this.followFocusRepair=null,this.knownProjectedNodes=new WeakSet,this.markUserIntent=()=>{this.pendingUserIntent=!0,this.cancelPendingUserIntentExpiry();const owner=this.ownerDocument.defaultView;if(!owner){this.pendingUserIntent=!1;return}const firstFrame={owner,handle:0};firstFrame.handle=owner.requestAnimationFrame(()=>{if(this.pendingUserIntentExpiryFrame!==firstFrame)return;if(!this.isConnected||this.ownerDocument.defaultView!==owner){this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1;return}const secondFrame={owner,handle:0};secondFrame.handle=owner.requestAnimationFrame(()=>{this.pendingUserIntentExpiryFrame===secondFrame&&(this.pendingUserIntentExpiryFrame=null,this.pendingUserIntent=!1)}),this.pendingUserIntentExpiryFrame=secondFrame}),this.pendingUserIntentExpiryFrame=firstFrame},this.onPointerDown=event=>{const scroll=this.scrollEl;if(!scroll||event.button!==0||event.target!==scroll)return;const computed=getComputedStyle(scroll),borderLeft=Number.parseFloat(computed.borderLeftWidth)||0,borderRight=Number.parseFloat(computed.borderRightWidth)||0,gutter=scroll.offsetWidth-scroll.clientWidth-borderLeft-borderRight;if(gutter<=0)return;const rect=scroll.getBoundingClientRect();if(!(computed.direction==="rtl"?event.clientX<=rect.left+borderLeft+gutter:event.clientX>=rect.right-borderRight-gutter))return;this.scrollbarDragActive=!0;const owner=this.ownerDocument.defaultView;!owner||this.scrollbarDragWindow===owner||(this.releaseScrollbarDragListeners(),this.scrollbarDragWindow=owner,owner.addEventListener("pointerup",this.onPointerUp),owner.addEventListener("pointercancel",this.onPointerUp),owner.addEventListener("lostpointercapture",this.onPointerUp))},this.onPointerUp=()=>{this.scrollbarDragActive=!1,this.releaseScrollbarDragListeners()},this.onKeyDown=e=>{(e.key==="PageUp"||e.key==="ArrowUp"||e.key==="Home")&&this.markUserIntent()},this.onScroll=()=>{const el=this.scrollEl;if(!el)return;if(el.scrollHeight-el.scrollTop-el.clientHeight<=this.effectiveBottomThreshold){this.clearUserIntent(),this.follow||(this.follow=!0);return}(this.consumeUserIntent()||this.scrollbarDragActive)&&this.follow&&(this.follow=!1)},this.onVirtualRangeChanged=e=>{const list=this.virtualListEl;if(!list||e.composedPath()[0]!==list)return;const detail=e.detail;if(!detail||!Number.isFinite(detail.start)||!Number.isFinite(detail.end)||detail.start<0||detail.end<detail.start)return;if(list.items.length>0&&detail.end>=list.items.length-1){this.clearUserIntent(),this.follow||(this.follow=!0);return}if(this.consumeUserIntent()||this.scrollbarDragActive){this.follow&&(this.follow=!1);return}this.follow&&this.performScrollToEnd("auto")},this.onSlotChange=()=>{this.announceNewProjectedNodes();const wasVirtual=this.armedMode==="virtual";this.armObservers(),this.armedMode==="virtual"!==wasVirtual&&this.requestUpdate()},this.onContentMutations=records=>{this.scheduleGrowthTick();const sink=this.announcementSink;if(sink)for(const record of records)for(const node of record.addedNodes){if(this.knownProjectedNodes.has(node)||node instanceof Element&&node.hasAttribute("data-lr-chat-viewport-unread-boundary"))continue;this.knownProjectedNodes.add(node);const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}}static{this.defaultStrings={...super.defaultStrings,chatViewportLabel:LYRA_DEFAULT_chatViewportLabel,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,jumpToLatest:LYRA_DEFAULT_jumpToLatest,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,newMessageCount:LYRA_DEFAULT_newMessageCount,newMessages:LYRA_DEFAULT_newMessages,newMessagesCount:LYRA_DEFAULT_newMessagesCount,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 messageElements(){let elements=this.contentSlot?.assignedElements({flatten:!0})??Array.from(this.children);for(let depth=0;depth<4&&elements.some(element=>element.localName==="slot");depth++)elements=elements.flatMap(element=>element.localName==="slot"?element.assignedElements({flatten:!0}):[element]);return elements.filter(element=>!element.hasAttribute("data-lr-chat-viewport-unread-boundary"))}get virtualListEl(){const children=this.messageElements;return children.length===1&&children[0]instanceof LyraVirtualList?children[0]:null}get effectiveBottomThreshold(){return finiteRange(this.bottomThreshold,24,0)}get effectiveUnreadStartIndex(){return this.unreadStartIndex==null?null:finiteCount(this.unreadStartIndex)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.hasUpdated&&this.armObservers()}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.teardownObservers(),this.releaseScrollbarDragListeners(),this.clearUserIntent(),this.scrollbarDragActive=!1,this.followFocusRepair=null,this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||!changed.has("follow")||!this.follow||changed.get("follow")!==!1)return;const pill=this.renderRoot.querySelector('[part="jump-pill"]');this.followFocusRepair=pill?captureComposedFocusRepair(pill,this.transcriptFocusOwner()):null}firstUpdated(changed){super.firstUpdated(changed),this.armObservers()}updated(changed){super.updated(changed),changed.has("live")&&this.syncAnnouncementSink();const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("follow")){if(this.follow){const behavior=wasMounting?"auto":this.pendingScrollBehavior??(prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth");this.pendingScrollBehavior=void 0,this.performScrollToEnd(behavior)}wasMounting||this.emit("lr-follow-change",{following:this.follow})}changed.has("unreadStartIndex")&&!wasMounting&&this.updateUnreadDividerPosition();const focusRepair=this.followFocusRepair;this.followFocusRepair=null,focusRepair&&applyComposedFocusRepair(focusRepair)}transcriptFocusOwner(){const list=this.virtualListEl;return list?collectComposedFocusTargets(list,{includeRoot:!1,mode:"programmatic"}).elements[0]??null:this.scrollEl??null}scrollToBottom(options){const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth";this.follow?this.performScrollToEnd(behavior):(this.pendingScrollBehavior=behavior,this.follow=!0)}scrollToUnread(options){const unreadStartIndex=this.effectiveUnreadStartIndex;if(unreadStartIndex==null)return!1;const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth",list=this.virtualListEl;if(list)return unreadStartIndex>=list.items.length?!1:(list.scrollToIndex(unreadStartIndex,{align:"start",behavior}),!0);const scrollEl=this.scrollEl;return!scrollEl||this.unreadDividerTop==null?!1:(scrollEl.scrollTo({top:this.unreadDividerTop,behavior}),!0)}performScrollToEnd(behavior){const list=this.virtualListEl;if(list){list.items.length>0&&list.scrollToIndex(list.items.length-1,{align:"end",behavior});return}const el=this.scrollEl;el&&el.scrollTo({top:el.scrollHeight,behavior})}get totalCount(){const list=this.virtualListEl;return list?list.items.length:this.messageElements.length}get unreadCount(){const unreadStartIndex=this.effectiveUnreadStartIndex;return unreadStartIndex==null?0:Math.max(0,this.totalCount-unreadStartIndex)}pillLabel(){const count=this.unreadCount;if(count<=0)return this.localize("jumpToLatest");const key=getPluralRules(this.effectiveLocale).select(count)==="one"?"newMessageCount":"newMessagesCount";return this.localize(key,void 0,{count:getNumberFormat(this.effectiveLocale).format(count)})}updateUnreadDividerPosition(){const unreadStartIndex=this.effectiveUnreadStartIndex;if(this.virtualListEl||unreadStartIndex==null){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}const content=this.contentEl,target=this.messageElements[unreadStartIndex];if(!target||!content){this.unreadDividerTop=null,this.syncSemanticUnreadBoundary();return}this.syncSemanticUnreadBoundary(target),this.unreadDividerTop=target.getBoundingClientRect().top-content.getBoundingClientRect().top}syncSemanticUnreadBoundary(target){if(!target||this.virtualListEl){this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0;return}const parent=target.parentNode;if(!parent)return;const boundary=this.unreadBoundaryEl??this.ownerDocument.createElement("div");boundary.setAttribute("data-lr-chat-viewport-unread-boundary",""),boundary.setAttribute("role","separator"),boundary.setAttribute("aria-label",this.localize("newMessages"));const targetSlot=target.getAttribute("slot");targetSlot===null?boundary.removeAttribute("slot"):boundary.setAttribute("slot",targetSlot),(boundary.parentNode!==parent||boundary.nextSibling!==target)&&parent.insertBefore(boundary,target),this.unreadBoundaryEl=boundary,this.knownProjectedNodes.add(boundary)}cancelPendingUserIntentExpiry(){const frame=this.pendingUserIntentExpiryFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.pendingUserIntentExpiryFrame=null}clearUserIntent(){this.pendingUserIntent=!1,this.cancelPendingUserIntentExpiry()}consumeUserIntent(){const wasPending=this.pendingUserIntent;return this.clearUserIntent(),wasPending}releaseScrollbarDragListeners(){const owner=this.scrollbarDragWindow;owner&&(owner.removeEventListener("pointerup",this.onPointerUp),owner.removeEventListener("pointercancel",this.onPointerUp),owner.removeEventListener("lostpointercapture",this.onPointerUp),this.scrollbarDragWindow=void 0)}scheduleGrowthTick(){if(this.growthFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{this.growthFrame===frame&&(this.growthFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.updateUnreadDividerPosition(),this.follow&&this.performScrollToEnd("auto")))}),this.growthFrame=frame}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){const politeness=this.live==="polite"||this.live==="assertive"?this.live:void 0;if(!this.isConnected||politeness===void 0){this.releaseAnnouncementSink();return}this.announcementSink?.politeness===politeness&&this.announcementSink.element.ownerDocument===this.ownerDocument||(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink(politeness,{document:this.ownerDocument,source:this}))}announcementTextFor(node){const primary=composedAccessibilityText(node);if(!(node instanceof Element)||!node.shadowRoot)return primary;const content=composedAccessibilityText(node.childNodes),normalizedPrimary=primary.replace(/\s+/g," ").trim(),normalizedContent=content.replace(/\s+/g," ").trim();return!normalizedContent||normalizedPrimary.includes(normalizedContent)?primary:primary?`${primary} ${content}`:content}announceNewProjectedNodes(){const sink=this.announcementSink;for(const node of this.messageElements){if(this.knownProjectedNodes.has(node)||(this.knownProjectedNodes.add(node),!sink||!this.hasUpdated))continue;const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}}armObservers(){const owner=this.ownerDocument.defaultView,list=this.virtualListEl,mode=list?"virtual":"slotted";for(const node of this.messageElements)this.knownProjectedNodes.add(node);if(this.observerWindow===owner&&this.armedMode===mode&&(mode==="slotted"||this.listenedVirtualList===list))return;if(this.teardownObservers(),this.observerWindow=owner??void 0,this.armedMode=mode,list)this.listenedVirtualList=list,list.addEventListener("lr-visible-range-changed",this.onVirtualRangeChanged);else{const content=this.contentEl;if(content){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.scheduleGrowthTick()}}),this.contentResizeObserver=observer,this.contentResizeObserver.observe(content)}}const MutationObserverCtor=owner?.MutationObserver;if(MutationObserverCtor){let observer;observer=new MutationObserverCtor(records=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.contentMutationObserver!==observer||this.onContentMutations(records)}),this.contentMutationObserver=observer,this.contentMutationObserver.observe(this,{childList:!0})}}const scrollEl=this.scrollEl;if(scrollEl){let baselineSeen=!1;const ResizeObserverCtor=owner?.ResizeObserver;if(ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{if(!(!this.isConnected||this.ownerDocument.defaultView!==owner||this.scrollResizeObserver!==observer)){if(!baselineSeen){baselineSeen=!0;return}this.follow&&this.performScrollToEnd("auto")}}),this.scrollResizeObserver=observer,this.scrollResizeObserver.observe(scrollEl)}}const generation=++this.armGeneration;queueMicrotask(()=>{!this.isConnected||generation!==this.armGeneration||this.updateUnreadDividerPosition()})}teardownObservers(){this.scrollResizeObserver?.disconnect(),this.scrollResizeObserver=void 0,this.contentResizeObserver?.disconnect(),this.contentResizeObserver=void 0,this.contentMutationObserver?.disconnect(),this.contentMutationObserver=void 0,this.listenedVirtualList?.removeEventListener("lr-visible-range-changed",this.onVirtualRangeChanged),this.listenedVirtualList=void 0,this.observerWindow=void 0,this.armedMode=null,this.armGeneration++;const frame=this.growthFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.growthFrame=null}render(){const label=this.accessibleLabel??(this.label||this.localize("chatViewportLabel")),virtual=this.virtualListEl!==null;return html`
|
|
2
2
|
<div part="base" ?data-virtual=${virtual}>
|
|
3
3
|
<div
|
|
4
4
|
part="scroll"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{styles}from"./generation-metrics.styles.js";import{getNumberFormat,getPluralRules}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_elapsedMinutesSecondsTemplate,LYRA_DEFAULT_generationStatusElapsedSeconds,LYRA_DEFAULT_generationStatusThroughput,LYRA_DEFAULT_generationStatusTokenCount,LYRA_DEFAULT_generationStatusTokensCount,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_stopGenerating}from"../../../internal/default-strings.generated.js";function stopIcon(){return svg`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{styles}from"./generation-metrics.styles.js";import{getNumberFormat,getPluralRules}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_elapsedMinutesSecondsTemplate,LYRA_DEFAULT_generationStatusElapsedSeconds,LYRA_DEFAULT_generationStatusThroughput,LYRA_DEFAULT_generationStatusTokenCount,LYRA_DEFAULT_generationStatusTokensCount,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_stopGenerating}from"../../../internal/default-strings.generated.js";function stopIcon(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -8,7 +8,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
8
8
|
aria-hidden="true"
|
|
9
9
|
focusable="false"
|
|
10
10
|
><rect x="6" y="6" width="12" height="12" rx="1.5"></rect></svg>
|
|
11
|
-
`}function formatElapsed(ms,locale){const totalSeconds=Math.max(0,ms)/1e3;if(totalSeconds<59.95)return{key:"generationStatusElapsedSeconds",values:{seconds:getNumberFormat(locale,{minimumFractionDigits:1,maximumFractionDigits:1}).format(Math.round(totalSeconds*10)/10)}};const wholeSeconds=Math.round(totalSeconds),minutes=Math.floor(wholeSeconds/60),seconds=wholeSeconds%60,numberFormat=getNumberFormat(locale,{maximumFractionDigits:0});return{key:"elapsedMinutesSecondsTemplate",values:{minutes:numberFormat.format(minutes),seconds:numberFormat.format(seconds)}}}function formatTokenCount(count,locale){const rounded=Math.max(0,Math.round(count));return{rounded,formatted:getNumberFormat(locale).format(rounded)}}function formatThroughput(value,locale){const clamped=Math.max(0,value),rounded=clamped<10?Math.round(clamped*10)/10:Math.round(clamped);return getNumberFormat(locale,{maximumFractionDigits:clamped<10?1:0}).format(rounded)}const showStopConverter={fromAttribute(value){return value!=="false"},toAttribute(value){return value?null:"false"}},GENERATION_METRICS_STATUS=literalSetConverter(["idle","running","complete"],"idle");class LyraGenerationMetrics extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,elapsedMinutesSecondsTemplate:LYRA_DEFAULT_elapsedMinutesSecondsTemplate,generationStatusElapsedSeconds:LYRA_DEFAULT_generationStatusElapsedSeconds,generationStatusThroughput:LYRA_DEFAULT_generationStatusThroughput,generationStatusTokenCount:LYRA_DEFAULT_generationStatusTokenCount,generationStatusTokensCount:LYRA_DEFAULT_generationStatusTokensCount,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get status(){return this._status}set status(next){const normalized=GENERATION_METRICS_STATUS.normalize(next),old=this._status;old!==normalized&&(this._status=normalized,this.requestUpdate("status",old))}constructor(){super(),this._status="idle",this.showStop=!0,this.elapsedMs=0,this.tickerGeneration=0,this.onStopClick=()=>{this.emit("lr-stop",null)},this.requestUpdate("status",void 0)}connectedCallback(){super.connectedCallback(),this.status==="running"&&(this.elapsedMs=this.computeElapsedMs(),this.startTicker())}disconnectedCallback(){this.stopTicker(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopTicker(),this.isConnected&&this.status==="running"&&this.startTicker()}willUpdate(changed){super.willUpdate(changed),changed.has("status")?this.status==="running"?(this.validStartedAt==null&&(this.fallbackStartMs=Date.now()),this.elapsedMs=this.computeElapsedMs()):this.status==="idle"&&(this.fallbackStartMs=void 0,this.elapsedMs=0):this.status==="running"&&changed.has("startedAt")&&(this.validStartedAt==null?this.fallbackStartMs=Date.now()-this.elapsedMs:this.fallbackStartMs=void 0,this.elapsedMs=this.computeElapsedMs())}updated(changed){super.updated(changed),changed.has("status")&&(this.status==="running"?this.startTicker():this.stopTicker())}startTicker(){if(this.stopTicker(),!this.isConnected||this.status!=="running")return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;const generation=this.tickerGeneration,handle=ownerWindow.setInterval(()=>{this.tickTimer!==handle||this.tickTimerOwner!==ownerWindow||this.tickTimerDocument!==ownerDocument||this.tickerGeneration!==generation||!this.isConnected||this.status!=="running"||this.ownerDocument!==ownerDocument||(this.elapsedMs=this.computeElapsedMs())},1e3);this.tickTimer=handle,this.tickTimerOwner=ownerWindow,this.tickTimerDocument=ownerDocument}stopTicker(){this.tickerGeneration+=1,this.tickTimer!==void 0&&this.tickTimerOwner?.clearInterval(this.tickTimer),this.tickTimer=void 0,this.tickTimerOwner=void 0,this.tickTimerDocument=void 0}get validStartedAt(){if(!(this.startedAt==null||!Number.isFinite(this.startedAt)))return finiteRange(this.startedAt,this.startedAt,0)}computeElapsedMs(){const start=this.validStartedAt??this.fallbackStartMs;return start==null?0:Math.max(0,Date.now()-start)}get validTokenCount(){if(!(this.tokenCount==null||!Number.isFinite(this.tokenCount)))return finiteCount(Math.round(this.tokenCount))}get effectiveTokensPerSecond(){if(this.tokensPerSecond!=null&&Number.isFinite(this.tokensPerSecond))return finiteRange(this.tokensPerSecond,this.tokensPerSecond,0);const tokenCount=this.validTokenCount;if(tokenCount!==void 0){const elapsedSeconds=this.elapsedMs/1e3;if(elapsedSeconds>=1)return tokenCount/elapsedSeconds}}render(){const validTokenCount=this.validTokenCount,hasTokens=validTokenCount!==void 0,throughput=this.effectiveTokensPerSecond,hasThroughput=throughput!==void 0,locale=this.effectiveLocale,elapsed=formatElapsed(this.elapsedMs,locale),tokenCount=hasTokens?formatTokenCount(validTokenCount,locale):void 0,tokenMessageKey=tokenCount&&getPluralRules(locale).select(tokenCount.rounded)==="one"?"generationStatusTokenCount":"generationStatusTokensCount";return html`
|
|
11
|
+
`}function formatElapsed(ms,locale){const totalSeconds=Math.max(0,ms)/1e3;if(totalSeconds<59.95)return{key:"generationStatusElapsedSeconds",values:{seconds:getNumberFormat(locale,{minimumFractionDigits:1,maximumFractionDigits:1}).format(Math.round(totalSeconds*10)/10)}};const wholeSeconds=Math.round(totalSeconds),minutes=Math.floor(wholeSeconds/60),seconds=wholeSeconds%60,numberFormat=getNumberFormat(locale,{maximumFractionDigits:0});return{key:"elapsedMinutesSecondsTemplate",values:{minutes:numberFormat.format(minutes),seconds:numberFormat.format(seconds)}}}function formatTokenCount(count,locale){const rounded=Math.max(0,Math.round(count));return{rounded,formatted:getNumberFormat(locale).format(rounded)}}function formatThroughput(value,locale){const clamped=Math.max(0,value),rounded=clamped<10?Math.round(clamped*10)/10:Math.round(clamped);return getNumberFormat(locale,{maximumFractionDigits:clamped<10?1:0}).format(rounded)}const showStopConverter={fromAttribute(value){return value!=="false"},toAttribute(value){return value?null:"false"}},GENERATION_METRICS_STATUS=literalSetConverter(["idle","running","complete"],"idle");class LyraGenerationMetrics extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,elapsedMinutesSecondsTemplate:LYRA_DEFAULT_elapsedMinutesSecondsTemplate,generationStatusElapsedSeconds:LYRA_DEFAULT_generationStatusElapsedSeconds,generationStatusThroughput:LYRA_DEFAULT_generationStatusThroughput,generationStatusTokenCount:LYRA_DEFAULT_generationStatusTokenCount,generationStatusTokensCount:LYRA_DEFAULT_generationStatusTokensCount,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,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get status(){return this._status}set status(next){const normalized=GENERATION_METRICS_STATUS.normalize(next),old=this._status;old!==normalized&&(this._status=normalized,this.requestUpdate("status",old))}constructor(){super(),this._status="idle",this.showStop=!0,this.elapsedMs=0,this.tickerGeneration=0,this.onStopClick=()=>{this.emit("lr-stop",null)},this.requestUpdate("status",void 0)}connectedCallback(){super.connectedCallback(),this.status==="running"&&(this.elapsedMs=this.computeElapsedMs(),this.startTicker())}disconnectedCallback(){this.stopTicker(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.stopTicker(),this.isConnected&&this.status==="running"&&this.startTicker()}willUpdate(changed){super.willUpdate(changed),changed.has("status")?this.status==="running"?(this.validStartedAt==null&&(this.fallbackStartMs=Date.now()),this.elapsedMs=this.computeElapsedMs()):this.status==="idle"&&(this.fallbackStartMs=void 0,this.elapsedMs=0):this.status==="running"&&changed.has("startedAt")&&(this.validStartedAt==null?this.fallbackStartMs=Date.now()-this.elapsedMs:this.fallbackStartMs=void 0,this.elapsedMs=this.computeElapsedMs())}updated(changed){super.updated(changed),changed.has("status")&&(this.status==="running"?this.startTicker():this.stopTicker())}startTicker(){if(this.stopTicker(),!this.isConnected||this.status!=="running")return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;const generation=this.tickerGeneration,handle=ownerWindow.setInterval(()=>{this.tickTimer!==handle||this.tickTimerOwner!==ownerWindow||this.tickTimerDocument!==ownerDocument||this.tickerGeneration!==generation||!this.isConnected||this.status!=="running"||this.ownerDocument!==ownerDocument||(this.elapsedMs=this.computeElapsedMs())},1e3);this.tickTimer=handle,this.tickTimerOwner=ownerWindow,this.tickTimerDocument=ownerDocument}stopTicker(){this.tickerGeneration+=1,this.tickTimer!==void 0&&this.tickTimerOwner?.clearInterval(this.tickTimer),this.tickTimer=void 0,this.tickTimerOwner=void 0,this.tickTimerDocument=void 0}get validStartedAt(){if(!(this.startedAt==null||!Number.isFinite(this.startedAt)))return finiteRange(this.startedAt,this.startedAt,0)}computeElapsedMs(){const start=this.validStartedAt??this.fallbackStartMs;return start==null?0:Math.max(0,Date.now()-start)}get validTokenCount(){if(!(this.tokenCount==null||!Number.isFinite(this.tokenCount)))return finiteCount(Math.round(this.tokenCount))}get effectiveTokensPerSecond(){if(this.tokensPerSecond!=null&&Number.isFinite(this.tokensPerSecond))return finiteRange(this.tokensPerSecond,this.tokensPerSecond,0);const tokenCount=this.validTokenCount;if(tokenCount!==void 0){const elapsedSeconds=this.elapsedMs/1e3;if(elapsedSeconds>=1)return tokenCount/elapsedSeconds}}render(){const validTokenCount=this.validTokenCount,hasTokens=validTokenCount!==void 0,throughput=this.effectiveTokensPerSecond,hasThroughput=throughput!==void 0,locale=this.effectiveLocale,elapsed=formatElapsed(this.elapsedMs,locale),tokenCount=hasTokens?formatTokenCount(validTokenCount,locale):void 0,tokenMessageKey=tokenCount&&getPluralRules(locale).select(tokenCount.rounded)==="one"?"generationStatusTokenCount":"generationStatusTokensCount";return html`
|
|
12
12
|
<div part="base">
|
|
13
13
|
<span part="elapsed">${this.localize(elapsed.key,void 0,elapsed.values)}</span>
|
|
14
14
|
${hasTokens?html`<span part="tokens"
|
|
@@ -3,7 +3,7 @@ import{css}from"lit";const styles=css`
|
|
|
3
3
|
[part='base'] { display: flex; flex-direction: column; gap: var(--lr-space-m); }
|
|
4
4
|
[part='header'] { display: grid; grid-template-columns: auto minmax(var(--lr-size-8rem), 1fr) auto; gap: var(--lr-space-s); align-items: center; }
|
|
5
5
|
[part='activity'] { min-inline-size: 0; }
|
|
6
|
-
[part='status'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap:
|
|
6
|
+
[part='status'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: break-word; }
|
|
7
7
|
[part='controls'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); }
|
|
8
8
|
[part='controls'] button {
|
|
9
9
|
min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border);
|
|
@@ -138,6 +138,15 @@ import{css}from"lit";const styles=css`
|
|
|
138
138
|
lr-virtual-list::part(row-actions) {
|
|
139
139
|
min-inline-size: 0;
|
|
140
140
|
}
|
|
141
|
+
/* row-start/row-actions (see thread-list.class.ts) are plain <span>s, so they default to
|
|
142
|
+
display: inline -- an ordinary text baseline box with descender strut height. Their
|
|
143
|
+
content is adornments (icon/avatar, action buttons), not text, so center them on a flex
|
|
144
|
+
line instead; row-content/row-meta hold real text and keep their own inline/block flow. */
|
|
145
|
+
lr-virtual-list::part(row-start),
|
|
146
|
+
lr-virtual-list::part(row-actions) {
|
|
147
|
+
display: inline-flex;
|
|
148
|
+
align-items: center;
|
|
149
|
+
}
|
|
141
150
|
lr-virtual-list::part(row-action) {
|
|
142
151
|
display: inline-flex;
|
|
143
152
|
align-items: center;
|
|
@@ -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,srOnly}from"../../../internal/a11y.js";import{place}from"../../../internal/positioner.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./usage-badge.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{durationMessageValue}from"../../../internal/duration.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_usageBadgeCostLabel,LYRA_DEFAULT_usageBadgeLabel,LYRA_DEFAULT_usageBadgeLatencyLabel,LYRA_DEFAULT_usageBadgeTokensIn,LYRA_DEFAULT_usageBadgeTokensInLabel,LYRA_DEFAULT_usageBadgeTokensOut,LYRA_DEFAULT_usageBadgeTokensOutLabel,LYRA_DEFAULT_usageBadgeTotalTokensLabel}from"../../../internal/default-strings.generated.js";class LyraUsageBadge extends LyraElement{constructor(){super(...arguments),this.costText="",this.summary="",this.abbreviate=!1,this.tooltipOpen=!1,this.hasDetailsSlot=!1,this.hasSummarySlot=!1,this.detailsText="",this.tooltipId=nextId("usage-badge-tooltip"),this.hovering=!1,this.focused=!1,this.onDetailsSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.hasDetailsSlot=assigned.length>0,this.detailsText=assigned.slice(0,64).map(element=>{const renderedText=element.innerText;return typeof renderedText=="string"?renderedText:element.textContent??""}).join(" ").replace(/\s+/g," ").trim().slice(0,4096),this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onSummarySlotChange=e=>{this.hasSummarySlot=e.target.assignedElements({flatten:!0}).length>0,this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onMouseEnter=()=>{this.hovering=!0,this.showTooltip()},this.onMouseLeave=()=>{this.hovering=!1,!this.focused&&this.hideTooltip()},this.onFocus=()=>{this.focused=!0,this.showTooltip()},this.onBlur=()=>{this.focused=!1,!this.hovering&&this.hideTooltip()},this.onKeyDown=e=>{e.key==="Escape"&&this.tooltipOpen&&(e.stopPropagation(),this.hideTooltip())}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,usageBadgeCostLabel:LYRA_DEFAULT_usageBadgeCostLabel,usageBadgeLabel:LYRA_DEFAULT_usageBadgeLabel,usageBadgeLatencyLabel:LYRA_DEFAULT_usageBadgeLatencyLabel,usageBadgeTokensIn:LYRA_DEFAULT_usageBadgeTokensIn,usageBadgeTokensInLabel:LYRA_DEFAULT_usageBadgeTokensInLabel,usageBadgeTokensOut:LYRA_DEFAULT_usageBadgeTokensOut,usageBadgeTokensOutLabel:LYRA_DEFAULT_usageBadgeTokensOutLabel,usageBadgeTotalTokensLabel:LYRA_DEFAULT_usageBadgeTotalTokensLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{const children=Array.from(this.children);this.hasDetailsSlot=children.some(child=>child.getAttribute("slot")==="details"),this.hasSummarySlot=children.some(child=>child.getAttribute("slot")==="summary")}),this.hasUpdated&&(changed.has("tokensIn")||changed.has("tokensOut")||changed.has("costText")||changed.has("latencyMs")||changed.has("summary"))&&!this.hasInteractiveTooltip&&this.closeTooltipLifecycle()}updated(changed){if(super.updated(changed),changed.has("tooltipOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen)){const anchor=this.renderRoot.querySelector('[part="base"]'),tooltip=this.renderRoot.querySelector('[part="tooltip"]');anchor&&tooltip&&(this.cleanupPositioner=place(anchor,tooltip,{placement:"top-start"}))}}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen=!1,this.hovering=!1,this.focused=!1}get hasTokensIn(){return this.tokensIn!=null&&Number.isFinite(this.tokensIn)}get hasTokensOut(){return this.tokensOut!=null&&Number.isFinite(this.tokensOut)}get hasCost(){return this.costText.length>0}get validLatencyMs(){if(!(this.latencyMs==null||!Number.isFinite(this.latencyMs)))return finiteRange(this.latencyMs,this.latencyMs,0)}get hasLatency(){return this.validLatencyMs!==void 0}get hasVisibleContent(){return this.hasTokensIn||this.hasTokensOut||this.hasCost||this.hasLatency}get hasVisibleSummary(){return this.summary.length>0||this.hasSummarySlot}get hasDisplayContent(){return this.hasVisibleContent||this.hasVisibleSummary}get hasTooltipContent(){return this.hasVisibleContent||this.hasDetailsSlot}get hasInteractiveTooltip(){return this.hasDisplayContent&&this.hasTooltipContent}formatTokenCount(n){return getNumberFormat(this.effectiveLocale,this.abbreviate?{notation:"compact"}:{}).format(n)}formatTokenCountFull(n){return getNumberFormat(this.effectiveLocale).format(n)}localizedDuration(ms){if(this.formatLatency)return this.formatLatency(ms);const duration=durationMessageValue(ms),value=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:duration.key==="durationMilliseconds"?0:1}).format(duration.value);return this.localize(duration.key,void 0,{value})}showTooltip(){!this.hasInteractiveTooltip||this.tooltipOpen||(this.tooltipOpen=!0)}hideTooltip(){this.tooltipOpen&&(this.tooltipOpen=!1)}closeTooltipLifecycle(){this.tooltipOpen=!1,this.hovering=!1,this.focused=!1,this.cleanupPositioner?.(),this.cleanupPositioner=void 0}render(){const interactive=this.hasInteractiveTooltip,tokensIn=this.hasTokensIn?finiteCount(this.tokensIn):void 0,tokensOut=this.hasTokensOut?finiteCount(this.tokensOut):void 0,hasBoth=tokensIn!==void 0&&tokensOut!==void 0;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,srOnly}from"../../../internal/a11y.js";import{place}from"../../../internal/positioner.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./usage-badge.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{durationMessageValue}from"../../../internal/duration.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut,LYRA_DEFAULT_usageBadgeCostLabel,LYRA_DEFAULT_usageBadgeLabel,LYRA_DEFAULT_usageBadgeLatencyLabel,LYRA_DEFAULT_usageBadgeTokensIn,LYRA_DEFAULT_usageBadgeTokensInLabel,LYRA_DEFAULT_usageBadgeTokensOut,LYRA_DEFAULT_usageBadgeTokensOutLabel,LYRA_DEFAULT_usageBadgeTotalTokensLabel}from"../../../internal/default-strings.generated.js";class LyraUsageBadge extends LyraElement{constructor(){super(...arguments),this.costText="",this.summary="",this.abbreviate=!1,this.tooltipOpen=!1,this.hasDetailsSlot=!1,this.hasSummarySlot=!1,this.detailsText="",this.tooltipId=nextId("usage-badge-tooltip"),this.hovering=!1,this.focused=!1,this.onDetailsSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.hasDetailsSlot=assigned.length>0,this.detailsText=assigned.slice(0,64).map(element=>{const renderedText=element.innerText;return typeof renderedText=="string"?renderedText:element.textContent??""}).join(" ").replace(/\s+/g," ").trim().slice(0,4096),this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onSummarySlotChange=e=>{this.hasSummarySlot=e.target.assignedElements({flatten:!0}).length>0,this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onMouseEnter=()=>{this.hovering=!0,this.showTooltip()},this.onMouseLeave=()=>{this.hovering=!1,!this.focused&&this.hideTooltip()},this.onFocus=()=>{this.focused=!0,this.showTooltip()},this.onBlur=()=>{this.focused=!1,!this.hovering&&this.hideTooltip()},this.onKeyDown=e=>{e.key==="Escape"&&this.tooltipOpen&&(e.stopPropagation(),this.hideTooltip())}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,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,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut,usageBadgeCostLabel:LYRA_DEFAULT_usageBadgeCostLabel,usageBadgeLabel:LYRA_DEFAULT_usageBadgeLabel,usageBadgeLatencyLabel:LYRA_DEFAULT_usageBadgeLatencyLabel,usageBadgeTokensIn:LYRA_DEFAULT_usageBadgeTokensIn,usageBadgeTokensInLabel:LYRA_DEFAULT_usageBadgeTokensInLabel,usageBadgeTokensOut:LYRA_DEFAULT_usageBadgeTokensOut,usageBadgeTokensOutLabel:LYRA_DEFAULT_usageBadgeTokensOutLabel,usageBadgeTotalTokensLabel:LYRA_DEFAULT_usageBadgeTotalTokensLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{const children=Array.from(this.children);this.hasDetailsSlot=children.some(child=>child.getAttribute("slot")==="details"),this.hasSummarySlot=children.some(child=>child.getAttribute("slot")==="summary")}),this.hasUpdated&&(changed.has("tokensIn")||changed.has("tokensOut")||changed.has("costText")||changed.has("latencyMs")||changed.has("summary"))&&!this.hasInteractiveTooltip&&this.closeTooltipLifecycle()}updated(changed){if(super.updated(changed),changed.has("tooltipOpen")&&(this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen)){const anchor=this.renderRoot.querySelector('[part="base"]'),tooltip=this.renderRoot.querySelector('[part="tooltip"]');anchor&&tooltip&&(this.cleanupPositioner=place(anchor,tooltip,{placement:"top-start"}))}}disconnectedCallback(){super.disconnectedCallback(),this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.tooltipOpen=!1,this.hovering=!1,this.focused=!1}get hasTokensIn(){return this.tokensIn!=null&&Number.isFinite(this.tokensIn)}get hasTokensOut(){return this.tokensOut!=null&&Number.isFinite(this.tokensOut)}get hasCost(){return this.costText.length>0}get validLatencyMs(){if(!(this.latencyMs==null||!Number.isFinite(this.latencyMs)))return finiteRange(this.latencyMs,this.latencyMs,0)}get hasLatency(){return this.validLatencyMs!==void 0}get hasVisibleContent(){return this.hasTokensIn||this.hasTokensOut||this.hasCost||this.hasLatency}get hasVisibleSummary(){return this.summary.length>0||this.hasSummarySlot}get hasDisplayContent(){return this.hasVisibleContent||this.hasVisibleSummary}get hasTooltipContent(){return this.hasVisibleContent||this.hasDetailsSlot}get hasInteractiveTooltip(){return this.hasDisplayContent&&this.hasTooltipContent}formatTokenCount(n){return getNumberFormat(this.effectiveLocale,this.abbreviate?{notation:"compact"}:{}).format(n)}formatTokenCountFull(n){return getNumberFormat(this.effectiveLocale).format(n)}localizedDuration(ms){if(this.formatLatency)return this.formatLatency(ms);const duration=durationMessageValue(ms),value=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:duration.key==="durationMilliseconds"?0:1}).format(duration.value);return this.localize(duration.key,void 0,{value})}showTooltip(){!this.hasInteractiveTooltip||this.tooltipOpen||(this.tooltipOpen=!0)}hideTooltip(){this.tooltipOpen&&(this.tooltipOpen=!1)}closeTooltipLifecycle(){this.tooltipOpen=!1,this.hovering=!1,this.focused=!1,this.cleanupPositioner?.(),this.cleanupPositioner=void 0}render(){const interactive=this.hasInteractiveTooltip,tokensIn=this.hasTokensIn?finiteCount(this.tokensIn):void 0,tokensOut=this.hasTokensOut?finiteCount(this.tokensOut):void 0,hasBoth=tokensIn!==void 0&&tokensOut!==void 0;return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
role=${interactive?"group":nothing}
|
|
@@ -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}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{styles}from"./file-tree.styles.js";import{LyraTreeItem}from"../tree/tree-item.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileTreeDiffSummary,LYRA_DEFAULT_fileTreeLabel,LYRA_DEFAULT_gitStatusAdded,LYRA_DEFAULT_gitStatusConflicted,LYRA_DEFAULT_gitStatusDeleted,LYRA_DEFAULT_gitStatusIgnored,LYRA_DEFAULT_gitStatusModified,LYRA_DEFAULT_gitStatusRenamed,LYRA_DEFAULT_gitStatusUntracked,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_FILE_TREE_NODES=1e4,MAX_FILE_TREE_DEPTH=64,GIT_STATUSES=new Set(["added","modified","deleted","renamed","untracked","conflicted","ignored"]);function boundedArrayShape(value){try{if(!Array.isArray(value))return{isArray:!1,length:0};const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return{isArray:!0,length:typeof length=="number"&&Number.isSafeInteger(length)&&length>=0?Math.min(length,MAX_FILE_TREE_NODES):0}}catch{return{isArray:!1,length:0}}}function normalizeFileTreeNodes(value){const rootShape=boundedArrayShape(value),roots=rootShape.isArray?value:[],drafts=[],rootDrafts=[],seenObjects=new WeakSet,seenPaths=new Set,stack=[{input:roots,output:rootDrafts,depth:0,index:0,length:rootShape.length}];let inspected=0;for(;stack.length>0&&drafts.length<MAX_FILE_TREE_NODES&&inspected<MAX_FILE_TREE_NODES;){const frame=stack[stack.length-1];if(frame.index>=frame.length){stack.pop();continue}const sourceIndex=frame.index++;inspected+=1;let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(frame.input,String(sourceIndex))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const candidate=descriptor.value;if(!(typeof candidate!="object"||candidate===null||seenObjects.has(candidate))){seenObjects.add(candidate);try{const record=candidate,path=record.path;if(typeof path!="string"||path.trim().length===0||seenPaths.has(path))continue;seenPaths.add(path);const name=record.name,kind=record.kind,mimeType=record.mimeType,gitStatus=record.gitStatus,additions=record.additions,deletions=record.deletions,hasChildren=record.hasChildren,rawChildren=record.children,fields={path,...typeof name=="string"?{name}:{},...kind==="file"||kind==="directory"?{kind}:{},...typeof mimeType=="string"?{mimeType}:{},...typeof gitStatus=="string"&&GIT_STATUSES.has(gitStatus)?{gitStatus}:{},...additions===void 0?{}:{additions:finiteCount(typeof additions=="number"?additions:0)},...deletions===void 0?{}:{deletions:finiteCount(typeof deletions=="number"?deletions:0)},...hasChildren===void 0?{}:{hasChildren:!!hasChildren}},childShape=boundedArrayShape(rawChildren),childrenProvided=childShape.isArray,draft={fields,children:[],childrenProvided};frame.output.push(draft),drafts.push(draft),childrenProvided&&frame.depth<MAX_FILE_TREE_DEPTH&&stack.push({input:rawChildren,output:draft.children,depth:frame.depth+1,index:0,length:childShape.length})}catch{}}}for(let index=drafts.length-1;index>=0;index--){const draft=drafts[index];draft.normalized=Object.freeze({...draft.fields,...draft.childrenProvided?{children:Object.freeze(draft.children.map(child=>child.normalized))}:{}})}return Object.freeze(rootDrafts.map(draft=>draft.normalized))}const GIT_STATUS_LETTER={added:"A",modified:"M",deleted:"D",renamed:"R",untracked:"U",conflicted:"C",ignored:"!"},GIT_STATUS_TONE={added:"success",untracked:"success",modified:"brand",renamed:"brand",deleted:"danger",conflicted:"danger",ignored:"neutral"},GIT_STATUS_KEY={added:"gitStatusAdded",modified:"gitStatusModified",deleted:"gitStatusDeleted",renamed:"gitStatusRenamed",untracked:"gitStatusUntracked",conflicted:"gitStatusConflicted",ignored:"gitStatusIgnored"};function baseName(path){const segments=path.split("/").filter(Boolean);return segments[segments.length-1]??path}function isDirectory(node){return node.kind==="directory"||node.children!==void 0||node.hasChildren===!0}function isLazyUnloaded(node){return isDirectory(node)&&node.hasChildren===!0&&node.children===void 0}class LyraFileTree extends LyraElement{constructor(){super(...arguments),this._nodes=[],this.selectedPath=null,this.nodesByPath=new Map,this.parentPathByPath=new Map,this.onNodeSelect=e=>{e.stopPropagation();const{nodeId}=e.detail,node=this.nodesByPath.get(nodeId);if(!node)return;const wasSelected=this.selectedPath===nodeId;this.selectedPath=nodeId,this.emit("lr-file-select",Object.freeze({filePath:nodeId,node})),!isDirectory(node)&&wasSelected&&this.emit("lr-file-open",Object.freeze({filePath:nodeId,node}))},this.onNodeToggle=e=>{e.stopPropagation();const{nodeId,expanded}=e.detail;if(!expanded)return;const node=this.nodesByPath.get(nodeId);node&&isLazyUnloaded(node)&&this.emit("lr-load-children",Object.freeze({filePath:nodeId}))}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileTreeDiffSummary:LYRA_DEFAULT_fileTreeDiffSummary,fileTreeLabel:LYRA_DEFAULT_fileTreeLabel,gitStatusAdded:LYRA_DEFAULT_gitStatusAdded,gitStatusConflicted:LYRA_DEFAULT_gitStatusConflicted,gitStatusDeleted:LYRA_DEFAULT_gitStatusDeleted,gitStatusIgnored:LYRA_DEFAULT_gitStatusIgnored,gitStatusModified:LYRA_DEFAULT_gitStatusModified,gitStatusRenamed:LYRA_DEFAULT_gitStatusRenamed,gitStatusUntracked:LYRA_DEFAULT_gitStatusUntracked,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get nodes(){return this._nodes}set nodes(value){const previous=this._nodes;this._nodes=normalizeFileTreeNodes(value),this.requestUpdate("nodes",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("nodes")){this.nodesByPath=new Map,this.parentPathByPath=new Map;const stack=[...this.nodes].reverse().map(node=>({node,parentPath:void 0}));for(;stack.length>0;){const{node,parentPath}=stack.pop();if(this.nodesByPath.set(node.path,node),parentPath!==void 0&&this.parentPathByPath.set(node.path,parentPath),node.children)for(let index=node.children.length-1;index>=0;index--)stack.push({node:node.children[index],parentPath:node.path})}}}toTreeItem(node){const badges=[];node.gitStatus&&badges.push({text:GIT_STATUS_LETTER[node.gitStatus],tone:GIT_STATUS_TONE[node.gitStatus],label:this.localize(GIT_STATUS_KEY[node.gitStatus])});const description=node.additions!==void 0||node.deletions!==void 0?this.localize("fileTreeDiffSummary",void 0,{additions:getNumberFormat(this.effectiveLocale).format(node.additions??0),deletions:getNumberFormat(this.effectiveLocale).format(node.deletions??0)}):void 0;let children;return isLazyUnloaded(node)?children=[{id:`${node.path} loading`,label:this.localize("loading"),disabled:!0}]:node.children&&(children=node.children.map(c=>this.toTreeItem(c))),{id:node.path,label:node.name??baseName(node.path),selected:this.selectedPath===node.path,children,badges:badges.length>0?badges:void 0,description,icon:isDirectory(node)?void 0:html`<lr-file-icon
|
|
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}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{tag}from"../../../internal/prefix.js";import{styles}from"./file-tree.styles.js";import{LyraTreeItem}from"../tree/tree-item.class.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileTreeDiffSummary,LYRA_DEFAULT_fileTreeLabel,LYRA_DEFAULT_gitStatusAdded,LYRA_DEFAULT_gitStatusConflicted,LYRA_DEFAULT_gitStatusDeleted,LYRA_DEFAULT_gitStatusIgnored,LYRA_DEFAULT_gitStatusModified,LYRA_DEFAULT_gitStatusRenamed,LYRA_DEFAULT_gitStatusUntracked,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_FILE_TREE_NODES=1e4,MAX_FILE_TREE_DEPTH=64,GIT_STATUSES=new Set(["added","modified","deleted","renamed","untracked","conflicted","ignored"]);function boundedArrayShape(value){try{if(!Array.isArray(value))return{isArray:!1,length:0};const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return{isArray:!0,length:typeof length=="number"&&Number.isSafeInteger(length)&&length>=0?Math.min(length,MAX_FILE_TREE_NODES):0}}catch{return{isArray:!1,length:0}}}function normalizeFileTreeNodes(value){const rootShape=boundedArrayShape(value),roots=rootShape.isArray?value:[],drafts=[],rootDrafts=[],seenObjects=new WeakSet,seenPaths=new Set,stack=[{input:roots,output:rootDrafts,depth:0,index:0,length:rootShape.length}];let inspected=0;for(;stack.length>0&&drafts.length<MAX_FILE_TREE_NODES&&inspected<MAX_FILE_TREE_NODES;){const frame=stack[stack.length-1];if(frame.index>=frame.length){stack.pop();continue}const sourceIndex=frame.index++;inspected+=1;let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(frame.input,String(sourceIndex))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const candidate=descriptor.value;if(!(typeof candidate!="object"||candidate===null||seenObjects.has(candidate))){seenObjects.add(candidate);try{const record=candidate,path=record.path;if(typeof path!="string"||path.trim().length===0||seenPaths.has(path))continue;seenPaths.add(path);const name=record.name,kind=record.kind,mimeType=record.mimeType,gitStatus=record.gitStatus,additions=record.additions,deletions=record.deletions,hasChildren=record.hasChildren,rawChildren=record.children,fields={path,...typeof name=="string"?{name}:{},...kind==="file"||kind==="directory"?{kind}:{},...typeof mimeType=="string"?{mimeType}:{},...typeof gitStatus=="string"&&GIT_STATUSES.has(gitStatus)?{gitStatus}:{},...additions===void 0?{}:{additions:finiteCount(typeof additions=="number"?additions:0)},...deletions===void 0?{}:{deletions:finiteCount(typeof deletions=="number"?deletions:0)},...hasChildren===void 0?{}:{hasChildren:!!hasChildren}},childShape=boundedArrayShape(rawChildren),childrenProvided=childShape.isArray,draft={fields,children:[],childrenProvided};frame.output.push(draft),drafts.push(draft),childrenProvided&&frame.depth<MAX_FILE_TREE_DEPTH&&stack.push({input:rawChildren,output:draft.children,depth:frame.depth+1,index:0,length:childShape.length})}catch{}}}for(let index=drafts.length-1;index>=0;index--){const draft=drafts[index];draft.normalized=Object.freeze({...draft.fields,...draft.childrenProvided?{children:Object.freeze(draft.children.map(child=>child.normalized))}:{}})}return Object.freeze(rootDrafts.map(draft=>draft.normalized))}const GIT_STATUS_LETTER={added:"A",modified:"M",deleted:"D",renamed:"R",untracked:"U",conflicted:"C",ignored:"!"},GIT_STATUS_TONE={added:"success",untracked:"success",modified:"brand",renamed:"brand",deleted:"danger",conflicted:"danger",ignored:"neutral"},GIT_STATUS_KEY={added:"gitStatusAdded",modified:"gitStatusModified",deleted:"gitStatusDeleted",renamed:"gitStatusRenamed",untracked:"gitStatusUntracked",conflicted:"gitStatusConflicted",ignored:"gitStatusIgnored"};function baseName(path){const segments=path.split("/").filter(Boolean);return segments[segments.length-1]??path}function isDirectory(node){return node.kind==="directory"||node.children!==void 0||node.hasChildren===!0}function isLazyUnloaded(node){return isDirectory(node)&&node.hasChildren===!0&&node.children===void 0}class LyraFileTree extends LyraElement{constructor(){super(...arguments),this._nodes=[],this.selectedPath=null,this.nodesByPath=new Map,this.parentPathByPath=new Map,this.onNodeSelect=e=>{e.stopPropagation();const{nodeId}=e.detail,node=this.nodesByPath.get(nodeId);if(!node)return;const wasSelected=this.selectedPath===nodeId;this.selectedPath=nodeId,this.emit("lr-file-select",Object.freeze({filePath:nodeId,node})),!isDirectory(node)&&wasSelected&&this.emit("lr-file-open",Object.freeze({filePath:nodeId,node}))},this.onNodeToggle=e=>{e.stopPropagation();const{nodeId,expanded}=e.detail;if(!expanded)return;const node=this.nodesByPath.get(nodeId);node&&isLazyUnloaded(node)&&this.emit("lr-load-children",Object.freeze({filePath:nodeId}))}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileTreeDiffSummary:LYRA_DEFAULT_fileTreeDiffSummary,fileTreeLabel:LYRA_DEFAULT_fileTreeLabel,gitStatusAdded:LYRA_DEFAULT_gitStatusAdded,gitStatusConflicted:LYRA_DEFAULT_gitStatusConflicted,gitStatusDeleted:LYRA_DEFAULT_gitStatusDeleted,gitStatusIgnored:LYRA_DEFAULT_gitStatusIgnored,gitStatusModified:LYRA_DEFAULT_gitStatusModified,gitStatusRenamed:LYRA_DEFAULT_gitStatusRenamed,gitStatusUntracked:LYRA_DEFAULT_gitStatusUntracked,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get nodes(){return this._nodes}set nodes(value){const previous=this._nodes;this._nodes=normalizeFileTreeNodes(value),this.requestUpdate("nodes",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("nodes")){this.nodesByPath=new Map,this.parentPathByPath=new Map;const stack=[...this.nodes].reverse().map(node=>({node,parentPath:void 0}));for(;stack.length>0;){const{node,parentPath}=stack.pop();if(this.nodesByPath.set(node.path,node),parentPath!==void 0&&this.parentPathByPath.set(node.path,parentPath),node.children)for(let index=node.children.length-1;index>=0;index--)stack.push({node:node.children[index],parentPath:node.path})}}}toTreeItem(node){const badges=[];node.gitStatus&&badges.push({text:GIT_STATUS_LETTER[node.gitStatus],tone:GIT_STATUS_TONE[node.gitStatus],label:this.localize(GIT_STATUS_KEY[node.gitStatus])});const description=node.additions!==void 0||node.deletions!==void 0?this.localize("fileTreeDiffSummary",void 0,{additions:getNumberFormat(this.effectiveLocale).format(node.additions??0),deletions:getNumberFormat(this.effectiveLocale).format(node.deletions??0)}):void 0;let children;return isLazyUnloaded(node)?children=[{id:`${node.path} loading`,label:this.localize("loading"),disabled:!0}]:node.children&&(children=node.children.map(c=>this.toTreeItem(c))),{id:node.path,label:node.name??baseName(node.path),selected:this.selectedPath===node.path,children,badges:badges.length>0?badges:void 0,description,icon:isDirectory(node)?void 0:html`<lr-file-icon
|
|
2
2
|
mime-type=${node.mimeType??""}
|
|
3
3
|
name=${node.name??baseName(node.path)}
|
|
4
4
|
decorative
|
|
@@ -410,7 +410,7 @@ export declare class LyraHeatmap extends LyraElement<LyraHeatmapEventMap> {
|
|
|
410
410
|
/**
|
|
411
411
|
* The single cell to mark as persistently selected -- `row`/`col` in matrix mode, `date` in
|
|
412
412
|
* calendar mode. Purely a controlled, consumer-owned visual/accessibility marker, mirroring
|
|
413
|
-
* `<lr-lite-chart>`'s `
|
|
413
|
+
* `<lr-lite-chart>`'s `selectedIndices` -- this component never mutates it itself; a consumer
|
|
414
414
|
* wires it up from `lr-cell-click` (or any other source) to build a toggle-select
|
|
415
415
|
* interaction. Unset (the default, `null`) draws no selection ring, adds no selected-cell text
|
|
416
416
|
* to the host's `aria-label`, and adds no selected suffix to the keyboard announcement,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger,finiteRange}from"../../../internal/numbers.js";import{getScratchCtx}from"../../../internal/canvas.js";import{resolveCssLength}from"../../../internal/css-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,minMax,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_heatmapCalendarCellLabel,LYRA_DEFAULT_heatmapCalendarLabel,LYRA_DEFAULT_heatmapDecorationLimit,LYRA_DEFAULT_heatmapDefaultColLabel,LYRA_DEFAULT_heatmapDefaultRowLabel,LYRA_DEFAULT_heatmapMatrixCellLabel,LYRA_DEFAULT_heatmapMatrixLabel,LYRA_DEFAULT_heatmapNoDataValue,LYRA_DEFAULT_heatmapProjectionLimit,LYRA_DEFAULT_heatmapSelectedCellLabel,LYRA_DEFAULT_heatmapValueLabel}from"../../../internal/default-strings.generated.js";const PAD_LEFT=60,PAD_TOP=20,FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,DEFAULT_BUCKET_COUNT=5,FIT_MIN_CELL=4,MAX_BUCKET_COUNT=256,MAX_HEATMAP_CELLS=1e4,MAX_HEATMAP_DECORATIONS=256,MAX_ACCESSIBLE_HEATMAP_CELLS=400,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),MS_PER_DAY=864e5;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}const HEX_RE=/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,RGB_RE=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/i;function hexToRgb(hex){const clean=hex.trim().replace("#","");if(!HEX_RE.test(clean))return null;const hasAlpha=clean.length===4||clean.length===8,full=clean.length<=4?clean.split("").map(c=>c+c).join(""):clean,num=Number.parseInt(full,16);return hasAlpha?[num>>>24&255,num>>>16&255,num>>>8&255,(num&255)/255]:[num>>16&255,num>>8&255,num&255,1]}function parseRgbString(value){const match=RGB_RE.exec(value);if(!match)return null;const a=match[4]===void 0?1:Number(match[4]);return[Number(match[1]),Number(match[2]),Number(match[3]),a]}function formatRgb([r,g,b,a]){const alpha=Math.min(1,Math.max(0,a));return alpha>=1?`rgb(${r}, ${g}, ${b})`:`rgba(${r}, ${g}, ${b}, ${Math.round(alpha*1e3)/1e3})`}const warnedInvalidColors=new Set;function warnInvalidColor(color){warnedInvalidColors.has(color)||(warnedInvalidColors.add(color),console.warn(`<lr-heatmap> could not parse "${color}" (set via --lr-heatmap-scale-lo/-hi) as a CSS color; falling back to the default ramp endpoint.`))}let warnedNoCanvasContext=!1;function warnNoCanvasContext(){warnedNoCanvasContext||(warnedNoCanvasContext=!0,console.warn("<lr-heatmap>: no 2D canvas context is available in this environment; color resolution for non-hex/non-rgb values (e.g. oklch(), color(srgb ...), named colors) will fall back to the given default instead of resolving the requested color."))}function normalizeBucketCount(bucketCount){return finiteInteger(bucketCount,DEFAULT_BUCKET_COUNT,2,MAX_BUCKET_COUNT)}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0},toAttribute(value){return value==null?null:String(value)}},DEFAULT_MATRIX_DATA=Object.freeze({kind:"matrix",rowLabels:Object.freeze([]),colLabels:Object.freeze([]),values:Object.freeze([])});function normalizeCellSizeClamp(value){if(!(value==null||!Number.isFinite(value)))return finiteRange(value,FIT_MIN_CELL,FIT_MIN_CELL)}const bucketCountConverter={fromAttribute(value){return value===null?DEFAULT_BUCKET_COUNT:normalizeBucketCount(Number(value))},toAttribute(value){return String(normalizeBucketCount(value))}};function resolveRgb(color,fallbackHex,ownerDocument){const fallback=hexToRgb(fallbackHex)??[0,0,0,1],direct=hexToRgb(color);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return warnNoCanvasContext(),fallback;const sentinel="rgb(1, 2, 3)";ctx.fillStyle=sentinel;const sentinelNormalized=ctx.fillStyle;if(ctx.fillStyle=color,ctx.fillStyle===sentinelNormalized&&color.trim()!==sentinel)return warnInvalidColor(color),fallback;const normalized=ctx.fillStyle;return hexToRgb(normalized)??parseRgbString(normalized)??fallback}function mixRgb(from,to,t){const clamped=Math.min(1,Math.max(0,t)),r=Math.round(from[0]+(to[0]-from[0])*clamped),g=Math.round(from[1]+(to[1]-from[1])*clamped),b=Math.round(from[2]+(to[2]-from[2])*clamped),a=from[3]+(to[3]-from[3])*clamped;return formatRgb([r,g,b,a])}class LyraHeatmap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,heatmapCalendarCellLabel:LYRA_DEFAULT_heatmapCalendarCellLabel,heatmapCalendarLabel:LYRA_DEFAULT_heatmapCalendarLabel,heatmapDecorationLimit:LYRA_DEFAULT_heatmapDecorationLimit,heatmapDefaultColLabel:LYRA_DEFAULT_heatmapDefaultColLabel,heatmapDefaultRowLabel:LYRA_DEFAULT_heatmapDefaultRowLabel,heatmapMatrixCellLabel:LYRA_DEFAULT_heatmapMatrixCellLabel,heatmapMatrixLabel:LYRA_DEFAULT_heatmapMatrixLabel,heatmapNoDataValue:LYRA_DEFAULT_heatmapNoDataValue,heatmapProjectionLimit:LYRA_DEFAULT_heatmapProjectionLimit,heatmapSelectedCellLabel:LYRA_DEFAULT_heatmapSelectedCellLabel,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps"])}static{this.identityCollectionObjectProperties=Object.freeze(["data"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get effectiveMode(){return this.data.kind}get matrixRowLabels(){return this.cachedMatrixData.rowLabels}get matrixColLabels(){return this.cachedMatrixData.colLabels}get matrixValues(){return this.cachedMatrixData.values}get calendarDays(){return this.data.kind==="calendar"?this.data.days:[]}get calendarData(){return this.data.kind==="calendar"?this.data:void 0}get cellSize(){return this._cellSize??(this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE)}set cellSize(value){const oldValue=this._cellSize;this._cellSize=value==null?void 0:finiteRange(value,this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE,1),this.requestUpdate("cellSize",oldValue)}get maxCellSize(){return this._maxCellSize}set maxCellSize(value){const oldValue=this._maxCellSize;this._maxCellSize=normalizeCellSizeClamp(value),this.requestUpdate("maxCellSize",oldValue)}get minCellSize(){return this._minCellSize}set minCellSize(value){const oldValue=this._minCellSize;this._minCellSize=normalizeCellSizeClamp(value),this.requestUpdate("minCellSize",oldValue)}get normalizedFirstDayOfWeek(){return(finiteInteger(this.calendarData?.firstDayOfWeek??0,0)%7+7)%7}get bucketCount(){return this._bucketCount}set bucketCount(value){const oldValue=this._bucketCount;this._bucketCount=normalizeBucketCount(value),this.requestUpdate("bucketCount",oldValue)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}get calendarMonthLabelText(){return this.calendarData?.monthLabelText}get calendarColumnX(){return this.calendarData?.columnX}get calendarRowY(){return this.calendarData?.rowY}constructor(){super(),this.data=DEFAULT_MATRIX_DATA,this.scale="linear",this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,this.accessibleCells=!1,this.cachedValueRange=null,this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1},this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays),this.cachedCalendarSortedValues=[],this.cachedCalendarCellsByPos=new Map,this.cachedCalendarCellsByDate=new Map,this.cachedAnnotations=[],this.cachedLegendStops=[],this.cachedColorSteps=[],this.cachedCalendarAnnotationDates=new Set,this.cachedMatrixAnnotationPositions=new Set,this.decorationProjectionTruncated=!1,this.cachedCalendarDateByPos=[],this.cachedAccessiblePositions=[],this.cachedAccessiblePositionsByKey=new Map,this.cachedAccessiblePositionIndexByKey=new Map,this.cachedRamp=null,this.canvasHasContent=!1,this.canvasVisible=!0,this.drawDirty=!1,this.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!1,this.onDprChange=()=>{this.watchDpr(),this.requestDraw()},this.scheduleDraw=()=>{if(this.drawFrameRequest)return;const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const request={owner,handle:0};request.handle=owner.requestAnimationFrame(()=>{this.drawFrameRequest===request&&(this.drawFrameRequest=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.requestDraw())}),this.drawFrameRequest=request},this.onPointerMove=e=>{const next=this.hitTest(e.offsetX,e.offsetY);this.samePos(this.hoverCell,next)||(this.hoverCell=next)},this.onPointerLeave=()=>{this.hoverCell=null},this.onCanvasClick=e=>{const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e)},this.canvasColorCache=new Map,this.onAccessibleCellFocus=e=>{if(this.restoringAccessibleFocus)return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onAccessibleCellKeyDown=e=>{if(!ARROW_KEYS.has(e.key))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell))},new ThemeWatcher(this,()=>this.refreshTheme())}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(oldValue===value||this.syncingGeneratedSemantics)&&(name==="role"&&(this.authorRole=value),name==="aria-label"&&(this.authorAriaLabel=value))}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.refreshAccessibleTargetSize();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(owner&&ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleDraw()}),this.resizeObserver=observer,observer.observe(this)}const IntersectionObserverCtor=owner?.IntersectionObserver;if(this.canvasVisible=!0,owner&&IntersectionObserverCtor){let observer;observer=new IntersectionObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.intersectionObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this);!entry||entry.isIntersecting===this.canvasVisible||(this.canvasVisible=entry.isIntersecting,this.canvasVisible&&this.drawDirty&&this.scheduleDraw())}),this.intersectionObserver=observer,observer.observe(this)}this.cachedRamp=null,this.canvasColorCache.clear(),this.watchDpr()}disconnectedCallback(){super.disconnectedCallback(),this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.releaseAnnouncementSink(),this.hoverCell=null,this.focusedCell=null,this.liveText="",this.canvasHasContent=!1,this.drawDirty=!0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.canvasVisible=!0,this.clearDprWatcher(),this.cancelDrawFrame()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}watchDpr(){this.clearDprWatcher();const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.matchMedia!="function")return;const query2=owner.matchMedia(`(resolution: ${owner.devicePixelRatio}dppx)`),listener=()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.dprQuery!==query2||this.onDprChange()};this.dprQuery=query2,this.dprChangeListener=listener,query2.addEventListener("change",listener)}clearDprWatcher(){this.dprQuery&&this.dprChangeListener&&this.dprQuery.removeEventListener("change",this.dprChangeListener),this.dprQuery=void 0,this.dprChangeListener=void 0}willUpdate(changed){super.willUpdate(changed),(changed.has("data")||!this.hasUpdated)&&this.rebuildCanonicalMatrixData(),(changed.has("annotations")||changed.has("legendStops")||changed.has("colorSteps")||!this.hasUpdated)&&this.rebuildBoundedDecorations();const accessibleModeChanged=changed.has("accessibleCells")&&this.hasUpdated,collectionChanged=changed.has("data")||changed.has("cellInteractive"),activeRenderedControl=collectionChanged||accessibleModeChanged?activeElementIn(this.shadowRoot):null,activeAccessibleCell=activeRenderedControl?.matches('[part="cell"]')?activeRenderedControl:null,renderedAccessibleCells=activeAccessibleCell?.matches('[part="cell"]')?[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]]:[],accessibleFocusSnapshot=activeAccessibleCell?.matches('[part="cell"]')?{identity:activeAccessibleCell.dataset.cellIdentity,index:renderedAccessibleCells.indexOf(activeAccessibleCell)}:void 0;if(collectionChanged&&(this.focusedCell=null,this.hoverCell=null,this.liveText=""),changed.has("data")||changed.has("locale")||!this.hasUpdated){this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays,this.normalizedFirstDayOfWeek,this.calendarMonthLabelText,this.effectiveLocale),this.cachedCalendarSortedValues=this.cachedCalendarGrid.cells.map(cell=>cell.value).filter(value=>Number.isFinite(value)&&value>=0).sort((a,b)=>a-b),this.cachedCalendarCellsByPos=new Map(this.cachedCalendarGrid.cells.map(cell=>[`${cell.week}:${cell.weekday}`,cell])),this.cachedCalendarCellsByDate=new Map(this.cachedCalendarGrid.cells.map(cell=>[cell.date,cell]));const{firstWeekStart,weekCount}=this.cachedCalendarGrid;this.cachedCalendarDateByPos=Array.from({length:weekCount*7},(_,index)=>isoDateAtOffset(firstWeekStart,index))}if(changed.has("colorSteps")||!this.hasUpdated){const colorSteps=this.cachedColorSteps.map(sanitizeCssColor);colorSteps.length>=2&&colorSteps.every(color=>color!==void 0)?this.style.setProperty("--lr-heatmap-color-steps-gradient",`linear-gradient(to right, ${colorSteps.join(", ")})`):this.style.removeProperty("--lr-heatmap-color-steps-gradient")}if((changed.has("data")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),accessibleFocusSnapshot){const positions=this.accessibleCellPositions(),target=(accessibleFocusSnapshot.identity==null?void 0:positions.find(pos=>this.accessibleCellIdentity(pos)===accessibleFocusSnapshot.identity))??positions[Math.min(Math.max(accessibleFocusSnapshot.index,0),positions.length-1)]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeAccessibleCell??void 0,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}if(accessibleModeChanged){const previouslyAccessible=changed.get("accessibleCells")===!0;if(previouslyAccessible&&!this.accessibleCells&&activeAccessibleCell){const key=activeAccessibleCell.dataset.cellKey,target=key?this.accessibleCellAtKey(key):null;target&&(this.focusedCell=target,this.liveText=this.resolveCellText(target)),this.pendingAccessibleFocus="canvas",this.pendingAccessibleFocusOrigin=activeAccessibleCell,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}else if(!previouslyAccessible&&this.accessibleCells&&activeRenderedControl?.matches('[part="canvas"]')){const positions=this.accessibleCellPositions(),target=this.focusedCell?positions.find(pos=>this.samePos(pos,this.focusedCell))??positions[0]??null:positions[0]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeRenderedControl,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}}const bounds=this.cachedValueRange,range=bounds?`${this.formatNumericValue(bounds[0])}\u2013${this.formatNumericValue(bounds[1])}`:this.localize("heatmapNoDataValue"),valueLabel=this.localizedValueLabel();let label;if(this.effectiveMode==="calendar")label=this.localize("heatmapCalendarLabel",void 0,{days:this.formatCount(this.cachedCalendarGrid.cells.length),label:valueLabel,range});else{const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;label=this.localize("heatmapMatrixLabel",void 0,{rows:this.formatCount(rows),cols:this.formatCount(cols),label:valueLabel,range})}const selectedText=this.selectedCellDescription(),generatedAriaLabel=[label,selectedText,this.projectionDescription()].filter(Boolean).join(" ");this.generatedAriaLabel=generatedAriaLabel,this.syncingGeneratedSemantics=!0;try{this.authorRole===null&&this.setAttribute("role","group"),this.authorAriaLabel===null&&this.setAttribute("aria-label",generatedAriaLabel)}finally{this.syncingGeneratedSemantics=!1}}rebuildBoundedDecorations(){this.cachedAnnotations=this.annotations.slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedLegendStops=(this.legendStops??[]).slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedColorSteps=(this.colorSteps??[]).slice(0,MAX_HEATMAP_DECORATIONS),this.cachedCalendarAnnotationDates=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.date==null?[]:[annotation.date])),this.cachedMatrixAnnotationPositions=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.row==null||annotation.col==null?[]:[`${annotation.row}:${annotation.col}`])),this.decorationProjectionTruncated=this.annotations.length>MAX_HEATMAP_DECORATIONS||(this.legendStops?.length??0)>MAX_HEATMAP_DECORATIONS||(this.colorSteps?.length??0)>MAX_HEATMAP_DECORATIONS}get projectionTruncated(){return this.decorationProjectionTruncated||(this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated)}get cellProjectionTruncated(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated}projectedCellCount(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount*7:this.matrixRowLabels.length*this.matrixColLabels.length}projectionDescription(){const messages=[];return this.cellProjectionTruncated&&messages.push(this.localize("heatmapProjectionLimit",void 0,{count:this.formatCount(this.projectedCellCount())})),this.decorationProjectionTruncated&&messages.push(this.localize("heatmapDecorationLimit",void 0,{count:this.formatCount(MAX_HEATMAP_DECORATIONS)})),messages.join(" ")}rebuildCanonicalMatrixData(){if(this.data.kind!=="matrix"){this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1};return}const colCount=Math.min(this.data.colLabels.length,MAX_HEATMAP_CELLS),rowLimit=colCount===0?Math.min(this.data.rowLabels.length,MAX_HEATMAP_CELLS):Math.floor(MAX_HEATMAP_CELLS/colCount),rowCount=Math.min(this.data.rowLabels.length,rowLimit),rowLabels=this.data.rowLabels.slice(0,rowCount).map(String),colLabels=this.data.colLabels.slice(0,colCount).map(String),source=this.data,values=Array.from({length:rowCount},(_,row)=>Array.from({length:colCount},(_2,col)=>source.values[row]?.[col]??-1));this.cachedMatrixData={rowLabels,colLabels,values,truncated:rowCount!==this.data.rowLabels.length||colCount!==this.data.colLabels.length||this.data.values.some((row,index)=>index>=rowCount||row.length>colCount)}}selectedCellDescription(){if(!this.selectedCell)return"";if(this.effectiveMode==="calendar"){if(this.selectedCell.date==null)return"";const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);return match?this.localize("heatmapSelectedCellLabel",void 0,{cell:this.calendarCellText({week:match.week,weekday:match.weekday,date:match.date})}):""}const{row,col}=this.selectedCell;return row==null||col==null||row<0||row>=this.matrixRowLabels.length||col<0||col>=this.matrixColLabels.length?"":this.localize("heatmapSelectedCellLabel",void 0,{cell:this.matrixCellText({row,col})})}computeValueRange(){const source=this.effectiveMode==="calendar"?this.cachedCalendarGrid.cells.map(cell=>cell.value):this.matrixValues.flat();return minMax(source.filter(v=>Number.isFinite(v)&&v>=0))}localizedValueLabel(){return this.valueLabel===void 0?this.localize("heatmapValueLabel"):this.valueLabel}formatNumericValue(value){return getNumberFormat(this.effectiveLocale||void 0).format(value)}updated(changed){if(super.updated(changed),["data","cellSize","maxCellSize","minCellSize","valueLabel","scale","fitToWidth","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","legendStops","accessibleCells","accessibleTargetSizePx","locale"].some(name=>changed.has(name))){if(changed.has("focusedCell")&&[...changed.keys()].every(key=>key==="focusedCell"||key==="liveText")&&this.repaintFocusRing(changed.get("focusedCell")))return;this.requestDraw()}const pending=this.pendingAccessibleFocus;if(pending===void 0)return;this.pendingAccessibleFocus=void 0;const origin=this.pendingAccessibleFocusOrigin;this.pendingAccessibleFocusOrigin=void 0;const generation=this.accessibleFocusGeneration;this.scheduleAfterUpdate(()=>{try{if(generation!==this.accessibleFocusGeneration||!this.isConnected)return;if(origin){const internalActive=activeElementIn(this.shadowRoot),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return}if(pending==="base"){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}if(pending==="canvas"){this.shadowRoot?.querySelector('[part="canvas"]')?.focus();return}const identity=this.accessibleCellIdentity(pending);[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellIdentity===identity)?.focus()}finally{this.restoringAccessibleFocus=!1}},"heatmap-accessible-focus")}refreshTheme(){this.cachedRamp=null,this.refreshAccessibleTargetSize()||this.requestDraw()}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssLength(raw,{host:this}),next=resolved!==void 0&&Number.isFinite(resolved)&&resolved>0?resolved:DEFAULT_ACCESSIBLE_TARGET_SIZE_PX;return next===this.accessibleTargetSizePx?!1:(this.accessibleTargetSizePx=next,!0)}scaleEndpoints(cs){const lo=cs.getPropertyValue("--lr-heatmap-scale-lo").trim()||cs.getPropertyValue("--_lr-heatmap-scale-lo").trim()||FALLBACK_SCALE_LO,hi=cs.getPropertyValue("--lr-heatmap-scale-hi").trim()||cs.getPropertyValue("--_lr-heatmap-scale-hi").trim()||FALLBACK_SCALE_HI;return[lo,hi]}labelColor(cs){return cs.getPropertyValue("--lr-color-text-quiet").trim()||"#6b7280"}labelFont(cs){return cs.getPropertyValue("--lr-heatmap-label-font").trim()||cs.getPropertyValue("--_lr-heatmap-label-font").trim()||FALLBACK_LABEL_FONT}noDataFill(cs){return cs.getPropertyValue("--lr-heatmap-no-data-fill").trim()||cs.getPropertyValue("--_lr-heatmap-no-data-fill").trim()||FALLBACK_NO_DATA_FILL}focusRingColor(cs){return cs.getPropertyValue("--lr-heatmap-focus-ring-color").trim()||cs.getPropertyValue("--_lr-heatmap-focus-ring-color").trim()||FALLBACK_FOCUS_RING_COLOR}annotationColor(cs){return cs.getPropertyValue("--lr-heatmap-annotation-color").trim()||cs.getPropertyValue("--_lr-heatmap-annotation-color").trim()||FALLBACK_ANNOTATION_COLOR}selectedColor(cs){return cs.getPropertyValue("--lr-heatmap-selected-color").trim()||cs.getPropertyValue("--_lr-heatmap-selected-color").trim()||FALLBACK_SELECTED_COLOR}strokeCellState(ctx,x,y,size,state2,color){const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(size-RING_LINE_WIDTH-1)/2)),extent=Math.max(1,size-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),ctx.strokeRect(x+inset,y+inset,extent,extent),ctx.setLineDash?.([])}isSelectedPos(pos){return this.selectedCell?"week"in pos?this.selectedCell.date==null?!1:this.calendarCellAt(pos).date===this.selectedCell.date:this.selectedCell.row===pos.row&&this.selectedCell.col===pos.col:!1}draw(){if(!this.canvasVisible){this.drawDirty=!0;return}this.drawDirty=!1,this.canvasHasContent=!1,this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.canvasVisible&&this.draw()}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas)return!1;const current=this.focusedCell;if(this.effectiveMode==="calendar"){if(previous&&!("week"in previous)||current&&!("week"in current))return!1;this.repaintCalendarFocusCell(previous&&"week"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintCalendarFocusCell(current)}else{if(previous&&!("row"in previous)||current&&!("row"in current))return!1;this.repaintMatrixFocusCell(previous&&"row"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintMatrixFocusCell(current)}return!0}cancelDrawFrame(){const request=this.drawFrameRequest;request&&request.owner.cancelAnimationFrame(request.handle),this.drawFrameRequest=void 0}resolveColorStep(color,fallback){const safe=sanitizeCssColor(color);if(!safe)return fallback;const scope=this.ownerDocument.createElement("span"),probe=this.ownerDocument.createElement("span");scope.hidden=!0,scope.style.color=fallback,probe.style.color=safe,scope.append(probe),this.renderRoot.append(scope);try{return this.ownerDocument.defaultView?.getComputedStyle(probe).color.trim()||fallback}finally{scope.remove()}}colorRamp(bucketCount,cs){const steps=this.cachedColorSteps;if(steps&&steps.length>=2){const key2=`steps ${steps.join(" ")}`;if(this.cachedRamp?.key===key2)return this.cachedRamp;const resolved=steps.map((color,index)=>this.resolveColorStep(color,index===steps.length-1?FALLBACK_SCALE_HI:FALLBACK_SCALE_LO)),colors2=resolved.map(color=>formatRgb(resolveRgb(color,FALLBACK_SCALE_LO,this.ownerDocument))),loRgb2=resolveRgb(resolved[0],FALLBACK_SCALE_LO,this.ownerDocument),hiRgb2=resolveRgb(resolved[resolved.length-1],FALLBACK_SCALE_HI,this.ownerDocument);return this.cachedRamp={key:key2,colors:colors2,loRgb:loRgb2,hiRgb:hiRgb2},this.cachedRamp}const[scaleLo,scaleHi]=this.scaleEndpoints(cs),normalizedBucketCount=normalizeBucketCount(bucketCount),key=`${scaleLo}\0${scaleHi}\0${normalizedBucketCount}`;if(this.cachedRamp?.key===key)return this.cachedRamp;const loRgb=resolveRgb(scaleLo,FALLBACK_SCALE_LO,this.ownerDocument),hiRgb=resolveRgb(scaleHi,FALLBACK_SCALE_HI,this.ownerDocument),colors=Array.from({length:normalizedBucketCount},(_,i)=>mixRgb(loRgb,hiRgb,i/(normalizedBucketCount-1)));return this.cachedRamp={key,colors,loRgb,hiRgb},this.cachedRamp}calendarCellSize(){const{weekCount}=this.cachedCalendarGrid;let size;if(this.fitToWidth&&weekCount>0){const hostWidth=this.clientWidth||CAL_PAD_LEFT+weekCount*(this.cellSize+CAL_GAP);size=this.clampFitCellSize((hostWidth-CAL_PAD_LEFT)/weekCount-CAL_GAP)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}clampFitCellSize(size){const floored=finiteRange(size,FIT_MIN_CELL,Math.max(FIT_MIN_CELL,this.minCellSize??FIT_MIN_CELL));return this.maxCellSize==null?floored:Math.min(floored,this.maxCellSize)}columnXFor(week){return this.calendarColumnPositions()[week]??CAL_PAD_LEFT}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const cellSize=this.calendarCellSize(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?CAL_PAD_LEFT:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedColumnGeometry={callback,cellSize,weekCount,positions},positions}calendarRowPositions(){const cellSize=this.calendarCellSize(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedRowGeometry={callback,cellSize,positions},positions}weekAtX(x,weekCount){const positions=this.calendarColumnPositions(),cellSize=this.calendarCellSize();for(let week=0;week<weekCount;week++){const start=positions[week];if(x>=start&&x<start+cellSize)return week}return null}weekdayAtY(y){const positions=this.calendarRowPositions(),cellSize=this.calendarCellSize();for(let weekday=0;weekday<7;weekday++){const start=positions[weekday];if(y>=start&&y<start+cellSize)return weekday}return null}weekdayLabels(firstWeekStart){const formatter=getDateTimeFormat(this.effectiveLocale||void 0,{weekday:"short",timeZone:"UTC"}),labels=["","","","","","",""];for(const weekday of[1,3,5]){const row=(weekday-this.normalizedFirstDayOfWeek+7)%7;labels[row]=this.calendarWeekdayLabelText?.(weekday)??formatter.format(new Date(firstWeekStart.getTime()+row*MS_PER_DAY))}return labels}drawCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cellSize=this.calendarCellSize(),w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const buckets=normalizeBucketCount(this.bucketCount),ramp=this.colorRamp(buckets,cs).colors,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const value=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(value<0||!Number.isFinite(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=linearBucket(value,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,buckets)];ctx.fillRect(x,y,cellSize,cellSize)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.date==null)continue;const match=this.cachedCalendarCellsByDate.get(ann.date);if(!match)continue;const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.date!=null){const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);if(match){const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"week"in this.focusedCell){const{week,weekday}=this.focusedCell;if(week<weekCount&&weekday<7){const x=this.columnXFor(week),y=this.rowYFor(weekday);this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const m of monthLabels)ctx.fillText(m.label,this.columnXFor(m.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)}),this.canvasHasContent=!0}matrixCellSize(cols){let size;if(this.fitToWidth&&cols>0){const hostWidth=this.clientWidth||PAD_LEFT+cols*this.cellSize;size=this.clampFitCellSize((hostWidth-PAD_LEFT)/cols)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}paintMatrixCell(ctx,row,col,cellSize,cs,rampData,noDataFill){const value=this.matrixValues[row]?.[col]??-1,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.({row,col},value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(value<0||!Number.isFinite(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,rampData.colors.length);ctx.fillStyle=step<0?noDataFill:rampData.colors[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=rampData.colors[linearBucket(value,lo,hi,rampData.colors.length)]:ctx.fillStyle=mixRgb(rampData.loRgb,rampData.hiRgb,linearAlpha(value,lo,hi));ctx.fillRect(PAD_LEFT+col*cellSize,PAD_TOP+row*cellSize,cellSize-1,cellSize-1)}paintMatrixFocusOverlays(ctx,row,col,cellSize,cs){const x=PAD_LEFT+col*cellSize,y=PAD_TOP+row*cellSize;this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),this.selectedCell?.row===row&&this.selectedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintMatrixFocusCell(pos){if(!pos||!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(pos.row<0||pos.row>=rows||pos.col<0||pos.col>=cols)return;const cellSize=this.matrixCellSize(cols),x=PAD_LEFT+pos.col*cellSize,y=PAD_TOP+pos.row*cellSize,ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);cs&&(this.paintMatrixCell(ctx,pos.row,pos.col,cellSize,cs,this.colorRamp(RAMP_STEPS,cs),this.noDataFill(cs)),this.paintMatrixFocusOverlays(ctx,pos.row,pos.col,cellSize,cs))}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(value<0||!Number.isFinite(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=ramp[linearBucket(value,lo,hi,ramp.length)]:ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,ramp.length)];ctx.fillRect(this.columnXFor(week),this.rowYFor(weekday),cellSize,cellSize)}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),matches=candidate=>candidate?.date===date;this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),matches(this.selectedCell??void 0)&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"week"in this.focusedCell&&this.focusedCell.week===week&&this.focusedCell.weekday===weekday&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintCalendarFocusCell(pos){if(!pos||!this.canvas)return;const{weekCount,firstWeekStart}=this.cachedCalendarGrid;if(pos.week<0||pos.week>=weekCount||pos.weekday<0||pos.weekday>=7)return;const cellSize=this.calendarCellSize(),x=this.columnXFor(pos.week),y=this.rowYFor(pos.weekday),ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors;this.paintCalendarCell(ctx,pos.week,pos.weekday,cellSize,cs,ramp,this.noDataFill(cs)),this.paintCalendarFocusOverlays(ctx,pos.week,pos.weekday,cellSize,cs),ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const month of this.cachedCalendarGrid.monthLabels)ctx.fillText(month.label,this.columnXFor(month.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)})}drawMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length,cellSize=this.matrixCellSize(cols),w=PAD_LEFT+cols*cellSize,h=PAD_TOP+rows*cellSize,dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,rampData=this.colorRamp(RAMP_STEPS,cs),ramp=rampData.colors,{loRgb,hiRgb}=rampData,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){const v=this.matrixValues[r]?.[c]??-1,x=PAD_LEFT+c*cellSize,y=PAD_TOP+r*cellSize,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(v<0||!Number.isFinite(v))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(v,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=linearBucket(v,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else{const t=linearAlpha(v,lo,hi);ctx.fillStyle=mixRgb(loRgb,hiRgb,t)}ctx.fillRect(x,y,cellSize-1,cellSize-1)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.row==null||ann.col==null||ann.row<0||ann.row>=rows||ann.col<0||ann.col>=cols)continue;const x=PAD_LEFT+ann.col*cellSize,y=PAD_TOP+ann.row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.row!=null&&this.selectedCell.col!=null){const{row,col}=this.selectedCell;if(row>=0&&row<rows&&col>=0&&col<cols){const x=PAD_LEFT+col*cellSize,y=PAD_TOP+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"row"in this.focusedCell){const{row,col}=this.focusedCell;if(row<rows&&col<cols){const x=PAD_LEFT+col*cellSize,y=PAD_TOP+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs),this.matrixRowLabels.forEach((label,r)=>{ctx.fillText(label,4,PAD_TOP+r*cellSize+cellSize/2+3)}),this.matrixColLabels.forEach((label,c)=>{ctx.fillText(label,PAD_LEFT+c*cellSize+2,PAD_TOP-6)}),this.canvasHasContent=!0}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return null;const cellSize=this.matrixCellSize(cols),col=Math.floor((x-PAD_LEFT)/cellSize),row=Math.floor((y-PAD_TOP)/cellSize);if(row<0||row>=rows||col<0||col>=cols)return null;const pos={row,col};return this.isCellInteractive(pos)?pos:null}firstInteractiveMatrixCell(rows,cols){for(let r=0;r<rows;r++)for(let c=0;c<cols;c++)if(this.isCellInteractive({row:r,col:c}))return{row:r,col:c};return null}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){let r=row,c=col;for(;;){const nr=Math.min(rows-1,Math.max(0,r+dRow)),nc=Math.min(cols-1,Math.max(0,c+dCol));if(nr===r&&nc===c)return{row,col};if(r=nr,c=nc,this.isCellInteractive({row:r,col:c}))return{row:r,col:c}}}firstInteractiveCalendarCell(weekCount){for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);if(this.isCellInteractive(pos))return pos}return null}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){let w=week,d=weekday;for(;;){const nw=Math.min(weekCount-1,Math.max(0,w+dWeek)),nd=Math.min(6,Math.max(0,d+dWeekday));if(nw===w&&nd===d)return this.calendarPos(week,weekday);w=nw,d=nd;const pos=this.calendarPos(w,d);if(this.isCellInteractive(pos))return pos}}hitTestCalendar(x,y){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return null;const week=this.weekAtX(x,weekCount),weekday=this.weekdayAtY(y);if(week===null||weekday===null)return null;const pos=this.calendarPos(week,weekday);return this.isCellInteractive(pos)?pos:null}calendarCellAt(pos){const match=this.cachedCalendarCellsByPos.get(`${pos.week}:${pos.weekday}`);return match?{date:match.date,value:match.value}:{date:this.calendarDateAt(pos.week,pos.weekday),value:-1}}calendarDateAt(week,weekday){const index=week*7+weekday;return this.cachedCalendarDateByPos[index]??isoDateAtOffset(this.cachedCalendarGrid.firstWeekStart,index)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){if("week"in pos){const cellSize2=this.calendarCellSize();return{x:this.columnXFor(pos.week),y:this.rowYFor(pos.weekday),w:cellSize2,h:cellSize2}}const cellSize=this.matrixCellSize(this.matrixColLabels.length);return{x:PAD_LEFT+pos.col*cellSize,y:PAD_TOP+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}defaultCellText(pos){return"week"in pos?this.calendarCellText(pos):this.matrixCellText(pos)}matrixCellText(pos){const rowLabel=this.matrixRowLabels[pos.row]??this.localize("heatmapDefaultRowLabel",void 0,{n:this.formatCount(pos.row+1)}),colLabel=this.matrixColLabels[pos.col]??this.localize("heatmapDefaultColLabel",void 0,{n:this.formatCount(pos.col+1)}),v=this.matrixValues[pos.row]?.[pos.col],valueText=v==null||v<0||!Number.isFinite(v)?this.localize("heatmapNoDataValue"):this.formatNumericValue(v);return this.localize("heatmapMatrixCellLabel",void 0,{row:rowLabel,col:colLabel,value:valueText})}calendarCellText(pos){const{date,value}=this.calendarCellAt(pos),label=parseIsoDate(date).toLocaleString(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}),valueText=value<0||!Number.isFinite(value)?this.localize("heatmapNoDataValue"):this.formatNumericValue(value);return this.localize("heatmapCalendarCellLabel",void 0,{date:label,value:valueText})}valueAt(pos){return"week"in pos?this.calendarCellAt(pos).value:this.matrixValues[pos.row]?.[pos.col]??-1}resolveCellText(pos){return this.cellText?this.cellText(pos,this.valueAt(pos)):this.defaultCellText(pos)}isCellInteractive(pos){return this.cellInteractive?.(pos,this.valueAt(pos))??!0}announce(pos){const text=this.resolveCellText(pos),announcement=this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcementSink?.announce(announcement)}emitCellClick(pos){if(this.isCellInteractive(pos))if("week"in pos){const{date,value}=this.calendarCellAt(pos);this.emit("lr-cell-click",{date,value})}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;this.emit("lr-cell-click",{row:pos.row,col:pos.col,value})}}tooltipStyle(pos){const rect=this.cellRect(pos);return{left:`${rect.x+rect.w/2}px`,top:`${rect.y}px`}}samePos(a,b){return a===b?!0:!a||!b?!1:"week"in a&&"week"in b?a.week===b.week&&a.weekday===b.weekday:"row"in a&&"row"in b?a.row===b.row&&a.col===b.col:!1}onMatrixKeyDown(e){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("row"in this.focusedCell)){const next2=this.firstInteractiveMatrixCell(rows,cols);if(!next2)return;this.focusedCell=next2,this.announce(next2);return}const{row,col}=this.focusedCell;let dRow=0,dCol=0;e.key==="ArrowUp"?dRow=-1:e.key==="ArrowDown"?dRow=1:e.key==="ArrowLeft"?dCol=-1:e.key==="ArrowRight"&&(dCol=1);const next=this.nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols);this.focusedCell=next,this.announce(next)}onCalendarKeyDown(e){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("week"in this.focusedCell)){const next2=this.firstInteractiveCalendarCell(weekCount);if(!next2)return;this.focusedCell=next2,this.announce(next2);return}const{week,weekday}=this.focusedCell;let dWeek=0,dWeekday=0;e.key==="ArrowUp"?dWeekday=-1:e.key==="ArrowDown"?dWeekday=1:e.key==="ArrowLeft"?dWeek=-1:e.key==="ArrowRight"&&(dWeek=1);const next=this.nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount);this.focusedCell=next,this.announce(next)}resolveCanvasColor(value,cs){const cached=this.canvasColorCache.get(value);if(cached!==void 0)return cached;const fallback=this.noDataFill(cs);let candidate=value;if(value.includes("var(")){if(this.colorProbe||(this.colorProbe=this.ownerDocument.createElement("span"),this.colorProbe.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;",this.shadowRoot.appendChild(this.colorProbe)),this.colorProbe.style.color="",this.colorProbe.style.color=value,!this.colorProbe.style.color)return this.canvasColorCache.set(value,fallback),fallback;candidate=this.ownerDocument.defaultView?.getComputedStyle(this.colorProbe).color||fallback}const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return fallback;ctx.fillStyle="rgb(1, 2, 3)";const firstSentinel=ctx.fillStyle;ctx.fillStyle=candidate;let resolved=ctx.fillStyle;if(resolved===firstSentinel){ctx.fillStyle="rgb(4, 5, 6)";const secondSentinel=ctx.fillStyle;ctx.fillStyle=candidate,resolved=ctx.fillStyle,resolved===secondSentinel&&(resolved=fallback)}return this.canvasColorCache.set(value,resolved),resolved}rebuildAccessiblePositions(){const positions=[];if(this.effectiveMode==="calendar"){const{weekCount}=this.cachedCalendarGrid;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);this.isCellInteractive(pos)&&positions.push(pos)}}else for(let row=0;row<this.matrixRowLabels.length;row++)for(let col=0;col<this.matrixColLabels.length;col++){const pos={row,col};this.isCellInteractive(pos)&&positions.push(pos)}this.cachedAccessiblePositions=positions,this.cachedAccessiblePositionsByKey=new Map(positions.map(position=>[this.accessibleCellKey(position),position])),this.cachedAccessiblePositionIndexByKey=new Map(positions.map((position,index)=>[this.accessibleCellKey(position),index]))}accessibleCellPositions(){return this.cachedAccessiblePositions}accessibleCellKey(pos){return"week"in pos?`calendar-${pos.week}-${pos.weekday}`:`matrix-${pos.row}-${pos.col}`}accessibleCellIdentity(pos){return"week"in pos?pos.date:this.accessibleCellKey(pos)}accessibleCellAtKey(key){return this.cachedAccessiblePositionsByKey.get(key)??null}focusAccessibleCell(pos){pos&&this.updateComplete.then(()=>{[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellKey===this.accessibleCellKey(pos))?.focus()})}renderAccessibleCells(){if(!this.accessibleCells)return html``;const positions=this.accessibleCellPositions(),tabStop=this.focusedCell??positions[0]??null,focusIndex=tabStop?this.cachedAccessiblePositionIndexByKey.get(this.accessibleCellKey(tabStop))??0:0,start=Math.max(0,Math.min(Math.max(0,positions.length-MAX_ACCESSIBLE_HEATMAP_CELLS),focusIndex-Math.floor(MAX_ACCESSIBLE_HEATMAP_CELLS/2))),renderedPositions=positions.slice(start,start+MAX_ACCESSIBLE_HEATMAP_CELLS),renderedRows=new Map;for(const pos of renderedPositions){const rowIndex="week"in pos?pos.weekday+1:pos.row+1,row=renderedRows.get(rowIndex);row?row.push(pos):renderedRows.set(rowIndex,[pos])}const rowCount=this.effectiveMode==="calendar"?7:this.matrixRowLabels.length,colCount=this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount:this.matrixColLabels.length;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,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger,finiteRange}from"../../../internal/numbers.js";import{getScratchCtx}from"../../../internal/canvas.js";import{resolveCssLength}from"../../../internal/css-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,minMax,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_heatmapCalendarCellLabel,LYRA_DEFAULT_heatmapCalendarLabel,LYRA_DEFAULT_heatmapDecorationLimit,LYRA_DEFAULT_heatmapDefaultColLabel,LYRA_DEFAULT_heatmapDefaultRowLabel,LYRA_DEFAULT_heatmapMatrixCellLabel,LYRA_DEFAULT_heatmapMatrixLabel,LYRA_DEFAULT_heatmapNoDataValue,LYRA_DEFAULT_heatmapProjectionLimit,LYRA_DEFAULT_heatmapSelectedCellLabel,LYRA_DEFAULT_heatmapValueLabel}from"../../../internal/default-strings.generated.js";const PAD_LEFT=60,PAD_TOP=20,FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,DEFAULT_BUCKET_COUNT=5,FIT_MIN_CELL=4,MAX_BUCKET_COUNT=256,MAX_HEATMAP_CELLS=1e4,MAX_HEATMAP_DECORATIONS=256,MAX_ACCESSIBLE_HEATMAP_CELLS=400,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),MS_PER_DAY=864e5;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}const HEX_RE=/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,RGB_RE=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/i;function hexToRgb(hex){const clean=hex.trim().replace("#","");if(!HEX_RE.test(clean))return null;const hasAlpha=clean.length===4||clean.length===8,full=clean.length<=4?clean.split("").map(c=>c+c).join(""):clean,num=Number.parseInt(full,16);return hasAlpha?[num>>>24&255,num>>>16&255,num>>>8&255,(num&255)/255]:[num>>16&255,num>>8&255,num&255,1]}function parseRgbString(value){const match=RGB_RE.exec(value);if(!match)return null;const a=match[4]===void 0?1:Number(match[4]);return[Number(match[1]),Number(match[2]),Number(match[3]),a]}function resolveViaPixelReadback(ctx){try{ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[r=0,g=0,b=0,a=0]=ctx.getImageData(0,0,1,1).data;return[r,g,b,a/255]}catch{return null}}function formatRgb([r,g,b,a]){const alpha=Math.min(1,Math.max(0,a));return alpha>=1?`rgb(${r}, ${g}, ${b})`:`rgba(${r}, ${g}, ${b}, ${Math.round(alpha*1e3)/1e3})`}const warnedInvalidColors=new Set;function warnInvalidColor(color){warnedInvalidColors.has(color)||(warnedInvalidColors.add(color),console.warn(`<lr-heatmap> could not parse "${color}" (set via --lr-heatmap-scale-lo/-hi) as a CSS color; falling back to the default ramp endpoint.`))}let warnedNoCanvasContext=!1;function warnNoCanvasContext(){warnedNoCanvasContext||(warnedNoCanvasContext=!0,console.warn("<lr-heatmap>: no 2D canvas context is available in this environment; color resolution for non-hex/non-rgb values (e.g. oklch(), color(srgb ...), named colors) will fall back to the given default instead of resolving the requested color."))}function normalizeBucketCount(bucketCount){return finiteInteger(bucketCount,DEFAULT_BUCKET_COUNT,2,MAX_BUCKET_COUNT)}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0},toAttribute(value){return value==null?null:String(value)}},DEFAULT_MATRIX_DATA=Object.freeze({kind:"matrix",rowLabels:Object.freeze([]),colLabels:Object.freeze([]),values:Object.freeze([])});function normalizeCellSizeClamp(value){if(!(value==null||!Number.isFinite(value)))return finiteRange(value,FIT_MIN_CELL,FIT_MIN_CELL)}const bucketCountConverter={fromAttribute(value){return value===null?DEFAULT_BUCKET_COUNT:normalizeBucketCount(Number(value))},toAttribute(value){return String(normalizeBucketCount(value))}};function resolveRgb(color,fallbackHex,ownerDocument){const fallback=hexToRgb(fallbackHex)??[0,0,0,1],direct=hexToRgb(color);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return warnNoCanvasContext(),fallback;const sentinel="rgb(1, 2, 3)";ctx.fillStyle=sentinel;const sentinelNormalized=ctx.fillStyle;if(ctx.fillStyle=color,ctx.fillStyle===sentinelNormalized&&color.trim()!==sentinel)return warnInvalidColor(color),fallback;const normalized=ctx.fillStyle;return hexToRgb(normalized)??parseRgbString(normalized)??resolveViaPixelReadback(ctx)??fallback}function mixRgb(from,to,t){const clamped=Math.min(1,Math.max(0,t)),r=Math.round(from[0]+(to[0]-from[0])*clamped),g=Math.round(from[1]+(to[1]-from[1])*clamped),b=Math.round(from[2]+(to[2]-from[2])*clamped),a=from[3]+(to[3]-from[3])*clamped;return formatRgb([r,g,b,a])}class LyraHeatmap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,heatmapCalendarCellLabel:LYRA_DEFAULT_heatmapCalendarCellLabel,heatmapCalendarLabel:LYRA_DEFAULT_heatmapCalendarLabel,heatmapDecorationLimit:LYRA_DEFAULT_heatmapDecorationLimit,heatmapDefaultColLabel:LYRA_DEFAULT_heatmapDefaultColLabel,heatmapDefaultRowLabel:LYRA_DEFAULT_heatmapDefaultRowLabel,heatmapMatrixCellLabel:LYRA_DEFAULT_heatmapMatrixCellLabel,heatmapMatrixLabel:LYRA_DEFAULT_heatmapMatrixLabel,heatmapNoDataValue:LYRA_DEFAULT_heatmapNoDataValue,heatmapProjectionLimit:LYRA_DEFAULT_heatmapProjectionLimit,heatmapSelectedCellLabel:LYRA_DEFAULT_heatmapSelectedCellLabel,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps"])}static{this.identityCollectionObjectProperties=Object.freeze(["data"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get effectiveMode(){return this.data.kind}get matrixRowLabels(){return this.cachedMatrixData.rowLabels}get matrixColLabels(){return this.cachedMatrixData.colLabels}get matrixValues(){return this.cachedMatrixData.values}get calendarDays(){return this.data.kind==="calendar"?this.data.days:[]}get calendarData(){return this.data.kind==="calendar"?this.data:void 0}get cellSize(){return this._cellSize??(this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE)}set cellSize(value){const oldValue=this._cellSize;this._cellSize=value==null?void 0:finiteRange(value,this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE,1),this.requestUpdate("cellSize",oldValue)}get maxCellSize(){return this._maxCellSize}set maxCellSize(value){const oldValue=this._maxCellSize;this._maxCellSize=normalizeCellSizeClamp(value),this.requestUpdate("maxCellSize",oldValue)}get minCellSize(){return this._minCellSize}set minCellSize(value){const oldValue=this._minCellSize;this._minCellSize=normalizeCellSizeClamp(value),this.requestUpdate("minCellSize",oldValue)}get normalizedFirstDayOfWeek(){return(finiteInteger(this.calendarData?.firstDayOfWeek??0,0)%7+7)%7}get bucketCount(){return this._bucketCount}set bucketCount(value){const oldValue=this._bucketCount;this._bucketCount=normalizeBucketCount(value),this.requestUpdate("bucketCount",oldValue)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}get calendarMonthLabelText(){return this.calendarData?.monthLabelText}get calendarColumnX(){return this.calendarData?.columnX}get calendarRowY(){return this.calendarData?.rowY}constructor(){super(),this.data=DEFAULT_MATRIX_DATA,this.scale="linear",this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,this.accessibleCells=!1,this.cachedValueRange=null,this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1},this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays),this.cachedCalendarSortedValues=[],this.cachedCalendarCellsByPos=new Map,this.cachedCalendarCellsByDate=new Map,this.cachedAnnotations=[],this.cachedLegendStops=[],this.cachedColorSteps=[],this.cachedCalendarAnnotationDates=new Set,this.cachedMatrixAnnotationPositions=new Set,this.decorationProjectionTruncated=!1,this.cachedCalendarDateByPos=[],this.cachedAccessiblePositions=[],this.cachedAccessiblePositionsByKey=new Map,this.cachedAccessiblePositionIndexByKey=new Map,this.cachedRamp=null,this.canvasHasContent=!1,this.canvasVisible=!0,this.drawDirty=!1,this.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!1,this.onDprChange=()=>{this.watchDpr(),this.requestDraw()},this.scheduleDraw=()=>{if(this.drawFrameRequest)return;const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const request={owner,handle:0};request.handle=owner.requestAnimationFrame(()=>{this.drawFrameRequest===request&&(this.drawFrameRequest=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.requestDraw())}),this.drawFrameRequest=request},this.onPointerMove=e=>{const next=this.hitTest(e.offsetX,e.offsetY);this.samePos(this.hoverCell,next)||(this.hoverCell=next)},this.onPointerLeave=()=>{this.hoverCell=null},this.onCanvasClick=e=>{const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e)},this.canvasColorCache=new Map,this.onAccessibleCellFocus=e=>{if(this.restoringAccessibleFocus)return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onAccessibleCellKeyDown=e=>{if(!ARROW_KEYS.has(e.key))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell))},new ThemeWatcher(this,()=>this.refreshTheme())}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(oldValue===value||this.syncingGeneratedSemantics)&&(name==="role"&&(this.authorRole=value),name==="aria-label"&&(this.authorAriaLabel=value))}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.refreshAccessibleTargetSize();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(owner&&ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleDraw()}),this.resizeObserver=observer,observer.observe(this)}const IntersectionObserverCtor=owner?.IntersectionObserver;if(this.canvasVisible=!0,owner&&IntersectionObserverCtor){let observer;observer=new IntersectionObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.intersectionObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this);!entry||entry.isIntersecting===this.canvasVisible||(this.canvasVisible=entry.isIntersecting,this.canvasVisible&&this.drawDirty&&this.scheduleDraw())}),this.intersectionObserver=observer,observer.observe(this)}this.cachedRamp=null,this.canvasColorCache.clear(),this.watchDpr()}disconnectedCallback(){super.disconnectedCallback(),this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.releaseAnnouncementSink(),this.hoverCell=null,this.focusedCell=null,this.liveText="",this.canvasHasContent=!1,this.drawDirty=!0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.canvasVisible=!0,this.clearDprWatcher(),this.cancelDrawFrame()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}watchDpr(){this.clearDprWatcher();const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.matchMedia!="function")return;const query2=owner.matchMedia(`(resolution: ${owner.devicePixelRatio}dppx)`),listener=()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.dprQuery!==query2||this.onDprChange()};this.dprQuery=query2,this.dprChangeListener=listener,query2.addEventListener("change",listener)}clearDprWatcher(){this.dprQuery&&this.dprChangeListener&&this.dprQuery.removeEventListener("change",this.dprChangeListener),this.dprQuery=void 0,this.dprChangeListener=void 0}willUpdate(changed){super.willUpdate(changed),(changed.has("data")||!this.hasUpdated)&&this.rebuildCanonicalMatrixData(),(changed.has("annotations")||changed.has("legendStops")||changed.has("colorSteps")||!this.hasUpdated)&&this.rebuildBoundedDecorations();const accessibleModeChanged=changed.has("accessibleCells")&&this.hasUpdated,collectionChanged=changed.has("data")||changed.has("cellInteractive"),activeRenderedControl=collectionChanged||accessibleModeChanged?activeElementIn(this.shadowRoot):null,activeAccessibleCell=activeRenderedControl?.matches('[part="cell"]')?activeRenderedControl:null,renderedAccessibleCells=activeAccessibleCell?.matches('[part="cell"]')?[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]]:[],accessibleFocusSnapshot=activeAccessibleCell?.matches('[part="cell"]')?{identity:activeAccessibleCell.dataset.cellIdentity,index:renderedAccessibleCells.indexOf(activeAccessibleCell)}:void 0;if(collectionChanged&&(this.focusedCell=null,this.hoverCell=null,this.liveText=""),changed.has("data")||changed.has("locale")||!this.hasUpdated){this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays,this.normalizedFirstDayOfWeek,this.calendarMonthLabelText,this.effectiveLocale),this.cachedCalendarSortedValues=this.cachedCalendarGrid.cells.map(cell=>cell.value).filter(value=>Number.isFinite(value)&&value>=0).sort((a,b)=>a-b),this.cachedCalendarCellsByPos=new Map(this.cachedCalendarGrid.cells.map(cell=>[`${cell.week}:${cell.weekday}`,cell])),this.cachedCalendarCellsByDate=new Map(this.cachedCalendarGrid.cells.map(cell=>[cell.date,cell]));const{firstWeekStart,weekCount}=this.cachedCalendarGrid;this.cachedCalendarDateByPos=Array.from({length:weekCount*7},(_,index)=>isoDateAtOffset(firstWeekStart,index))}if(changed.has("colorSteps")||!this.hasUpdated){const colorSteps=this.cachedColorSteps.map(sanitizeCssColor);colorSteps.length>=2&&colorSteps.every(color=>color!==void 0)?this.style.setProperty("--lr-heatmap-color-steps-gradient",`linear-gradient(to right, ${colorSteps.join(", ")})`):this.style.removeProperty("--lr-heatmap-color-steps-gradient")}if((changed.has("data")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),accessibleFocusSnapshot){const positions=this.accessibleCellPositions(),target=(accessibleFocusSnapshot.identity==null?void 0:positions.find(pos=>this.accessibleCellIdentity(pos)===accessibleFocusSnapshot.identity))??positions[Math.min(Math.max(accessibleFocusSnapshot.index,0),positions.length-1)]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeAccessibleCell??void 0,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}if(accessibleModeChanged){const previouslyAccessible=changed.get("accessibleCells")===!0;if(previouslyAccessible&&!this.accessibleCells&&activeAccessibleCell){const key=activeAccessibleCell.dataset.cellKey,target=key?this.accessibleCellAtKey(key):null;target&&(this.focusedCell=target,this.liveText=this.resolveCellText(target)),this.pendingAccessibleFocus="canvas",this.pendingAccessibleFocusOrigin=activeAccessibleCell,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}else if(!previouslyAccessible&&this.accessibleCells&&activeRenderedControl?.matches('[part="canvas"]')){const positions=this.accessibleCellPositions(),target=this.focusedCell?positions.find(pos=>this.samePos(pos,this.focusedCell))??positions[0]??null:positions[0]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeRenderedControl,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}}const bounds=this.cachedValueRange,range=bounds?`${this.formatNumericValue(bounds[0])}\u2013${this.formatNumericValue(bounds[1])}`:this.localize("heatmapNoDataValue"),valueLabel=this.localizedValueLabel();let label;if(this.effectiveMode==="calendar")label=this.localize("heatmapCalendarLabel",void 0,{days:this.formatCount(this.cachedCalendarGrid.cells.length),label:valueLabel,range});else{const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;label=this.localize("heatmapMatrixLabel",void 0,{rows:this.formatCount(rows),cols:this.formatCount(cols),label:valueLabel,range})}const selectedText=this.selectedCellDescription(),generatedAriaLabel=[label,selectedText,this.projectionDescription()].filter(Boolean).join(" ");this.generatedAriaLabel=generatedAriaLabel,this.syncingGeneratedSemantics=!0;try{this.authorRole===null&&this.setAttribute("role","group"),this.authorAriaLabel===null&&this.setAttribute("aria-label",generatedAriaLabel)}finally{this.syncingGeneratedSemantics=!1}}rebuildBoundedDecorations(){this.cachedAnnotations=this.annotations.slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedLegendStops=(this.legendStops??[]).slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedColorSteps=(this.colorSteps??[]).slice(0,MAX_HEATMAP_DECORATIONS),this.cachedCalendarAnnotationDates=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.date==null?[]:[annotation.date])),this.cachedMatrixAnnotationPositions=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.row==null||annotation.col==null?[]:[`${annotation.row}:${annotation.col}`])),this.decorationProjectionTruncated=this.annotations.length>MAX_HEATMAP_DECORATIONS||(this.legendStops?.length??0)>MAX_HEATMAP_DECORATIONS||(this.colorSteps?.length??0)>MAX_HEATMAP_DECORATIONS}get projectionTruncated(){return this.decorationProjectionTruncated||(this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated)}get cellProjectionTruncated(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated}projectedCellCount(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount*7:this.matrixRowLabels.length*this.matrixColLabels.length}projectionDescription(){const messages=[];return this.cellProjectionTruncated&&messages.push(this.localize("heatmapProjectionLimit",void 0,{count:this.formatCount(this.projectedCellCount())})),this.decorationProjectionTruncated&&messages.push(this.localize("heatmapDecorationLimit",void 0,{count:this.formatCount(MAX_HEATMAP_DECORATIONS)})),messages.join(" ")}rebuildCanonicalMatrixData(){if(this.data.kind!=="matrix"){this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1};return}const colCount=Math.min(this.data.colLabels.length,MAX_HEATMAP_CELLS),rowLimit=colCount===0?Math.min(this.data.rowLabels.length,MAX_HEATMAP_CELLS):Math.floor(MAX_HEATMAP_CELLS/colCount),rowCount=Math.min(this.data.rowLabels.length,rowLimit),rowLabels=this.data.rowLabels.slice(0,rowCount).map(String),colLabels=this.data.colLabels.slice(0,colCount).map(String),source=this.data,values=Array.from({length:rowCount},(_,row)=>Array.from({length:colCount},(_2,col)=>source.values[row]?.[col]??-1));this.cachedMatrixData={rowLabels,colLabels,values,truncated:rowCount!==this.data.rowLabels.length||colCount!==this.data.colLabels.length||this.data.values.some((row,index)=>index>=rowCount||row.length>colCount)}}selectedCellDescription(){if(!this.selectedCell)return"";if(this.effectiveMode==="calendar"){if(this.selectedCell.date==null)return"";const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);return match?this.localize("heatmapSelectedCellLabel",void 0,{cell:this.calendarCellText({week:match.week,weekday:match.weekday,date:match.date})}):""}const{row,col}=this.selectedCell;return row==null||col==null||row<0||row>=this.matrixRowLabels.length||col<0||col>=this.matrixColLabels.length?"":this.localize("heatmapSelectedCellLabel",void 0,{cell:this.matrixCellText({row,col})})}computeValueRange(){const source=this.effectiveMode==="calendar"?this.cachedCalendarGrid.cells.map(cell=>cell.value):this.matrixValues.flat();return minMax(source.filter(v=>Number.isFinite(v)&&v>=0))}localizedValueLabel(){return this.valueLabel===void 0?this.localize("heatmapValueLabel"):this.valueLabel}formatNumericValue(value){return getNumberFormat(this.effectiveLocale||void 0).format(value)}updated(changed){if(super.updated(changed),["data","cellSize","maxCellSize","minCellSize","valueLabel","scale","fitToWidth","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","legendStops","accessibleCells","accessibleTargetSizePx","locale"].some(name=>changed.has(name))){if(changed.has("focusedCell")&&[...changed.keys()].every(key=>key==="focusedCell"||key==="liveText")&&this.repaintFocusRing(changed.get("focusedCell")))return;this.requestDraw()}const pending=this.pendingAccessibleFocus;if(pending===void 0)return;this.pendingAccessibleFocus=void 0;const origin=this.pendingAccessibleFocusOrigin;this.pendingAccessibleFocusOrigin=void 0;const generation=this.accessibleFocusGeneration;this.scheduleAfterUpdate(()=>{try{if(generation!==this.accessibleFocusGeneration||!this.isConnected)return;if(origin){const internalActive=activeElementIn(this.shadowRoot),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return}if(pending==="base"){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}if(pending==="canvas"){this.shadowRoot?.querySelector('[part="canvas"]')?.focus();return}const identity=this.accessibleCellIdentity(pending);[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellIdentity===identity)?.focus()}finally{this.restoringAccessibleFocus=!1}},"heatmap-accessible-focus")}refreshTheme(){this.cachedRamp=null,this.refreshAccessibleTargetSize()||this.requestDraw()}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssLength(raw,{host:this}),next=resolved!==void 0&&Number.isFinite(resolved)&&resolved>0?resolved:DEFAULT_ACCESSIBLE_TARGET_SIZE_PX;return next===this.accessibleTargetSizePx?!1:(this.accessibleTargetSizePx=next,!0)}scaleEndpoints(cs){const lo=cs.getPropertyValue("--lr-heatmap-scale-lo").trim()||cs.getPropertyValue("--_lr-heatmap-scale-lo").trim()||FALLBACK_SCALE_LO,hi=cs.getPropertyValue("--lr-heatmap-scale-hi").trim()||cs.getPropertyValue("--_lr-heatmap-scale-hi").trim()||FALLBACK_SCALE_HI;return[lo,hi]}labelColor(cs){return cs.getPropertyValue("--lr-color-text-quiet").trim()||"#6b7280"}labelFont(cs){return cs.getPropertyValue("--lr-heatmap-label-font").trim()||cs.getPropertyValue("--_lr-heatmap-label-font").trim()||FALLBACK_LABEL_FONT}noDataFill(cs){return cs.getPropertyValue("--lr-heatmap-no-data-fill").trim()||cs.getPropertyValue("--_lr-heatmap-no-data-fill").trim()||FALLBACK_NO_DATA_FILL}focusRingColor(cs){return cs.getPropertyValue("--lr-heatmap-focus-ring-color").trim()||cs.getPropertyValue("--_lr-heatmap-focus-ring-color").trim()||FALLBACK_FOCUS_RING_COLOR}annotationColor(cs){return cs.getPropertyValue("--lr-heatmap-annotation-color").trim()||cs.getPropertyValue("--_lr-heatmap-annotation-color").trim()||FALLBACK_ANNOTATION_COLOR}selectedColor(cs){return cs.getPropertyValue("--lr-heatmap-selected-color").trim()||cs.getPropertyValue("--_lr-heatmap-selected-color").trim()||FALLBACK_SELECTED_COLOR}strokeCellState(ctx,x,y,size,state2,color){const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(size-RING_LINE_WIDTH-1)/2)),extent=Math.max(1,size-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),ctx.strokeRect(x+inset,y+inset,extent,extent),ctx.setLineDash?.([])}isSelectedPos(pos){return this.selectedCell?"week"in pos?this.selectedCell.date==null?!1:this.calendarCellAt(pos).date===this.selectedCell.date:this.selectedCell.row===pos.row&&this.selectedCell.col===pos.col:!1}draw(){if(!this.canvasVisible){this.drawDirty=!0;return}this.drawDirty=!1,this.canvasHasContent=!1,this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.canvasVisible&&this.draw()}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas)return!1;const current=this.focusedCell;if(this.effectiveMode==="calendar"){if(previous&&!("week"in previous)||current&&!("week"in current))return!1;this.repaintCalendarFocusCell(previous&&"week"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintCalendarFocusCell(current)}else{if(previous&&!("row"in previous)||current&&!("row"in current))return!1;this.repaintMatrixFocusCell(previous&&"row"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintMatrixFocusCell(current)}return!0}cancelDrawFrame(){const request=this.drawFrameRequest;request&&request.owner.cancelAnimationFrame(request.handle),this.drawFrameRequest=void 0}resolveColorStep(color,fallback){const safe=sanitizeCssColor(color);if(!safe)return fallback;const scope=this.ownerDocument.createElement("span"),probe=this.ownerDocument.createElement("span");scope.hidden=!0,scope.style.color=fallback,probe.style.color=safe,scope.append(probe),this.renderRoot.append(scope);try{return this.ownerDocument.defaultView?.getComputedStyle(probe).color.trim()||fallback}finally{scope.remove()}}colorRamp(bucketCount,cs){const steps=this.cachedColorSteps;if(steps&&steps.length>=2){const key2=`steps ${steps.join(" ")}`;if(this.cachedRamp?.key===key2)return this.cachedRamp;const resolved=steps.map((color,index)=>this.resolveColorStep(color,index===steps.length-1?FALLBACK_SCALE_HI:FALLBACK_SCALE_LO)),colors2=resolved.map(color=>formatRgb(resolveRgb(color,FALLBACK_SCALE_LO,this.ownerDocument))),loRgb2=resolveRgb(resolved[0],FALLBACK_SCALE_LO,this.ownerDocument),hiRgb2=resolveRgb(resolved[resolved.length-1],FALLBACK_SCALE_HI,this.ownerDocument);return this.cachedRamp={key:key2,colors:colors2,loRgb:loRgb2,hiRgb:hiRgb2},this.cachedRamp}const[scaleLo,scaleHi]=this.scaleEndpoints(cs),normalizedBucketCount=normalizeBucketCount(bucketCount),key=`${scaleLo}\0${scaleHi}\0${normalizedBucketCount}`;if(this.cachedRamp?.key===key)return this.cachedRamp;const loRgb=resolveRgb(scaleLo,FALLBACK_SCALE_LO,this.ownerDocument),hiRgb=resolveRgb(scaleHi,FALLBACK_SCALE_HI,this.ownerDocument),colors=Array.from({length:normalizedBucketCount},(_,i)=>mixRgb(loRgb,hiRgb,i/(normalizedBucketCount-1)));return this.cachedRamp={key,colors,loRgb,hiRgb},this.cachedRamp}calendarCellSize(){const{weekCount}=this.cachedCalendarGrid;let size;if(this.fitToWidth&&weekCount>0){const hostWidth=this.clientWidth||CAL_PAD_LEFT+weekCount*(this.cellSize+CAL_GAP);size=this.clampFitCellSize((hostWidth-CAL_PAD_LEFT)/weekCount-CAL_GAP)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}clampFitCellSize(size){const floored=finiteRange(size,FIT_MIN_CELL,Math.max(FIT_MIN_CELL,this.minCellSize??FIT_MIN_CELL));return this.maxCellSize==null?floored:Math.min(floored,this.maxCellSize)}columnXFor(week){return this.calendarColumnPositions()[week]??CAL_PAD_LEFT}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const cellSize=this.calendarCellSize(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?CAL_PAD_LEFT:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedColumnGeometry={callback,cellSize,weekCount,positions},positions}calendarRowPositions(){const cellSize=this.calendarCellSize(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+CAL_GAP;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedRowGeometry={callback,cellSize,positions},positions}weekAtX(x,weekCount){const positions=this.calendarColumnPositions(),cellSize=this.calendarCellSize();for(let week=0;week<weekCount;week++){const start=positions[week];if(x>=start&&x<start+cellSize)return week}return null}weekdayAtY(y){const positions=this.calendarRowPositions(),cellSize=this.calendarCellSize();for(let weekday=0;weekday<7;weekday++){const start=positions[weekday];if(y>=start&&y<start+cellSize)return weekday}return null}weekdayLabels(firstWeekStart){const formatter=getDateTimeFormat(this.effectiveLocale||void 0,{weekday:"short",timeZone:"UTC"}),labels=["","","","","","",""];for(const weekday of[1,3,5]){const row=(weekday-this.normalizedFirstDayOfWeek+7)%7;labels[row]=this.calendarWeekdayLabelText?.(weekday)??formatter.format(new Date(firstWeekStart.getTime()+row*MS_PER_DAY))}return labels}drawCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cellSize=this.calendarCellSize(),w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const buckets=normalizeBucketCount(this.bucketCount),ramp=this.colorRamp(buckets,cs).colors,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const value=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(value<0||!Number.isFinite(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=linearBucket(value,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,buckets)];ctx.fillRect(x,y,cellSize,cellSize)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.date==null)continue;const match=this.cachedCalendarCellsByDate.get(ann.date);if(!match)continue;const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.date!=null){const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);if(match){const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"week"in this.focusedCell){const{week,weekday}=this.focusedCell;if(week<weekCount&&weekday<7){const x=this.columnXFor(week),y=this.rowYFor(weekday);this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const m of monthLabels)ctx.fillText(m.label,this.columnXFor(m.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)}),this.canvasHasContent=!0}matrixCellSize(cols){let size;if(this.fitToWidth&&cols>0){const hostWidth=this.clientWidth||PAD_LEFT+cols*this.cellSize;size=this.clampFitCellSize((hostWidth-PAD_LEFT)/cols)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}paintMatrixCell(ctx,row,col,cellSize,cs,rampData,noDataFill){const value=this.matrixValues[row]?.[col]??-1,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.({row,col},value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(value<0||!Number.isFinite(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,rampData.colors.length);ctx.fillStyle=step<0?noDataFill:rampData.colors[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=rampData.colors[linearBucket(value,lo,hi,rampData.colors.length)]:ctx.fillStyle=mixRgb(rampData.loRgb,rampData.hiRgb,linearAlpha(value,lo,hi));ctx.fillRect(PAD_LEFT+col*cellSize,PAD_TOP+row*cellSize,cellSize-1,cellSize-1)}paintMatrixFocusOverlays(ctx,row,col,cellSize,cs){const x=PAD_LEFT+col*cellSize,y=PAD_TOP+row*cellSize;this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),this.selectedCell?.row===row&&this.selectedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintMatrixFocusCell(pos){if(!pos||!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(pos.row<0||pos.row>=rows||pos.col<0||pos.col>=cols)return;const cellSize=this.matrixCellSize(cols),x=PAD_LEFT+pos.col*cellSize,y=PAD_TOP+pos.row*cellSize,ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);cs&&(this.paintMatrixCell(ctx,pos.row,pos.col,cellSize,cs,this.colorRamp(RAMP_STEPS,cs),this.noDataFill(cs)),this.paintMatrixFocusOverlays(ctx,pos.row,pos.col,cellSize,cs))}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(value<0||!Number.isFinite(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=ramp[linearBucket(value,lo,hi,ramp.length)]:ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,ramp.length)];ctx.fillRect(this.columnXFor(week),this.rowYFor(weekday),cellSize,cellSize)}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),matches=candidate=>candidate?.date===date;this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),matches(this.selectedCell??void 0)&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"week"in this.focusedCell&&this.focusedCell.week===week&&this.focusedCell.weekday===weekday&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintCalendarFocusCell(pos){if(!pos||!this.canvas)return;const{weekCount,firstWeekStart}=this.cachedCalendarGrid;if(pos.week<0||pos.week>=weekCount||pos.weekday<0||pos.weekday>=7)return;const cellSize=this.calendarCellSize(),x=this.columnXFor(pos.week),y=this.rowYFor(pos.weekday),ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors;this.paintCalendarCell(ctx,pos.week,pos.weekday,cellSize,cs,ramp,this.noDataFill(cs)),this.paintCalendarFocusOverlays(ctx,pos.week,pos.weekday,cellSize,cs),ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const month of this.cachedCalendarGrid.monthLabels)ctx.fillText(month.label,this.columnXFor(month.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)})}drawMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length,cellSize=this.matrixCellSize(cols),w=PAD_LEFT+cols*cellSize,h=PAD_TOP+rows*cellSize,dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,rampData=this.colorRamp(RAMP_STEPS,cs),ramp=rampData.colors,{loRgb,hiRgb}=rampData,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){const v=this.matrixValues[r]?.[c]??-1,x=PAD_LEFT+c*cellSize,y=PAD_TOP+r*cellSize,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(override,cs);else if(v<0||!Number.isFinite(v))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(v,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=linearBucket(v,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else{const t=linearAlpha(v,lo,hi);ctx.fillStyle=mixRgb(loRgb,hiRgb,t)}ctx.fillRect(x,y,cellSize-1,cellSize-1)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.row==null||ann.col==null||ann.row<0||ann.row>=rows||ann.col<0||ann.col>=cols)continue;const x=PAD_LEFT+ann.col*cellSize,y=PAD_TOP+ann.row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.row!=null&&this.selectedCell.col!=null){const{row,col}=this.selectedCell;if(row>=0&&row<rows&&col>=0&&col<cols){const x=PAD_LEFT+col*cellSize,y=PAD_TOP+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}if(this.focusedCell&&"row"in this.focusedCell){const{row,col}=this.focusedCell;if(row<rows&&col<cols){const x=PAD_LEFT+col*cellSize,y=PAD_TOP+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs),this.matrixRowLabels.forEach((label,r)=>{ctx.fillText(label,4,PAD_TOP+r*cellSize+cellSize/2+3)}),this.matrixColLabels.forEach((label,c)=>{ctx.fillText(label,PAD_LEFT+c*cellSize+2,PAD_TOP-6)}),this.canvasHasContent=!0}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return null;const cellSize=this.matrixCellSize(cols),col=Math.floor((x-PAD_LEFT)/cellSize),row=Math.floor((y-PAD_TOP)/cellSize);if(row<0||row>=rows||col<0||col>=cols)return null;const pos={row,col};return this.isCellInteractive(pos)?pos:null}firstInteractiveMatrixCell(rows,cols){for(let r=0;r<rows;r++)for(let c=0;c<cols;c++)if(this.isCellInteractive({row:r,col:c}))return{row:r,col:c};return null}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){let r=row,c=col;for(;;){const nr=Math.min(rows-1,Math.max(0,r+dRow)),nc=Math.min(cols-1,Math.max(0,c+dCol));if(nr===r&&nc===c)return{row,col};if(r=nr,c=nc,this.isCellInteractive({row:r,col:c}))return{row:r,col:c}}}firstInteractiveCalendarCell(weekCount){for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);if(this.isCellInteractive(pos))return pos}return null}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){let w=week,d=weekday;for(;;){const nw=Math.min(weekCount-1,Math.max(0,w+dWeek)),nd=Math.min(6,Math.max(0,d+dWeekday));if(nw===w&&nd===d)return this.calendarPos(week,weekday);w=nw,d=nd;const pos=this.calendarPos(w,d);if(this.isCellInteractive(pos))return pos}}hitTestCalendar(x,y){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return null;const week=this.weekAtX(x,weekCount),weekday=this.weekdayAtY(y);if(week===null||weekday===null)return null;const pos=this.calendarPos(week,weekday);return this.isCellInteractive(pos)?pos:null}calendarCellAt(pos){const match=this.cachedCalendarCellsByPos.get(`${pos.week}:${pos.weekday}`);return match?{date:match.date,value:match.value}:{date:this.calendarDateAt(pos.week,pos.weekday),value:-1}}calendarDateAt(week,weekday){const index=week*7+weekday;return this.cachedCalendarDateByPos[index]??isoDateAtOffset(this.cachedCalendarGrid.firstWeekStart,index)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){if("week"in pos){const cellSize2=this.calendarCellSize();return{x:this.columnXFor(pos.week),y:this.rowYFor(pos.weekday),w:cellSize2,h:cellSize2}}const cellSize=this.matrixCellSize(this.matrixColLabels.length);return{x:PAD_LEFT+pos.col*cellSize,y:PAD_TOP+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}defaultCellText(pos){return"week"in pos?this.calendarCellText(pos):this.matrixCellText(pos)}matrixCellText(pos){const rowLabel=this.matrixRowLabels[pos.row]??this.localize("heatmapDefaultRowLabel",void 0,{n:this.formatCount(pos.row+1)}),colLabel=this.matrixColLabels[pos.col]??this.localize("heatmapDefaultColLabel",void 0,{n:this.formatCount(pos.col+1)}),v=this.matrixValues[pos.row]?.[pos.col],valueText=v==null||v<0||!Number.isFinite(v)?this.localize("heatmapNoDataValue"):this.formatNumericValue(v);return this.localize("heatmapMatrixCellLabel",void 0,{row:rowLabel,col:colLabel,value:valueText})}calendarCellText(pos){const{date,value}=this.calendarCellAt(pos),label=parseIsoDate(date).toLocaleString(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}),valueText=value<0||!Number.isFinite(value)?this.localize("heatmapNoDataValue"):this.formatNumericValue(value);return this.localize("heatmapCalendarCellLabel",void 0,{date:label,value:valueText})}valueAt(pos){return"week"in pos?this.calendarCellAt(pos).value:this.matrixValues[pos.row]?.[pos.col]??-1}resolveCellText(pos){return this.cellText?this.cellText(pos,this.valueAt(pos)):this.defaultCellText(pos)}isCellInteractive(pos){return this.cellInteractive?.(pos,this.valueAt(pos))??!0}announce(pos){const text=this.resolveCellText(pos),announcement=this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcementSink?.announce(announcement)}emitCellClick(pos){if(this.isCellInteractive(pos))if("week"in pos){const{date,value}=this.calendarCellAt(pos);this.emit("lr-cell-click",{date,value})}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;this.emit("lr-cell-click",{row:pos.row,col:pos.col,value})}}tooltipStyle(pos){const rect=this.cellRect(pos);return{left:`${rect.x+rect.w/2}px`,top:`${rect.y}px`}}samePos(a,b){return a===b?!0:!a||!b?!1:"week"in a&&"week"in b?a.week===b.week&&a.weekday===b.weekday:"row"in a&&"row"in b?a.row===b.row&&a.col===b.col:!1}onMatrixKeyDown(e){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("row"in this.focusedCell)){const next2=this.firstInteractiveMatrixCell(rows,cols);if(!next2)return;this.focusedCell=next2,this.announce(next2);return}const{row,col}=this.focusedCell;let dRow=0,dCol=0;e.key==="ArrowUp"?dRow=-1:e.key==="ArrowDown"?dRow=1:e.key==="ArrowLeft"?dCol=-1:e.key==="ArrowRight"&&(dCol=1);const next=this.nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols);this.focusedCell=next,this.announce(next)}onCalendarKeyDown(e){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell);return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("week"in this.focusedCell)){const next2=this.firstInteractiveCalendarCell(weekCount);if(!next2)return;this.focusedCell=next2,this.announce(next2);return}const{week,weekday}=this.focusedCell;let dWeek=0,dWeekday=0;e.key==="ArrowUp"?dWeekday=-1:e.key==="ArrowDown"?dWeekday=1:e.key==="ArrowLeft"?dWeek=-1:e.key==="ArrowRight"&&(dWeek=1);const next=this.nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount);this.focusedCell=next,this.announce(next)}resolveCanvasColor(value,cs){const cached=this.canvasColorCache.get(value);if(cached!==void 0)return cached;const fallback=this.noDataFill(cs);let candidate=value;if(value.includes("var(")){if(this.colorProbe||(this.colorProbe=this.ownerDocument.createElement("span"),this.colorProbe.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;",this.shadowRoot.appendChild(this.colorProbe)),this.colorProbe.style.color="",this.colorProbe.style.color=value,!this.colorProbe.style.color)return this.canvasColorCache.set(value,fallback),fallback;candidate=this.ownerDocument.defaultView?.getComputedStyle(this.colorProbe).color||fallback}const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return fallback;ctx.fillStyle="rgb(1, 2, 3)";const firstSentinel=ctx.fillStyle;ctx.fillStyle=candidate;let resolved=ctx.fillStyle;if(resolved===firstSentinel){ctx.fillStyle="rgb(4, 5, 6)";const secondSentinel=ctx.fillStyle;ctx.fillStyle=candidate,resolved=ctx.fillStyle,resolved===secondSentinel&&(resolved=fallback)}return this.canvasColorCache.set(value,resolved),resolved}rebuildAccessiblePositions(){const positions=[];if(this.effectiveMode==="calendar"){const{weekCount}=this.cachedCalendarGrid;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);this.isCellInteractive(pos)&&positions.push(pos)}}else for(let row=0;row<this.matrixRowLabels.length;row++)for(let col=0;col<this.matrixColLabels.length;col++){const pos={row,col};this.isCellInteractive(pos)&&positions.push(pos)}this.cachedAccessiblePositions=positions,this.cachedAccessiblePositionsByKey=new Map(positions.map(position=>[this.accessibleCellKey(position),position])),this.cachedAccessiblePositionIndexByKey=new Map(positions.map((position,index)=>[this.accessibleCellKey(position),index]))}accessibleCellPositions(){return this.cachedAccessiblePositions}accessibleCellKey(pos){return"week"in pos?`calendar-${pos.week}-${pos.weekday}`:`matrix-${pos.row}-${pos.col}`}accessibleCellIdentity(pos){return"week"in pos?pos.date:this.accessibleCellKey(pos)}accessibleCellAtKey(key){return this.cachedAccessiblePositionsByKey.get(key)??null}focusAccessibleCell(pos){pos&&this.updateComplete.then(()=>{[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellKey===this.accessibleCellKey(pos))?.focus()})}renderAccessibleCells(){if(!this.accessibleCells)return html``;const positions=this.accessibleCellPositions(),tabStop=this.focusedCell??positions[0]??null,focusIndex=tabStop?this.cachedAccessiblePositionIndexByKey.get(this.accessibleCellKey(tabStop))??0:0,start=Math.max(0,Math.min(Math.max(0,positions.length-MAX_ACCESSIBLE_HEATMAP_CELLS),focusIndex-Math.floor(MAX_ACCESSIBLE_HEATMAP_CELLS/2))),renderedPositions=positions.slice(start,start+MAX_ACCESSIBLE_HEATMAP_CELLS),renderedRows=new Map;for(const pos of renderedPositions){const rowIndex="week"in pos?pos.weekday+1:pos.row+1,row=renderedRows.get(rowIndex);row?row.push(pos):renderedRows.set(rowIndex,[pos])}const rowCount=this.effectiveMode==="calendar"?7:this.matrixRowLabels.length,colCount=this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount:this.matrixColLabels.length;return html`
|
|
2
2
|
<div
|
|
3
3
|
part="cells"
|
|
4
4
|
role="grid"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{chevronIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{styles}from"./pagination.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{sizes}from"../../../internal/sizes.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_items,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationApplied,LYRA_DEFAULT_paginationEmptySummary,LYRA_DEFAULT_paginationFirstPage,LYRA_DEFAULT_paginationJumpToPage,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_paginationLastPage,LYRA_DEFAULT_paginationPage,LYRA_DEFAULT_paginationSummary,LYRA_DEFAULT_previous,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";function normalizePaginationFormat(value){return value==="compact"?"compact":"standard"}const MAX_PAGE_SLOTS=101,MAX_WINDOW_COUNT=25;function pageSequence(from,to){return to<from?[]:Array.from({length:to-from+1},(_,offset)=>from+offset)}function paginationItems(current,totalPages,siblingCount,boundaryCount){if(totalPages<=0)return[];const asPage=page=>({type:"page",page}),budget=Math.min(boundaryCount*2+siblingCount*2+3,MAX_PAGE_SLOTS);if(totalPages<=budget)return pageSequence(1,totalPages).map(asPage);const windowFloor=boundaryCount+1,windowCeiling=totalPages-boundaryCount;let from=current-siblingCount,to=current+siblingCount;from<windowFloor&&(to+=windowFloor-from,from=windowFloor),to>windowCeiling&&(from-=to-windowCeiling,to=windowCeiling),from=Math.max(from,windowFloor),to=Math.min(to,windowCeiling);let spare=(from>windowFloor?0:1)+(to<windowCeiling?0:1);for(;spare>0;){if(to<windowCeiling)to+=1;else if(from>windowFloor)from-=1;else break;spare-=1}return[...pageSequence(1,boundaryCount).map(asPage),...from>windowFloor?[{type:"gap",target:Math.max(windowFloor,from-Math.max(1,siblingCount*2+1))}]:[],...pageSequence(from,to).map(asPage),...to<windowCeiling?[{type:"gap",target:Math.min(windowCeiling,to+Math.max(1,siblingCount*2+1))}]:[],...pageSequence(totalPages-boundaryCount+1,totalPages).map(asPage)]}class LyraPagination extends LyraElement{constructor(){super(...arguments),this.page=1,this.pageSize=10,this.total=0,this.disabled=!1,this.loading=!1,this.withSummary=!1,this.size="m",this._format="standard",this.siblingCount=2,this.boundaryCount=1,this.withEdges=!1,this.withoutNav=!1,this.hideSinglePage=!1,this.hrefTemplate="",this.appearance="outlined",this.itemLabel="",this.accessibleLabel=null,this.draftPage="",this.invalidDraft=!1,this.liveText="",this.internals=attachInternalsSafely(this),this.initialized=!1,this.pendingFocusOrigin=null,this.onPageInput=event=>{const input=event.currentTarget;this.draftPage=input.value,this.invalidDraft=input.value!==""&&this.validRequestedPage(input.value)==null},this.commitPage=event=>{const input=event.currentTarget,page=this.validRequestedPage(input.value);if(page==null){this.invalidDraft=!0;return}this.requestPage(page)},this.onPageKeyDown=event=>{event.key==="Enter"&&(event.preventDefault(),this.commitPage(event))},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,items:LYRA_DEFAULT_items,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationApplied:LYRA_DEFAULT_paginationApplied,paginationEmptySummary:LYRA_DEFAULT_paginationEmptySummary,paginationFirstPage:LYRA_DEFAULT_paginationFirstPage,paginationJumpToPage:LYRA_DEFAULT_paginationJumpToPage,paginationLabel:LYRA_DEFAULT_paginationLabel,paginationLastPage:LYRA_DEFAULT_paginationLastPage,paginationPage:LYRA_DEFAULT_paginationPage,paginationSummary:LYRA_DEFAULT_paginationSummary,previous:LYRA_DEFAULT_previous,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,sizes,styles]}get format(){return this._format}set format(value){const previous=this._format;this._format=normalizePaginationFormat(value),this.requestUpdate("format",previous)}clearPendingFocus(){this.pendingFocusPage=void 0,this.pendingFocusOrigin=null}focusTargetIsInside(target){if(typeof target!="object"||!("nodeType"in target))return!1;const node=target;return this.contains(node)||this.renderRoot.contains(node)}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.clearPendingFocus(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}get primaryControl(){return this.format==="compact"?this.pageInput:this.renderRoot.querySelector('[part~="page-current"]')??void 0}focus(options){this.primaryControl?.focus(options)}blur(){this.primaryControl?.blur()}click(){this.controlsDisabled||this.primaryControl?.click()}get normalizedTotalItems(){return finiteCount(this.total)}get normalizedPageSize(){return finiteCount(this.pageSize)}get calculatedTotalPages(){return this.normalizedTotalItems===0||this.normalizedPageSize===0?0:Math.ceil(this.normalizedTotalItems/this.normalizedPageSize)}get totalPages(){return this.calculatedTotalPages}get currentPage(){return this.calculatedTotalPages===0?0:finiteInteger(this.page,1,1,this.calculatedTotalPages)}get controlsDisabled(){return this.disabled||this.loading||this.calculatedTotalPages===0}get normalizedSiblingCount(){return finiteCount(this.siblingCount,2,MAX_WINDOW_COUNT)}get normalizedBoundaryCount(){return finiteCount(this.boundaryCount,1,MAX_WINDOW_COUNT)}pageHref(page){const template=this.hrefTemplate;return typeof template=="function"?safeLinkHref(template(page)):typeof template!="string"||template===""?null:safeLinkHref(template.split("{page}").join(String(page)))}get hasHrefTemplate(){const template=this.hrefTemplate;return typeof template=="function"||typeof template=="string"&&template!==""}pageLink(page,inactive){if(!this.hasHrefTemplate)return{href:null,renderAnchor:!1};if(inactive||page<1||page>this.calculatedTotalPages)return{href:null,renderAnchor:!0};const href=this.pageHref(page);return{href,renderAnchor:href!==null}}localizedProperty(key,value){return value??this.localize(key)}formatNumber(value){return getNumberFormat(this.effectiveLocale).format(value)}summaryText(){const total=this.normalizedTotalItems,itemLabel=this.itemLabel||this.localize(total===1?"item":"items");if(this.calculatedTotalPages===0)return this.localize("paginationEmptySummary",void 0,{total:this.formatNumber(0),itemLabel});const start=(this.currentPage-1)*this.normalizedPageSize+1,end=Math.min(total,this.currentPage*this.normalizedPageSize);return this.localize("paginationSummary",void 0,{start:this.formatNumber(start),end:this.formatNumber(end),total:this.formatNumber(total),itemLabel})}willUpdate(changed){super.willUpdate(changed),setCustomState(this.internals,"disabled",this.disabled),(changed.has("page")||changed.has("pageSize")||changed.has("total"))&&(this.draftPage=this.calculatedTotalPages===0?"":String(this.currentPage),this.invalidDraft=!1),this.initialized&&changed.has("page")&&this.calculatedTotalPages>0&&(this.liveText=this.localize("paginationApplied",void 0,{page:this.formatNumber(this.currentPage),totalPages:this.formatNumber(this.calculatedTotalPages)}),this.sink?.announce(this.liveText)),this.initialized=!0}updated(changed){if(super.updated(changed),!changed.has("page")||this.pendingFocusPage===void 0)return;const requestedPage=this.pendingFocusPage,active=deepActiveElementIn(this.ownerDocument),focusMovedOutside=active!==this.pendingFocusOrigin&&active!==null&&active!==this.ownerDocument.body&&!this.focusTargetIsInside(active);if(this.clearPendingFocus(),this.currentPage!==requestedPage||focusMovedOutside)return;(this.format==="compact"?this.pageInput:this.renderRoot.querySelector('[part~="page-current"]'))?.focus()}validRequestedPage(value){if(value.trim()==="")return null;const page=Number(value);return!Number.isInteger(page)||page<1||page>this.calculatedTotalPages?null:page}requestPage(page){if(this.controlsDisabled||page===this.currentPage||page<1||page>this.calculatedTotalPages)return;const focusOrigin=deepActiveElementIn(this.ownerDocument),detail=()=>Object.freeze({page,pageSize:this.normalizedPageSize});if(this.emit("lr-before-page-change",detail(),{cancelable:!0}).defaultPrevented){this.draftPage=this.calculatedTotalPages===0?"":String(this.currentPage),this.invalidDraft=!1;return}this.pendingFocusPage=page,this.pendingFocusOrigin=focusOrigin,this.emit("lr-page-change",detail()),this.draftPage=this.calculatedTotalPages===0?"":String(this.currentPage),this.invalidDraft=!1}renderNavButton(direction){const isPrevious=direction==="previous",current=this.currentPage,label=isPrevious?this.localizedProperty("previous",this.previousLabel):this.localizedProperty("next",this.nextLabel),spent=isPrevious?current<=1:current>=this.calculatedTotalPages,target=isPrevious?current-1:current+1,inactive=this.controlsDisabled||spent,{href,renderAnchor}=this.pageLink(target,inactive),part=isPrevious?"button previous-button":"button next-button",icon=html`<span part=${isPrevious?"previous-icon":"next-icon"} aria-hidden="true"
|
|
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{live}from"lit/directives/live.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{chevronIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{styles}from"./pagination.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{sizes}from"../../../internal/sizes.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_items,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationApplied,LYRA_DEFAULT_paginationEmptySummary,LYRA_DEFAULT_paginationFirstPage,LYRA_DEFAULT_paginationJumpToPage,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_paginationLastPage,LYRA_DEFAULT_paginationPage,LYRA_DEFAULT_paginationSummary,LYRA_DEFAULT_popover,LYRA_DEFAULT_previous,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";function normalizePaginationFormat(value){return value==="compact"?"compact":"standard"}const MAX_PAGE_SLOTS=101,MAX_WINDOW_COUNT=25;function pageSequence(from,to){return to<from?[]:Array.from({length:to-from+1},(_,offset)=>from+offset)}function paginationItems(current,totalPages,siblingCount,boundaryCount){if(totalPages<=0)return[];const asPage=page=>({type:"page",page}),budget=Math.min(boundaryCount*2+siblingCount*2+3,MAX_PAGE_SLOTS);if(totalPages<=budget)return pageSequence(1,totalPages).map(asPage);const windowFloor=boundaryCount+1,windowCeiling=totalPages-boundaryCount;let from=current-siblingCount,to=current+siblingCount;from<windowFloor&&(to+=windowFloor-from,from=windowFloor),to>windowCeiling&&(from-=to-windowCeiling,to=windowCeiling),from=Math.max(from,windowFloor),to=Math.min(to,windowCeiling);let spare=(from>windowFloor?0:1)+(to<windowCeiling?0:1);for(;spare>0;){if(to<windowCeiling)to+=1;else if(from>windowFloor)from-=1;else break;spare-=1}return[...pageSequence(1,boundaryCount).map(asPage),...from>windowFloor?[{type:"gap",target:Math.max(windowFloor,from-Math.max(1,siblingCount*2+1))}]:[],...pageSequence(from,to).map(asPage),...to<windowCeiling?[{type:"gap",target:Math.min(windowCeiling,to+Math.max(1,siblingCount*2+1))}]:[],...pageSequence(totalPages-boundaryCount+1,totalPages).map(asPage)]}class LyraPagination extends LyraElement{constructor(){super(...arguments),this.page=1,this.pageSize=10,this.total=0,this.disabled=!1,this.loading=!1,this.withSummary=!1,this.size="m",this._format="standard",this.siblingCount=2,this.boundaryCount=1,this.withEdges=!1,this.withoutNav=!1,this.hideSinglePage=!1,this.hrefTemplate="",this.appearance="outlined",this.itemLabel="",this.accessibleLabel=null,this.draftPage="",this.invalidDraft=!1,this.liveText="",this.internals=attachInternalsSafely(this),this.initialized=!1,this.pendingFocusOrigin=null,this.onPageInput=event=>{const input=event.currentTarget;this.draftPage=input.value,this.invalidDraft=input.value!==""&&this.validRequestedPage(input.value)==null},this.commitPage=event=>{const input=event.currentTarget,page=this.validRequestedPage(input.value);if(page==null){this.invalidDraft=!0;return}this.requestPage(page)},this.onPageKeyDown=event=>{event.key==="Enter"&&(event.preventDefault(),this.commitPage(event))},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,items:LYRA_DEFAULT_items,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,paginationApplied:LYRA_DEFAULT_paginationApplied,paginationEmptySummary:LYRA_DEFAULT_paginationEmptySummary,paginationFirstPage:LYRA_DEFAULT_paginationFirstPage,paginationJumpToPage:LYRA_DEFAULT_paginationJumpToPage,paginationLabel:LYRA_DEFAULT_paginationLabel,paginationLastPage:LYRA_DEFAULT_paginationLastPage,paginationPage:LYRA_DEFAULT_paginationPage,paginationSummary:LYRA_DEFAULT_paginationSummary,popover:LYRA_DEFAULT_popover,previous:LYRA_DEFAULT_previous,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,sizes,styles]}get format(){return this._format}set format(value){const previous=this._format;this._format=normalizePaginationFormat(value),this.requestUpdate("format",previous)}clearPendingFocus(){this.pendingFocusPage=void 0,this.pendingFocusOrigin=null}focusTargetIsInside(target){if(typeof target!="object"||!("nodeType"in target))return!1;const node=target;return this.contains(node)||this.renderRoot.contains(node)}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.clearPendingFocus(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}get primaryControl(){return this.format==="compact"?this.pageInput:this.renderRoot.querySelector('[part~="page-current"]')??void 0}focus(options){this.primaryControl?.focus(options)}blur(){this.primaryControl?.blur()}click(){this.controlsDisabled||this.primaryControl?.click()}get normalizedTotalItems(){return finiteCount(this.total)}get normalizedPageSize(){return finiteCount(this.pageSize)}get calculatedTotalPages(){return this.normalizedTotalItems===0||this.normalizedPageSize===0?0:Math.ceil(this.normalizedTotalItems/this.normalizedPageSize)}get totalPages(){return this.calculatedTotalPages}get currentPage(){return this.calculatedTotalPages===0?0:finiteInteger(this.page,1,1,this.calculatedTotalPages)}get controlsDisabled(){return this.disabled||this.loading||this.calculatedTotalPages===0}get normalizedSiblingCount(){return finiteCount(this.siblingCount,2,MAX_WINDOW_COUNT)}get normalizedBoundaryCount(){return finiteCount(this.boundaryCount,1,MAX_WINDOW_COUNT)}pageHref(page){const template=this.hrefTemplate;return typeof template=="function"?safeLinkHref(template(page)):typeof template!="string"||template===""?null:safeLinkHref(template.split("{page}").join(String(page)))}get hasHrefTemplate(){const template=this.hrefTemplate;return typeof template=="function"||typeof template=="string"&&template!==""}pageLink(page,inactive){if(!this.hasHrefTemplate)return{href:null,renderAnchor:!1};if(inactive||page<1||page>this.calculatedTotalPages)return{href:null,renderAnchor:!0};const href=this.pageHref(page);return{href,renderAnchor:href!==null}}localizedProperty(key,value){return value??this.localize(key)}formatNumber(value){return getNumberFormat(this.effectiveLocale).format(value)}summaryText(){const total=this.normalizedTotalItems,itemLabel=this.itemLabel||this.localize(total===1?"item":"items");if(this.calculatedTotalPages===0)return this.localize("paginationEmptySummary",void 0,{total:this.formatNumber(0),itemLabel});const start=(this.currentPage-1)*this.normalizedPageSize+1,end=Math.min(total,this.currentPage*this.normalizedPageSize);return this.localize("paginationSummary",void 0,{start:this.formatNumber(start),end:this.formatNumber(end),total:this.formatNumber(total),itemLabel})}willUpdate(changed){super.willUpdate(changed),setCustomState(this.internals,"disabled",this.disabled),(changed.has("page")||changed.has("pageSize")||changed.has("total"))&&(this.draftPage=this.calculatedTotalPages===0?"":String(this.currentPage),this.invalidDraft=!1),this.initialized&&changed.has("page")&&this.calculatedTotalPages>0&&(this.liveText=this.localize("paginationApplied",void 0,{page:this.formatNumber(this.currentPage),totalPages:this.formatNumber(this.calculatedTotalPages)}),this.sink?.announce(this.liveText)),this.initialized=!0}updated(changed){if(super.updated(changed),!changed.has("page")||this.pendingFocusPage===void 0)return;const requestedPage=this.pendingFocusPage,active=deepActiveElementIn(this.ownerDocument),focusMovedOutside=active!==this.pendingFocusOrigin&&active!==null&&active!==this.ownerDocument.body&&!this.focusTargetIsInside(active);if(this.clearPendingFocus(),this.currentPage!==requestedPage||focusMovedOutside)return;(this.format==="compact"?this.pageInput:this.renderRoot.querySelector('[part~="page-current"]'))?.focus()}validRequestedPage(value){if(value.trim()==="")return null;const page=Number(value);return!Number.isInteger(page)||page<1||page>this.calculatedTotalPages?null:page}requestPage(page){if(this.controlsDisabled||page===this.currentPage||page<1||page>this.calculatedTotalPages)return;const focusOrigin=deepActiveElementIn(this.ownerDocument),detail=()=>Object.freeze({page,pageSize:this.normalizedPageSize});if(this.emit("lr-before-page-change",detail(),{cancelable:!0}).defaultPrevented){this.draftPage=this.calculatedTotalPages===0?"":String(this.currentPage),this.invalidDraft=!1;return}this.pendingFocusPage=page,this.pendingFocusOrigin=focusOrigin,this.emit("lr-page-change",detail()),this.draftPage=this.calculatedTotalPages===0?"":String(this.currentPage),this.invalidDraft=!1}renderNavButton(direction){const isPrevious=direction==="previous",current=this.currentPage,label=isPrevious?this.localizedProperty("previous",this.previousLabel):this.localizedProperty("next",this.nextLabel),spent=isPrevious?current<=1:current>=this.calculatedTotalPages,target=isPrevious?current-1:current+1,inactive=this.controlsDisabled||spent,{href,renderAnchor}=this.pageLink(target,inactive),part=isPrevious?"button previous-button":"button next-button",icon=html`<span part=${isPrevious?"previous-icon":"next-icon"} aria-hidden="true"
|
|
2
2
|
><slot name=${isPrevious?"previous-icon":"next-icon"}>${chevronIcon()}</slot></span
|
|
3
3
|
>`;return renderAnchor?html`<a
|
|
4
4
|
part=${part}
|