@aceshooting/lyra-ui 30.2.0 → 30.4.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.
Files changed (93) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/ai/adapters/a2ui.d.ts +10 -4
  3. package/dist/ai/adapters/a2ui.js +1 -1
  4. package/dist/ai/adapters/ag-ui.d.ts +17 -4
  5. package/dist/ai/adapters/ag-ui.js +1 -1
  6. package/dist/ai/adapters/ai-sdk.js +1 -1
  7. package/dist/ai/runtime.js +1 -1
  8. package/dist/components/agent-tools/mcp-app/mcp-app-protocol.d.ts +15 -0
  9. package/dist/components/agent-tools/mcp-app/mcp-app-protocol.js +36 -0
  10. package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +31 -4
  11. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +4 -4
  12. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
  13. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  14. package/dist/components/conversation/message-actions/message-actions.class.d.ts +3 -3
  15. package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
  16. package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
  17. package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
  18. package/dist/components/conversation/message-parts/message-parts.js +1 -1
  19. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -1
  20. package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +1 -1
  21. package/dist/components/forms/select/select.class.js +1 -1
  22. package/dist/components/layout/app-rail/app-rail.class.d.ts +1 -1
  23. package/dist/components/layout/app-rail/app-rail.class.js +1 -1
  24. package/dist/components/layout/multi-split/multi-split.class.d.ts +4 -1
  25. package/dist/components/layout/multi-split/multi-split.class.js +6 -3
  26. package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
  27. package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
  28. package/dist/components/layout/page/page.class.d.ts +3 -1
  29. package/dist/components/layout/page/page.class.js +1 -1
  30. package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
  31. package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
  32. package/dist/components/layout/scroller/scroller.class.d.ts +1 -1
  33. package/dist/components/layout/scroller/scroller.class.js +1 -1
  34. package/dist/components/layout/split-panel/split-panel.class.d.ts +1 -1
  35. package/dist/components/layout/split-panel/split-panel.class.js +1 -1
  36. package/dist/components/layout/stepper/stepper.class.d.ts +1 -1
  37. package/dist/components/layout/stepper/stepper.class.js +1 -1
  38. package/dist/components/layout/widget/widget.class.d.ts +1 -1
  39. package/dist/components/layout/widget/widget.class.js +1 -1
  40. package/dist/components/media/file-input/file-input.styles.js +1 -1
  41. package/dist/components/media/map/map-control-chrome.js +1 -0
  42. package/dist/components/media/map/map-control-options.d.ts +6 -2
  43. package/dist/components/media/map/map-control-options.js +1 -1
  44. package/dist/components/media/map/map-controls-lifecycle.js +1 -1
  45. package/dist/components/media/map/map-controls-readiness.js +1 -0
  46. package/dist/components/media/map/map.class.d.ts +39 -2
  47. package/dist/components/media/map/map.class.js +13 -7
  48. package/dist/components/media/map/map.styles.js +1 -1
  49. package/dist/components/overlays/dialog/dialog.class.d.ts +2 -2
  50. package/dist/components/overlays/dialog/dialog.class.js +1 -1
  51. package/dist/components/utility/copy-button/copy-button.class.d.ts +13 -15
  52. package/dist/components/utility/copy-button/copy-button.class.js +3 -3
  53. package/dist/components/utility/copy-button/copy-button.styles.js +1 -1
  54. package/dist/components/utility/tour/tour.class.d.ts +2 -2
  55. package/dist/components/utility/tour/tour.class.js +1 -1
  56. package/dist/events.d.ts +10 -1
  57. package/dist/framework-types.d.ts +1 -1
  58. package/dist/internal/localization-types.d.ts +1 -1
  59. package/dist/internal/localization.js +1 -1
  60. package/dist/internal/modal-host.styles.js +1 -0
  61. package/dist/internal/modal-surface-controller.js +1 -1
  62. package/dist/internal/overlay-stack.d.ts +1 -1
  63. package/dist/internal/overlay-stack.js +1 -1
  64. package/dist/internal/package-metadata.js +1 -1
  65. package/dist/internal/scoped-definitions.generated.js +1 -1
  66. package/dist/internal/style-property-lease.js +1 -1
  67. package/dist/lyra.d.ts +1 -1
  68. package/llms/components/lr-app-rail.md +4 -0
  69. package/llms/components/lr-badge.md +3 -0
  70. package/llms/components/lr-copy-button.md +15 -7
  71. package/llms/components/lr-file-input.md +5 -0
  72. package/llms/components/lr-map.md +80 -8
  73. package/llms/components/lr-mcp-app.md +94 -4
  74. package/llms/components/lr-message-parts.md +18 -0
  75. package/llms/components/lr-multi-split.md +4 -0
  76. package/llms/components/lr-page.md +5 -1
  77. package/llms/components/lr-responsive-panel.md +5 -1
  78. package/llms/components/lr-select.md +3 -2
  79. package/llms/components/lr-token-input.md +4 -3
  80. package/llms/components/lr-tooltip.md +4 -4
  81. package/llms/peers.md +1 -1
  82. package/llms/shared/ai-and-peers.md +88 -3
  83. package/llms/shared/events-and-types.md +25 -1
  84. package/llms/shared/localization-and-rtl.md +29 -0
  85. package/llms/shared/styles-and-tokens.md +75 -14
  86. package/llms/shared.md +217 -18
  87. package/locales.json +1 -1
  88. package/package.json +8 -4
  89. package/registrations.json +1 -1
  90. package/skills/compose-lyra-interfaces/SKILL.md +5 -3
  91. package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
  92. package/skills/lyra-ui/SKILL.md +17 -8
  93. package/skills/lyra-ui/lyra-gen.md +95 -0
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{finiteRange}from"../../../internal/numbers.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeFrameSrc}from"../../../internal/safe-url.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./mcp-app.styles.js";import{purposeAccessibleLabel}from"../semantic-owner.js";import{LYRA_DEFAULT_mcpAppLabel,LYRA_DEFAULT_mcpAppLoading,LYRA_DEFAULT_mcpAppUnavailable}from"../../../internal/default-strings/agent-tools.generated.js";function record(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function resolveResource(resource){const value=record(resource);if(!value||typeof value.uri!="string")return null;const uri=value.uri.trim();if(!uri)return null;const ownsHtml=Object.prototype.hasOwnProperty.call(value,"html"),ownsSrc=Object.prototype.hasOwnProperty.call(value,"src");if(ownsHtml===ownsSrc)return null;if(ownsHtml)return typeof value.html!="string"||value.html.length===0?null:{resource,uri,html:value.html};const src=safeFrameSrc(value.src);return src?{resource,uri,src}:null}function sameAppDocument(a,b){if(!a||!b||a.uri!==b.uri||a.html!==b.html||a.src!==b.src)return!1;const policy=({csp,permissions,metadata})=>JSON.stringify([csp,permissions,metadata]);try{return policy(a.resource)===policy(b.resource)}catch{return!1}}const CSP_HOST=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])$/i;function cspSources(values){return(values??[]).flatMap(value=>{try{const url=new URL(value);return(url.protocol==="https:"||url.protocol==="http:")&&CSP_HOST.test(url.hostname)?[url.origin]:[]}catch{return[]}})}function buildCsp(csp){const resources=cspSources(csp?.resourceDomains),connections=cspSources(csp?.connectDomains),frames=cspSources(csp?.frameDomains);return["default-src 'none'","script-src 'unsafe-inline'","style-src 'unsafe-inline'",`img-src data: blob: ${resources.join(" ")}`.trim(),`font-src data: ${resources.join(" ")}`.trim(),`media-src data: blob: ${resources.join(" ")}`.trim(),`connect-src ${connections.length?connections.join(" "):"'none'"}`,`frame-src ${frames.length?frames.join(" "):"'none'"}`,"base-uri 'none'","form-action 'none'"].join("; ")}function withCsp(htmlSource,csp){return`${`<meta http-equiv="Content-Security-Policy" content="${buildCsp(csp)}">`}${htmlSource}`}function absoluteLinkHref(value){try{const url=new URL(typeof value=="string"?value:"");return["http:","https:","mailto:"].includes(url.protocol)?url.href:null}catch{return null}}const heightAttributeConverter={fromAttribute(value){if(value===null)return null;const numeric=Number(value);return Number.isFinite(numeric)?numeric:value.trim()}};function permissionPolicy(permissions){return[permissions?.camera?"camera":"",permissions?.microphone?"microphone":"",permissions?.geolocation?"geolocation":"",permissions?.clipboardRead?"clipboard-read":"",permissions?.clipboardWrite?"clipboard-write":""].filter(Boolean).map(permission=>`${permission} *`).join("; ")}class LyraMcpApp extends LyraElement{constructor(){super(...arguments),this.resource=null,this.height=320,this.maxHeight=800,this.label="",this.accessibleLabel=null,this.loaded=!1,this.frameHeight=320,this.frameGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.suppressNextResourceAnnouncement=!0,this.onPortMessage=event=>{this.handleMessage(event.data)}}static{this.defaultStrings={...super.defaultStrings,mcpAppLabel:LYRA_DEFAULT_mcpAppLabel,mcpAppLoading:LYRA_DEFAULT_mcpAppLoading,mcpAppUnavailable:LYRA_DEFAULT_mcpAppUnavailable}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["resource"])}static{this.styles=[LyraElement.styles,styles]}resourceAvailable(resource){return resolveResource(resource)!==null}invalidateFrame(){this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.loaded=!1,this.frameGeneration++,this.requestUpdate()}closeFramePort(){this.framePort?.removeEventListener("message",this.onPortMessage),this.framePort?.close(),this.framePort=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextResourceAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){this.invalidateFrame(),this.suppressNextResourceAnnouncement=!0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateFrame(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed);const keptFrame=changed.has("resource")&&this.hasUpdated&&sameAppDocument(resolveResource(changed.get("resource")),resolveResource(this.resource));if(changed.has("resource")&&!keptFrame){if(this.hasUpdated&&!this.suppressNextResourceAnnouncement){const wasAvailable=this.resourceAvailable(changed.get("resource"));this.resourceAvailable(this.resource)?this.announcements.announcePolite(this.localize("mcpAppLoading")):wasAvailable&&this.announcements.announceAssertive(this.localize("mcpAppUnavailable"))}this.loaded=!1,this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.frameGeneration++}(changed.has("resource")&&!keptFrame||changed.has("height")||changed.has("maxHeight"))&&(this.frameHeight=finiteRange(this.heightPx(),320,120,this.maxHeightPx()))}updated(_changed){super.updated(_changed),this.suppressNextResourceAnnouncement=!1}createFrameNonce(){return crypto.randomUUID()}onLoad(event,frameGeneration,resource){if(!this.isConnected||frameGeneration!==this.frameGeneration||event.currentTarget!==this.frame)return;const currentResource=resolveResource(this.resource);if(!currentResource||currentResource.resource!==resource.resource&&!sameAppDocument(currentResource,resource))return;if(this.loaded){this.invalidateFrame();return}this.frameNonce??=this.createFrameNonce();const frame=event.currentTarget,port=new MessageChannel;this.framePort=port.port1,this.framePort.addEventListener("message",this.onPortMessage),this.framePort.start(),this.loaded=!0,this.bootstrapPort={frame,port:port.port2},this.postHostContext({resource:{uri:resource.uri,metadata:resource.resource.metadata},locale:this.effectiveLocale,direction:this.effectiveDirection}),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.emit("lr-mcp-ready",{uri:resource.uri})}heightPx(){return resolveCssLength(this.height,{host:this})??Number.NaN}maxHeightPx(){return finiteRange(resolveCssLength(this.maxHeight,{host:this})??Number.NaN,800,120,1e4)}handleMessage(data){const message=record(data);if(!(typeof this.frameNonce!="string"||message?.nonce!==this.frameNonce)&&!(message?.channel!=="lyra-mcp-app"||message.version!==1||typeof message.type!="string"))switch(message.type){case"resize":{const requested=typeof message.height=="number"?message.height:this.heightPx(),height=finiteRange(requested,this.heightPx(),120,this.maxHeightPx());this.frameHeight=height,this.emit("lr-mcp-resize",{height});break}case"tool-call":typeof message.name=="string"&&this.emit("lr-mcp-tool-call",{requestId:typeof message.requestId=="string"?message.requestId:void 0,name:message.name,args:message.args,frameGeneration:this.frameGeneration});break;case"send-message":this.emit("lr-mcp-send-message",{message:message.message});break;case"open-link":{const href=absoluteLinkHref(message.href);href&&this.emit("lr-mcp-open-link",{href})}break;case"log":this.emit("lr-mcp-log",{level:typeof message.level=="string"?message.level:"info",value:message.value});break}}post(message,frame=this.frame,transferPort){const nonce=this.frameNonce;if(typeof nonce=="string"){if(transferPort){const target=frame?.contentWindow;if(!target)return;target.postMessage({...message,nonce},"*",[transferPort]);return}this.framePort?.postMessage({...message,nonce})}}postHostContext(context){const bootstrap=this.bootstrapPort;this.bootstrapPort=void 0,this.post({channel:"lyra-mcp-app",version:1,type:"host-context",context},bootstrap?.frame,bootstrap?.port)}postToolResult(requestId,options){const value=record(options);if(typeof requestId!="string"||!requestId.trim()||!value)return;const frameGeneration=value.frameGeneration;if(typeof frameGeneration!="number"||!Number.isSafeInteger(frameGeneration)||frameGeneration!==this.frameGeneration)return;const hasResult=Object.prototype.hasOwnProperty.call(value,"result"),hasError=Object.prototype.hasOwnProperty.call(value,"error");hasResult!==hasError&&(hasError&&(typeof value.error!="string"||!value.error.trim())||this.post({channel:"lyra-mcp-app",version:1,type:"tool-result",requestId,...hasResult?{result:value.result}:{},...hasError?{error:value.error}:{}}))}render(){const resource=resolveResource(this.resource);if(!resource)return html`<div part="base"><p part="error">${this.localize("mcpAppUnavailable")}</p></div>`;const fallbackLabel=(!this.hasAttribute("aria-label")&&typeof this.accessibleLabel=="string"?this.accessibleLabel:"")||this.label||resource.resource.title||this.localize("mcpAppLabel"),label=purposeAccessibleLabel(this,fallbackLabel),frameGeneration=this.frameGeneration;return html`<div part="base">
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{finiteRange}from"../../../internal/numbers.js";import{resolveCssLength}from"../../../internal/css-length.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeFrameSrc}from"../../../internal/safe-url.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{styles}from"./mcp-app.styles.js";import{McpAppSession,MCP_APP_PROXY_DOCUMENT,mcpRecord}from"./mcp-app-protocol.js";import{purposeAccessibleLabel}from"../semantic-owner.js";import{LYRA_DEFAULT_mcpAppLabel,LYRA_DEFAULT_mcpAppLoading,LYRA_DEFAULT_mcpAppUnavailable}from"../../../internal/default-strings/agent-tools.generated.js";function record(value){return value&&typeof value=="object"&&!Array.isArray(value)?value:null}function resolveResource(resource){const value=record(resource);if(!value||typeof value.uri!="string")return null;const uri=value.uri.trim();if(!uri)return null;const ownsHtml=Object.prototype.hasOwnProperty.call(value,"html"),ownsSrc=Object.prototype.hasOwnProperty.call(value,"src");if(ownsHtml===ownsSrc)return null;if(ownsHtml)return typeof value.html!="string"||value.html.length===0?null:{resource,uri,html:value.html};const src=safeFrameSrc(value.src);return src?{resource,uri,src}:null}function sameAppDocument(a,b){if(!a||!b||a.uri!==b.uri||a.html!==b.html||a.src!==b.src)return!1;const policy=({csp,permissions,metadata})=>JSON.stringify([csp,permissions,metadata]);try{return policy(a.resource)===policy(b.resource)}catch{return!1}}const CSP_HOST=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])$/i;function cspSources(values){return(values??[]).flatMap(value=>{try{const url=new URL(value);return(url.protocol==="https:"||url.protocol==="http:")&&CSP_HOST.test(url.hostname)?[url.origin]:[]}catch{return[]}})}function buildCsp(csp,externalAssets){const resources=cspSources(csp?.resourceDomains),connections=cspSources(csp?.connectDomains),frames=cspSources(csp?.frameDomains);return["default-src 'none'",`script-src 'unsafe-inline' ${externalAssets?resources.join(" "):""}`.trim(),`style-src 'unsafe-inline' ${externalAssets?resources.join(" "):""}`.trim(),`img-src data: blob: ${resources.join(" ")}`.trim(),`font-src data: ${resources.join(" ")}`.trim(),`media-src data: blob: ${resources.join(" ")}`.trim(),`connect-src ${connections.length?connections.join(" "):"'none'"}`,`frame-src ${frames.length?frames.join(" "):"'none'"}`,"base-uri 'none'","form-action 'none'"].join("; ")}function withCsp(htmlSource,csp,externalAssets=!1){return`${`<meta http-equiv="Content-Security-Policy" content="${buildCsp(csp,externalAssets)}">`}${htmlSource}`}function absoluteLinkHref(value){try{const url=new URL(typeof value=="string"?value:"");return["http:","https:","mailto:"].includes(url.protocol)?url.href:null}catch{return null}}const heightAttributeConverter={fromAttribute(value){if(value===null)return null;const numeric=Number(value);return Number.isFinite(numeric)?numeric:value.trim()}};function permissionPolicy(permissions){return[permissions?.camera?"camera":"",permissions?.microphone?"microphone":"",permissions?.geolocation?"geolocation":"",permissions?.clipboardRead?"clipboard-read":"",permissions?.clipboardWrite?"clipboard-write":""].filter(Boolean).map(permission=>`${permission} *`).join("; ")}class LyraMcpApp extends LyraElement{constructor(){super(...arguments),this.resource=null,this.protocol="legacy",this.hostCapabilities={},this.height=320,this.maxHeight=800,this.label="",this.accessibleLabel=null,this.loaded=!1,this.frameHeight=320,this.frameGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.suppressNextResourceAnnouncement=!0,this.onPortMessage=event=>{this.handleMessage(event.data)}}static{this.defaultStrings={...super.defaultStrings,mcpAppLabel:LYRA_DEFAULT_mcpAppLabel,mcpAppLoading:LYRA_DEFAULT_mcpAppLoading,mcpAppUnavailable:LYRA_DEFAULT_mcpAppUnavailable}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["resource","hostCapabilities"])}static{this.styles=[LyraElement.styles,styles]}resourceAvailable(resource){return resolveResource(resource)!==null}invalidateFrame(){this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.loaded=!1,this.frameGeneration++,this.requestUpdate()}closeFramePort(){this.deliveredEnvironment=void 0,this.protocolSession?.close(),this.protocolSession=void 0,this.framePort?.removeEventListener("message",this.onPortMessage),this.framePort?.close(),this.framePort=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextResourceAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){this.invalidateFrame(),this.suppressNextResourceAnnouncement=!0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.invalidateFrame(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed);const keptFrame=changed.has("resource")&&this.hasUpdated&&sameAppDocument(resolveResource(changed.get("resource")),resolveResource(this.resource));if(changed.has("resource")&&!keptFrame||changed.has("protocol")||changed.has("hostCapabilities")){if(this.hasUpdated&&!this.suppressNextResourceAnnouncement){const wasAvailable=this.resourceAvailable(changed.get("resource"));this.resourceAvailable(this.resource)?this.announcements.announcePolite(this.localize("mcpAppLoading")):wasAvailable&&this.announcements.announceAssertive(this.localize("mcpAppUnavailable"))}this.loaded=!1,this.closeFramePort(),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.frameNonce=this.resourceAvailable(this.resource)?this.createFrameNonce():void 0,this.frameGeneration++}(changed.has("resource")&&!keptFrame||changed.has("height")||changed.has("maxHeight"))&&(this.frameHeight=finiteRange(this.heightPx(),320,120,this.maxHeightPx())),this.pendingEnvironment=this.loaded?{locale:this.effectiveLocale,direction:this.effectiveDirection}:void 0}updated(_changed){super.updated(_changed),this.suppressNextResourceAnnouncement=!1;const context=this.pendingEnvironment;this.pendingEnvironment=void 0,this.loaded&&this.deliveredEnvironment&&context&&(context.locale!==this.deliveredEnvironment.locale||context.direction!==this.deliveredEnvironment.direction)&&(this.deliveredEnvironment=context,this.postHostContext(context))}createFrameNonce(){return crypto.randomUUID()}onLoad(event,frameGeneration,resource){if(!this.isConnected||frameGeneration!==this.frameGeneration||event.currentTarget!==this.frame)return;const currentResource=resolveResource(this.resource);if(!currentResource||currentResource.resource!==resource.resource&&!sameAppDocument(currentResource,resource))return;if(this.loaded){this.invalidateFrame();return}this.frameNonce??=this.createFrameNonce();const frame=event.currentTarget,port=new MessageChannel;this.framePort=port.port1,this.framePort.addEventListener("message",this.onPortMessage),this.framePort.start(),this.loaded=!0,this.bootstrapPort={frame,port:port.port2},this.deliveredEnvironment={locale:this.effectiveLocale,direction:this.effectiveDirection},this.postHostContext({resource:{uri:resource.uri,metadata:resource.resource.metadata},...this.deliveredEnvironment}),this.bootstrapPort?.port.close(),this.bootstrapPort=void 0,this.protocol==="mcp-apps"&&(this.protocolSession=new McpAppSession({generation:frameGeneration,capabilities:this.hostCapabilities,context:{locale:this.effectiveLocale,displayMode:"inline",availableDisplayModes:["inline"]},send:message=>this.post({channel:"lyra-mcp-app",version:1,type:"mcp-apps",message}),request:detail=>this.emit("lr-mcp-request",detail),initialized:()=>this.emit("lr-mcp-initialized",{uri:resource.uri,frameGeneration}),resize:requested=>{const height=finiteRange(requested,this.heightPx(),120,this.maxHeightPx());this.frameHeight=height,this.emit("lr-mcp-resize",{height})},log:(level,value)=>this.emit("lr-mcp-log",{level,value})}),this.post({channel:"lyra-mcp-app",version:1,type:"mcp-resource",title:this.frame?.title??this.localize("mcpAppLabel"),allow:permissionPolicy(resource.resource.permissions),...resource.html?{html:withCsp(resource.html,resource.resource.csp,!0)}:{src:resource.src}})),this.emit("lr-mcp-ready",{uri:resource.uri})}heightPx(){return resolveCssLength(this.height,{host:this})??Number.NaN}maxHeightPx(){return finiteRange(resolveCssLength(this.maxHeight,{host:this})??Number.NaN,800,120,1e4)}handleMessage(data){const message=record(data);if(!(typeof this.frameNonce!="string"||message?.nonce!==this.frameNonce)&&!(message?.channel!=="lyra-mcp-app"||message.version!==1||typeof message.type!="string")){if(this.protocol==="mcp-apps"){message.type==="mcp-apps"?this.protocolSession?.receive(message.message):message.type==="mcp-navigation"&&this.invalidateFrame();return}switch(message.type){case"resize":{const requested=typeof message.height=="number"?message.height:this.heightPx(),height=finiteRange(requested,this.heightPx(),120,this.maxHeightPx());this.frameHeight=height,this.emit("lr-mcp-resize",{height});break}case"tool-call":typeof message.name=="string"&&this.emit("lr-mcp-tool-call",{requestId:typeof message.requestId=="string"?message.requestId:void 0,name:message.name,args:message.args,frameGeneration:this.frameGeneration});break;case"send-message":this.emit("lr-mcp-send-message",{message:message.message});break;case"open-link":{const href=absoluteLinkHref(message.href);href&&this.emit("lr-mcp-open-link",{href})}break;case"log":this.emit("lr-mcp-log",{level:typeof message.level=="string"?message.level:"info",value:message.value});break}}}post(message,frame=this.frame,transferPort){const nonce=this.frameNonce;if(typeof nonce=="string"){if(transferPort){const target=frame?.contentWindow;if(!target)return;target.postMessage({...message,nonce},"*",[transferPort]);return}this.framePort?.postMessage({...message,nonce})}}postHostContext(context){const bootstrap=this.bootstrapPort;if(this.bootstrapPort=void 0,this.protocol==="mcp-apps"&&!bootstrap){const params=mcpRecord(context);params&&this.protocolSession?.updateHostContext(params);return}this.post({channel:"lyra-mcp-app",version:1,type:"host-context",context},bootstrap?.frame,bootstrap?.port)}postMcpResponse(requestId,options){return this.protocolSession?.respond(requestId,options)??!1}postMcpNotification(method,params,frameGeneration){return frameGeneration!==this.frameGeneration?!1:this.protocolSession?.notify(method,params)??!1}teardownApp(){return this.protocolSession?.teardownResource()??Promise.resolve(!1)}postToolResult(requestId,options){const value=record(options);if(typeof requestId!="string"||!requestId.trim()||!value)return;const frameGeneration=value.frameGeneration;if(typeof frameGeneration!="number"||!Number.isSafeInteger(frameGeneration)||frameGeneration!==this.frameGeneration)return;const hasResult=Object.prototype.hasOwnProperty.call(value,"result"),hasError=Object.prototype.hasOwnProperty.call(value,"error");hasResult!==hasError&&(hasError&&(typeof value.error!="string"||!value.error.trim())||this.post({channel:"lyra-mcp-app",version:1,type:"tool-result",requestId,...hasResult?{result:value.result}:{},...hasError?{error:value.error}:{}}))}proxyDocument(resource){let policy=resource.resource.csp;if(resource.src){let origin;try{origin=new URL(resource.src,this.ownerDocument.baseURI).origin}catch{}policy={frameDomains:origin?[origin]:[]}}return withCsp(MCP_APP_PROXY_DOCUMENT,policy,!0)}render(){const resource=resolveResource(this.resource);if(!resource)return html`<div part="base"><p part="error">${this.localize("mcpAppUnavailable")}</p></div>`;const fallbackLabel=(!this.hasAttribute("aria-label")&&typeof this.accessibleLabel=="string"?this.accessibleLabel:"")||this.label||resource.resource.title||this.localize("mcpAppLabel"),label=purposeAccessibleLabel(this,fallbackLabel),frameGeneration=this.frameGeneration;return html`<div part="base">
2
2
  ${this.loaded?nothing:html`<p part="loading">${this.localize("mcpAppLoading")}</p>`}
3
3
  ${keyed(frameGeneration,html`<iframe
4
4
  part="frame"
@@ -6,9 +6,9 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
6
6
  sandbox="allow-forms allow-scripts"
7
7
  referrerpolicy="no-referrer"
8
8
  allow=${permissionPolicy(resource.resource.permissions)}
9
- src=${resource.src??nothing}
10
- .srcdoc=${resource.html?withCsp(resource.html,resource.resource.csp):nothing}
9
+ src=${this.protocol==="mcp-apps"?nothing:resource.src??nothing}
10
+ .srcdoc=${this.protocol==="mcp-apps"?this.proxyDocument(resource):resource.html?withCsp(resource.html,resource.resource.csp):nothing}
11
11
  style=${styleMap({height:`${this.frameHeight}px`})}
12
12
  @load=${event=>this.onLoad(event,frameGeneration,resource)}
13
13
  ></iframe>`)}
14
- </div>`}}__decorate([property({attribute:!1})],LyraMcpApp.prototype,"resource",void 0),__decorate([property({converter:heightAttributeConverter})],LyraMcpApp.prototype,"height",void 0),__decorate([property({attribute:"max-height",converter:heightAttributeConverter})],LyraMcpApp.prototype,"maxHeight",void 0),__decorate([property()],LyraMcpApp.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraMcpApp.prototype,"accessibleLabel",void 0),__decorate([state()],LyraMcpApp.prototype,"loaded",void 0),__decorate([state()],LyraMcpApp.prototype,"frameHeight",void 0),__decorate([query("iframe")],LyraMcpApp.prototype,"frame",void 0);export{LyraMcpApp};
14
+ </div>`}}__decorate([property({attribute:!1})],LyraMcpApp.prototype,"resource",void 0),__decorate([property()],LyraMcpApp.prototype,"protocol",void 0),__decorate([property({attribute:!1})],LyraMcpApp.prototype,"hostCapabilities",void 0),__decorate([property({converter:heightAttributeConverter})],LyraMcpApp.prototype,"height",void 0),__decorate([property({attribute:"max-height",converter:heightAttributeConverter})],LyraMcpApp.prototype,"maxHeight",void 0),__decorate([property()],LyraMcpApp.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraMcpApp.prototype,"accessibleLabel",void 0),__decorate([state()],LyraMcpApp.prototype,"loaded",void 0),__decorate([state()],LyraMcpApp.prototype,"frameHeight",void 0),__decorate([query("iframe")],LyraMcpApp.prototype,"frame",void 0);export{LyraMcpApp};
@@ -84,11 +84,11 @@ label?:string;
84
84
  /** Host `aria-label`, forwarded to the internal `role="log"` element -- an `aria-label` left
85
85
  * on the custom-element host itself names nothing, because the log role lives inside the
86
86
  * shadow root. Wins over `label` and the localized default. */
87
- accessibleLabel:string|null;private unreadDividerTop;private scrollEl?;private contentEl?;private contentSlot?;private pendingUserIntent;private pendingUserIntentExpiryFrame;private scrollbarDragActive;private scrollbarDragWindow?;private isMounting;private pendingScrollBehavior?;private contentResizeObserver?;private contentMutationObserver?;private readonly announcements;private get announcementSink();private get livePoliteness();private scrollResizeObserver?;private growthFrame;private listenedVirtualList?;private observerWindow?;private armedMode;private armGeneration;private followFocusRepair;private readonly knownProjectedNodes;private unreadBoundaryEl?;private messageElementsCache;private get messageElements();private collectMessageElements;private get virtualListEl();private get effectiveBottomThreshold();private get effectiveUnreadStartIndex();connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues<this>):void;firstUpdated(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private transcriptFocusOwner;
87
+ accessibleLabel:string|null;private unreadDividerTop;private scrollEl?;private contentEl?;private contentSlot?;private pendingUserIntent;private keyboardScrollIntent?;private pendingUserIntentExpiryFrame;private scrollbarDragActive;private scrollbarDragWindow?;private isMounting;private pendingScrollBehavior?;private contentResizeObserver?;private contentMutationObserver?;private readonly announcements;private get announcementSink();private get livePoliteness();private scrollResizeObserver?;private growthFrame;private listenedVirtualList?;private observerWindow?;private armedMode;private armGeneration;private followFocusRepair;private readonly knownProjectedNodes;private unreadBoundaryEl?;private messageElementsCache;private get messageElements();private collectMessageElements;private get virtualListEl();private get effectiveBottomThreshold();private get effectiveUnreadStartIndex();connectedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues<this>):void;firstUpdated(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private transcriptFocusOwner;
88
88
  /** Scrolls to the end and re-engages `follow`. Default `smooth`, forced to `auto` under
89
89
  * `prefers-reduced-motion`. */
90
90
  scrollToBottom(options?:{behavior?:'auto'|'smooth';}):void;
91
91
  /** Scrolls the unread divider to the top of the view; `false` when `unreadStartIndex` is
92
92
  * `null`/out of range. Does not re-engage `follow`. See the class doc for why virtual mode uses
93
93
  * `align: 'start'` and what that trades off. */
94
- scrollToUnread(options?:{behavior?:'auto'|'smooth';}):boolean;private performScrollToEnd;private get totalCount();private get unreadCount();private pillLabel;private updateUnreadDividerPosition;private syncSemanticUnreadBoundary;private markUserIntent;private readonly passiveIntent;private cancelPendingUserIntentExpiry;private clearUserIntent;private consumeUserIntent;private onPointerDown;private onPointerUp;private releaseScrollbarDragListeners;private onKeyDown;private onScroll;private onVirtualScroll;private onSlotChange;private scheduleGrowthTick;private announcementTextFor;private onContentMutations;private announceProjectedNode;private announceAfterRender;private announceNewProjectedNodes;private armObservers;private teardownObservers;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chat-viewport':LyraChatViewport;}}
94
+ scrollToUnread(options?:{behavior?:'auto'|'smooth';}):boolean;private performScrollToEnd;private get totalCount();private get unreadCount();private pillLabel;private updateUnreadDividerPosition;private syncSemanticUnreadBoundary;private markUserIntent;private readonly passiveIntent;private cancelPendingUserIntentExpiry;private clearUserIntent;private consumeUserIntent;private onPointerDown;private onPointerUp;private releaseScrollbarDragListeners;private clearKeyboardScrollIntent;private onKeyDown;private onScroll;private onVirtualScroll;private onSlotChange;private scheduleGrowthTick;private announcementTextFor;private onContentMutations;private announceProjectedNode;private announceAfterRender;private announceNewProjectedNodes;private armObservers;private teardownObservers;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chat-viewport':LyraChatViewport;}}
@@ -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")&&registry&&!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")&&registry&&!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"
@@ -28,9 +28,9 @@ import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';impo
28
28
  *
29
29
  * The toolbar has no `size`/`compact` property of its own: every built-in action composes
30
30
  * `<lr-icon-button>` (the embedded `lr-copy-button` does the same one level deeper), so each one's
31
- * hit area is that component's shared `--lr-icon-button-size` floor (2.5rem/40px), same as
32
- * everywhere else in the library. For a dense action row where 40px per action is more than the
33
- * layout can afford, lower `--lr-icon-button-size-scope` (the subtree-scoped input) or
31
+ * hit area follows that component's shared `--lr-icon-button-size` floor, same as
32
+ * everywhere else in the library. For a denser action row, lower
33
+ * `--lr-icon-button-size-scope` (the subtree-scoped input) or
34
34
  * `--lr-theme-icon-button-size` (the application-wide one) -- NOT `--lr-icon-button-size` itself,
35
35
  * which every `LyraElement` re-declares on its own `:host` and so never reaches a composed child
36
36
  * (`internal/tokens.test.ts` proves this) -- on this element or any ancestor of it;
@@ -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 - Passthrough from rendered Markdown, tool-result, or widget content, or
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))}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.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){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
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
- >`;case"tool-call":{if(this.toolDisplay==="block")return this.renderToolBlock(part,pairing?.results.get(part.id));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
+ >`: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
- >`;case"attachment":return html`<lr-attachment-chip
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>`;case"data":return part.widget&&typeof part.widget=="object"?html`<lr-widget-renderer .document=${{version:"2",root:part.widget}}></lr-widget-renderer>`:html`<lr-json-viewer .data=${part.data}></lr-json-viewer>`;case"audio":{const src=safeMediaSrc(part.src);return html`${src?html`<audio part="audio-control" controls>
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';import'../../agent-tools/thinking-panel/thinking-panel.js';import'../../agent-tools/tool-call-block/tool-call-block.js';import'../../agent-tools/tool-call-chip/tool-call-chip.js';import'../../agent-tools/tool-result-view/tool-result-view.js';import'../../forms/button/button.js';import'../../layout/details/details.js';import'../../media/attachment-chip/attachment-chip.js';import'../../retrieval/citation-badge/citation-badge.js';import'../../utility/json-viewer/json-viewer.js';import'../markdown/markdown.js';import'../widget-renderer/widget-renderer.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"../../agent-tools/thinking-panel/thinking-panel.js";import"../../agent-tools/tool-call-block/tool-call-block.js";import"../../agent-tools/tool-call-chip/tool-call-chip.js";import"../../agent-tools/tool-result-view/tool-result-view.js";import"../../forms/button/button.js";import"../../layout/details/details.js";import"../../media/attachment-chip/attachment-chip.js";import"../../retrieval/citation-badge/citation-badge.js";import"../../utility/json-viewer/json-viewer.js";import"../markdown/markdown.js";import"../widget-renderer/widget-renderer.js";import{defineElement}from"../../../internal/prefix.js";import{LyraMessageParts}from"./message-parts.class.js";defineElement("message-parts",LyraMessageParts);
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);
@@ -206,7 +206,7 @@ get autocorrect():boolean;set autocorrect(next:boolean|string);autocomplete:stri
206
206
  * attempts, including a synchronous fieldset cascade. */
207
207
  get open():boolean;set open(next:boolean);
208
208
  /** Visual size on the shared six-tier control ladder. `small`/`medium`/`large` alias
209
- * `s`/`m`/`l`; the preview action keeps the library-wide 40px minimum hit area. */
209
+ * `s`/`m`/`l`; the preview action keeps the shared --lr-icon-button-size minimum hit area. */
210
210
  size:LyraSize;private get activeIndex();private get query();private readonly slotPresence;private previewingId;private listId;private controlId;private audioEl?;private pendingPreviewId;private previewGeneration;protected get catalogEditing():CatalogPickerController<LyraVoiceCatalogEntry>;private readonly catalogPicker;connectedCallback():void;protected willUpdate(changed:PropertyValues<this>):void;disconnectedCallback():void;adoptedCallback():void;
211
211
  /** The current voice id (empty string when nothing is selected).*/
212
212
  get value():string;set value(next:string);
@@ -46,7 +46,7 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
46
46
  * node bounds dwarf the visible viewport the raw rectangle collapses to a few pixels, which
47
47
  * leaves the only pointer-drag handle for panning effectively unclickable; the floor grows it
48
48
  * symmetrically about its own centre so it still points at what the viewport shows. The visible
49
- * `viewport` stays exact. Defaults to Lyra's 40px interaction floor; set `0` to opt out.
49
+ * `viewport` stays exact. Defaults to the shared `--lr-icon-button-size` floor; set `0` to opt out.
50
50
  * @status stable
51
51
  * @since 4.0.0
52
52
  */