@aceshooting/lyra-ui 30.5.0 → 30.7.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 (203) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +1 -1
  3. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.d.ts +7 -4
  4. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +5 -5
  5. package/dist/components/conversation/code-block/onig.provenance.json +1 -1
  6. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  7. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  8. package/dist/components/conversation/markdown/markdown-core.class.d.ts +11 -1
  9. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  10. package/dist/components/conversation/markdown/markdown-progressive.js +2 -2
  11. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  12. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  13. package/dist/components/conversation/markdown/markdown.class.d.ts +11 -1
  14. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  15. package/dist/components/conversation/message-parts/message-parts.class.d.ts +1 -1
  16. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  17. package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
  18. package/dist/components/conversation/model-select/model-select.class.d.ts +8 -1
  19. package/dist/components/conversation/model-select/model-select.class.js +2 -2
  20. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +5 -0
  21. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
  22. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  23. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  24. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  25. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  26. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +6 -0
  27. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  28. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +9 -2
  29. package/dist/components/conversation/voice-picker/voice-picker.class.js +2 -2
  30. package/dist/components/conversation/widget-renderer/default-registry.js +1 -1
  31. package/dist/components/conversation/widget-renderer/registry.d.ts +1 -27
  32. package/dist/components/conversation/widget-renderer/registry.js +1 -1
  33. package/dist/components/conversation/widget-renderer/resolve.d.ts +1 -29
  34. package/dist/components/conversation/widget-renderer/resolve.js +1 -1
  35. package/dist/components/conversation/widget-renderer/widget-renderer.class.d.ts +1 -1
  36. package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
  37. package/dist/components/forms/catalog-picker-base.d.ts +3 -1
  38. package/dist/components/forms/catalog-picker-base.js +3 -3
  39. package/dist/components/forms/combobox/combobox.class.d.ts +9 -2
  40. package/dist/components/forms/combobox/combobox.class.js +2 -2
  41. package/dist/components/forms/date-picker/date-input.class.d.ts +9 -2
  42. package/dist/components/forms/date-picker/date-input.class.js +2 -2
  43. package/dist/components/forms/input/input-shared.d.ts +9 -2
  44. package/dist/components/forms/input/input-shared.js +2 -2
  45. package/dist/components/forms/input/time-input.class.d.ts +9 -2
  46. package/dist/components/forms/input/time-input.class.js +2 -2
  47. package/dist/components/forms/input/time-input.styles.js +1 -1
  48. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +18 -3
  49. package/dist/components/forms/locale-picker/locale-picker.class.js +2 -2
  50. package/dist/components/forms/phone-input/phone-input.class.d.ts +9 -2
  51. package/dist/components/forms/phone-input/phone-input.class.js +2 -2
  52. package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
  53. package/dist/components/forms/select/select.class.d.ts +9 -2
  54. package/dist/components/forms/select/select.class.js +2 -2
  55. package/dist/components/forms/textarea/textarea.class.d.ts +9 -2
  56. package/dist/components/forms/textarea/textarea.class.js +2 -2
  57. package/dist/components/forms/token-input/token-input.class.d.ts +9 -2
  58. package/dist/components/forms/token-input/token-input.class.js +2 -2
  59. package/dist/components/forms/token-input/token-input.styles.js +1 -1
  60. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +5 -2
  61. package/dist/components/layout/dock-panel/dock-panel.styles.js +1 -1
  62. package/dist/components/layout/menu/menu-item.class.d.ts +7 -4
  63. package/dist/components/layout/menu/menu-item.class.js +3 -2
  64. package/dist/components/layout/multi-split/multi-split.class.d.ts +73 -6
  65. package/dist/components/layout/multi-split/multi-split.class.js +4 -4
  66. package/dist/components/layout/multi-split/multi-split.styles.js +1 -1
  67. package/dist/components/layout/page/page.class.d.ts +7 -0
  68. package/dist/components/layout/page/page.styles.js +1 -1
  69. package/dist/components/media/flag/language-map.js +1 -1
  70. package/dist/components/media/image-viewer/image-viewer-panorama.d.ts +1 -5
  71. package/dist/components/media/image-viewer/image-viewer-panorama.js +1 -8
  72. package/dist/components/media/image-viewer/image-viewer.class.d.ts +1 -1
  73. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  74. package/dist/components/media/map/map-control-options.d.ts +7 -3
  75. package/dist/components/media/map/map-control-options.js +1 -1
  76. package/dist/components/media/map/map-controls-lifecycle.js +1 -1
  77. package/dist/components/media/map/map-feature-loader.js +1 -1
  78. package/dist/components/media/map/map-loader.d.ts +10 -4
  79. package/dist/components/media/map/map-loader.js +1 -1
  80. package/dist/components/media/map/map-scene-admission.js +1 -0
  81. package/dist/components/media/map/map-scene-completion-adapter.js +1 -0
  82. package/dist/components/media/map/map-scene-completion-camera.js +1 -0
  83. package/dist/components/media/map/map-scene-configuration-controller.js +1 -0
  84. package/dist/components/media/map/map-scene-configuration.d.ts +15 -0
  85. package/dist/components/media/map/map-scene-configuration.js +1 -0
  86. package/dist/components/media/map/map-scene-controls.js +1 -0
  87. package/dist/components/media/map/map-scene-errors.js +1 -0
  88. package/dist/components/media/map/map-scene-line-layer.js +1 -0
  89. package/dist/components/media/map/map-scene-lines.js +1 -0
  90. package/dist/components/media/map/map-scene-owner.js +1 -0
  91. package/dist/components/media/map/map-scene-position-registry.js +1 -0
  92. package/dist/components/media/map/map-scene-render-controller.js +1 -0
  93. package/dist/components/media/map/map-scene-render-input.js +1 -0
  94. package/dist/components/media/map/map-scene-source-snapshot.js +1 -0
  95. package/dist/components/media/map/map-scene-status.js +1 -0
  96. package/dist/components/media/map/map-scene-types.d.ts +55 -0
  97. package/dist/components/media/map/map.class.d.ts +60 -12
  98. package/dist/components/media/map/map.class.js +23 -6
  99. package/dist/components/media/map/map.styles.js +1 -1
  100. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +1 -1
  101. package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
  102. package/dist/components/media/video/video.class.d.ts +1 -1
  103. package/dist/components/media/video/video.class.js +1 -1
  104. package/dist/components/retrieval/graph/graph-builtin-3d-engine.js +1 -1
  105. package/dist/components/retrieval/graph/graph-curvature.js +1 -0
  106. package/dist/components/retrieval/graph/graph-engine-columns.js +1 -1
  107. package/dist/components/retrieval/graph/graph-model.d.ts +4 -0
  108. package/dist/components/retrieval/graph/graph-node-renderer.d.ts +13 -0
  109. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -0
  110. package/dist/components/retrieval/graph/graph-source-controller.js +1 -1
  111. package/dist/components/retrieval/graph/graph-spatial-controller.js +3 -1
  112. package/dist/components/retrieval/graph/graph-spatial.js +1 -1
  113. package/dist/components/retrieval/graph/graph-webgl-engine.js +1 -1
  114. package/dist/components/retrieval/graph/graph.class.d.ts +11 -3
  115. package/dist/components/retrieval/graph/graph.class.js +4 -4
  116. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +8 -2
  117. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +4 -2
  118. package/dist/events.d.ts +36 -1
  119. package/dist/framework-types.d.ts +1 -1
  120. package/dist/internal/collection-policy.js +1 -0
  121. package/dist/internal/collection-snapshot.js +1 -1
  122. package/dist/internal/default-strings/media.generated.js +1 -1
  123. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  124. package/dist/internal/engine-3d-loader.d.ts +8 -2
  125. package/dist/internal/engine-3d-loader.js +1 -1
  126. package/dist/internal/form-control.styles.js +1 -1
  127. package/dist/internal/locale-loaders.generated.js +1 -1
  128. package/dist/internal/localization-runtime.js +1 -1
  129. package/dist/internal/localization-types.d.ts +1 -1
  130. package/dist/internal/localization.js +1 -1
  131. package/dist/internal/map-camera-follow-controller.d.ts +9 -0
  132. package/dist/internal/map-camera-follow-controller.js +1 -0
  133. package/dist/internal/map-camera-follow-data.js +1 -0
  134. package/dist/internal/map-camera-follow-scene.js +1 -0
  135. package/dist/internal/map-camera-session-controller.d.ts +59 -0
  136. package/dist/internal/map-camera-session-controller.js +1 -0
  137. package/dist/internal/map-camera-session-data.d.ts +16 -0
  138. package/dist/internal/map-camera-session-data.js +1 -0
  139. package/dist/internal/map-camera-session.js +1 -0
  140. package/dist/internal/map-scene-session.js +1 -0
  141. package/dist/internal/media-panorama.d.ts +5 -0
  142. package/dist/internal/media-panorama.js +8 -0
  143. package/dist/internal/package-metadata.js +1 -1
  144. package/dist/internal/sequence-playback-binding.js +1 -0
  145. package/dist/internal/typed-columns.d.ts +3 -1
  146. package/dist/internal/typed-columns.js +1 -1
  147. package/dist/internal/variants.d.ts +7 -0
  148. package/dist/internal/widget-default-registry.js +1 -0
  149. package/dist/internal/widget-document.d.ts +29 -0
  150. package/dist/internal/widget-document.js +1 -0
  151. package/dist/internal/widget-type-registry.d.ts +27 -0
  152. package/dist/internal/widget-type-registry.js +1 -0
  153. package/dist/lyra.d.ts +1 -1
  154. package/dist/lyra.js +1 -1
  155. package/dist/map-camera-session.d.ts +10 -0
  156. package/dist/map-camera-session.js +1 -0
  157. package/dist/sequence-time-binding.d.ts +3 -0
  158. package/dist/sequence-time-binding.js +1 -0
  159. package/dist/simulation-clock.d.ts +3 -0
  160. package/dist/simulation-clock.js +1 -0
  161. package/dist/time-index.d.ts +3 -0
  162. package/dist/time-index.js +1 -0
  163. package/llms/components/lr-artifact-panel.md +8 -3
  164. package/llms/components/lr-combobox.md +2 -0
  165. package/llms/components/lr-country-picker.md +2 -0
  166. package/llms/components/lr-currency-picker.md +2 -0
  167. package/llms/components/lr-date-picker.md +2 -0
  168. package/llms/components/lr-dock-panel.md +5 -2
  169. package/llms/components/lr-graph.md +121 -3
  170. package/llms/components/lr-input.md +2 -0
  171. package/llms/components/lr-knowledge-graph-explorer.md +6 -1
  172. package/llms/components/lr-locale-picker.md +8 -1
  173. package/llms/components/lr-map.md +315 -7
  174. package/llms/components/lr-markdown-core.md +2 -1
  175. package/llms/components/lr-markdown.md +12 -1
  176. package/llms/components/lr-menu.md +5 -2
  177. package/llms/components/lr-model-select.md +2 -0
  178. package/llms/components/lr-multi-split.md +53 -4
  179. package/llms/components/lr-native-time-input.md +2 -0
  180. package/llms/components/lr-number-input.md +2 -0
  181. package/llms/components/lr-page.md +9 -1
  182. package/llms/components/lr-phone-input.md +2 -0
  183. package/llms/components/lr-select.md +2 -0
  184. package/llms/components/lr-sequence-playback.md +44 -0
  185. package/llms/components/lr-streaming-text-core.md +3 -2
  186. package/llms/components/lr-streaming-text.md +4 -1
  187. package/llms/components/lr-suggestion-chips.md +6 -2
  188. package/llms/components/lr-textarea.md +2 -0
  189. package/llms/components/lr-time-input.md +2 -0
  190. package/llms/components/lr-time-zone-picker.md +2 -0
  191. package/llms/components/lr-token-input.md +2 -0
  192. package/llms/components/lr-unit-picker.md +2 -0
  193. package/llms/components/lr-voice-picker.md +2 -0
  194. package/llms/peers.md +7 -7
  195. package/llms/shared/imports-and-registration.md +1 -1
  196. package/llms/shared/localization-and-rtl.md +15 -1
  197. package/llms/shared/testing-and-utilities.md +184 -0
  198. package/llms/shared.md +200 -2
  199. package/locales.json +1 -1
  200. package/package.json +37 -21
  201. package/registrations.json +1 -1
  202. package/skills/lyra-ui/lyra-gen.md +2 -0
  203. /package/dist/{components/media/image-viewer/image-viewer-panorama.styles.js → internal/media-panorama.styles.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{progressiveMarkdownBlocks,streamingTailText}from"./markdown-streaming-tail.js";import{MARKDOWN_CODE_HEADER_MAX,sanitizeCodeLanguageLabel}from"./markdown-code-header.js";import{html,nothing}from"lit";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{styleMap}from"lit/directives/style-map.js";import{Slugger}from"../../../internal/slugger.js";import{finiteInteger}from"../../../internal/numbers.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeLinkHref,safeMediaSrc}from"../../../internal/safe-url.js";import{supportsCustomHighlights}from"../../../internal/text-highlights.js";import{normalizeShikiLanguage,SHIKI_THEMES}from"../code-block/shiki-types.js";import{resolveIsDarkTheme,watchDarkTheme}from"../code-block/shiki-dark-theme.js";import{loadMarkdownDeps,getMarkdownDepsIfLoaded}from"./markdown-loader.js";import{getKatex}from"./katex-loader.js";function createMarkdownParser(marked){if(!(!marked||typeof marked!="object"&&typeof marked!="function"||typeof marked.Marked!="function"))return new marked.Marked}class MarkdownParserController{get(marked){if(marked)return this.module!==marked&&(this.module=marked,this.parser=createMarkdownParser(marked)),this.parser}}function normalizeMarkdownLeadingTabs(content,tabSize){const width=finiteInteger(tabSize,4,1,32);return content.replace(/^[\t ]+/gm,indentation=>{let column=0,normalized="";for(const character of indentation){const spaces=character===" "?width-column%width:1;normalized+=" ".repeat(spaces),column+=spaces}return normalized})}class MarkdownOwnedAnimationFrameController{get handle(){return this.pending?.handle}get settled(){return this.pending?.settled}request(owner,callback){if(this.pending)return this.pending.handle;let resolveFrame;const settled=new Promise(resolve=>{resolveFrame=resolve}),pending={owner,settled,resolve:resolveFrame};this.pending=pending;try{pending.handle=owner.requestAnimationFrame(()=>{this.pending===pending&&(this.pending=void 0,pending.resolve(),callback())})}catch{this.pending===pending&&(this.pending=void 0),pending.resolve();return}return pending.handle}cancel(){const pending=this.pending;if(!pending)return!1;this.pending=void 0;try{pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle)}catch{}finally{pending.resolve()}return!0}}const HTML_ESCAPES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function escapeHtml(text){return text.replace(/[&<>"']/g,ch=>HTML_ESCAPES[ch]??ch)}const TEXT_ESCAPE_PATTERN=/[<>"']|&(?!(?:#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g;function escapeMarkdownText(text){return text.replace(TEXT_ESCAPE_PATTERN,ch=>HTML_ESCAPES[ch]??ch)}function cleanHref(href){try{return encodeURI(href).replace(/%25/g,"%")}catch{return null}}const HIGHLIGHT_CACHE_MAX=100,MARKDOWN_HIGHLIGHT_SOURCE_MAX=8192,HIGHLIGHT_CACHE_MAX_BYTES=2*1024*1024,HIGHLIGHT_CACHE_ENTRY_MAX_BYTES=512*1024,FAILED_HIGHLIGHT_MAX=256;function markdownHighlightKey(language,code){let a=2166136261,b=2654435769;const input=`${language}\0${code}`;for(let index=0;index<input.length;index++){const unit=input.charCodeAt(index);a=Math.imul(a^unit,16777619)>>>0,b=Math.imul(b^unit,2246822507)>>>0}return`${language}:${code.length}:${a.toString(36)}:${b.toString(36)}`}function addFailedHighlightKey(failed,key){if(!failed.has(key)){if(failed.size>=FAILED_HIGHLIGHT_MAX){const oldest=failed.values().next().value;oldest!==void 0&&failed.delete(oldest)}failed.add(key)}}async function processPendingHighlights(pending,worker,concurrency=4){const unique=[...new Map(pending.map(item=>[item.key,item])).values()];let next=0;const run=async()=>{for(;next<unique.length;){const item=unique[next++];item&&await worker(item)}};await Promise.all(Array.from({length:Math.min(concurrency,unique.length)},()=>run()))}function getCachedHighlight(cache,key){const cached=cache.get(key);return cached!==void 0&&(cache.delete(key),cache.set(key,cached)),cached}const cacheBytes=new WeakMap;function setCachedHighlight(cache,key,html2,max=HIGHLIGHT_CACHE_MAX,maxBytes=HIGHLIGHT_CACHE_MAX_BYTES){const entryBytes=(key.length+html2.length)*2;if(entryBytes>HIGHLIGHT_CACHE_ENTRY_MAX_BYTES||entryBytes>maxBytes)return!1;let retainedBytes=cacheBytes.get(cache)??0;const evict=evictedKey=>{retainedBytes-=(evictedKey.length+(cache.get(evictedKey)??"").length)*2,cache.delete(evictedKey)};for(cache.has(key)&&evict(key);cache.size>=max||retainedBytes+entryBytes>maxBytes;){const oldest=cache.keys().next().value;if(oldest===void 0)break;evict(oldest)}return cache.set(key,html2),cacheBytes.set(cache,retainedBytes+entryBytes),!0}const MATH_INLINE_RE=/^\$(?![\s$])((?:\\\$|[^$])*?(?:\\\$|[^$\s\\]))\$(?![$\d])/;function mathExtension(renderMath){return{name:"math",level:"inline",start(src){const index=src.indexOf("$");return index===-1?void 0:index},tokenizer(src){if(src.startsWith("$$")){const close=src.indexOf("$$",2);if(close>2){const raw=src.slice(0,close+2),tex=src.slice(2,close).trim();if(tex)return{type:"math",raw,tex,display:!0}}}const inline=MATH_INLINE_RE.exec(src);if(inline)return{type:"math",raw:inline[0],tex:inline[1].replace(/\\\$/g,"$").trim(),display:!1}},renderer(token){return renderMath(token)}}}const MARKDOWN_SANITIZER_WARNING_KEY="lyra-markdown-dompurify-unavailable",MARKDOWN_SANITIZER_WARNING="<lr-markdown>/<lr-markdown-core>: HTML sanitization is unavailable because the optional DOMPurify peer could not load. Content is rendered as plain text unless trusted HTML is explicitly selected.";function warnMarkdownSanitizerUnavailable(){devWarnOnce(MARKDOWN_SANITIZER_WARNING_KEY,MARKDOWN_SANITIZER_WARNING)}function isTaskListItem(item){return typeof item=="object"&&item!==null&&item.task===!0}function taskItemCheckboxLabel(context,tokens){for(const candidate of tokens){if(typeof candidate!="object"||candidate===null)continue;const token=candidate;if(token.type!=="text"&&token.type!=="paragraph"||!Array.isArray(token.tokens))continue;const inlineTokens=token.tokens.filter(inline=>typeof inline!="object"||inline===null?!0:inline.type!=="checkbox"),label=context.parser.parseInline(inlineTokens,context.parser.textRenderer).replace(/\s+/g," ").trim();if(label)return label}return null}function parseMarkdownDocument(options){return createMarkdownRenderContext(options).render(options.content)}function createMarkdownRenderContext(options){const{marked,gfm,linkTarget,escapeHtmlOption,trustedHtmlOption,highlightCodeOption,getCachedHighlight:getCached,failedHighlightKeys,headingAnchorsOption,mathOption,cachedKatex,pendingKeys,headingTreeOut}=options,headingOffset=finiteInteger(options.headingOffset,0),slugger=options.slugger??new Slugger,activeHighlightKeys=options.activeHighlightKeys??new Set,pendingHighlightKeys=new Set(options.pendingKeys.map(({key})=>key)),taskItemCheckboxLabels=[];let hadMathFallback=!1,hasRawHtml=(options.markedConfigurations??[]).some(configuration=>!!(configuration?.renderer||configuration?.hooks||configuration?.extensions)),codeInvocations=0,codeHasSourceTabs=!1;const probeCodeTabs=options.codeBlockHeaderOption===!0&&options.rawContent!==void 0&&/^[\t ]*\t/m.test(options.rawContent)?rawCodeTabProbe(options.rawContent,options.content,options.tabSize??4):void 0,headerEnabled=options.codeBlockHeaderOption===!0&&!!(options.codeFrameNonce&&options.codeBlocksOut),wrapCode=(inner,token,lang)=>{const ordinal=codeInvocations++,source=token.text.replace(/\n$/,""),hasSourceTabs=probeCodeTabs?.(token.raw)??!1,records=options.codeBlocksOut;if(!headerEnabled||!records||!source||token.escaped||records.length+(options.codeBlockIndexOffset??0)>=MARKDOWN_CODE_HEADER_MAX)return inner;const index=records.length+(options.codeBlockIndexOffset??0);return/^ +/m.test(source)&&hasSourceTabs&&(codeHasSourceTabs=!0),records.push({language:sanitizeCodeLanguageLabel(lang),source,ordinal}),`<div part='code-block-frame' data-lr-code-frame='${options.codeFrameNonce}:${index}'>${inner.replace(/\n$/,"")}</div>
1
+ import{progressiveMarkdownBlocks,streamingTailText}from"./markdown-streaming-tail.js";import{MARKDOWN_CODE_HEADER_MAX,sanitizeCodeLanguageLabel}from"./markdown-code-header.js";import{html,nothing}from"lit";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{styleMap}from"lit/directives/style-map.js";import{Slugger}from"../../../internal/slugger.js";import{finiteInteger}from"../../../internal/numbers.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeLinkHref,safeMediaSrc}from"../../../internal/safe-url.js";import{supportsCustomHighlights}from"../../../internal/text-highlights.js";import{normalizeShikiLanguage,SHIKI_THEMES}from"../code-block/shiki-types.js";import{resolveIsDarkTheme,watchDarkTheme}from"../code-block/shiki-dark-theme.js";import{loadMarkdownDeps,getMarkdownDepsIfLoaded}from"./markdown-loader.js";import{getKatex}from"./katex-loader.js";function createMarkdownParser(marked){if(!(!marked||typeof marked!="object"&&typeof marked!="function"||typeof marked.Marked!="function"))return new marked.Marked}class MarkdownParserController{get(marked){if(marked)return this.module!==marked&&(this.module=marked,this.parser=createMarkdownParser(marked)),this.parser}}function normalizeMarkdownLeadingTabs(content,tabSize){const width=finiteInteger(tabSize,4,1,32);return content.replace(/^[\t ]+/gm,indentation=>{let column=0,normalized="";for(const character of indentation){const spaces=character===" "?width-column%width:1;normalized+=" ".repeat(spaces),column+=spaces}return normalized})}class MarkdownOwnedAnimationFrameController{get handle(){return this.pending?.handle}get settled(){return this.pending?.settled}request(owner,callback){if(this.pending)return this.pending.handle;let resolveFrame;const settled=new Promise(resolve=>{resolveFrame=resolve}),pending={owner,settled,resolve:resolveFrame};this.pending=pending;try{pending.handle=owner.requestAnimationFrame(()=>{this.pending===pending&&(this.pending=void 0,pending.resolve(),callback())})}catch{this.pending===pending&&(this.pending=void 0),pending.resolve();return}return pending.handle}cancel(){const pending=this.pending;if(!pending)return!1;this.pending=void 0;try{pending.handle!==void 0&&pending.owner.cancelAnimationFrame(pending.handle)}catch{}finally{pending.resolve()}return!0}}const HTML_ESCAPES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function escapeHtml(text){return text.replace(/[&<>"']/g,ch=>HTML_ESCAPES[ch]??ch)}const TEXT_ESCAPE_PATTERN=/[<>"']|&(?!(?:#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g;function escapeMarkdownText(text){return text.replace(TEXT_ESCAPE_PATTERN,ch=>HTML_ESCAPES[ch]??ch)}function cleanHref(href){try{return encodeURI(href).replace(/%25/g,"%")}catch{return null}}const HIGHLIGHT_CACHE_MAX=100,MARKDOWN_HIGHLIGHT_SOURCE_MAX=8192,HIGHLIGHT_CACHE_MAX_BYTES=2*1024*1024,HIGHLIGHT_CACHE_ENTRY_MAX_BYTES=512*1024,FAILED_HIGHLIGHT_MAX=256;function markdownHighlightKey(language,code){let a=2166136261,b=2654435769;const input=`${language}\0${code}`;for(let index=0;index<input.length;index++){const unit=input.charCodeAt(index);a=Math.imul(a^unit,16777619)>>>0,b=Math.imul(b^unit,2246822507)>>>0}return`${language}:${code.length}:${a.toString(36)}:${b.toString(36)}`}function addFailedHighlightKey(failed,key){if(!failed.has(key)){if(failed.size>=FAILED_HIGHLIGHT_MAX){const oldest=failed.values().next().value;oldest!==void 0&&failed.delete(oldest)}failed.add(key)}}async function processPendingHighlights(pending,worker,concurrency=4){const unique=[...new Map(pending.map(item=>[item.key,item])).values()];let next=0;const run=async()=>{for(;next<unique.length;){const item=unique[next++];item&&await worker(item)}};await Promise.all(Array.from({length:Math.min(concurrency,unique.length)},()=>run()))}function getCachedHighlight(cache,key){const cached=cache.get(key);return cached!==void 0&&(cache.delete(key),cache.set(key,cached)),cached}const cacheBytes=new WeakMap;function setCachedHighlight(cache,key,html2,max=HIGHLIGHT_CACHE_MAX,maxBytes=HIGHLIGHT_CACHE_MAX_BYTES){const entryBytes=(key.length+html2.length)*2;if(entryBytes>HIGHLIGHT_CACHE_ENTRY_MAX_BYTES||entryBytes>maxBytes)return!1;let retainedBytes=cacheBytes.get(cache)??0;const evict=evictedKey=>{retainedBytes-=(evictedKey.length+(cache.get(evictedKey)??"").length)*2,cache.delete(evictedKey)};for(cache.has(key)&&evict(key);cache.size>=max||retainedBytes+entryBytes>maxBytes;){const oldest=cache.keys().next().value;if(oldest===void 0)break;evict(oldest)}return cache.set(key,html2),cacheBytes.set(cache,retainedBytes+entryBytes),!0}const MATH_INLINE_RE=/^\$(?![\s$])((?:\\\$|[^$])*?(?:\\\$|[^$\s\\]))\$(?![$\d])/;function mathExtension(renderMath){return{name:"math",level:"inline",start(src){const index=src.indexOf("$");return index===-1?void 0:index},tokenizer(src){if(src.startsWith("$$")){const close=src.indexOf("$$",2);if(close>2){const raw=src.slice(0,close+2),tex=src.slice(2,close).trim();if(tex)return{type:"math",raw,tex,display:!0}}}const inline=MATH_INLINE_RE.exec(src);if(inline)return{type:"math",raw:inline[0],tex:inline[1].replace(/\\\$/g,"$").trim(),display:!1}},renderer(token){return renderMath(token)}}}const MARKDOWN_SANITIZER_WARNING_KEY="lyra-markdown-dompurify-unavailable",MARKDOWN_SANITIZER_WARNING="<lr-markdown>/<lr-markdown-core>: HTML sanitization is unavailable because the optional DOMPurify peer could not load. Content is rendered as plain text unless trusted HTML is explicitly selected.";function warnMarkdownSanitizerUnavailable(){devWarnOnce(MARKDOWN_SANITIZER_WARNING_KEY,MARKDOWN_SANITIZER_WARNING)}function isTaskListItem(item){return typeof item=="object"&&item!==null&&item.task===!0}function taskItemCheckboxLabel(context,tokens){for(const candidate of tokens){if(typeof candidate!="object"||candidate===null)continue;const token=candidate;if(token.type!=="text"&&token.type!=="paragraph"||!Array.isArray(token.tokens))continue;const inlineTokens=token.tokens.filter(inline=>typeof inline!="object"||inline===null?!0:inline.type!=="checkbox"),label=context.parser.parseInline(inlineTokens,context.parser.textRenderer).replace(/\s+/g," ").trim();if(label)return label}return null}function parseMarkdownDocument(options){return createMarkdownRenderContext(options).render(options.content)}function createMarkdownRenderContext(options){const{marked,gfm,linkTarget,escapeHtmlOption,trustedHtmlOption,withoutImagesOption=!1,highlightCodeOption,getCachedHighlight:getCached,failedHighlightKeys,headingAnchorsOption,mathOption,cachedKatex,pendingKeys,headingTreeOut}=options,headingOffset=finiteInteger(options.headingOffset,0),slugger=options.slugger??new Slugger,activeHighlightKeys=options.activeHighlightKeys??new Set,pendingHighlightKeys=new Set(options.pendingKeys.map(({key})=>key)),taskItemCheckboxLabels=[];let hadMathFallback=!1,hasRawHtml=(options.markedConfigurations??[]).some(configuration=>!!(configuration?.renderer||configuration?.hooks||configuration?.extensions)),codeInvocations=0,codeHasSourceTabs=!1;const probeCodeTabs=options.codeBlockHeaderOption===!0&&options.rawContent!==void 0&&/^[\t ]*\t/m.test(options.rawContent)?rawCodeTabProbe(options.rawContent,options.content,options.tabSize??4):void 0,headerEnabled=options.codeBlockHeaderOption===!0&&!!(options.codeFrameNonce&&options.codeBlocksOut),wrapCode=(inner,token,lang)=>{const ordinal=codeInvocations++,source=token.text.replace(/\n$/,""),hasSourceTabs=probeCodeTabs?.(token.raw)??!1,records=options.codeBlocksOut;if(!headerEnabled||!records||!source||token.escaped||records.length+(options.codeBlockIndexOffset??0)>=MARKDOWN_CODE_HEADER_MAX)return inner;const index=records.length+(options.codeBlockIndexOffset??0);return/^ +/m.test(source)&&hasSourceTabs&&(codeHasSourceTabs=!0),records.push({language:sanitizeCodeLanguageLabel(lang),source,ordinal}),`<div part='code-block-frame' data-lr-code-frame='${options.codeFrameNonce}:${index}'>${inner.replace(/\n$/,"")}</div>
2
2
  `},instance=new marked.Marked;mathOption&&instance.use({extensions:[mathExtension(token=>{if(!cachedKatex)return hadMathFallback=!0,escapeHtml(token.display?`$$${token.tex}$$`:`$${token.tex}$`);try{const mathml=cachedKatex.renderToString(token.tex,{output:"mathml",throwOnError:!1});return`<span part='math' data-display='${token.display?"block":"inline"}'>${mathml}</span>`}catch{return escapeHtml(token.display?`$$${token.tex}$$`:`$${token.tex}$`)}})]}),instance.use({renderer:{heading(token){const depth=Math.min(6,Math.max(1,token.depth+headingOffset)),label=this.parser.parseInline(token.tokens,this.parser.textRenderer),slug=slugger.slug(label);headingTreeOut.push({id:slug,label,level:depth});const idAttr=headingAnchorsOption&&slug?` id='${escapeHtml(slug)}'`:"";return`<h${depth} part='heading'${idAttr}>${this.parser.parseInline(token.tokens)}</h${depth}>
3
3
  `},paragraph(token){return`<p part='paragraph'>${this.parser.parseInline(token.tokens)}</p>
4
4
  `},list(token){const ordered=token.ordered,start=token.start,allTaskItems=token.items.length>0&&token.items.every(isTaskListItem);let body="";for(const item of token.items)body+=this.listitem(item);const tag=ordered?"ol":"ul",startAttr=ordered&&start!==1?` start='${start}'`:"";return`<${tag}${allTaskItems?ordered?" part='list task-list'":" part='list task-list' role='list'":" part='list'"}${startAttr}>
@@ -14,8 +14,8 @@ ${this.tablerow({text:headerRow})}</thead>
14
14
  `,tbody=bodyRows?`<tbody>${bodyRows}</tbody>
15
15
  `:"";return`<div part='table-wrapper' role='group' tabindex='0'><table part='table'>
16
16
  ${thead}${tbody}</table></div>
17
- `},link(token){const text=this.parser.parseInline(token.tokens),href=cleanHref(token.href);if(href===null)return text;const safeHref=trustedHtmlOption?href:safeLinkHref(href);if(safeHref===null)return text;const titleAttr=token.title?` title='${escapeHtml(token.title)}'`:"",targetAttr=linkTarget?` target='${escapeHtml(linkTarget)}' rel='noopener noreferrer'`:"";return`<a part='link' href='${escapeHtml(safeHref)}'${titleAttr}${targetAttr}>${text}</a>`},image(token){const altText=this.parser.parseInline(token.tokens,this.parser.textRenderer),href=cleanHref(token.href);if(href===null)return escapeHtml(altText);const safeHref=trustedHtmlOption?href:safeMediaSrc(href);if(safeHref===null)return escapeHtml(altText);const titleAttr=token.title?` title='${escapeHtml(token.title)}'`:"";return`<img part='img' src='${escapeHtml(safeHref)}' alt='${escapeHtml(altText)}'${titleAttr}>`},html(token){return hasRawHtml=!0,escapeHtmlOption?escapeHtml(token.text):token.text},text(token){return escapeHtmlOption&&token.escaped===!0&&!token.tokens?escapeMarkdownText(token.text):!1}}});for(const configuration of options.markedConfigurations??[]){if(!configuration||typeof configuration!="object")continue;const configuredDefaults=Object.fromEntries(Object.entries(configuration).filter(([,value])=>value!=null));Object.keys(configuredDefaults).length>0&&instance.use(configuredDefaults)}const capable=instance;return{instance:capable,render(source,seed){let html2,state={inLink:!1,inRawBlock:!1};if(seed){const defaults={...instance.defaults,gfm,async:!1},lexer=new capable.Lexer(defaults);Object.assign(lexer.tokens.links,seed.links),Object.assign(lexer.state,seed.state);const tokens=lexer.lex(source);state={inLink:lexer.state.inLink,inRawBlock:lexer.state.inRawBlock},instance.defaults.walkTokens&&capable.walkTokens(tokens,instance.defaults.walkTokens),html2=capable.parser(tokens,defaults)}else html2=instance.parse(source,{gfm,async:!1});if(typeof html2!="string")throw new TypeError("The Markdown parser returned non-string markup.");return headerEnabled&&options.rawContent!==void 0&&options.tabSize!==void 0&&codeHasSourceTabs&&restoreMarkdownCodeTabs(instance,options,codeInvocations),{html:html2,hadMathFallback,hasRawHtml,state}}}}function rawCodeTabProbe(raw,normalized,tabSize){let cursor=0,lines;return envelope=>{if(!envelope)return!0;const start=normalized.indexOf(envelope,cursor);if(start<0)return!0;if(cursor=start+envelope.length,!lines){lines=[];let offset=0;for(const match of raw.matchAll(/[^\r\n\u2028\u2029]*(?:\r\n|[\r\n\u2028\u2029]|$)/g))match[0]&&(lines.push({normalized:offset,raw:match.index,end:match.index+match[0].length}),offset+=normalizeMarkdownLeadingTabs(match[0],tabSize).length);if(offset!==normalized.length)return!0}const locate=offset=>{let low=0,high=lines.length;for(;low+1<high;){const middle=low+high>>>1;lines[middle].normalized<=offset?low=middle:high=middle}return low},first=lines[locate(start)],last=lines[locate(Math.max(start,cursor-1))];return!first||!last||/^[\t ]*\t/m.test(raw.slice(first.raw,last.end))}}function restoreMarkdownCodeTabs(instance,options,invocations){const parser=instance;if(!(typeof parser.lexer!="function"||typeof parser.walkTokens!="function"))try{const defaults={...instance.defaults,gfm:options.gfm,async:!1},hooks=defaults.hooks,source=hooks?.preprocess?hooks.preprocess(options.rawContent):options.rawContent;if(typeof source!="string")return;let tokens=parser.lexer(source,defaults);if(hooks?.processAllTokens&&(tokens=hooks.processAllTokens(tokens)),!Array.isArray(tokens))return;const originals=[];if(parser.walkTokens(tokens,token=>{token.type==="code"&&typeof token.text=="string"&&originals.push(token.text.replace(/\n$/,""))}),originals.length!==invocations)return;for(const record of options.codeBlocksOut??[]){const candidate=originals[record.ordinal];candidate!==void 0&&normalizeMarkdownLeadingTabs(candidate,options.tabSize)===record.source&&(record.source=candidate)}}catch{}}const KATEX_OVERRIDE=Symbol.for("@aceshooting/lyra-ui/markdown-katex-override");function readKatexOverride(){return Reflect.has(globalThis,KATEX_OVERRIDE)?{present:!0,value:Reflect.get(globalThis,KATEX_OVERRIDE)}:{present:!1,value:null}}function createMarkdownKatexState(){let resolved,loadStarted=!1;const subscribers=new Set;return{getIfLoaded(){const override=readKatexOverride();return override.present?override.value:resolved??null},isConfirmedMissing(){const override=readKatexOverride();return(override.present?override.value:resolved)===null},startLoad(onResolved){readKatexOverride().present||resolved!==void 0||(subscribers.add(onResolved),!loadStarted&&(loadStarted=!0,getKatex().then(katex=>{resolved=katex;const pending=[...subscribers];subscribers.clear();for(const subscriber of pending)subscriber()})))}}}function markdownCodeTransformer(lang){return{name:"lr-markdown-code-block",pre(node){node.properties.part=["code-block"],node.properties.tabindex="0"},code(node){const classValue=node.properties.class,classes=Array.isArray(classValue)?classValue.map(String):classValue?[String(classValue)]:[];node.properties.class=[...classes,`language-${lang}`]}}}const SHIKI_COLOR=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,SHIKI_STYLE_TO_DATA={color:"data-lr-shiki-light","background-color":"data-lr-shiki-light-bg","--shiki-light":"data-lr-shiki-light","--shiki-light-bg":"data-lr-shiki-light-bg","--shiki-dark":"data-lr-shiki-dark","--shiki-dark-bg":"data-lr-shiki-dark-bg"},SHIKI_DATA_TO_STYLE={"data-lr-shiki-light":"color","data-lr-shiki-light-bg":"background-color","data-lr-shiki-dark":"--shiki-dark","data-lr-shiki-dark-bg":"--shiki-dark-bg"};function encodeMarkdownHighlightStyles(markup){return markup.replace(/\sstyle=([\x22\x27])(.*?)\1/gi,(_attribute,_quote,value)=>{const attributes=[];for(const declaration of value.split(";")){const separator=declaration.indexOf(":");if(separator<0)continue;const property=declaration.slice(0,separator).trim().toLowerCase(),color=declaration.slice(separator+1).trim(),dataAttribute=SHIKI_STYLE_TO_DATA[property];dataAttribute&&SHIKI_COLOR.test(color)&&attributes.push(`${dataAttribute}="${color}"`)}return attributes.length>0?` ${attributes.join(" ")}`:""})}function restoreMarkdownHighlightStyles(markup){return markup.includes("data-lr-shiki-")?markup.replace(/<[a-z][^<>]*>/gi,openingTag=>{const declarations=[],cleanTag=openingTag.replace(/\s(data-lr-shiki-(?:light-bg|dark-bg|light|dark))=([\x22\x27])(#[\da-f]+)\2/gi,(attribute,name,_quote,color)=>{const property=SHIKI_DATA_TO_STYLE[name.toLowerCase()];return!property||!SHIKI_COLOR.test(color)?attribute:(declarations.push(`${property}:${color}`),"")});return declarations.length===0?cleanTag:`${cleanTag.slice(0,-1)} style="${declarations.join(";")}">`}):markup}function enforceMarkdownAnchorRelGuard(markup){if(!/target/i.test(markup))return markup;const template=document.createElement("template");template.innerHTML=markup;let changed=!1;for(const link of template.content.querySelectorAll("a[target],area[target]")){const rel=resolveGuardedRel(link.getAttribute("rel"),"target");rel!==link.getAttribute("rel")&&(link.setAttribute("rel",rel),changed=!0)}return changed?template.innerHTML:markup}function tokenizeMarkdownHighlight(hl,pending){if(pending.code.length>MARKDOWN_HIGHLIGHT_SOURCE_MAX)return null;try{const highlighted=hl.codeToHtml(pending.code,{lang:normalizeShikiLanguage(pending.lang),themes:SHIKI_THEMES,transformers:[markdownCodeTransformer(pending.lang)]});return`${encodeMarkdownHighlightStyles(highlighted)}
18
- `}catch{return null}}const markdownDepsLoadGenerations=new WeakMap;function beginMarkdownDepsLoad(host,apply){const generation=(markdownDepsLoadGenerations.get(host)??0)+1;markdownDepsLoadGenerations.set(host,generation);const alreadyLoaded=getMarkdownDepsIfLoaded();if(alreadyLoaded){apply(alreadyLoaded);return}loadMarkdownDeps().then(resolved=>{!host.isConnected||markdownDepsLoadGenerations.get(host)!==generation||apply(resolved)})}function markdownNeedsReparse(changed){return changed.has("content")||changed.has("tabSize")||changed.has("htmlMode")||changed.has("withoutGfm")||changed.has("linkTarget")||changed.has("headingOffset")||changed.has("streaming")||changed.has("headingAnchors")||changed.has("math")||changed.has("withoutSyntaxHighlighting")||changed.has("languages")||changed.has("languageLoaders")||changed.has("codeBlockHeader")||changed.has("streamingRender")}function markdownHighlightConfigChanged(changed){return changed.has("withoutSyntaxHighlighting")||changed.has("languages")||changed.has("languageLoaders")||changed.has("codeBlockHeader")}function markdownLanguageSetChanged(changed){return changed.has("languages")||changed.has("languageLoaders")}function normalizeMarkdownStreamingRender(value){return value==="progressive"?"progressive":"plain"}function normalizeMarkdownHtmlMode(value){return value==="escape"||value==="trusted"?value:"sanitize"}function markdownSanitizerPolicy(options){return options.htmlMode!=="sanitize"?null:{ADD_ATTR:["target"],FORBID_ATTR:["style","data-lr-code-chrome"],...options.codeBlockHeader?{FORBID_TAGS:["style"]}:{},...options.math?{ADD_TAGS:["semantics","annotation"]}:{}}}function renderMarkdownDocument(options){const{deps,tag}=options;if(!deps.marked)return{status:"fallback",error:new Error(`<${tag}> could not render: the "marked" peer dependency failed to load.`),headingTree:null};const pendingKeys=[],headingTree=[];let rawHtml,hadMathFallback,hasRawHtml=!0;try{const parsed=options.parse(deps.marked,pendingKeys,headingTree);rawHtml=parsed.html,hadMathFallback=parsed.hadMathFallback,hasRawHtml=parsed.hasRawHtml!==!1}catch(error){return{status:"fallback",error,headingTree:null}}options.onParsed();const mathFailed=hadMathFallback&&options.isKatexConfirmedMissing(),policy=markdownSanitizerPolicy({...options,codeBlockHeader:options.codeBlockHeader??!1});if(policy===null)return{status:"rendered",html:finishMarkdownHtml(deps,null,rawHtml,hasRawHtml),headingTree,mathFailed,pendingKeys};if(!deps.DOMPurify){const error=new Error(`<${tag}> could not render: sanitize is enabled (the default) but the "dompurify" peer dependency failed to load — refusing to render unsanitized HTML. Install it with \`pnpm add dompurify\`, or set html-mode="trusted" to explicitly opt out of sanitization.`);return warnMarkdownSanitizerUnavailable(),{status:"fallback",error,headingTree}}let sanitized;try{sanitized=finishMarkdownHtml(deps,policy,rawHtml,hasRawHtml)}catch(error){return warnMarkdownSanitizerUnavailable(),{status:"fallback",error,headingTree}}return{status:"rendered",html:sanitized,headingTree,mathFailed,pendingKeys}}function finishMarkdownHtml(deps,policy,rawHtml,hasRawHtml=!0){if(typeof rawHtml!="string")throw new TypeError("The Markdown parser returned non-string markup.");let result=rawHtml;if(policy!==null){if(!deps.DOMPurify)throw new Error("The HTML sanitizer is unavailable.");const sanitized=deps.DOMPurify.sanitize(rawHtml,policy);if(typeof sanitized!="string")throw new TypeError("The HTML sanitizer returned non-string markup.");result=sanitized}const styled=restoreMarkdownHighlightStyles(result);return hasRawHtml?enforceMarkdownAnchorRelGuard(styled):styled}function markdownMathPeerError(tag){return new Error(`<${tag}> needs the optional peer dependency \`katex\` to render math (the \`math\` property is set) — install it with \`pnpm add katex\`.`)}function applyMarkdownAriaBusy(host,busy){busy?host.setAttribute("aria-busy","true"):host.removeAttribute("aria-busy")}function markdownScrollBehavior(root){return!root.ownerDocument.defaultView||prefersReducedMotion(root)?"auto":"smooth"}function applyMarkdownFragmentAnchor(root,anchor,headingTree){if(!anchor.id)return!1;let index=-1;const headingLimit=Math.min(headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let headingIndex2=0;headingIndex2<headingLimit;headingIndex2++)if(headingTree[headingIndex2]?.id===anchor.id){index=headingIndex2;break}if(index<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,escapedIdMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const candidate=node;if(candidate.getAttribute("id")===anchor.id&&(escapedIdMatch??=candidate),/^H[1-6]$/.test(candidate.tagName)&&(headingIndex===index&&(positionalMatch=candidate),headingIndex++),escapedIdMatch&&positionalMatch)break}const el=escapedIdMatch??positionalMatch;return el?(el.scrollIntoView({behavior:markdownScrollBehavior(root),block:"start"}),!0):!1}function applyMarkdownTextQuoteAnchor(root,anchor,locale,index=createTextQuoteIndex(scopeFromElement(root),locale)){const match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(index.scope,match):null;return range?(((range.startContainer.nodeType===1?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:markdownScrollBehavior(root),block:"center"}),!0):!1}const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MARKDOWN_PAINTED_HIGHLIGHT_LIMIT=100;function repaintMarkdownHighlights(options){const resolved=[],rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const workBudget=options.index.createWorkBudget(),matches=[];for(const highlight of prioritizedHighlightCandidates(options.highlights,options.activeHighlightId)){if(matches.length>=MARKDOWN_PAINTED_HIGHLIGHT_LIMIT)break;if(highlight.anchor.kind!=="text-quote")continue;const match=options.index.resolve(highlight.anchor,workBudget);match&&matches.push({highlight,match})}const ranges=rangesFromTextQuoteMatches(options.index.scope,matches.map(({match})=>match));for(let position=0;position<matches.length;position++){const{highlight}=matches[position],range=ranges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),resolved.push({id:highlight.id,range}),highlight.id===options.activeHighlightId&&(activeRange=range))}for(const[tone,ranges2]of rangesByTone)options.handle.setRanges(tone,ranges2);if(options.handle.setActive(activeRange),!supportsCustomHighlights(options.root.ownerDocument)){const walker=options.root.ownerDocument.createTreeWalker(options.root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MARKDOWN_PAINTED_HIGHLIGHT_LIMIT&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}}return resolved}function hitTestHighlightRanges(ranges,x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=ranges.length-1;i>=0;i--){const hit=ranges[i];if(hit)for(const rect of hit.range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return hit.id}}return null}const nativeElementGetAttribute=typeof Element>"u"?void 0:Element.prototype.getAttribute,nativeAnchorHref=typeof HTMLAnchorElement>"u"?void 0:Object.getOwnPropertyDescriptor(HTMLAnchorElement.prototype,"href")?.get;function markdownAnchorFromTarget(target){if(!(typeof target!="object"&&typeof target!="function"||target===null)&&!(!nativeElementGetAttribute||!nativeAnchorHref))try{return nativeElementGetAttribute.call(target,"data-lr-brand-probe"),nativeAnchorHref.call(target),target}catch{return}}function nativeAnchorAttribute(anchor,name){try{const value=nativeElementGetAttribute?.call(anchor,name);return typeof value=="string"?value:void 0}catch{return}}function internalLinkHrefFrom(e,prefix){if(!prefix)return null;const anchor=e.composedPath().find(target=>markdownAnchorFromTarget(target)!==void 0);if(!anchor)return null;const href=nativeAnchorAttribute(anchor,"href")??"";return href.startsWith(prefix)?href:null}function markdownTableRegionLabel(localize){return localize("markdownTableRegion")}const MARKDOWN_TABLE_WRAPPER_SELECTOR='[part="table-wrapper"][role="group"]';function markdownHasTableWrappers(root){return root?.nodeType===1&&root.matches(MARKDOWN_TABLE_WRAPPER_SELECTOR)||root?.querySelector(MARKDOWN_TABLE_WRAPPER_SELECTOR)!=null}function labelMarkdownTableWrappers(root,label){if(!root)return;const wrappers=[...root?.nodeType===1&&root.matches(MARKDOWN_TABLE_WRAPPER_SELECTOR)?[root]:[],...root.querySelectorAll(MARKDOWN_TABLE_WRAPPER_SELECTOR)];for(const wrapper of wrappers)wrapper.getAttribute("aria-label")!==label&&wrapper.setAttribute("aria-label",label)}function renderMarkdownContent(options){const isFallback=!options.progressive&&options.renderedHtml===null,tail=options.progressive?.tail,sanitizedMaxHeight=sanitizeCssLength(options.maxHeight);return html`<div
17
+ `},link(token){const text=this.parser.parseInline(token.tokens),href=cleanHref(token.href);if(href===null)return text;const safeHref=trustedHtmlOption?href:safeLinkHref(href);if(safeHref===null)return text;const titleAttr=token.title?` title='${escapeHtml(token.title)}'`:"",targetAttr=linkTarget?` target='${escapeHtml(linkTarget)}' rel='noopener noreferrer'`:"";return`<a part='link' href='${escapeHtml(safeHref)}'${titleAttr}${targetAttr}>${text}</a>`},image(token){const altText=this.parser.parseInline(token.tokens,this.parser.textRenderer);if(withoutImagesOption)return escapeHtml(altText);const href=cleanHref(token.href);if(href===null)return escapeHtml(altText);const safeHref=trustedHtmlOption?href:safeMediaSrc(href);if(safeHref===null)return escapeHtml(altText);const titleAttr=token.title?` title='${escapeHtml(token.title)}'`:"";return`<img part='img' src='${escapeHtml(safeHref)}' alt='${escapeHtml(altText)}'${titleAttr}>`},html(token){return hasRawHtml=!0,escapeHtmlOption?escapeHtml(token.text):token.text},text(token){return escapeHtmlOption&&token.escaped===!0&&!token.tokens?escapeMarkdownText(token.text):!1}}});for(const configuration of options.markedConfigurations??[]){if(!configuration||typeof configuration!="object")continue;const configuredDefaults=Object.fromEntries(Object.entries(configuration).filter(([,value])=>value!=null));Object.keys(configuredDefaults).length>0&&instance.use(configuredDefaults)}const capable=instance;return{instance:capable,render(source,seed){let html2,state={inLink:!1,inRawBlock:!1};if(seed){const defaults={...instance.defaults,gfm,async:!1},lexer=new capable.Lexer(defaults);Object.assign(lexer.tokens.links,seed.links),Object.assign(lexer.state,seed.state);const tokens=lexer.lex(source);state={inLink:lexer.state.inLink,inRawBlock:lexer.state.inRawBlock},instance.defaults.walkTokens&&capable.walkTokens(tokens,instance.defaults.walkTokens),html2=capable.parser(tokens,defaults)}else html2=instance.parse(source,{gfm,async:!1});if(typeof html2!="string")throw new TypeError("The Markdown parser returned non-string markup.");return headerEnabled&&options.rawContent!==void 0&&options.tabSize!==void 0&&codeHasSourceTabs&&restoreMarkdownCodeTabs(instance,options,codeInvocations),{html:html2,hadMathFallback,hasRawHtml,state}}}}function rawCodeTabProbe(raw,normalized,tabSize){let cursor=0,lines;return envelope=>{if(!envelope)return!0;const start=normalized.indexOf(envelope,cursor);if(start<0)return!0;if(cursor=start+envelope.length,!lines){lines=[];let offset=0;for(const match of raw.matchAll(/[^\r\n\u2028\u2029]*(?:\r\n|[\r\n\u2028\u2029]|$)/g))match[0]&&(lines.push({normalized:offset,raw:match.index,end:match.index+match[0].length}),offset+=normalizeMarkdownLeadingTabs(match[0],tabSize).length);if(offset!==normalized.length)return!0}const locate=offset=>{let low=0,high=lines.length;for(;low+1<high;){const middle=low+high>>>1;lines[middle].normalized<=offset?low=middle:high=middle}return low},first=lines[locate(start)],last=lines[locate(Math.max(start,cursor-1))];return!first||!last||/^[\t ]*\t/m.test(raw.slice(first.raw,last.end))}}function restoreMarkdownCodeTabs(instance,options,invocations){const parser=instance;if(!(typeof parser.lexer!="function"||typeof parser.walkTokens!="function"))try{const defaults={...instance.defaults,gfm:options.gfm,async:!1},hooks=defaults.hooks,source=hooks?.preprocess?hooks.preprocess(options.rawContent):options.rawContent;if(typeof source!="string")return;let tokens=parser.lexer(source,defaults);if(hooks?.processAllTokens&&(tokens=hooks.processAllTokens(tokens)),!Array.isArray(tokens))return;const originals=[];if(parser.walkTokens(tokens,token=>{token.type==="code"&&typeof token.text=="string"&&originals.push(token.text.replace(/\n$/,""))}),originals.length!==invocations)return;for(const record of options.codeBlocksOut??[]){const candidate=originals[record.ordinal];candidate!==void 0&&normalizeMarkdownLeadingTabs(candidate,options.tabSize)===record.source&&(record.source=candidate)}}catch{}}const KATEX_OVERRIDE=Symbol.for("@aceshooting/lyra-ui/markdown-katex-override");function readKatexOverride(){return Reflect.has(globalThis,KATEX_OVERRIDE)?{present:!0,value:Reflect.get(globalThis,KATEX_OVERRIDE)}:{present:!1,value:null}}function createMarkdownKatexState(){let resolved,loadStarted=!1;const subscribers=new Set;return{getIfLoaded(){const override=readKatexOverride();return override.present?override.value:resolved??null},isConfirmedMissing(){const override=readKatexOverride();return(override.present?override.value:resolved)===null},startLoad(onResolved){readKatexOverride().present||resolved!==void 0||(subscribers.add(onResolved),!loadStarted&&(loadStarted=!0,getKatex().then(katex=>{resolved=katex;const pending=[...subscribers];subscribers.clear();for(const subscriber of pending)subscriber()})))}}}function markdownCodeTransformer(lang){return{name:"lr-markdown-code-block",pre(node){node.properties.part=["code-block"],node.properties.tabindex="0"},code(node){const classValue=node.properties.class,classes=Array.isArray(classValue)?classValue.map(String):classValue?[String(classValue)]:[];node.properties.class=[...classes,`language-${lang}`]}}}const SHIKI_COLOR=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,SHIKI_STYLE_TO_DATA={color:"data-lr-shiki-light","background-color":"data-lr-shiki-light-bg","--shiki-light":"data-lr-shiki-light","--shiki-light-bg":"data-lr-shiki-light-bg","--shiki-dark":"data-lr-shiki-dark","--shiki-dark-bg":"data-lr-shiki-dark-bg"},SHIKI_DATA_TO_STYLE={"data-lr-shiki-light":"color","data-lr-shiki-light-bg":"background-color","data-lr-shiki-dark":"--shiki-dark","data-lr-shiki-dark-bg":"--shiki-dark-bg"};function encodeMarkdownHighlightStyles(markup){return markup.replace(/\sstyle=([\x22\x27])(.*?)\1/gi,(_attribute,_quote,value)=>{const attributes=[];for(const declaration of value.split(";")){const separator=declaration.indexOf(":");if(separator<0)continue;const property=declaration.slice(0,separator).trim().toLowerCase(),color=declaration.slice(separator+1).trim(),dataAttribute=SHIKI_STYLE_TO_DATA[property];dataAttribute&&SHIKI_COLOR.test(color)&&attributes.push(`${dataAttribute}="${color}"`)}return attributes.length>0?` ${attributes.join(" ")}`:""})}function restoreMarkdownHighlightStyles(markup){return markup.includes("data-lr-shiki-")?markup.replace(/<[a-z][^<>]*>/gi,openingTag=>{const declarations=[],cleanTag=openingTag.replace(/\s(data-lr-shiki-(?:light-bg|dark-bg|light|dark))=([\x22\x27])(#[\da-f]+)\2/gi,(attribute,name,_quote,color)=>{const property=SHIKI_DATA_TO_STYLE[name.toLowerCase()];return!property||!SHIKI_COLOR.test(color)?attribute:(declarations.push(`${property}:${color}`),"")});return declarations.length===0?cleanTag:`${cleanTag.slice(0,-1)} style="${declarations.join(";")}">`}):markup}const MARKDOWN_IMAGE_MARKUP=/<(?:img|image|feimage|input|source|video)\b/i;function stripMarkdownImages(markup){if(!MARKDOWN_IMAGE_MARKUP.test(markup))return markup;const template=document.createElement("template");template.innerHTML=markup;const root=template.content,doc=root.ownerDocument;let changed=!1;for(const element of root.querySelectorAll("img, input"))element.localName==="input"&&element.getAttribute("type")?.trim().toLowerCase()!=="image"||(element.replaceWith(doc.createTextNode(element.getAttribute("alt")??"")),changed=!0);for(const element of root.querySelectorAll("picture source, image, feImage"))element.remove(),changed=!0;for(const element of root.querySelectorAll("video[poster]"))element.removeAttribute("poster"),changed=!0;return changed?template.innerHTML:markup}function enforceMarkdownAnchorRelGuard(markup){if(!/target/i.test(markup))return markup;const template=document.createElement("template");template.innerHTML=markup;let changed=!1;for(const link of template.content.querySelectorAll("a[target],area[target]")){const rel=resolveGuardedRel(link.getAttribute("rel"),"target");rel!==link.getAttribute("rel")&&(link.setAttribute("rel",rel),changed=!0)}return changed?template.innerHTML:markup}function tokenizeMarkdownHighlight(hl,pending){if(pending.code.length>MARKDOWN_HIGHLIGHT_SOURCE_MAX)return null;try{const highlighted=hl.codeToHtml(pending.code,{lang:normalizeShikiLanguage(pending.lang),themes:SHIKI_THEMES,transformers:[markdownCodeTransformer(pending.lang)]});return`${encodeMarkdownHighlightStyles(highlighted)}
18
+ `}catch{return null}}const markdownDepsLoadGenerations=new WeakMap;function beginMarkdownDepsLoad(host,apply){const generation=(markdownDepsLoadGenerations.get(host)??0)+1;markdownDepsLoadGenerations.set(host,generation);const alreadyLoaded=getMarkdownDepsIfLoaded();if(alreadyLoaded){apply(alreadyLoaded);return}loadMarkdownDeps().then(resolved=>{!host.isConnected||markdownDepsLoadGenerations.get(host)!==generation||apply(resolved)})}function markdownNeedsReparse(changed){return changed.has("content")||changed.has("tabSize")||changed.has("htmlMode")||changed.has("withoutGfm")||changed.has("withoutImages")||changed.has("linkTarget")||changed.has("headingOffset")||changed.has("streaming")||changed.has("headingAnchors")||changed.has("math")||changed.has("withoutSyntaxHighlighting")||changed.has("languages")||changed.has("languageLoaders")||changed.has("codeBlockHeader")||changed.has("streamingRender")}function markdownHighlightConfigChanged(changed){return changed.has("withoutSyntaxHighlighting")||changed.has("languages")||changed.has("languageLoaders")||changed.has("codeBlockHeader")}function markdownLanguageSetChanged(changed){return changed.has("languages")||changed.has("languageLoaders")}function normalizeMarkdownStreamingRender(value){return value==="progressive"?"progressive":"plain"}function normalizeMarkdownHtmlMode(value){return value==="escape"||value==="trusted"?value:"sanitize"}function markdownSanitizerPolicy(options){return options.htmlMode!=="sanitize"?null:{ADD_ATTR:["target"],FORBID_ATTR:["style","data-lr-code-chrome"],...options.codeBlockHeader||options.withoutImages?{FORBID_TAGS:["style"]}:{},...options.math?{ADD_TAGS:["semantics","annotation"]}:{}}}function renderMarkdownDocument(options){const{deps,tag}=options;if(!deps.marked)return{status:"fallback",error:new Error(`<${tag}> could not render: the "marked" peer dependency failed to load.`),headingTree:null};const pendingKeys=[],headingTree=[];let rawHtml,hadMathFallback,hasRawHtml=!0;try{const parsed=options.parse(deps.marked,pendingKeys,headingTree);rawHtml=parsed.html,hadMathFallback=parsed.hadMathFallback,hasRawHtml=parsed.hasRawHtml!==!1}catch(error){return{status:"fallback",error,headingTree:null}}options.onParsed();const mathFailed=hadMathFallback&&options.isKatexConfirmedMissing(),policy=markdownSanitizerPolicy({...options,codeBlockHeader:options.codeBlockHeader??!1}),withoutImages=options.withoutImages??!1;if(policy===null)return{status:"rendered",html:finishMarkdownHtml(deps,null,rawHtml,hasRawHtml,withoutImages),headingTree,mathFailed,pendingKeys};if(!deps.DOMPurify){const error=new Error(`<${tag}> could not render: sanitize is enabled (the default) but the "dompurify" peer dependency failed to load — refusing to render unsanitized HTML. Install it with \`pnpm add dompurify\`, or set html-mode="trusted" to explicitly opt out of sanitization.`);return warnMarkdownSanitizerUnavailable(),{status:"fallback",error,headingTree}}let sanitized;try{sanitized=finishMarkdownHtml(deps,policy,rawHtml,hasRawHtml,withoutImages)}catch(error){return warnMarkdownSanitizerUnavailable(),{status:"fallback",error,headingTree}}return{status:"rendered",html:sanitized,headingTree,mathFailed,pendingKeys}}function finishMarkdownHtml(deps,policy,rawHtml,hasRawHtml=!0,withoutImages=!1){if(typeof rawHtml!="string")throw new TypeError("The Markdown parser returned non-string markup.");let result=rawHtml;if(policy!==null){if(!deps.DOMPurify)throw new Error("The HTML sanitizer is unavailable.");const sanitized=deps.DOMPurify.sanitize(rawHtml,policy);if(typeof sanitized!="string")throw new TypeError("The HTML sanitizer returned non-string markup.");result=sanitized}const styled=restoreMarkdownHighlightStyles(result),guarded=hasRawHtml?enforceMarkdownAnchorRelGuard(styled):styled;return withoutImages?stripMarkdownImages(guarded):guarded}function markdownMathPeerError(tag){return new Error(`<${tag}> needs the optional peer dependency \`katex\` to render math (the \`math\` property is set) — install it with \`pnpm add katex\`.`)}function applyMarkdownAriaBusy(host,busy){busy?host.setAttribute("aria-busy","true"):host.removeAttribute("aria-busy")}function markdownScrollBehavior(root){return!root.ownerDocument.defaultView||prefersReducedMotion(root)?"auto":"smooth"}function applyMarkdownFragmentAnchor(root,anchor,headingTree){if(!anchor.id)return!1;let index=-1;const headingLimit=Math.min(headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let headingIndex2=0;headingIndex2<headingLimit;headingIndex2++)if(headingTree[headingIndex2]?.id===anchor.id){index=headingIndex2;break}if(index<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,escapedIdMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const candidate=node;if(candidate.getAttribute("id")===anchor.id&&(escapedIdMatch??=candidate),/^H[1-6]$/.test(candidate.tagName)&&(headingIndex===index&&(positionalMatch=candidate),headingIndex++),escapedIdMatch&&positionalMatch)break}const el=escapedIdMatch??positionalMatch;return el?(el.scrollIntoView({behavior:markdownScrollBehavior(root),block:"start"}),!0):!1}function applyMarkdownTextQuoteAnchor(root,anchor,locale,index=createTextQuoteIndex(scopeFromElement(root),locale)){const match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(index.scope,match):null;return range?(((range.startContainer.nodeType===1?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:markdownScrollBehavior(root),block:"center"}),!0):!1}const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MARKDOWN_PAINTED_HIGHLIGHT_LIMIT=100;function repaintMarkdownHighlights(options){const resolved=[],rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const workBudget=options.index.createWorkBudget(),matches=[];for(const highlight of prioritizedHighlightCandidates(options.highlights,options.activeHighlightId)){if(matches.length>=MARKDOWN_PAINTED_HIGHLIGHT_LIMIT)break;if(highlight.anchor.kind!=="text-quote")continue;const match=options.index.resolve(highlight.anchor,workBudget);match&&matches.push({highlight,match})}const ranges=rangesFromTextQuoteMatches(options.index.scope,matches.map(({match})=>match));for(let position=0;position<matches.length;position++){const{highlight}=matches[position],range=ranges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),resolved.push({id:highlight.id,range}),highlight.id===options.activeHighlightId&&(activeRange=range))}for(const[tone,ranges2]of rangesByTone)options.handle.setRanges(tone,ranges2);if(options.handle.setActive(activeRange),!supportsCustomHighlights(options.root.ownerDocument)){const walker=options.root.ownerDocument.createTreeWalker(options.root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MARKDOWN_PAINTED_HIGHLIGHT_LIMIT&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}}return resolved}function hitTestHighlightRanges(ranges,x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=ranges.length-1;i>=0;i--){const hit=ranges[i];if(hit)for(const rect of hit.range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return hit.id}}return null}const nativeElementGetAttribute=typeof Element>"u"?void 0:Element.prototype.getAttribute,nativeAnchorHref=typeof HTMLAnchorElement>"u"?void 0:Object.getOwnPropertyDescriptor(HTMLAnchorElement.prototype,"href")?.get;function markdownAnchorFromTarget(target){if(!(typeof target!="object"&&typeof target!="function"||target===null)&&!(!nativeElementGetAttribute||!nativeAnchorHref))try{return nativeElementGetAttribute.call(target,"data-lr-brand-probe"),nativeAnchorHref.call(target),target}catch{return}}function nativeAnchorAttribute(anchor,name){try{const value=nativeElementGetAttribute?.call(anchor,name);return typeof value=="string"?value:void 0}catch{return}}function internalLinkHrefFrom(e,prefix){if(!prefix)return null;const anchor=e.composedPath().find(target=>markdownAnchorFromTarget(target)!==void 0);if(!anchor)return null;const href=nativeAnchorAttribute(anchor,"href")??"";return href.startsWith(prefix)?href:null}function markdownTableRegionLabel(localize){return localize("markdownTableRegion")}const MARKDOWN_TABLE_WRAPPER_SELECTOR='[part="table-wrapper"][role="group"]';function markdownHasTableWrappers(root){return root?.nodeType===1&&root.matches(MARKDOWN_TABLE_WRAPPER_SELECTOR)||root?.querySelector(MARKDOWN_TABLE_WRAPPER_SELECTOR)!=null}function labelMarkdownTableWrappers(root,label){if(!root)return;const wrappers=[...root?.nodeType===1&&root.matches(MARKDOWN_TABLE_WRAPPER_SELECTOR)?[root]:[],...root.querySelectorAll(MARKDOWN_TABLE_WRAPPER_SELECTOR)];for(const wrapper of wrappers)wrapper.getAttribute("aria-label")!==label&&wrapper.setAttribute("aria-label",label)}function renderMarkdownContent(options){const isFallback=!options.progressive&&options.renderedHtml===null,tail=options.progressive?.tail,sanitizedMaxHeight=sanitizeCssLength(options.maxHeight);return html`<div
19
19
  part="content"
20
20
  role="document"
21
21
  tabindex=${options.content.trim()?"0":nothing}
@@ -209,10 +209,20 @@ tabSize:number;
209
209
  * override replaces the escaping and is the consumer's responsibility. Independently of this,
210
210
  * every markdown-native link/image `href`/`src` is always scheme-validated
211
211
  * (`http:`/`https:`/`blob:`/`mailto:`, plus `data:` for images) unless `htmlMode` is `trusted`
212
- * -- a rejected scheme drops the anchor/image, rendering only its text/alt content. */
212
+ * -- a rejected scheme drops the anchor/image, rendering only its text/alt content. The scheme
213
+ * allowlist still admits any http(s), relative or `data:` image; set `withoutImages` for untrusted
214
+ * content that must not load images at all. */
213
215
  htmlMode:MarkdownHtmlMode;
214
216
  /** Disables GitHub-flavored Markdown (tables, strikethrough, autolinks, task lists).*/
215
217
  withoutGfm:boolean;
218
+ /** Untrusted-content switch for every `htmlMode`: renders each image as its alt text, exactly as
219
+ * a refused `src` is rendered, so displaying the document never loads an image element.
220
+ * It covers Markdown images and, after sanitization, raw HTML: `<img>` and
221
+ * `<input type="image">` become their alt text, `<picture>` sources and SVG `<image>`/`<feImage>`
222
+ * are removed, and `<video>` loses its `poster`. In `sanitize` mode authored `<style>` elements
223
+ * are removed too; `trusted` mode does not inspect authored CSS. Set it for language-model output
224
+ * or other content that should not trigger requests to arbitrary URLs. */
225
+ withoutImages:boolean;
216
226
  /** `target` applied to every rendered `<a>`, with `rel="noopener
217
227
  * noreferrer"` always added alongside it whenever a `target` is emitted.
218
228
  * `'_blank'` (the default) preserves today's exact output. Set to `null`
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{getMarkdownDepsIfLoaded}from"./markdown-loader.js";import{loadShikiHighlighter,loadShikiLanguage,loadShikiHighlighterCore,normalizeShikiLanguage}from"../code-block/code-loader.js";import{ensureShikiLanguageLoaded,resolvedShikiLanguages}from"../code-block/shiki-types.js";import{createMarkdownKatexState,tokenizeMarkdownHighlight}from"./markdown-shared.js";import{createMarkdownVariantContext,MarkdownRuntimeBase}from"./markdown-base.class.js";import{styles}from"./markdown.styles.js";import{LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode,LYRA_DEFAULT_markdownTableRegion}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const katexState=createMarkdownKatexState();class LyraMarkdown extends MarkdownRuntimeBase{constructor(){super(...arguments),this.content="",this.tabSize=4,this.htmlMode="sanitize",this.withoutGfm=!1,this.linkTarget="_blank",this.internalLinkPrefix="",this.headingOffset=0,this.streaming=!1,this.streamingRender="plain",this.codeBlockHeader=!1,this.withoutSyntaxHighlighting=!1,this.headingAnchors=!1,this.math=!1,this.maxHeight=""}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed,markdownTableRegion:LYRA_DEFAULT_markdownTableRegion}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.variant=createMarkdownVariantContext("lr-markdown",katexState)}static getMarked(){const parser=this.variant.sharedParser.get(getMarkdownDepsIfLoaded()?.marked);if(!parser)throw new Error("LyraMarkdown.getMarked() requires the optional `marked` peer; await preloadMarkdown() first.");return parser}static updateAll(){for(const instance of this.variant.connectedInstances)instance.renderMarkdown()}connectedCallback(){this.adoptScriptContent(),super.connectedCallback()}adoptScriptContent(){if(this.hasAttribute("content")||this.content)return;const text=this.querySelector(':scope > script[type="text/markdown"]')?.textContent;text!=null&&(this.content=text.trim())}get markdownVariant(){return LyraMarkdown.variant}get highlightLanguageSources(){return combineShikiLanguageSources(this.languages,this.languageLoaders)}async tokenizePendingHighlight(pending,languages,isCurrent){const normalizedLang=normalizeShikiLanguage(pending.lang),sources=combineShikiLanguageSources(languages,this.languageLoaders);let highlighter;if(sources&&(sources[normalizedLang]??sources[pending.lang])){if(highlighter=await loadShikiHighlighterCore(resolvedShikiLanguages(sources)),!isCurrent())return;if(!highlighter)return null;const loaded=await ensureShikiLanguageLoaded(highlighter,normalizedLang,sources[normalizedLang]??sources[pending.lang]);if(!isCurrent())return;if(!loaded)return null}else{const base=await loadShikiHighlighter();if(!isCurrent())return;if(!base)return null;const loaded=await loadShikiLanguage(base,pending.lang);if(!isCurrent())return;highlighter=loaded?base:null}if(isCurrent())return highlighter?tokenizeMarkdownHighlight(highlighter,pending):null}}__decorate([property()],LyraMarkdown.prototype,"content",void 0),__decorate([property({type:Number,attribute:"tab-size"})],LyraMarkdown.prototype,"tabSize",void 0),__decorate([property({attribute:"html-mode"})],LyraMarkdown.prototype,"htmlMode",void 0),__decorate([property({type:Boolean,attribute:"without-gfm"})],LyraMarkdown.prototype,"withoutGfm",void 0),__decorate([property({attribute:"link-target"})],LyraMarkdown.prototype,"linkTarget",void 0),__decorate([property({attribute:"internal-link-prefix"})],LyraMarkdown.prototype,"internalLinkPrefix",void 0),__decorate([property({type:Number,attribute:"heading-offset"})],LyraMarkdown.prototype,"headingOffset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMarkdown.prototype,"streaming",void 0),__decorate([property({attribute:"streaming-render"})],LyraMarkdown.prototype,"streamingRender",void 0),__decorate([property({type:Boolean,attribute:"code-block-header"})],LyraMarkdown.prototype,"codeBlockHeader",void 0),__decorate([property({type:Boolean,attribute:"without-syntax-highlighting"})],LyraMarkdown.prototype,"withoutSyntaxHighlighting",void 0),__decorate([property({attribute:!1})],LyraMarkdown.prototype,"languages",void 0),__decorate([property({attribute:!1})],LyraMarkdown.prototype,"languageLoaders",void 0),__decorate([property({type:Boolean,attribute:"heading-anchors"})],LyraMarkdown.prototype,"headingAnchors",void 0),__decorate([property({type:Boolean})],LyraMarkdown.prototype,"math",void 0),__decorate([property({attribute:"max-height"})],LyraMarkdown.prototype,"maxHeight",void 0);export{LyraMarkdown};
1
+ import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{getMarkdownDepsIfLoaded}from"./markdown-loader.js";import{loadShikiHighlighter,loadShikiLanguage,loadShikiHighlighterCore,normalizeShikiLanguage}from"../code-block/code-loader.js";import{ensureShikiLanguageLoaded,resolvedShikiLanguages}from"../code-block/shiki-types.js";import{createMarkdownKatexState,tokenizeMarkdownHighlight}from"./markdown-shared.js";import{createMarkdownVariantContext,MarkdownRuntimeBase}from"./markdown-base.class.js";import{styles}from"./markdown.styles.js";import{LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode,LYRA_DEFAULT_markdownTableRegion}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const katexState=createMarkdownKatexState();class LyraMarkdown extends MarkdownRuntimeBase{constructor(){super(...arguments),this.content="",this.tabSize=4,this.htmlMode="sanitize",this.withoutGfm=!1,this.withoutImages=!1,this.linkTarget="_blank",this.internalLinkPrefix="",this.headingOffset=0,this.streaming=!1,this.streamingRender="plain",this.codeBlockHeader=!1,this.withoutSyntaxHighlighting=!1,this.headingAnchors=!1,this.math=!1,this.maxHeight=""}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed,markdownTableRegion:LYRA_DEFAULT_markdownTableRegion}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.variant=createMarkdownVariantContext("lr-markdown",katexState)}static getMarked(){const parser=this.variant.sharedParser.get(getMarkdownDepsIfLoaded()?.marked);if(!parser)throw new Error("LyraMarkdown.getMarked() requires the optional `marked` peer; await preloadMarkdown() first.");return parser}static updateAll(){for(const instance of this.variant.connectedInstances)instance.renderMarkdown()}connectedCallback(){this.adoptScriptContent(),super.connectedCallback()}adoptScriptContent(){if(this.hasAttribute("content")||this.content)return;const text=this.querySelector(':scope > script[type="text/markdown"]')?.textContent;text!=null&&(this.content=text.trim())}get markdownVariant(){return LyraMarkdown.variant}get highlightLanguageSources(){return combineShikiLanguageSources(this.languages,this.languageLoaders)}async tokenizePendingHighlight(pending,languages,isCurrent){const normalizedLang=normalizeShikiLanguage(pending.lang),sources=combineShikiLanguageSources(languages,this.languageLoaders);let highlighter;if(sources&&(sources[normalizedLang]??sources[pending.lang])){if(highlighter=await loadShikiHighlighterCore(resolvedShikiLanguages(sources)),!isCurrent())return;if(!highlighter)return null;const loaded=await ensureShikiLanguageLoaded(highlighter,normalizedLang,sources[normalizedLang]??sources[pending.lang]);if(!isCurrent())return;if(!loaded)return null}else{const base=await loadShikiHighlighter();if(!isCurrent())return;if(!base)return null;const loaded=await loadShikiLanguage(base,pending.lang);if(!isCurrent())return;highlighter=loaded?base:null}if(isCurrent())return highlighter?tokenizeMarkdownHighlight(highlighter,pending):null}}__decorate([property()],LyraMarkdown.prototype,"content",void 0),__decorate([property({type:Number,attribute:"tab-size"})],LyraMarkdown.prototype,"tabSize",void 0),__decorate([property({attribute:"html-mode"})],LyraMarkdown.prototype,"htmlMode",void 0),__decorate([property({type:Boolean,attribute:"without-gfm"})],LyraMarkdown.prototype,"withoutGfm",void 0),__decorate([property({type:Boolean,attribute:"without-images"})],LyraMarkdown.prototype,"withoutImages",void 0),__decorate([property({attribute:"link-target"})],LyraMarkdown.prototype,"linkTarget",void 0),__decorate([property({attribute:"internal-link-prefix"})],LyraMarkdown.prototype,"internalLinkPrefix",void 0),__decorate([property({type:Number,attribute:"heading-offset"})],LyraMarkdown.prototype,"headingOffset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMarkdown.prototype,"streaming",void 0),__decorate([property({attribute:"streaming-render"})],LyraMarkdown.prototype,"streamingRender",void 0),__decorate([property({type:Boolean,attribute:"code-block-header"})],LyraMarkdown.prototype,"codeBlockHeader",void 0),__decorate([property({type:Boolean,attribute:"without-syntax-highlighting"})],LyraMarkdown.prototype,"withoutSyntaxHighlighting",void 0),__decorate([property({attribute:!1})],LyraMarkdown.prototype,"languages",void 0),__decorate([property({attribute:!1})],LyraMarkdown.prototype,"languageLoaders",void 0),__decorate([property({type:Boolean,attribute:"heading-anchors"})],LyraMarkdown.prototype,"headingAnchors",void 0),__decorate([property({type:Boolean})],LyraMarkdown.prototype,"math",void 0),__decorate([property({attribute:"max-height"})],LyraMarkdown.prototype,"maxHeight",void 0);export{LyraMarkdown};
@@ -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{LyraWidgetTypeRegistry}from'../widget-renderer/registry.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'../../../internal/widget-type-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
@@ -1,4 +1,4 @@
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"}
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"../../../internal/widget-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
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
3
3
  .name=${invocation.name}
4
4
  .displayName=${invocationDisplayName(invocation)}
@@ -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';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';
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.class.js';import'../markdown/markdown.js';
@@ -1,4 +1,4 @@
1
- import{type TemplateResult,type PropertyValues}from'lit';import{LyraCatalogPickerElement}from'../catalog-picker-element.js';import type{LyraSize}from'../../../internal/variants.js';import type{LyraSelectionDirection}from'../../../internal/shared-unions.js';import{CatalogPickerController,type LyraCatalog,type LyraCatalogEntry}from'../../../internal/catalog-picker.js';export type{LyraCatalog,LyraCatalogEntry}from'../../../internal/catalog-picker.js';
1
+ import{type TemplateResult,type PropertyValues}from'lit';import{LyraCatalogPickerElement}from'../catalog-picker-element.js';import type{LyraSize,LyraLabelDisplay}from'../../../internal/variants.js';import type{LyraSelectionDirection}from'../../../internal/shared-unions.js';import{CatalogPickerController,type LyraCatalog,type LyraCatalogEntry}from'../../../internal/catalog-picker.js';export type{LyraCatalog,LyraCatalogEntry}from'../../../internal/catalog-picker.js';
2
2
  /** A catalog row: a selectable model, keyed by `id` with a display `label`.*/
3
3
  export interface LyraModelCatalogEntry extends LyraCatalogEntry{
4
4
  /** Optional literal icon hint (for example, an emoji), rendered decoratively before `label`.*/
@@ -159,6 +159,13 @@ readonly:boolean;
159
159
  * associated name. Leaving both empty keeps the `aria-label || placeholder || 'Model'` chain.
160
160
  */
161
161
  label:string;
162
+ /**
163
+ * Whether the `label` renders on screen. `hidden` keeps the label as the accessible name but
164
+ * removes it visually (compact toolbars, table cells); hint, error and required semantics are
165
+ * unaffected. Reflected so styles and `[label-display]` selectors match.
166
+ * @attr label-display
167
+ */
168
+ labelDisplay:LyraLabelDisplay;
162
169
  /** Hint text below the field. Unset (the default): no hint chrome renders.*/
163
170
  hint:string;
164
171
  /** Error text below the field (overridden by slotted `error` content). Unset (the default): no
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{guard}from"lit/directives/guard.js";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{publicCollectionTruncation,collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraCatalogPickerElement}from"../catalog-picker-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{styles}from"./model-select.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_catalogPickerInputLimit,LYRA_DEFAULT_model,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraModelSelect extends LyraCatalogPickerElement{constructor(){super(...arguments),this.provider="",this.allowCustom=!1,this.readonly=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.slotPresence=new SlotPresenceController(this),this.listId=nextId("model-select-list"),this.controlId=nextId("model-select-control"),this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,isReadonly:()=>this.readonly,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label],emitInput:detail=>this.emit("lr-input",detail),emitChange:detail=>this.emit("lr-change",detail),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state,oldValue)=>{state==="open"?this.requestUpdate("open",oldValue):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)},forwardFreeInputClick:!0}),this.limitAnnouncements=new AnnouncementSinkController(this),this.limitMounted=!1,this.previousInputLimit=!1,this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onTriggerFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)}}static{this.defaultStrings={...super.defaultStrings,catalogPickerInputLimit:LYRA_DEFAULT_catalogPickerInputLimit,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.ownedCollectionLimits={catalog:{entries:1024}}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}get catalogEditing(){return this.catalogPicker}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);const modeChanged=this.prepareModeFocus(this.closedMode);if(this.catalogPicker.suppressControlEvents=modeChanged,this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))){const activeValue=typeof this.renderRoot?.querySelector=="function"?this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value:void 0;this.catalogPicker.reconcileRows(activeValue,changed.has("value")||changed.has("allowCustom")||modeChanged,!1)}}disconnectedCallback(){super.disconnectedCallback(),this.clearModeFocus(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.clearModeFocus(),this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}requiredMessage(){return this.localize("modelSelectRequired")}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state,_mode){this.catalogPicker.restoreState(state)}formDisabledCallback(disabled){this.formDisabledChanged(disabled)}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}get inputLimited(){return publicCollectionTruncation(this,"catalog")!==void 0}updated(changed){super.updated(changed);const limited=this.inputLimited;this.limitMounted&&limited&&!this.previousInputLimit&&this.limitAnnouncements.announcePolite(this.localize("catalogPickerInputLimit")),this.previousInputLimit=limited,this.limitMounted=!0,this.syncCatalogDescription(this.controlId);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("readonly")||changed.has("touched")||changed.has("value"))&&(changed.has("readonly")&&this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),this.publishValidityStates(),this.catalogPicker.suppressControlEvents=!1,this.finishModeFocus("model-select-mode-focus")}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value,disabled=entry.disabled===!0;return html`<div
1
+ import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{guard}from"lit/directives/guard.js";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{publicCollectionTruncation,collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraCatalogPickerElement}from"../catalog-picker-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{styles}from"./model-select.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_catalogPickerInputLimit,LYRA_DEFAULT_model,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraModelSelect extends LyraCatalogPickerElement{constructor(){super(...arguments),this.provider="",this.allowCustom=!1,this.readonly=!1,this.label="",this.labelDisplay="visible",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.slotPresence=new SlotPresenceController(this),this.listId=nextId("model-select-list"),this.controlId=nextId("model-select-control"),this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,isReadonly:()=>this.readonly,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label],emitInput:detail=>this.emit("lr-input",detail),emitChange:detail=>this.emit("lr-change",detail),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state,oldValue)=>{state==="open"?this.requestUpdate("open",oldValue):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)},forwardFreeInputClick:!0}),this.limitAnnouncements=new AnnouncementSinkController(this),this.limitMounted=!1,this.previousInputLimit=!1,this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onTriggerFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)}}static{this.defaultStrings={...super.defaultStrings,catalogPickerInputLimit:LYRA_DEFAULT_catalogPickerInputLimit,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.ownedCollectionLimits={catalog:{entries:1024}}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}get catalogEditing(){return this.catalogPicker}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);const modeChanged=this.prepareModeFocus(this.closedMode);if(this.catalogPicker.suppressControlEvents=modeChanged,this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))){const activeValue=typeof this.renderRoot?.querySelector=="function"?this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value:void 0;this.catalogPicker.reconcileRows(activeValue,changed.has("value")||changed.has("allowCustom")||modeChanged,!1)}}disconnectedCallback(){super.disconnectedCallback(),this.clearModeFocus(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.clearModeFocus(),this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}requiredMessage(){return this.localize("modelSelectRequired")}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state,_mode){this.catalogPicker.restoreState(state)}formDisabledCallback(disabled){this.formDisabledChanged(disabled)}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}get inputLimited(){return publicCollectionTruncation(this,"catalog")!==void 0}updated(changed){super.updated(changed);const limited=this.inputLimited;this.limitMounted&&limited&&!this.previousInputLimit&&this.limitAnnouncements.announcePolite(this.localize("catalogPickerInputLimit")),this.previousInputLimit=limited,this.limitMounted=!0,this.syncCatalogDescription(this.controlId);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("readonly")||changed.has("touched")||changed.has("value"))&&(changed.has("readonly")&&this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),this.publishValidityStates(),this.catalogPicker.suppressControlEvents=!1,this.finishModeFocus("model-select-mode-focus")}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value,disabled=entry.disabled===!0;return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -96,4 +96,4 @@ import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../in
96
96
  `}render(){return html`<div part="form-control" tabindex="-1">
97
97
  ${this.inputLimited?html`<p part="limit">${this.localize("catalogPickerInputLimit")}</p>`:nothing}
98
98
  ${this.closedMode?this.renderClosed():this.renderFreeText()}
99
- </div>`}}__decorate([property()],LyraModelSelect.prototype,"provider",void 0),__decorate([property({attribute:!1})],LyraModelSelect.prototype,"catalog",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"allow-custom"})],LyraModelSelect.prototype,"allowCustom",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraModelSelect.prototype,"readonly",void 0),__decorate([property()],LyraModelSelect.prototype,"label",void 0),__decorate([property()],LyraModelSelect.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraModelSelect.prototype,"errorText",void 0),__decorate([property()],LyraModelSelect.prototype,"placeholder",void 0),__decorate([property({converter:spellcheckConverter})],LyraModelSelect.prototype,"spellcheck",void 0),__decorate([property()],LyraModelSelect.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraModelSelect.prototype,"autocorrect",null),__decorate([property()],LyraModelSelect.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraModelSelect.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraModelSelect.prototype,"enterKeyHint",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraModelSelect.prototype,"open",null),__decorate([property({reflect:!0})],LyraModelSelect.prototype,"size",void 0);export{LyraModelSelect};
99
+ </div>`}}__decorate([property()],LyraModelSelect.prototype,"provider",void 0),__decorate([property({attribute:!1})],LyraModelSelect.prototype,"catalog",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"allow-custom"})],LyraModelSelect.prototype,"allowCustom",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraModelSelect.prototype,"readonly",void 0),__decorate([property()],LyraModelSelect.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraModelSelect.prototype,"labelDisplay",void 0),__decorate([property()],LyraModelSelect.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraModelSelect.prototype,"errorText",void 0),__decorate([property()],LyraModelSelect.prototype,"placeholder",void 0),__decorate([property({converter:spellcheckConverter})],LyraModelSelect.prototype,"spellcheck",void 0),__decorate([property()],LyraModelSelect.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraModelSelect.prototype,"autocorrect",null),__decorate([property()],LyraModelSelect.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraModelSelect.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraModelSelect.prototype,"enterKeyHint",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraModelSelect.prototype,"open",null),__decorate([property({reflect:!0})],LyraModelSelect.prototype,"size",void 0);export{LyraModelSelect};
@@ -48,6 +48,11 @@ htmlMode:MarkdownHtmlMode;
48
48
  * GitHub-flavored Markdown (tables, strikethrough, autolinks, task lists). Unset (the default)
49
49
  * matches the composed element's own default. */
50
50
  withoutGfm:boolean;
51
+ /** Forwarded verbatim to the composed Markdown element's own `withoutImages` -- renders every
52
+ * image as its alt text so untrusted output (a streamed language-model answer, for example)
53
+ * never makes the page load an image. Unset (the default) matches the composed element's own
54
+ * default. */
55
+ withoutImages:boolean;
51
56
  /** Forwarded verbatim to the composed Markdown element's own `linkTarget` -- the `target`
52
57
  * applied to every rendered `<a>`, with `rel="noopener noreferrer"` always added by the
53
58
  * composed element alongside it whenever a `target` is emitted. `'_blank'` (the default)
@@ -1,3 +1,3 @@
1
- import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{Announcer}from"../../../internal/announcer.js";import{finiteDuration}from"../../../internal/numbers.js";import{streamingTailText}from"../markdown/markdown-streaming-tail.js";import{styles}from"./streaming-text.styles.js";import{IncrementalMarkdownDetector}from"./markdown-detection.js";import{looksLikeMarkdown}from"./markdown-detection.js";const DEFAULT_COALESCE_MS=50;class StreamingTextRuntimeBase extends LyraElement{static{this.styles=[LyraElement.styles,styles]}get markdownLanguages(){return combineShikiLanguageSources(this.languages,this.languageLoaders)}get safeCoalesceMs(){return finiteDuration(this.coalesceMs,DEFAULT_COALESCE_MS,0)}constructor(){super(),this.content="",this.streaming=!1,this.streamingRender="plain",this.coalesceMs=DEFAULT_COALESCE_MS,this.contentMode="auto",this.tabSize=4,this.htmlMode="sanitize",this.withoutGfm=!1,this.linkTarget="_blank",this.internalLinkPrefix="",this.headingOffset=0,this.withoutSyntaxHighlighting=!1,this.headingAnchors=!1,this.math=!1,this.maxHeight="",this.displayedContent="",this.lastScannedResult=!1,this.markdownDetector=new IncrementalMarkdownDetector,this.coalescer=new Announcer({throttleMs:this.safeCoalesceMs,onFlush:text=>{this.displayedContent=text}})}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.coalescer.setTimerHost(ownerWindow),this.hasUpdated&&this.displayedContent!==this.content&&this.coalescer.announce(this.content,{force:!0})}willUpdate(changed){super.willUpdate(changed),changed.has("coalesceMs")&&(this.coalescer.throttleMs=this.safeCoalesceMs),changed.has("content")&&this.coalescer.announce(this.content,{force:!this.hasUpdated}),changed.has("streaming")&&changed.get("streaming")!==void 0&&changed.get("streaming")!==this.streaming&&this.coalescer.announce(this.content,{force:!0}),changed.has("displayedContent")&&this.displayedContent!==this.lastScannedContent&&(this.lastScannedContent=this.displayedContent,this.lastScannedResult=this.markdownDetector.update(this.displayedContent))}updated(changed){super.updated(changed),changed.has("displayedContent")&&!this.effectiveMarkdown&&this.emit("lr-content-settled",null)}disconnectedCallback(){super.disconnectedCallback(),this.coalescer.cancel()}adoptedCallback(){super.adoptedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.coalescer.setTimerHost(ownerWindow)}get effectiveMarkdown(){return this.contentMode==="markdown"?!0:this.contentMode==="plain"?!1:this.lastScannedResult}stopOwnedEvent(event){event.stopPropagation()}render(){const cursor=this.streaming?html`<span part="cursor" aria-hidden="true"></span>`:nothing;return html`<div part="base"
1
+ import{__decorate}from"tslib";import{combineShikiLanguageSources}from"../../../internal/shiki-language-sources.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{Announcer}from"../../../internal/announcer.js";import{finiteDuration}from"../../../internal/numbers.js";import{streamingTailText}from"../markdown/markdown-streaming-tail.js";import{styles}from"./streaming-text.styles.js";import{IncrementalMarkdownDetector}from"./markdown-detection.js";import{looksLikeMarkdown}from"./markdown-detection.js";const DEFAULT_COALESCE_MS=50;class StreamingTextRuntimeBase extends LyraElement{static{this.styles=[LyraElement.styles,styles]}get markdownLanguages(){return combineShikiLanguageSources(this.languages,this.languageLoaders)}get safeCoalesceMs(){return finiteDuration(this.coalesceMs,DEFAULT_COALESCE_MS,0)}constructor(){super(),this.content="",this.streaming=!1,this.streamingRender="plain",this.coalesceMs=DEFAULT_COALESCE_MS,this.contentMode="auto",this.tabSize=4,this.htmlMode="sanitize",this.withoutGfm=!1,this.withoutImages=!1,this.linkTarget="_blank",this.internalLinkPrefix="",this.headingOffset=0,this.withoutSyntaxHighlighting=!1,this.headingAnchors=!1,this.math=!1,this.maxHeight="",this.displayedContent="",this.lastScannedResult=!1,this.markdownDetector=new IncrementalMarkdownDetector,this.coalescer=new Announcer({throttleMs:this.safeCoalesceMs,onFlush:text=>{this.displayedContent=text}})}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.coalescer.setTimerHost(ownerWindow),this.hasUpdated&&this.displayedContent!==this.content&&this.coalescer.announce(this.content,{force:!0})}willUpdate(changed){super.willUpdate(changed),changed.has("coalesceMs")&&(this.coalescer.throttleMs=this.safeCoalesceMs),changed.has("content")&&this.coalescer.announce(this.content,{force:!this.hasUpdated}),changed.has("streaming")&&changed.get("streaming")!==void 0&&changed.get("streaming")!==this.streaming&&this.coalescer.announce(this.content,{force:!0}),changed.has("displayedContent")&&this.displayedContent!==this.lastScannedContent&&(this.lastScannedContent=this.displayedContent,this.lastScannedResult=this.markdownDetector.update(this.displayedContent))}updated(changed){super.updated(changed),changed.has("displayedContent")&&!this.effectiveMarkdown&&this.emit("lr-content-settled",null)}disconnectedCallback(){super.disconnectedCallback(),this.coalescer.cancel()}adoptedCallback(){super.adoptedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.coalescer.setTimerHost(ownerWindow)}get effectiveMarkdown(){return this.contentMode==="markdown"?!0:this.contentMode==="plain"?!1:this.lastScannedResult}stopOwnedEvent(event){event.stopPropagation()}render(){const cursor=this.streaming?html`<span part="cursor" aria-hidden="true"></span>`:nothing;return html`<div part="base"
2
2
  >${this.effectiveMarkdown?html`${this.renderMarkdown()}${cursor}`:html`<span class="plain">${streamingTailText(this.displayedContent)}</span> ${cursor}`}</div
3
- >`}}__decorate([property()],StreamingTextRuntimeBase.prototype,"content",void 0),__decorate([property({type:Boolean,reflect:!0})],StreamingTextRuntimeBase.prototype,"streaming",void 0),__decorate([property({attribute:"streaming-render"})],StreamingTextRuntimeBase.prototype,"streamingRender",void 0),__decorate([property({type:Number,attribute:"coalesce-ms"})],StreamingTextRuntimeBase.prototype,"coalesceMs",void 0),__decorate([property({reflect:!0,attribute:"content-mode"})],StreamingTextRuntimeBase.prototype,"contentMode",void 0),__decorate([property({attribute:!1})],StreamingTextRuntimeBase.prototype,"languages",void 0),__decorate([property({attribute:!1})],StreamingTextRuntimeBase.prototype,"languageLoaders",void 0),__decorate([property({type:Number,attribute:"tab-size"})],StreamingTextRuntimeBase.prototype,"tabSize",void 0),__decorate([property({attribute:"html-mode"})],StreamingTextRuntimeBase.prototype,"htmlMode",void 0),__decorate([property({type:Boolean,attribute:"without-gfm"})],StreamingTextRuntimeBase.prototype,"withoutGfm",void 0),__decorate([property({attribute:"link-target"})],StreamingTextRuntimeBase.prototype,"linkTarget",void 0),__decorate([property({attribute:"internal-link-prefix"})],StreamingTextRuntimeBase.prototype,"internalLinkPrefix",void 0),__decorate([property({type:Number,attribute:"heading-offset"})],StreamingTextRuntimeBase.prototype,"headingOffset",void 0),__decorate([property({type:Boolean,attribute:"without-syntax-highlighting"})],StreamingTextRuntimeBase.prototype,"withoutSyntaxHighlighting",void 0),__decorate([property({type:Boolean,attribute:"heading-anchors"})],StreamingTextRuntimeBase.prototype,"headingAnchors",void 0),__decorate([property({type:Boolean})],StreamingTextRuntimeBase.prototype,"math",void 0),__decorate([property({attribute:"max-height"})],StreamingTextRuntimeBase.prototype,"maxHeight",void 0),__decorate([state()],StreamingTextRuntimeBase.prototype,"displayedContent",void 0);export{StreamingTextRuntimeBase,looksLikeMarkdown};
3
+ >`}}__decorate([property()],StreamingTextRuntimeBase.prototype,"content",void 0),__decorate([property({type:Boolean,reflect:!0})],StreamingTextRuntimeBase.prototype,"streaming",void 0),__decorate([property({attribute:"streaming-render"})],StreamingTextRuntimeBase.prototype,"streamingRender",void 0),__decorate([property({type:Number,attribute:"coalesce-ms"})],StreamingTextRuntimeBase.prototype,"coalesceMs",void 0),__decorate([property({reflect:!0,attribute:"content-mode"})],StreamingTextRuntimeBase.prototype,"contentMode",void 0),__decorate([property({attribute:!1})],StreamingTextRuntimeBase.prototype,"languages",void 0),__decorate([property({attribute:!1})],StreamingTextRuntimeBase.prototype,"languageLoaders",void 0),__decorate([property({type:Number,attribute:"tab-size"})],StreamingTextRuntimeBase.prototype,"tabSize",void 0),__decorate([property({attribute:"html-mode"})],StreamingTextRuntimeBase.prototype,"htmlMode",void 0),__decorate([property({type:Boolean,attribute:"without-gfm"})],StreamingTextRuntimeBase.prototype,"withoutGfm",void 0),__decorate([property({type:Boolean,attribute:"without-images"})],StreamingTextRuntimeBase.prototype,"withoutImages",void 0),__decorate([property({attribute:"link-target"})],StreamingTextRuntimeBase.prototype,"linkTarget",void 0),__decorate([property({attribute:"internal-link-prefix"})],StreamingTextRuntimeBase.prototype,"internalLinkPrefix",void 0),__decorate([property({type:Number,attribute:"heading-offset"})],StreamingTextRuntimeBase.prototype,"headingOffset",void 0),__decorate([property({type:Boolean,attribute:"without-syntax-highlighting"})],StreamingTextRuntimeBase.prototype,"withoutSyntaxHighlighting",void 0),__decorate([property({type:Boolean,attribute:"heading-anchors"})],StreamingTextRuntimeBase.prototype,"headingAnchors",void 0),__decorate([property({type:Boolean})],StreamingTextRuntimeBase.prototype,"math",void 0),__decorate([property({attribute:"max-height"})],StreamingTextRuntimeBase.prototype,"maxHeight",void 0),__decorate([state()],StreamingTextRuntimeBase.prototype,"displayedContent",void 0);export{StreamingTextRuntimeBase,looksLikeMarkdown};
@@ -8,7 +8,7 @@ export interface LyraStreamingTextCoreEventMap extends StreamingTextRuntimeEvent
8
8
  * `languages` map already covers every fenced-code language it will ever stream, or who never
9
9
  * renders fenced code at all. Every capability is identical to `<lr-streaming-text>` -- token
10
10
  * coalescing, `contentMode` auto-detection, the blinking cursor, the `lr-content-settled` event,
11
- * and the full forwarded Markdown configuration surface (`tabSize`, `htmlMode`, `withoutGfm`,
11
+ * and the full forwarded Markdown configuration surface (`tabSize`, `htmlMode`, `withoutGfm`, `withoutImages`,
12
12
  * `linkTarget`, `internalLinkPrefix`, `headingOffset`, `withoutSyntaxHighlighting`, `headingAnchors`, `math`,
13
13
  * `maxHeight`) -- only which Markdown element Markdown mode composes differs: this variant
14
14
  * renders `<lr-markdown-core>` (`../markdown/markdown-core.js`) instead of `<lr-markdown>`, so this
@@ -8,6 +8,7 @@ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/dec
8
8
  .tabSize=${this.tabSize}
9
9
  .htmlMode=${this.htmlMode}
10
10
  .withoutGfm=${this.withoutGfm}
11
+ .withoutImages=${this.withoutImages}
11
12
  .linkTarget=${this.linkTarget}
12
13
  .internalLinkPrefix=${this.internalLinkPrefix}
13
14
  .headingOffset=${this.headingOffset}
@@ -41,7 +41,7 @@ import{type TemplateResult}from'lit';import{StreamingTextRuntimeBase}from'./stre
41
41
  * component's own `languages` through verbatim; plain-text mode
42
42
  * renders into a `white-space: pre-wrap` span instead. The rest of
43
43
  * `<lr-markdown>`'s configuration surface is forwarded verbatim too --
44
- * `tabSize`, `htmlMode`, `withoutGfm`, `linkTarget`, `internalLinkPrefix`,
44
+ * `tabSize`, `htmlMode`, `withoutGfm`, `withoutImages`, `linkTarget`, `internalLinkPrefix`,
45
45
  * `headingOffset`, `withoutSyntaxHighlighting`, `headingAnchors`, `math`, and
46
46
  * `maxHeight` -- each defaulting to exactly `<lr-markdown>`'s own default, so
47
47
  * leaving all of them unset renders identically to before this wrapper
@@ -9,6 +9,7 @@ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/dec
9
9
  .tabSize=${this.tabSize}
10
10
  .htmlMode=${this.htmlMode}
11
11
  .withoutGfm=${this.withoutGfm}
12
+ .withoutImages=${this.withoutImages}
12
13
  .linkTarget=${this.linkTarget}
13
14
  .internalLinkPrefix=${this.internalLinkPrefix}
14
15
  .headingOffset=${this.headingOffset}
@@ -44,6 +44,12 @@ disabled?:boolean;}export interface LyraSuggestionChipsEventMap{'lr-suggestion-s
44
44
  * @cssprop [--lr-suggestion-chips-hover-bg=var(--lr-color-brand-quiet)] - Background of a hovered chip.
45
45
  * @cssprop [--lr-suggestion-chips-hover-border=var(--lr-color-brand)] - Border color of a hovered chip.
46
46
  * @cssprop [--lr-suggestion-chips-disabled-opacity=var(--lr-opacity-disabled)] - Opacity of a chip whose suggestion sets `disabled`.
47
+ * @cssprop [--lr-suggestion-chips-label-lines=1] - Maximum lines of each `chip-label` before it is
48
+ * clamped with an ellipsis. Unset, the scrolling row shows one line and a `wrap` row shows up to
49
+ * 3, so full-question starter prompts stay readable in a narrow chat column.
50
+ * @cssprop [--lr-suggestion-chips-chip-max-inline-size=var(--lr-size-16rem)] - Maximum inline size of
51
+ * each chip. In a `wrap` row it is further clamped to the row's inline size, so a chip never
52
+ * overflows its container.
47
53
  * @status stable
48
54
  * @since 4.0.0
49
55
  */
@@ -1 +1 @@
1
- import{focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; max-inline-size: 100%; } [part='base'] { max-inline-size: 100%; } .row { display: flex; justify-content: var(--lr-suggestion-chips-justify, flex-start); gap: var(--lr-space-xs); } :host([wrap]) .row { flex-wrap: wrap; } [part~='chip'] { display: flex; align-items: center; gap: var(--lr-space-xs); flex: 0 0 auto; max-inline-size: var(--lr-size-16rem); padding-inline: var(--lr-space-m); padding-block: var(--lr-space-xs); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-pill); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; text-align: start; cursor: pointer; min-block-size: var(--lr-size-2-5rem); transition: background-color var(--lr-transition-fast), border-color var(--lr-transition-fast); } .content { display: flex; flex-direction: column; align-items: flex-start; gap: var(--lr-space-2xs); min-inline-size: 0; } [part='chip-icon'] { flex: none; line-height: var(--lr-line-height-compact); } [part~='chip']:where(:not(:disabled)):hover { background: var(--lr-suggestion-chips-hover-bg, var(--lr-color-brand-quiet)); border-color: var(--lr-suggestion-chips-hover-border, var(--lr-color-brand)); } [part~='chip']:where(:not(:disabled)):active { background: color-mix( in oklab, var(--lr-suggestion-chips-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); border-color: var(--lr-suggestion-chips-hover-border, var(--lr-color-brand)); } [part~='chip']:disabled { cursor: not-allowed; opacity: var(--lr-suggestion-chips-disabled-opacity, var(--lr-opacity-disabled)); } [part~='chip']:focus-visible { ${focusRing} } [part='chip-label'] { display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; inline-size: 100%; } [part='chip-detail'] { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; inline-size: 100%; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-xs); } `;export{styles};
1
+ import{focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; max-inline-size: 100%; } [part='base'] { max-inline-size: 100%; } .row { display: flex; justify-content: var(--lr-suggestion-chips-justify, flex-start); gap: var(--lr-space-xs); } :host([wrap]) .row { flex-wrap: wrap; } [part~='chip'] { display: flex; align-items: center; gap: var(--lr-space-xs); flex: 0 0 auto; max-inline-size: var(--lr-suggestion-chips-chip-max-inline-size, var(--lr-size-16rem)); padding-inline: var(--lr-space-m); padding-block: var(--lr-space-xs); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-pill); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; text-align: start; cursor: pointer; min-block-size: var(--lr-size-2-5rem); transition: background-color var(--lr-transition-fast), border-color var(--lr-transition-fast); } .content { display: flex; flex-direction: column; align-items: flex-start; gap: var(--lr-space-2xs); min-inline-size: 0; } [part='chip-icon'] { flex: none; line-height: var(--lr-line-height-compact); } :host([wrap]) [part~='chip'] { max-inline-size: min(var(--lr-suggestion-chips-chip-max-inline-size, var(--lr-size-16rem)), 100%); } [part~='chip']:where(:not(:disabled)):hover { background: var(--lr-suggestion-chips-hover-bg, var(--lr-color-brand-quiet)); border-color: var(--lr-suggestion-chips-hover-border, var(--lr-color-brand)); } [part~='chip']:where(:not(:disabled)):active { background: color-mix( in oklab, var(--lr-suggestion-chips-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); border-color: var(--lr-suggestion-chips-hover-border, var(--lr-color-brand)); } [part~='chip']:disabled { cursor: not-allowed; opacity: var(--lr-suggestion-chips-disabled-opacity, var(--lr-opacity-disabled)); } [part~='chip']:focus-visible { ${focusRing} } [part='chip-label'] { display: -webkit-box; -webkit-line-clamp: var(--lr-suggestion-chips-label-lines, 1); -webkit-box-orient: vertical; overflow: hidden; inline-size: 100%; } :host([wrap]) [part='chip-label'] { -webkit-line-clamp: var(--lr-suggestion-chips-label-lines, 3); } [part='chip-detail'] { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; inline-size: 100%; color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-xs); } `;export{styles};
@@ -1,4 +1,4 @@
1
- import{type TemplateResult,type PropertyValues}from'lit';import{LyraCatalogPickerElement}from'../catalog-picker-element.js';import type{LyraSize}from'../../../internal/variants.js';import type{LyraSelectionDirection}from'../../../internal/shared-unions.js';import{CatalogPickerController,type LyraCatalog,type LyraCatalogEntry}from'../../../internal/catalog-picker.js';
1
+ import{type TemplateResult,type PropertyValues}from'lit';import{LyraCatalogPickerElement}from'../catalog-picker-element.js';import type{LyraSize,LyraLabelDisplay}from'../../../internal/variants.js';import type{LyraSelectionDirection}from'../../../internal/shared-unions.js';import{CatalogPickerController,type LyraCatalog,type LyraCatalogEntry}from'../../../internal/catalog-picker.js';
2
2
  /** A catalog row: a selectable TTS voice.*/
3
3
  export interface LyraVoiceCatalogEntry extends LyraCatalogEntry{
4
4
  /** Rendered (with `description`) as a quiet `[part="option-meta"]` second line.*/
@@ -198,7 +198,14 @@ readonly:boolean;
198
198
  * preview icons. */
199
199
  withoutPreview:boolean;
200
200
  /** Visible label text. The `label` slot appends custom label content to the same native label.*/
201
- label:string;hint:string;errorText:string;placeholder:string;spellcheck:boolean;autocapitalize:string;private autocorrectValue;
201
+ label:string;
202
+ /**
203
+ * Whether the `label` renders on screen. `hidden` keeps the label as the accessible name but
204
+ * removes it visually (compact toolbars, table cells); hint, error and required semantics are
205
+ * unaffected. Reflected so styles and `[label-display]` selectors match.
206
+ * @attr label-display
207
+ */
208
+ labelDisplay:LyraLabelDisplay;hint:string;errorText:string;placeholder:string;spellcheck:boolean;autocapitalize:string;private autocorrectValue;
202
209
  /** Native editing-assistance state forwarded as canonical `autocorrect="on"|"off"`. Reads are
203
210
  * boolean; writes accept the boolean IDL and the `'on'`/`'off'` vocabulary. */
204
211
  get autocorrect():boolean;set autocorrect(next:boolean|string);autocomplete:string;inputMode:string;enterKeyHint:string;
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{guard}from"lit/directives/guard.js";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraCatalogPickerElement}from"../catalog-picker-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{autocorrectConverter,normalizeAutocorrect,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{publicCollectionTruncation,collectionSupport}from"../../../internal/collection-snapshot.js";import{LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_catalogPickerInputLimit,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraVoicePicker extends LyraCatalogPickerElement{constructor(){super(...arguments),this.provider="",this.allowCustom=!1,this.readonly=!1,this.withoutPreview=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.slotPresence=new SlotPresenceController(this),this.previewingId=null,this.listId=nextId("voice-picker-list"),this.controlId=nextId("voice-picker-control"),this.pendingPreviewId=null,this.previewGeneration=0,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,isReadonly:()=>this.readonly,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label,entry.language??"",entry.description??""],emitInput:detail=>this.emit("lr-input",detail),emitChange:detail=>this.emit("lr-change",detail),beforeValueChange:value=>{const previewTarget=this.internalPreviewTargetId;previewTarget!==null&&previewTarget!==value&&this.stopInternalPreview()},beforeActiveIndexChange:next=>this.reconcilePreviewForActiveIndex(next),afterQueryChange:()=>this.reconcilePreviewVisibility(this.open,this.catalogPicker.filteredEntries),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state2,oldValue)=>{state2==="open"?(this.catalogPicker.open||this.reconcilePreviewVisibility(!1,[]),this.requestUpdate("open",oldValue)):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)}}),this.limitAnnouncements=new AnnouncementSinkController(this),this.limitMounted=!1,this.previousInputLimit=!1,this.onAudioEnded=event=>{event.currentTarget===this.audioEl&&this.stopInternalPreview()},this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio,isDomErrorEvent=direct.localName!=="audio",audioLike=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget,failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause=="function"&&typeof audioLike.removeEventListener=="function"?audioLike:void 0;if(!failedAudio||(failedAudio.removeEventListener("ended",this.onAudioEnded),failedAudio.removeEventListener("error",this.onAudioLoadFailure),failedAudio.pause(),failedAudio!==this.audioEl))return;const pendingVoiceId=this.pendingPreviewId;this.previewGeneration++,this.audioEl=void 0,this.pendingPreviewId=null,isDomErrorEvent&&this.previewingId===null&&pendingVoiceId!==null&&(this.previewingId=pendingVoiceId,this.emit("lr-preview-change",{voiceId:pendingVoiceId})),this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))},this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;candidate&&(this.internalPreviewTargetId===candidate?this.stopInternalPreview():this.requestPreview(candidate))},this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation(),this.internalPreviewTargetId===entry.id?this.stopInternalPreview():this.requestPreview(entry.id)},this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onControlBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onControlFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)}}static{this.defaultStrings={...super.defaultStrings,catalogPickerInputLimit:LYRA_DEFAULT_catalogPickerInputLimit,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.ownedCollectionLimits={catalog:{entries:1024}}}static{this.properties={value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!1,useDefault:!0,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}get catalogEditing(){return this.catalogPicker}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);const switchingMode=this.prepareModeFocus(this.closedMode);if(this.catalogPicker.suppressControlEvents=switchingMode,this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value,rows=this.closedMode?this.effectiveEntries:this.filteredEntries;this.catalogPicker.reconcileRows(activeValue,this.open&&(changed.has("value")||changed.has("allowCustom")||switchingMode),!1),this.reconcilePreviewVisibility(this.open,rows)}changed.has("catalog")&&this.internalPreviewTargetId!==null&&this.stopInternalPreview(),changed.has("withoutPreview")&&this.withoutPreview&&this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}requiredMessage(){return this.localize("voicePickerRequired")}releaseOnDisable(){super.releaseOnDisable(),this.stopInternalPreview()}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state2,_mode){this.catalogPicker.restoreState(state2)}formDisabledCallback(disabled){this.formDisabledChanged(disabled)}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}get inputLimited(){return publicCollectionTruncation(this,"catalog")!==void 0}updated(changed){super.updated(changed);const limited=this.inputLimited;this.limitMounted&&limited&&!this.previousInputLimit&&this.limitAnnouncements.announcePolite(this.localize("catalogPickerInputLimit")),this.previousInputLimit=limited,this.limitMounted=!0,this.syncCatalogDescription(this.controlId);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("readonly")||changed.has("touched")||changed.has("value"))&&(changed.has("readonly")&&this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),this.publishValidityStates(),this.finishModeFocus("voice-picker-mode-focus"),this.catalogPicker.suppressControlEvents=!1}get internalPreviewTargetId(){return this.pendingPreviewId??this.previewingId}reconcilePreviewVisibility(open,rows){const target=this.internalPreviewTargetId;if(target===null)return;const standaloneCandidate=open&&this.activeIndex>=0?rows[this.activeIndex]?.id??this.value:this.value,hasVisibleRow=open&&rows.some(entry=>entry.id===target&&!!entry.previewUrl);target!==standaloneCandidate&&!hasVisibleRow&&this.stopInternalPreview()}reconcilePreviewForActiveIndex(next){const target=this.internalPreviewTargetId;if(target!==null){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries,nextCandidate=this.open&&next>=0?rows[next]?.id??this.value:this.value;target!==nextCandidate&&this.stopInternalPreview()}}get previewCandidateId(){return this.open&&this.activeIndex>=0?(this.closedMode?this.effectiveEntries:this.filteredEntries)[this.activeIndex]?.id??this.value:this.value}requestPreview(voiceId){if(!voiceId)return;const currentTarget=this.internalPreviewTargetId;currentTarget!==null&&currentTarget!==voiceId&&this.stopInternalPreview();const previewUrl=this.catalogPicker.entryFor(voiceId)?.previewUrl;!this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:!0}).defaultPrevented&&previewUrl&&this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe,audio.addEventListener("ended",this.onAudioEnded),audio.addEventListener("error",this.onAudioLoadFailure);const generation=++this.previewGeneration;this.audioEl=audio,this.pendingPreviewId=voiceId;let playResult;try{playResult=audio.play()}catch{this.onAudioLoadFailure(audio);return}Promise.resolve(playResult).then(()=>{generation!==this.previewGeneration||audio!==this.audioEl||this.pendingPreviewId!==voiceId||(this.pendingPreviewId=null,this.previewingId=voiceId,this.emit("lr-preview-change",{voiceId}))},()=>this.onAudioLoadFailure(audio))}stopInternalPreview(){const hadTarget=this.internalPreviewTargetId!==null||this.audioEl!==void 0;this.audioEl&&(this.audioEl.removeEventListener("ended",this.onAudioEnded),this.audioEl.removeEventListener("error",this.onAudioLoadFailure),this.audioEl.pause(),this.audioEl=void 0),hadTarget&&this.previewGeneration++,this.pendingPreviewId=null,this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))}get previewButtonLabel(){const candidate=this.previewCandidateId,playing=this.previewingId!==null&&this.previewingId===candidate,name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value,meta=[entry.language,entry.description].filter(Boolean).join(" · ");return html`<div
1
+ import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{guard}from"lit/directives/guard.js";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraCatalogPickerElement}from"../catalog-picker-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{autocorrectConverter,normalizeAutocorrect,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{publicCollectionTruncation,collectionSupport}from"../../../internal/collection-snapshot.js";import{LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_catalogPickerInputLimit,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraVoicePicker extends LyraCatalogPickerElement{constructor(){super(...arguments),this.provider="",this.allowCustom=!1,this.readonly=!1,this.withoutPreview=!1,this.label="",this.labelDisplay="visible",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.slotPresence=new SlotPresenceController(this),this.previewingId=null,this.listId=nextId("voice-picker-list"),this.controlId=nextId("voice-picker-control"),this.pendingPreviewId=null,this.previewGeneration=0,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,isReadonly:()=>this.readonly,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label,entry.language??"",entry.description??""],emitInput:detail=>this.emit("lr-input",detail),emitChange:detail=>this.emit("lr-change",detail),beforeValueChange:value=>{const previewTarget=this.internalPreviewTargetId;previewTarget!==null&&previewTarget!==value&&this.stopInternalPreview()},beforeActiveIndexChange:next=>this.reconcilePreviewForActiveIndex(next),afterQueryChange:()=>this.reconcilePreviewVisibility(this.open,this.catalogPicker.filteredEntries),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state2,oldValue)=>{state2==="open"?(this.catalogPicker.open||this.reconcilePreviewVisibility(!1,[]),this.requestUpdate("open",oldValue)):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)}}),this.limitAnnouncements=new AnnouncementSinkController(this),this.limitMounted=!1,this.previousInputLimit=!1,this.onAudioEnded=event=>{event.currentTarget===this.audioEl&&this.stopInternalPreview()},this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio,isDomErrorEvent=direct.localName!=="audio",audioLike=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget,failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause=="function"&&typeof audioLike.removeEventListener=="function"?audioLike:void 0;if(!failedAudio||(failedAudio.removeEventListener("ended",this.onAudioEnded),failedAudio.removeEventListener("error",this.onAudioLoadFailure),failedAudio.pause(),failedAudio!==this.audioEl))return;const pendingVoiceId=this.pendingPreviewId;this.previewGeneration++,this.audioEl=void 0,this.pendingPreviewId=null,isDomErrorEvent&&this.previewingId===null&&pendingVoiceId!==null&&(this.previewingId=pendingVoiceId,this.emit("lr-preview-change",{voiceId:pendingVoiceId})),this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))},this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;candidate&&(this.internalPreviewTargetId===candidate?this.stopInternalPreview():this.requestPreview(candidate))},this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation(),this.internalPreviewTargetId===entry.id?this.stopInternalPreview():this.requestPreview(entry.id)},this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onControlBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onControlFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)}}static{this.defaultStrings={...super.defaultStrings,catalogPickerInputLimit:LYRA_DEFAULT_catalogPickerInputLimit,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.ownedCollectionLimits={catalog:{entries:1024}}}static{this.properties={value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!1,useDefault:!0,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}get catalogEditing(){return this.catalogPicker}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);const switchingMode=this.prepareModeFocus(this.closedMode);if(this.catalogPicker.suppressControlEvents=switchingMode,this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value,rows=this.closedMode?this.effectiveEntries:this.filteredEntries;this.catalogPicker.reconcileRows(activeValue,this.open&&(changed.has("value")||changed.has("allowCustom")||switchingMode),!1),this.reconcilePreviewVisibility(this.open,rows)}changed.has("catalog")&&this.internalPreviewTargetId!==null&&this.stopInternalPreview(),changed.has("withoutPreview")&&this.withoutPreview&&this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}requiredMessage(){return this.localize("voicePickerRequired")}releaseOnDisable(){super.releaseOnDisable(),this.stopInternalPreview()}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state2,_mode){this.catalogPicker.restoreState(state2)}formDisabledCallback(disabled){this.formDisabledChanged(disabled)}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}get inputLimited(){return publicCollectionTruncation(this,"catalog")!==void 0}updated(changed){super.updated(changed);const limited=this.inputLimited;this.limitMounted&&limited&&!this.previousInputLimit&&this.limitAnnouncements.announcePolite(this.localize("catalogPickerInputLimit")),this.previousInputLimit=limited,this.limitMounted=!0,this.syncCatalogDescription(this.controlId);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("readonly")||changed.has("touched")||changed.has("value"))&&(changed.has("readonly")&&this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),this.publishValidityStates(),this.finishModeFocus("voice-picker-mode-focus"),this.catalogPicker.suppressControlEvents=!1}get internalPreviewTargetId(){return this.pendingPreviewId??this.previewingId}reconcilePreviewVisibility(open,rows){const target=this.internalPreviewTargetId;if(target===null)return;const standaloneCandidate=open&&this.activeIndex>=0?rows[this.activeIndex]?.id??this.value:this.value,hasVisibleRow=open&&rows.some(entry=>entry.id===target&&!!entry.previewUrl);target!==standaloneCandidate&&!hasVisibleRow&&this.stopInternalPreview()}reconcilePreviewForActiveIndex(next){const target=this.internalPreviewTargetId;if(target!==null){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries,nextCandidate=this.open&&next>=0?rows[next]?.id??this.value:this.value;target!==nextCandidate&&this.stopInternalPreview()}}get previewCandidateId(){return this.open&&this.activeIndex>=0?(this.closedMode?this.effectiveEntries:this.filteredEntries)[this.activeIndex]?.id??this.value:this.value}requestPreview(voiceId){if(!voiceId)return;const currentTarget=this.internalPreviewTargetId;currentTarget!==null&&currentTarget!==voiceId&&this.stopInternalPreview();const previewUrl=this.catalogPicker.entryFor(voiceId)?.previewUrl;!this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:!0}).defaultPrevented&&previewUrl&&this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe,audio.addEventListener("ended",this.onAudioEnded),audio.addEventListener("error",this.onAudioLoadFailure);const generation=++this.previewGeneration;this.audioEl=audio,this.pendingPreviewId=voiceId;let playResult;try{playResult=audio.play()}catch{this.onAudioLoadFailure(audio);return}Promise.resolve(playResult).then(()=>{generation!==this.previewGeneration||audio!==this.audioEl||this.pendingPreviewId!==voiceId||(this.pendingPreviewId=null,this.previewingId=voiceId,this.emit("lr-preview-change",{voiceId}))},()=>this.onAudioLoadFailure(audio))}stopInternalPreview(){const hadTarget=this.internalPreviewTargetId!==null||this.audioEl!==void 0;this.audioEl&&(this.audioEl.removeEventListener("ended",this.onAudioEnded),this.audioEl.removeEventListener("error",this.onAudioLoadFailure),this.audioEl.pause(),this.audioEl=void 0),hadTarget&&this.previewGeneration++,this.pendingPreviewId=null,this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))}get previewButtonLabel(){const candidate=this.previewCandidateId,playing=this.previewingId!==null&&this.previewingId===candidate,name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value,meta=[entry.language,entry.description].filter(Boolean).join(" · ");return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -125,4 +125,4 @@ import{__decorate}from"tslib";import{AnnouncementSinkController}from"../../../in
125
125
  `}render(){return html`<div part="form-control" tabindex="-1">
126
126
  ${this.inputLimited?html`<p part="limit">${this.localize("catalogPickerInputLimit")}</p>`:nothing}
127
127
  ${this.closedMode?this.renderClosed():this.renderFreeText()}
128
- </div>`}}__decorate([property()],LyraVoicePicker.prototype,"provider",void 0),__decorate([property({attribute:!1})],LyraVoicePicker.prototype,"catalog",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"allow-custom"})],LyraVoicePicker.prototype,"allowCustom",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraVoicePicker.prototype,"readonly",void 0),__decorate([property({type:Boolean,attribute:"without-preview",reflect:!0})],LyraVoicePicker.prototype,"withoutPreview",void 0),__decorate([property()],LyraVoicePicker.prototype,"label",void 0),__decorate([property()],LyraVoicePicker.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraVoicePicker.prototype,"errorText",void 0),__decorate([property()],LyraVoicePicker.prototype,"placeholder",void 0),__decorate([property({converter:spellcheckConverter})],LyraVoicePicker.prototype,"spellcheck",void 0),__decorate([property()],LyraVoicePicker.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraVoicePicker.prototype,"autocorrect",null),__decorate([property()],LyraVoicePicker.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraVoicePicker.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraVoicePicker.prototype,"enterKeyHint",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraVoicePicker.prototype,"open",null),__decorate([property({reflect:!0})],LyraVoicePicker.prototype,"size",void 0),__decorate([state()],LyraVoicePicker.prototype,"previewingId",void 0);export{LyraVoicePicker};
128
+ </div>`}}__decorate([property()],LyraVoicePicker.prototype,"provider",void 0),__decorate([property({attribute:!1})],LyraVoicePicker.prototype,"catalog",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"allow-custom"})],LyraVoicePicker.prototype,"allowCustom",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraVoicePicker.prototype,"readonly",void 0),__decorate([property({type:Boolean,attribute:"without-preview",reflect:!0})],LyraVoicePicker.prototype,"withoutPreview",void 0),__decorate([property()],LyraVoicePicker.prototype,"label",void 0),__decorate([property({attribute:"label-display",reflect:!0})],LyraVoicePicker.prototype,"labelDisplay",void 0),__decorate([property()],LyraVoicePicker.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraVoicePicker.prototype,"errorText",void 0),__decorate([property()],LyraVoicePicker.prototype,"placeholder",void 0),__decorate([property({converter:spellcheckConverter})],LyraVoicePicker.prototype,"spellcheck",void 0),__decorate([property()],LyraVoicePicker.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraVoicePicker.prototype,"autocorrect",null),__decorate([property()],LyraVoicePicker.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraVoicePicker.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraVoicePicker.prototype,"enterKeyHint",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraVoicePicker.prototype,"open",null),__decorate([property({reflect:!0})],LyraVoicePicker.prototype,"size",void 0),__decorate([state()],LyraVoicePicker.prototype,"previewingId",void 0);export{LyraVoicePicker};