@aceshooting/lyra-ui 30.9.0 → 31.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +361 -335
- package/dist/ai/adapters/ag-ui.js +1 -1
- package/dist/autoloader-cdn.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
- 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 +2 -2
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +26 -11
- package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
- 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.d.ts +11 -3
- package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +8 -4
- package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -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.d.ts +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- 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/document-library/document-library-cursor.js +1 -0
- package/dist/components/data/document-library/document-library-types.d.ts +20 -0
- package/dist/components/data/document-library/document-library.class.d.ts +37 -26
- package/dist/components/data/document-library/document-library.class.js +20 -11
- package/dist/components/data/document-library/document-library.styles.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +2 -2
- 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/combobox/combobox.class.d.ts +20 -12
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- 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/dock-panel/dock-panel.class.d.ts +1 -1
- package/dist/components/layout/dock-panel/dock-panel.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/page/page.class.d.ts +3 -3
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
- package/dist/components/layout/segmented/segmented.class.js +34 -24
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.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-anchor-controller.js +1 -1
- package/dist/components/media/map/map-canvas-target.js +1 -0
- 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 +15 -6
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
- package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
- package/dist/components/media/sequence-playback/sequence-playback.styles.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/overlay.styles.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/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.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/diff-view/diff-view.class.d.ts +5 -5
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/icon/icon.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/archive-viewer/archive-viewer.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/document-preview/document-preview.class.js +2 -2
- package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
- package/dist/components/viewers/html-viewer/html-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 +2 -2
- 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/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/table-viewer-shared.js +4 -4
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
- package/dist/data-sources.d.ts +10 -0
- package/dist/events.d.ts +9 -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/default-strings/conversation.generated.js +1 -1
- package/dist/internal/default-strings/data.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.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/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/map-custom-layer-controller.js +1 -1
- package/dist/internal/media-panorama.js +1 -1
- package/dist/internal/native-modal-context.js +1 -1
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-order.js +1 -1
- package/dist/internal/overlay-stack.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/runtime-diagnostics.js +1 -0
- 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-cursor-controller.js +1 -0
- package/dist/internal/source-cursor-projection.js +1 -0
- package/dist/internal/source-page-scope.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-bootstrap.js +1 -1
- package/dist/theme/theme.js +1 -1
- package/dist/utilities/overlay-manager.d.ts +2 -0
- package/llms/components/lr-attachment-chip.md +27 -12
- package/llms/components/lr-attachment-trigger.md +27 -7
- package/llms/components/lr-budget-meter.md +31 -0
- package/llms/components/lr-button.md +6 -4
- package/llms/components/lr-chat-composer.md +26 -9
- package/llms/components/lr-chat-message.md +44 -3
- package/llms/components/lr-chat-viewport.md +39 -2
- package/llms/components/lr-combobox.md +27 -1
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-dialog.md +10 -0
- package/llms/components/lr-diff-view.md +6 -0
- package/llms/components/lr-document-library.md +90 -6
- package/llms/components/lr-drop-zone.md +26 -2
- package/llms/components/lr-graph.md +5 -0
- package/llms/components/lr-icon-button.md +2 -1
- package/llms/components/lr-ingestion-queue.md +76 -8
- package/llms/components/lr-json-viewer.md +51 -0
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-locale-picker.md +5 -0
- package/llms/components/lr-map.md +33 -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-message-feedback.md +38 -3
- package/llms/components/lr-number-input.md +28 -1
- package/llms/components/lr-page.md +4 -2
- package/llms/components/lr-prompt-input.md +6 -3
- package/llms/components/lr-segmented.md +30 -10
- package/llms/components/lr-sequence-playback.md +47 -12
- 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 +4 -1
- package/llms/peers.md +2 -2
- package/llms/shared/events-and-types.md +61 -2
- package/llms/shared/forms-and-accessibility.md +46 -4
- package/llms/shared/imports-and-registration.md +154 -110
- package/llms/shared/testing-and-utilities.md +5 -1
- package/llms/shared.md +266 -117
- package/locales.json +1 -1
- package/package.json +22 -21
- package/registrations.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SourceRequestController}from"../../../internal/source-request-controller.js";import{prepareChartModel,revealPreparedSourcePoint}from"./chart-prepared-data.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{LazyChartSyncController}from"./chart-sync-lazy.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{collectionSupport,snapshotPublicCollection,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues,chartSeriesValueLimit}from"./chart-series-bounds.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{decimalPlaces,finiteAdd,finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{bidiStyles,isolateHtml,isolatedMessage}from"./chart-bidi.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes,normalizeChartRecordLimit}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{categoryLabelGrowth,hasCategoryLabelText,sparseCategoryLabelExtent,visibleCategoryLabelIndexes,widestEstimatedCategoryLabel}from"./lite-chart-axis-layout.js";import{LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartInputLimit,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointCoordinates,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartPreparedSummary,LYRA_DEFAULT_chartPreparedUnavailable,LYRA_DEFAULT_chartSummary,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";function isLiteChartSeries(value){return hasArraySeriesData(value)}function normalizeLiteChartSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isLiteChartSeries):[])}catch{return Object.freeze([])}}function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),autoNumberConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();return trimmed.toLowerCase()==="auto"?"auto":Number(trimmed)}},DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,AUTO_CATEGORY_LABEL_INSET=10,VALUE_AXIS_TICK_OFFSET=6,AUTO_VALUE_AXIS_SAFETY_INSET=8,MAX_AUTO_VALUE_AXIS_GUTTER=240,MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION=.4,MAX_SCROLL_CONTENT_WIDTH=1e6,CATEGORY_LABEL_SELECTION_BOUNDS=Object.freeze({characterWidth:APPROX_LABEL_CHARACTER_WIDTH,laneInset:AUTO_CATEGORY_LABEL_INSET,maxContentWidth:MAX_SCROLL_CONTENT_WIDTH,maxRenderedRecords:MAX_RENDERED_CHART_RECORDS});function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function snapToStep(value,step){return Number.isFinite(step)&&step>0?Number(value.toFixed(Math.min(decimalPlaces(step),100))):value}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return Number((lo*(1-ratio)+hi*ratio).toPrecision(15))}).filter(Number.isFinite)}function logarithmicTicks(lo,hi,count){if(!(lo>0&&hi>lo)||!Number.isFinite(lo)||!Number.isFinite(hi))return;const start=Math.log10(lo),end=Math.log10(hi),span=end-start;if(!(span>0))return;const decades=span>=1,step=decades?Math.ceil(span/count):niceStep(hi-lo,count);if(!Number.isFinite(step)||step<=0)return[...new Set(safeDomainTicks(lo,hi,count))];const ticks=[lo],minimumGap=decades?step/2:span/(count*2),first=Math.ceil((decades?start:lo)/step);for(let index=0;index<=count+1;index++){const value=decades?10**((first+index)*step):snapToStep((first+index)*step,step);if(!Number.isFinite(value)||value>=hi)break;if(value<=ticks.at(-1))continue;const logarithm=Math.log10(value);logarithm-Math.log10(ticks.at(-1))>=minimumGap&&end-logarithm>=minimumGap&&ticks.push(value)}return ticks.push(hi),ticks}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const snap=value=>snapToStep(value,step),roundedLo=snap(Math.floor(lo/step)*step),roundedHi=snap(Math.ceil(hi/step)*step);Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=snap(lo+index*step);Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this._preparedData=null,this.preparedDirty=!0,this.preparedActive=!1,this.preparedChanged=!1,this.preparedInvalid=!1,this.preparedPending=!1,this.preparedRequestFailed=!1,this.announcedPreparedInvalid=!1,this.preparedRequests=new SourceRequestController(this,{channels:["point"],onReset:()=>{this.preparedPending=!1}}),this.labels=[],this.maxRecords=1e3,this._datasets=Object.freeze([]),this.datasetsTruncated=!1,this.datasetsSources=new CollectionSourceTracker,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.stacked=!1,this.tableTotals=!1,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.hostAccessibleLabel=null,this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this._activeMarkIndex=0,this.syncPlot={y:0,height:0},this.syncCategoryPositions=new Map,this.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.themeWatcher=new ThemeWatcher(this,()=>this.requestUpdate()),this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.syncGroup="",this.chartSync=new LazyChartSyncController(this,(label,index)=>this.syncPresentation(label,index),void 0,target=>target.nodeType===1&&target.hasAttribute("data-mark-index"),()=>this.requestUpdate()),this.deferredTableGeneration=0,this.streamingTableUpdate=!1}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartInputLimit:LYRA_DEFAULT_chartInputLimit,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointCoordinates:LYRA_DEFAULT_chartPointCoordinates,chartPreparedSummary:LYRA_DEFAULT_chartPreparedSummary,chartPreparedUnavailable:LYRA_DEFAULT_chartPreparedUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSummary:LYRA_DEFAULT_chartSummary,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTotal:LYRA_DEFAULT_chartTotal,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,bidiStyles]}get preparedData(){return this._preparedData}set preparedData(value){const previous=this._preparedData;this._preparedData=value,this.requestUpdate("preparedData",previous),value===previous&&this.requestUpdate()}refreshPreparedModel(){if(!this.preparedDirty)return;this.preparedDirty=!1,this.preparedChanged=!0,this.preparedInvalid=!1,this.preparedRequestFailed=!1,this.preparedBaseModel=this.preparedModel=void 0,this.preparedEffective=void 0;const input=this._preparedData;this.preparedActive=input!==null;try{if(input!==null){const model=prepareChartModel(input,this.effectiveType,normalizeChartRecordLimit(this.maxRecords));if(model.kind==="series"&&this.stacked)throw new TypeError("Ordered series cannot be stacked");this.preparedBaseModel=this.preparedModel=model,this.preparedRequests.setSource(input,model.revision)}else this.preparedRequests.setSource(void 0,void 0)}catch{this.preparedInvalid=!0,this.preparedRequests.setSource(void 0,void 0)}}async revealSourcePoint(ref){if(!this.isConnected||!ref||typeof ref.seriesId!="string")return!1;ref=Object.freeze({seriesId:ref.seriesId,sourceIndex:ref.sourceIndex}),this.preparedDirty&&await this.updateComplete;const model=this.preparedBaseModel;if(!model||model.kind!=="series")return!1;const series=model.series.find(series2=>series2.id===ref.seriesId);if(!series||!Number.isSafeInteger(ref.sourceIndex)||ref.sourceIndex<0||ref.sourceIndex>=series.counts.sourceCount)return!1;const lease=this.preparedRequests.begin("point",this.effectiveLocale);if(!lease)return!1;this.preparedPending=!0,this.preparedRequestFailed=!1,this.requestUpdate("preparedView",null);const signal=lease.context.signal;try{const result=await revealPreparedSourcePoint(model,ref,signal,()=>lease.isCurrent()&&this.preparedBaseModel===model);return result.status!=="ready"||!lease.isCurrent()||this.preparedBaseModel!==model||model.source.revision!==model.revision?!1:(this.preparedModel=result.model,this.preparedChanged=!0,this.preparedEffective=void 0,this.recordSampleMemo=void 0,this.marksMemo=void 0,this.dataTableRows=void 0,!0)}catch{return lease.isCurrent()&&(this.preparedRequestFailed=!0,this.announcements.announceAssertive(this.localize("chartPreparedUnavailable"))),!1}finally{lease.isCurrent()&&(this.preparedPending=!1,this.requestUpdate("preparedView",null))}}get displayDatasets(){if(!this.preparedActive)return this.datasets;const model=this.preparedModel;if(!model)return[];if(this.preparedEffective?.model===model)return this.preparedEffective.datasets;const datasets=model.series.map(series=>Object.freeze({label:series.label,data:model.kind==="series"?Object.freeze(series.samples.map(point=>point?.y??null)):series.values}));return this.preparedEffective={model,datasets},datasets}get displayLabels(){return this.preparedActive?this.preparedModel?.labels??[]:this.labels}datumLabel(datasetIndex,index){const point=this.preparedModel?.kind==="series"?this.preparedModel.series[datasetIndex]?.samples[index]:void 0;return point?`${point.sourceIndex}: ${this.localize("chartPointCoordinates",void 0,{x:formatChartValue(point.x,this.effectiveLocale),y:point.y===null?"":formatChartValue(point.y,this.effectiveLocale)})}`:this.displayLabels[index]??""}preparedX(datasetIndex,index,plotX,plotW){const model=this.preparedModel,point=model?.series[datasetIndex]?.samples[index];if(!model||!point)return plotX;let lo=1/0,hi=-1/0;for(const series of model.series)series.xDomain&&(lo=Math.min(lo,series.xDomain.min),hi=Math.max(hi,series.xDomain.max));const fraction=lo===hi?.5:domainFraction(point.x,lo,hi);return plotX+(this.effectiveDirection==="rtl"?1-fraction:fraction)*plotW}preparedDescription(){const model=this.preparedModel;if(!model)return this.description??"";const summary=this.localize("chartPreparedSummary",void 0,{validCount:formatChartValue(model.validCount,this.effectiveLocale),invalidCount:formatChartValue(model.invalidCount,this.effectiveLocale),displayedCount:formatChartValue(model.displayedCount,this.effectiveLocale)}),domains=(this.preparedBaseModel??model).series.flatMap(series=>{if(!series.yDomain)return[];const first=series.samples[0]?.y??0,last=series.samples.at(-1)?.y??0;return[this.localize("chartSummary",void 0,{label:series.label,count:formatChartValue(series.counts.validCount,this.effectiveLocale),min:formatChartValue(series.yDomain.min,this.effectiveLocale),max:formatChartValue(series.yDomain.max,this.effectiveLocale),trend:this.localize(last>first?"chartTrendIncreasing":last<first?"chartTrendDecreasing":"chartTrendFlat")})]});return[this.description,...domains,summary].filter(Boolean).join(this.localize("chartSummarySeparator"))}get datasets(){return this._datasets}set datasets(value){if(this.datasetsSources.isRebind("datasets",value,this._datasets))return;const previous=this._datasets,bounded=boundChartSeriesValues(value);this.datasetsTruncated=bounded!==void 0,this._datasets=normalizeLiteChartSeries(snapshotPublicCollection(bounded??value,this.ownerDocument?.defaultView,{onResult:result=>{this.datasetsTruncated||=result.truncated}})),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get activeMarkIndex(){return this._activeMarkIndex}set activeMarkIndex(index){index!==this._activeMarkIndex&&(this.renderRoot?.querySelector(`[data-mark-index="${this._activeMarkIndex}"]`)?.setAttribute("tabindex","-1"),this._activeMarkIndex=index,this.renderRoot?.querySelector(`[data-mark-index="${index}"]`)?.setAttribute("tabindex","0"))}appendData(label,values,maxPoints=0){if(this._preparedData===null){this.deferStreamedTable(),this.streamingTableUpdate=!0;try{const bound=chartSeriesValueLimit(this.datasets.length),requested=Math.max(0,finiteCount(maxPoints,0)),limit=requested>0?Math.min(requested,bound):bound;let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const retained=Math.min(domainLength+1,limit),start=domainLength+1-retained,labels=new Array(retained);for(let i=0;i<retained-1;i++)labels[i]=this.labels[start+i]??"";labels[retained-1]=label,this.labels=labels;const previous=this._datasets;this._datasets=Object.freeze(previous.map((series,index)=>{const data=new Array(retained);for(let i=0;i<retained-1;i++)data[i]=start+i<series.data.length?series.data[start+i]:null;return data[retained-1]=snapshotPublicCollection(values[index]??null,this.ownerDocument?.defaultView),Object.freeze({...series,data:Object.freeze(data)})})),this.datasetsSources.isRebind("datasets",this._datasets,previous),this.datasetsTruncated=!1,this.requestUpdate("datasets",previous)}finally{this.streamingTableUpdate=!1}}}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.displayDatasets.map(series=>series.label)].map(escapeCsvField).join(",");if(this.preparedModel?.kind==="series"){const rows2=[];return this.preparedModel.series.forEach((entry,datasetIndex)=>entry.samples.forEach((point,index)=>{if(!point||point.y===null)return;const label=this.datumLabel(datasetIndex,index),value=this.formatter?.({value:point.y,surface:"export",datasetIndex,index,label,seriesLabel:entry.label,axis:"y"})??point.y;rows2.push([label,...this.displayDatasets.map((_series,position)=>position===datasetIndex?value:"")].map(escapeCsvField).join(","))})),[header,...rows2].join(`\r
|
|
1
|
+
import{__decorate}from"tslib";import{SourceRequestController}from"../../../internal/source-request-controller.js";import{prepareChartModel,revealPreparedSourcePoint}from"./chart-prepared-data.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{LazyChartSyncController}from"./chart-sync-lazy.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{collectionSupport,snapshotPublicCollection,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues,chartSeriesValueLimit}from"./chart-series-bounds.js";import{nativeSvgTitle}from"../../../internal/svg-title.js";import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{decimalPlaces,finiteAdd,finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{bidiStyles,isolateHtml,isolatedMessage}from"./chart-bidi.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes,normalizeChartRecordLimit}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{categoryLabelGrowth,hasCategoryLabelText,sparseCategoryLabelExtent,visibleCategoryLabelIndexes,widestEstimatedCategoryLabel}from"./lite-chart-axis-layout.js";import{LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartInputLimit,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointCoordinates,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartPreparedSummary,LYRA_DEFAULT_chartPreparedUnavailable,LYRA_DEFAULT_chartSummary,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";function isLiteChartSeries(value){return hasArraySeriesData(value)}function normalizeLiteChartSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isLiteChartSeries):[])}catch{return Object.freeze([])}}function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),autoNumberConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();return trimmed.toLowerCase()==="auto"?"auto":Number(trimmed)}},DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,AUTO_CATEGORY_LABEL_INSET=10,VALUE_AXIS_TICK_OFFSET=6,AUTO_VALUE_AXIS_SAFETY_INSET=8,MAX_AUTO_VALUE_AXIS_GUTTER=240,MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION=.4,MAX_SCROLL_CONTENT_WIDTH=1e6,CATEGORY_LABEL_SELECTION_BOUNDS=Object.freeze({characterWidth:APPROX_LABEL_CHARACTER_WIDTH,laneInset:AUTO_CATEGORY_LABEL_INSET,maxContentWidth:MAX_SCROLL_CONTENT_WIDTH,maxRenderedRecords:MAX_RENDERED_CHART_RECORDS});function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const relativeSpan=(top-bottom)/bottom,fraction=relativeSpan<=1?Math.log1p((value-bottom)/bottom)/Math.log1p(relativeSpan):(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function snapToStep(value,step){const places=decimalPlaces(step);return Number.isFinite(step)&&step>0&&places<=100?Number(value.toFixed(places)):value}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return Number((lo*(1-ratio)+hi*ratio).toPrecision(15))}).filter(Number.isFinite)}function logarithmicTicks(lo,hi,count){if(!(lo>0&&hi>lo)||!Number.isFinite(lo)||!Number.isFinite(hi))return;const start=Math.log10(lo),end=Math.log10(hi),span=end-start;if(!(span>0))return;const decades=span>=1,step=decades?Math.ceil(span/count):niceStep(hi-lo,count);if(!Number.isFinite(step)||step<=0)return[...new Set(safeDomainTicks(lo,hi,count))];const ticks=[lo],minimumGap=decades?step/2:span/(count*2),first=Math.ceil((decades?start:lo)/step);for(let index=0;index<=count+1;index++){const value=decades?10**((first+index)*step):snapToStep((first+index)*step,step);if(!Number.isFinite(value)||value>=hi)break;if(value<=ticks.at(-1))continue;const logarithm=Math.log10(value);logarithm-Math.log10(ticks.at(-1))>=minimumGap&&end-logarithm>=minimumGap&&ticks.push(value)}return ticks.push(hi),ticks}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const snap=value=>snapToStep(value,step),roundedLo=snap(Math.floor(lo/step)*step),roundedHi=snap(Math.ceil(hi/step)*step);Number.isFinite(roundedLo)&&(lo=Math.min(lo,roundedLo)),Number.isFinite(roundedHi)&&(hi=Math.max(hi,roundedHi));const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=snap(lo+index*step);Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this._preparedData=null,this.preparedDirty=!0,this.preparedActive=!1,this.preparedChanged=!1,this.preparedInvalid=!1,this.preparedPending=!1,this.preparedRequestFailed=!1,this.announcedPreparedInvalid=!1,this.preparedRequests=new SourceRequestController(this,{channels:["point"],onReset:()=>{this.preparedPending=!1}}),this.labels=[],this.maxRecords=1e3,this._datasets=Object.freeze([]),this.datasetsTruncated=!1,this.datasetsSources=new CollectionSourceTracker,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.stacked=!1,this.tableTotals=!1,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.hostAccessibleLabel=null,this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this._activeMarkIndex=0,this.syncPlot={y:0,height:0},this.syncCategoryPositions=new Map,this.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.themeWatcher=new ThemeWatcher(this,()=>this.requestUpdate()),this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.syncGroup="",this.chartSync=new LazyChartSyncController(this,(label,index)=>this.syncPresentation(label,index),void 0,target=>target.nodeType===1&&target.hasAttribute("data-mark-index"),()=>this.requestUpdate()),this.deferredTableGeneration=0,this.streamingTableUpdate=!1}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartInputLimit:LYRA_DEFAULT_chartInputLimit,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointCoordinates:LYRA_DEFAULT_chartPointCoordinates,chartPreparedSummary:LYRA_DEFAULT_chartPreparedSummary,chartPreparedUnavailable:LYRA_DEFAULT_chartPreparedUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSummary:LYRA_DEFAULT_chartSummary,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTotal:LYRA_DEFAULT_chartTotal,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,bidiStyles]}get preparedData(){return this._preparedData}set preparedData(value){const previous=this._preparedData;this._preparedData=value,this.requestUpdate("preparedData",previous),value===previous&&this.requestUpdate()}refreshPreparedModel(){if(!this.preparedDirty)return;this.preparedDirty=!1,this.preparedChanged=!0,this.preparedInvalid=!1,this.preparedRequestFailed=!1,this.preparedBaseModel=this.preparedModel=void 0,this.preparedEffective=void 0;const input=this._preparedData;this.preparedActive=input!==null;try{if(input!==null){const model=prepareChartModel(input,this.effectiveType,normalizeChartRecordLimit(this.maxRecords));if(model.kind==="series"&&this.stacked)throw new TypeError("Ordered series cannot be stacked");this.preparedBaseModel=this.preparedModel=model,this.preparedRequests.setSource(input,model.revision)}else this.preparedRequests.setSource(void 0,void 0)}catch{this.preparedInvalid=!0,this.preparedRequests.setSource(void 0,void 0)}}async revealSourcePoint(ref){if(!this.isConnected||!ref||typeof ref.seriesId!="string")return!1;ref=Object.freeze({seriesId:ref.seriesId,sourceIndex:ref.sourceIndex}),this.preparedDirty&&await this.updateComplete;const model=this.preparedBaseModel;if(!model||model.kind!=="series")return!1;const series=model.series.find(series2=>series2.id===ref.seriesId);if(!series||!Number.isSafeInteger(ref.sourceIndex)||ref.sourceIndex<0||ref.sourceIndex>=series.counts.sourceCount)return!1;const lease=this.preparedRequests.begin("point",this.effectiveLocale);if(!lease)return!1;this.preparedPending=!0,this.preparedRequestFailed=!1,this.requestUpdate("preparedView",null);const signal=lease.context.signal;try{const result=await revealPreparedSourcePoint(model,ref,signal,()=>lease.isCurrent()&&this.preparedBaseModel===model);return result.status!=="ready"||!lease.isCurrent()||this.preparedBaseModel!==model||model.source.revision!==model.revision?!1:(this.preparedModel=result.model,this.preparedChanged=!0,this.preparedEffective=void 0,this.recordSampleMemo=void 0,this.marksMemo=void 0,this.dataTableRows=void 0,!0)}catch{return lease.isCurrent()&&(this.preparedRequestFailed=!0,this.announcements.announceAssertive(this.localize("chartPreparedUnavailable"))),!1}finally{lease.isCurrent()&&(this.preparedPending=!1,this.requestUpdate("preparedView",null))}}get displayDatasets(){if(!this.preparedActive)return this.datasets;const model=this.preparedModel;if(!model)return[];if(this.preparedEffective?.model===model)return this.preparedEffective.datasets;const datasets=model.series.map(series=>Object.freeze({label:series.label,data:model.kind==="series"?Object.freeze(series.samples.map(point=>point?.y??null)):series.values}));return this.preparedEffective={model,datasets},datasets}get displayLabels(){return this.preparedActive?this.preparedModel?.labels??[]:this.labels}datumLabel(datasetIndex,index){const point=this.preparedModel?.kind==="series"?this.preparedModel.series[datasetIndex]?.samples[index]:void 0;return point?`${point.sourceIndex}: ${this.localize("chartPointCoordinates",void 0,{x:formatChartValue(point.x,this.effectiveLocale),y:point.y===null?"":formatChartValue(point.y,this.effectiveLocale)})}`:this.displayLabels[index]??""}preparedX(datasetIndex,index,plotX,plotW){const model=this.preparedModel,point=model?.series[datasetIndex]?.samples[index];if(!model||!point)return plotX;let lo=1/0,hi=-1/0;for(const series of model.series)series.xDomain&&(lo=Math.min(lo,series.xDomain.min),hi=Math.max(hi,series.xDomain.max));const fraction=lo===hi?.5:domainFraction(point.x,lo,hi);return plotX+(this.effectiveDirection==="rtl"?1-fraction:fraction)*plotW}preparedDescription(){const model=this.preparedModel;if(!model)return this.description??"";const summary=this.localize("chartPreparedSummary",void 0,{validCount:formatChartValue(model.validCount,this.effectiveLocale),invalidCount:formatChartValue(model.invalidCount,this.effectiveLocale),displayedCount:formatChartValue(model.displayedCount,this.effectiveLocale)}),domains=(this.preparedBaseModel??model).series.flatMap(series=>{if(!series.yDomain)return[];const first=series.samples[0]?.y??0,last=series.samples.at(-1)?.y??0;return[this.localize("chartSummary",void 0,{label:series.label,count:formatChartValue(series.counts.validCount,this.effectiveLocale),min:formatChartValue(series.yDomain.min,this.effectiveLocale),max:formatChartValue(series.yDomain.max,this.effectiveLocale),trend:this.localize(last>first?"chartTrendIncreasing":last<first?"chartTrendDecreasing":"chartTrendFlat")})]});return[this.description,...domains,summary].filter(Boolean).join(this.localize("chartSummarySeparator"))}get datasets(){return this._datasets}set datasets(value){if(this.datasetsSources.isRebind("datasets",value,this._datasets))return;const previous=this._datasets,bounded=boundChartSeriesValues(value);this.datasetsTruncated=bounded!==void 0,this._datasets=normalizeLiteChartSeries(snapshotPublicCollection(bounded??value,this.ownerDocument?.defaultView,{onResult:result=>{this.datasetsTruncated||=result.truncated}})),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get activeMarkIndex(){return this._activeMarkIndex}set activeMarkIndex(index){index!==this._activeMarkIndex&&(this.renderRoot?.querySelector(`[data-mark-index="${this._activeMarkIndex}"]`)?.setAttribute("tabindex","-1"),this._activeMarkIndex=index,this.renderRoot?.querySelector(`[data-mark-index="${index}"]`)?.setAttribute("tabindex","0"))}appendData(label,values,maxPoints=0){if(this._preparedData===null){this.deferStreamedTable(),this.streamingTableUpdate=!0;try{const bound=chartSeriesValueLimit(this.datasets.length),requested=Math.max(0,finiteCount(maxPoints,0)),limit=requested>0?Math.min(requested,bound):bound;let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const retained=Math.min(domainLength+1,limit),start=domainLength+1-retained,labels=new Array(retained);for(let i=0;i<retained-1;i++)labels[i]=this.labels[start+i]??"";labels[retained-1]=label,this.labels=labels;const previous=this._datasets;this._datasets=Object.freeze(previous.map((series,index)=>{const data=new Array(retained);for(let i=0;i<retained-1;i++)data[i]=start+i<series.data.length?series.data[start+i]:null;return data[retained-1]=snapshotPublicCollection(values[index]??null,this.ownerDocument?.defaultView),Object.freeze({...series,data:Object.freeze(data)})})),this.datasetsSources.isRebind("datasets",this._datasets,previous),this.datasetsTruncated=!1,this.requestUpdate("datasets",previous)}finally{this.streamingTableUpdate=!1}}}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.displayDatasets.map(series=>series.label)].map(escapeCsvField).join(",");if(this.preparedModel?.kind==="series"){const rows2=[];return this.preparedModel.series.forEach((entry,datasetIndex)=>entry.samples.forEach((point,index)=>{if(!point||point.y===null)return;const label=this.datumLabel(datasetIndex,index),value=this.formatter?.({value:point.y,surface:"export",datasetIndex,index,label,seriesLabel:entry.label,axis:"y"})??point.y;rows2.push([label,...this.displayDatasets.map((_series,position)=>position===datasetIndex?value:"")].map(escapeCsvField).join(","))})),[header,...rows2].join(`\r
|
|
2
2
|
`)}const rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.displayLabels[index]??"";return[label,...this.displayDatasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label,axis:"y"})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
|
|
3
|
-
`)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&(name==="style"||name==="class")&&(this.fitAxisTitles(),this.fitCategoryLabels())}connectedCallback(){super.connectedCallback(),this.requestUpdate(),this.armResizeObserver()}armResizeObserver(){const target=this.svgEl,ownerDocument=this.ownerDocument;if(!this.isConnected||!target||this.resizeObserver&&this.resizeObserverDocument===ownerDocument&&this.resizeObserverTarget===target)return;this.resetResizeObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverCtor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.resizeObserverTarget!==target)return;const svgEntry=entries.find(entry=>entry.target===target);if(svgEntry){const box=svgEntry.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=target.getBoundingClientRect();this.plotWidth=rect.width,this.plotHeight=rect.height}}entries.some(entry=>this.axisTitleTargets.has(entry.target))&&this.queueAxisTitleFit()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target),this.syncAxisTitleTargets()}disconnectedCallback(){this.preparedRequests.refresh(),this.preparedModel=this.preparedBaseModel=void 0,this.preparedEffective=void 0,this.preparedDirty=!0,this.clearDeferredTable(),this.chartSync.disconnect(),super.disconnectedCallback(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver()}adoptedCallback(){this.preparedRequests.adopted(),this.clearDeferredTable(),this.chartSync.disconnect(),super.adoptedCallback(),this.requestUpdate(),this.resetResizeObserver(),this.announcements.adopted(),this.isConnected?this.themeWatcher.hostConnected():this.themeWatcher.hostDisconnected(),this.refreshFitMeasurementAvailability()}resetResizeObserver(){this.axisTitleFrame!==void 0&&(this.resizeObserverDocument?.defaultView?.cancelAnimationFrame(this.axisTitleFrame),this.axisTitleFrame=void 0),this.axisTitleTargets.clear(),this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.resizeObserverTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver()}willUpdate(changed){super.willUpdate(changed),this.refreshPreparedModel();const shouldSync=this.preparedModel?.kind!=="series"&&this.isConnected&&typeof this.syncGroup=="string"&&this.syncGroup.trim()!=="";if(this.chartSync.enabled!==shouldSync&&this.chartSync.update(this.syncGroup,shouldSync),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!(this.preparedChanged||["type","labels","datasets","skipZero","maxRecords","plotWidth","layout"].some(name=>changed.has(name))))return;const active=shadowFocusTarget(this)??null,hadFocusedMark=active?.matches('[part="bar"], [part="point"]')??!1,priorPosition=Number(active?.getAttribute("data-mark-index")??this.activeMarkIndex),datasetAttribute=active?.getAttribute("data-dataset-index"),indexAttribute=active?.getAttribute("data-index"),datasetIndex=Number(datasetAttribute),index=Number(indexAttribute),marks=this.interactiveMarks(),sameIdentity=datasetAttribute!=null&&indexAttribute!==null&&indexAttribute!==void 0?marks.findIndex(mark=>mark.datasetIndex===datasetIndex&&mark.index===index):-1;this.activeMarkIndex=marks.length?sameIdentity>=0?sameIdentity:Math.min(Math.max(priorPosition,0),marks.length-1):0,this.refocusMarkAfterUpdate=hadFocusedMark&&marks.length>0,this.refocusChartAfterUpdate=hadFocusedMark&&marks.length===0}updated(changed){super.updated(changed);const wasMounting=this.isMounting;if(this.preparedChanged=!1,this.setAttribute("aria-busy",String(this.preparedPending)),!wasMounting&&this.preparedInvalid&&!this.announcedPreparedInvalid&&this.announcements.announceAssertive(this.localize("chartPreparedUnavailable")),this.announcedPreparedInvalid=this.preparedInvalid,this.isMounting=!1,changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}const inputLimit=this.inputLimitMessage(),sampling=this.dataTruncationMessage(),dataTruncation=inputLimit&&sampling?[inputLimit,sampling].join(this.localize("chartSummarySeparator")):inputLimit||sampling;wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus()),(changed.size===0||[...changed.keys()].some(name=>!["selectedIndices","dataTableExpandedOverride","dataTable","dataTableToggle","description","label"].includes(String(name))))&&(this.fitAxisTitles(),this.fitCategoryLabels()),this.syncAxisTitleTargets();const dataChanged=["datasets","labels","type","skipZero","layout","maxRecords","maxSeries"].some(name=>changed.has(name));this.chartSync.update(this.syncGroup,this.preparedModel?.kind!=="series",dataChanged)}fitAxisTitles(){if(!(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length))for(const title of this.svgEl.querySelectorAll('[part="axis-title"]')){const text=Array.from(title.childNodes).find(node=>node.nodeType===3);if(!text)continue;const source=title.getAttribute("aria-label")??"",extent=finiteRange(Number(title.getAttribute("data-title-extent")),0,0,MAX_SCROLL_CONTENT_WIDTH),previous=this.axisTitleFits.get(title);if(!(previous?.source===source&&previous.extent===extent&&previous.display===text.data&&previous.width===title.getComputedTextLength())){if(title.style.removeProperty("opacity"),text.data=source,title.getComputedTextLength()>extent)if(text.data="…",title.getComputedTextLength()>extent)title.style.opacity="0";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=`${source.slice(0,middle)}…`,title.getComputedTextLength()<=extent?lower=middle:upper=middle-1}const last=source.charCodeAt(lower-1);last>=55296&&last<=56319&&(lower-=1),text.data=`${source.slice(0,lower)}…`}this.axisTitleFits.set(title,{source,extent,display:text.data,width:title.getComputedTextLength()})}}}fitOneCategoryLabel(tick,x,anchor,extent){const width=this.fitCategoryBatch([{tick,extent}])[0]??0;return anchor==="start"?x+width:anchor==="end"?x-width:x}fitCategoryBatch(items){const candidates=items.map(({tick,extent})=>{const text=Array.from(tick.childNodes).find(node=>node.nodeType===3),source=tick.getAttribute("data-full-label")??"",bounded=finiteRange(extent,0,0,MAX_SCROLL_CONTENT_WIDTH);return tick.setAttribute("data-label-extent",String(bounded)),text&&(text.data=source),{tick,text,source,bounded,lower:0,upper:source.length,middle:0,overflow:!1}}),fullWidths=candidates.map(item=>item.tick.getComputedTextLength());candidates.forEach((item,index)=>{item.overflow=!!item.text&&fullWidths[index]>item.bounded});let searching=candidates.filter(item=>item.overflow&&item.source.length>1);for(;searching.length;){for(const item of searching)item.middle=Math.ceil((item.lower+item.upper)/2),item.text.data=`${item.source.slice(0,item.middle)}…`;const widths2=searching.map(item=>item.tick.getComputedTextLength());searching.forEach((item,index)=>{widths2[index]<=item.bounded?item.lower=item.middle:item.upper=item.middle-1}),searching=searching.filter(item=>item.lower<item.upper)}for(const item of candidates)if(item.text){if(item.overflow){const last=item.source.charCodeAt(item.lower-1);last>=55296&&last<=56319&&item.lower--,item.text.data=item.source.length?`${item.source.slice(0,item.lower)}…`:""}item.text.data===item.source?item.tick.removeAttribute("aria-label"):item.tick.setAttribute("aria-label",item.source)}return candidates.map(item=>item.tick.getComputedTextLength())}fitCategoryLabels(){if(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length)return;const ticks=[...this.svgEl.querySelectorAll('[part="axis-label"][data-full-label]')].filter(tick=>hasCategoryLabelText(tick.getAttribute("data-full-label"))).sort((a,b)=>Number(a.getAttribute("x"))-Number(b.getAttribute("x"))),count=ticks.length;if(count===0)return;const MARGIN=BAR_CORNER_RADIUS,positionOf=tick=>Number(tick.getAttribute("x"))||0,anchorOf=tick=>tick.getAttribute("text-anchor")??"middle",first=ticks[0],last=ticks[count-1],firstIsBoundary=count>1&&anchorOf(first)!=="middle",lastIsBoundary=count>1&&anchorOf(last)!=="middle";let firstRightEdge=positionOf(first),lastLeftEdge=positionOf(last);if(firstIsBoundary&&lastIsBoundary&&count===2){const half=Math.max(0,(positionOf(last)-positionOf(first))/2-MARGIN);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),half),lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),half)}else{if(firstIsBoundary){const gap=positionOf(ticks[1])-positionOf(first);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),gap-MARGIN)}if(lastIsBoundary){const gap=positionOf(last)-positionOf(ticks[count-2]);lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),gap-MARGIN)}}const interiors=[];for(let index=0;index<count;index++){if(index===0&&firstIsBoundary||index===count-1&&lastIsBoundary)continue;const tick=ticks[index],x=positionOf(tick),leftAvailable=index===0?MAX_SCROLL_CONTENT_WIDTH:index===1&&firstIsBoundary?x-firstRightEdge:(x-positionOf(ticks[index-1]))/2,rightAvailable=index===count-1?MAX_SCROLL_CONTENT_WIDTH:index===count-2&&lastIsBoundary?lastLeftEdge-x:(positionOf(ticks[index+1])-x)/2,extent=2*Math.min(leftAvailable,rightAvailable)-MARGIN;interiors.push({tick,extent})}this.fitCategoryBatch(interiors)}syncAxisTitleTargets(){if(!this.resizeObserver||!this.svgEl)return;const current=new Set(this.svgEl.querySelectorAll('[part="axis-title"]'));for(const title of this.axisTitleTargets)current.has(title)||this.resizeObserver.unobserve(title);for(const title of current)this.axisTitleTargets.has(title)||this.resizeObserver.observe(title);this.axisTitleTargets=current}queueAxisTitleFit(){const document=this.resizeObserverDocument,window=document?.defaultView;if(!window||this.axisTitleFrame!==void 0)return;const generation=this.resizeObserverGeneration,frame=window.requestAnimationFrame(()=>{this.axisTitleFrame!==frame||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==document||(this.axisTitleFrame=void 0,this.fitAxisTitles())});this.axisTitleFrame=frame}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return this.forcedColorsMemo??=forcedColorsActive(this.ownerDocument?.defaultView)}markPaint(index,series){const color=this.colorFor(index,series);return this.effectiveType==="bar"&&this.forcedColors()?`url(#${this.forcedColorPatternId}-${index})`:color}legendEncoding(index){return this.forcedColors()?forcedColorEncoding(index).name:nothing}markDash(index){if(!this.forcedColors())return nothing;const dash=forcedColorEncoding(index).dash;return dash.length?dash.join(" "):"none"}renderForcedColorPatterns(){if(this.effectiveType!=="bar"||!this.forcedColors())return nothing;const size=8,half=size/2,texture="var(--lr-color-surface)";return svg`<defs>
|
|
3
|
+
`)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&(name==="style"||name==="class")&&(this.fitAxisTitles(),this.fitCategoryLabels())}connectedCallback(){super.connectedCallback(),this.requestUpdate(),this.armResizeObserver()}armResizeObserver(){const target=this.svgEl,ownerDocument=this.ownerDocument;if(!this.isConnected||!target||this.resizeObserver&&this.resizeObserverDocument===ownerDocument&&this.resizeObserverTarget===target)return;this.resetResizeObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverCtor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.resizeObserverTarget!==target)return;const svgEntry=entries.find(entry=>entry.target===target);if(svgEntry){const box=svgEntry.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=target.getBoundingClientRect();this.plotWidth=rect.width,this.plotHeight=rect.height}}entries.some(entry=>this.axisTitleTargets.has(entry.target))&&this.queueAxisTitleFit()});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target),this.syncAxisTitleTargets()}disconnectedCallback(){this.preparedRequests.refresh(),this.preparedModel=this.preparedBaseModel=void 0,this.preparedEffective=void 0,this.preparedDirty=!0,this.clearDeferredTable(),this.chartSync.disconnect(),super.disconnectedCallback(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver()}adoptedCallback(){this.preparedRequests.adopted(),this.clearDeferredTable(),this.chartSync.disconnect(),super.adoptedCallback(),this.requestUpdate(),this.resetResizeObserver(),this.announcements.adopted(),this.isConnected?this.themeWatcher.hostConnected():this.themeWatcher.hostDisconnected(),this.refreshFitMeasurementAvailability()}resetResizeObserver(){this.axisTitleFrame!==void 0&&(this.resizeObserverDocument?.defaultView?.cancelAnimationFrame(this.axisTitleFrame),this.axisTitleFrame=void 0),this.axisTitleTargets.clear(),this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.resizeObserverTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver()}willUpdate(changed){super.willUpdate(changed),this.refreshPreparedModel();const shouldSync=this.preparedModel?.kind!=="series"&&this.isConnected&&typeof this.syncGroup=="string"&&this.syncGroup.trim()!=="";if(this.chartSync.enabled!==shouldSync&&this.chartSync.update(this.syncGroup,shouldSync),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!(this.preparedChanged||["type","labels","datasets","skipZero","maxRecords","plotWidth","layout"].some(name=>changed.has(name))))return;const active=shadowFocusTarget(this)??null,hadFocusedMark=active?.matches('[part="bar"], [part="point"]')??!1,priorPosition=Number(active?.getAttribute("data-mark-index")??this.activeMarkIndex),datasetAttribute=active?.getAttribute("data-dataset-index"),indexAttribute=active?.getAttribute("data-index"),datasetIndex=Number(datasetAttribute),index=Number(indexAttribute),marks=this.interactiveMarks(),sameIdentity=datasetAttribute!=null&&indexAttribute!==null&&indexAttribute!==void 0?marks.findIndex(mark=>mark.datasetIndex===datasetIndex&&mark.index===index):-1;this.activeMarkIndex=marks.length?sameIdentity>=0?sameIdentity:Math.min(Math.max(priorPosition,0),marks.length-1):0,this.refocusMarkAfterUpdate=hadFocusedMark&&marks.length>0,this.refocusChartAfterUpdate=hadFocusedMark&&marks.length===0}updated(changed){super.updated(changed);const wasMounting=this.isMounting;if(this.preparedChanged=!1,this.setAttribute("aria-busy",String(this.preparedPending)),!wasMounting&&this.preparedInvalid&&!this.announcedPreparedInvalid&&this.announcements.announceAssertive(this.localize("chartPreparedUnavailable")),this.announcedPreparedInvalid=this.preparedInvalid,this.isMounting=!1,changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}const inputLimit=this.inputLimitMessage(),sampling=this.dataTruncationMessage(),dataTruncation=inputLimit&&sampling?[inputLimit,sampling].join(this.localize("chartSummarySeparator")):inputLimit||sampling;wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus()),(changed.size===0||[...changed.keys()].some(name=>!["selectedIndices","dataTableExpandedOverride","dataTable","dataTableToggle","description","label"].includes(String(name))))&&(this.fitAxisTitles(),this.fitCategoryLabels()),this.syncAxisTitleTargets();const dataChanged=["datasets","labels","type","skipZero","layout","maxRecords","maxSeries"].some(name=>changed.has(name));this.chartSync.update(this.syncGroup,this.preparedModel?.kind!=="series",dataChanged)}fitAxisTitles(){if(!(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length))for(const title of this.svgEl.querySelectorAll('[part="axis-title"]')){const text=Array.from(title.childNodes).find(node=>node.nodeType===3);if(!text)continue;const source=title.getAttribute("aria-label")??"",extent=finiteRange(Number(title.getAttribute("data-title-extent")),0,0,MAX_SCROLL_CONTENT_WIDTH),previous=this.axisTitleFits.get(title);if(!(previous?.source===source&&previous.extent===extent&&previous.display===text.data&&previous.width===title.getComputedTextLength())){if(title.style.removeProperty("opacity"),text.data=source,title.getComputedTextLength()>extent)if(text.data="…",title.getComputedTextLength()>extent)title.style.opacity="0";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=`${source.slice(0,middle)}…`,title.getComputedTextLength()<=extent?lower=middle:upper=middle-1}const last=source.charCodeAt(lower-1);last>=55296&&last<=56319&&(lower-=1),text.data=`${source.slice(0,lower)}…`}this.axisTitleFits.set(title,{source,extent,display:text.data,width:title.getComputedTextLength()})}}}fitOneCategoryLabel(tick,x,anchor,extent){const width=this.fitCategoryBatch([{tick,extent}])[0]??0;return anchor==="start"?x+width:anchor==="end"?x-width:x}fitCategoryBatch(items){const candidates=items.map(({tick,extent})=>{const text=Array.from(tick.childNodes).find(node=>node.nodeType===3),source=tick.getAttribute("data-full-label")??"",bounded=finiteRange(extent,0,0,MAX_SCROLL_CONTENT_WIDTH);return tick.setAttribute("data-label-extent",String(bounded)),text&&(text.data=source),{tick,text,source,bounded,lower:0,upper:source.length,middle:0,overflow:!1}}),fullWidths=candidates.map(item=>item.tick.getComputedTextLength());candidates.forEach((item,index)=>{item.overflow=!!item.text&&fullWidths[index]>item.bounded});let searching=candidates.filter(item=>item.overflow&&item.source.length>1);for(;searching.length;){for(const item of searching)item.middle=Math.ceil((item.lower+item.upper)/2),item.text.data=`${item.source.slice(0,item.middle)}…`;const widths2=searching.map(item=>item.tick.getComputedTextLength());searching.forEach((item,index)=>{widths2[index]<=item.bounded?item.lower=item.middle:item.upper=item.middle-1}),searching=searching.filter(item=>item.lower<item.upper)}for(const item of candidates)if(item.text&&item.overflow){const last=item.source.charCodeAt(item.lower-1);last>=55296&&last<=56319&&item.lower--,item.text.data=item.source.length?`${item.source.slice(0,item.lower)}…`:""}const widths=candidates.map(item=>item.tick.getComputedTextLength());return candidates.forEach((item,index)=>{item.text&&(item.overflow&&widths[index]>item.bounded&&(item.text.data="",widths[index]=0),item.text.data===""&&item.source.length>0?item.tick.setAttribute("role","img"):item.tick.removeAttribute("role"),item.text.data===item.source?item.tick.removeAttribute("aria-label"):item.tick.setAttribute("aria-label",item.source))}),widths}fitCategoryLabels(){if(!this.ownerDocument?.defaultView||!this.isConnected||!this.svgEl?.getClientRects().length)return;const ticks=[...this.svgEl.querySelectorAll('[part="axis-label"][data-full-label]')].filter(tick=>{const hasText=hasCategoryLabelText(tick.getAttribute("data-full-label"));return hasText||(tick.removeAttribute("role"),tick.removeAttribute("aria-label")),hasText}).sort((a,b)=>Number(a.getAttribute("x"))-Number(b.getAttribute("x"))),count=ticks.length;if(count===0)return;const MARGIN=BAR_CORNER_RADIUS,positionOf=tick=>Number(tick.getAttribute("x"))||0,anchorOf=tick=>tick.getAttribute("text-anchor")??"middle",first=ticks[0],last=ticks[count-1],firstIsBoundary=count>1&&anchorOf(first)!=="middle",lastIsBoundary=count>1&&anchorOf(last)!=="middle";let firstRightEdge=positionOf(first),lastLeftEdge=positionOf(last);if(firstIsBoundary&&lastIsBoundary&&count===2){const half=Math.max(0,(positionOf(last)-positionOf(first))/2-MARGIN);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),half),lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),half)}else{if(firstIsBoundary){const gap=positionOf(ticks[1])-positionOf(first);firstRightEdge=this.fitOneCategoryLabel(first,positionOf(first),anchorOf(first),gap-MARGIN)}if(lastIsBoundary){const gap=positionOf(last)-positionOf(ticks[count-2]);lastLeftEdge=this.fitOneCategoryLabel(last,positionOf(last),anchorOf(last),gap-MARGIN)}}const interiors=[];for(let index=0;index<count;index++){if(index===0&&firstIsBoundary||index===count-1&&lastIsBoundary)continue;const tick=ticks[index],x=positionOf(tick),leftAvailable=index===0?MAX_SCROLL_CONTENT_WIDTH:index===1&&firstIsBoundary?x-firstRightEdge:(x-positionOf(ticks[index-1]))/2,rightAvailable=index===count-1?MAX_SCROLL_CONTENT_WIDTH:index===count-2&&lastIsBoundary?lastLeftEdge-x:(positionOf(ticks[index+1])-x)/2,extent=2*Math.min(leftAvailable,rightAvailable)-MARGIN;interiors.push({tick,extent})}this.fitCategoryBatch(interiors)}syncAxisTitleTargets(){if(!this.resizeObserver||!this.svgEl)return;const current=new Set(this.svgEl.querySelectorAll('[part="axis-title"]'));for(const title of this.axisTitleTargets)current.has(title)||this.resizeObserver.unobserve(title);for(const title of current)this.axisTitleTargets.has(title)||this.resizeObserver.observe(title);this.axisTitleTargets=current}queueAxisTitleFit(){const document=this.resizeObserverDocument,window=document?.defaultView;if(!window||this.axisTitleFrame!==void 0)return;const generation=this.resizeObserverGeneration,frame=window.requestAnimationFrame(()=>{this.axisTitleFrame!==frame||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==document||(this.axisTitleFrame=void 0,this.fitAxisTitles())});this.axisTitleFrame=frame}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return this.forcedColorsMemo??=forcedColorsActive(this.ownerDocument?.defaultView)}markPaint(index,series){const color=this.colorFor(index,series);return this.effectiveType==="bar"&&this.forcedColors()?`url(#${this.forcedColorPatternId}-${index})`:color}legendEncoding(index){return this.forcedColors()?forcedColorEncoding(index).name:nothing}markDash(index){if(!this.forcedColors())return nothing;const dash=forcedColorEncoding(index).dash;return dash.length?dash.join(" "):"none"}renderForcedColorPatterns(){if(this.effectiveType!=="bar"||!this.forcedColors())return nothing;const size=8,half=size/2,texture="var(--lr-color-surface)";return svg`<defs>
|
|
4
4
|
${this.recordSample().seriesIndexes.map(index=>{const series=this.displayDatasets[index],encoding=forcedColorEncoding(index).name,shapes=(()=>{switch(encoding){case"horizontal":return svg`<rect y=${half} width=${size} height="1" fill=${texture}></rect>`;case"vertical":return svg`<rect x=${half} width="1" height=${size} fill=${texture}></rect>`;case"diagonal":return svg`<path
|
|
5
5
|
d=${`M${-half},${size} L${half},0 M${half},${size} L${size+half},0`}
|
|
6
6
|
stroke=${texture}
|
|
@@ -9,8 +9,11 @@ export type ChatComposerWrap=LyraTextWrap;
|
|
|
9
9
|
/** Retained name for the shared native `selectionDirection` vocabulary.*/
|
|
10
10
|
export type ChatComposerSelectionDirection=LyraSelectionDirection;
|
|
11
11
|
/** Arrangement of the `start`/`end` action slots relative to the textarea. `'inline'` is today's
|
|
12
|
-
* single flex row; `'stacked'` arranges them as a compact rail beside a multi-row textarea
|
|
13
|
-
|
|
12
|
+
* single flex row; `'stacked'` arranges them as a compact rail beside a multi-row textarea;
|
|
13
|
+
* `'below'` gives the textarea its own full-width line with `start` and `end` on one row under it. */
|
|
14
|
+
export type ChatComposerActionsLayout='inline'|'stacked'|'below';
|
|
15
|
+
/** Placement of caller-supplied toolbar controls inside the composer frame.*/
|
|
16
|
+
export type ChatComposerToolbarPlacement='above'|'actions';export interface LyraChatComposerEventMap{input:InputEvent;change:Event;'lr-invalid':CustomEvent<null>;'lr-input':CustomEvent<{value:string;}>;'lr-change':CustomEvent<{value:string;}>;'lr-stop':CustomEvent<null>;'lr-submit':CustomEvent<{value:string;}>;blur:FocusEvent;focus:FocusEvent;}declare class LyraChatComposerBase extends LyraElement<LyraChatComposerEventMap>{}declare const LyraChatComposer_base:typeof LyraChatComposerBase&(new(...args:any[])=>import("../../../lyra.js").FormAssociatedInterface<string> &import("../../../internal/form-associated.js").FormAssociatedSubclassInterface<string>);
|
|
14
17
|
/**
|
|
15
18
|
* `<lr-chat-composer>` — the message input for a chat/agent conversation
|
|
16
19
|
* surface: an auto-resizing textarea plus a send/stop button. Form-
|
|
@@ -58,8 +61,9 @@ export type ChatComposerActionsLayout='inline'|'stacked';export interface LyraCh
|
|
|
58
61
|
*
|
|
59
62
|
* @customElement lr-chat-composer
|
|
60
63
|
* @slot toolbar - Auxiliary controls (e.g. a model or provider picker) rendered inside the frame,
|
|
61
|
-
* above the chips tray and input row,
|
|
62
|
-
*
|
|
64
|
+
* above the chips tray and input row by default, or between start and end below the textarea
|
|
65
|
+
* with toolbar-placement="actions" and actions-layout="below", sharing `[part="base"]`'s `:focus-within` affordance.
|
|
66
|
+
* @slot start - Content at the logical start of the input/action layout (e.g. an attach-file trigger).
|
|
63
67
|
* @slot chips - An attachment tray rendered above the input row (e.g. files queued for this message).
|
|
64
68
|
* @slot end - Overrides the built-in send/stop button entirely when it has assigned content.
|
|
65
69
|
* @event input - One realm-correct native `InputEvent` relayed from the textarea for each user edit.
|
|
@@ -75,10 +79,11 @@ export type ChatComposerActionsLayout='inline'|'stacked';export interface LyraCh
|
|
|
75
79
|
* @csspart base - The bordered root container. Drops its card chrome (border, background, padding,
|
|
76
80
|
* radius) under `frame="plain"`, where the focus affordance becomes an underline on this same
|
|
77
81
|
* part instead of the border-color shift.
|
|
78
|
-
* @csspart toolbar - The wrapper
|
|
79
|
-
*
|
|
82
|
+
* @csspart toolbar - The toolbar wrapper, above attachments by default or in the bottom action row
|
|
83
|
+
* with toolbar-placement="actions" and actions-layout="below". Hidden entirely when empty.
|
|
80
84
|
* @csspart chips - The wrapper around the `chips` slot. Hidden entirely when the slot is empty.
|
|
81
|
-
* @csspart row - The
|
|
85
|
+
* @csspart row - The input/action layout holding the textarea, start and end, plus the toolbar
|
|
86
|
+
* when toolbar-placement="actions" and actions-layout="below".
|
|
82
87
|
* @csspart start - The wrapper around the `start` slot. Hidden entirely when empty.
|
|
83
88
|
* @csspart textarea - The auto-resizing `<textarea>` itself.
|
|
84
89
|
* @csspart end - The wrapper around the `end` slot and the built-in `action-button`.
|
|
@@ -121,9 +126,19 @@ frame:ChatComposerFrame;private actionsLayoutValue;
|
|
|
121
126
|
* `'inline'` (the default) keeps today's single flex row. `'stacked'` arranges `start` above
|
|
122
127
|
* `end` as a compact rail in one column, beside a `textarea` that spans both rows -- for a
|
|
123
128
|
* multi-row composer where the action buttons would otherwise stretch to the row's full
|
|
124
|
-
* cross-axis height.
|
|
125
|
-
*
|
|
126
|
-
|
|
129
|
+
* cross-axis height. `'below'` puts the `textarea` on its own full-width line and `start` and
|
|
130
|
+
* `end` on one row beneath it (`start` at the inline start, `end` at the inline end, even while
|
|
131
|
+
* `start` is empty) -- the usual phone-width chat input with attach buttons; `min-rows`/
|
|
132
|
+
* `max-rows` growth and inner scrolling are unchanged. Layout only; slot content, empty-slot
|
|
133
|
+
* hiding and the built-in button are unchanged. Invalid direct or attribute values normalize and
|
|
134
|
+
* reflect as `'inline'`. */
|
|
135
|
+
get actionsLayout():ChatComposerActionsLayout;set actionsLayout(next:ChatComposerActionsLayout);private toolbarPlacementValue;
|
|
136
|
+
/** Toolbar position. `'above'` keeps controls above attachments. `'actions'` places them between
|
|
137
|
+
* start and end below the textarea only with `actionsLayout='below'`; other layouts retain the
|
|
138
|
+
* upper toolbar. Invalid or removed values normalize to `'above'`.
|
|
139
|
+
* @default 'above'
|
|
140
|
+
*/
|
|
141
|
+
get toolbarPlacement():ChatComposerToolbarPlacement;set toolbarPlacement(next:ChatComposerToolbarPlacement);private get toolbarInActions();private renderedToolbarInActions;private placementFocusRepair;
|
|
127
142
|
/** Turns off Enter-to-send: plain Enter inserts a newline, as Shift+Enter always does.*/
|
|
128
143
|
withoutEnterSubmit:boolean;
|
|
129
144
|
/** Consumer-controlled validation gate for submission. While idle, disables the built-in Send
|
|
@@ -153,4 +168,4 @@ wrap:ChatComposerWrap;autocomplete:string;inputMode:string;enterKeyHint:string;p
|
|
|
153
168
|
/** The internal native textarea for integrations that require direct DOM access.*/
|
|
154
169
|
get input():HTMLTextAreaElement|null;get selectionStart():number|null;set selectionStart(value:number|null);get selectionEnd():number|null;set selectionEnd(value:number|null);get selectionDirection():ChatComposerSelectionDirection|null;set selectionDirection(value:ChatComposerSelectionDirection|null);focus(options?:FocusOptions):void;blur():void;
|
|
155
170
|
/** Focuses the primary textarea, matching activation of the wrapped native control.*/
|
|
156
|
-
click():void;select():void;setSelectionRange(start:number|null,end:number|null,direction?:ChatComposerSelectionDirection):void;setRangeText(replacement:string):void;setRangeText(replacement:string,start:number,end:number,selectMode?:SelectionMode):void;protected willUpdate(changed:PropertyValues):void;protected firstUpdated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected updated(changed:PropertyValues):void;protected updateValidity():void;formResetCallback():void;private hasSlotted;private resizeTextarea;private armTextareaResizeObserver;private resetTextareaResizeWork;private onTextareaInput;private onTextareaChange;private onTextareaKeyDown;private onActionClick;private submit;private syncToolbarSlot;private syncStartSlot;private onChipsSlotChange;private syncEndSlot;private onTextareaBlur;private onTextareaFocus;private renderActionButton;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chat-composer':LyraChatComposer;}}
|
|
171
|
+
click():void;select():void;setSelectionRange(start:number|null,end:number|null,direction?:ChatComposerSelectionDirection):void;setRangeText(replacement:string):void;setRangeText(replacement:string,start:number,end:number,selectMode?:SelectionMode):void;protected willUpdate(changed:PropertyValues):void;protected firstUpdated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected updated(changed:PropertyValues):void;protected updateValidity():void;formResetCallback():void;private hasSlotted;private resizeTextarea;private armTextareaResizeObserver;private resetTextareaResizeWork;private onTextareaInput;private onTextareaChange;private onTextareaKeyDown;private onActionClick;private submit;private syncToolbarSlot;private syncStartSlot;private onChipsSlotChange;private syncEndSlot;private onTextareaBlur;private onTextareaFocus;private renderActionButton;private renderToolbar;private renderStart;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-chat-composer':LyraChatComposer;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sendIcon,stopIcon}from"../../../internal/icons.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./chat-composer.styles.js";import{normalizeChatComposerStatus}from"./chat-composer-status.js";import{CHAT_COMPOSER_STATUSES,normalizeChatComposerStatus as normalizeChatComposerStatus2}from"./chat-composer-status.js";import{autocorrectConverter,literalSetConverter,normalizeAutocorrect,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{LYRA_DEFAULT_composerLabel,LYRA_DEFAULT_sendMessage,LYRA_DEFAULT_stopGenerating}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const CHAT_COMPOSER_ACTIONS_LAYOUT=literalSetConverter(["inline","stacked"],"inline");class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,styles]}get status(){return this.statusValue}set status(value){const previous=this.statusValue,normalized=normalizeChatComposerStatus(value);this.statusValue=normalized,typeof value=="string"&&value!==normalized&&this.getAttribute("status")!==normalized&&this.setAttribute("status",normalized),this.requestUpdate("status",previous,{reflect:!0,hasChanged:()=>!0})}get actionsLayout(){return this.actionsLayoutValue}set actionsLayout(next){const normalized=CHAT_COMPOSER_ACTIONS_LAYOUT.normalizeReflected(this,"actions-layout",next),previous=this.actionsLayoutValue;previous!==normalized&&(this.actionsLayoutValue=normalized,this.requestUpdate("actionsLayout",previous))}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super(),this.placeholder="",this.minRows=1,this.maxRows=8,this.statusValue="idle",this.frame="card",this.actionsLayoutValue="inline",this.withoutEnterSubmit=!1,this.submitDisabled=!1,this.withoutStop=!1,this.readOnly=!1,this.accessibleLabel=null,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.hasToolbarSlot=!1,this.hasStartSlot=!1,this.hasChipsSlot=!1,this.hasEndSlot=!1,this.touched=!1,this.textareaResizeGeneration=0,this.onTextareaInput=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,this.resizeTextarea(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value})},this.onTextareaChange=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value})},this.onTextareaKeyDown=e=>{e.defaultPrevented||e.key==="Enter"&&(e.shiftKey||this.withoutEnterSubmit||e.isComposing||e.keyCode===229||this.status==="idle"&&(e.preventDefault(),this.submit()))},this.onActionClick=()=>{this.effectiveDisabled||(this.status==="idle"?this.submit():this.withoutStop||this.emit("lr-stop",null))},this.syncToolbarSlot=()=>{this.hasToolbarSlot=this.hasSlotted("toolbar")},this.syncStartSlot=()=>{this.hasStartSlot=this.hasSlotted("start")},this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:!0}).length>0},this.syncEndSlot=()=>{this.hasEndSlot=this.hasSlotted("end")},this.onTextareaBlur=event=>{this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onTextareaFocus=event=>{if(this.effectiveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){this.effectiveDisabled||this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;textarea&&(setNativeRangeText(textarea,replacement,start,end,selectMode),this.value=textarea.value,this.resizeTextarea())}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{this.syncToolbarSlot(),this.syncStartSlot(),this.hasChipsSlot=this.hasSlotted("chips"),this.syncEndSlot()})}firstUpdated(changed){super.firstUpdated(changed),this.resizeTextarea(),this.armTextareaResizeObserver(),this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby")}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.armTextareaResizeObserver(),this.resizeTextarea(),this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby"))}disconnectedCallback(){super.disconnectedCallback(),this.resetTextareaResizeWork(),this.descriptionLease?.release(),this.descriptionLease=void 0}adoptedCallback(){super.adoptedCallback(),this.resetTextareaResizeWork()}updated(changed){super.updated(changed),(changed.has("value")||changed.has("minRows")||changed.has("maxRows"))&&this.resizeTextarea(),(changed.has("minLength")||changed.has("maxLength")||changed.has("readOnly"))&&this.updateValidity()}updateValidity(){if(isBarredFromValidation({effectiveDisabled:this.effectiveDisabled,readonly:this.readOnly},this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const textarea=this.textareaEl;textarea&&textarea.value!==this.value&&(textarea.value=this.value);const own=lengthViolations(this.value,this.minLength,this.maxLength),tooShort=!!textarea?.validity.tooShort||own.tooShort,tooLong=!!textarea?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},textarea?.validationMessage||this.localize("valueInvalid"))}formResetCallback(){super.formResetCallback(),this.touched=!1}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style,lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2,paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom),borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth),minRows=this.effectiveMinRows,maxRows=this.effectiveMaxRows,minHeight=lineHeight*minRows+paddingBlock+borderBlock,maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock,next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`,ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl,ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver||this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta)return;this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf);const handle=ownerWindow.requestAnimationFrame(()=>{this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||(this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0,this.resizeTextarea())});this.textareaResizeRaf=handle,this.textareaResizeRafOwner=ownerWindow,this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer,this.textareaResizeObserverDocument=ownerDocument,this.textareaResizeObserverTarget=ta,observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1,this.textareaResizeObserver?.disconnect(),this.textareaResizeObserver=void 0,this.textareaResizeObserverDocument=void 0,this.textareaResizeObserverTarget=void 0,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf),this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0}submit(){this.submitDisabled||this.effectiveDisabled||this.status!=="idle"||this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle",showStop=busy&&!this.withoutStop;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sendIcon,stopIcon}from"../../../internal/icons.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./chat-composer.styles.js";import{normalizeChatComposerStatus}from"./chat-composer-status.js";import{CHAT_COMPOSER_STATUSES,normalizeChatComposerStatus as normalizeChatComposerStatus2}from"./chat-composer-status.js";import{autocorrectConverter,literalSetConverter,normalizeAutocorrect,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{LYRA_DEFAULT_composerLabel,LYRA_DEFAULT_sendMessage,LYRA_DEFAULT_stopGenerating}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const CHAT_COMPOSER_ACTIONS_LAYOUT=literalSetConverter(["inline","stacked","below"],"inline"),CHAT_COMPOSER_TOOLBAR_PLACEMENT=literalSetConverter(["above","actions"],"above");class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,styles]}get status(){return this.statusValue}set status(value){const previous=this.statusValue,normalized=normalizeChatComposerStatus(value);this.statusValue=normalized,typeof value=="string"&&value!==normalized&&this.getAttribute("status")!==normalized&&this.setAttribute("status",normalized),this.requestUpdate("status",previous,{reflect:!0,hasChanged:()=>!0})}get actionsLayout(){return this.actionsLayoutValue}set actionsLayout(next){const normalized=CHAT_COMPOSER_ACTIONS_LAYOUT.normalizeReflected(this,"actions-layout",next),previous=this.actionsLayoutValue;previous!==normalized&&(this.actionsLayoutValue=normalized,this.requestUpdate("actionsLayout",previous))}get toolbarPlacement(){return this.toolbarPlacementValue}set toolbarPlacement(next){const normalized=CHAT_COMPOSER_TOOLBAR_PLACEMENT.normalizeReflected(this,"toolbar-placement",next);this.hasUpdated&&!this.hasAttribute("toolbar-placement")&&this.setAttribute("toolbar-placement",normalized);const previous=this.toolbarPlacementValue;previous!==normalized&&(this.toolbarPlacementValue=normalized,this.requestUpdate("toolbarPlacement",previous))}get toolbarInActions(){return this.actionsLayout==="below"&&this.toolbarPlacement==="actions"}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super(),this.placeholder="",this.minRows=1,this.maxRows=8,this.statusValue="idle",this.frame="card",this.actionsLayoutValue="inline",this.toolbarPlacementValue="above",this.renderedToolbarInActions=!1,this.placementFocusRepair=null,this.withoutEnterSubmit=!1,this.submitDisabled=!1,this.withoutStop=!1,this.readOnly=!1,this.accessibleLabel=null,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.wrap="soft",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.hasToolbarSlot=!1,this.hasStartSlot=!1,this.hasChipsSlot=!1,this.hasEndSlot=!1,this.touched=!1,this.textareaResizeGeneration=0,this.onTextareaInput=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,this.resizeTextarea(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value})},this.onTextareaChange=event=>{if(this.effectiveDisabled||this.readOnly){event.stopPropagation();return}this.value=event.target.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value})},this.onTextareaKeyDown=e=>{e.defaultPrevented||e.key==="Enter"&&(e.shiftKey||this.withoutEnterSubmit||e.isComposing||e.keyCode===229||this.status==="idle"&&(e.preventDefault(),this.submit()))},this.onActionClick=()=>{this.effectiveDisabled||(this.status==="idle"?this.submit():this.withoutStop||this.emit("lr-stop",null))},this.syncToolbarSlot=()=>{this.hasToolbarSlot=this.hasSlotted("toolbar")},this.syncStartSlot=()=>{this.hasStartSlot=this.hasSlotted("start")},this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:!0}).length>0},this.syncEndSlot=()=>{this.hasEndSlot=this.hasSlotted("end")},this.onTextareaBlur=event=>{this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onTextareaFocus=event=>{if(this.effectiveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.requestUpdate("toolbarPlacement",void 0),this.addEventListener("invalid",()=>{this.touched=!0})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){this.textareaEl&&(this.textareaEl.selectionStart=value??0)}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){this.textareaEl&&(this.textareaEl.selectionEnd=value??0)}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){this.textareaEl&&(this.textareaEl.selectionDirection=value??"none")}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){this.effectiveDisabled||this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;textarea&&(setNativeRangeText(textarea,replacement,start,end,selectMode),this.value=textarea.value,this.resizeTextarea())}willUpdate(changed){if(super.willUpdate(changed),this.hasUpdated&&this.toolbarInActions!==this.renderedToolbarInActions){const active=deepActiveElementIn(this.ownerDocument);if(isHtmlElement(active)){for(const wrapper of this.renderRoot.querySelectorAll('[part="start"], [part="toolbar"]'))if(this.placementFocusRepair=captureComposedFocusRepair(wrapper,active),this.placementFocusRepair)break}}this.seedFirstRenderState(()=>{this.syncToolbarSlot(),this.syncStartSlot(),this.hasChipsSlot=this.hasSlotted("chips"),this.syncEndSlot()})}firstUpdated(changed){super.firstUpdated(changed),this.resizeTextarea(),this.armTextareaResizeObserver(),this.isConnected&&(this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby"))}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.armTextareaResizeObserver(),this.resizeTextarea(),this.descriptionLease??=acquireResolvedAriaRelationship(this,this.input,"aria-describedby"))}disconnectedCallback(){super.disconnectedCallback(),this.resetTextareaResizeWork(),this.placementFocusRepair=null,this.descriptionLease?.release(),this.descriptionLease=void 0}adoptedCallback(){super.adoptedCallback(),this.resetTextareaResizeWork()}updated(changed){super.updated(changed),this.renderedToolbarInActions=this.toolbarInActions;const repair=this.placementFocusRepair;this.placementFocusRepair=null,repair&&this.isConnected&&applyComposedFocusRepair(repair),(changed.has("value")||changed.has("minRows")||changed.has("maxRows"))&&this.resizeTextarea(),(changed.has("minLength")||changed.has("maxLength")||changed.has("readOnly"))&&this.updateValidity()}updateValidity(){if(isBarredFromValidation({effectiveDisabled:this.effectiveDisabled,readonly:this.readOnly},this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const textarea=this.textareaEl;textarea&&textarea.value!==this.value&&(textarea.value=this.value);const own=lengthViolations(this.value,this.minLength,this.maxLength),tooShort=!!textarea?.validity.tooShort||own.tooShort,tooLong=!!textarea?.validity.tooLong||own.tooLong;if(!tooShort&&!tooLong){this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({tooShort,tooLong},textarea?.validationMessage||this.localize("valueInvalid"))}formResetCallback(){super.formResetCallback(),this.touched=!1}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style,lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2,paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom),borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth),minRows=this.effectiveMinRows,maxRows=this.effectiveMaxRows,minHeight=lineHeight*minRows+paddingBlock+borderBlock,maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock,next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`,ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl,ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver||this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta)return;this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument)return;const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf);const handle=ownerWindow.requestAnimationFrame(()=>{this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||(this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0,this.resizeTextarea())});this.textareaResizeRaf=handle,this.textareaResizeRafOwner=ownerWindow,this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer,this.textareaResizeObserverDocument=ownerDocument,this.textareaResizeObserverTarget=ta,observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1,this.textareaResizeObserver?.disconnect(),this.textareaResizeObserver=void 0,this.textareaResizeObserverDocument=void 0,this.textareaResizeObserverTarget=void 0,this.textareaResizeRaf!==void 0&&this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf),this.textareaResizeRaf=void 0,this.textareaResizeRafOwner=void 0,this.textareaResizeRafDocument=void 0}submit(){this.submitDisabled||this.effectiveDisabled||this.status!=="idle"||this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle",showStop=busy&&!this.withoutStop;return html`
|
|
2
2
|
<button
|
|
3
3
|
part="action-button"
|
|
4
4
|
type="button"
|
|
@@ -10,18 +10,18 @@ import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribu
|
|
|
10
10
|
${showStop?stopIcon():sendIcon()}
|
|
11
11
|
</span>
|
|
12
12
|
</button>
|
|
13
|
-
`}
|
|
13
|
+
`}renderToolbar(){return html`<div part="toolbar" ?hidden=${!this.hasToolbarSlot}>
|
|
14
|
+
<slot name="toolbar" @slotchange=${this.syncToolbarSlot}></slot>
|
|
15
|
+
</div>`}renderStart(){return html`<span part="start" ?hidden=${!this.hasStartSlot}>
|
|
16
|
+
<slot name="start" @slotchange=${this.syncStartSlot}></slot>
|
|
17
|
+
</span>`}render(){return html`
|
|
14
18
|
<div part="base">
|
|
15
|
-
|
|
16
|
-
<slot name="toolbar" @slotchange=${this.syncToolbarSlot}></slot>
|
|
17
|
-
</div>
|
|
19
|
+
${this.toolbarInActions?nothing:this.renderToolbar()}
|
|
18
20
|
<div part="chips" ?hidden=${!this.hasChipsSlot}>
|
|
19
21
|
<slot name="chips" @slotchange=${this.onChipsSlotChange}></slot>
|
|
20
22
|
</div>
|
|
21
23
|
<div part="row">
|
|
22
|
-
|
|
23
|
-
<slot name="start" @slotchange=${this.syncStartSlot}></slot>
|
|
24
|
-
</span>
|
|
24
|
+
${this.toolbarInActions?nothing:this.renderStart()}
|
|
25
25
|
<textarea
|
|
26
26
|
part="textarea"
|
|
27
27
|
aria-label=${this.accessibleLabel??(this.placeholder||this.localize("composerLabel"))}
|
|
@@ -48,10 +48,12 @@ import{__decorate}from"tslib";import{setNativeRangeText,nativeAutocorrectAttribu
|
|
|
48
48
|
@focus=${this.onTextareaFocus}
|
|
49
49
|
@blur=${this.onTextareaBlur}
|
|
50
50
|
></textarea>
|
|
51
|
+
${this.toolbarInActions?this.renderStart():nothing}
|
|
52
|
+
${this.toolbarInActions?this.renderToolbar():nothing}
|
|
51
53
|
<span part="end">
|
|
52
54
|
<slot name="end" @slotchange=${this.syncEndSlot}></slot>
|
|
53
55
|
${this.hasEndSlot?nothing:this.renderActionButton()}
|
|
54
56
|
</span>
|
|
55
57
|
</div>
|
|
56
58
|
</div>
|
|
57
|
-
`}}__decorate([property()],LyraChatComposer.prototype,"placeholder",void 0),__decorate([property({type:Number,attribute:"min-rows"})],LyraChatComposer.prototype,"minRows",void 0),__decorate([property({type:Number,attribute:"max-rows"})],LyraChatComposer.prototype,"maxRows",void 0),__decorate([property({reflect:!0})],LyraChatComposer.prototype,"status",null),__decorate([property({reflect:!0})],LyraChatComposer.prototype,"frame",void 0),__decorate([property({reflect:!0,attribute:"actions-layout",converter:CHAT_COMPOSER_ACTIONS_LAYOUT})],LyraChatComposer.prototype,"actionsLayout",null),__decorate([property({type:Boolean,reflect:!0,attribute:"without-enter-submit"})],LyraChatComposer.prototype,"withoutEnterSubmit",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"submit-disabled"})],LyraChatComposer.prototype,"submitDisabled",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"without-stop"})],LyraChatComposer.prototype,"withoutStop",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"readonly"})],LyraChatComposer.prototype,"readOnly",void 0),__decorate([property({converter:lengthLimitConverter,attribute:"minlength"})],LyraChatComposer.prototype,"minLength",void 0),__decorate([property({converter:lengthLimitConverter,attribute:"maxlength"})],LyraChatComposer.prototype,"maxLength",void 0),__decorate([property({attribute:"aria-label"})],LyraChatComposer.prototype,"accessibleLabel",void 0),__decorate([property({converter:trueDefaultBooleanConverter})],LyraChatComposer.prototype,"spellcheck",void 0),__decorate([property()],LyraChatComposer.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraChatComposer.prototype,"autocorrect",null),__decorate([property()],LyraChatComposer.prototype,"wrap",void 0),__decorate([property()],LyraChatComposer.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraChatComposer.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraChatComposer.prototype,"enterKeyHint",void 0),__decorate([state()],LyraChatComposer.prototype,"hasToolbarSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"hasStartSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"hasChipsSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"hasEndSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"touched",void 0),__decorate([query("textarea")],LyraChatComposer.prototype,"textareaEl",void 0);export{CHAT_COMPOSER_STATUSES,LyraChatComposer,normalizeChatComposerStatus2 as normalizeChatComposerStatus};
|
|
59
|
+
`}}__decorate([property()],LyraChatComposer.prototype,"placeholder",void 0),__decorate([property({type:Number,attribute:"min-rows"})],LyraChatComposer.prototype,"minRows",void 0),__decorate([property({type:Number,attribute:"max-rows"})],LyraChatComposer.prototype,"maxRows",void 0),__decorate([property({reflect:!0})],LyraChatComposer.prototype,"status",null),__decorate([property({reflect:!0})],LyraChatComposer.prototype,"frame",void 0),__decorate([property({reflect:!0,attribute:"actions-layout",converter:CHAT_COMPOSER_ACTIONS_LAYOUT})],LyraChatComposer.prototype,"actionsLayout",null),__decorate([property({reflect:!0,attribute:"toolbar-placement",converter:CHAT_COMPOSER_TOOLBAR_PLACEMENT})],LyraChatComposer.prototype,"toolbarPlacement",null),__decorate([property({type:Boolean,reflect:!0,attribute:"without-enter-submit"})],LyraChatComposer.prototype,"withoutEnterSubmit",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"submit-disabled"})],LyraChatComposer.prototype,"submitDisabled",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"without-stop"})],LyraChatComposer.prototype,"withoutStop",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"readonly"})],LyraChatComposer.prototype,"readOnly",void 0),__decorate([property({converter:lengthLimitConverter,attribute:"minlength"})],LyraChatComposer.prototype,"minLength",void 0),__decorate([property({converter:lengthLimitConverter,attribute:"maxlength"})],LyraChatComposer.prototype,"maxLength",void 0),__decorate([property({attribute:"aria-label"})],LyraChatComposer.prototype,"accessibleLabel",void 0),__decorate([property({converter:trueDefaultBooleanConverter})],LyraChatComposer.prototype,"spellcheck",void 0),__decorate([property()],LyraChatComposer.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraChatComposer.prototype,"autocorrect",null),__decorate([property()],LyraChatComposer.prototype,"wrap",void 0),__decorate([property()],LyraChatComposer.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraChatComposer.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraChatComposer.prototype,"enterKeyHint",void 0),__decorate([state()],LyraChatComposer.prototype,"hasToolbarSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"hasStartSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"hasChipsSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"hasEndSlot",void 0),__decorate([state()],LyraChatComposer.prototype,"touched",void 0),__decorate([query("textarea")],LyraChatComposer.prototype,"textareaEl",void 0);export{CHAT_COMPOSER_STATUSES,LyraChatComposer,normalizeChatComposerStatus2 as normalizeChatComposerStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-chat-composer-gap, var(--lr-space-xs)); box-sizing: border-box; border: var(--lr-border-width-thin) solid var(--lr-chat-composer-border-color, var(--lr-color-border)); border-radius: var(--lr-chat-composer-radius, var(--lr-radius)); background: var(--lr-chat-composer-bg, var(--lr-color-surface)); padding: var(--lr-chat-composer-padding, var(--lr-space-s)); transition: border-color var(--lr-transition-fast); } [part='base']:focus-within { border-color: var(--lr-color-brand); } :host([frame='plain']) [part='base'] { padding: 0; border: 0; border-radius: 0; background: transparent; } :host([frame='plain']) [part='base']:focus-within { box-shadow: var( --lr-chat-composer-focus-shadow, inset 0 calc(-1 * var(--lr-focus-ring-width)) 0 0 var(--lr-focus-ring-color) ); } :host(:disabled) [part='base'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='toolbar'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); } [part='toolbar'][hidden] { display: none; } [part='chips'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='chips'][hidden] { display: none; } [part='row'] { display: flex; align-items: flex-end; gap: var(--lr-space-s); } [part='start'] { display: flex; flex: 0 0 auto; align-items: center; padding-block-end: var(--lr-space-xs); } [part='start'][hidden] { display: none; } [part='textarea'] { flex: 1 1 auto; min-inline-size: 0; box-sizing: border-box; resize: none; border: none; outline: none; background: transparent; color: inherit; font: inherit; line-height: var(--lr-line-height-normal); padding-block: var(--lr-space-xs); overflow-x: hidden; overflow-y: hidden; } [part='textarea'][wrap='off'] { overflow-x: auto; } [part='textarea']::placeholder { color: var(--lr-color-text-quiet); } [part='textarea']:disabled { cursor: not-allowed; } [part='end'] { display: flex; flex: 0 0 auto; align-items: center; gap: var(--lr-space-xs); } :host([actions-layout='stacked']) [part='row'] { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; align-items: stretch; } :host([actions-layout='stacked']) [part='start'] { grid-column: 1; grid-row: 1; padding-block-end: 0; } :host([actions-layout='stacked']) [part='textarea'] { grid-column: 2; grid-row: 1 / span 2; } :host([actions-layout='stacked']) [part='end'] { grid-column: 1; grid-row: 2; } [part='action-button'] { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; box-sizing: border-box; ${iconHitTarget} border: none; border-radius: var(--lr-radius); background: var(--lr-color-brand); color: var(--lr-color-on-brand); font-size: var(--lr-font-size-lg); line-height: var(--lr-line-height-none); cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-hover)); } :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='action-button']:focus-visible { ${focusRing} } [part='action-button']:disabled { cursor: not-allowed; opacity: var(--lr-opacity-disabled); } [part='send-glyph'], [part='stop-glyph'] { display: inline-flex; } :host(:dir(rtl)) [part='send-glyph'] { transform: scaleX(-1); } :host([status='sending']) [part='action-button'], :host([status='streaming']) [part='action-button'] { background: var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)); } :host([status='sending']) :where([part='action-button']):hover:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ); } :host([status='sending']) :where([part='action-button']):active:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } @media (prefers-reduced-motion: reduce) { [part='base'], [part='action-button'] { transition: none !important; } } `;export{styles};
|
|
1
|
+
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-chat-composer-gap, var(--lr-space-xs)); box-sizing: border-box; border: var(--lr-border-width-thin) solid var(--lr-chat-composer-border-color, var(--lr-color-border)); border-radius: var(--lr-chat-composer-radius, var(--lr-radius)); background: var(--lr-chat-composer-bg, var(--lr-color-surface)); padding: var(--lr-chat-composer-padding, var(--lr-space-s)); transition: border-color var(--lr-transition-fast); } [part='base']:focus-within { border-color: var(--lr-color-brand); } :host([frame='plain']) [part='base'] { padding: 0; border: 0; border-radius: 0; background: transparent; } :host([frame='plain']) [part='base']:focus-within { box-shadow: var( --lr-chat-composer-focus-shadow, inset 0 calc(-1 * var(--lr-focus-ring-width)) 0 0 var(--lr-focus-ring-color) ); } :host(:disabled) [part='base'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='toolbar'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); } [part='toolbar'][hidden] { display: none; } [part='chips'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='chips'][hidden] { display: none; } [part='row'] { display: flex; align-items: flex-end; gap: var(--lr-space-s); } [part='start'] { display: flex; flex: 0 0 auto; align-items: center; padding-block-end: var(--lr-space-xs); } [part='start'][hidden] { display: none; } [part='textarea'] { flex: 1 1 auto; min-inline-size: 0; box-sizing: border-box; resize: none; border: none; outline: none; background: transparent; color: inherit; font: inherit; line-height: var(--lr-line-height-normal); padding-block: var(--lr-space-xs); overflow-x: hidden; overflow-y: hidden; } [part='textarea'][wrap='off'] { overflow-x: auto; } [part='textarea']::placeholder { color: var(--lr-color-text-quiet); } [part='textarea']:disabled { cursor: not-allowed; } [part='end'] { display: flex; flex: 0 0 auto; align-items: center; gap: var(--lr-space-xs); } :host([actions-layout='stacked']) [part='row'] { display: grid; grid-template-columns: auto minmax(0, 1fr); grid-template-rows: auto auto; align-items: stretch; } :host([actions-layout='stacked']) [part='start'] { grid-column: 1; grid-row: 1; padding-block-end: 0; } :host([actions-layout='stacked']) [part='textarea'] { grid-column: 2; grid-row: 1 / span 2; } :host([actions-layout='stacked']) [part='end'] { grid-column: 1; grid-row: 2; } :host([actions-layout='below']) [part='row'] { display: grid; grid-template-columns: minmax(0, 1fr) auto; grid-template-rows: auto auto; align-items: center; } :host([actions-layout='below']) [part='textarea'] { grid-column: 1 / -1; grid-row: 1; } :host([actions-layout='below']) [part='start'] { grid-column: 1; grid-row: 2; justify-self: start; padding-block-end: 0; } :host([actions-layout='below']) [part='end'] { grid-column: 2; grid-row: 2; } :host([actions-layout='below'][toolbar-placement='actions']) [part='row'] { grid-template-columns: auto minmax(0, 1fr) auto; column-gap: 0; } :host([actions-layout='below'][toolbar-placement='actions']) [part='start'], :host([actions-layout='below'][toolbar-placement='actions']) [part='toolbar'] { margin-inline-end: var(--lr-space-s); } :host([actions-layout='below'][toolbar-placement='actions']) [part='toolbar'] { grid-column: 2; grid-row: 2; min-inline-size: 0; max-inline-size: 100%; overflow: auto; } :host([actions-layout='below'][toolbar-placement='actions']) [part='end'] { grid-column: 3; } [part='action-button'] { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto; box-sizing: border-box; ${iconHitTarget} border: none; border-radius: var(--lr-radius); background: var(--lr-color-brand); color: var(--lr-color-on-brand); font-size: var(--lr-font-size-lg); line-height: var(--lr-line-height-none); cursor: pointer; transition: background-color var(--lr-transition-fast); } :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-hover)); } :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-brand), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='action-button']:focus-visible { ${focusRing} } [part='action-button']:disabled { cursor: not-allowed; opacity: var(--lr-opacity-disabled); } [part='send-glyph'], [part='stop-glyph'] { display: inline-flex; } :host(:dir(rtl)) [part='send-glyph'] { transform: scaleX(-1); } :host([status='sending']) [part='action-button'], :host([status='streaming']) [part='action-button'] { background: var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)); } :host([status='sending']) :where([part='action-button']):hover:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):hover:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-hover) ); } :host([status='sending']) :where([part='action-button']):active:where(:not(:disabled)), :host([status='streaming']) :where([part='action-button']):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-chat-composer-busy-bg, var(--lr-color-text-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } @media (prefers-reduced-motion: reduce) { [part='base'], [part='action-button'] { transition: none !important; } } `;export{styles};
|
|
@@ -4,6 +4,9 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
4
4
|
export type ChatMessageActionsPlacement=ChatMessageActionsPosition;
|
|
5
5
|
/** Where `<lr-chat-message>`'s `attachments` slot renders relative to the message body.*/
|
|
6
6
|
export type ChatMessageAttachmentsPlacement='before'|'after';
|
|
7
|
+
/** Where `<lr-chat-message>`'s `avatar` slot renders: in the header row above the body (`'top'`),
|
|
8
|
+
* or in its own column beside the body at the inline start (`'start'`) or end (`'end'`). */
|
|
9
|
+
export type ChatMessageAvatarPlacement='top'|'start'|'end';
|
|
7
10
|
/** `lr-toggle-request`/`lr-toggle` detail of `<lr-chat-message>`.*/
|
|
8
11
|
export interface ChatMessageToggleDetail{
|
|
9
12
|
/** Whether the message body is shown in the resulting (on `lr-toggle-request`, the proposed)
|
|
@@ -38,7 +41,9 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
|
|
|
38
41
|
* `failure` slot has content, in which case this internal announcement is
|
|
39
42
|
* skipped: the host's own `role="alert"` failure content is expected to
|
|
40
43
|
* announce itself, and firing both would double-announce the same failure
|
|
41
|
-
* with two different (and differently specific) messages.
|
|
44
|
+
* with two different (and differently specific) messages. `announce-status="false"` turns both
|
|
45
|
+
* built-in announcements off for an application that announces replies itself; the visible status
|
|
46
|
+
* text is unaffected.
|
|
42
47
|
*
|
|
43
48
|
* `messageRole` identifies the author (`user`/`assistant`/`system`, matching
|
|
44
49
|
* the vocabulary of chat/completion APIs). The platform `role` property remains available for
|
|
@@ -48,6 +53,12 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
|
|
|
48
53
|
* `actions-placement="outside"` renders the `actions` slot as a sibling immediately after the
|
|
49
54
|
* message bubble instead of nested inside the footer.
|
|
50
55
|
*
|
|
56
|
+
* `avatar-placement="start"` (or `"end"`) moves the `avatar` slot out of the header row into its own
|
|
57
|
+
* column beside the body; badges and the collapse toggle stay in the header. Combine it with
|
|
58
|
+
* `--lr-chat-message-bubble-border-width: 0` and a transparent `--lr-chat-message-bubble-bg` for a
|
|
59
|
+
* plain-text message with a side avatar. Set `--lr-chat-message-width: fit-content` to size each
|
|
60
|
+
* bubble to its content (up to `--lr-chat-message-max-width`) while it stays on its role's side.
|
|
61
|
+
*
|
|
51
62
|
* @customElement lr-chat-message
|
|
52
63
|
* @slot - The message body.
|
|
53
64
|
* @slot avatar - An avatar/icon for the message author.
|
|
@@ -76,7 +87,7 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
|
|
|
76
87
|
* @event lr-toggle - Collapse state committed. `detail: { expanded }` carries the resulting state.
|
|
77
88
|
* @csspart bubble - The message article and bubble root. Programmatically focusable (`tabindex="-1"`) so focus has a stable place to land when the built-in retry button is removed. Its fill, text, and geometry derive from the documented theme hooks.
|
|
78
89
|
* @csspart header - The row above the message body — avatar, badges, and the collapse toggle. Hidden entirely when none of those have anything to show.
|
|
79
|
-
* @csspart avatar - The wrapper around the `avatar` slot.
|
|
90
|
+
* @csspart avatar - The wrapper around the `avatar` slot. Inside `header` by default; a column of `bubble` beside the body when `avatar-placement` is `start` or `end`.
|
|
80
91
|
* @csspart badges - The wrapper around the `badges` slot.
|
|
81
92
|
* @csspart collapse-button - The built-in collapse/expand toggle (only rendered when `collapsible`).
|
|
82
93
|
* @csspart body - The wrapper around the default slot (the message content). Hidden while `collapsed`.
|
|
@@ -91,6 +102,10 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
|
|
|
91
102
|
* @csspart retry-button - The built-in retry button (only rendered when `status="failed"`).
|
|
92
103
|
* @csspart actions - The wrapper around the `actions` slot. Rendered inside the footer by default; a sibling immediately after `bubble` when `actions-placement="outside"`.
|
|
93
104
|
* @cssprop [--lr-chat-message-max-width=80%] - Maximum inline size of the message bubble.
|
|
105
|
+
* @cssprop [--lr-chat-message-width=auto] - Inline size of the message bubble. `fit-content` shrinks the bubble to its content, capped by `--lr-chat-message-max-width`, while it stays aligned to its role's side.
|
|
106
|
+
* @cssprop [--lr-chat-message-bubble-border-width=var(--lr-border-width-thin)] - Bubble border width for every role and status; `0` removes the border.
|
|
107
|
+
* @cssprop [--lr-chat-message-bubble-border-color=var(--lr-color-border-subtle)] - Bubble border color for every role except `user`.
|
|
108
|
+
* @cssprop [--lr-chat-message-user-bubble-border-color=transparent] - Bubble border color for `message-role="user"`.
|
|
94
109
|
* @cssprop [--lr-chat-message-bubble-bg=var(--lr-color-surface)] - Bubble fill for every role except `user`.
|
|
95
110
|
* @cssprop [--lr-chat-message-bubble-color=var(--lr-color-text)] - Bubble text color for every role except `user`.
|
|
96
111
|
* @cssprop [--lr-chat-message-user-bubble-bg=var(--lr-color-brand-quiet)] - Bubble fill for `message-role="user"`.
|
|
@@ -99,6 +114,7 @@ expanded:boolean;}export interface LyraChatMessageEventMap{'lr-message-retry':Cu
|
|
|
99
114
|
* @cssprop [--lr-chat-message-streaming-border-color=var(--lr-color-brand)] - Streaming bubble border.
|
|
100
115
|
* @cssprop [--lr-chat-message-failed-border-color=var(--lr-color-danger)] - Failed bubble border.
|
|
101
116
|
* @cssprop [--lr-chat-message-failed-bg=var(--lr-color-danger-quiet)] - Failed bubble fill.
|
|
117
|
+
* @cssprop [--lr-chat-message-failed-color=var(--lr-color-text)] - Failed bubble text color, for every role; pairs with `--lr-chat-message-failed-bg` so the role text color never lands on the failed fill.
|
|
102
118
|
* @cssprop [--lr-chat-message-footer-color=var(--lr-color-text-quiet)] - Default footer text.
|
|
103
119
|
* @cssprop [--lr-chat-message-user-footer-color=var(--lr-color-text)] - User-message footer text.
|
|
104
120
|
* @cssprop [--lr-chat-message-failed-footer-color=var(--lr-color-danger)] - Failed-message footer text.
|
|
@@ -140,7 +156,15 @@ collapsed:boolean;
|
|
|
140
156
|
* always matches what's on screen. */
|
|
141
157
|
attachmentsPlacement:ChatMessageAttachmentsPlacement;
|
|
142
158
|
/** Where the actions row renders relative to the bubble.*/
|
|
143
|
-
actionsPlacement:ChatMessageActionsPlacement;
|
|
159
|
+
actionsPlacement:ChatMessageActionsPlacement;
|
|
160
|
+
/** Where the `avatar` slot renders. `'top'` (the default) keeps it in the header row above the
|
|
161
|
+
* body; `'start'`/`'end'` lay it beside the body at the inline start/end, mirroring under RTL.
|
|
162
|
+
* Any other value behaves as `'top'`. */
|
|
163
|
+
avatarPlacement:ChatMessageAvatarPlacement;
|
|
164
|
+
/** Whether status transitions are announced through the shared live region (the failure and
|
|
165
|
+
* streaming-complete announcements described above). `announce-status="false"` silences both
|
|
166
|
+
* while keeping the visible status text, for an application that announces replies itself. */
|
|
167
|
+
announceStatus:boolean;private hasAvatarSlot;private hasBadgesSlot;private hasAttachmentsSlot;private hasActionsSlot;private hasFailureSlot;private politeSink?;private assertiveSink?;private bubbleEl?;private readonly bodyId;private _status;private previousStatus;private isMounting;private statusAtDisconnect?;
|
|
144
168
|
/** Delivery/generation state. Drives the footer's status dot/text and,
|
|
145
169
|
* for `"failed"`, the bubble's danger treatment and the built-in retry
|
|
146
170
|
* button. Declared via `static properties` above with a hand-written
|
|
@@ -1,18 +1,12 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,retryIcon}from"../../../internal/icons.js";import{formatTimeOfDay}from"../../../internal/intl-cache.js";import{literalSetConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{styles}from"./chat-message.styles.js";import{LYRA_DEFAULT_chatCompleteAnnounce,LYRA_DEFAULT_chatFailedAnnounce,LYRA_DEFAULT_chatFailedToSend,LYRA_DEFAULT_chatResponding,LYRA_DEFAULT_chatSending,LYRA_DEFAULT_collapseMessage,LYRA_DEFAULT_expandMessage}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_promptStudioRoleAssistant,LYRA_DEFAULT_promptStudioRoleSystem,LYRA_DEFAULT_promptStudioRoleUser,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const STATUS_TEXT_KEY={sending:"chatSending",streaming:"chatResponding",failed:"chatFailedToSend"},CHAT_MESSAGE_STATUS=literalSetConverter(["sending","sent","failed","streaming"],"sent");class LyraChatMessage extends LyraElement{constructor(){super(...arguments),this.messageRole="assistant",this.messageId="",this.collapsible=!1,this.collapsed=!1,this.attachmentsPlacement="after",this.actionsPlacement="inside",this.hasAvatarSlot=!1,this.hasBadgesSlot=!1,this.hasAttachmentsSlot=!1,this.hasActionsSlot=!1,this.hasFailureSlot=!1,this.bodyId=nextId("chat-message-body"),this._status="sent",this.previousStatus="sent",this.isMounting=!0,this.onAvatarSlotChange=()=>{this.hasAvatarSlot=this.hasSlotted("avatar")},this.onBadgesSlotChange=()=>{this.hasBadgesSlot=this.hasSlotted("badges")},this.onAttachmentsSlotChange=()=>{this.hasAttachmentsSlot=this.hasSlotted("attachments")},this.onActionsSlotChange=()=>{this.hasActionsSlot=this.hasSlotted("actions")},this.onFailureSlotChange=()=>{this.hasFailureSlot=this.hasSlotted("failure")},this.toggleCollapsed=()=>{const detail={expanded:this.collapsed};requestThenCommit({requestDetail:detail,emitRequest:(requestDetail,init)=>this.emit("lr-toggle-request",requestDetail,init),commit:()=>{this.collapsed=!detail.expanded,this.emit("lr-toggle",detail)}})},this.onRetryClick=()=>{this.emit("lr-message-retry",{messageId:this.messageId||void 0}),this.status!=="failed"&&this.bubbleEl?.focus()}}static{this.defaultStrings={...super.defaultStrings,chatCompleteAnnounce:LYRA_DEFAULT_chatCompleteAnnounce,chatFailedAnnounce:LYRA_DEFAULT_chatFailedAnnounce,chatFailedToSend:LYRA_DEFAULT_chatFailedToSend,chatResponding:LYRA_DEFAULT_chatResponding,chatSending:LYRA_DEFAULT_chatSending,collapse:LYRA_DEFAULT_collapse,collapseMessage:LYRA_DEFAULT_collapseMessage,details:LYRA_DEFAULT_details,expandMessage:LYRA_DEFAULT_expandMessage,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,promptStudioRoleAssistant:LYRA_DEFAULT_promptStudioRoleAssistant,promptStudioRoleSystem:LYRA_DEFAULT_promptStudioRoleSystem,promptStudioRoleUser:LYRA_DEFAULT_promptStudioRoleUser,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={status:{reflect:!0,noAccessor:!0,converter:CHAT_MESSAGE_STATUS}}}get status(){return this._status}set status(value){const normalized=CHAT_MESSAGE_STATUS.normalizeReflected(this,"status",value),old=this._status;normalized!==old&&(this.previousStatus=old,this._status=normalized,this.requestUpdate("status",old))}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?changed.has("status")&&(this.status==="failed"?this.hasFailureSlot=this.hasSlotted("failure"):this.previousStatus==="failed"&&this.hasFailureSlot&&this.isFocusWithinFailureSlot()&&this.bubbleEl?.focus()):(this.hasAvatarSlot=this.hasSlotted("avatar"),this.hasBadgesSlot=this.hasSlotted("badges"),this.hasAttachmentsSlot=this.hasSlotted("attachments"),this.hasActionsSlot=this.hasSlotted("actions"),this.status==="failed"&&(this.hasFailureSlot=this.hasSlotted("failure")))}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("status")&&this.announceStatusChange(this.previousStatus)}connectedCallback(){super.connectedCallback(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.statusAtDisconnect!==void 0&&(this.isMounting=this.status!==this.statusAtDisconnect&&this.isUpdatePending,this.statusAtDisconnect=void 0)}disconnectedCallback(){this.statusAtDisconnect=this.status,this.isMounting=!0,this.politeSink?.release(),this.assertiveSink?.release(),this.politeSink=this.assertiveSink=void 0,super.disconnectedCallback()}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}isFocusWithinFailureSlot(){const root=this.getRootNode(),active=activeElementIn(!this.isConnected||root.nodeType===Node.ELEMENT_NODE?null:root);try{return!active||active.nodeType!==Node.ELEMENT_NODE?!1:Array.from(this.children).some(el=>el.getAttribute("slot")==="failure"&&el.contains(active))}catch{return!1}}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}get statusText(){return this.status==="sent"?void 0:this.localize(STATUS_TEXT_KEY[this.status])}announceStatusChange(previous){if(previous
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,retryIcon}from"../../../internal/icons.js";import{formatTimeOfDay}from"../../../internal/intl-cache.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{styles}from"./chat-message.styles.js";import{LYRA_DEFAULT_chatCompleteAnnounce,LYRA_DEFAULT_chatFailedAnnounce,LYRA_DEFAULT_chatFailedToSend,LYRA_DEFAULT_chatResponding,LYRA_DEFAULT_chatSending,LYRA_DEFAULT_collapseMessage,LYRA_DEFAULT_expandMessage}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_promptStudioRoleAssistant,LYRA_DEFAULT_promptStudioRoleSystem,LYRA_DEFAULT_promptStudioRoleUser,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const STATUS_TEXT_KEY={sending:"chatSending",streaming:"chatResponding",failed:"chatFailedToSend"},CHAT_MESSAGE_STATUS=literalSetConverter(["sending","sent","failed","streaming"],"sent");class LyraChatMessage extends LyraElement{constructor(){super(...arguments),this.messageRole="assistant",this.messageId="",this.collapsible=!1,this.collapsed=!1,this.attachmentsPlacement="after",this.actionsPlacement="inside",this.avatarPlacement="top",this.announceStatus=!0,this.hasAvatarSlot=!1,this.hasBadgesSlot=!1,this.hasAttachmentsSlot=!1,this.hasActionsSlot=!1,this.hasFailureSlot=!1,this.bodyId=nextId("chat-message-body"),this._status="sent",this.previousStatus="sent",this.isMounting=!0,this.onAvatarSlotChange=()=>{this.hasAvatarSlot=this.hasSlotted("avatar")},this.onBadgesSlotChange=()=>{this.hasBadgesSlot=this.hasSlotted("badges")},this.onAttachmentsSlotChange=()=>{this.hasAttachmentsSlot=this.hasSlotted("attachments")},this.onActionsSlotChange=()=>{this.hasActionsSlot=this.hasSlotted("actions")},this.onFailureSlotChange=()=>{this.hasFailureSlot=this.hasSlotted("failure")},this.toggleCollapsed=()=>{const detail={expanded:this.collapsed};requestThenCommit({requestDetail:detail,emitRequest:(requestDetail,init)=>this.emit("lr-toggle-request",requestDetail,init),commit:()=>{this.collapsed=!detail.expanded,this.emit("lr-toggle",detail)}})},this.onRetryClick=()=>{this.emit("lr-message-retry",{messageId:this.messageId||void 0}),this.status!=="failed"&&this.bubbleEl?.focus()}}static{this.defaultStrings={...super.defaultStrings,chatCompleteAnnounce:LYRA_DEFAULT_chatCompleteAnnounce,chatFailedAnnounce:LYRA_DEFAULT_chatFailedAnnounce,chatFailedToSend:LYRA_DEFAULT_chatFailedToSend,chatResponding:LYRA_DEFAULT_chatResponding,chatSending:LYRA_DEFAULT_chatSending,collapse:LYRA_DEFAULT_collapse,collapseMessage:LYRA_DEFAULT_collapseMessage,details:LYRA_DEFAULT_details,expandMessage:LYRA_DEFAULT_expandMessage,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,promptStudioRoleAssistant:LYRA_DEFAULT_promptStudioRoleAssistant,promptStudioRoleSystem:LYRA_DEFAULT_promptStudioRoleSystem,promptStudioRoleUser:LYRA_DEFAULT_promptStudioRoleUser,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={status:{reflect:!0,noAccessor:!0,converter:CHAT_MESSAGE_STATUS}}}get status(){return this._status}set status(value){const normalized=CHAT_MESSAGE_STATUS.normalizeReflected(this,"status",value),old=this._status;normalized!==old&&(this.previousStatus=old,this._status=normalized,this.requestUpdate("status",old))}willUpdate(changed){super.willUpdate(changed),this.hasUpdated?changed.has("status")&&(this.status==="failed"?this.hasFailureSlot=this.hasSlotted("failure"):this.previousStatus==="failed"&&this.hasFailureSlot&&this.isFocusWithinFailureSlot()&&this.bubbleEl?.focus()):(this.hasAvatarSlot=this.hasSlotted("avatar"),this.hasBadgesSlot=this.hasSlotted("badges"),this.hasAttachmentsSlot=this.hasSlotted("attachments"),this.hasActionsSlot=this.hasSlotted("actions"),this.status==="failed"&&(this.hasFailureSlot=this.hasSlotted("failure")))}updated(changed){super.updated(changed);const wasMounting=this.isMounting;this.isMounting=!1,!wasMounting&&changed.has("status")&&this.announceStatusChange(this.previousStatus)}connectedCallback(){super.connectedCallback(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.statusAtDisconnect!==void 0&&(this.isMounting=this.status!==this.statusAtDisconnect&&this.isUpdatePending,this.statusAtDisconnect=void 0)}disconnectedCallback(){this.statusAtDisconnect=this.status,this.isMounting=!0,this.politeSink?.release(),this.assertiveSink?.release(),this.politeSink=this.assertiveSink=void 0,super.disconnectedCallback()}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}isFocusWithinFailureSlot(){const root=this.getRootNode(),active=activeElementIn(!this.isConnected||root.nodeType===Node.ELEMENT_NODE?null:root);try{return!active||active.nodeType!==Node.ELEMENT_NODE?!1:Array.from(this.children).some(el=>el.getAttribute("slot")==="failure"&&el.contains(active))}catch{return!1}}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}get statusText(){return this.status==="sent"?void 0:this.localize(STATUS_TEXT_KEY[this.status])}announceStatusChange(previous){if(!(previous===this.status||!this.announceStatus))if(this.status==="failed"){if(this.hasFailureSlot)return;this.assertiveSink?.announce(this.localize("chatFailedAnnounce"))}else previous==="streaming"&&this.status==="sent"&&this.politeSink?.announce(this.localize("chatCompleteAnnounce"))}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>formatTimeOfDay(date,this.effectiveLocale)),suppressBuiltInFailedUi=this.status==="failed"&&this.hasFailureSlot,statusText=suppressBuiltInFailedUi?void 0:this.statusText,avatarBeside=this.avatarPlacement==="start"||this.avatarPlacement==="end",showHeader=!avatarBeside&&this.hasAvatarSlot||this.hasBadgesSlot||this.collapsible,actionsOutside=this.actionsPlacement==="outside",showFooter=!!statusText||!!ts||!actionsOutside&&this.hasActionsSlot,authorLabel=this.localize(this.messageRole==="user"?"promptStudioRoleUser":this.messageRole==="system"?"promptStudioRoleSystem":"promptStudioRoleAssistant"),articleLabel=this.hasAttribute("aria-label")?this.getAttribute("aria-label")??"":authorLabel,actionsBlock=html`<span part="actions" ?hidden=${!this.hasActionsSlot}
|
|
2
2
|
><slot name="actions" @slotchange=${this.onActionsSlotChange}></slot
|
|
3
3
|
></span>`,attachmentsBlock=html`<div part="attachments" ?hidden=${!this.hasAttachmentsSlot}>
|
|
4
4
|
<slot name="attachments" @slotchange=${this.onAttachmentsSlotChange}></slot>
|
|
5
|
-
</div
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
role="article"
|
|
9
|
-
aria-label=${articleLabel}
|
|
10
|
-
tabindex="-1"
|
|
11
|
-
>
|
|
5
|
+
</div>`,avatarBlock=html`<span part="avatar" ?hidden=${!this.hasAvatarSlot}
|
|
6
|
+
><slot name="avatar" @slotchange=${this.onAvatarSlotChange}></slot
|
|
7
|
+
></span>`,content=html`
|
|
12
8
|
<div part="header" ?hidden=${!showHeader}>
|
|
13
|
-
|
|
14
|
-
><slot name="avatar" @slotchange=${this.onAvatarSlotChange}></slot
|
|
15
|
-
></span>
|
|
9
|
+
${avatarBeside?nothing:avatarBlock}
|
|
16
10
|
<span part="badges" ?hidden=${!this.hasBadgesSlot}
|
|
17
11
|
><slot name="badges" @slotchange=${this.onBadgesSlotChange}></slot
|
|
18
12
|
></span>
|
|
@@ -43,6 +37,14 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
|
|
|
43
37
|
</button>`:nothing}
|
|
44
38
|
${actionsOutside?nothing:actionsBlock}
|
|
45
39
|
</div>
|
|
40
|
+
`;return html`
|
|
41
|
+
<div
|
|
42
|
+
part="bubble"
|
|
43
|
+
role="article"
|
|
44
|
+
aria-label=${articleLabel}
|
|
45
|
+
tabindex="-1"
|
|
46
|
+
>
|
|
47
|
+
${avatarBeside?html`${this.avatarPlacement==="start"?avatarBlock:nothing}<div class="content">${content}</div>${this.avatarPlacement==="end"?avatarBlock:nothing}`:content}
|
|
46
48
|
</div>
|
|
47
49
|
${actionsOutside?actionsBlock:nothing}
|
|
48
|
-
`}}__decorate([property({reflect:!0,attribute:"message-role"})],LyraChatMessage.prototype,"messageRole",void 0),__decorate([property({attribute:"message-id",reflect:!0})],LyraChatMessage.prototype,"messageId",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"timestamp",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"formatTimestamp",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsed",void 0),__decorate([property({attribute:"attachments-placement"})],LyraChatMessage.prototype,"attachmentsPlacement",void 0),__decorate([property({reflect:!0,attribute:"actions-placement"})],LyraChatMessage.prototype,"actionsPlacement",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAvatarSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasBadgesSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAttachmentsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasFailureSlot",void 0),__decorate([query('[part="bubble"]')],LyraChatMessage.prototype,"bubbleEl",void 0);export{LyraChatMessage};
|
|
50
|
+
`}}__decorate([property({reflect:!0,attribute:"message-role"})],LyraChatMessage.prototype,"messageRole",void 0),__decorate([property({attribute:"message-id",reflect:!0})],LyraChatMessage.prototype,"messageId",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"timestamp",void 0),__decorate([property({attribute:!1})],LyraChatMessage.prototype,"formatTimestamp",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraChatMessage.prototype,"collapsed",void 0),__decorate([property({attribute:"attachments-placement"})],LyraChatMessage.prototype,"attachmentsPlacement",void 0),__decorate([property({reflect:!0,attribute:"actions-placement"})],LyraChatMessage.prototype,"actionsPlacement",void 0),__decorate([property({reflect:!0,attribute:"avatar-placement"})],LyraChatMessage.prototype,"avatarPlacement",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"announce-status",converter:trueDefaultBooleanConverter})],LyraChatMessage.prototype,"announceStatus",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAvatarSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasBadgesSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasAttachmentsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraChatMessage.prototype,"hasFailureSlot",void 0),__decorate([query('[part="bubble"]')],LyraChatMessage.prototype,"bubbleEl",void 0);export{LyraChatMessage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; font-size: var(--lr-font-size-md-sm); line-height: var(--lr-line-height-normal); } [part='bubble'] { display: flex; flex-direction: column; gap: var(--lr-space-xs); max-inline-size: var(--lr-chat-message-max-width, 80%); padding: var(--lr-chat-message-bubble-padding, var(--lr-space-m)); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-chat-message-bubble-radius, var(--lr-radius)); background: var(--lr-chat-message-bubble-bg, var(--lr-color-surface)); color: var(--lr-chat-message-bubble-color, var(--lr-color-text)); overflow-wrap: anywhere; } :host([message-role='user']) [part='bubble'] { margin-inline-start: auto; background: var(--lr-chat-message-user-bubble-bg, var(--lr-color-brand-quiet)); color: var(--lr-chat-message-user-bubble-color, var(--lr-color-text)); border-color: transparent; } :host([message-role='assistant']) [part='bubble'] { margin-inline-end: auto; } :host([message-role='system']) [part='bubble'] { margin-inline-end: auto; color: var(--lr-chat-message-system-color, var(--lr-color-text-quiet)); font-style: italic; border-style: dashed; } :host([status='failed']) [part='bubble'] { border-color: var(--lr-chat-message-failed-border-color, var(--lr-color-danger)); background: var(--lr-chat-message-failed-bg, var(--lr-color-danger-quiet)); } :host([status='streaming']) [part='bubble'] { border-color: var(--lr-chat-message-streaming-border-color, var(--lr-color-brand)); } [part='header'] { display: flex; align-items: center; gap: var(--lr-space-xs); } [part='header'][hidden], [part='avatar'][hidden], [part='badges'][hidden], [part='attachments'][hidden], [part='footer'][hidden], [part='actions'][hidden], [part='body'][hidden] { display: none; } [part='avatar'] { flex: 0 0 auto; display: inline-flex; } [part='badges'] { flex: 1 1 auto; display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); min-inline-size: 0; } [part='collapse-button'] { font: inherit; flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} margin-inline-start: auto; border: none; background: var(--lr-icon-button-bg, transparent); color: var(--lr-icon-button-color, var(--lr-color-text-quiet)); border-radius: var(--lr-icon-button-radius, var(--lr-radius)); cursor: pointer; } [part='collapse-button']:hover { background: var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)); color: var(--lr-icon-button-color-hover, var(--lr-color-text)); } [part='collapse-button']:active { background: var( --lr-icon-button-bg-active, color-mix( in oklab, var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); color: var(--lr-icon-button-color-active, var(--lr-icon-button-color-hover, var(--lr-color-text))); } [part~='bubble']:focus-visible { ${focusRing} } [part='collapse-button']:focus-visible, [part='retry-button']:focus-visible { ${focusRing} } [part='collapse-button'] .chevron { display: inline-flex; transition: transform var(--lr-transition-fast); } :host(:not([collapsed])) [part='collapse-button'] .chevron { transform: rotate(90deg); } :host([collapsed]:dir(rtl)) [part='collapse-button'] .chevron { transform: scaleX(-1); } [part='attachments'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='failure'] { display: contents; } [part='footer'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); font-size: var(--lr-font-size-xs); color: var(--lr-chat-message-footer-color, var(--lr-color-text-quiet)); } [part='actions'] { display: flex; align-items: center; gap: var(--lr-space-xs); } :host([message-role='user']) [part='actions'] { margin-inline-start: auto; } :host([message-role='assistant']) [part='actions'], :host([message-role='system']) [part='actions'] { margin-inline-end: auto; } :host([actions-placement='outside']) [part='actions'] { margin-block-start: var(--lr-space-2xs); } :host([actions-placement='outside'][message-role='user']) [part='actions'] { justify-content: flex-end; } :host([actions-placement='outside'][message-role='assistant']) [part='actions'], :host([actions-placement='outside'][message-role='system']) [part='actions'] { justify-content: flex-start; } [part='timestamp'] { white-space: nowrap; } :host([message-role='user']) [part='footer'] { color: var(--lr-chat-message-user-footer-color, var(--lr-color-text)); } :host([status='failed']) [part='footer'] { color: var(--lr-chat-message-failed-footer-color, var(--lr-color-danger)); } [part='status-indicator'] { flex: 0 0 auto; inline-size: var(--lr-size-0-5rem); block-size: var(--lr-size-0-5rem); border-radius: 50%; background: var(--lr-chat-message-indicator-color, var(--lr-color-text-quiet)); } :host([status='streaming']) [part='status-indicator'] { background: var(--lr-chat-message-streaming-indicator-color, var(--lr-color-brand)); animation: var(--_lr-motion-animation, lr-chat-message-pulse var(--lr-transition-ambient) infinite); } :host([status='failed']) [part='status-indicator'] { background: var(--lr-chat-message-failed-indicator-color, var(--lr-color-danger)); } [part='status-text'] { white-space: nowrap; } :host([status='failed']) [part='status-text'] { color: var(--lr-chat-message-failed-status-color, var(--lr-color-danger)); font-weight: var(--lr-font-weight-semibold); } @keyframes lr-chat-message-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } } [part='retry-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; gap: var(--lr-space-xs); padding: var(--lr-size-0-125rem) var(--lr-space-xs); border: var(--lr-border-width-thin) solid var(--lr-color-danger); border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-danger); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; } [part='retry-button']:hover { background: var(--lr-color-danger-quiet); } [part='retry-button']:active { background: color-mix(in oklab, var(--lr-color-danger-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='retry-button'] svg { inline-size: var(--lr-size-0-875em); block-size: var(--lr-size-0-875em); } @media (prefers-reduced-motion: reduce) { [part='status-indicator'] { animation: none !important; opacity: 1; } [part='collapse-button'] .chevron { transition: none !important; } } `;export{styles};
|
|
1
|
+
import{iconHitTarget,focusRing}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: block; font-size: var(--lr-font-size-md-sm); line-height: var(--lr-line-height-normal); } [part='bubble'] { display: flex; flex-direction: column; gap: var(--lr-space-xs); inline-size: var(--lr-chat-message-width, auto); max-inline-size: var(--lr-chat-message-max-width, 80%); padding: var(--lr-chat-message-bubble-padding, var(--lr-space-m)); border: var(--lr-chat-message-bubble-border-width, var(--lr-border-width-thin)) solid var(--lr-chat-message-bubble-border-color, var(--lr-color-border-subtle)); border-radius: var(--lr-chat-message-bubble-radius, var(--lr-radius)); background: var(--lr-chat-message-bubble-bg, var(--lr-color-surface)); color: var(--lr-chat-message-bubble-color, var(--lr-color-text)); overflow-wrap: anywhere; } :host([message-role='user']) [part='bubble'] { margin-inline-start: auto; background: var(--lr-chat-message-user-bubble-bg, var(--lr-color-brand-quiet)); color: var(--lr-chat-message-user-bubble-color, var(--lr-color-text)); border-color: var(--lr-chat-message-user-bubble-border-color, transparent); } :host([message-role='assistant']) [part='bubble'] { margin-inline-end: auto; } :host([message-role='system']) [part='bubble'] { margin-inline-end: auto; color: var(--lr-chat-message-system-color, var(--lr-color-text-quiet)); font-style: italic; border-style: dashed; } :host([status='failed']) [part='bubble'] { border-color: var(--lr-chat-message-failed-border-color, var(--lr-color-danger)); background: var(--lr-chat-message-failed-bg, var(--lr-color-danger-quiet)); color: var(--lr-chat-message-failed-color, var(--lr-color-text)); } :host([status='streaming']) [part='bubble'] { border-color: var(--lr-chat-message-streaming-border-color, var(--lr-color-brand)); } :host([avatar-placement='start']) [part='bubble'], :host([avatar-placement='end']) [part='bubble'] { flex-direction: row; align-items: flex-start; gap: var(--lr-space-s); } .content { flex: 1 1 auto; min-inline-size: 0; display: flex; flex-direction: column; gap: var(--lr-space-xs); } [part='header'] { display: flex; align-items: center; gap: var(--lr-space-xs); } [part='header'][hidden], [part='avatar'][hidden], [part='badges'][hidden], [part='attachments'][hidden], [part='footer'][hidden], [part='actions'][hidden], [part='body'][hidden] { display: none; } [part='avatar'] { flex: 0 0 auto; display: inline-flex; } [part='badges'] { flex: 1 1 auto; display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); min-inline-size: 0; } [part='collapse-button'] { font: inherit; flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} margin-inline-start: auto; border: none; background: var(--lr-icon-button-bg, transparent); color: var(--lr-icon-button-color, var(--lr-color-text-quiet)); border-radius: var(--lr-icon-button-radius, var(--lr-radius)); cursor: pointer; } [part='collapse-button']:hover { background: var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)); color: var(--lr-icon-button-color-hover, var(--lr-color-text)); } [part='collapse-button']:active { background: var( --lr-icon-button-bg-active, color-mix( in oklab, var(--lr-icon-button-bg-hover, var(--lr-color-surface-raised)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ) ); color: var(--lr-icon-button-color-active, var(--lr-icon-button-color-hover, var(--lr-color-text))); } [part~='bubble']:focus-visible { ${focusRing} } [part='collapse-button']:focus-visible, [part='retry-button']:focus-visible { ${focusRing} } [part='collapse-button'] .chevron { display: inline-flex; transition: transform var(--lr-transition-fast); } :host(:not([collapsed])) [part='collapse-button'] .chevron { transform: rotate(90deg); } :host([collapsed]:dir(rtl)) [part='collapse-button'] .chevron { transform: scaleX(-1); } [part='attachments'] { display: flex; flex-wrap: wrap; gap: var(--lr-space-xs); } [part='failure'] { display: contents; } [part='footer'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); font-size: var(--lr-font-size-xs); color: var(--lr-chat-message-footer-color, var(--lr-color-text-quiet)); } [part='actions'] { display: flex; align-items: center; gap: var(--lr-space-xs); } :host([message-role='user']) [part='actions'] { margin-inline-start: auto; } :host([message-role='assistant']) [part='actions'], :host([message-role='system']) [part='actions'] { margin-inline-end: auto; } :host([actions-placement='outside']) [part='actions'] { margin-block-start: var(--lr-space-2xs); } :host([actions-placement='outside'][message-role='user']) [part='actions'] { justify-content: flex-end; } :host([actions-placement='outside'][message-role='assistant']) [part='actions'], :host([actions-placement='outside'][message-role='system']) [part='actions'] { justify-content: flex-start; } [part='timestamp'] { white-space: nowrap; } :host([message-role='user']) [part='footer'] { color: var(--lr-chat-message-user-footer-color, var(--lr-color-text)); } :host([status='failed']) [part='footer'] { color: var(--lr-chat-message-failed-footer-color, var(--lr-color-danger)); } [part='status-indicator'] { flex: 0 0 auto; inline-size: var(--lr-size-0-5rem); block-size: var(--lr-size-0-5rem); border-radius: 50%; background: var(--lr-chat-message-indicator-color, var(--lr-color-text-quiet)); } :host([status='streaming']) [part='status-indicator'] { background: var(--lr-chat-message-streaming-indicator-color, var(--lr-color-brand)); animation: var(--_lr-motion-animation, lr-chat-message-pulse var(--lr-transition-ambient) infinite); } :host([status='failed']) [part='status-indicator'] { background: var(--lr-chat-message-failed-indicator-color, var(--lr-color-danger)); } [part='status-text'] { white-space: nowrap; } :host([status='failed']) [part='status-text'] { color: var(--lr-chat-message-failed-status-color, var(--lr-color-danger)); font-weight: var(--lr-font-weight-semibold); } @keyframes lr-chat-message-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } } [part='retry-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; gap: var(--lr-space-xs); padding: var(--lr-size-0-125rem) var(--lr-space-xs); border: var(--lr-border-width-thin) solid var(--lr-color-danger); border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-danger); font: inherit; font-size: var(--lr-font-size-xs); cursor: pointer; } [part='retry-button']:hover { background: var(--lr-color-danger-quiet); } [part='retry-button']:active { background: color-mix(in oklab, var(--lr-color-danger-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='retry-button'] svg { inline-size: var(--lr-size-0-875em); block-size: var(--lr-size-0-875em); } @media (prefers-reduced-motion: reduce) { [part='status-indicator'] { animation: none !important; opacity: 1; } [part='collapse-button'] .chevron { transition: none !important; } } `;export{styles};
|