@aceshooting/lyra-ui 30.1.0 → 30.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/dist/ai/adapters/a2ui.d.ts +10 -4
- package/dist/ai/adapters/a2ui.js +1 -1
- package/dist/ai/adapters/ag-ui.d.ts +17 -4
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/ai/adapters/ai-sdk.js +1 -1
- package/dist/ai/runtime.js +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.d.ts +15 -0
- package/dist/components/agent-tools/mcp-app/mcp-app-protocol.js +36 -0
- package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +31 -4
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +4 -4
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/chart-prepared-data.d.ts +3 -1
- package/dist/components/charts/chart/chart-prepared-data.js +1 -1
- package/dist/components/charts/chart/chart.class.js +2 -2
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
- package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
- package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +2 -2
- package/dist/components/forms/combobox/option.class.d.ts +1 -1
- package/dist/components/forms/combobox/option.class.js +2 -2
- package/dist/components/forms/radio/radio.class.d.ts +1 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/map/map-anchor-controller.js +1 -1
- package/dist/components/media/map/map-control-chrome.js +1 -0
- package/dist/components/media/map/map-control-options.d.ts +6 -2
- package/dist/components/media/map/map-control-options.js +1 -1
- package/dist/components/media/map/map-controls-lifecycle.js +1 -1
- package/dist/components/media/map/map-controls-readiness.js +1 -0
- package/dist/components/media/map/map.class.d.ts +39 -2
- package/dist/components/media/map/map.class.js +13 -7
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +11 -11
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/events.d.ts +10 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessible-text-controller.js +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/default-label-forwarding.js +1 -0
- package/dist/internal/hierarchy-summary-source.js +1 -0
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.d.ts +8 -0
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/llms/components/lr-file-input.md +5 -0
- package/llms/components/lr-map.md +87 -14
- package/llms/components/lr-mcp-app.md +94 -4
- package/llms/components/lr-message-parts.md +18 -0
- package/llms/components/lr-pptx-viewer.md +9 -5
- package/llms/components/lr-select.md +3 -2
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +77 -3
- package/llms/shared/events-and-types.md +25 -1
- package/llms/shared/localization-and-rtl.md +29 -0
- package/llms/shared.md +131 -4
- package/locales.json +1 -1
- package/package.json +12 -8
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +5 -3
- package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
- package/skills/lyra-ui/SKILL.md +16 -8
- package/skills/lyra-ui/lyra-gen.md +86 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";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{HostDescriptionController}from"../../../internal/aria-controls.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./chat-viewport.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{AnnouncementSinkController}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_newMessages,LYRA_DEFAULT_newMessagesCount}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_jumpToLatest}from"../../../internal/default-strings/shared.generated.js";const virtualCount=list=>{const source=list.source??list.items;return Array.isArray(source)?source.length:finiteCount(source.count)};class LyraChatViewport extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="scroll"][role="log"]')),this.follow=!0,this.live="off",this.bottomThreshold=24,this.unreadStartIndex=null,this.accessibleLabel=null,this.unreadDividerTop=null,this.pendingUserIntent=!1,this.pendingUserIntentExpiryFrame=null,this.scrollbarDragActive=!1,this.isMounting=!0,this.announcements=new AnnouncementSinkController(this),this.growthFrame=null,this.armedMode=null,this.armGeneration=0,this.followFocusRepair=null,this.knownProjectedNodes=new WeakSet,this.messageElementsCache=null,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.passiveIntent={handleEvent:()=>this.markUserIntent(),passive:!0},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"||e.key===" "&&e.shiftKey)&&this.markUserIntent()},this.onScroll=()=>{const list=this.listenedVirtualList,el=list?list.scrollContainer: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.onVirtualScroll=e=>{e.composedPath()[0]===this.listenedVirtualList&&this.onScroll()},this.onSlotChange=()=>{this.messageElementsCache=null,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)this.knownProjectedNodes.has(node)||node instanceof Element&&node.hasAttribute("data-lr-chat-viewport-unread-boundary")||(this.knownProjectedNodes.add(node),node.parentNode===this&&this.announceProjectedNode(node,sink))}}static{this.defaultStrings={...super.defaultStrings,chatViewportLabel:LYRA_DEFAULT_chatViewportLabel,jumpToLatest:LYRA_DEFAULT_jumpToLatest,newMessages:LYRA_DEFAULT_newMessages,newMessagesCount:LYRA_DEFAULT_newMessagesCount}}static{this.styles=[LyraElement.styles,styles]}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.announcements.adopted()}get announcementSink(){return this.announcements.setExclusiveChannel(this.livePoliteness),this.livePoliteness?this.announcements.current(this.livePoliteness):void 0}get livePoliteness(){return this.live==="polite"||this.live==="assertive"?this.live:void 0}get messageElements(){return this.messageElementsCache??=this.collectMessageElements()}collectMessageElements(){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[only,...rest]=this.messageElements;return only&&rest.length===0&&"scrollToIndex"in only&&"scrollContainer"in only?only:null}get effectiveBottomThreshold(){return finiteRange(this.bottomThreshold,24,0)}get effectiveUnreadStartIndex(){return this.unreadStartIndex==null?null:finiteCount(this.unreadStartIndex)}connectedCallback(){super.connectedCallback(),this.announcements.setExclusiveChannel(this.livePoliteness),this.hasUpdated&&this.armObservers()}disconnectedCallback(){super.disconnectedCallback(),this.messageElementsCache=null,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.messageElementsCache=null,this.hasUpdated&&changed.has("follow")&&this.follow&&changed.get("follow")===!1){const pill=this.renderRoot.querySelector('[part="jump-pill"]');this.followFocusRepair=pill?captureComposedFocusRepair(pill,this.transcriptFocusOwner()):null}this.hasUpdated&&changed.has("unreadStartIndex")&&this.updateUnreadDividerPosition()}firstUpdated(changed){super.firstUpdated(changed),this.messageElementsCache=null,this.armObservers()}updated(changed){super.updated(changed),changed.has("live")&&this.announcements.setExclusiveChannel(this.livePoliteness),this.unreadBoundaryEl?.setAttribute("aria-label",this.localize("newMessages"));const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("follow")){if(this.follow){const behavior=wasMounting?"auto":this.pendingScrollBehavior??(prefersReducedMotion(this)?"auto":"smooth");this.pendingScrollBehavior=void 0,this.performScrollToEnd(behavior)}wasMounting||this.emit("lr-follow-change",{following:this.follow})}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)?"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;this.messageElementsCache=null;const behavior=prefersReducedMotion(this)?"auto":options?.behavior??"smooth",list=this.virtualListEl;if(list)return unreadStartIndex>=virtualCount(list)?!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.listenedVirtualList;if(list){const count=virtualCount(list);count>0&&list.scrollToIndex(count-1,{align:"end",behavior});return}const el=this.scrollEl;el&&el.scrollTo({top:el.scrollHeight,behavior})}get totalCount(){const list=this.listenedVirtualList;return list?virtualCount(list):this.messageElements.length}get unreadCount(){const unreadStartIndex=this.effectiveUnreadStartIndex;return unreadStartIndex==null?0:Math.max(0,this.totalCount-unreadStartIndex)}pillLabel(){const count=this.unreadCount;return count<=0?this.localize("jumpToLatest"):this.localize("newMessagesCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count})}updateUnreadDividerPosition(){const unreadStartIndex=this.effectiveUnreadStartIndex;if(this.listenedVirtualList||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.listenedVirtualList){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.requestUpdate()))}),this.growthFrame=frame}announcementTextFor(node){const primary=composedAccessibilityText(node);if(node.nodeType!==Node.ELEMENT_NODE||!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}announceProjectedNode(node,sink){const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();if(text){sink.announce(text);return}node.nodeType===Node.ELEMENT_NODE&&node.localName.includes("-")&&this.announceAfterRender(node)}async announceAfterRender(node){const registry=node.ownerDocument.defaultView?.customElements;!node.matches(":defined")&®istry&&!registry.get(node.localName)&&await registry.whenDefined(node.localName);try{const pending=node.updateComplete;if(pending===null||typeof pending!="object"&&typeof pending!="function"||typeof pending.then!="function")return;await pending}catch{return}const sink=this.announcementSink;if(!sink||!this.isConnected||node.parentNode!==this)return;const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}announceNewProjectedNodes(){const sink=this.announcementSink;for(const node of this.messageElements)this.knownProjectedNodes.has(node)||(this.knownProjectedNodes.add(node),!(!sink||!this.hasUpdated)&&this.announceProjectedNode(node,sink))}armObservers(){const owner=this.ownerDocument.defaultView,list=this.virtualListEl,mode=list?"virtual":"slotted";if(this.observerWindow===owner&&this.armedMode===mode&&(mode==="slotted"||this.listenedVirtualList===list))return;for(const node of this.messageElements)this.knownProjectedNodes.add(node);this.teardownObservers(),this.observerWindow=owner??void 0,this.armedMode=mode;const generation=++this.armGeneration;if(list){this.listenedVirtualList=list,list.addEventListener("lr-virtual-scroll",this.onVirtualScroll);const MutationObserverCtor=owner?.MutationObserver;list.updateComplete.then(()=>{const spacer=list.scrollContainer?.querySelector('[part="spacer"]');if(!spacer||!MutationObserverCtor||generation!==this.armGeneration)return;const observer=new MutationObserverCtor(()=>{this.contentMutationObserver===observer&&this.scheduleGrowthTick()});this.contentMutationObserver=observer,observer.observe(spacer,{attributeFilter:["style","data-item-count"]}),this.requestUpdate(),this.follow&&this.performScrollToEnd("auto")})}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)}}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-virtual-scroll",this.onVirtualScroll),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==null?this.localize("chatViewportLabel"):this.label),virtual=this.virtualListEl!==null;return html`
|
|
1
|
+
import{__decorate}from"tslib";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{HostDescriptionController}from"../../../internal/aria-controls.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./chat-viewport.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{AnnouncementSinkController}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_newMessages,LYRA_DEFAULT_newMessagesCount}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_jumpToLatest}from"../../../internal/default-strings/shared.generated.js";const virtualCount=list=>{const source=list.source??list.items;return Array.isArray(source)?source.length:finiteCount(source.count)};class LyraChatViewport extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="scroll"][role="log"]')),this.follow=!0,this.live="off",this.bottomThreshold=24,this.unreadStartIndex=null,this.accessibleLabel=null,this.unreadDividerTop=null,this.pendingUserIntent=!1,this.pendingUserIntentExpiryFrame=null,this.scrollbarDragActive=!1,this.isMounting=!0,this.announcements=new AnnouncementSinkController(this),this.growthFrame=null,this.armedMode=null,this.armGeneration=0,this.followFocusRepair=null,this.knownProjectedNodes=new WeakSet,this.messageElementsCache=null,this.markUserIntent=()=>{this.clearKeyboardScrollIntent(),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.passiveIntent={handleEvent:()=>this.markUserIntent(),passive:!0},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=>{this.clearKeyboardScrollIntent();const owner=this.listenedVirtualList?.scrollContainer??this.scrollEl,win=this.ownerDocument.defaultView;if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||!owner||!win||e.key!=="PageUp"&&e.key!=="ArrowUp"&&e.key!=="Home"&&!(e.key===" "&&e.shiftKey)||keyEventOwnedByInnerControl(e,{container:owner}))return;for(const target of e.composedPath()){if(target===owner)break;if(isHtmlElement(target)&&target.scrollHeight>target.clientHeight&&/^(auto|scroll)$/.test(win.getComputedStyle(target).overflowY))return}if(e.isTrusted&&owner.scrollTop<=0||(this.markUserIntent(),!e.isTrusted||owner.scrollTop<=0))return;let settlement,startDeadline;const cancelSettlement=()=>{settlement!==void 0&&win.cancelAnimationFrame(settlement),settlement=void 0},finish=()=>{this.keyboardScrollIntent===intent&&this.clearKeyboardScrollIntent()},stable=(position,frames)=>{settlement=win.requestAnimationFrame(()=>{settlement=void 0,!(this.keyboardScrollIntent!==intent||owner.scrollTop!==position)&&(frames>1?stable(position,frames-1):finish())})},settled=()=>{!intent.moved&&owner.scrollTop>=intent.start||(cancelSettlement(),stable(owner.scrollTop,2))},intent={owner,event:e,start:owner.scrollTop,height:owner.scrollHeight,viewport:owner.clientHeight,moved:!1,last:owner.scrollTop,moving:()=>{win.clearTimeout(startDeadline)},cleanup:()=>{win.clearTimeout(startDeadline),cancelSettlement(),owner.removeEventListener("scrollend",settled),owner.removeEventListener("focusout",finish)}};this.keyboardScrollIntent=intent,startDeadline=win.setTimeout(finish,500),owner.addEventListener("scrollend",settled),owner.addEventListener("focusout",finish)},this.onScroll=()=>{const list=this.listenedVirtualList,el=list?list.scrollContainer:this.scrollEl;if(!el)return;const keyboard=this.keyboardScrollIntent,sameGeometry=keyboard?.owner===el&&!keyboard.event.defaultPrevented&&keyboard.height===el.scrollHeight&&keyboard.viewport===el.clientHeight;keyboard&&!sameGeometry&&(this.clearKeyboardScrollIntent(),this.clearUserIntent());const keyboardCaused=sameGeometry&&el.scrollTop<keyboard.start;if(keyboardCaused&&el.scrollTop!==keyboard.last&&(keyboard.moved=!0,keyboard.last=el.scrollTop,keyboard.moving()),el.scrollHeight-el.scrollTop-el.clientHeight<=this.effectiveBottomThreshold){this.clearUserIntent(),this.follow||(this.follow=!0);return}(this.consumeUserIntent()||keyboardCaused||this.scrollbarDragActive)&&this.follow&&(this.clearKeyboardScrollIntent(),this.follow=!1)},this.onVirtualScroll=e=>{e.composedPath()[0]===this.listenedVirtualList&&this.onScroll()},this.onSlotChange=()=>{this.messageElementsCache=null,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)this.knownProjectedNodes.has(node)||node instanceof Element&&node.hasAttribute("data-lr-chat-viewport-unread-boundary")||(this.knownProjectedNodes.add(node),node.parentNode===this&&this.announceProjectedNode(node,sink))}}static{this.defaultStrings={...super.defaultStrings,chatViewportLabel:LYRA_DEFAULT_chatViewportLabel,jumpToLatest:LYRA_DEFAULT_jumpToLatest,newMessages:LYRA_DEFAULT_newMessages,newMessagesCount:LYRA_DEFAULT_newMessagesCount}}static{this.styles=[LyraElement.styles,styles]}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.announcements.adopted()}get announcementSink(){return this.announcements.setExclusiveChannel(this.livePoliteness),this.livePoliteness?this.announcements.current(this.livePoliteness):void 0}get livePoliteness(){return this.live==="polite"||this.live==="assertive"?this.live:void 0}get messageElements(){return this.messageElementsCache??=this.collectMessageElements()}collectMessageElements(){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[only,...rest]=this.messageElements;return only&&rest.length===0&&"scrollToIndex"in only&&"scrollContainer"in only?only:null}get effectiveBottomThreshold(){return finiteRange(this.bottomThreshold,24,0)}get effectiveUnreadStartIndex(){return this.unreadStartIndex==null?null:finiteCount(this.unreadStartIndex)}connectedCallback(){super.connectedCallback(),this.announcements.setExclusiveChannel(this.livePoliteness),this.hasUpdated&&this.armObservers()}disconnectedCallback(){super.disconnectedCallback(),this.messageElementsCache=null,this.teardownObservers(),this.releaseScrollbarDragListeners(),this.clearUserIntent(),this.clearKeyboardScrollIntent(),this.scrollbarDragActive=!1,this.followFocusRepair=null,this.unreadBoundaryEl?.remove(),this.unreadBoundaryEl=void 0}willUpdate(changed){if(super.willUpdate(changed),this.messageElementsCache=null,this.hasUpdated&&changed.has("follow")&&this.follow&&changed.get("follow")===!1){const pill=this.renderRoot.querySelector('[part="jump-pill"]');this.followFocusRepair=pill?captureComposedFocusRepair(pill,this.transcriptFocusOwner()):null}this.hasUpdated&&changed.has("unreadStartIndex")&&this.updateUnreadDividerPosition()}firstUpdated(changed){super.firstUpdated(changed),this.messageElementsCache=null,this.armObservers()}updated(changed){super.updated(changed),changed.has("live")&&this.announcements.setExclusiveChannel(this.livePoliteness),this.unreadBoundaryEl?.setAttribute("aria-label",this.localize("newMessages"));const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("follow")){if(this.follow){const behavior=wasMounting?"auto":this.pendingScrollBehavior??(prefersReducedMotion(this)?"auto":"smooth");this.pendingScrollBehavior=void 0,this.performScrollToEnd(behavior)}wasMounting||this.emit("lr-follow-change",{following:this.follow})}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){this.clearKeyboardScrollIntent(),this.clearUserIntent();const behavior=prefersReducedMotion(this)?"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;this.messageElementsCache=null;const behavior=prefersReducedMotion(this)?"auto":options?.behavior??"smooth",list=this.virtualListEl;if(list)return unreadStartIndex>=virtualCount(list)?!1:(this.clearKeyboardScrollIntent(),this.clearUserIntent(),list.scrollToIndex(unreadStartIndex,{align:"start",behavior}),!0);const scrollEl=this.scrollEl;return!scrollEl||this.unreadDividerTop==null?!1:(this.clearKeyboardScrollIntent(),this.clearUserIntent(),scrollEl.scrollTo({top:this.unreadDividerTop,behavior}),!0)}performScrollToEnd(behavior){const list=this.listenedVirtualList;if(list){const count=virtualCount(list);count>0&&list.scrollToIndex(count-1,{align:"end",behavior});return}const el=this.scrollEl;el&&el.scrollTo({top:el.scrollHeight,behavior})}get totalCount(){const list=this.listenedVirtualList;return list?virtualCount(list):this.messageElements.length}get unreadCount(){const unreadStartIndex=this.effectiveUnreadStartIndex;return unreadStartIndex==null?0:Math.max(0,this.totalCount-unreadStartIndex)}pillLabel(){const count=this.unreadCount;return count<=0?this.localize("jumpToLatest"):this.localize("newMessagesCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count})}updateUnreadDividerPosition(){const unreadStartIndex=this.effectiveUnreadStartIndex;if(this.listenedVirtualList||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.listenedVirtualList){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)}clearKeyboardScrollIntent(){this.keyboardScrollIntent?.cleanup(),this.keyboardScrollIntent=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.requestUpdate()))}),this.growthFrame=frame}announcementTextFor(node){const primary=composedAccessibilityText(node);if(node.nodeType!==Node.ELEMENT_NODE||!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}announceProjectedNode(node,sink){const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();if(text){sink.announce(text);return}node.nodeType===Node.ELEMENT_NODE&&node.localName.includes("-")&&this.announceAfterRender(node)}async announceAfterRender(node){const registry=node.ownerDocument.defaultView?.customElements;!node.matches(":defined")&®istry&&!registry.get(node.localName)&&await registry.whenDefined(node.localName);try{const pending=node.updateComplete;if(pending===null||typeof pending!="object"&&typeof pending!="function"||typeof pending.then!="function")return;await pending}catch{return}const sink=this.announcementSink;if(!sink||!this.isConnected||node.parentNode!==this)return;const text=this.announcementTextFor(node).replace(/\s+/g," ").trim();text&&sink.announce(text)}announceNewProjectedNodes(){const sink=this.announcementSink;for(const node of this.messageElements)this.knownProjectedNodes.has(node)||(this.knownProjectedNodes.add(node),!(!sink||!this.hasUpdated)&&this.announceProjectedNode(node,sink))}armObservers(){const owner=this.ownerDocument.defaultView,list=this.virtualListEl,mode=list?"virtual":"slotted";if(this.observerWindow===owner&&this.armedMode===mode&&(mode==="slotted"||this.listenedVirtualList===list))return;for(const node of this.messageElements)this.knownProjectedNodes.add(node);this.teardownObservers(),this.observerWindow=owner??void 0,this.armedMode=mode;const generation=++this.armGeneration;if(list){this.listenedVirtualList=list,list.addEventListener("lr-virtual-scroll",this.onVirtualScroll);const MutationObserverCtor=owner?.MutationObserver;list.updateComplete.then(()=>{const spacer=list.scrollContainer?.querySelector('[part="spacer"]');if(!spacer||!MutationObserverCtor||generation!==this.armGeneration)return;const observer=new MutationObserverCtor(()=>{this.contentMutationObserver===observer&&this.scheduleGrowthTick()});this.contentMutationObserver=observer,observer.observe(spacer,{attributeFilter:["style","data-item-count"]}),this.requestUpdate(),this.follow&&this.performScrollToEnd("auto")})}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)}}queueMicrotask(()=>{!this.isConnected||generation!==this.armGeneration||this.updateUnreadDividerPosition()})}teardownObservers(){this.clearKeyboardScrollIntent(),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-virtual-scroll",this.onVirtualScroll),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==null?this.localize("chatViewportLabel"):this.label),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
|
-
import type{MarkdownStreamingRender}from'../markdown/markdown-shared.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import type{CitationSelectEventDetail,MessagePart}from'../../../ai/types.js';import type{LyraThinkingPanelEventMap,ThinkingPanelToggleDetail}from'../../agent-tools/thinking-panel/thinking-panel.class.js';import type{LyraToolCallBlockEventMap,ToolCallBlockRenderErrorDetail,ToolCallBlockToggleDetail}from'../../agent-tools/tool-call-block/tool-call-block.class.js';import type{LyraToolCallChipEventMap}from'../../agent-tools/tool-call-chip/tool-call-chip.class.js';import type{LyraToolResultViewEventMap}from'../../agent-tools/tool-result-view/tool-result-view.class.js';import type{LyraAttachmentChipEventMap}from'../../media/attachment-chip/attachment-chip.class.js';import type{LyraCitationBadgeEventMap}from'../../retrieval/citation-badge/citation-badge.class.js';import type{LyraJsonViewerEventMap}from'../../utility/json-viewer/json-viewer.class.js';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraMarkdownEventMap}from'../markdown/markdown.class.js';import type{LyraWidgetRendererEventMap}from'../widget-renderer/widget-renderer.class.js';
|
|
1
|
+
import type{MarkdownStreamingRender}from'../markdown/markdown-shared.js';import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';import{type PropertyValues,type TemplateResult}from'lit';import type{CitationSelectEventDetail,MessagePart}from'../../../ai/types.js';import type{LyraThinkingPanelEventMap,ThinkingPanelToggleDetail}from'../../agent-tools/thinking-panel/thinking-panel.class.js';import type{LyraToolCallBlockEventMap,ToolCallBlockRenderErrorDetail,ToolCallBlockToggleDetail}from'../../agent-tools/tool-call-block/tool-call-block.class.js';import type{LyraToolCallChipEventMap}from'../../agent-tools/tool-call-chip/tool-call-chip.class.js';import type{LyraToolResultViewEventMap}from'../../agent-tools/tool-result-view/tool-result-view.class.js';import type{LyraAttachmentChipEventMap}from'../../media/attachment-chip/attachment-chip.class.js';import type{LyraCitationBadgeEventMap}from'../../retrieval/citation-badge/citation-badge.class.js';import type{LyraJsonViewerEventMap}from'../../utility/json-viewer/json-viewer.class.js';import{LyraElement}from'../../../internal/lyra-element.js';import type{LyraMarkdownEventMap}from'../markdown/markdown.class.js';import type{LyraWidgetTypeRegistry}from'../widget-renderer/registry.js';import type{LyraWidgetRendererEventMap}from'../widget-renderer/widget-renderer.class.js';
|
|
2
2
|
/**
|
|
3
3
|
* Host override for how one message part renders. Returning `undefined` delegates that part
|
|
4
4
|
* entirely to the built-in renderer, keeping every built-in affordance intact. Returning any other
|
|
@@ -44,6 +44,11 @@ export type MessagePartsToolDisplay='chip'|'block';export interface LyraMessageP
|
|
|
44
44
|
* part. `disabled` gates built-in retry and resume requests. Custom renderers own their controls.
|
|
45
45
|
*
|
|
46
46
|
* Citation ranks are derived in one linear render prepass, including for mixed streaming arrays.
|
|
47
|
+
* Built-in non-text component renderers load on first use with localized loading/error fallback.
|
|
48
|
+
* Custom-rendered parts do not load the corresponding built-in renderer. Audio stays native.
|
|
49
|
+
* Widget parts use `widgetRegistry` and the separate controlled `widgetBindingState`; unchanged
|
|
50
|
+
* widget content keeps its document identity across unrelated text updates. Widget-v2 validation
|
|
51
|
+
* and its fail-closed identity and security rules still apply.
|
|
47
52
|
*
|
|
48
53
|
* `tool-display="block"` pairs each `tool-call` part with the first `tool-result` part carrying its
|
|
49
54
|
* invocation id and renders the pair through one collapsed `<lr-tool-call-block>` at the call's
|
|
@@ -71,8 +76,8 @@ export type MessagePartsToolDisplay='chip'|'block';export interface LyraMessageP
|
|
|
71
76
|
* @event lr-toggle - Passthrough from a rendered reasoning panel or tool-call block.
|
|
72
77
|
* @event lr-tool-call-chip-select - Passthrough from a rendered tool-call chip. The
|
|
73
78
|
* `lr-tool-chip-select` alias it replaced was removed in 9.0.0.
|
|
74
|
-
* @event lr-render-error -
|
|
75
|
-
* tool-call block (`callId` included).
|
|
79
|
+
* @event lr-render-error - A lazy part renderer failed to load, or passthrough from rendered Markdown,
|
|
80
|
+
* tool-result, widget content, or tool-call block (`callId` included).
|
|
76
81
|
* @event lr-link-activate - Passthrough from rendered Markdown.
|
|
77
82
|
* @event lr-highlight-activate - Passthrough from rendered Markdown.
|
|
78
83
|
* @event lr-text-select - Passthrough from rendered Markdown.
|
|
@@ -136,6 +141,10 @@ withoutReasoning:boolean;
|
|
|
136
141
|
* delegates to the built-in renderer -- any other return fully replaces it, including that
|
|
137
142
|
* part's own interactive wiring (retry/citation/tool-call/widget events). */
|
|
138
143
|
renderPart?:MessagePartRenderer;
|
|
144
|
+
/** Immutable registry forwarded to every built-in widget part. Custom renderers own their registry.*/
|
|
145
|
+
widgetRegistry:LyraWidgetTypeRegistry;
|
|
146
|
+
/** Explicit controlled binding state shared by built-in widget parts; reassign after updates.*/
|
|
147
|
+
widgetBindingState?:unknown;
|
|
139
148
|
/** Rendering mode forwarded to built-in text and reasoning Markdown parts.*/
|
|
140
149
|
streamingRender:MarkdownStreamingRender;
|
|
141
150
|
/** Adds source-copy headers to built-in text and reasoning Markdown parts. Custom renderers replace this surface.*/
|
|
@@ -146,4 +155,4 @@ codeBlockHeader:boolean;
|
|
|
146
155
|
* even once an earlier citation rolls out of the rendered window. Opt in for a message that can
|
|
147
156
|
* grow an unusually large number of parts (e.g. a long agentic run with many interleaved
|
|
148
157
|
* tool-call/tool-result parts), where unbounded live DOM can visibly stall the main thread. */
|
|
149
|
-
maxRenderedParts:number;private knownErrorIds;private redactionByInvocation;private redactionMemo;private errorAnnouncementSink?;private suppressNextErrorAnnouncement;connectedCallback():void;disconnectedCallback():void;private get effectiveParts();private get effectiveMaxRenderedParts();private get renderedParts();protected willUpdate(changed:PropertyValues<this>):void;private projectRedactions;private redacted;protected updated(_changed:PropertyValues<this>):void;private selectCitation;private partNames;private renderToolBlock;private pairTools;private renderPartMarkdown;private renderBuiltin;private resumeDispatching;private requestResume;private renderInterruption;private renderOne;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-message-parts':LyraMessageParts;}}
|
|
158
|
+
maxRenderedParts:number;private readonly widgetDocuments;private readonly rendererLoads;private readonly failedRendererLoads;private rendererReady;private rendererFallback;private widgetDocument;private knownErrorIds;private redactionByInvocation;private redactionMemo;private errorAnnouncementSink?;private suppressNextErrorAnnouncement;connectedCallback():void;disconnectedCallback():void;private get effectiveParts();private get effectiveMaxRenderedParts();private get renderedParts();protected willUpdate(changed:PropertyValues<this>):void;private projectRedactions;private redacted;protected updated(_changed:PropertyValues<this>):void;private selectCitation;private partNames;private renderToolBlock;private pairTools;private renderPartMarkdown;private renderBuiltin;private resumeDispatching;private requestResume;private renderInterruption;private renderOne;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-message-parts':LyraMessageParts;}}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{isToolCallStatus}from"../../agent-tools/tool-status.js";import{projectedRedactionFields,redactToolDetail,TOO_MANY_REDACTION_PATHS}from"../../agent-tools/tool-redaction.js";import{literalSetConverter}from"../../../internal/converters.js";import{finiteCount}from"../../../internal/numbers.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isNonBlankIdentity,isRecord}from"../../retrieval/retrieval-identity.js";import{styles}from"./message-parts.styles.js";import{LYRA_DEFAULT_messagePartError,LYRA_DEFAULT_messagePartRetry,LYRA_DEFAULT_messagePartsLabel,LYRA_DEFAULT_streamInterrupted,LYRA_DEFAULT_streamResume}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_envListValueHidden,LYRA_DEFAULT_retry,LYRA_DEFAULT_thinkingPanelLabel}from"../../../internal/default-strings/shared.generated.js";const MESSAGE_PARTS_CONTENT_MODES=Object.freeze(["plain","markdown"]),MESSAGE_PARTS_TOOL_DISPLAY=literalSetConverter(["chip","block"],"chip"),EMPTY_REDACTED_FIELDS=Object.freeze([]),TOOL_BLOCK_EXPORTPARTS="header:tool-block-header, body:tool-block-body, args:tool-block-args, result:tool-block-result, error:tool-block-error";function resolveBlockStatus(invocation,result){const status=isToolCallStatus(invocation.status)?invocation.status:"pending";return status==="denied"||status==="incomplete"?status:status==="error"||result&&"error"in result?"error":result&&result.state==="streaming"?"running":result?"success":status}function invocationDuration(invocation){if(invocation.startedAt==null||invocation.endedAt==null)return;const diff=invocation.endedAt-invocation.startedAt;return Number.isFinite(diff)?diff:void 0}function invocationDisplayName(invocation){return typeof invocation.displayName=="string"?invocation.displayName:void 0}function normalizeMessagePartsContentMode(value){return typeof value=="string"&&MESSAGE_PARTS_CONTENT_MODES.includes(value)?value:"markdown"}class LyraMessageParts extends LyraElement{constructor(){super(...arguments),this.parts=[],this.disabled=!1,this.contentModeValue="markdown",this.toolDisplayValue="chip",this.withoutReasoning=!1,this.streamingRender="plain",this.codeBlockHeader=!1,this.maxRenderedParts=0,this.knownErrorIds=new Set,this.redactionByInvocation=new Map,this.redactionMemo=new WeakMap,this.suppressNextErrorAnnouncement=!0,this.resumeDispatching=!1}static{this.defaultStrings={...super.defaultStrings,envListValueHidden:LYRA_DEFAULT_envListValueHidden,messagePartError:LYRA_DEFAULT_messagePartError,messagePartRetry:LYRA_DEFAULT_messagePartRetry,messagePartsLabel:LYRA_DEFAULT_messagePartsLabel,retry:LYRA_DEFAULT_retry,streamInterrupted:LYRA_DEFAULT_streamInterrupted,streamResume:LYRA_DEFAULT_streamResume,thinkingPanelLabel:LYRA_DEFAULT_thinkingPanelLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["parts"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-citation-select","lr-part-retry","lr-part-resume"])}get contentMode(){return this.contentModeValue}set contentMode(value){const previous=this.contentModeValue,normalized=normalizeMessagePartsContentMode(value);this.contentModeValue=normalized,typeof value=="string"&&value!==normalized&&this.getAttribute("content-mode")!==normalized&&this.setAttribute("content-mode",normalized),this.requestUpdate("contentMode",previous,{reflect:!0,hasChanged:()=>!0})}get toolDisplay(){return this.toolDisplayValue}set toolDisplay(value){const normalized=MESSAGE_PARTS_TOOL_DISPLAY.normalizeReflected(this,"tool-display",value),previous=this.toolDisplayValue;previous!==normalized&&(this.toolDisplayValue=normalized,this.requestUpdate("toolDisplay",previous))}
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{isToolCallStatus}from"../../agent-tools/tool-status.js";import{projectedRedactionFields,redactToolDetail,TOO_MANY_REDACTION_PATHS}from"../../agent-tools/tool-redaction.js";import{literalSetConverter}from"../../../internal/converters.js";import{finiteCount}from"../../../internal/numbers.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{DEFAULT_WIDGET_TYPE_REGISTRY}from"../widget-renderer/default-registry.js";import{tag}from"../../../internal/prefix.js";import{isNonBlankIdentity,isRecord}from"../../retrieval/retrieval-identity.js";import{styles}from"./message-parts.styles.js";import{LYRA_DEFAULT_messagePartError,LYRA_DEFAULT_messagePartRetry,LYRA_DEFAULT_messagePartsLabel,LYRA_DEFAULT_streamInterrupted,LYRA_DEFAULT_streamResume}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_envListValueHidden,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_thinkingPanelLabel}from"../../../internal/default-strings/shared.generated.js";const MESSAGE_PARTS_CONTENT_MODES=Object.freeze(["plain","markdown"]),PART_RENDERER_LOADERS={"thinking-panel":()=>import("../../agent-tools/thinking-panel/thinking-panel.js"),"tool-call-block":()=>import("../../agent-tools/tool-call-block/tool-call-block.js"),"tool-call-chip":()=>import("../../agent-tools/tool-call-chip/tool-call-chip.js"),"tool-result-view":()=>import("../../agent-tools/tool-result-view/tool-result-view.js"),"citation-badge":()=>import("../../retrieval/citation-badge/citation-badge.js"),"attachment-chip":()=>import("../../media/attachment-chip/attachment-chip.js"),"json-viewer":()=>import("../../utility/json-viewer/json-viewer.js"),"widget-renderer":()=>import("../widget-renderer/widget-renderer.js"),button:()=>import("../../forms/button/button.js")};function sameWidgetSnapshot(left,right){const pending=[[left,right]],seen=new WeakMap;for(;pending.length>0;){const[a,b]=pending.pop();if(Object.is(a,b))continue;if(!a||!b||typeof a!="object"||typeof b!="object"||Array.isArray(a)!==Array.isArray(b))return!1;if(!Array.isArray(a)){const aPrototype=Object.getPrototypeOf(a),bPrototype=Object.getPrototypeOf(b);if(aPrototype!==Object.prototype&&aPrototype!==null||bPrototype!==Object.prototype&&bPrototype!==null)return!1}const paired=seen.get(a);if(paired){if(paired!==b)return!1;continue}seen.set(a,b);const aKeys=Object.keys(a);if(aKeys.length!==Object.keys(b).length)return!1;for(const key of aKeys){const aField=Object.getOwnPropertyDescriptor(a,key),bField=Object.getOwnPropertyDescriptor(b,key);if(!aField||!bField||!("value"in aField)||!("value"in bField))return!1;pending.push([aField.value,bField.value])}}return!0}const MESSAGE_PARTS_TOOL_DISPLAY=literalSetConverter(["chip","block"],"chip"),EMPTY_REDACTED_FIELDS=Object.freeze([]),TOOL_BLOCK_EXPORTPARTS="header:tool-block-header, body:tool-block-body, args:tool-block-args, result:tool-block-result, error:tool-block-error";function resolveBlockStatus(invocation,result){const status=isToolCallStatus(invocation.status)?invocation.status:"pending";return status==="denied"||status==="incomplete"?status:status==="error"||result&&"error"in result?"error":result&&result.state==="streaming"?"running":result?"success":status}function invocationDuration(invocation){if(invocation.startedAt==null||invocation.endedAt==null)return;const diff=invocation.endedAt-invocation.startedAt;return Number.isFinite(diff)?diff:void 0}function invocationDisplayName(invocation){return typeof invocation.displayName=="string"?invocation.displayName:void 0}function normalizeMessagePartsContentMode(value){return typeof value=="string"&&MESSAGE_PARTS_CONTENT_MODES.includes(value)?value:"markdown"}class LyraMessageParts extends LyraElement{constructor(){super(...arguments),this.parts=[],this.disabled=!1,this.contentModeValue="markdown",this.toolDisplayValue="chip",this.withoutReasoning=!1,this.widgetRegistry=DEFAULT_WIDGET_TYPE_REGISTRY,this.streamingRender="plain",this.codeBlockHeader=!1,this.maxRenderedParts=0,this.widgetDocuments=new Map,this.rendererLoads=new Map,this.failedRendererLoads=new Set,this.knownErrorIds=new Set,this.redactionByInvocation=new Map,this.redactionMemo=new WeakMap,this.suppressNextErrorAnnouncement=!0,this.resumeDispatching=!1}static{this.defaultStrings={...super.defaultStrings,envListValueHidden:LYRA_DEFAULT_envListValueHidden,loading:LYRA_DEFAULT_loading,messagePartError:LYRA_DEFAULT_messagePartError,messagePartRetry:LYRA_DEFAULT_messagePartRetry,messagePartsLabel:LYRA_DEFAULT_messagePartsLabel,retry:LYRA_DEFAULT_retry,streamInterrupted:LYRA_DEFAULT_streamInterrupted,streamResume:LYRA_DEFAULT_streamResume,thinkingPanelLabel:LYRA_DEFAULT_thinkingPanelLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["parts","widgetBindingState"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-citation-select","lr-part-retry","lr-part-resume"])}get contentMode(){return this.contentModeValue}set contentMode(value){const previous=this.contentModeValue,normalized=normalizeMessagePartsContentMode(value);this.contentModeValue=normalized,typeof value=="string"&&value!==normalized&&this.getAttribute("content-mode")!==normalized&&this.setAttribute("content-mode",normalized),this.requestUpdate("contentMode",previous,{reflect:!0,hasChanged:()=>!0})}get toolDisplay(){return this.toolDisplayValue}set toolDisplay(value){const normalized=MESSAGE_PARTS_TOOL_DISPLAY.normalizeReflected(this,"tool-display",value),previous=this.toolDisplayValue;previous!==normalized&&(this.toolDisplayValue=normalized,this.requestUpdate("toolDisplay",previous))}rendererReady(name){if(typeof customElements>"u"||customElements.get(tag(name)))return!0;if(!this.rendererLoads.has(name)){const loading=PART_RENDERER_LOADERS[name]().then(()=>{this.requestUpdate()}).catch(error=>{this.failedRendererLoads.add(name),this.requestUpdate(),this.emit("lr-render-error",{error})});this.rendererLoads.set(name,loading)}return!1}rendererFallback(name){return html`<span aria-busy=${this.failedRendererLoads.has(name)?"false":"true"}
|
|
2
|
+
>${this.failedRendererLoads.has(name)?this.localize("messagePartError"):this.localize("loading")}</span>`}widgetDocument(part){const cached=this.widgetDocuments.get(part.id);if(cached&&sameWidgetSnapshot(cached.root,part.widget))return cached;const document=Object.freeze({version:"2",root:part.widget});return this.widgetDocuments.set(part.id,document),document}connectedCallback(){super.connectedCallback(),this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.suppressNextErrorAnnouncement=!0,this.requestUpdate()))}disconnectedCallback(){super.disconnectedCallback(),this.widgetDocuments.clear(),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.suppressNextErrorAnnouncement=!0}get effectiveParts(){const seen=new Set;return this.parts.filter(part=>{const id=part?.id;return!isNonBlankIdentity(id)||seen.has(id)||part.type==="tool-call"&&!isRecord(part.invocation)||part.type==="citation"&&!isRecord(part.citation)||part.type==="attachment"&&!isRecord(part.document)?!1:(seen.add(id),!0)})}get effectiveMaxRenderedParts(){return finiteCount(this.maxRenderedParts,0)}get renderedParts(){const parts=this.effectiveParts,max=this.effectiveMaxRenderedParts;return max>0&&parts.length>max?parts.slice(-max):parts}willUpdate(changed){if(super.willUpdate(changed),!changed.has("parts")&&this.hasUpdated||(this.redactionByInvocation=this.projectRedactions(),!changed.has("parts")))return;const current=this.effectiveParts.filter(part=>part.type==="error");if(this.hasUpdated&&!this.suppressNextErrorAnnouncement)for(const part of current)this.knownErrorIds.has(part.id)||this.errorAnnouncementSink?.announce(part.message||this.localize("messagePartError"));this.knownErrorIds=new Set(current.map(part=>part.id))}projectRedactions(){const map=new Map,seen=new Set;for(const part of this.effectiveParts){if(part.type!=="tool-call")continue;const id=part.invocation.id;if(typeof id!="string"||seen.has(id))continue;seen.add(id);const paths=projectedRedactionFields(part.invocation.redactedFields)??TOO_MANY_REDACTION_PATHS;paths.length>0&&map.set(id,paths)}return map}redacted(part,invocationId,source){if(typeof invocationId!="string")return;const paths=this.redactionByInvocation.get(invocationId);if(!paths)return;const detail=redactToolDetail(source,paths,this.localize("envListValueHidden"),this.redactionMemo.get(part));return this.redactionMemo.set(part,detail),detail}updated(_changed){super.updated(_changed),this.suppressNextErrorAnnouncement=!1}selectCitation(event,part){event.stopPropagation(),this.emit("lr-citation-select",{citation:part.citation})}partNames(part){const parts=["part"];switch(part.type){case"text":parts.push("text");break;case"reasoning":parts.push("reasoning");break;case"tool-call":parts.push("tool-call");break;case"tool-result":parts.push("tool-result");break;case"citation":parts.push("citation");break;case"attachment":parts.push("attachment");break;case"data":parts.push("data");break;case"audio":parts.push("audio");break;case"error":parts.push("error");break}return part.state==="streaming"&&parts.push("part-streaming"),part.state==="interrupted"&&parts.push("part-interrupted"),parts.join(" ")}renderToolBlock(part,paired){if(!this.rendererReady("tool-call-block"))return this.rendererFallback("tool-call-block");const invocation=part.invocation,result=paired?paired.result:invocation.result,error=paired&&"error"in paired?paired.error:invocation.error,redactedFields=this.redactionByInvocation.get(invocation.id)??EMPTY_REDACTED_FIELDS;return html`<lr-tool-call-block
|
|
2
3
|
.name=${invocation.name}
|
|
3
4
|
.displayName=${invocationDisplayName(invocation)}
|
|
4
5
|
.callId=${invocation.id}
|
|
@@ -11,18 +12,18 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
11
12
|
exportparts=${TOOL_BLOCK_EXPORTPARTS}
|
|
12
13
|
></lr-tool-call-block>`}pairTools(parts,custom){const calls=new Map;for(const part of parts){if(part.type!=="tool-call"||custom.has(part.id))continue;const id=part.invocation.id;isNonBlankIdentity(id)&&!calls.has(id)&&calls.set(id,part.id)}const results=new Map,folded=new Set;for(const part of parts){if(part.type!=="tool-result"||part.state==="interrupted"||custom.has(part.id))continue;const id=part.invocationId;if(!isNonBlankIdentity(id))continue;const callPartId=calls.get(id);callPartId===void 0||results.has(callPartId)||(results.set(callPartId,part),folded.add(part.id))}return{custom,results,folded}}renderPartMarkdown(part){return html`<lr-markdown .content=${part.text} .streaming=${part.state==="streaming"}
|
|
13
14
|
.streamingRender=${this.streamingRender}
|
|
14
|
-
.codeBlockHeader=${this.codeBlockHeader}></lr-markdown>`}renderBuiltin(part,citationRank,pairing){switch(part.type){case"text":return this.contentMode==="markdown"?this.renderPartMarkdown(part):part.text;case"reasoning":return html`<lr-thinking-panel
|
|
15
|
+
.codeBlockHeader=${this.codeBlockHeader}></lr-markdown>`}renderBuiltin(part,citationRank,pairing){switch(part.type){case"text":return this.contentMode==="markdown"?this.renderPartMarkdown(part):part.text;case"reasoning":return this.rendererReady("thinking-panel")?html`<lr-thinking-panel
|
|
15
16
|
.label=${this.localize("thinkingPanelLabel")}
|
|
16
17
|
.mode=${part.state==="streaming"?"live":"post-hoc"}
|
|
17
18
|
?expanded=${part.collapsed===!1}
|
|
18
19
|
>${this.contentMode==="markdown"?this.renderPartMarkdown(part):part.text}</lr-thinking-panel
|
|
19
|
-
|
|
20
|
+
>`:this.rendererFallback("thinking-panel");case"tool-call":{if(this.toolDisplay==="block")return this.renderToolBlock(part,pairing?.results.get(part.id));if(!this.rendererReady("tool-call-chip"))return this.rendererFallback("tool-call-chip");const masked=this.redacted(part,part.invocation.id,{args:void 0,result:void 0,error:part.invocation.error}),summary=masked?masked.error:part.invocation.error;return html`<lr-tool-call-chip
|
|
20
21
|
.callId=${part.invocation.id}
|
|
21
22
|
.name=${part.invocation.name}
|
|
22
23
|
.displayName=${invocationDisplayName(part.invocation)}
|
|
23
24
|
.status=${part.invocation.status}
|
|
24
25
|
.summary=${typeof summary=="string"?summary:""}
|
|
25
|
-
></lr-tool-call-chip>`}case"tool-result":{const hasError="error"in part,masked=this.redacted(part,part.invocationId,{args:void 0,result:part.result,error:hasError?part.error:void 0}),result=masked?masked.result:part.result;return hasError?html`<div part="tool-result-error">
|
|
26
|
+
></lr-tool-call-chip>`}case"tool-result":{if(!this.rendererReady("tool-result-view"))return this.rendererFallback("tool-result-view");const hasError="error"in part,masked=this.redacted(part,part.invocationId,{args:void 0,result:part.result,error:hasError?part.error:void 0}),result=masked?masked.result:part.result;return hasError?html`<div part="tool-result-error">
|
|
26
27
|
<span>${masked?masked.error:part.error}</span>
|
|
27
28
|
${part.result!==void 0?html`<lr-tool-result-view
|
|
28
29
|
.toolName=${part.name??""}
|
|
@@ -31,13 +32,13 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
31
32
|
</div>`:html`<lr-tool-result-view
|
|
32
33
|
.toolName=${part.name??""}
|
|
33
34
|
.result=${result}
|
|
34
|
-
></lr-tool-result-view>`}case"citation":return html`<lr-citation-badge
|
|
35
|
+
></lr-tool-result-view>`}case"citation":return this.rendererReady("citation-badge")?html`<lr-citation-badge
|
|
35
36
|
.index=${citationRank}
|
|
36
37
|
.sourceId=${part.citation.sourceId??""}
|
|
37
38
|
.label=${part.citation.label??""}
|
|
38
39
|
@lr-citation-activate=${event=>this.selectCitation(event,part)}
|
|
39
40
|
>${part.citation.quote??nothing}</lr-citation-badge
|
|
40
|
-
|
|
41
|
+
>`:this.rendererFallback("citation-badge");case"attachment":return this.rendererReady("attachment-chip")?html`<lr-attachment-chip
|
|
41
42
|
.attachmentId=${part.document.id}
|
|
42
43
|
.name=${part.document.name}
|
|
43
44
|
.mimeType=${part.document.mimeType??""}
|
|
@@ -46,10 +47,11 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
46
47
|
without-remove-button
|
|
47
48
|
status="success"
|
|
48
49
|
size="s"
|
|
49
|
-
></lr-attachment-chip
|
|
50
|
+
></lr-attachment-chip>`:this.rendererFallback("attachment-chip");case"data":return part.widget&&typeof part.widget=="object"?this.rendererReady("widget-renderer")?html`<lr-widget-renderer .document=${this.widgetDocument(part)}
|
|
51
|
+
.registry=${this.widgetRegistry} .bindingState=${this.widgetBindingState}></lr-widget-renderer>`:this.rendererFallback("widget-renderer"):this.rendererReady("json-viewer")?html`<lr-json-viewer .data=${part.data}></lr-json-viewer>`:this.rendererFallback("json-viewer");case"audio":{const src=safeMediaSrc(part.src);return html`${src?html`<audio part="audio-control" controls>
|
|
50
52
|
<source src=${src} type=${part.mimeType||nothing} />
|
|
51
53
|
</audio>`:nothing}
|
|
52
|
-
${part.transcript?html`<p part="audio-transcript">${part.transcript}</p>`:nothing}`}case"error":return html`<span>${part.message||this.localize("messagePartError")}</span> ${part.retryable?html`<lr-button
|
|
54
|
+
${part.transcript?html`<p part="audio-transcript">${part.transcript}</p>`:nothing}`}case"error":return part.retryable&&!this.rendererReady("button")?html`<span>${part.message||this.localize("messagePartError")}</span> ${this.rendererFallback("button")}`:html`<span>${part.message||this.localize("messagePartError")}</span> ${part.retryable?html`<lr-button
|
|
53
55
|
part="retry"
|
|
54
56
|
size="s"
|
|
55
57
|
variant="neutral"
|
|
@@ -59,6 +61,6 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
59
61
|
>${this.localize("retry")}</lr-button
|
|
60
62
|
>`:nothing}`}}requestResume(part){const current=this.renderedParts.find(candidate=>candidate.id===part.id);if(!(this.resumeDispatching||this.disabled||current!==part||part.state!=="interrupted"||part.interruption?.resumable!==!0)){this.resumeDispatching=!0;try{this.emit("lr-part-resume",{part})}finally{this.resumeDispatching=!1}}}renderInterruption(part){return part.state!=="interrupted"?nothing:html`<div part="interruption"><span>${this.localize("streamInterrupted")}</span>${part.interruption?.reason?html`<span>${part.interruption.reason}</span>`:nothing}${part.interruption?.resumable===!0?html`<button part="resume" type="button" ?disabled=${this.disabled}
|
|
61
63
|
@click=${()=>this.requestResume(part)}>${this.localize("streamResume")}</button>`:nothing}</div>`}renderOne(part,citationRank,custom,pairing){return part.type==="reasoning"&&this.withoutReasoning?nothing:pairing?.folded.has(part.id)?nothing:html`<div part=${this.partNames(part)} data-type=${part.type} data-state=${part.state??"complete"}
|
|
62
|
-
>${custom.has(part.id)?custom.get(part.id):html`${this.renderBuiltin(part,citationRank,pairing)}${this.renderInterruption(part)}`}</div>`}render(){const label=this.getAttribute("aria-label")??this.localize("messagePartsLabel"),allParts=this.effectiveParts,citationRanks=new Map;let citationRank=0;for(const part of allParts)part.type==="citation"&&citationRanks.set(part.id,++citationRank);const parts=this.renderedParts,custom=new Map;this.renderPart&&parts.forEach((part,index)=>{if(part.type==="reasoning"&&this.withoutReasoning)return;const rendered=this.renderPart?.(part,index);rendered!==void 0&&custom.set(part.id,rendered)});const pairing=this.toolDisplay==="block"?this.pairTools(parts,custom):void 0;return html`<div part="base" role="group" aria-label=${label}>
|
|
64
|
+
>${custom.has(part.id)?custom.get(part.id):html`${this.renderBuiltin(part,citationRank,pairing)}${this.renderInterruption(part)}`}</div>`}render(){const label=this.getAttribute("aria-label")??this.localize("messagePartsLabel"),allParts=this.effectiveParts,citationRanks=new Map;let citationRank=0;for(const part of allParts)part.type==="citation"&&citationRanks.set(part.id,++citationRank);const parts=this.renderedParts,widgetIds=new Set(parts.filter(part=>part.type==="data"&&part.widget).map(part=>part.id));for(const id of this.widgetDocuments.keys())widgetIds.has(id)||this.widgetDocuments.delete(id);const custom=new Map;this.renderPart&&parts.forEach((part,index)=>{if(part.type==="reasoning"&&this.withoutReasoning)return;const rendered=this.renderPart?.(part,index);rendered!==void 0&&custom.set(part.id,rendered)});const pairing=this.toolDisplay==="block"?this.pairTools(parts,custom):void 0;return html`<div part="base" role="group" aria-label=${label}>
|
|
63
65
|
${repeat(parts,part=>part.id,part=>this.renderOne(part,citationRanks.get(part.id)??0,custom,pairing))}
|
|
64
|
-
</div>`}}__decorate([property({attribute:!1})],LyraMessageParts.prototype,"parts",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMessageParts.prototype,"disabled",void 0),__decorate([property({reflect:!0,attribute:"content-mode"})],LyraMessageParts.prototype,"contentMode",null),__decorate([property({reflect:!0,attribute:"tool-display",converter:MESSAGE_PARTS_TOOL_DISPLAY})],LyraMessageParts.prototype,"toolDisplay",null),__decorate([property({type:Boolean,attribute:"without-reasoning",reflect:!0})],LyraMessageParts.prototype,"withoutReasoning",void 0),__decorate([property({attribute:!1})],LyraMessageParts.prototype,"renderPart",void 0),__decorate([property({attribute:"streaming-render"})],LyraMessageParts.prototype,"streamingRender",void 0),__decorate([property({type:Boolean,attribute:"code-block-header"})],LyraMessageParts.prototype,"codeBlockHeader",void 0),__decorate([property({type:Number,attribute:"max-rendered-parts"})],LyraMessageParts.prototype,"maxRenderedParts",void 0);export{LyraMessageParts};
|
|
66
|
+
</div>`}}__decorate([property({attribute:!1})],LyraMessageParts.prototype,"parts",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMessageParts.prototype,"disabled",void 0),__decorate([property({reflect:!0,attribute:"content-mode"})],LyraMessageParts.prototype,"contentMode",null),__decorate([property({reflect:!0,attribute:"tool-display",converter:MESSAGE_PARTS_TOOL_DISPLAY})],LyraMessageParts.prototype,"toolDisplay",null),__decorate([property({type:Boolean,attribute:"without-reasoning",reflect:!0})],LyraMessageParts.prototype,"withoutReasoning",void 0),__decorate([property({attribute:!1})],LyraMessageParts.prototype,"renderPart",void 0),__decorate([property({attribute:!1})],LyraMessageParts.prototype,"widgetRegistry",void 0),__decorate([property({attribute:!1})],LyraMessageParts.prototype,"widgetBindingState",void 0),__decorate([property({attribute:"streaming-render"})],LyraMessageParts.prototype,"streamingRender",void 0),__decorate([property({type:Boolean,attribute:"code-block-header"})],LyraMessageParts.prototype,"codeBlockHeader",void 0),__decorate([property({type:Number,attribute:"max-rendered-parts"})],LyraMessageParts.prototype,"maxRenderedParts",void 0);export{LyraMessageParts};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** @deprecated Import @aceshooting/lyra-ui/components/lr-message-parts.js to register this component.*/
|
|
2
|
-
export*from'./message-parts.class.js';
|
|
2
|
+
export*from'./message-parts.class.js';export type{}from'../../forms/button/button.js';export type{}from'../../layout/details/details.js';export type{}from'../../forms/icon-button/icon-button.js';export type{}from'../../overlays/overlay/tooltip.js';import'../markdown/markdown.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./message-parts.class.js";import"
|
|
1
|
+
export*from"./message-parts.class.js";import"../markdown/markdown.js";import{defineElement}from"../../../internal/prefix.js";import{LyraMessageParts}from"./message-parts.class.js";defineElement("message-parts",LyraMessageParts);
|
|
@@ -162,4 +162,4 @@ click():void;
|
|
|
162
162
|
/** Moves focus to the internal checkbox control.*/
|
|
163
163
|
focus(options?:FocusOptions):void;
|
|
164
164
|
/** Removes focus from the internal checkbox control.*/
|
|
165
|
-
blur():void;private toggle;private onClick;private onKeyDown;private onSlotChange;private
|
|
165
|
+
blur():void;private toggle;private onClick;private onKeyDown;private onSlotChange;private handleLabelSlotChange;private onLabelSlotChange;private recomputeHasLabelSlot;private onBlur;private onFocus;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-checkbox':LyraCheckbox;}}export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{tag}from"../../../internal/prefix.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_checkboxRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{tag}from"../../../internal/prefix.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_checkboxRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
part="checkmark checked-icon"
|
|
4
4
|
width="1em"
|
|
@@ -26,7 +26,7 @@ import{__decorate}from"tslib";import{SlotPresenceController}from"../../../intern
|
|
|
26
26
|
aria-hidden="true"
|
|
27
27
|
focusable="false"
|
|
28
28
|
><line x1="5" y1="12" x2="19" y2="12"></line></svg>
|
|
29
|
-
`}class LyraCheckboxBase extends LyraElement{}class LyraCheckbox extends CheckedFormAssociated(LyraCheckboxBase){constructor(){super(...arguments),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.slotPresence=new SlotPresenceController(this),this.labelTextObserver=new AccessibleTextController(this,[],()=>this.recomputeHasLabelSlot(),["slot"]),this._groupDisabled=!1,this._indeterminate=!1,this.toggleGuard=new VetoWriteGuard,this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.toggle()},this.onKeyDown=e=>{this.liveDisabled||e.repeat||(e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.toggle())},this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onBlur=event=>{this.liveDisabled||this.setInteracted(!0),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,checkboxRequired:LYRA_DEFAULT_checkboxRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={indeterminate:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0}}}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}isDisabledByOwner(){return this._groupDisabled}checkedWritten(previous){markVetoGuardWrite(this.toggleGuard),this.notifyOwningGroup()}valueWritten(previous){this.notifyOwningGroup()}requiredMessage(){return this.localize("checkboxRequired")}commitFormValue(value){const state2=`${this.checked?"checked":"unchecked"}${this.indeterminate?"/indeterminate":""}`;this.internals.setFormValue(this.checked?value:null,state2)}publishCustomStates(){super.publishCustomStates();const barred=this.isBarredFromValidation();this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),setCustomState(this.internals,"indeterminate",!!this.indeterminate)}formStateRestoreCallback(state2,reason){this.checked=state2==="checked"||state2==="checked/indeterminate",this.indeterminate=state2==="checked/indeterminate"||state2==="unchecked/indeterminate"}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}get indeterminate(){return this._indeterminate}set indeterminate(next){const old=this._indeterminate;this._indeterminate=!!next,this.commitFormValue(this.value),this.updateValidity(),this.notifyOwningGroup(),this.requestUpdate("indeterminate",old)}notifyOwningGroup(){this.closest?.(tag("checkbox-group"))?.notifyCheckboxStateChange?.(this)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".checkbox-owner")??null}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated?this.recomputeHasLabelSlot():this.seedFirstRenderState(()=>{this.recomputeHasLabelSlot()})}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}resetFromGroup(){this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}toggle(){if(this.liveDisabled)return;const proposed=!this.checked;requestThenCommit({requestDetail:{checked:proposed,value:this.value},emitRequest:(detail,init)=>this.emit("lr-checkbox-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.setInteracted(!0),this.checked=proposed,this.indeterminate=!1,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:this.checked,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked,value:this.value})}})}
|
|
29
|
+
`}class LyraCheckboxBase extends LyraElement{}class LyraCheckbox extends CheckedFormAssociated(LyraCheckboxBase){constructor(){super(...arguments),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.slotPresence=new SlotPresenceController(this),this.labelTextObserver=new AccessibleTextController(this,[],()=>this.recomputeHasLabelSlot(),["slot"]),this._groupDisabled=!1,this._indeterminate=!1,this.toggleGuard=new VetoWriteGuard,this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.toggle()},this.onKeyDown=e=>{this.liveDisabled||e.repeat||(e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.toggle())},this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onBlur=event=>{this.liveDisabled||this.setInteracted(!0),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)}}static{this.defaultStrings={...super.defaultStrings,checkboxRequired:LYRA_DEFAULT_checkboxRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={indeterminate:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0}}}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}isDisabledByOwner(){return this._groupDisabled}checkedWritten(previous){markVetoGuardWrite(this.toggleGuard),this.notifyOwningGroup()}valueWritten(previous){this.notifyOwningGroup()}requiredMessage(){return this.localize("checkboxRequired")}commitFormValue(value){const state2=`${this.checked?"checked":"unchecked"}${this.indeterminate?"/indeterminate":""}`;this.internals.setFormValue(this.checked?value:null,state2)}publishCustomStates(){super.publishCustomStates();const barred=this.isBarredFromValidation();this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),setCustomState(this.internals,"indeterminate",!!this.indeterminate)}formStateRestoreCallback(state2,reason){this.checked=state2==="checked"||state2==="checked/indeterminate",this.indeterminate=state2==="checked/indeterminate"||state2==="unchecked/indeterminate"}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}get indeterminate(){return this._indeterminate}set indeterminate(next){const old=this._indeterminate;this._indeterminate=!!next,this.commitFormValue(this.value),this.updateValidity(),this.notifyOwningGroup(),this.requestUpdate("indeterminate",old)}notifyOwningGroup(){this.closest?.(tag("checkbox-group"))?.notifyCheckboxStateChange?.(this)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".checkbox-owner")??null}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated?this.recomputeHasLabelSlot():this.seedFirstRenderState(()=>{this.recomputeHasLabelSlot()})}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}resetFromGroup(){this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}toggle(){if(this.liveDisabled)return;const proposed=!this.checked;requestThenCommit({requestDetail:{checked:proposed,value:this.value},emitRequest:(detail,init)=>this.emit("lr-checkbox-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.setInteracted(!0),this.checked=proposed,this.indeterminate=!1,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:this.checked,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked,value:this.value})}})}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!defaultLabelForwardingSlots(this).includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabelSlot())}recomputeHasLabelSlot(){const renderRoot=this.renderRoot,childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(childNodes).filter(node=>isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}render(){const mixed=this.indeterminate,hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText),hasError=this.hasErrorSlot||(this.errorText??"").length>0,controlParts=["box","control",this.checked?"checked control--checked":"",mixed?"indeterminate control--indeterminate":""].filter(Boolean).join(" "),describedBy=[hasError?"checkbox-error":"",hasHint?"checkbox-hint":""].filter(Boolean).join(" "),invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`
|
|
30
30
|
<div part="form-control">
|
|
31
31
|
<span class="checkbox-layout" part="row" @click=${this.onClick}>
|
|
32
32
|
<span
|
|
@@ -96,6 +96,6 @@ data?:unknown;
|
|
|
96
96
|
*/
|
|
97
97
|
get label():string;set label(next:string);
|
|
98
98
|
/** Accessible text generated from flattened default-slot content, excluding named adornments.*/
|
|
99
|
-
get defaultLabel():string;private computeDefaultLabel;private readonly labelTextObserver;private observedDefaultLabel;private cachedDefaultLabel?;private readonly handlePointerEnter;private readonly handlePointerLeave;private readonly handleFocusIn;private readonly handleFocusOut;private readonly handleLabelMutation;private
|
|
99
|
+
get defaultLabel():string;private computeDefaultLabel;private readonly labelTextObserver;private observedDefaultLabel;private cachedDefaultLabel?;private readonly handlePointerEnter;private readonly handlePointerLeave;private readonly handleFocusIn;private readonly handleFocusOut;private readonly handleLabelMutation;private sourceParentForLabelNode;private isClosedSourceDetailsBranch;private isSourceLabelVisible;private handleLabelSlotChange;private inertAncestorReleases;private bindInertAncestors;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;private handleLabelRecords;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private syncOptionState;
|
|
100
100
|
/** Returns an accessibility-visible label generated from flattened default-slot content.*/
|
|
101
101
|
getTextLabel():string;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-option':LyraOption;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{subscribeInheritedAttributes}from"../../../internal/inherited-attribute-hub.js";import{composedParentElement}from"../../../internal/active-element.js";import{html,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{markOptionSelectedDirty,notifyOptionSelectedWrite,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{styles}from"./option.styles.js";const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{subscribeInheritedAttributes}from"../../../internal/inherited-attribute-hub.js";import{composedParentElement}from"../../../internal/active-element.js";import{html,svg}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisibilityHidden}from"../../../internal/a11y.js";import{composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{markOptionSelectedDirty,notifyOptionSelectedWrite,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{styles}from"./option.styles.js";const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{subscribeInheritedAttributes}from"../../../
|
|
|
11
11
|
aria-hidden="true"
|
|
12
12
|
focusable="false"
|
|
13
13
|
><polyline points="5 12.5 10 17.5 19 6.5"></polyline></svg>
|
|
14
|
-
`}class LyraOption extends LyraElement{constructor(){super(...arguments),this.slotPresence=new SlotPresenceController(this),this.optionInternals=attachInternalsSafely(this),this.hasHover=!1,this.hasCurrent=!1,this._label="",this.selectedValue=!1,this.defaultSelectedValue=!1,this.selectedDirty=!1,this.value="",this.disabled=!1,this.title="",this.group="",this.searchText="",this.sub="",this.dotColor="",this.labelTextObserver=new AccessibleTextController(this,[],records=>this.handleLabelRecords([...records]),["slot","title"],!0,!1,()=>this
|
|
14
|
+
`}class LyraOption extends LyraElement{constructor(){super(...arguments),this.slotPresence=new SlotPresenceController(this),this.optionInternals=attachInternalsSafely(this),this.hasHover=!1,this.hasCurrent=!1,this._label="",this.selectedValue=!1,this.defaultSelectedValue=!1,this.selectedDirty=!1,this.value="",this.disabled=!1,this.title="",this.group="",this.searchText="",this.sub="",this.dotColor="",this.labelTextObserver=new AccessibleTextController(this,[],records=>this.handleLabelRecords([...records]),["slot","title"],!0,!1,()=>defaultLabelForwardingSlots(this).length>0),this.observedDefaultLabel="",this.handlePointerEnter=()=>{this.hasHover=!0,this.syncOptionState()},this.handlePointerLeave=()=>{this.hasHover=!1,this.syncOptionState()},this.handleFocusIn=()=>{this.hasCurrent=!0,this.syncOptionState()},this.handleFocusOut=()=>{this.hasCurrent=!1,this.syncOptionState()},this.handleLabelMutation=(presentationChanged=!1)=>{const next=this.defaultLabel;next===this.observedDefaultLabel&&!presentationChanged||(this.observedDefaultLabel=next,this.requestUpdate(),this.emit("lr-option-change"))},this.handleLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!defaultLabelForwardingSlots(this).includes(target)||(this.cachedDefaultLabel=void 0,this.labelTextObserver.bind(),this.handleLabelMutation())},this.inertAncestorReleases=[]}static{this.styles=[LyraElement.styles,styles]}get selected(){return this.selectedValue}set selected(next){this.setLiveSelected(next,!0),notifyOptionSelectedWrite(this,()=>this.emit("lr-option-change"))}get defaultSelected(){return this.defaultSelectedValue}set defaultSelected(next){const normalized=!!next,old=this.defaultSelectedValue;old!==normalized&&(this.defaultSelectedValue=normalized,this.selectedDirty||this.setLiveSelected(normalized,!1),this.requestUpdate("defaultSelected",old))}setLiveSelected(next,dirty){dirty&&(this.selectedDirty=!0,markOptionSelectedDirty(this,!0));const normalized=!!next,old=this.selectedValue;old!==normalized&&(this.selectedValue=normalized,this.requestUpdate("selected",old))}[SET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty||markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}[RESET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty=!1,markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}get label(){return this._label.trim()||this.defaultLabel}set label(next){const normalized=String(next??""),old=this._label;old!==normalized&&(this._label=normalized,this.requestUpdate("label",old))}get defaultLabel(){if(!("childNodes"in this))return"";const pending=this.labelTextObserver.takeRecords();if(pending.length){this.cachedDefaultLabel=void 0;const ownerDocument=this.ownerDocument;queueMicrotask(()=>{this.isConnected&&this.ownerDocument===ownerDocument&&this.handleLabelRecords(pending)})}return this.isConnected?this.cachedDefaultLabel??=this.computeDefaultLabel():this.computeDefaultLabel()}computeDefaultLabel(){const roots=Array.from(this.childNodes??[]).filter(node=>isDefaultLabelNode(node));return composedAccessibilityText(roots,{requireRendered:!1,shouldPruneNode:node=>!this.contains(node)&&!this.isSourceLabelVisible(node),skipRootAncestorValidation:!0}).replace(/\s+/g," ").trim()}sourceParentForLabelNode(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root&&root.host.nodeType===1?root.host:null}isClosedSourceDetailsBranch(details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;const summary=Array.from(details.children).find(child=>child.localName==="summary");return branch!==summary}isSourceLabelVisible(node){const target=node.nodeType===1?node:this.sourceParentForLabelNode(node);if(!target?.isConnected||isAccessibilitySubtreeExcluded(target)||isAccessibilityVisibilityHidden(target))return!1;let branch=target,ancestor=this.sourceParentForLabelNode(target);for(;ancestor;){if(isAccessibilitySubtreeExcluded(ancestor)||this.isClosedSourceDetailsBranch(ancestor,branch))return!1;branch=ancestor,ancestor=this.sourceParentForLabelNode(ancestor)}return!0}bindInertAncestors(){for(const release of this.inertAncestorReleases.splice(0))release();const roots=new Map;for(let ancestor=composedParentElement(this);ancestor;ancestor=composedParentElement(ancestor)){const root=ancestor.getRootNode();let elements=roots.get(root);elements||roots.set(root,elements=new Set),elements.add(ancestor)}for(const[root,ancestors]of roots){const release=subscribeInheritedAttributes(root,this.ownerDocument.defaultView?.MutationObserver,{attributes:["inert"],changed:records=>{!defaultLabelForwardingSlots(this).length&&records.some(record=>ancestors.has(record.target))&&this.emit("lr-option-change")}});release&&this.inertAncestorReleases.push(release)}}connectedCallback(){super.connectedCallback(),this.addEventListener("pointerenter",this.handlePointerEnter),this.addEventListener("pointerleave",this.handlePointerLeave),this.addEventListener("focusin",this.handleFocusIn),this.addEventListener("focusout",this.handleFocusOut),this.syncOptionState(),this.addEventListener("slotchange",this.handleLabelSlotChange),this.cachedDefaultLabel=void 0,this.observedDefaultLabel=this.defaultLabel,this.bindInertAncestors()}disconnectedCallback(){for(const release of this.inertAncestorReleases.splice(0))release();this.removeEventListener("pointerenter",this.handlePointerEnter),this.removeEventListener("pointerleave",this.handlePointerLeave),this.removeEventListener("focusin",this.handleFocusIn),this.removeEventListener("focusout",this.handleFocusOut),this.removeEventListener("slotchange",this.handleLabelSlotChange),this.hasHover=!1,this.hasCurrent=!1,this.syncOptionState(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cachedDefaultLabel=void 0,this.labelTextObserver.adopted(),this.isConnected&&this.bindInertAncestors()}handleLabelRecords(records){this.cachedDefaultLabel=void 0;const presentationChanged=records.some(record=>{if(record.type==="attributes"&&record.attributeName==="inert"||record.type==="attributes"&&record.attributeName==="slot"&&this.contains(record.target))return!0;let node=record.target;for(;node&&node!==this&&node.parentNode!==this;)node=node.parentNode;return node&&node!==this&&!isDefaultLabelNode(node)?!0:record.type==="childList"&&record.target===this&&[...record.addedNodes,...record.removedNodes].some(child=>!isDefaultLabelNode(child))});this.handleLabelMutation(presentationChanged)}shouldUpdate(changed){return this.hasUpdated&&changed.size===1&&changed.has("label")&&!this.labelTextObserver.hasDrainedRecords()?(queueMicrotask(()=>this.emit("lr-option-change")),!1):super.shouldUpdate(changed)}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&!changed.has("label")&&!changed.has("slot")&&this.labelTextObserver.preserveBindingForNextUpdate()}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&(this.hasCurrent=!1),this.syncOptionState(),(changed.has("value")||changed.has("disabled")||changed.has("group")||changed.has("title")||changed.has("searchText")||changed.has("sub")||changed.has("dotColor")||changed.has("label")||changed.has("defaultSelected")||changed.has("data"))&&this.emit("lr-option-change")}syncOptionState(){this.optionInternals.role="option",this.optionInternals.ariaSelected=this.selected?"true":"false",this.optionInternals.ariaDisabled=this.disabled?"true":"false",setCustomState(this.optionInternals,"current",this.hasCurrent&&!this.disabled),setCustomState(this.optionInternals,"selected",this.selected),setCustomState(this.optionInternals,"disabled",this.disabled),setCustomState(this.optionInternals,"hover",this.hasHover&&!this.disabled)}getTextLabel(){return this.defaultLabel}render(){const hasStart=this.slotPresence.has("start")||this.slotPresence.has("prefix"),hasEnd=this.slotPresence.has("end")||this.slotPresence.has("suffix");return html`
|
|
15
15
|
<div part="base">
|
|
16
16
|
<span part="checked-icon" aria-hidden="true" inert ?hidden=${!this.selected}>
|
|
17
17
|
${checkmarkGlyph()}
|
|
@@ -164,4 +164,4 @@ setCustomValidity(message:string):void;private applyCustomValidity;private refle
|
|
|
164
164
|
/** Clears consumer-supplied validity on the standalone radio or its owning group.*/
|
|
165
165
|
resetValidity():void;click():void;focus(options?:FocusOptions):void;blur():void;private currentGroup;private group;private select;private uncheckSameNameRadios;
|
|
166
166
|
/** Actual contiguous button-run position. Standalone and non-adjacent controls stay rounded.*/
|
|
167
|
-
protected get buttonRunPosition():RadioButtonRunPosition;private isNestedInteractiveEvent;protected onClick:()=>void;protected onKeyDown:(event:KeyboardEvent)=>void;protected onFocus:(event:FocusEvent)=>void;protected onBlur:(event:FocusEvent)=>void;private
|
|
167
|
+
protected get buttonRunPosition():RadioButtonRunPosition;private isNestedInteractiveEvent;protected onClick:()=>void;protected onKeyDown:(event:KeyboardEvent)=>void;protected onFocus:(event:FocusEvent)=>void;protected onBlur:(event:FocusEvent)=>void;private recomputeHasLabel;private assignedAdornmentNodes;private recomputeButtonAdornments;private handleLabelSlotChange;private onLabelSlotChange;private onSlotChange;private onAdornmentSlotChange;private get invalid();render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-radio':LyraRadio;}}export{};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings/forms.generated.js";installFormControlLabelSupport();class LyraRadioBase extends LyraElement{}class LyraRadio extends CheckedFormAssociated(LyraRadioBase){constructor(){super(...arguments),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.recomputeHasLabel(),this.recomputeButtonAdornments()},["slot"]),this.swappingControl=!1,this.committingCustomError=!1,this.resettingCustomError=!1,this._radioName="",this._radioValue="on",this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this.onClick=event=>{if(event&&this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.select()},this.onKeyDown=event=>{if(this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{!this.effectiveDisabled&&!this.matches(":disabled")&&!this.swappingControl&&this.setInteracted(!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.labelTextObserver.bind(),this.recomputeButtonAdornments()}}static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}static{this.properties={appearance:{reflect:!0,converter:declaredDefaultConverter("default")},pill:{type:Boolean,reflect:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")}}}get name(){return this._radioName}set name(value){const old=this._radioName,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._radioName=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._radioValue}set value(value){const old=this._radioValue,next=value??"on";old!==next&&(this._radioValue=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}radioCustomMessage(){return this.currentGroup()?.customError??this.validityController.customValidityMessage}get customError(){return this.radioCustomMessage()||null}set customError(next){this.setCustomValidity(next??"")}acceptsCheckedWrite(previous,next){return previous!==next}checkedWritten(previous){this.isConnected&&this.group()?.radioCheckedChanged?.(this)}isDisabledByOwner(){return!!this.currentGroup()&&this._groupDisabled}reportsRequired(){return this.effectiveRequired}requiredMessage(){return this.localize("radioRequired")}commitFormValue(value){this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?value:null,this.checked?"checked":"unchecked")}updateValidity(){const owned=!!this.currentGroup(),violates=!this.isBarredFromValidation()&&!owned&&this.effectiveRequired&&!this.checked;this[SET_ANCHORED_VALIDITY](violates?{valueMissing:!0}:{},this.requiredMessage())}formResetCallback(){this.currentGroup()||super.formResetCallback()}formStateRestoreCallback(state2,reason){this.currentGroup()||(this.checked=state2==="checked")}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}syncFormState(){this.commitFormValue(this.value),this.updateValidity()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}willUpdate(changed){super.willUpdate(changed),this.swappingControl=this.hasUpdated&&changed.has("appearance")}updated(changed){super.updated(changed),this.swappingControl=!1,this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),super.disconnectedCallback()}resetFromGroup(){this.setInteracted(!1),this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}setCustomValidity(message){if(this.committingCustomError){this.resettingCustomError&&this.applyCustomValidity(message??"");return}const old=this.radioCustomMessage()||null;this.committingCustomError=!0;try{this.applyCustomValidity(message??""),this.reflectCustomError(this.radioCustomMessage())}finally{this.committingCustomError=!1}this.requestUpdate("customError",old)}applyCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message);return}this.validityController.setCustomValidity(message),this.syncValidityStates(),this.requestUpdate()}reflectCustomError(message){message?this.getAttribute("custom-error")!==message&&this.setAttribute("custom-error",message):this.hasAttribute("custom-error")&&this.removeAttribute("custom-error")}resetValidity(){if(this.committingCustomError)return;const old=this.radioCustomMessage()||null;this.committingCustomError=!0,this.resettingCustomError=!0;try{this.applyCustomValidity(""),this.reflectCustomError(this.radioCustomMessage())}finally{this.resettingCustomError=!1,this.committingCustomError=!1}this.requestUpdate("customError",old)}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!this.effectiveDisabled){if(this.checked||this.setInteracted(!0),group){group.selectRadio?.(this);return}this.checked||(this.checked=!0,this.uncheckSameNameRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})),this.emit("lr-activate",{value:this.value})}}uncheckSameNameRadios(){if(this.name)for(const other of this.getRootNode().querySelectorAll(`${tag("radio")},${tag("radio-button")}`))other!==this&&other.name===this.name&&other.form===this.form&&!other.currentGroup()&&(other.checked=!1)}get buttonRunPosition(){return this._buttonRunPosition}isNestedInteractiveEvent(event){const currentTarget=event.currentTarget;for(const entry of event.composedPath()){if(entry===currentTarget)break;if(entry&&typeof entry=="object"&&entry.nodeType===1&&isActionableElement(entry))return!0}return!1}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes??[]).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabel())}renderButtonContent(){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings/forms.generated.js";installFormControlLabelSupport();class LyraRadioBase extends LyraElement{}class LyraRadio extends CheckedFormAssociated(LyraRadioBase){constructor(){super(...arguments),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.recomputeHasLabel(),this.recomputeButtonAdornments()},["slot"]),this.swappingControl=!1,this.committingCustomError=!1,this.resettingCustomError=!1,this._radioName="",this._radioValue="on",this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this.onClick=event=>{if(event&&this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.select()},this.onKeyDown=event=>{if(this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{!this.effectiveDisabled&&!this.matches(":disabled")&&!this.swappingControl&&this.setInteracted(!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.labelTextObserver.bind(),this.recomputeButtonAdornments()}}static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}static{this.properties={appearance:{reflect:!0,converter:declaredDefaultConverter("default")},pill:{type:Boolean,reflect:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")}}}get name(){return this._radioName}set name(value){const old=this._radioName,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._radioName=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._radioValue}set value(value){const old=this._radioValue,next=value??"on";old!==next&&(this._radioValue=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}radioCustomMessage(){return this.currentGroup()?.customError??this.validityController.customValidityMessage}get customError(){return this.radioCustomMessage()||null}set customError(next){this.setCustomValidity(next??"")}acceptsCheckedWrite(previous,next){return previous!==next}checkedWritten(previous){this.isConnected&&this.group()?.radioCheckedChanged?.(this)}isDisabledByOwner(){return!!this.currentGroup()&&this._groupDisabled}reportsRequired(){return this.effectiveRequired}requiredMessage(){return this.localize("radioRequired")}commitFormValue(value){this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?value:null,this.checked?"checked":"unchecked")}updateValidity(){const owned=!!this.currentGroup(),violates=!this.isBarredFromValidation()&&!owned&&this.effectiveRequired&&!this.checked;this[SET_ANCHORED_VALIDITY](violates?{valueMissing:!0}:{},this.requiredMessage())}formResetCallback(){this.currentGroup()||super.formResetCallback()}formStateRestoreCallback(state2,reason){this.currentGroup()||(this.checked=state2==="checked")}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}syncFormState(){this.commitFormValue(this.value),this.updateValidity()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}willUpdate(changed){super.willUpdate(changed),this.swappingControl=this.hasUpdated&&changed.has("appearance")}updated(changed){super.updated(changed),this.swappingControl=!1,this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),super.disconnectedCallback()}resetFromGroup(){this.setInteracted(!1),this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}setCustomValidity(message){if(this.committingCustomError){this.resettingCustomError&&this.applyCustomValidity(message??"");return}const old=this.radioCustomMessage()||null;this.committingCustomError=!0;try{this.applyCustomValidity(message??""),this.reflectCustomError(this.radioCustomMessage())}finally{this.committingCustomError=!1}this.requestUpdate("customError",old)}applyCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message);return}this.validityController.setCustomValidity(message),this.syncValidityStates(),this.requestUpdate()}reflectCustomError(message){message?this.getAttribute("custom-error")!==message&&this.setAttribute("custom-error",message):this.hasAttribute("custom-error")&&this.removeAttribute("custom-error")}resetValidity(){if(this.committingCustomError)return;const old=this.radioCustomMessage()||null;this.committingCustomError=!0,this.resettingCustomError=!0;try{this.applyCustomValidity(""),this.reflectCustomError(this.radioCustomMessage())}finally{this.resettingCustomError=!1,this.committingCustomError=!1}this.requestUpdate("customError",old)}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!this.effectiveDisabled){if(this.checked||this.setInteracted(!0),group){group.selectRadio?.(this);return}this.checked||(this.checked=!0,this.uncheckSameNameRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})),this.emit("lr-activate",{value:this.value})}}uncheckSameNameRadios(){if(this.name)for(const other of this.getRootNode().querySelectorAll(`${tag("radio")},${tag("radio-button")}`))other!==this&&other.name===this.name&&other.form===this.form&&!other.currentGroup()&&(other.checked=!1)}get buttonRunPosition(){return this._buttonRunPosition}isNestedInteractiveEvent(event){const currentTarget=event.currentTarget;for(const entry of event.composedPath()){if(entry===currentTarget)break;if(entry&&typeof entry=="object"&&entry.nodeType===1&&isActionableElement(entry))return!0}return!1}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes??[]).filter(node=>isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!defaultLabelForwardingSlots(this).includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabel())}renderButtonContent(){return html`
|
|
2
2
|
<span part="start prefix" ?hidden=${!this.hasStart}>
|
|
3
3
|
<slot name="start" @slotchange=${this.onAdornmentSlotChange}></slot>
|
|
4
4
|
<slot name="prefix" @slotchange=${this.onAdornmentSlotChange}></slot>
|