@aceshooting/lyra-ui 30.9.0 → 31.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +236 -339
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/charts/chart/box-plot.class.js +2 -2
- package/dist/components/charts/chart/chart-sync.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
- package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
- package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
- package/dist/components/conversation/markdown/markdown-shared.js +3 -3
- package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
- package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +31 -2
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline-cluster.js +1 -1
- package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
- package/dist/components/data/timeline/timeline-item.class.js +16 -12
- package/dist/components/data/timeline/timeline-item.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.d.ts +14 -2
- package/dist/components/data/timeline/timeline.class.js +9 -5
- package/dist/components/data/tree/tree-item.class.js +1 -1
- package/dist/components/data/tree/tree.class.d.ts +2 -0
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/button/button.class.d.ts +8 -6
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-core.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
- package/dist/components/forms/icon-button/icon-button.class.js +2 -2
- package/dist/components/forms/input/input-shared.js +2 -2
- package/dist/components/forms/input/number-input-locale.js +1 -0
- package/dist/components/forms/input/number-input.class.d.ts +19 -2
- package/dist/components/forms/input/number-input.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/flag/flag-url-resolver.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
- package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/map/map-owned-features.js +1 -1
- package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
- package/dist/components/media/map/map-scene-render-controller.js +1 -1
- package/dist/components/media/map/map.class.d.ts +5 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/video/video.class.d.ts +3 -3
- package/dist/components/media/video/video.class.js +3 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
- package/dist/components/overlays/overlay/tooltip.class.js +3 -3
- package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
- package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/anchored-overlay-runtime.js +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/drop-session-controller.js +1 -1
- package/dist/internal/engine-3d.js +1 -1
- package/dist/internal/icon-only-content.js +1 -1
- package/dist/internal/layered-layout.js +1 -1
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/safe-url.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/source-window-controller.js +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/viewer-search.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/sequence-time-binding.js +1 -1
- package/dist/simulation-clock.js +1 -1
- package/dist/styles/reservations.css +1 -1
- package/dist/styles/reservations.styles.js +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +13 -7
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-json-viewer.md +17 -0
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-markdown-core.md +2 -1
- package/llms/components/lr-markdown.md +20 -4
- package/llms/components/lr-menu.md +3 -1
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-prompt-input.md +1 -1
- package/llms/components/lr-streaming-text-core.md +3 -2
- package/llms/components/lr-streaming-text.md +4 -1
- package/llms/components/lr-suggestion-chips.md +28 -5
- package/llms/components/lr-tab-group.md +13 -1
- package/llms/components/lr-tab.md +5 -0
- package/llms/components/lr-table.md +25 -4
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +38 -4
- package/llms/components/lr-tooltip.md +3 -1
- package/llms/components/lr-tree.md +4 -0
- package/llms/components/lr-virtual-list.md +1 -0
- package/llms/peers.md +2 -2
- package/llms/shared/forms-and-accessibility.md +21 -4
- package/llms/shared.md +21 -4
- package/package.json +21 -20
- package/registrations.json +1 -1
|
@@ -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={"&":"&","<":"<",">":">",'"':""","'":"'"};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>
|
|
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,safeLinkHrefWithin,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={"&":"&","<":"<",">":">",'"':""","'":"'"};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,linkSchemesOption=null,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);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(
|
|
17
|
+
`},link(token){const text=this.parser.parseInline(token.tokens),href=cleanHref(token.href);if(href===null)return text;const safeHref=linkSchemesOption?safeLinkHrefWithin(href,linkSchemesOption):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}const XLINK_NAMESPACE="http://www.w3.org/1999/xlink";function enforceMarkdownLinkSchemes(markup,allowed){if(!/<(?:a|area)[\s/>]/i.test(markup))return markup;const template=document.createElement("template");template.innerHTML=markup;let changed=!1;for(const link of template.content.querySelectorAll("a, area"))[link.getAttribute("href"),link.getAttributeNS(XLINK_NAMESPACE,"href")].every(href=>href===null||safeLinkHrefWithin(href,allowed)!==null)||(link.localName==="area"?link.remove():link.replaceWith(...link.childNodes),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("linkSchemes")||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,linkSchemes=options.linkSchemes??null;if(policy===null)return{status:"rendered",html:finishMarkdownHtml(deps,null,rawHtml,hasRawHtml,withoutImages,linkSchemes),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,linkSchemes)}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,linkSchemes=null){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,narrowed=linkSchemes?enforceMarkdownLinkSchemes(guarded,linkSchemes):guarded;return withoutImages?stripMarkdownImages(narrowed):narrowed}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}
|
|
@@ -229,6 +229,16 @@ withoutImages:boolean;
|
|
|
229
229
|
* (or the empty string, e.g. via the `link-target=""` attribute) to omit
|
|
230
230
|
* `target`/`rel` entirely, so rendered links open in the same tab. */
|
|
231
231
|
linkTarget:string|null;
|
|
232
|
+
/** Narrows which link destinations may become anchors: a space- or comma-separated list of
|
|
233
|
+
* `http`, `https`, `blob`, `mailto` and `relative` (a URL with no scheme of its own: a path,
|
|
234
|
+
* query, fragment or scheme-relative `//host` URL), e.g. `link-schemes="https"`. Unset (the
|
|
235
|
+
* default) keeps the standard allowlist. Tokens are case-insensitive and may end in `:`; any
|
|
236
|
+
* other token is ignored, so this can only narrow that allowlist, never widen it, and a list with
|
|
237
|
+
* no recognised token (including the empty string) allows no link at all. A refused link fails
|
|
238
|
+
* closed: it renders as its plain text, never as an anchor. When set, it applies in every
|
|
239
|
+
* `htmlMode` (`trusted` included) to Markdown links, autolinks and, after sanitization, raw HTML
|
|
240
|
+
* `<a>`/`<area>` elements. Images are governed separately by `withoutImages`. */
|
|
241
|
+
linkSchemes?:string;
|
|
232
242
|
/** When set, a rendered link whose `href` starts with this prefix is
|
|
233
243
|
* treated as internal — its click is intercepted and reported via
|
|
234
244
|
* `lr-link-activate` instead of navigating. Empty (the default) means
|
|
@@ -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.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
|
+
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:"link-schemes"})],LyraMarkdown.prototype,"linkSchemes",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{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{thumbIcon}from"../../../internal/icons.js";import{nextId}from"../../../internal/a11y.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{composedContains}from"../../../internal/overlay-stack.js";import{getOwnDataDescriptor,isObjectValue,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{autocorrectConverter,declaredDefaultConverter,normalizeAutocorrect,omittedEmptyStringConverter,trueDefaultSpellcheckConverter}from"../../../internal/converters.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./message-feedback.styles.js";import{leaseTabIndex}from"../../../internal/roving-toolbar.js";import{LYRA_DEFAULT_feedbackCommentLabel,LYRA_DEFAULT_feedbackCommentPlaceholder,LYRA_DEFAULT_feedbackNegative,LYRA_DEFAULT_feedbackPositive,LYRA_DEFAULT_feedbackReasonsLabel,LYRA_DEFAULT_feedbackSubmit,LYRA_DEFAULT_feedbackSubmitted}from"../../../internal/default-strings/conversation.generated.js";const MAX_PROJECTED_FEEDBACK_REASONS=1e4,EMPTY_FEEDBACK_DETAIL_PROJECTION=Object.freeze({reasons:Object.freeze([]),commentable:!1});function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function projectFeedbackDetail(detail){if(!isObjectValue(detail))return EMPTY_FEEDBACK_DETAIL_PROJECTION;const reasonsDescriptor=getOwnDataDescriptor(detail,"reasons"),commentableDescriptor=getOwnDataDescriptor(detail,"commentable"),commentable=commentableDescriptor!==MISSING_OWN_DATA_DESCRIPTOR&&commentableDescriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&commentableDescriptor.value===!0,reasonsValue=reasonsDescriptor!==MISSING_OWN_DATA_DESCRIPTOR&&reasonsDescriptor!==UNSAFE_OWN_DATA_DESCRIPTOR?reasonsDescriptor.value:void 0;if(!isArrayValue(reasonsValue))return commentable?Object.freeze({reasons:Object.freeze([]),commentable}):EMPTY_FEEDBACK_DETAIL_PROJECTION;const lengthDescriptor=getOwnDataDescriptor(reasonsValue,"length");if(lengthDescriptor===MISSING_OWN_DATA_DESCRIPTOR||lengthDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return commentable?Object.freeze({reasons:Object.freeze([]),commentable}):EMPTY_FEEDBACK_DETAIL_PROJECTION;const reasons=[],seen=new Set,length=Math.min(lengthDescriptor.value,MAX_PROJECTED_FEEDBACK_REASONS);for(let index=0;index<length;index+=1){const rowDescriptor=getOwnDataDescriptor(reasonsValue,String(index));if(rowDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rowDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!isObjectValue(rowDescriptor.value))continue;const row=rowDescriptor.value,idDescriptor=getOwnDataDescriptor(row,"id"),labelDescriptor=getOwnDataDescriptor(row,"label");if(idDescriptor===MISSING_OWN_DATA_DESCRIPTOR||idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||labelDescriptor===MISSING_OWN_DATA_DESCRIPTOR||labelDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof idDescriptor.value!="string"||typeof labelDescriptor.value!="string")continue;const id=idDescriptor.value,label=labelDescriptor.value;id.trim().length===0||seen.has(id)||(seen.add(id),reasons.push(Object.freeze({id,label})))}return Object.freeze({reasons:Object.freeze(reasons),commentable})}class LyraMessageFeedback extends LyraElement{constructor(){super(...arguments),this.rating=null,this.detailFor="down",this.disabled=!1,this.pending=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.panelOpen=!1,this.selectedReasonIds=[],this.commentDraft="",this.detailProjectionSource=Symbol("unprojected-feedback-detail"),this.detailProjection=EMPTY_FEEDBACK_DETAIL_PROJECTION,this.submissionSequence=0,this.submissionCount=0,this.legacyNoArgumentSettlementInvalidated=!1,this.lifecycleGeneration=0,this.focusGeneration=0,this.settingPending=!1,this.panelId=nextId("message-feedback-panel"),this.upToolbarAction=this.createToolbarAction("up"),this.downToolbarAction=this.createToolbarAction("down"),this.onPanelKeyDown=e=>{e.key==="Escape"&&(e.stopPropagation(),this.closePanel())},this.stopChipAliasEvent=event=>{event.stopPropagation()},this.onCommentInput=e=>{this.commentDraft=e.target.value},this.onCommentFocus=event=>{relayNativeEvent(this,event)},this.onCommentBlur=event=>{relayNativeEvent(this,event)},this.submissionRequestDispatching=!1,this.onSubmit=()=>{if(this.disabled||this.pending||!this.rating||!this.panelOpen)return;const validReasonIds=new Set(this.detailReasons.map(reason=>reason.id));this.requestSubmission({rating:this.rating,reasonIds:this.selectedReasonIds.filter(id=>validReasonIds.has(id)),comment:this.detailCommentable?this.commentDraft.trim():""},this.rating,!0)}}static{this.defaultStrings={...super.defaultStrings,feedbackCommentLabel:LYRA_DEFAULT_feedbackCommentLabel,feedbackCommentPlaceholder:LYRA_DEFAULT_feedbackCommentPlaceholder,feedbackNegative:LYRA_DEFAULT_feedbackNegative,feedbackPositive:LYRA_DEFAULT_feedbackPositive,feedbackReasonsLabel:LYRA_DEFAULT_feedbackReasonsLabel,feedbackSubmit:LYRA_DEFAULT_feedbackSubmit,feedbackSubmitted:LYRA_DEFAULT_feedbackSubmitted}}emitFeedbackSubmitRequest(detail){return this.emit("lr-feedback-submit-request",Object.freeze(detail),{cancelable:!0})}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["detail"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-feedback-submit-request"])}get autocorrect(){return this.autocorrectValue}set autocorrect(next){const previous=this.autocorrectValue;this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate("autocorrect",previous)}createToolbarAction(direction){const host=this,button=()=>direction==="up"?host.upButtonEl:host.downButtonEl,tabIndexLease=leaseTabIndex();return{id:direction,get disabled(){return!button()||button().disabled},focus(options){button()?.focus(options)},setTabIndex(tabIndex){tabIndexLease.set(button(),tabIndex)},releaseTabIndex:()=>tabIndexLease.release(),matchesEventPath(path){const target=button();return target!==void 0&&path.includes(target)}}}getToolbarActions(){return[this.upToolbarAction,this.downToolbarAction]}focus(options){(this.rating==="down"?this.downButtonEl:this.upButtonEl)?.focus(options)}blur(){this.upButtonEl?.blur(),this.downButtonEl?.blur()}click(){this.disabled||this.pending||(this.rating==="down"?this.downButtonEl:this.upButtonEl)?.click()}get detailReasons(){return this.currentDetailProjection.reasons}get detailCommentable(){return this.currentDetailProjection.commentable}get currentDetailProjection(){const detail=this.detail;return detail!==this.detailProjectionSource&&(this.detailProjectionSource=detail,this.detailProjection=projectFeedbackDetail(detail)),this.detailProjection}get hasDetailContent(){return this.detailReasons.length>0||this.detailCommentable}detailApplies(direction){return this.detailFor==="both"||this.detailFor===direction}requestUpdate(name,oldValue,options){const currentValue=name==="rating"?this.rating:name==="detail"?this.detail:name==="detailFor"?this.detailFor:name==="pending"?this.pending:void 0,changed=oldValue!==currentValue,internalRatingWrite=name==="rating"&&this.pendingInternalRating?.rating===this.rating;changed&&(name==="rating"||name==="detail"||name==="detailFor"||name==="pending")&&!(name==="rating"&&internalRatingWrite)&&(this.focusGeneration=(this.focusGeneration??0)+1,this.pendingSubmission&&(name!=="pending"||!this.settingPending&&this.pending===!1)&&this.invalidatePendingSubmission()),super.requestUpdate(name,oldValue,options)}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.sink?.release(),this.sink=void 0,this.lifecycleGeneration+=1,this.invalidatePendingSubmission(),this.upToolbarAction.releaseTabIndex?.(),this.downToolbarAction.releaseTabIndex?.(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.lifecycleGeneration+=1,this.invalidatePendingSubmission(),this.upToolbarAction.releaseTabIndex?.(),this.downToolbarAction.releaseTabIndex?.()}willUpdate(changed){if(super.willUpdate(changed),changed.has("rating")){const internal=this.pendingInternalRating?.rating===this.rating;this.pendingInternalRating=void 0,internal||(this.invalidatePendingSubmission(),this.setPending(!1),this.panelOpen=!1,this.selectedReasonIds=[],this.commentDraft="")}if(changed.has("detail")){const validIds=new Set(this.detailReasons.map(reason=>reason.id));this.selectedReasonIds=this.selectedReasonIds.filter(id=>validIds.has(id)),this.detailCommentable||(this.commentDraft="")}this.panelOpen&&(!this.rating||!this.detailApplies(this.rating)||!this.hasDetailContent)&&(this.invalidatePendingSubmission(),this.setPending(!1),this.panelOpen=!1,changed.has("detailFor")&&(this.selectedReasonIds=[],this.commentDraft=""))}updated(changed){super.updated(changed),(changed.has("disabled")||changed.has("pending"))&&this.emit("lr-toolbar-actions-change")}setRatingFromInteraction(rating){this.pendingInternalRating={rating},this.rating=rating}activateThumb(next){if(this.disabled||this.pending)return;const previousRating=this.rating;if(this.rating===next){if(this.panelOpen){this.setRatingFromInteraction(null),this.panelOpen=!1,this.selectedReasonIds=[],this.commentDraft="",this.emit("lr-feedback-change",{rating:null}),this.requestSubmission({rating:null,reasonIds:[],comment:""},previousRating,!0);return}if(this.detailApplies(next)&&this.hasDetailContent){this.panelOpen=!0;return}this.setRatingFromInteraction(null),this.emit("lr-feedback-change",{rating:null}),this.requestSubmission({rating:null,reasonIds:[],comment:""},previousRating,!1);return}this.selectedReasonIds=[],this.commentDraft="",this.setRatingFromInteraction(next),this.panelOpen=this.detailApplies(next)&&this.hasDetailContent,this.emit("lr-feedback-change",{rating:next}),this.panelOpen||this.requestSubmission({rating:next,reasonIds:[],comment:""},previousRating,!1)}focusActiveThumb(){(this.rating==="down"?this.downButtonEl:this.upButtonEl)?.focus()}closePanel(){this.panelOpen&&(this.panelOpen=!1,this.focusActiveThumb())}toggleReason(id){this.disabled||this.pending||(this.selectedReasonIds=this.selectedReasonIds.includes(id)?this.selectedReasonIds.filter(r=>r!==id):[...this.selectedReasonIds,id])}setPending(pending){this.settingPending=!0,this.pending=pending,this.settingPending=!1}invalidatePendingSubmission(){const transaction=this.pendingSubmission;transaction&&(this.pendingSubmission=void 0,this.dispatchingSubmission===transaction&&(this.dispatchingSubmission=void 0),this.legacyNoArgumentSettlementInvalidated=!0,this.focusGeneration+=1,this.setPending(!1))}isCurrentPendingSubmission(transaction){return this.pendingSubmission===transaction&&this.pending&&this.isConnected&&transaction.lifecycleGeneration===this.lifecycleGeneration&&transaction.rating===this.rating&&transaction.detail===this.detail&&transaction.detailFor===this.detailFor?!0:(this.pendingSubmission===transaction&&this.invalidatePendingSubmission(),!1)}canSettleWithoutSubmissionId(transaction){return!this.legacyNoArgumentSettlementInvalidated&&this.submissionCount===1&&transaction.sequence===1}scheduleSettlementFocus(transaction,destination){const focusGeneration=++this.focusGeneration,lifecycleGeneration=transaction.lifecycleGeneration;this.ownsSettlementFocus()&&this.updateComplete.then(()=>{focusGeneration!==this.focusGeneration||lifecycleGeneration!==this.lifecycleGeneration||!this.isConnected||this.pending||this.pendingSubmission||!this.ownsSettlementFocus()||(destination==="submit"&&this.panelOpen?this.submitButtonEl?.focus():this.focusActiveThumb())})}ownsSettlementFocus(){const doc=this.ownerDocument,active=deepActiveElementIn(doc);return active===null||active===doc.body||active===doc.documentElement||composedContains(this,active)}settlePendingSubmission(settlement,submissionId){const transaction=this.pendingSubmission;if(!transaction||!this.isCurrentPendingSubmission(transaction))return!1;if(submissionId===void 0){if(!this.canSettleWithoutSubmissionId(transaction))return!1}else if(submissionId!==transaction.submissionId)return!1;return transaction.settlement?!1:this.dispatchingSubmission===transaction?(transaction.settlement=settlement,!0):(this.commitSettlement(transaction,settlement),!0)}commitSettlement(transaction,settlement){if(this.isCurrentPendingSubmission(transaction)){if(this.pendingSubmission=void 0,this.dispatchingSubmission===transaction&&(this.dispatchingSubmission=void 0),this.setPending(!1),settlement==="finalize"){this.panelOpen=!1,this.sink?.announce(this.localize("feedbackSubmitted")),this.scheduleSettlementFocus(transaction,"thumb");return}this.setRatingFromInteraction(transaction.previousRating),this.panelOpen=transaction.panelWasOpen,this.scheduleSettlementFocus(transaction,transaction.panelWasOpen?"submit":"thumb")}}finalizePendingSubmit(submissionId){return this.settlePendingSubmission("finalize",submissionId)}revertPendingSubmit(submissionId){return this.settlePendingSubmission("revert",submissionId)}requestSubmission(detail,previousRating,panelWasOpen){if(!this.submissionRequestDispatching){this.submissionRequestDispatching=!0;try{this.focusGeneration+=1;const sequence=++this.submissionSequence;this.submissionCount+=1;const transaction={submissionId:nextId("message-feedback-submission"),sequence,lifecycleGeneration:this.lifecycleGeneration,rating:this.rating,detail:this.detail,detailFor:this.detailFor,previousRating,panelWasOpen};this.pendingSubmission=transaction,this.setPending(!0),this.dispatchingSubmission=transaction;const event=this.emitFeedbackSubmitRequest({...detail,submissionId:transaction.submissionId});if(this.dispatchingSubmission===transaction&&(this.dispatchingSubmission=void 0),!this.isCurrentPendingSubmission(transaction))return;if(transaction.settlement){this.commitSettlement(transaction,transaction.settlement);return}event.defaultPrevented||this.commitSettlement(transaction,"finalize")}finally{this.submissionRequestDispatching=!1}}}renderThumb(direction){const pressed=this.rating===direction,canExpand=this.detailApplies(direction)&&this.hasDetailContent;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{thumbIcon}from"../../../internal/icons.js";import{nextId}from"../../../internal/a11y.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{composedContains}from"../../../internal/overlay-stack.js";import{getOwnDataDescriptor,isObjectValue,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{autocorrectConverter,declaredDefaultConverter,normalizeAutocorrect,omittedEmptyStringConverter,trueDefaultSpellcheckConverter}from"../../../internal/converters.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./message-feedback.styles.js";import{leaseTabIndex}from"../../../internal/roving-toolbar.js";import{LYRA_DEFAULT_feedbackCommentLabel,LYRA_DEFAULT_feedbackCommentPlaceholder,LYRA_DEFAULT_feedbackNegative,LYRA_DEFAULT_feedbackPositive,LYRA_DEFAULT_feedbackReasonsLabel,LYRA_DEFAULT_feedbackSubmit,LYRA_DEFAULT_feedbackSubmitted}from"../../../internal/default-strings/conversation.generated.js";const MAX_PROJECTED_FEEDBACK_REASONS=1e4,EMPTY_FEEDBACK_DETAIL_PROJECTION=Object.freeze({reasons:Object.freeze([]),commentable:!1});function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function projectFeedbackDetail(detail){if(!isObjectValue(detail))return EMPTY_FEEDBACK_DETAIL_PROJECTION;const reasonsDescriptor=getOwnDataDescriptor(detail,"reasons"),commentableDescriptor=getOwnDataDescriptor(detail,"commentable"),commentable=commentableDescriptor!==MISSING_OWN_DATA_DESCRIPTOR&&commentableDescriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&commentableDescriptor.value===!0,reasonsValue=reasonsDescriptor!==MISSING_OWN_DATA_DESCRIPTOR&&reasonsDescriptor!==UNSAFE_OWN_DATA_DESCRIPTOR?reasonsDescriptor.value:void 0;if(!isArrayValue(reasonsValue))return commentable?Object.freeze({reasons:Object.freeze([]),commentable}):EMPTY_FEEDBACK_DETAIL_PROJECTION;const lengthDescriptor=getOwnDataDescriptor(reasonsValue,"length");if(lengthDescriptor===MISSING_OWN_DATA_DESCRIPTOR||lengthDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return commentable?Object.freeze({reasons:Object.freeze([]),commentable}):EMPTY_FEEDBACK_DETAIL_PROJECTION;const reasons=[],seen=new Set,length=Math.min(lengthDescriptor.value,MAX_PROJECTED_FEEDBACK_REASONS);for(let index=0;index<length;index+=1){const rowDescriptor=getOwnDataDescriptor(reasonsValue,String(index));if(rowDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rowDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!isObjectValue(rowDescriptor.value))continue;const row=rowDescriptor.value,idDescriptor=getOwnDataDescriptor(row,"id"),labelDescriptor=getOwnDataDescriptor(row,"label");if(idDescriptor===MISSING_OWN_DATA_DESCRIPTOR||idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||labelDescriptor===MISSING_OWN_DATA_DESCRIPTOR||labelDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof idDescriptor.value!="string"||typeof labelDescriptor.value!="string")continue;const id=idDescriptor.value,label=labelDescriptor.value;id.trim().length===0||seen.has(id)||(seen.add(id),reasons.push(Object.freeze({id,label})))}return Object.freeze({reasons:Object.freeze(reasons),commentable})}class LyraMessageFeedback extends LyraElement{constructor(){super(...arguments),this.rating=null,this.detailFor="down",this.disabled=!1,this.pending=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.panelOpen=!1,this.selectedReasonIds=[],this.commentDraft="",this.detailProjectionSource=Symbol("unprojected-feedback-detail"),this.detailProjection=EMPTY_FEEDBACK_DETAIL_PROJECTION,this.submissionSequence=0,this.submissionCount=0,this.legacyNoArgumentSettlementInvalidated=!1,this.lifecycleGeneration=0,this.focusGeneration=0,this.settingPending=!1,this.panelId=nextId("message-feedback-panel"),this.upToolbarAction=this.createToolbarAction("up"),this.downToolbarAction=this.createToolbarAction("down"),this.onPanelKeyDown=e=>{e.key==="Escape"&&(e.stopPropagation(),this.closePanel())},this.stopChipAliasEvent=event=>{event.stopPropagation()},this.onCommentInput=e=>{this.commentDraft=e.target.value},this.onCommentFocus=event=>{relayNativeEvent(this,event)},this.onCommentBlur=event=>{relayNativeEvent(this,event)},this.submissionRequestDispatching=!1,this.onSubmit=()=>{if(this.disabled||this.pending||!this.rating||!this.panelOpen)return;const validReasonIds=new Set(this.detailReasons.map(reason=>reason.id));this.requestSubmission({rating:this.rating,reasonIds:this.selectedReasonIds.filter(id=>validReasonIds.has(id)),comment:this.detailCommentable?this.commentDraft.trim():""},this.rating,!0)}}static{this.defaultStrings={...super.defaultStrings,feedbackCommentLabel:LYRA_DEFAULT_feedbackCommentLabel,feedbackCommentPlaceholder:LYRA_DEFAULT_feedbackCommentPlaceholder,feedbackNegative:LYRA_DEFAULT_feedbackNegative,feedbackPositive:LYRA_DEFAULT_feedbackPositive,feedbackReasonsLabel:LYRA_DEFAULT_feedbackReasonsLabel,feedbackSubmit:LYRA_DEFAULT_feedbackSubmit,feedbackSubmitted:LYRA_DEFAULT_feedbackSubmitted}}emitFeedbackSubmitRequest(detail){return this.emit("lr-feedback-submit-request",Object.freeze(detail),{cancelable:!0})}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["detail"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-feedback-submit-request"])}get autocorrect(){return this.autocorrectValue}set autocorrect(next){const previous=this.autocorrectValue;this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate("autocorrect",previous)}createToolbarAction(direction){const host=this,button=()=>direction==="up"?host.upButtonEl:host.downButtonEl,tabIndexLease=leaseTabIndex();return{id:direction,get disabled(){return!button()||button().disabled},focus(options){button()?.focus(options)},setTabIndex(tabIndex){tabIndexLease.set(button(),tabIndex)},releaseTabIndex:()=>tabIndexLease.release(),matchesEventPath(path){const target=button();return target!==void 0&&path.includes(target)}}}getToolbarActions(){return[this.upToolbarAction,this.downToolbarAction]}focus(options){(this.rating==="down"?this.downButtonEl:this.upButtonEl)?.focus(options)}blur(){this.upButtonEl?.blur(),this.downButtonEl?.blur()}click(){this.disabled||this.pending||(this.rating==="down"?this.downButtonEl:this.upButtonEl)?.click()}get detailReasons(){return this.currentDetailProjection.reasons}get detailCommentable(){return this.currentDetailProjection.commentable}get currentDetailProjection(){const detail=this.detail;return detail!==this.detailProjectionSource&&(this.detailProjectionSource=detail,this.detailProjection=projectFeedbackDetail(detail)),this.detailProjection}get hasDetailContent(){return this.detailReasons.length>0||this.detailCommentable}detailApplies(direction){return this.detailFor==="both"||this.detailFor===direction}requestUpdate(name,oldValue,options){const currentValue=name==="rating"?this.rating:name==="detail"?this.detail:name==="detailFor"?this.detailFor:name==="pending"?this.pending:void 0,changed=oldValue!==currentValue,internalRatingWrite=name==="rating"&&this.pendingInternalRating?.rating===this.rating;changed&&(name==="rating"||name==="detail"||name==="detailFor"||name==="pending")&&!(name==="rating"&&internalRatingWrite)&&(this.focusGeneration=(this.focusGeneration??0)+1,this.pendingSubmission&&(name!=="pending"||!this.settingPending&&this.pending===!1)&&this.invalidatePendingSubmission()),super.requestUpdate(name,oldValue,options)}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.sink?.release(),this.sink=void 0,this.lifecycleGeneration+=1,this.invalidatePendingSubmission(),this.upToolbarAction.releaseTabIndex?.(),this.downToolbarAction.releaseTabIndex?.(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.lifecycleGeneration+=1,this.invalidatePendingSubmission(),this.upToolbarAction.releaseTabIndex?.(),this.downToolbarAction.releaseTabIndex?.()}willUpdate(changed){if(super.willUpdate(changed),changed.has("rating")){const internal=this.pendingInternalRating?.rating===this.rating;this.pendingInternalRating=void 0,internal||(this.invalidatePendingSubmission(),this.setPending(!1),this.panelOpen=!1,this.selectedReasonIds=[],this.commentDraft="")}if(changed.has("detail")){const validIds=new Set(this.detailReasons.map(reason=>reason.id));this.selectedReasonIds=this.selectedReasonIds.filter(id=>validIds.has(id)),this.detailCommentable||(this.commentDraft="")}this.panelOpen&&(!this.rating||!this.detailApplies(this.rating)||!this.hasDetailContent)&&(this.invalidatePendingSubmission(),this.setPending(!1),this.panelOpen=!1,changed.has("detailFor")&&(this.selectedReasonIds=[],this.commentDraft=""))}updated(changed){super.updated(changed),(changed.has("disabled")||changed.has("pending"))&&this.emit("lr-toolbar-actions-change")}setRatingFromInteraction(rating){this.pendingInternalRating={rating},this.rating=rating}activateThumb(next){if(this.disabled||this.pending)return;const previousRating=this.rating;if(this.rating===next){if(this.panelOpen){this.setRatingFromInteraction(null),this.panelOpen=!1,this.selectedReasonIds=[],this.commentDraft="",this.emit("lr-feedback-change",{rating:null}),this.requestSubmission({rating:null,reasonIds:[],comment:""},previousRating,!0);return}if(this.detailApplies(next)&&this.hasDetailContent){this.panelOpen=!0;return}this.setRatingFromInteraction(null),this.emit("lr-feedback-change",{rating:null}),this.requestSubmission({rating:null,reasonIds:[],comment:""},previousRating,!1);return}this.selectedReasonIds=[],this.commentDraft="",this.setRatingFromInteraction(next),this.panelOpen=this.detailApplies(next)&&this.hasDetailContent,this.emit("lr-feedback-change",{rating:next}),this.panelOpen||this.requestSubmission({rating:next,reasonIds:[],comment:""},previousRating,!1)}focusActiveThumb(){(this.rating==="down"?this.downButtonEl:this.upButtonEl)?.focus()}closePanel(){this.panelOpen&&(this.panelOpen=!1,this.focusActiveThumb())}toggleReason(id,event){if(this.disabled||this.pending||event.defaultPrevented){event.preventDefault();return}this.selectedReasonIds=this.selectedReasonIds.includes(id)?this.selectedReasonIds.filter(r=>r!==id):[...this.selectedReasonIds,id]}setPending(pending){this.settingPending=!0,this.pending=pending,this.settingPending=!1}invalidatePendingSubmission(){const transaction=this.pendingSubmission;transaction&&(this.pendingSubmission=void 0,this.dispatchingSubmission===transaction&&(this.dispatchingSubmission=void 0),this.legacyNoArgumentSettlementInvalidated=!0,this.focusGeneration+=1,this.setPending(!1))}isCurrentPendingSubmission(transaction){return this.pendingSubmission===transaction&&this.pending&&this.isConnected&&transaction.lifecycleGeneration===this.lifecycleGeneration&&transaction.rating===this.rating&&transaction.detail===this.detail&&transaction.detailFor===this.detailFor?!0:(this.pendingSubmission===transaction&&this.invalidatePendingSubmission(),!1)}canSettleWithoutSubmissionId(transaction){return!this.legacyNoArgumentSettlementInvalidated&&this.submissionCount===1&&transaction.sequence===1}scheduleSettlementFocus(transaction,destination){const focusGeneration=++this.focusGeneration,lifecycleGeneration=transaction.lifecycleGeneration;this.ownsSettlementFocus()&&this.updateComplete.then(()=>{focusGeneration!==this.focusGeneration||lifecycleGeneration!==this.lifecycleGeneration||!this.isConnected||this.pending||this.pendingSubmission||!this.ownsSettlementFocus()||(destination==="submit"&&this.panelOpen?this.submitButtonEl?.focus():this.focusActiveThumb())})}ownsSettlementFocus(){const doc=this.ownerDocument,active=deepActiveElementIn(doc);return active===null||active===doc.body||active===doc.documentElement||composedContains(this,active)}settlePendingSubmission(settlement,submissionId){const transaction=this.pendingSubmission;if(!transaction||!this.isCurrentPendingSubmission(transaction))return!1;if(submissionId===void 0){if(!this.canSettleWithoutSubmissionId(transaction))return!1}else if(submissionId!==transaction.submissionId)return!1;return transaction.settlement?!1:this.dispatchingSubmission===transaction?(transaction.settlement=settlement,!0):(this.commitSettlement(transaction,settlement),!0)}commitSettlement(transaction,settlement){if(this.isCurrentPendingSubmission(transaction)){if(this.pendingSubmission=void 0,this.dispatchingSubmission===transaction&&(this.dispatchingSubmission=void 0),this.setPending(!1),settlement==="finalize"){this.panelOpen=!1,this.sink?.announce(this.localize("feedbackSubmitted")),this.scheduleSettlementFocus(transaction,"thumb");return}this.setRatingFromInteraction(transaction.previousRating),this.panelOpen=transaction.panelWasOpen,this.scheduleSettlementFocus(transaction,transaction.panelWasOpen?"submit":"thumb")}}finalizePendingSubmit(submissionId){return this.settlePendingSubmission("finalize",submissionId)}revertPendingSubmit(submissionId){return this.settlePendingSubmission("revert",submissionId)}requestSubmission(detail,previousRating,panelWasOpen){if(!this.submissionRequestDispatching){this.submissionRequestDispatching=!0;try{this.focusGeneration+=1;const sequence=++this.submissionSequence;this.submissionCount+=1;const transaction={submissionId:nextId("message-feedback-submission"),sequence,lifecycleGeneration:this.lifecycleGeneration,rating:this.rating,detail:this.detail,detailFor:this.detailFor,previousRating,panelWasOpen};this.pendingSubmission=transaction,this.setPending(!0),this.dispatchingSubmission=transaction;const event=this.emitFeedbackSubmitRequest({...detail,submissionId:transaction.submissionId});if(this.dispatchingSubmission===transaction&&(this.dispatchingSubmission=void 0),!this.isCurrentPendingSubmission(transaction))return;if(transaction.settlement){this.commitSettlement(transaction,transaction.settlement);return}event.defaultPrevented||this.commitSettlement(transaction,"finalize")}finally{this.submissionRequestDispatching=!1}}}renderThumb(direction){const pressed=this.rating===direction,canExpand=this.detailApplies(direction)&&this.hasDetailContent;return html`
|
|
2
2
|
<button
|
|
3
3
|
part=${direction==="up"?"up-button":"down-button"}
|
|
4
4
|
type="button"
|
|
@@ -32,7 +32,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
|
|
|
32
32
|
toggleable
|
|
33
33
|
?selected=${selectedReasons.has(reason.id)}
|
|
34
34
|
.disabled=${this.disabled||this.pending}
|
|
35
|
-
@lr-chip-toggle-request=${event=>{event.stopPropagation(),this.toggleReason(reason.id)}}
|
|
35
|
+
@lr-chip-toggle-request=${event=>{event.stopPropagation(),this.toggleReason(reason.id,event)}}
|
|
36
36
|
@lr-chip-select=${this.stopChipAliasEvent}
|
|
37
37
|
>${reason.label}</lr-chip
|
|
38
38
|
>
|
|
@@ -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"../../../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"}
|
|
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,seenRight=new WeakSet;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}if(seenRight.has(b))return!1;seen.set(a,b),seenRight.add(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)}
|
|
@@ -85,7 +85,8 @@ submitDisabled:boolean;
|
|
|
85
85
|
withoutStop:boolean;
|
|
86
86
|
/** Forwarded to the composed composer: `'plain'` removes its border, background and padding.*/
|
|
87
87
|
frame:ChatComposerFrame;
|
|
88
|
-
/** Forwarded to the composed composer: `'stacked'` arranges `start` above `end` beside the textarea
|
|
88
|
+
/** Forwarded to the composed composer: `'stacked'` arranges `start` above `end` beside the textarea;
|
|
89
|
+
* `'below'` puts both on one row under a full-width textarea. */
|
|
89
90
|
actionsLayout:ChatComposerActionsLayout;minRows:number;maxRows:number;
|
|
90
91
|
/** Forwarded to the composed native textarea. `spellcheck="false"` parses as `false`, matching
|
|
91
92
|
* the textarea's true default while remaining usable from plain HTML. */
|
|
@@ -60,6 +60,10 @@ withoutImages:boolean;
|
|
|
60
60
|
* `link-target=""` attribute) to omit `target`/`rel` entirely so rendered links open in the
|
|
61
61
|
* same tab. */
|
|
62
62
|
linkTarget:string|null;
|
|
63
|
+
/** Forwarded verbatim to the composed Markdown element's own `linkSchemes` -- narrows which link
|
|
64
|
+
* destinations may become anchors (for example `link-schemes="https"`); a refused link renders
|
|
65
|
+
* as plain text. Unset keeps the standard allowlist. */
|
|
66
|
+
linkSchemes?:string;
|
|
63
67
|
/** Forwarded verbatim to the composed Markdown element's own `internalLinkPrefix`. Empty (the
|
|
64
68
|
* default) matches the composed element's own default -- every link is treated as external. */
|
|
65
69
|
internalLinkPrefix:string;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
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({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};
|
|
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:"link-schemes"})],StreamingTextRuntimeBase.prototype,"linkSchemes",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};
|
|
@@ -9,7 +9,7 @@ export interface LyraStreamingTextCoreEventMap extends StreamingTextRuntimeEvent
|
|
|
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
11
|
* and the full forwarded Markdown configuration surface (`tabSize`, `htmlMode`, `withoutGfm`, `withoutImages`,
|
|
12
|
-
* `linkTarget`, `internalLinkPrefix`, `headingOffset`, `withoutSyntaxHighlighting`, `headingAnchors`, `math`,
|
|
12
|
+
* `linkTarget`, `linkSchemes`, `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
|
|
15
15
|
* component's own module never textually contains a reference to `<lr-markdown>`'s ~200-language
|
|
@@ -10,6 +10,7 @@ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/dec
|
|
|
10
10
|
.withoutGfm=${this.withoutGfm}
|
|
11
11
|
.withoutImages=${this.withoutImages}
|
|
12
12
|
.linkTarget=${this.linkTarget}
|
|
13
|
+
.linkSchemes=${this.linkSchemes}
|
|
13
14
|
.internalLinkPrefix=${this.internalLinkPrefix}
|
|
14
15
|
.headingOffset=${this.headingOffset}
|
|
15
16
|
.withoutSyntaxHighlighting=${this.withoutSyntaxHighlighting}
|
|
@@ -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`, `withoutImages`, `linkTarget`, `internalLinkPrefix`,
|
|
44
|
+
* `tabSize`, `htmlMode`, `withoutGfm`, `withoutImages`, `linkTarget`, `linkSchemes`, `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
|
|
@@ -11,6 +11,7 @@ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/dec
|
|
|
11
11
|
.withoutGfm=${this.withoutGfm}
|
|
12
12
|
.withoutImages=${this.withoutImages}
|
|
13
13
|
.linkTarget=${this.linkTarget}
|
|
14
|
+
.linkSchemes=${this.linkSchemes}
|
|
14
15
|
.internalLinkPrefix=${this.internalLinkPrefix}
|
|
15
16
|
.headingOffset=${this.headingOffset}
|
|
16
17
|
.withoutSyntaxHighlighting=${this.withoutSyntaxHighlighting}
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';export interface LyraChatSuggestion{suggestionId:string;
|
|
2
2
|
/** Nonblank text used as the chip button's visible and accessible name.*/
|
|
3
3
|
label:string;
|
|
4
|
-
/** Optional literal icon hint (for example, an emoji). Rendered decoratively before the text
|
|
4
|
+
/** Optional literal icon hint (for example, an emoji). Rendered decoratively before the text, as
|
|
5
|
+
* text: markup in it is shown verbatim, never parsed. `iconName` and a slotted icon win over it. */
|
|
5
6
|
icon?:string;
|
|
7
|
+
/** Optional `<lr-icon>` name rendered decoratively before the text, for a vector icon instead of
|
|
8
|
+
* literal text. Wins over `icon`; a slotted `icon-<suggestionId>` element wins over both. */
|
|
9
|
+
iconName?:string;
|
|
10
|
+
/** Optional registered `<lr-icon>` library resolving `iconName`. Omitted uses the default set.*/
|
|
11
|
+
iconLibrary?:string;
|
|
6
12
|
/** An optional secondary line (Perplexity-style related questions).*/
|
|
7
13
|
detail?:string;
|
|
8
14
|
/**
|
|
@@ -30,13 +36,21 @@ disabled?:boolean;}export interface LyraSuggestionChipsEventMap{'lr-suggestion-s
|
|
|
30
36
|
* past it instead of landing on it. Omitted or `false` renders the chip exactly as before this
|
|
31
37
|
* field existed.
|
|
32
38
|
*
|
|
39
|
+
* Each chip can show a decorative icon before its text, in increasing precedence: `icon` (literal
|
|
40
|
+
* text such as an emoji), `iconName` (+ optional `iconLibrary`, rendered as an `<lr-icon>`), or a
|
|
41
|
+
* light-DOM element assigned to the per-suggestion `icon-<suggestionId>` slot, such as an inline
|
|
42
|
+
* `<svg>` or `<lr-icon>`. Icons are always hidden from assistive technology; the chip's accessible
|
|
43
|
+
* name stays its `label`. No icon field is ever parsed as markup.
|
|
44
|
+
*
|
|
33
45
|
* @customElement lr-suggestion-chips
|
|
34
46
|
* @event lr-suggestion-select - `detail: { suggestionId, label }`.
|
|
47
|
+
* @slot icon-<suggestionId> - Decorative icon for the suggestion with that `suggestionId` (for
|
|
48
|
+
* example `slot="icon-a"` for `suggestionId: 'a'`); replaces its `iconName`/`icon`.
|
|
35
49
|
* @csspart base - The labeled group.
|
|
36
50
|
* @csspart row - The flex container holding the chips, in both the wrapping and the scrolling
|
|
37
51
|
* layout. Style this to change how chip lines pack (`justify-content`, `row-gap`).
|
|
38
52
|
* @csspart chip - Each suggestion button.
|
|
39
|
-
* @csspart chip-icon - Optional decorative literal icon.
|
|
53
|
+
* @csspart chip-icon - Optional decorative icon wrapper (literal `icon`, `iconName` icon or slotted icon).
|
|
40
54
|
* @csspart chip-label - The primary text.
|
|
41
55
|
* @csspart chip-detail - The secondary line (only rendered when `detail` is set).
|
|
42
56
|
* @cssprop [--lr-suggestion-chips-justify=flex-start] - Main-axis packing of the chip row. `center`
|
|
@@ -62,4 +76,4 @@ suggestions:readonly LyraChatSuggestion[];
|
|
|
62
76
|
wrap:boolean;
|
|
63
77
|
/** Accessible name for the group. Optional. Omitting it localizes the default `suggestionsLabel`
|
|
64
78
|
* message; an explicit empty string renders no visible/accessible label. */
|
|
65
|
-
label?:string;private activeIndex;private readonly rovingToolbar;private pendingFocus?;private focusRepairGeneration;private normalizeSuggestions;private get effectiveSuggestions();disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private restorePendingFocus;private select;private chipButtons;private focusChip;private onChipFocus;private isSuggestionDisabled;private effectiveActiveIndex;private stopEvent;private onKeyDown;private renderChip;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-suggestion-chips':LyraSuggestionChips;}}
|
|
79
|
+
label?:string;private activeIndex;private readonly rovingToolbar;private readonly slots;private pendingFocus?;private focusRepairGeneration;private normalizeSuggestions;private get effectiveSuggestions();disconnectedCallback():void;adoptedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private restorePendingFocus;private select;private chipButtons;private focusChip;private onChipFocus;private isSuggestionDisabled;private effectiveActiveIndex;private stopEvent;private onKeyDown;private renderChip;private renderChipIcon;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-suggestion-chips':LyraSuggestionChips;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{styles}from"./suggestion-chips.styles.js";import{applyComposedFocusRepair,captureComposedFocusRepair}from"../../../internal/focus-navigation.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{RovingToolbarController}from"../../../internal/roving-toolbar.js";import{LYRA_DEFAULT_suggestionsLabel}from"../../../internal/default-strings/conversation.generated.js";class LyraSuggestionChips extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="group"]')),this.suggestions=[],this.wrap=!1,this.activeIndex=0,this.rovingToolbar=new RovingToolbarController,this.focusRepairGeneration=0,this.stopEvent=e=>e.stopPropagation(),this.onKeyDown=e=>{const suggestions=this.effectiveSuggestions,target=this.rovingToolbar.move(e,suggestions.length,this.activeIndex,this.effectiveDirection,index=>!this.isSuggestionDisabled(suggestions[index]));if(target===null){(e.key==="ArrowLeft"||e.key==="ArrowRight"||e.key==="Home"||e.key==="End")&&suggestions.length>0&&suggestions.every(item=>this.isSuggestionDisabled(item))&&e.preventDefault();return}e.preventDefault(),this.activeIndex=target,this.focusChip(target)}}static{this.defaultStrings={...super.defaultStrings,suggestionsLabel:LYRA_DEFAULT_suggestionsLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["suggestions"])}static{this.styles=[LyraElement.styles,styles]}normalizeSuggestions(items){const seen=new Set,normalized=[];for(const suggestion of items??[]){let suggestionId,label;try{suggestionId=suggestion?.suggestionId,label=suggestion?.label}catch{continue}typeof suggestionId!="string"||suggestionId.trim()===""||typeof label!="string"||label.trim()===""||seen.has(suggestionId)||(seen.add(suggestionId),normalized.push(suggestion))}return normalized}get effectiveSuggestions(){return this.normalizeSuggestions(this.suggestions)}disconnectedCallback(){this.focusRepairGeneration++,this.pendingFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.focusRepairGeneration++,this.pendingFocus=void 0}willUpdate(changed){if(super.willUpdate(changed),changed.has("suggestions")||changed.has("wrap")){const active=deepActiveElementIn(this.ownerDocument),activeElement=active?.nodeType===1&&"dataset"in active?active:null,suggestionId=activeElement?.dataset.suggestionId,repair=activeElement?captureComposedFocusRepair(this,activeElement):null,generation=++this.focusRepairGeneration;this.pendingFocus=suggestionId&&repair?{suggestionId,index:this.activeIndex,repair,generation}:void 0}if(changed.has("suggestions")){const previous=this.normalizeSuggestions(changed.get("suggestions")),current=this.effectiveSuggestions,activeId=this.pendingFocus?.suggestionId??previous[this.activeIndex]?.suggestionId,remapped=activeId?current.findIndex(suggestion=>suggestion.suggestionId===activeId):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(0,current.length-1))}}updated(changed){super.updated(changed);const pending=this.pendingFocus;this.pendingFocus=void 0,pending&&this.restorePendingFocus(pending)}async restorePendingFocus(pending){if(await this.renderRoot.querySelector(tag("scroller"))?.updateComplete,await Promise.resolve(),pending.generation!==this.focusRepairGeneration||!this.isConnected)return;const buttons=this.chipButtons(),target=buttons.find(button=>button.dataset.suggestionId===pending.suggestionId)??buttons[Math.min(pending.index,Math.max(0,buttons.length-1))]??null;applyComposedFocusRepair(pending.repair,target)}select(suggestion){suggestion.disabled||this.emit("lr-suggestion-select",{suggestionId:suggestion.suggestionId,label:suggestion.label})}chipButtons(){return[...this.renderRoot.querySelectorAll('[part~="chip"]')]}focusChip(index){this.chipButtons()[index]?.focus()}onChipFocus(index){this.activeIndex=index}isSuggestionDisabled(suggestion){return suggestion?.disabled===!0}effectiveActiveIndex(suggestions){const count=suggestions.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!this.isSuggestionDisabled(suggestions[clamped]))return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!this.isSuggestionDisabled(suggestions[forward]))return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!this.isSuggestionDisabled(suggestions[backward]))return backward;return-1}renderChip(suggestion,index,activeIndex){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{styles}from"./suggestion-chips.styles.js";import{applyComposedFocusRepair,captureComposedFocusRepair}from"../../../internal/focus-navigation.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{RovingToolbarController}from"../../../internal/roving-toolbar.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{ifDefined}from"lit/directives/if-defined.js";import{LYRA_DEFAULT_suggestionsLabel}from"../../../internal/default-strings/conversation.generated.js";class LyraSuggestionChips extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="group"]')),this.suggestions=[],this.wrap=!1,this.activeIndex=0,this.rovingToolbar=new RovingToolbarController,this.slots=new SlotPresenceController(this,{observeLightDom:!0}),this.focusRepairGeneration=0,this.stopEvent=e=>e.stopPropagation(),this.onKeyDown=e=>{const suggestions=this.effectiveSuggestions,target=this.rovingToolbar.move(e,suggestions.length,this.activeIndex,this.effectiveDirection,index=>!this.isSuggestionDisabled(suggestions[index]));if(target===null){(e.key==="ArrowLeft"||e.key==="ArrowRight"||e.key==="Home"||e.key==="End")&&suggestions.length>0&&suggestions.every(item=>this.isSuggestionDisabled(item))&&e.preventDefault();return}e.preventDefault(),this.activeIndex=target,this.focusChip(target)}}static{this.defaultStrings={...super.defaultStrings,suggestionsLabel:LYRA_DEFAULT_suggestionsLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["suggestions"])}static{this.styles=[LyraElement.styles,styles]}normalizeSuggestions(items){const seen=new Set,normalized=[];for(const suggestion of items??[]){let suggestionId,label;try{suggestionId=suggestion?.suggestionId,label=suggestion?.label}catch{continue}typeof suggestionId!="string"||suggestionId.trim()===""||typeof label!="string"||label.trim()===""||seen.has(suggestionId)||(seen.add(suggestionId),normalized.push(suggestion))}return normalized}get effectiveSuggestions(){return this.normalizeSuggestions(this.suggestions)}disconnectedCallback(){this.focusRepairGeneration++,this.pendingFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.focusRepairGeneration++,this.pendingFocus=void 0}willUpdate(changed){if(super.willUpdate(changed),changed.has("suggestions")||changed.has("wrap")){const active=deepActiveElementIn(this.ownerDocument),activeElement=active?.nodeType===1&&"dataset"in active?active:null,suggestionId=activeElement?.dataset.suggestionId,repair=activeElement?captureComposedFocusRepair(this,activeElement):null,generation=++this.focusRepairGeneration;this.pendingFocus=suggestionId&&repair?{suggestionId,index:this.activeIndex,repair,generation}:void 0}if(changed.has("suggestions")){const previous=this.normalizeSuggestions(changed.get("suggestions")),current=this.effectiveSuggestions,activeId=this.pendingFocus?.suggestionId??previous[this.activeIndex]?.suggestionId,remapped=activeId?current.findIndex(suggestion=>suggestion.suggestionId===activeId):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(0,current.length-1))}}updated(changed){super.updated(changed);const pending=this.pendingFocus;this.pendingFocus=void 0,pending&&this.restorePendingFocus(pending)}async restorePendingFocus(pending){if(await this.renderRoot.querySelector(tag("scroller"))?.updateComplete,await Promise.resolve(),pending.generation!==this.focusRepairGeneration||!this.isConnected)return;const buttons=this.chipButtons(),target=buttons.find(button=>button.dataset.suggestionId===pending.suggestionId)??buttons[Math.min(pending.index,Math.max(0,buttons.length-1))]??null;applyComposedFocusRepair(pending.repair,target)}select(suggestion){suggestion.disabled||this.emit("lr-suggestion-select",{suggestionId:suggestion.suggestionId,label:suggestion.label})}chipButtons(){return[...this.renderRoot.querySelectorAll('[part~="chip"]')]}focusChip(index){this.chipButtons()[index]?.focus()}onChipFocus(index){this.activeIndex=index}isSuggestionDisabled(suggestion){return suggestion?.disabled===!0}effectiveActiveIndex(suggestions){const count=suggestions.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!this.isSuggestionDisabled(suggestions[clamped]))return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!this.isSuggestionDisabled(suggestions[forward]))return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!this.isSuggestionDisabled(suggestions[backward]))return backward;return-1}renderChip(suggestion,index,activeIndex){return html`
|
|
2
2
|
<button
|
|
3
3
|
type="button"
|
|
4
4
|
part="chip"
|
|
@@ -8,13 +8,13 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
8
8
|
@click=${()=>this.select(suggestion)}
|
|
9
9
|
@focus=${()=>this.onChipFocus(index)}
|
|
10
10
|
>
|
|
11
|
-
${
|
|
11
|
+
${this.renderChipIcon(suggestion)}
|
|
12
12
|
<span class="content">
|
|
13
13
|
<span part="chip-label">${suggestion.label}</span>
|
|
14
14
|
${suggestion.detail?html`<span part="chip-detail">${suggestion.detail}</span>`:nothing}
|
|
15
15
|
</span>
|
|
16
16
|
</button>
|
|
17
|
-
`}render(){const suggestions=this.effectiveSuggestions;if(suggestions.length===0)return html``;const label=this.label==null?this.localize("suggestionsLabel"):this.label,ariaLabel=this.getAttribute("aria-label")??label,activeIndex=this.effectiveActiveIndex(suggestions),chips=repeat(suggestions,s=>s.suggestionId,(s,i)=>this.renderChip(s,i,activeIndex));return html`
|
|
17
|
+
`}renderChipIcon(suggestion){const slotName=`icon-${suggestion.suggestionId}`,iconName=typeof suggestion.iconName=="string"&&suggestion.iconName.trim()!==""?suggestion.iconName:void 0,literal=typeof suggestion.icon=="string"&&suggestion.icon!==""?suggestion.icon:void 0;if(!this.slots.has(slotName)&&!iconName&&!literal)return nothing;const fallback=iconName?html`<lr-icon name=${iconName} library=${ifDefined(suggestion.iconLibrary||void 0)}></lr-icon>`:literal??nothing;return html`<span part="chip-icon" aria-hidden="true"><slot name=${slotName}>${fallback}</slot></span>`}render(){const suggestions=this.effectiveSuggestions;if(suggestions.length===0)return html``;const label=this.label==null?this.localize("suggestionsLabel"):this.label,ariaLabel=this.getAttribute("aria-label")??label,activeIndex=this.effectiveActiveIndex(suggestions),chips=repeat(suggestions,s=>s.suggestionId,(s,i)=>this.renderChip(s,i,activeIndex));return html`
|
|
18
18
|
<div part="base" role="group" aria-label=${ariaLabel} @keydown=${this.onKeyDown}>
|
|
19
19
|
${this.wrap?html`<div part="row" class="row">${chips}</div>`:html`<lr-scroller orientation="horizontal" without-scrollbar @lr-scroll=${this.stopEvent}><div part="row" class="row">${chips}</div></lr-scroller>`}
|
|
20
20
|
</div>
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** @deprecated Import @aceshooting/lyra-ui/components/lr-suggestion-chips.js to register this component.*/
|
|
2
|
-
export*from'./suggestion-chips.class.js';import'../../layout/scroller/scroller.js';
|
|
2
|
+
export*from'./suggestion-chips.class.js';import'../../layout/scroller/scroller.js';import'../../utility/icon/icon.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export*from"./suggestion-chips.class.js";import{LyraSuggestionChips}from"./suggestion-chips.class.js";import{defineElement}from"../../../internal/prefix.js";import"../../layout/scroller/scroller.js";defineElement("suggestion-chips",LyraSuggestionChips);
|
|
1
|
+
export*from"./suggestion-chips.class.js";import{LyraSuggestionChips}from"./suggestion-chips.class.js";import{defineElement}from"../../../internal/prefix.js";import"../../layout/scroller/scroller.js";import"../../utility/icon/icon.js";defineElement("suggestion-chips",LyraSuggestionChips);
|
|
@@ -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-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
|
+
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); } [part='chip-icon'] ::slotted(svg:not([width])) { inline-size: var(--lr-size-1em); block-size: var(--lr-size-1em); vertical-align: middle; } :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};
|