@aceshooting/lyra-ui 21.0.0 → 21.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +6 -3
- package/custom-elements.json +1 -1
- package/dist/ai/runtime.js +1 -1
- package/dist/ai/types.d.ts +13 -5
- package/dist/cli/lyra-rename-ledger.mjs +1 -0
- package/dist/cli/migrate-wa.mjs +33 -13
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.d.ts +5 -3
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +3 -2
- package/dist/components/agent-tools/tool-call-block/tool-call-block.class.d.ts +15 -3
- package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +3 -3
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +24 -8
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +3 -3
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -0
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +9 -5
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.styles.js +1 -1
- package/dist/components/agent-tools/tool-status.js +2 -2
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +8 -0
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +3 -2
- package/dist/components/agent-tools/tool-timeline/tool-timeline.styles.js +1 -1
- package/dist/components/agent-tools/trace-tree/span.d.ts +2 -2
- package/dist/components/charts/chart/box-plot.class.d.ts +3 -1
- package/dist/components/charts/chart/box-plot.class.js +9 -9
- package/dist/components/charts/chart/chart-bidi.d.ts +109 -0
- package/dist/components/charts/chart/chart-bidi.js +1 -0
- package/dist/components/charts/chart/chart.class.d.ts +17 -2
- package/dist/components/charts/chart/chart.class.js +10 -8
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +24 -5
- package/dist/components/charts/chart/lite-chart.class.js +9 -9
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/code-block/shiki-dark-theme.d.ts +2 -2
- package/dist/components/conversation/code-block/shiki-dark-theme.js +1 -1
- package/dist/components/conversation/conversation-item/conversation-item.class.d.ts +18 -2
- package/dist/components/conversation/conversation-item/conversation-item.class.js +3 -3
- package/dist/components/conversation/conversation-item/conversation-item.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +3 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +3 -1
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +7 -2
- package/dist/components/conversation/message-actions/message-actions.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +6 -2
- package/dist/components/conversation/message-parts/message-parts.class.js +5 -3
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +3 -2
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +1 -5
- package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +7 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +3 -4
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +7 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.js +3 -4
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +13 -2
- package/dist/components/conversation/thread-list/thread-list.class.js +3 -3
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/document-library/document-library.class.js +2 -0
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/flow-node/flow-node.class.d.ts +6 -2
- package/dist/components/data/flow-node/flow-node.class.js +6 -2
- package/dist/components/data/flow-node/flow-node.styles.js +1 -1
- package/dist/components/data/gauge/gauge.styles.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +3 -0
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/sparkline/sparkline.class.d.ts +5 -3
- package/dist/components/data/stat/stat.class.d.ts +4 -3
- package/dist/components/data/table/table.class.d.ts +32 -5
- package/dist/components/data/table/table.class.js +3 -2
- package/dist/components/forms/button/button.class.d.ts +7 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.styles.js +1 -1
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -0
- package/dist/components/layout/app-rail/app-rail.class.d.ts +50 -11
- package/dist/components/layout/app-rail/app-rail.class.js +2 -2
- package/dist/components/layout/command-palette/command-palette.class.js +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +6 -5
- package/dist/components/layout/split-panel/split-panel.class.d.ts +2 -1
- package/dist/components/media/flag/language-map.d.ts +8 -0
- package/dist/components/media/flag/language-map.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +7 -1
- package/dist/components/media/map/map.class.d.ts +111 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/media-card/media-card.class.d.ts +18 -5
- package/dist/components/media/media-card/media-card.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.d.ts +20 -0
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/retrieval/graph/graph.class.d.ts +3 -3
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +5 -3
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +3 -2
- package/dist/components/retrieval/mind-map/mind-map.class.d.ts +3 -3
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +4 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +5 -1
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +4 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +5 -1
- package/dist/components/utility/icon/icon.class.d.ts +9 -3
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/mutation-observer/mutation-observer.class.d.ts +14 -8
- package/dist/components/utility/mutation-observer/mutation-observer.class.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.d.ts +6 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.js +7 -1
- package/dist/components/viewers/document-viewer/registry.d.ts +12 -3
- package/dist/components/viewers/geojson-view/geojson-view.class.d.ts +13 -5
- package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.class.d.ts +3 -2
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +644 -1242
- package/dist/internal/anchored-overlay-runtime.d.ts +2 -2
- package/dist/internal/cell-range.d.ts +0 -6
- package/dist/internal/cell-range.js +1 -1
- package/dist/internal/css-token-length.d.ts +7 -0
- package/dist/internal/css-token-length.js +1 -0
- package/dist/internal/default-strings.generated.d.ts +1 -1
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/deferred-focus-return.d.ts +7 -4
- package/dist/internal/deferred-focus-return.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +35 -0
- package/dist/internal/dev-mode-attribute-warning.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/papaparse-loader.d.ts +1 -1
- package/dist/internal/papaparse-loader.js +1 -1
- package/dist/internal/positioner.d.ts +10 -0
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/shared-unions.d.ts +2 -1
- package/dist/internal/slotted-overlay-controller.d.ts +20 -0
- package/dist/internal/slotted-overlay-controller.js +1 -0
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/internal/text-quote.js +1 -1
- package/dist/internal/theme-observation.d.ts +4 -0
- package/dist/internal/theme-observation.js +1 -0
- package/dist/internal/theme-watcher.js +1 -1
- package/dist/localization.d.ts +6 -1
- package/dist/localization.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/translations/ar/agent-tools.js +1 -1
- package/dist/translations/cs/agent-tools.js +1 -1
- package/dist/translations/da/agent-tools.js +1 -1
- package/dist/translations/de/agent-tools.js +1 -1
- package/dist/translations/de-CH/agent-tools.js +1 -1
- package/dist/translations/es/agent-tools.js +1 -1
- package/dist/translations/fa/agent-tools.js +1 -1
- package/dist/translations/fi/agent-tools.js +1 -1
- package/dist/translations/fr/agent-tools.js +1 -1
- package/dist/translations/he/agent-tools.js +1 -1
- package/dist/translations/hi/agent-tools.js +1 -1
- package/dist/translations/hr/agent-tools.js +1 -1
- package/dist/translations/hu/agent-tools.js +1 -1
- package/dist/translations/id/agent-tools.js +1 -1
- package/dist/translations/it/agent-tools.js +1 -1
- package/dist/translations/ja/agent-tools.js +1 -1
- package/dist/translations/kk/agent-tools.js +1 -1
- package/dist/translations/ko/agent-tools.js +1 -1
- package/dist/translations/nb/agent-tools.js +1 -1
- package/dist/translations/nl/agent-tools.js +1 -1
- package/dist/translations/nn/agent-tools.js +1 -1
- package/dist/translations/pl/agent-tools.js +1 -1
- package/dist/translations/pt-BR/agent-tools.js +1 -1
- package/dist/translations/pt-PT/agent-tools.js +1 -1
- package/dist/translations/pt-PT/charts.js +1 -1
- package/dist/translations/pt-PT/conversation.js +1 -1
- package/dist/translations/pt-PT/data.js +1 -1
- package/dist/translations/pt-PT/forms.js +1 -1
- package/dist/translations/pt-PT/layout.js +1 -1
- package/dist/translations/pt-PT/media.js +1 -1
- package/dist/translations/pt-PT/retrieval.js +1 -1
- package/dist/translations/pt-PT/shared.js +1 -1
- package/dist/translations/pt-PT/utility.js +1 -1
- package/dist/translations/pt-PT/viewers.js +2 -2
- package/dist/translations/ro/agent-tools.js +1 -1
- package/dist/translations/ru/agent-tools.js +1 -1
- package/dist/translations/sl/agent-tools.js +1 -1
- package/dist/translations/sv/agent-tools.js +1 -1
- package/dist/translations/tr/agent-tools.js +1 -1
- package/dist/translations/uk/agent-tools.js +1 -1
- package/dist/translations/zh-CN/agent-tools.js +1 -1
- package/dist/translations/zh-TW/agent-tools.js +1 -1
- package/dist/utilities/index.d.ts +1 -1
- package/dist/utilities/index.js +1 -1
- package/dist/utilities/localization.d.ts +28 -10
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-accordion-item.md +2 -344
- package/llms/components/lr-accordion.md +2 -344
- package/llms/components/lr-app-rail-group.md +2 -721
- package/llms/components/lr-app-rail-item.md +2 -721
- package/llms/components/lr-app-rail.md +29 -4
- package/llms/components/lr-bar-chart.md +2 -87
- package/llms/components/lr-box-plot.md +1 -1
- package/llms/components/lr-breadcrumb-item.md +2 -67
- package/llms/components/lr-bubble-chart.md +2 -87
- package/llms/components/lr-button.md +7 -0
- package/llms/components/lr-chart.md +4 -5
- package/llms/components/lr-chip-group.md +2 -272
- package/llms/components/lr-conversation-item.md +20 -2
- package/llms/components/lr-date-input.md +2 -457
- package/llms/components/lr-date-picker.md +6 -2
- package/llms/components/lr-document-library.md +3 -3
- package/llms/components/lr-document-viewer.md +14 -5
- package/llms/components/lr-doughnut-chart.md +2 -87
- package/llms/components/lr-dropdown-item.md +2 -306
- package/llms/components/lr-dropdown.md +6 -0
- package/llms/components/lr-flag.md +9 -1
- package/llms/components/lr-flow-node.md +4 -1
- package/llms/components/lr-geojson-view.md +3 -90
- package/llms/components/lr-geojson-viewer.md +13 -5
- package/llms/components/lr-icon-button.md +4 -1
- package/llms/components/lr-icon.md +14 -6
- package/llms/components/lr-input.md +9 -2
- package/llms/components/lr-lite-chart.md +17 -9
- package/llms/components/lr-map.md +87 -2
- package/llms/components/lr-markdown-core.md +5 -4
- package/llms/components/lr-markdown.md +4 -2
- package/llms/components/lr-media-card.md +10 -5
- package/llms/components/lr-menu-item.md +2 -306
- package/llms/components/lr-menu.md +9 -6
- package/llms/components/lr-menubar-item.md +2 -125
- package/llms/components/lr-message-actions.md +4 -1
- package/llms/components/lr-message-parts.md +14 -5
- package/llms/components/lr-mutation-observer.md +12 -6
- package/llms/components/lr-navigation-menu-item.md +2 -237
- package/llms/components/lr-number-input.md +4 -0
- package/llms/components/lr-option.md +2 -712
- package/llms/components/lr-pie-chart.md +2 -87
- package/llms/components/lr-polar-area-chart.md +2 -87
- package/llms/components/lr-popover.md +10 -0
- package/llms/components/lr-prompt-input.md +5 -1
- package/llms/components/lr-radar-chart.md +2 -87
- package/llms/components/lr-reorder-item.md +2 -157
- package/llms/components/lr-result-field.md +2 -117
- package/llms/components/lr-retrieval-results.md +3 -1
- package/llms/components/lr-rubric-form.md +3 -2
- package/llms/components/lr-scatter-chart.md +2 -87
- package/llms/components/lr-selection-toolbar.md +4 -2
- package/llms/components/lr-source-card.md +2 -186
- package/llms/components/lr-source-picker.md +3 -1
- package/llms/components/lr-sparkline.md +9 -4
- package/llms/components/lr-split-panel.md +5 -3
- package/llms/components/lr-stat.md +4 -3
- package/llms/components/lr-streaming-text-core.md +7 -5
- package/llms/components/lr-streaming-text.md +9 -6
- package/llms/components/lr-swatch-picker.md +130 -0
- package/llms/components/lr-tag.md +2 -177
- package/llms/components/lr-thread-list.md +27 -4
- package/llms/components/lr-timeline-item.md +2 -120
- package/llms/components/lr-toast-item.md +2 -223
- package/llms/components/lr-tool-call-block.md +12 -3
- package/llms/components/lr-tool-call-chip.md +12 -6
- package/llms/components/lr-tool-param-form.md +3 -2
- package/llms/components/lr-tool-result-dialog.md +7 -3
- package/llms/components/lr-tool-result-view.md +4 -3
- package/llms/components/lr-tool-timeline.md +12 -5
- package/llms/components/lr-tree-item.md +2 -354
- package/llms/index.md +22 -4
- package/llms/migration.md +75 -1
- package/llms/peers.md +1 -1
- package/llms/shared.md +86 -39
- package/llms-full.txt +739 -163
- package/package.json +6 -6
- package/registrations.json +1 -1
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -435,7 +435,15 @@ private interactiveMarks;
|
|
|
435
435
|
/** A fit-layout chart needs the SVG's allocated dimensions before any coordinate-based
|
|
436
436
|
* content can be drawn. Keep the SVG itself mounted so ResizeObserver can provide that first
|
|
437
437
|
* measurement, while a realm without ResizeObserver keeps the established fallback rendering. */
|
|
438
|
-
private awaitingFitMeasurement;private refreshFitMeasurementAvailability;private markIndexMap;private normalizedMarkIndex;
|
|
438
|
+
private awaitingFitMeasurement;private refreshFitMeasurementAvailability;private markIndexMap;private normalizedMarkIndex;
|
|
439
|
+
/** The message key and interpolation values of one mark's summary, shared by the spoken
|
|
440
|
+
* announcement (a plain string) and the visible data-list item (with isolated values). */
|
|
441
|
+
private markSummary;private markAnnouncement;
|
|
442
|
+
/** The visible data-list item: the same sentence as the announcement, with the caller-supplied
|
|
443
|
+
* and formatted values each isolated so a number-first value keeps its order under RTL. Only
|
|
444
|
+
* the visible list needs the isolated parts; a visually hidden one keeps the plain string, since
|
|
445
|
+
* isolation changes painted order and nothing a screen reader reads. */
|
|
446
|
+
private markListItem;private onMarkFocus;private focusMark;
|
|
439
447
|
/**
|
|
440
448
|
* A value-to-y-pixel mapping for a bar's top/bottom edge. `'linear'` (the
|
|
441
449
|
* default) is the standard `niceDomain`-fraction formula. `'sqrt'`
|
|
@@ -492,13 +500,24 @@ private roundedBarPath;private domain;private emitPoint;private emitNearestLineP
|
|
|
492
500
|
* (`renderChart()`) and handed to both this method and the category-label
|
|
493
501
|
* x-position calc so the two can never drift apart from each other.
|
|
494
502
|
*/
|
|
495
|
-
private renderBars;private renderLines;render():TemplateResult;private resolvedValueAxisGutter;
|
|
503
|
+
private renderBars;private renderLines;render():TemplateResult;private resolvedValueAxisGutter;
|
|
504
|
+
/** The widest rendered category label under the deterministic per-character estimate. */
|
|
505
|
+
private widestEstimatedCategoryLabel;
|
|
506
|
+
/** Width-only automatic cap, kept for tick positions that are not in source order (a reordering
|
|
507
|
+
* `barX`), where "adjacent label" has no single meaning to measure. */
|
|
508
|
+
private automaticMaxLabels;
|
|
509
|
+
/** Automatic selection against the labels' anchored extents (anchorAwareCategoryLabelPicks()):
|
|
510
|
+
* `undefined` renders every sampled label; `null` means the tick positions are not in source
|
|
511
|
+
* order, so the caller falls back to the width-only cap. */
|
|
512
|
+
private automaticLabelIndexes;
|
|
496
513
|
/** Indexes retained by `maxLabels`, selected from the generated mark sample so an independently
|
|
497
514
|
* sampled domain cannot erase requested labels at a later set intersection. The generated mark
|
|
498
515
|
* sample caps the useful result at 1,000, so this selector must do the same rather than allocate
|
|
499
|
-
* an arbitrary consumer-supplied `maxLabels` count. In auto mode the
|
|
500
|
-
*
|
|
501
|
-
*
|
|
516
|
+
* an arbitrary consumer-supplied `maxLabels` count. In auto mode the rendered source indexes and
|
|
517
|
+
* their tick positions (`tickX`) supply a deterministic selection that keeps the estimated
|
|
518
|
+
* breathing room between every adjacent pair of labels, measuring each where it is anchored.
|
|
519
|
+
* `undefined` means every *sampled* label renders, preserving the default and non-finite-value
|
|
520
|
+
* behavior. */
|
|
502
521
|
private visibleLabelIndexes;
|
|
503
522
|
/** A valid `barSlotWidth`, capped so the category run stays finite, or `undefined` to keep the
|
|
504
523
|
* derived slot. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};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-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{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{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function isLiteChartSeries(value){try{return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Array.isArray(value.data)}catch{return!1}}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;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 hasCategoryLabelText(label){return(label??"").trim()!==""}function sparseCategoryLabelExtent(labels,xs,position,grow,pitch,width){if(!hasCategoryLabelText(labels[position]))return width;const emptyBefore=position>0&&!hasCategoryLabelText(labels[position-1]),emptyAfter=position<labels.length-1&&!hasCategoryLabelText(labels[position+1]);if(!emptyBefore&&!emptyAfter)return width;const x=xs[position],halfToward=step=>{let outermost=-1;for(let index=position+step;index>=0&&index<labels.length;index+=step){if(hasCategoryLabelText(labels[index]))return Math.abs(x-xs[index])/2;outermost=index}return outermost<0?Number.POSITIVE_INFINITY:Math.abs(x-xs[outermost])+pitch/2},extent=grow==="middle"?2*Math.min(halfToward(-1),halfToward(1))-BAR_CORNER_RADIUS:halfToward(grow==="right"?1:-1)-BAR_CORNER_RADIUS;return finiteRange(Math.max(width,extent),width,width,MAX_SCROLL_CONTENT_WIDTH)}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 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 lo*(1-ratio)+hi*ratio}).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):(first+index)*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 roundedLo=Math.floor(lo/step)*step,roundedHi=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=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.labels=[],this._datasets=Object.freeze([]),this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!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.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.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.categoryLabelFits=new WeakMap,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get datasets(){return this._datasets}set datasets(value){const previous=this._datasets;this._datasets=normalizeLiteChartSeries(value),this.requestUpdate("datasets",previous)}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}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))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}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.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.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
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};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-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{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,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function isLiteChartSeries(value){try{return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Array.isArray(value.data)}catch{return!1}}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;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 hasCategoryLabelText(label){return(label??"").trim()!==""}function categoryLabelGrowth(index,count){return count<=1?"middle":index===0?"right":index===count-1?"left":"middle"}function anchorAwareCategoryLabelPicks(positions,width,gap,firstGrowth,lastGrowth){const count=positions.length;if(count<=2)return;const last=count-1,leftEdge=candidate=>{const growth=candidate===0?firstGrowth:candidate===last?lastGrowth:"middle",x=positions[candidate];return growth==="right"?x:growth==="left"?x-width:x-width/2},clears=(before,after)=>leftEdge(after)-(leftEdge(before)+width)>=gap-1e-6;let everyCandidateFits=!0;for(let candidate=1;candidate<count&&everyCandidateFits;candidate++)everyCandidateFits=clears(candidate-1,candidate);if(everyCandidateFits)return;const firstCenter=leftEdge(0)+width/2,span=leftEdge(last)+width/2-firstCenter,densest=Math.min(last,Math.floor(span/(width+gap)+1e-9)+1);for(let labels=densest;labels>2;labels--){const picks=[0];let candidate=1,fits=!0;for(let slot=1;slot<labels-1&&fits;slot++){const center=firstCenter+slot*span/(labels-1),latest=last-(labels-1-slot);for(;candidate<latest&&Math.abs(positions[candidate+1]-center)<=Math.abs(positions[candidate]-center);)candidate++;fits=clears(picks[picks.length-1],candidate),picks.push(candidate++)}if(fits&&clears(picks[picks.length-1],last))return[...picks,last]}return[0,last]}function sparseCategoryLabelExtent(labels,xs,position,grow,pitch,width){if(!hasCategoryLabelText(labels[position]))return width;const emptyBefore=position>0&&!hasCategoryLabelText(labels[position-1]),emptyAfter=position<labels.length-1&&!hasCategoryLabelText(labels[position+1]);if(!emptyBefore&&!emptyAfter)return width;const x=xs[position],halfToward=step=>{let outermost=-1;for(let index=position+step;index>=0&&index<labels.length;index+=step){if(hasCategoryLabelText(labels[index]))return Math.abs(x-xs[index])/2;outermost=index}return outermost<0?Number.POSITIVE_INFINITY:Math.abs(x-xs[outermost])+pitch/2},extent=grow==="middle"?2*Math.min(halfToward(-1),halfToward(1))-BAR_CORNER_RADIUS:halfToward(grow==="right"?1:-1)-BAR_CORNER_RADIUS;return finiteRange(Math.max(width,extent),width,width,MAX_SCROLL_CONTENT_WIDTH)}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 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 lo*(1-ratio)+hi*ratio}).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):(first+index)*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 roundedLo=Math.floor(lo/step)*step,roundedHi=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=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.labels=[],this._datasets=Object.freeze([]),this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!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.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.resizeObserverGeneration=0,this.axisTitleTargets=new Set,this.axisTitleFits=new WeakMap,this.categoryLabelFits=new WeakMap,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly,bidiStyles]}get datasets(){return this._datasets}set datasets(value){const previous=this._datasets;this._datasets=normalizeLiteChartSeries(value),this.requestUpdate("datasets",previous)}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}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))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}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.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.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
|
|
2
2
|
`)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&(name==="style"||name==="class")&&(this.fitAxisTitles(),this.fitCategoryLabels())}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.armResizeObserver(),this.armForcedColorsWatcher()}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(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver(),this.releaseAnnouncementSink(),this.syncAnnouncementSink(),this.refreshFitMeasurementAvailability(),this.armForcedColorsWatcher()}armForcedColorsWatcher(){const ownerWindow=this.ownerDocument?.defaultView??void 0;ownerWindow?.matchMedia&&(this.forcedColorsWindow===ownerWindow&&this.forcedColorsQuery||(this.disarmForcedColorsWatcher(),this.forcedColorsWindow=ownerWindow,this.forcedColorsQuery=ownerWindow.matchMedia("(forced-colors: active)"),this.forcedColorsQuery.addEventListener("change",this.onForcedColorsChange)))}disarmForcedColorsWatcher(){this.forcedColorsQuery?.removeEventListener("change",this.onForcedColorsChange),this.forcedColorsQuery=void 0,this.forcedColorsWindow=void 0}syncAnnouncementSink(){this.isConnected&&this.politeAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.politeAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.politeAnnouncementSink?.release(),this.politeAnnouncementSink=void 0}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){if(super.willUpdate(changed),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=activeElementIn(this.shadowRoot)??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.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 dataTruncation=this.dataTruncationMessage();wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.politeAnnouncementSink?.announce(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus()),this.fitAxisTitles(),this.fitCategoryLabels(),this.syncAxisTitleTargets()}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 bounded=finiteRange(extent,0,0,MAX_SCROLL_CONTENT_WIDTH);tick.setAttribute("data-label-extent",String(bounded));const text=Array.from(tick.childNodes).find(node=>node.nodeType===3);if(!text)return x;const source=tick.getAttribute("data-full-label")??"",previous=this.categoryLabelFits.get(tick);if(previous?.source===source&&previous.extent===bounded&&previous.display===text.data&&previous.width===tick.getComputedTextLength())return anchor==="start"?x+previous.width:anchor==="end"?x-previous.width:x;if(text.data=source,tick.getComputedTextLength()>bounded)if(source.length<=1)text.data=source.length===0?source:"…";else{let lower=0,upper=source.length;for(;lower<upper;){const middle=Math.ceil((lower+upper)/2);text.data=middle===0?"…":`${source.slice(0,middle)}…`,tick.getComputedTextLength()<=bounded?lower=middle:upper=middle-1}const lastCode=source.charCodeAt(lower-1);lastCode>=55296&&lastCode<=56319&&(lower-=1),text.data=lower===0?"…":`${source.slice(0,lower)}…`}text.data===source?tick.removeAttribute("aria-label"):tick.setAttribute("aria-label",source);const width=tick.getComputedTextLength();return this.categoryLabelFits.set(tick,{source,extent:bounded,display:text.data,width}),anchor==="start"?x+width:anchor==="end"?x-width:x}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)}}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;this.fitOneCategoryLabel(tick,x,anchorOf(tick),extent)}}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 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
3
|
${this.recordSample().seriesIndexes.map(index=>{const series=this.datasets[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
|
|
4
4
|
d=${`M${-half},${size} L${half},0 M${half},${size} L${size+half},0`}
|
|
@@ -19,7 +19,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
19
19
|
<rect width=${size} height=${size} fill=${this.colorFor(index,series)}></rect>
|
|
20
20
|
${shapes}
|
|
21
21
|
</pattern>`})}
|
|
22
|
-
</defs>`}resolvePointText(label,value,datasetIndex,index){return this.formatter?.({value,surface:"visual",datasetIndex,...index===void 0?{}:{index},label,seriesLabel:this.datasets[datasetIndex]?.label,axis:"y"})??this.pointText?.(label,value,datasetIndex)}formatTableCell(value,context,numberFormat){return this.formatter?.({value,surface:"table",datasetIndex:context.datasetIndex??void 0,index:context.index,label:context.label,seriesLabel:context.seriesLabel??void 0,axis:"y",...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??numberFormat.format(value)}tableTotalAt(index,seriesIndexes){let total=0,hasValue=!1;for(const seriesIndex of seriesIndexes){const series=this.datasets[seriesIndex];if(!series)continue;const value=series.data[index];value==null||!Number.isFinite(value)||(total=finiteAdd(total,value),hasValue=!0)}return hasValue?total:null}recordCount(){let count=this.labels.length;for(const series of this.datasets)count=Math.max(count,series.data.length);return count}recordSample(){const rowCount=this.recordCount(),seriesCount=this.datasets.length;return{rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.recordSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}hasCustomDataTable(){return Array.from(this.children).some(child=>child.getAttribute("slot")==="data-table")}interactiveMarks(){const marks=[],sample=this.recordSample();if(this.effectiveType==="bar")for(const index of sample.rowIndexes)for(const datasetIndex of sample.seriesIndexes){const value=this.datasets[datasetIndex]?.data[index];value==null||!Number.isFinite(value)||this.skipZero&&value===0||marks.push({datasetIndex,index,label:this.labels[index]??"",value})}else sample.seriesIndexes.forEach(datasetIndex=>{const series=this.datasets[datasetIndex];series&&sample.rowIndexes.forEach(index=>{const value=series.data[index];value==null||!Number.isFinite(value)||marks.push({datasetIndex,index,label:this.labels[index]??"",value})})});return marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){return new Map(this.interactiveMarks().map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index]))}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}
|
|
22
|
+
</defs>`}resolvePointText(label,value,datasetIndex,index){return this.formatter?.({value,surface:"visual",datasetIndex,...index===void 0?{}:{index},label,seriesLabel:this.datasets[datasetIndex]?.label,axis:"y"})??this.pointText?.(label,value,datasetIndex)}formatTableCell(value,context,numberFormat){return this.formatter?.({value,surface:"table",datasetIndex:context.datasetIndex??void 0,index:context.index,label:context.label,seriesLabel:context.seriesLabel??void 0,axis:"y",...context.kind==="total"?{statistic:"total"}:{}})??this.tableCellFormatter?.(value,context)??numberFormat.format(value)}tableTotalAt(index,seriesIndexes){let total=0,hasValue=!1;for(const seriesIndex of seriesIndexes){const series=this.datasets[seriesIndex];if(!series)continue;const value=series.data[index];value==null||!Number.isFinite(value)||(total=finiteAdd(total,value),hasValue=!0)}return hasValue?total:null}recordCount(){let count=this.labels.length;for(const series of this.datasets)count=Math.max(count,series.data.length);return count}recordSample(){const rowCount=this.recordCount(),seriesCount=this.datasets.length;return{rowCount,seriesCount,...sampleChartTableIndexes(rowCount,seriesCount)}}generatedDataIsSampled(){if(this.hasCustomDataTable())return!1;const sample=this.recordSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.localize("chartDataSampled"):""}hasCustomDataTable(){return Array.from(this.children).some(child=>child.getAttribute("slot")==="data-table")}interactiveMarks(){const marks=[],sample=this.recordSample();if(this.effectiveType==="bar")for(const index of sample.rowIndexes)for(const datasetIndex of sample.seriesIndexes){const value=this.datasets[datasetIndex]?.data[index];value==null||!Number.isFinite(value)||this.skipZero&&value===0||marks.push({datasetIndex,index,label:this.labels[index]??"",value})}else sample.seriesIndexes.forEach(datasetIndex=>{const series=this.datasets[datasetIndex];series&&sample.rowIndexes.forEach(index=>{const value=series.data[index];value==null||!Number.isFinite(value)||marks.push({datasetIndex,index,label:this.labels[index]??"",value})})});return marks}awaitingFitMeasurement(){return this.layout==="fit"&&this.fitMeasurementAvailable&&(this.plotWidth<=0||this.plotHeight<=0)}refreshFitMeasurementAvailability(){this.fitMeasurementAvailable=typeof this.ownerDocument?.defaultView?.ResizeObserver=="function"}markIndexMap(){return new Map(this.interactiveMarks().map((mark,index)=>[`${mark.datasetIndex}:${mark.index}`,index]))}normalizedMarkIndex(marks=this.interactiveMarks()){return marks.length?Math.min(Math.max(this.activeMarkIndex,0),marks.length-1):-1}markSummary(index,marks){const mark=marks[index];if(!mark)return;const series=this.datasets[mark.datasetIndex]?.label??this.localize("chartSeriesLabel"),custom=this.formatter?.({value:mark.value,surface:"spoken",datasetIndex:mark.datasetIndex,index:mark.index,label:mark.label,seriesLabel:series,axis:"y"})??this.resolvePointText(mark.label,mark.value,mark.datasetIndex,mark.index);return custom?{format:values=>this.localize("liteChartCustomMarkSummary",void 0,values),values:{content:custom,index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)},isolated:["content"]}:{format:values=>this.localize("liteChartMarkSummary",void 0,values),values:{series,label:mark.label,value:getNumberFormat(this.effectiveLocale).format(mark.value),index:getNumberFormat(this.effectiveLocale).format(index+1),total:getNumberFormat(this.effectiveLocale).format(marks.length)},isolated:["series","label","value"]}}markAnnouncement(index,marks=this.interactiveMarks()){const summary=this.markSummary(index,marks);return summary?summary.format(summary.values):""}markListItem(index,marks){const summary=this.markSummary(index,marks);return summary?isolatedMessage(summary.format,summary.values,summary.isolated):""}onMarkFocus(index){const marks=this.interactiveMarks();marks[index]&&(this.activeMarkIndex=index,this.liveRegion?.announce(this.markAnnouncement(index,marks),{force:!0}))}focusMark(index){this.interactiveMarks()[index]&&(this.activeMarkIndex=index,this.updateComplete.then(()=>{const mark=Array.from(this.renderRoot.querySelectorAll('[part="bar"], [part="point"]'))[index];mark&&(activeElementIn(this.shadowRoot)===mark?this.onMarkFocus(index):mark.focus())}))}barValueToY(value,plotY,plotH,lo,hi){if(this.scale==="sqrt"){const zeroY=plotY+plotH-domainFraction(0,lo,hi)*plotH;if(value>=0){const domainMax2=hi>0?hi:1,fraction2=Math.sqrt(Math.min(domainMax2,value)/domainMax2);return zeroY-fraction2*(zeroY-plotY)}const domainMax=lo<0?-lo:1,fraction=Math.sqrt(Math.min(domainMax,-value)/domainMax);return zeroY+fraction*(plotY+plotH-zeroY)}return plotY+plotH-this.valueFraction(value,lo,hi)*plotH}valueFraction(value,lo,hi){return this.scale==="logarithmic"?logDomainFraction(value,this.logDomainFloor(lo,hi),hi):domainFraction(value,lo,hi)}logDomainFloor(lo,hi){if(lo>0)return lo;let smallest=Number.POSITIVE_INFINITY;for(const series of this.datasets)for(const value of series.data)value==null||!Number.isFinite(value)||value<=0||value<smallest&&(smallest=value);return Number.isFinite(smallest)?smallest:hi>0?hi/10:1}effectiveMinBarHeight(){return this.minBarHeight==null?void 0:finiteRange(this.minBarHeight,0,0,MAX_SCROLL_CONTENT_WIDTH)}roundedBarPath(x,y,w,h){const r=Math.max(0,Math.min(BAR_CORNER_RADIUS,w/2,h));return r<=0?`M${x},${y} h${w} v${h} h${-w} Z`:`M${x},${y+r} Q${x},${y} ${x+r},${y} H${x+w-r} Q${x+w},${y} ${x+w},${y+r} V${y+h} H${x} Z`}domain(){let lo=1/0,hi=-1/0;if(this.effectiveType==="bar"&&this.stacked)for(let i=0;i<this.recordCount();i++){let pos=0,neg=0;for(const s of this.datasets){const v=s.data[i];v==null||!Number.isFinite(v)||(v>=0?pos=finiteAdd(pos,v):neg=finiteAdd(neg,v))}lo=Math.min(lo,neg),hi=Math.max(hi,pos)}else for(const s of this.datasets)for(const v of s.data)v==null||!Number.isFinite(v)||(lo=Math.min(lo,v),hi=Math.max(hi,v));(!Number.isFinite(lo)||!Number.isFinite(hi))&&(lo=0,hi=1);const domain=niceDomain(lo,hi,this.beginAtZero,TICK_COUNT);if(this.scale==="logarithmic"){const ticks=logarithmicTicks(this.logDomainFloor(domain.lo,domain.hi),domain.hi,TICK_COUNT);if(ticks)return{...domain,ticks}}return domain}emitPoint(datasetIndex,index){const label=this.labels[index],value=this.datasets[datasetIndex]?.data[index]??null;this.emit("lr-datum-activate",{kind:this.effectiveType==="bar"?"bar":"point",datasetIndex,index,label,value}),this.emit("lr-point-click",{datasetIndex,index,label,value})}emitNearestLinePoint(event,points,fallbackDatasetIndex,fallbackIndex){let selected=points.find(point=>point.datasetIndex===fallbackDatasetIndex&&point.index===fallbackIndex);const currentTarget=event.currentTarget,svgElement=currentTarget instanceof SVGElement?currentTarget.ownerSVGElement:null,screenMatrix=svgElement?.getScreenCTM();if(event.detail>0&&svgElement&&screenMatrix&&points.length){const renderedPoint=svgElement.createSVGPoint(),squaredDistance=point=>{renderedPoint.x=point.x,renderedPoint.y=point.y;const screenPoint=renderedPoint.matrixTransform(screenMatrix),dx=event.clientX-screenPoint.x,dy=event.clientY-screenPoint.y;return dx*dx+dy*dy};let bestDistance=selected?squaredDistance(selected):Number.POSITIVE_INFINITY;for(const point of points){const distance=squaredDistance(point);distance<bestDistance&&(selected=point,bestDistance=distance)}}this.emitPoint(selected?.datasetIndex??fallbackDatasetIndex,selected?.index??fallbackIndex)}onPointKeyDown(e,datasetIndex,index,markIndex){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.onMarkFocus(markIndex),this.emitPoint(datasetIndex,index);return}const marks=this.interactiveMarks();if(!marks.length)return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=markIndex;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(marks.length-1,markIndex+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,markIndex-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=marks.length-1;else return;e.preventDefault(),this.focusMark(next)}formatValueAxisTick(value){return this.formatter?.({value,surface:"tick",axis:"y"})??(this.tickFormat?this.tickFormat(value):formatTick(value,this.effectiveLocale))}renderGrid(plotX,plotY,plotW,plotH,ticks,lo,hi){const rtl=this.effectiveDirection==="rtl";return ticks.map(({value,label})=>{const y=plotY+plotH-this.valueFraction(value,lo,hi)*plotH;return svg`
|
|
23
23
|
<line part="grid-line" x1=${plotX} y1=${y} x2=${plotX+plotW} y2=${y}></line>
|
|
24
24
|
<text
|
|
25
25
|
part="axis-label"
|
|
@@ -120,7 +120,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
120
120
|
d=${d.trim()}
|
|
121
121
|
stroke=${color}
|
|
122
122
|
stroke-dasharray=${this.markDash(di)}
|
|
123
|
-
></path>${dots}`})}render(){return this.renderChart()}resolvedValueAxisGutter(ticks,measuredWidth){if(typeof this.valueAxisGutter=="number")return finiteRange(this.valueAxisGutter,PAD_LEFT,0,MAX_SCROLL_CONTENT_WIDTH);if(this.valueAxisGutter!=="auto"||ticks.length===0)return PAD_LEFT;let widest=0;for(const tick of ticks)widest=Math.max(widest,tick.label.length*APPROX_LABEL_CHARACTER_WIDTH);const requested=Math.ceil(widest)+VALUE_AXIS_TICK_OFFSET+AUTO_VALUE_AXIS_SAFETY_INSET,maximum=this.layout==="scroll"?MAX_AUTO_VALUE_AXIS_GUTTER:Math.max(PAD_LEFT,Math.min(MAX_AUTO_VALUE_AXIS_GUTTER,measuredWidth*MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION));return finiteRange(requested,PAD_LEFT,PAD_LEFT,maximum)}
|
|
123
|
+
></path>${dots}`})}render(){return this.renderChart()}resolvedValueAxisGutter(ticks,measuredWidth){if(typeof this.valueAxisGutter=="number")return finiteRange(this.valueAxisGutter,PAD_LEFT,0,MAX_SCROLL_CONTENT_WIDTH);if(this.valueAxisGutter!=="auto"||ticks.length===0)return PAD_LEFT;let widest=0;for(const tick of ticks)widest=Math.max(widest,tick.label.length*APPROX_LABEL_CHARACTER_WIDTH);const requested=Math.ceil(widest)+VALUE_AXIS_TICK_OFFSET+AUTO_VALUE_AXIS_SAFETY_INSET,maximum=this.layout==="scroll"?MAX_AUTO_VALUE_AXIS_GUTTER:Math.max(PAD_LEFT,Math.min(MAX_AUTO_VALUE_AXIS_GUTTER,measuredWidth*MAX_AUTO_VALUE_AXIS_GUTTER_FRACTION));return finiteRange(requested,PAD_LEFT,PAD_LEFT,maximum)}widestEstimatedCategoryLabel(renderedIndexes){let widest=0;for(const index of renderedIndexes){const label=this.labels[index]??"";widest=Math.max(widest,label.length*APPROX_LABEL_CHARACTER_WIDTH)}return widest}automaticMaxLabels(n,plotW,renderedIndexes){if(n<=1)return n;const widest=this.widestEstimatedCategoryLabel(renderedIndexes);if(widest===0)return n;const lane=widest+AUTO_CATEGORY_LABEL_INSET,fits=Math.floor(finiteRange(plotW,0,0,MAX_SCROLL_CONTENT_WIDTH)/lane);return Math.min(n,Math.max(2,fits))}automaticLabelIndexes(n,renderedIndexes,tickX){if(n<=1)return;const widest=this.widestEstimatedCategoryLabel(renderedIndexes);if(widest===0)return;const positions=renderedIndexes.map(tickX);for(let candidate=1;candidate<positions.length;candidate++)if(!(positions[candidate]>=positions[candidate-1]))return null;const picks=anchorAwareCategoryLabelPicks(positions,widest,AUTO_CATEGORY_LABEL_INSET,categoryLabelGrowth(renderedIndexes[0],n),categoryLabelGrowth(renderedIndexes[renderedIndexes.length-1],n));return picks&&new Set(picks.map(candidate=>renderedIndexes[candidate]))}visibleLabelIndexes(n,plotW,renderedIndexes,tickX){if(this.maxLabels==null)return;if(this.maxLabels==="auto"&&tickX){const automatic=this.automaticLabelIndexes(n,renderedIndexes,tickX);if(automatic!==null)return automatic}const requested=this.maxLabels==="auto"?this.automaticMaxLabels(n,plotW,renderedIndexes):this.maxLabels;if(typeof requested!="number")return;const max=finiteCount(requested,n);if(n<=max)return;const renderedCount=renderedIndexes.length,count=Math.min(renderedCount,MAX_RENDERED_CHART_RECORDS,Math.max(2,max));return count<=1?new Set(count===1?[renderedIndexes[0]]:[]):new Set(Array.from({length:count},(_,index)=>renderedIndexes[Math.round(index*(renderedCount-1)/(count-1))]))}fixedBarSlotWidth(n){const requested=typeof this.barSlotWidth=="number"?finiteNumber(this.barSlotWidth,0):0;if(requested<=0)return;const maxSlot=n>0?MAX_SCROLL_CONTENT_WIDTH/n:MAX_SCROLL_CONTENT_WIDTH;return finiteRange(requested,0,0,maxSlot)}displayCategoryLabel(label,availableWidth){const maxCharacters=Math.max(1,Math.floor(availableWidth/APPROX_LABEL_CHARACTER_WIDTH));return label.length<=maxCharacters?label:maxCharacters===1?"…":`${label.slice(0,maxCharacters-1)}…`}renderChart(){const direction=this.effectiveDirection==="rtl"?"rtl":"ltr",n=this.recordCount(),awaitingFitMeasurement=this.awaitingFitMeasurement(),h=finiteRange(this.plotHeight||200,200,0,MAX_SCROLL_CONTENT_WIDTH),measuredWidth=finiteRange(this.plotWidth||400,400,0,MAX_SCROLL_CONTENT_WIDTH),{lo,hi,ticks}=this.domain(),formattedTicks=awaitingFitMeasurement||this.withoutValueAxis?[]:ticks.map(value=>({value,label:this.formatValueAxisTick(value)})),axisGutter=this.resolvedValueAxisGutter(formattedTicks,measuredWidth)+(this.yLabel?AXIS_TITLE_SPACE:0),rtl=this.effectiveDirection==="rtl",padBottom=PAD_BOTTOM+(this.xLabel?AXIS_TITLE_SPACE:0),plotX=rtl?PAD_RIGHT:axisGutter,plotY=PAD_TOP,plotH=Math.max(0,h-plotY-padBottom);let w,plotW,slot,fixedSlot;if(this.layout==="scroll"){const maxSlot=n>0?MAX_SCROLL_CONTENT_WIDTH/n:MAX_SCROLL_CONTENT_WIDTH;slot=finiteRange(this.barWidth,32,0,maxSlot),plotW=n*slot,w=axisGutter+plotW+PAD_RIGHT}else w=measuredWidth,plotW=Math.max(0,w-axisGutter-PAD_RIGHT),fixedSlot=this.fixedBarSlotWidth(n),slot=fixedSlot??(n>0?plotW/n:0);const recordSample=this.recordSample(),selectedIndices=new Set,renderedRows=new Set(recordSample.rowIndexes);for(let index=0;index<this.selectedIndices.length;index++){const candidate=this.selectedIndices[index];typeof candidate=="number"&&Number.isInteger(candidate)&&renderedRows.has(candidate)&&selectedIndices.add(candidate)}const barOrigins=this.effectiveType==="bar"&&!awaitingFitMeasurement?new Map(recordSample.rowIndexes.map(index=>{const fallback=plotX+index*slot,candidate=typeof this.barX=="function"?this.barX(index):fallback;return[index,finiteRange(candidate,fallback,-MAX_SCROLL_CONTENT_WIDTH,MAX_SCROLL_CONTENT_WIDTH)]})):new Map,grid=awaitingFitMeasurement||this.withoutValueAxis?[]:this.renderGrid(plotX,plotY,plotW,plotH,formattedTicks,lo,hi),marks=awaitingFitMeasurement?[]:this.effectiveType==="bar"?this.renderBars(plotX,plotY,plotH,slot,lo,hi,barOrigins,recordSample,selectedIndices):this.renderLines(plotX,plotY,plotW,plotH,lo,hi,recordSample,selectedIndices),categoryLabelX=i=>this.effectiveType==="bar"&&n>0?(barOrigins.get(i)??plotX+i*slot)+slot/2:plotX+(n>1?i/(n-1)*plotW:plotW/2),visibleLabelIndexes=this.visibleLabelIndexes(n,fixedSlot===void 0||this.effectiveType!=="bar"?plotW:n*slot,recordSample.rowIndexes,categoryLabelX),tickOverrides=new Map,renderedTickIndexes=[];for(const i of recordSample.rowIndexes){if(visibleLabelIndexes&&!visibleLabelIndexes.has(i))continue;const label=this.labels[i]??"",override=this.axisLabelText?.(label,i);override!==null&&(tickOverrides.set(i,override),renderedTickIndexes.push(i))}const categoryLabelPitch=(renderedTickIndexes.length?n/renderedTickIndexes.length:1)*(this.effectiveType==="bar"?slot:n>1?plotW/(n-1):plotW),categoryLabelWidth=Math.max(0,categoryLabelPitch-BAR_CORNER_RADIUS),tickFullLabels=renderedTickIndexes.map(i=>{const override=tickOverrides.get(i);return typeof override=="string"?override:this.labels[i]??""}),tickXs=renderedTickIndexes.map(categoryLabelX),categoryLabels=awaitingFitMeasurement?[]:renderedTickIndexes.map((i,position)=>{const fullLabel=tickFullLabels[position],x=tickXs[position],growth=categoryLabelGrowth(i,n),textAnchor=growth==="middle"?"middle":growth==="right"?rtl?"end":"start":rtl?"start":"end",labelExtent=sparseCategoryLabelExtent(tickFullLabels,tickXs,position,growth,categoryLabelPitch,categoryLabelWidth),displayLabel=this.displayCategoryLabel(fullLabel,labelExtent);return svg`<text
|
|
124
124
|
part="axis-label"
|
|
125
125
|
x=${x}
|
|
126
126
|
y=${plotY+plotH+CATEGORY_LABEL_OFFSET}
|
|
@@ -179,15 +179,15 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
179
179
|
<thead>
|
|
180
180
|
<tr>
|
|
181
181
|
<th scope="col">${this.localize("chartCategory")}</th>
|
|
182
|
-
${recordSample.seriesIndexes.map(datasetIndex=>{const series=this.datasets[datasetIndex];return html`<th scope="col">${series.label}</th>`})}
|
|
182
|
+
${recordSample.seriesIndexes.map(datasetIndex=>{const series=this.datasets[datasetIndex];return html`<th scope="col">${isolateHtml(series.label,direction)}</th>`})}
|
|
183
183
|
${showTableTotals?html`<th scope="col">${this.localize("chartTotal")}</th>`:nothing}
|
|
184
184
|
</tr>
|
|
185
185
|
</thead>
|
|
186
186
|
<tbody>
|
|
187
187
|
${recordSample.rowIndexes.map(index=>{const label=this.labels[index]??"";return html`<tr>
|
|
188
|
-
<th scope="row">${label}</th>
|
|
189
|
-
${recordSample.seriesIndexes.map(datasetIndex=>{const series=this.datasets[datasetIndex],value=series.data[index];return html`<td>${value==null||!Number.isFinite(value)?"":this.formatTableCell(value,{kind:"value",datasetIndex,index,label,seriesLabel:series.label},tableNumberFormat)}</td>`})}
|
|
190
|
-
${showTableTotals?(()=>{const total=this.tableTotalAt(index,recordSample.seriesIndexes);return html`<td>${total==null?"":this.formatTableCell(total,{kind:"total",datasetIndex:null,index,label,seriesLabel:null},tableNumberFormat)}</td>`})():nothing}
|
|
188
|
+
<th scope="row">${isolateHtml(label,direction)}</th>
|
|
189
|
+
${recordSample.seriesIndexes.map(datasetIndex=>{const series=this.datasets[datasetIndex],value=series.data[index];return html`<td>${isolateHtml(value==null||!Number.isFinite(value)?"":this.formatTableCell(value,{kind:"value",datasetIndex,index,label,seriesLabel:series.label},tableNumberFormat),direction)}</td>`})}
|
|
190
|
+
${showTableTotals?(()=>{const total=this.tableTotalAt(index,recordSample.seriesIndexes);return html`<td>${isolateHtml(total==null?"":this.formatTableCell(total,{kind:"total",datasetIndex:null,index,label,seriesLabel:null},tableNumberFormat),direction)}</td>`})():nothing}
|
|
191
191
|
</tr>`})}
|
|
192
192
|
</tbody>
|
|
193
193
|
</table>`:html`<ul
|
|
@@ -195,7 +195,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
195
195
|
class=${this.dataTableVisible?nothing:"sr-only"}
|
|
196
196
|
aria-label=${this.localize("chartData")}
|
|
197
197
|
>
|
|
198
|
-
${marksForA11y.map((_mark,index)=>html`<li>${this.markAnnouncement(index,marksForA11y)}</li>`)}
|
|
198
|
+
${marksForA11y.map((_mark,index)=>html`<li>${this.dataTableVisible?this.markListItem(index,marksForA11y):this.markAnnouncement(index,marksForA11y)}</li>`)}
|
|
199
199
|
</ul>`}
|
|
200
200
|
</div>
|
|
201
201
|
${this.legend?html`<div part="legend">
|
|
@@ -206,7 +206,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
206
206
|
data-encoding=${this.legendEncoding(i)}
|
|
207
207
|
style=${styleMap({backgroundColor:this.colorFor(i,s)})}
|
|
208
208
|
></span>
|
|
209
|
-
${s.label}${this.formatter||this.legendText?html`<span part="legend-text">${this.formatter?.({value:recordSample.rowIndexes.reduce((sum,index)=>{const value=s.data[index];return typeof value=="number"&&Number.isFinite(value)?finiteAdd(sum,value):sum},0),surface:"legend",datasetIndex:i,seriesLabel:s.label,axis:"y"})??this.legendText?.(s.label,i)}</span>`:nothing}
|
|
209
|
+
${s.label}${this.formatter||this.legendText?html`<span part="legend-text">${isolateHtml(this.formatter?.({value:recordSample.rowIndexes.reduce((sum,index)=>{const value=s.data[index];return typeof value=="number"&&Number.isFinite(value)?finiteAdd(sum,value):sum},0),surface:"legend",datasetIndex:i,seriesLabel:s.label,axis:"y"})??this.legendText?.(s.label,i),direction)}</span>`:nothing}
|
|
210
210
|
</span>
|
|
211
211
|
`})}
|
|
212
212
|
</div>`:nothing}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{forcedColorLegendSwatchStyles}from"./chart-forced-colors.js";const styles=css` :host { display: block; position: relative; inline-size: 100%; min-inline-size: 0; min-block-size: var(--lr-chart-height, var(--_lr-chart-height, var(--lr-size-280px))); block-size: auto; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); --_lr-chart-grid-color: var(--lr-color-border-subtle); --_lr-chart-tick-color: var(--lr-color-text-quiet); --_lr-chart-tick-font-size: var(--lr-font-size-2xs); --_lr-chart-legend-color: var(--lr-color-text); --_lr-chart-tooltip-bg: var(--lr-color-surface); --_lr-chart-tooltip-text: var(--lr-color-text); } [part='base'] { position: relative; inline-size: 100%; block-size: 100%; box-sizing: border-box; display: grid; grid-template-columns: minmax(0, 1fr); grid-template-areas: 'plot' 'notice' 'legend' 'table'; gap: var(--lr-space-xs); } :host([layout='scroll']) [part='base'] { overflow-x: auto; overflow-y: hidden; } svg { grid-area: plot; display: block; inline-size: 100%; block-size: var(--lr-chart-height, var(--_lr-chart-height, var(--lr-size-280px))); min-block-size: var(--lr-icon-button-size); overflow: hidden; } [part='grid-line'] { stroke: var(--lr-chart-grid-color, var(--_lr-chart-grid-color)); stroke-width: var(--lr-border-width-thin); } [part='axis-label'] { fill: var(--lr-chart-tick-color, var(--_lr-chart-tick-color)); font-size: var(--lr-chart-tick-font-size, var(--_lr-chart-tick-font-size)); font-family: var(--lr-font); } [part='axis-title'] { fill: var(--lr-chart-tick-color, var(--_lr-chart-tick-color)); font-size: var(--lr-font-size-xs); font-weight: var(--lr-font-weight-semibold); font-family: var(--lr-font); } [part='bar'] { cursor: pointer; } [data-mark-hit-target] { cursor: pointer; } :where([part='bar']):hover, :where([part='point']):hover, :where(.mark-hit-group):hover [part='bar'], :where(.mark-hit-group):hover [part='point'] { fill: color-mix(in oklab, currentColor, var(--lr-color-mix-partner) var(--lr-color-mix-hover)); } :where([part='bar']):active, :where([part='point']):active, :where(.mark-hit-group):active [part='bar'], :where(.mark-hit-group):active [part='point'] { fill: color-mix(in oklab, currentColor, var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='bar'][data-selected], [part='point'][data-selected] { stroke: var(--lr-lite-chart-selected-outline-color, var(--lr-color-brand)); stroke-width: var(--lr-lite-chart-selected-outline-width, var(--lr-border-width-medium)); } [part='bar']:focus-visible, [part='point']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } :where(.mark-hit-group):has([part='bar']:focus-visible, [part='point']:focus-visible) [data-mark-hit-target] { stroke: var(--lr-focus-ring-color); stroke-width: var(--lr-focus-ring-width); } [part='line'] { fill: none; stroke-width: var(--lr-border-width-medium); } [part='bar'], [part='line'], [part='point'], pattern { forced-color-adjust: none; } [part='point'] { cursor: pointer; } [part='legend'] { grid-area: legend; display: flex; flex-wrap: wrap; gap: var(--lr-space-s); justify-content: center; flex: 0 0 auto; } [part='legend-item'] { display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; gap: var(--lr-size-0-35em); font-size: var(--lr-size-0-8rem); color: var(--lr-chart-legend-color, var(--_lr-chart-legend-color)); } [part='legend-swatch'] { inline-size: var(--lr-size-0-7em); block-size: var(--lr-size-0-7em); border-radius: var(--lr-size-2px); flex: 0 0 auto; } ${forcedColorLegendSwatchStyles} [part='legend-text'] { margin-inline-start: var(--lr-space-2xs); color: var(--lr-chart-tick-color, var(--_lr-chart-tick-color)); } [part='data-table'][data-visually-hidden] { position: absolute; inline-size: var(--lr-size-1px); block-size: var(--lr-size-1px); overflow: clip; clip-path: inset(50%); white-space: nowrap; } [part='data-table'] { grid-area: table; min-inline-size: 0; max-inline-size: 100%; overflow-x: auto; overflow-y: hidden; } [part='data-truncation'] { grid-area: notice; margin: 0; padding: var(--lr-space-xs); color: var(--lr-color-warning); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part='base']:where([data-legend-position='top']) { grid-template-areas: 'legend' 'plot' 'notice' 'table'; } [part='base']:where([data-legend-position='inline-start']) { grid-template-areas: 'legend plot' 'notice notice' 'table table'; grid-template-columns: minmax(0, min(33cqi, var(--lr-chart-legend-side-max, var(--lr-size-15rem)))) minmax(0, 1fr); } [part='base']:where([data-legend-position='inline-end']) { grid-template-areas: 'plot legend' 'notice notice' 'table table'; grid-template-columns: minmax(0, 1fr) minmax(0, min(33cqi, var(--lr-chart-legend-side-max, var(--lr-size-15rem)))); } @container (max-width: 479px) { [part='base']:where([data-legend-position='inline-start']), [part='base']:where([data-legend-position='inline-end']) { grid-template-areas: 'plot' 'notice' 'legend' 'table'; grid-template-columns: minmax(0, 1fr); } } [part='data-table-toggle'] { align-self: flex-start; font: inherit; font-size: var(--lr-font-size-xs); min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); max-inline-size: 100%; white-space: normal; overflow-wrap: break-word; cursor: pointer; } [part='data-table-toggle']:hover { background: var(--lr-lite-chart-data-table-toggle-hover-bg, var(--lr-color-brand-quiet)); } [part='data-table-toggle']:active { background: var( --lr-lite-chart-data-table-toggle-active-bg, color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active)) ); } [part='data-table-toggle']:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } `;export{styles};
|
|
1
|
+
import{css}from"lit";import{forcedColorLegendSwatchStyles}from"./chart-forced-colors.js";const styles=css` :host { display: block; position: relative; inline-size: 100%; min-inline-size: 0; min-block-size: var(--lr-chart-height, var(--_lr-chart-height, var(--lr-size-280px))); block-size: auto; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); --_lr-chart-grid-color: var(--lr-color-border-subtle); --_lr-chart-tick-color: var(--lr-color-text-quiet); --_lr-chart-tick-font-size: var(--lr-font-size-2xs); --_lr-chart-legend-color: var(--lr-color-text); --_lr-chart-tooltip-bg: var(--lr-color-surface); --_lr-chart-tooltip-text: var(--lr-color-text); } [part='base'] { position: relative; inline-size: 100%; block-size: 100%; box-sizing: border-box; display: grid; grid-template-columns: minmax(0, 1fr); grid-template-areas: 'plot' 'notice' 'legend' 'table'; gap: var(--lr-space-xs); } :host([layout='scroll']) [part='base'] { overflow-x: auto; overflow-y: hidden; } svg { grid-area: plot; display: block; inline-size: 100%; block-size: var(--lr-chart-height, var(--_lr-chart-height, var(--lr-size-280px))); min-block-size: var(--lr-icon-button-size); overflow: hidden; } [part='grid-line'] { stroke: var(--lr-chart-grid-color, var(--_lr-chart-grid-color)); stroke-width: var(--lr-border-width-thin); } [part='axis-label'] { fill: var(--lr-chart-tick-color, var(--_lr-chart-tick-color)); font-size: var(--lr-chart-tick-font-size, var(--_lr-chart-tick-font-size)); font-family: var(--lr-font); } [part='axis-title'] { fill: var(--lr-chart-tick-color, var(--_lr-chart-tick-color)); font-size: var(--lr-font-size-xs); font-weight: var(--lr-font-weight-semibold); font-family: var(--lr-font); } [part='axis-label'], [part='axis-title'] { unicode-bidi: plaintext; } [part='bar'] { cursor: pointer; } [data-mark-hit-target] { cursor: pointer; } :where([part='bar']):hover, :where([part='point']):hover, :where(.mark-hit-group):hover [part='bar'], :where(.mark-hit-group):hover [part='point'] { fill: color-mix(in oklab, currentColor, var(--lr-color-mix-partner) var(--lr-color-mix-hover)); } :where([part='bar']):active, :where([part='point']):active, :where(.mark-hit-group):active [part='bar'], :where(.mark-hit-group):active [part='point'] { fill: color-mix(in oklab, currentColor, var(--lr-color-mix-partner) var(--lr-color-mix-active)); } [part='bar'][data-selected], [part='point'][data-selected] { stroke: var(--lr-lite-chart-selected-outline-color, var(--lr-color-brand)); stroke-width: var(--lr-lite-chart-selected-outline-width, var(--lr-border-width-medium)); } [part='bar']:focus-visible, [part='point']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } :where(.mark-hit-group):has([part='bar']:focus-visible, [part='point']:focus-visible) [data-mark-hit-target] { stroke: var(--lr-focus-ring-color); stroke-width: var(--lr-focus-ring-width); } [part='line'] { fill: none; stroke-width: var(--lr-border-width-medium); } [part='bar'], [part='line'], [part='point'], pattern { forced-color-adjust: none; } [part='point'] { cursor: pointer; } [part='legend'] { grid-area: legend; display: flex; flex-wrap: wrap; gap: var(--lr-space-s); justify-content: center; flex: 0 0 auto; } [part='legend-item'] { display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; gap: var(--lr-size-0-35em); font-size: var(--lr-size-0-8rem); color: var(--lr-chart-legend-color, var(--_lr-chart-legend-color)); } [part='legend-swatch'] { inline-size: var(--lr-size-0-7em); block-size: var(--lr-size-0-7em); border-radius: var(--lr-size-2px); flex: 0 0 auto; } ${forcedColorLegendSwatchStyles} [part='legend-text'] { margin-inline-start: var(--lr-space-2xs); color: var(--lr-chart-tick-color, var(--_lr-chart-tick-color)); } [part='data-table'][data-visually-hidden] { position: absolute; inline-size: var(--lr-size-1px); block-size: var(--lr-size-1px); overflow: clip; clip-path: inset(50%); white-space: nowrap; } [part='data-table'] { grid-area: table; min-inline-size: 0; max-inline-size: 100%; overflow-x: auto; overflow-y: hidden; } [part='data-truncation'] { grid-area: notice; margin: 0; padding: var(--lr-space-xs); color: var(--lr-color-warning); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part='base']:where([data-legend-position='top']) { grid-template-areas: 'legend' 'plot' 'notice' 'table'; } [part='base']:where([data-legend-position='inline-start']) { grid-template-areas: 'legend plot' 'notice notice' 'table table'; grid-template-columns: minmax(0, min(33cqi, var(--lr-chart-legend-side-max, var(--lr-size-15rem)))) minmax(0, 1fr); } [part='base']:where([data-legend-position='inline-end']) { grid-template-areas: 'plot legend' 'notice notice' 'table table'; grid-template-columns: minmax(0, 1fr) minmax(0, min(33cqi, var(--lr-chart-legend-side-max, var(--lr-size-15rem)))); } @container (max-width: 479px) { [part='base']:where([data-legend-position='inline-start']), [part='base']:where([data-legend-position='inline-end']) { grid-template-areas: 'plot' 'notice' 'legend' 'table'; grid-template-columns: minmax(0, 1fr); } } [part='data-table-toggle'] { align-self: flex-start; font: inherit; font-size: var(--lr-font-size-xs); min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); max-inline-size: 100%; white-space: normal; overflow-wrap: break-word; cursor: pointer; } [part='data-table-toggle']:hover { background: var(--lr-lite-chart-data-table-toggle-hover-bg, var(--lr-color-brand-quiet)); } [part='data-table-toggle']:active { background: var( --lr-lite-chart-data-table-toggle-active-bg, color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active)) ); } [part='data-table-toggle']:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } `;export{styles};
|
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
* `--lr-color-text`/`--lr-color-surface` custom properties every other themed surface reads. */
|
|
6
6
|
export declare function resolveIsDarkTheme(host:Element):boolean;
|
|
7
7
|
/** Re-invokes `onChange` whenever the resolved theme might have changed: an OS-level
|
|
8
|
-
* prefers-color-scheme flip, or a
|
|
9
|
-
*
|
|
8
|
+
* prefers-color-scheme flip, or a theme attribute change anywhere in `host`'s flattened ancestor
|
|
9
|
+
* chain, including slots and shadow hosts. A consumer re-theming via `--lr-theme-*` custom properties
|
|
10
10
|
* fires no DOM event on its own -- this mirrors qr-code.class.ts's/heatmap.class.ts's/
|
|
11
11
|
* chart.class.ts's own theme-reactive canvases, the established pattern in this codebase for a
|
|
12
12
|
* component that can't just let CSS repaint itself. Returns a cleanup function. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getScratchCtx}from"../../../internal/canvas.js";function parseRgbTriplet(value){const match=value.match(/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/);return match?[Number(match[1]),Number(match[2]),Number(match[3])]:null}function parseHexTriplet(value){const match=value.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!match)return null;const hex=match[1],full=hex.length===3?hex.split("").map(c=>c+c).join(""):hex,num=Number.parseInt(full,16);return[num>>16&255,num>>8&255,num&255]}function toRgb(value,ownerDocument){const trimmed=value.trim();if(!trimmed)return null;const direct=parseRgbTriplet(trimmed)??parseHexTriplet(trimmed);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return null;ctx.fillStyle="rgb(1, 2, 3)",ctx.fillStyle=trimmed;const first=ctx.fillStyle;if(ctx.fillStyle="rgb(4, 5, 6)",ctx.fillStyle=trimmed,ctx.fillStyle!==first)return null;ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[red,green,blue,alpha]=ctx.getImageData(0,0,1,1).data;return alpha===0?null:[red,green,blue]}function relativeLuminance([r,g,b]){const[lr,lg,lb]=[r,g,b].map(channel=>{const value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4});return .2126*lr+.7152*lg+.0722*lb}function resolveIsDarkTheme(host){const view=host.ownerDocument.defaultView;if(!view||typeof view.getComputedStyle!="function")return!1;const probe=host.ownerDocument.createElement("span");probe.setAttribute("aria-hidden","true"),probe.setAttribute("style",["position:fixed","inline-size:0","block-size:0","overflow:hidden","pointer-events:none","color:var(--lr-color-text)","background-color:var(--lr-color-surface)"].join(";"));try{(host.shadowRoot??host).append(probe);const style=view.getComputedStyle(probe),text=toRgb(style.color,host.ownerDocument),surface=toRgb(style.backgroundColor,host.ownerDocument);return!!(text&&surface&&relativeLuminance(text)>relativeLuminance(surface))}catch{return!1}finally{probe.remove()}}function watchDarkTheme(host,onChange){const view=host.ownerDocument.defaultView;if(!view||!host.isConnected)return()=>{};let active=!0;const update=()=>{!active||!host.isConnected||host.ownerDocument.defaultView!==view||onChange()};let colorSchemeQuery;try{colorSchemeQuery=view.matchMedia?.("(prefers-color-scheme: dark)"),colorSchemeQuery?.addEventListener("change",update)}catch{colorSchemeQuery=void 0}let observer;const Observer=view.MutationObserver;if(typeof Observer=="function"){const targets=[host];let parent=host
|
|
1
|
+
import{getScratchCtx}from"../../../internal/canvas.js";import{flattenedThemeParent,THEME_ATTRIBUTES}from"../../../internal/theme-observation.js";function parseRgbTriplet(value){const match=value.match(/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/);return match?[Number(match[1]),Number(match[2]),Number(match[3])]:null}function parseHexTriplet(value){const match=value.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!match)return null;const hex=match[1],full=hex.length===3?hex.split("").map(c=>c+c).join(""):hex,num=Number.parseInt(full,16);return[num>>16&255,num>>8&255,num&255]}function toRgb(value,ownerDocument){const trimmed=value.trim();if(!trimmed)return null;const direct=parseRgbTriplet(trimmed)??parseHexTriplet(trimmed);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return null;ctx.fillStyle="rgb(1, 2, 3)",ctx.fillStyle=trimmed;const first=ctx.fillStyle;if(ctx.fillStyle="rgb(4, 5, 6)",ctx.fillStyle=trimmed,ctx.fillStyle!==first)return null;ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[red,green,blue,alpha]=ctx.getImageData(0,0,1,1).data;return alpha===0?null:[red,green,blue]}function relativeLuminance([r,g,b]){const[lr,lg,lb]=[r,g,b].map(channel=>{const value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4});return .2126*lr+.7152*lg+.0722*lb}function resolveIsDarkTheme(host){const view=host.ownerDocument.defaultView;if(!view||typeof view.getComputedStyle!="function")return!1;const probe=host.ownerDocument.createElement("span");probe.setAttribute("aria-hidden","true"),probe.setAttribute("style",["position:fixed","inline-size:0","block-size:0","overflow:hidden","pointer-events:none","color:var(--lr-color-text)","background-color:var(--lr-color-surface)"].join(";"));try{(host.shadowRoot??host).append(probe);const style=view.getComputedStyle(probe),text=toRgb(style.color,host.ownerDocument),surface=toRgb(style.backgroundColor,host.ownerDocument);return!!(text&&surface&&relativeLuminance(text)>relativeLuminance(surface))}catch{return!1}finally{probe.remove()}}function watchDarkTheme(host,onChange){const view=host.ownerDocument.defaultView;if(!view||!host.isConnected)return()=>{};let active=!0;const update=()=>{!active||!host.isConnected||host.ownerDocument.defaultView!==view||onChange()};let colorSchemeQuery;try{colorSchemeQuery=view.matchMedia?.("(prefers-color-scheme: dark)"),colorSchemeQuery?.addEventListener("change",update)}catch{colorSchemeQuery=void 0}let observer;const Observer=view.MutationObserver;if(typeof Observer=="function"){const targets=[host];let parent=flattenedThemeParent(host);for(;parent&&!targets.includes(parent);)targets.push(parent),parent=flattenedThemeParent(parent);try{observer=new Observer(update);for(const target of targets)observer.observe(target,{attributes:!0,attributeFilter:[...THEME_ATTRIBUTES]})}catch{observer?.disconnect(),observer=void 0}}return()=>{active&&(active=!1,colorSchemeQuery?.removeEventListener("change",update),observer?.disconnect())}}export{resolveIsDarkTheme,watchDarkTheme};
|
|
@@ -39,6 +39,14 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
39
39
|
* whereas a button is independently focusable, has its own accessible name,
|
|
40
40
|
* and composes cleanly with click-to-select.
|
|
41
41
|
*
|
|
42
|
+
* While an `lr-dropdown`, `lr-popover` or `lr-context-menu` opened from the `actions` slot is open
|
|
43
|
+
* (including one composed inside another component's shadow root), the row is in its menu-open state:
|
|
44
|
+
* the host matches `:state(menu-open)`, `[part="base"]` also carries `base-menu-open`, and the row
|
|
45
|
+
* keeps its hover tint. The menu opens into the browser top layer, where Chromium and WebKit stop
|
|
46
|
+
* matching `:hover` and `:focus-within` on the row while the pointer or focus is inside it, so key
|
|
47
|
+
* a hover- or focus-revealed actions trigger on this state as well -- otherwise the trigger hides
|
|
48
|
+
* while its menu is open, and a `display`-based reveal hides the menu with it.
|
|
49
|
+
*
|
|
42
50
|
* @customElement lr-conversation-item
|
|
43
51
|
* @slot actions - Overflow/icon-button controls (for example a pin/delete
|
|
44
52
|
* button or a `lr-menu` trigger) rendered at the trailing edge of the row.
|
|
@@ -69,7 +77,11 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
69
77
|
* (that's treated as an implicit cancel).
|
|
70
78
|
* @event blur - Re-dispatched from the in-place rename input as a bubbling, composed event.
|
|
71
79
|
* @event focus - Re-dispatched from the in-place rename input as a bubbling, composed event.
|
|
72
|
-
* @csspart base - The outer row wrapper (plain, no ARIA role) laying out `[part="select-button"]`, the rename button, and `actions`.
|
|
80
|
+
* @csspart base - The outer row wrapper (plain, no ARIA role) laying out `[part="select-button"]`, the rename button, and `actions`. Also carries `base-menu-open` while a menu opened from `actions` is open.
|
|
81
|
+
* @csspart base-menu-open - State alias on `base` while an `lr-dropdown`, `lr-popover` or
|
|
82
|
+
* `lr-context-menu` opened from the `actions` slot is open. Style a hover- or focus-revealed actions trigger on it too, e.g.
|
|
83
|
+
* `::part(base-menu-open) { --app-actions-opacity: 1; }`: the open menu sits in the top layer,
|
|
84
|
+
* where Chromium and WebKit stop matching `:hover`/`:focus-within` on the row.
|
|
73
85
|
* @csspart active-indicator - A decorative inline indicator rendered only while the row is active.
|
|
74
86
|
* @csspart select-button - The selectable region (`role="button"`, removed while renaming -- see the class doc). Wraps `content` and `timestamp`.
|
|
75
87
|
* @csspart start - The wrapper around the `start` slot, inside `select-button`. Always rendered, but `hidden` while the slot is empty.
|
|
@@ -105,6 +117,8 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
|
|
|
105
117
|
* plus an `excerpt`); `center` reads better for a reliably single-line row with a taller trailing
|
|
106
118
|
* action (e.g. `actions`), but is not the default because it would misalign every existing
|
|
107
119
|
* multi-line row's title against its own baseline.
|
|
120
|
+
* @cssstate menu-open - Present while an `lr-dropdown`, `lr-popover` or `lr-context-menu` opened
|
|
121
|
+
* from the `actions` slot is open, e.g. `lr-conversation-item:is(:hover, :focus-within, :state(menu-open)) .row-menu`.
|
|
108
122
|
* @status stable
|
|
109
123
|
* @since 4.0.0
|
|
110
124
|
*/
|
|
@@ -153,6 +167,8 @@ spellcheck:boolean;
|
|
|
153
167
|
autocapitalize:string;private autocorrectValue;
|
|
154
168
|
/** Native editing-assistance state forwarded as canonical `autocorrect="on"|"off"`. String
|
|
155
169
|
* writes are normalized for framework and plain-DOM interoperability; reads are boolean. */
|
|
156
|
-
get autocorrect():boolean;set autocorrect(next:boolean|string);private renaming;private draftLabel;private hasActionsSlot;private hasStartSlot;private hasContentSlot;private hasMetaSlot;private hasExcerptSlot;private labelInput?;private blurCommitGeneration;
|
|
170
|
+
get autocorrect():boolean;set autocorrect(next:boolean|string);private renaming;private draftLabel;private hasActionsSlot;private hasStartSlot;private hasContentSlot;private hasMetaSlot;private hasExcerptSlot;private labelInput?;private blurCommitGeneration;private readonly internals;
|
|
171
|
+
/** Whether a menu opened from the `actions` slot is open -- see the class doc's menu-open note. */
|
|
172
|
+
private readonly actionsOverlay;connectedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private focusRenameInput;private get normalizedTimestamp();private select;
|
|
157
173
|
/** Activates the selectable row, matching a native button host. */
|
|
158
174
|
click():void;private startRename;private restoreOptionFocus;private commitRename;private cancelRename;private onOptionClick;private onOptionKeyDown;private onRenameButtonClick;private onLabelInputChange;private onLabelInputKeyDown;private onLabelInputFocus;private onLabelInputBlur;private onActionsSlotChange;private syncStartSlot;private onContentSlotChange;private onMetaSlotChange;private onExcerptSlotChange;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-conversation-item':LyraConversationItem;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{styles}from"./conversation-item.styles.js";import{autocorrectConverter,normalizeAutocorrect,presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter,spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_rename,LYRA_DEFAULT_untitledConversation}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function pencilIcon(){return svg`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,svg}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{styles}from"./conversation-item.styles.js";import{autocorrectConverter,normalizeAutocorrect,presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter,spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{setCustomState}from"../../../internal/custom-states.js";import{SlottedOverlayController}from"../../../internal/slotted-overlay-controller.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_rename,LYRA_DEFAULT_untitledConversation}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function pencilIcon(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -11,8 +11,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
11
11
|
aria-hidden="true"
|
|
12
12
|
focusable="false"
|
|
13
13
|
><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg>
|
|
14
|
-
`}function defaultFormatTimestamp(date,locale,now=new Date){if(date.toDateString()===now.toDateString())return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit"}).format(date);const sameYear=date.getFullYear()===now.getFullYear();return getDateTimeFormat(locale,sameYear?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"}).format(date)}class LyraConversationItem extends LyraElement{constructor(){super(...arguments),this.conversationId="",this.label="",this.excerpt="",this.active=!1,this.compact=!1,this.renamable=!0,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.renaming=!1,this.draftLabel="",this.hasActionsSlot=!1,this.hasStartSlot=!1,this.hasContentSlot=!1,this.hasMetaSlot=!1,this.hasExcerptSlot=!1,this.blurCommitGeneration=0,this.onOptionClick=()=>{this.renaming||this.select()},this.onOptionKeyDown=e=>{this.renaming||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.select())},this.onRenameButtonClick=()=>{this.startRename()},this.onLabelInputChange=e=>{this.draftLabel=e.target.value},this.onLabelInputKeyDown=e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===229)&&(e.key==="Enter"?(e.preventDefault(),this.commitRename(!0)):e.key==="Escape"&&(e.preventDefault(),this.cancelRename(!0)))},this.onLabelInputFocus=()=>{this.emit("focus",null)},this.onLabelInputBlur=event=>{if(this.emit("blur",null),!this.renaming)return;const generation=++this.blurCommitGeneration,synthetic=!event.isTrusted;queueMicrotask(()=>{generation!==this.blurCommitGeneration||!this.renaming||!this.isConnected||!synthetic&&activeElementIn(this.shadowRoot)===this.labelInput||this.commitRename()})},this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.syncStartSlot=()=>{this.hasStartSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="start")},this.onContentSlotChange=e=>{this.hasContentSlot=e.target.assignedElements({flatten:!0}).length>0},this.onMetaSlotChange=e=>{this.hasMetaSlot=e.target.assignedElements({flatten:!0}).length>0},this.onExcerptSlotChange=e=>{this.hasExcerptSlot=e.target.assignedElements({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,rename:LYRA_DEFAULT_rename,untitledConversation:LYRA_DEFAULT_untitledConversation}}static{this.styles=[LyraElement.styles,styles]}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.renaming&&this.focusRenameInput()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.syncStartSlot(),this.hasContentSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="content"),this.hasMetaSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="meta"),this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt")),changed.has("renamable")&&!this.renamable&&this.renaming&&this.cancelRename()}updated(changed){super.updated(changed),changed.has("renaming")&&this.renaming&&this.focusRenameInput()}focusRenameInput(){this.labelInput?.focus(),this.labelInput?.select()}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}select(){this.emit("lr-select",{conversationId:this.conversationId})}click(){this.renaming?this.labelInput?.click():this.renderRoot.querySelector('[part="select-button"]')?.click()}startRename(){!this.renamable||this.renaming||(this.draftLabel=this.label,this.renaming=!0)}restoreOptionFocus(){this.updateComplete.then(()=>{this.renderRoot.querySelector('[part="select-button"]')?.focus()})}commitRename(restoreFocus=!1){this.renaming=!1,restoreFocus&&this.restoreOptionFocus();const next=this.draftLabel.trim();!next||next===this.label||this.emit("lr-rename",{conversationId:this.conversationId,label:next})}cancelRename(restoreFocus=!1){this.renaming=!1,restoreFocus&&this.restoreOptionFocus()}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>defaultFormatTimestamp(date,this.effectiveLocale)),displayLabel=this.label||this.localize("untitledConversation"),showRenameButton=this.renamable&&!this.renaming,renameLabel=this.localize("rename",void 0,{title:displayLabel});return html`
|
|
15
|
-
<div part
|
|
14
|
+
`}function defaultFormatTimestamp(date,locale,now=new Date){if(date.toDateString()===now.toDateString())return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit"}).format(date);const sameYear=date.getFullYear()===now.getFullYear();return getDateTimeFormat(locale,sameYear?{month:"short",day:"numeric"}:{month:"short",day:"numeric",year:"numeric"}).format(date)}class LyraConversationItem extends LyraElement{constructor(){super(...arguments),this.conversationId="",this.label="",this.excerpt="",this.active=!1,this.compact=!1,this.renamable=!0,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.renaming=!1,this.draftLabel="",this.hasActionsSlot=!1,this.hasStartSlot=!1,this.hasContentSlot=!1,this.hasMetaSlot=!1,this.hasExcerptSlot=!1,this.blurCommitGeneration=0,this.internals=attachInternalsSafely(this),this.actionsOverlay=new SlottedOverlayController(this,()=>this.renderRoot?.querySelector('slot[name="actions"]')),this.onOptionClick=()=>{this.renaming||this.select()},this.onOptionKeyDown=e=>{this.renaming||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.select())},this.onRenameButtonClick=()=>{this.startRename()},this.onLabelInputChange=e=>{this.draftLabel=e.target.value},this.onLabelInputKeyDown=e=>{e.stopPropagation(),!(e.isComposing||e.keyCode===229)&&(e.key==="Enter"?(e.preventDefault(),this.commitRename(!0)):e.key==="Escape"&&(e.preventDefault(),this.cancelRename(!0)))},this.onLabelInputFocus=()=>{this.emit("focus",null)},this.onLabelInputBlur=event=>{if(this.emit("blur",null),!this.renaming)return;const generation=++this.blurCommitGeneration,synthetic=!event.isTrusted;queueMicrotask(()=>{generation!==this.blurCommitGeneration||!this.renaming||!this.isConnected||!synthetic&&activeElementIn(this.shadowRoot)===this.labelInput||this.commitRename()})},this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.syncStartSlot=()=>{this.hasStartSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="start")},this.onContentSlotChange=e=>{this.hasContentSlot=e.target.assignedElements({flatten:!0}).length>0},this.onMetaSlotChange=e=>{this.hasMetaSlot=e.target.assignedElements({flatten:!0}).length>0},this.onExcerptSlotChange=e=>{this.hasExcerptSlot=e.target.assignedElements({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,rename:LYRA_DEFAULT_rename,untitledConversation:LYRA_DEFAULT_untitledConversation}}static{this.styles=[LyraElement.styles,styles]}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.renaming&&this.focusRenameInput()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.syncStartSlot(),this.hasContentSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="content"),this.hasMetaSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="meta"),this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt")),changed.has("renamable")&&!this.renamable&&this.renaming&&this.cancelRename(),setCustomState(this.internals,"menu-open",this.actionsOverlay.open)}updated(changed){super.updated(changed),changed.has("renaming")&&this.renaming&&this.focusRenameInput()}focusRenameInput(){this.labelInput?.focus(),this.labelInput?.select()}get normalizedTimestamp(){return normalizeLyraTimestamp(this.timestamp)}select(){this.emit("lr-select",{conversationId:this.conversationId})}click(){this.renaming?this.labelInput?.click():this.renderRoot.querySelector('[part="select-button"]')?.click()}startRename(){!this.renamable||this.renaming||(this.draftLabel=this.label,this.renaming=!0)}restoreOptionFocus(){this.updateComplete.then(()=>{this.renderRoot.querySelector('[part="select-button"]')?.focus()})}commitRename(restoreFocus=!1){this.renaming=!1,restoreFocus&&this.restoreOptionFocus();const next=this.draftLabel.trim();!next||next===this.label||this.emit("lr-rename",{conversationId:this.conversationId,label:next})}cancelRename(restoreFocus=!1){this.renaming=!1,restoreFocus&&this.restoreOptionFocus()}render(){const ts=this.normalizedTimestamp,formatter=this.formatTimestamp??(date=>defaultFormatTimestamp(date,this.effectiveLocale)),displayLabel=this.label||this.localize("untitledConversation"),showRenameButton=this.renamable&&!this.renaming,renameLabel=this.localize("rename",void 0,{title:displayLabel});return html`
|
|
15
|
+
<div part=${this.actionsOverlay.open?"base base-menu-open":"base"}>
|
|
16
16
|
${this.active?html`<span part="active-indicator" aria-hidden="true"></span>`:nothing}
|
|
17
17
|
<div
|
|
18
18
|
part="select-button"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";const styles=css`:host{font-size:var(--lr-font-size-md-sm);line-height:var(--lr-line-height-1-4);display:block}[part
|
|
1
|
+
import{css}from"lit";const styles=css`:host{font-size:var(--lr-font-size-md-sm);line-height:var(--lr-line-height-1-4);display:block}[part~=base]{align-items:var(--lr-conversation-item-align,flex-start);gap:var(--lr-space-xs);padding:var(--lr-space-s) var(--lr-space-m);border-radius:var(--lr-radius);transition:background-color var(--lr-transition-fast);display:flex;position:relative}[part=active-indicator]{inset-block:0;inset-inline:var(--lr-conversation-item-active-indicator-inset-inline,0 auto);inline-size:var(--lr-conversation-item-active-indicator-width,var(--lr-size-2px));box-sizing:border-box;border-radius:var(--lr-radius-xs);background:var(--lr-conversation-item-active-indicator-color,var(--lr-color-brand));pointer-events:none;z-index:var(--lr-layer-content);position:absolute}:host([compact]) [part~=base]{padding:var(--lr-conversation-item-compact-padding,var(--lr-space-xs) var(--lr-space-s));gap:var(--lr-conversation-item-compact-gap,var(--lr-space-2xs))}:host(:hover) [part~=base],[part~=base-menu-open]{background:color-mix(in srgb, var(--lr-color-text) 6%, transparent)}:host(:active) [part~=base]{background:color-mix(in oklab, transparent, var(--lr-color-mix-partner) var(--lr-color-mix-active))}:host([active]) [part~=base]{background:var(--lr-conversation-item-active-bg,var(--lr-color-brand-quiet))}:host([active]:active) [part~=base]{background:color-mix(in oklab, var(--lr-conversation-item-active-bg,var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active))}:host([active]) [part=excerpt],:host([active]) [part=timestamp]{color:var(--lr-conversation-item-active-color,var(--lr-color-text))}[part=select-button]{align-items:var(--lr-conversation-item-align,flex-start);gap:var(--lr-space-s);cursor:pointer;-webkit-tap-highlight-color:transparent;outline:none;flex:auto;min-inline-size:0;display:flex}[part=start]{min-inline-size:var(--lr-size-1-5rem);min-block-size:var(--lr-size-1-5rem);flex:none;justify-content:center;align-items:center;display:inline-flex}[part=start][hidden]{display:none}[part=select-button]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part=content]{gap:var(--lr-size-0-125rem);flex-direction:column;flex:auto;min-inline-size:0;display:flex}:host([compact]) [part=content]{gap:0}[part=label]{text-overflow:ellipsis;white-space:nowrap;font-weight:var(--lr-font-weight-semibold);color:var(--lr-color-text);display:block;overflow:hidden}[part=label-input]{box-sizing:border-box;inline-size:100%;padding:var(--lr-size-0-125rem) var(--lr-space-xs);border:var(--lr-border-width-thin) solid var(--lr-color-brand);border-radius:calc(var(--lr-radius) * .6);background:var(--lr-color-surface);color:var(--lr-color-text);font:inherit;font-weight:var(--lr-font-weight-semibold);display:block}[part=label-input]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part=excerpt]{text-overflow:ellipsis;white-space:nowrap;color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-sm);display:block;overflow:hidden}[part=excerpt][hidden]{display:none}[part=timestamp]{white-space:nowrap;color:var(--lr-color-text-quiet);font-size:var(--lr-font-size-xs);font-variant-numeric:tabular-nums;flex:none;align-self:flex-start}[part=rename-button]{font:inherit;min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);border-radius:calc(var(--lr-radius) * .6);color:var(--lr-color-text-quiet);cursor:pointer;-webkit-tap-highlight-color:transparent;transition:background-color var(--lr-transition-fast);background:0 0;border:none;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}[part=rename-button]:hover{background:color-mix(in srgb, var(--lr-color-text) 8%, transparent);color:var(--lr-color-text)}[part=rename-button]:active{background:color-mix(in oklab, transparent, var(--lr-color-mix-partner) var(--lr-color-mix-active));color:var(--lr-color-text)}[part=rename-button]:focus-visible{outline:var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);outline-offset:var(--lr-focus-ring-offset)}[part=rename-button] svg{display:block}[part=actions]{align-items:center;gap:var(--lr-space-xs);flex:none;display:flex}[part=actions][hidden]{display:none}@media (prefers-reduced-motion:reduce){[part~=base],[part=rename-button]{transition:none!important}}`;export{styles};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteInteger}from"../../../internal/numbers.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights}from"../../../internal/text-highlights.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{MarkdownCodeHeaderController,renderMarkdownCodeHeader}from"./markdown-code-header.js";import{MarkdownFallbackCodeScanner}from"./markdown-fallback-code.js";import{MarkdownProgressiveSession,markdownProgressiveEligible}from"./markdown-progressive.js";import{addFailedHighlightKey,applyMarkdownAriaBusy,applyMarkdownFragmentAnchor,applyMarkdownTextQuoteAnchor,beginMarkdownDepsLoad,getCachedHighlight,hitTestHighlightRanges,HIGHLIGHT_CACHE_MAX,internalLinkHrefFrom,markdownAnchorFromTarget,markdownTableRegionLabel,markdownHasTableWrappers,labelMarkdownTableWrappers,markdownHighlightConfigChanged,markdownLanguageSetChanged,markdownMathPeerError,markdownNeedsReparse,MarkdownOwnedAnimationFrameController,MarkdownParserController,normalizeMarkdownHtmlMode,normalizeMarkdownStreamingRender,createMarkdownRenderContext,finishMarkdownHtml,markdownSanitizerPolicy,normalizeMarkdownLeadingTabs,parseMarkdownDocument,processPendingHighlights,renderMarkdownContent,renderMarkdownDocument,repaintMarkdownHighlights,resolveMarkdownDarkTheme,setCachedHighlight}from"./markdown-shared.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_markdownTableRegion}from"../../../internal/default-strings.generated.js";const HIGHLIGHT_FAILURE_WARNING_KEY="lyra-markdown-highlight-failed",HIGHLIGHT_FAILURE_WARNING="<lr-markdown>/<lr-markdown-core>: Syntax highlighting could not complete. Code is rendered as plain text.";function keyboardHighlightIdFrom(ranges,event){const coordinateLess=event.clientX===0&&event.clientY===0&&event.screenX===0&&event.screenY===0;if(event.detail!==0&&!coordinateLess)return null;const anchor=event.composedPath().find(target=>markdownAnchorFromTarget(target)!==void 0);if(!anchor)return null;for(let index=ranges.length-1;index>=0;index--){const range=ranges[index];if(range)try{if(range.range.intersectsNode(anchor))return range.id}catch{}}return null}class LyraMarkdownRuntimeElement extends LyraElement{static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed,markdownTableRegion:LYRA_DEFAULT_markdownTableRegion}}}function createMarkdownVariantContext(tag,katexState){return{tag,connectedInstances:new Set,sharedParser:new MarkdownParserController,katexState}}class MarkdownRuntimeBase extends DocumentAnchorTarget(LyraMarkdownRuntimeElement){constructor(){super(),this.anchorKinds=["fragment","text-quote"],this.renderedHtml=null,this.renderedBlocks=[],this.streamingTail=null,this.progressiveRevision=0,this.isDarkTheme=!1,this.boundLocalize=this.localize.bind(this),this.hasTableWrappers=!1,this.fallbackCode=new MarkdownFallbackCodeScanner,this.parser=new MarkdownParserController,this.headingTree=[],this.markdownTextScopeBuilds=0,this.resolvedHighlightRanges=[],this.mathFailureReported=!1,this.highlightCache=new Map,this.highlightToken=0,this.streamingRenderFrames=new MarkdownOwnedAnimationFrameController,this.failedHighlightKeys=new Set,this.inFlightHighlightKeys=new Map,this.progressiveAdopted=!1,this.progressiveRebuild=!1,this.progressiveInputGeneration=0,this.codeBlocks=[],this.handleKatexResolved=()=>{this.isConnected&&(this.progressiveSession&&this.streaming?(this.progressiveSession.invalidateMath(),this.scheduleStreamingRender()):this.renderMarkdown())},this.onContentClick=event=>{if(this.codeHeader.handleClick(event))return;const href=internalLinkHrefFrom(event,this.internalLinkPrefix);href!==null&&event.preventDefault();const highlightId=hitTestHighlightRanges(this.resolvedHighlightRanges,event.clientX,event.clientY)??keyboardHighlightIdFrom(this.resolvedHighlightRanges,event);highlightId&&this.emit("lr-highlight-activate",{highlightId}),href!==null&&this.emit("lr-link-click",{href})},new ThemeWatcher(this,()=>this.refreshTheme()),this.codeHeader=new MarkdownCodeHeaderController(this,{isEnabled:()=>this.codeBlockHeader||this.codeBlockChrome,contentVersion:()=>this.progressiveSession?this.renderedBlocks:this.renderedHtml,getContentRoot:()=>this.contentRoot(),localize:this.boundLocalize,buildHeader:(frame,language)=>renderMarkdownCodeHeader(frame,language),emitCopy:outcome=>this.emit("lr-copy",outcome),emitCopyError:outcome=>this.emit("lr-copy-error",outcome)})}get marked(){return this.parser.get(this.deps?.marked)}refreshTheme(){this.isDarkTheme=resolveMarkdownDarkTheme(this)}connectedCallback(){super.connectedCallback(),this.markdownVariant.connectedInstances.add(this),this.refreshTheme(),beginMarkdownDepsLoad(this,resolved=>{this.deps=resolved,this.renderMarkdown(),this.requestUpdate()})}disconnectedCallback(){this.markdownVariant.connectedInstances.delete(this),super.disconnectedCallback(),this.highlightToken++,this.cancelStreamingRender(),this.highlightHandle?.release(),this.highlightHandle=void 0,this.textQuoteIndexCache=void 0,this.fallbackCode.reset()}adoptedCallback(){super.adoptedCallback(),this.codeHeader.hostAdopted(),this.cancelStreamingRender(),this.streaming&&this.progressiveSession&&this.scheduleStreamingRender()}firstUpdated(changed){super.firstUpdated(changed);const contentRoot=this.renderRoot.querySelector('[part="content"]');contentRoot&&this.bindTextSelection(contentRoot)}willUpdate(changed){super.willUpdate(changed);const active=this.shadowRoot?.activeElement,selector='[part~="code-block"], [part~="code-block-copy"], [part~="table-wrapper"]';if(active?.matches(selector)&&(this.rememberedFocus={node:active,index:[...this.renderRoot.querySelectorAll(selector)].indexOf(active),selector}),changed.has("math")&&(this.mathFailureReported=!1),!this.deps||!markdownNeedsReparse(changed))return;const progressive=normalizeMarkdownStreamingRender(this.streamingRender)==="progressive",configurationChanged=[...changed.keys()].some(key=>key!=="content"&&key!=="streaming"&&markdownNeedsReparse(new Map([[key,void 0]])));(markdownHighlightConfigChanged(changed)||!progressive&&(changed.has("content")||changed.has("streaming")))&&this.highlightToken++,markdownHighlightConfigChanged(changed)&&(this.failedHighlightKeys.clear(),markdownLanguageSetChanged(changed)&&this.highlightCache.clear()),progressive?configurationChanged&&(this.progressiveRebuild=!0):this.resetProgressiveMarkdown(),changed.has("content")&&this.progressiveInputGeneration++,this.streaming?(this.progressiveAdopted&&(this.progressiveSession?.resume(),this.progressiveAdopted=!1),this.progressiveSession?.update(this.content??""),this.progressiveSession&&this.syncProgressiveMarkdown(),this.scheduleStreamingRender()):(this.cancelStreamingRender(),(changed.has("content")&&!changed.has("streaming")||configurationChanged)&&this.resetProgressiveMarkdown(),this.renderMarkdown())}cancelStreamingRender(){const handle=this.streamingRenderRaf;this.streamingRenderRaf=void 0,!this.streamingRenderFrames.cancel()&&handle!==void 0&&this.ownerDocument.defaultView?.cancelAnimationFrame(handle)}scheduleStreamingRender(){if(this.streamingRenderRaf!==void 0)return;const view=this.ownerDocument.defaultView;if(!view){this.isConnected&&this.runStreamingFrame();return}const handle=this.streamingRenderFrames.request(view,()=>{this.streamingRenderRaf=void 0,this.isConnected&&this.ownerDocument.defaultView===view&&this.runStreamingFrame()});handle===void 0?this.isConnected&&this.runStreamingFrame():this.streamingRenderFrames.handle===handle&&(this.streamingRenderRaf=handle)}runStreamingFrame(){normalizeMarkdownStreamingRender(this.streamingRender)==="progressive"?this.renderProgressiveMarkdown():this.renderMarkdown()}async getUpdateComplete(){await super.getUpdateComplete();const generation=this.progressiveInputGeneration,remaining=(this.content?.length??0)-(this.progressiveSession?.end??0),cap=Math.ceil(Math.max(0,remaining)/65536)+2;for(let frames=0;frames<cap&&this.streamingRenderRaf!==void 0&&(await this.streamingRenderFrames.settled,await super.getUpdateComplete(),generation===this.progressiveInputGeneration);frames++);return super.getUpdateComplete()}updated(changed){super.updated(changed),applyMarkdownAriaBusy(this,!this.deps||this.streaming);const renderedChanged=changed.has("renderedHtml")||changed.has("renderedBlocks");if(renderedChanged&&(this.hasTableWrappers=markdownHasTableWrappers(this.contentRoot())),!this.hasTableWrappers)this.tableRegionLabel=void 0;else{const tableLabel=markdownTableRegionLabel(this.boundLocalize);(renderedChanged||tableLabel!==this.tableRegionLabel)&&(this.tableRegionLabel=tableLabel,labelMarkdownTableWrappers(this.contentRoot(),tableLabel))}const remembered=this.rememberedFocus;if(this.rememberedFocus=void 0,remembered&&!remembered.node.isConnected){let active=this.ownerDocument.activeElement;for(;active?.shadowRoot?.activeElement;)active=active.shadowRoot.activeElement;if(!active||active===this.ownerDocument.body||active===this.ownerDocument.documentElement){const target=this.renderRoot.querySelectorAll(remembered.selector)[remembered.index];target?target.focus({preventScroll:!0}):this.streaming&&(this.rememberedFocus=remembered)}}const locale=this.effectiveLocale,localeChanged=this.textQuoteLocale!==void 0&&this.textQuoteLocale!==locale;this.textQuoteLocale=locale;const renderedContentChanged=changed.has("renderedHtml")||changed.has("renderedBlocks")||changed.has("streamingTail")||changed.has("progressiveRevision");(localeChanged||renderedContentChanged||changed.has("content"))&&(this.textQuoteIndexCache=void 0),(renderedContentChanged||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),(changed.has("content")&&!(this.streaming&&this.streamingRender==="progressive"&&this.renderedHtml!==null)||renderedContentChanged)&&this.isConnected&&this.emit("lr-content-settled",null)}renderMarkdown(){if(this.streaming){if(normalizeMarkdownStreamingRender(this.streamingRender)==="progressive"){this.progressiveRebuild=!!this.progressiveSession,this.scheduleStreamingRender();return}this.renderedHtml=null,this.resetProgressiveMarkdown(),this.headingTree=[],this.codeHeader.setBlocks([]);return}const deps=this.deps;if(!deps)return;const session=this.progressiveSession;session?.update(this.content??""),session?.step(!0,!0),this.codeBlocks=[];const outcome=renderMarkdownDocument({tag:this.markdownVariant.tag,deps,htmlMode:normalizeMarkdownHtmlMode(this.htmlMode),math:this.math,codeBlockHeader:this.codeBlockHeader||this.codeBlockChrome,parse:(marked,pendingKeys,headingTreeOut)=>this.parseMarkdown(marked,pendingKeys,headingTreeOut),onParsed:()=>this.maybeLoadKatex(),isKatexConfirmedMissing:()=>this.markdownVariant.katexState.isConfirmedMissing()});if(outcome.headingTree&&(this.headingTree=outcome.headingTree),outcome.status==="fallback"){this.renderedHtml=null,this.resetProgressiveMarkdown(),this.codeHeader.setBlocks([]),this.emit("lr-render-error",{error:outcome.error});return}const mode=normalizeMarkdownHtmlMode(this.htmlMode);session&&!session.failed&&session.blocks.map(block=>block.html).join("")===outcome.html&&(mode!=="trusted"||!session.blocks.some(block=>block.hasRawHtml))&&(mode==="sanitize"||session.blocks.slice(0,-1).every(block=>block.balanced))?(this.progressiveAdopted=!0,this.syncProgressiveMarkdown()):this.resetProgressiveMarkdown(),this.renderedHtml=outcome.html,this.codeHeader.setBlocks(this.codeBlocks),outcome.mathFailed&&this.reportMathFailure(),outcome.pendingKeys.length>0&&this.highlightCode&&this.highlightPending(outcome.pendingKeys)}resetProgressiveMarkdown(){this.progressiveSession=void 0,this.progressiveAdopted=!1,this.progressiveRebuild=!1,this.renderedBlocks.length&&(this.renderedBlocks=[]),this.streamingTail=null}createProgressiveSession(previous){const deps=this.deps,mode=normalizeMarkdownHtmlMode(this.htmlMode);if(!deps?.marked||mode==="sanitize"&&!deps.DOMPurify)return;const context=createMarkdownRenderContext(this.markdownParseOptions(deps.marked,"",[],[],void 0,[]));if(!markdownProgressiveEligible(context.instance,this.gfm)){devWarnOnce("lyra-markdown-progressive-unavailable","<lr-markdown>: this parser configuration uses plain streaming.");return}const policy=markdownSanitizerPolicy({htmlMode:mode,math:this.math,codeBlockHeader:this.codeBlockHeader||this.codeBlockChrome}),activeHighlightKeys=new Set,session=new MarkdownProgressiveSession({parser:context.instance,gfm:this.gfm,tabSize:finiteInteger(this.tabSize,4,1,32),render:(source,rawSource,links,state2,slugger,prefix)=>{const pendingKeys=[],headings=[],records=[],options=this.markdownParseOptions(deps.marked,source,pendingKeys,headings,slugger,records,rawSource);options.codeBlockIndexOffset=prefix.length,options.activeHighlightKeys=activeHighlightKeys,options.highlightCodeOption=this.highlightCode;const result=createMarkdownRenderContext(options).render(source,{links,state:state2});return this.maybeLoadKatex(),{...result,rawHtml:result.html,html:finishMarkdownHtml(deps,policy,result.html),headings,codeBlocks:records,pendingKeys}}},previous?.blocks);return session.update(this.content??""),previous&&session.step(!1,!0,previous.end),session}renderProgressiveMarkdown(){const previous=this.progressiveSession;(!previous||this.progressiveRebuild)&&(this.progressiveSession=this.createProgressiveSession(previous),this.progressiveRebuild=!1);const session=this.progressiveSession;if(!session){this.renderedHtml=null,this.renderedBlocks=[],this.streamingTail=null,this.headingTree=[],this.codeHeader.setBlocks([]);return}session.update(this.content??""),session.step(),this.renderedHtml="",this.syncProgressiveMarkdown();const pending=session.nextHighlight();pending&&this.highlightCode&&this.highlightPending([pending]),session.pending&&this.scheduleStreamingRender()}syncProgressiveMarkdown(){const session=this.progressiveSession;if(!session)return;(session.blocks.length!==this.renderedBlocks.length||session.blocks.some((block,index)=>block.html!==this.renderedBlocks[index]?.html))&&(this.renderedBlocks=session.blocks.map((block,index)=>({id:`stream-${index}`,html:block.html})),this.progressiveRevision++);const tail=session.tail;(tail?.kind!==this.streamingTail?.kind||tail?.text!==this.streamingTail?.text)&&(this.streamingTail=tail),this.headingTree=session.headings,this.codeHeader.setBlocks(session.records)}progressiveStats(){return this.progressiveSession?.stats}maybeLoadKatex(){this.math&&this.markdownVariant.katexState.startLoad(this.handleKatexResolved)}reportMathFailure(){this.mathFailureReported||(this.mathFailureReported=!0,this.emit("lr-render-error",{error:markdownMathPeerError(this.markdownVariant.tag)}))}getCachedHighlight(key){return getCachedHighlight(this.highlightCache,key)}setCachedHighlight(key,html){return setCachedHighlight(this.highlightCache,key,html,HIGHLIGHT_CACHE_MAX)}async highlightPending(pendingKeys){const work=pendingKeys.filter(({key})=>this.inFlightHighlightKeys.get(key)!==this.highlightToken);if(work.length===0)return;const token=this.highlightToken;for(const{key}of work)this.inFlightHighlightKeys.set(key,token);const languages=this.languages,isCurrent=()=>token===this.highlightToken&&this.isConnected,tokenizeOne=async pending=>{const html=await this.tokenizePendingHighlight(pending,languages,isCurrent);!isCurrent()||html===void 0||(html===null||!this.setCachedHighlight(pending.key,html))&&addFailedHighlightKey(this.failedHighlightKeys,pending.key)};try{await processPendingHighlights(work,tokenizeOne)}catch{for(const{key}of work)addFailedHighlightKey(this.failedHighlightKeys,key);devWarnOnce(HIGHLIGHT_FAILURE_WARNING_KEY,HIGHLIGHT_FAILURE_WARNING)}finally{for(const{key}of work)this.inFlightHighlightKeys.get(key)===token&&this.inFlightHighlightKeys.delete(key)}this.isConnected&&(this.progressiveSession?(this.progressiveSession.invalidateHighlights(work.map(({key})=>key)),this.streaming?this.scheduleStreamingRender():this.renderMarkdown()):this.renderMarkdown())}parseMarkdown(marked,pendingKeys,headingTreeOut){const source=this.content??"";return parseMarkdownDocument(this.markdownParseOptions(marked,normalizeMarkdownLeadingTabs(source,finiteInteger(this.tabSize,4,1,32)),pendingKeys,headingTreeOut,void 0,this.codeBlocks,source))}markdownParseOptions(marked,content,pendingKeys,headingTreeOut,slugger,codeBlocksOut=[],rawContent=content){const variant=this.markdownVariant;return{marked,slugger,content,pendingKeys,headingTreeOut,codeBlocksOut,rawContent,markedConfigurations:[variant.sharedParser.get(marked)?.defaults,this.marked?.defaults],gfm:this.gfm,linkTarget:this.linkTarget,headingOffset:finiteInteger(this.headingOffset,0,0,6),escapeHtmlOption:normalizeMarkdownHtmlMode(this.htmlMode)==="escape",trustedHtmlOption:normalizeMarkdownHtmlMode(this.htmlMode)==="trusted",codeBlockHeaderOption:this.codeBlockHeader||this.codeBlockChrome,codeFrameNonce:this.codeBlockHeader||this.codeBlockChrome?this.codeHeader.nonce:void 0,tabSize:finiteInteger(this.tabSize,4,1,32),highlightCodeOption:this.highlightCode&&!this.streaming,getCachedHighlight:key=>this.getCachedHighlight(key),failedHighlightKeys:this.failedHighlightKeys,headingAnchorsOption:this.headingAnchors,mathOption:this.math,cachedKatex:this.math?variant.katexState.getIfLoaded():null}}getHeadingTree(){return[...this.headingTree]}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;if(anchor.kind==="fragment")return applyMarkdownFragmentAnchor(root,anchor,this.headingTree);if(anchor.kind==="text-quote"){const index=this.markdownTextIndex(root),found=applyMarkdownTextQuoteAnchor(root,anchor,this.effectiveLocale,index);return!supportsCustomHighlights(this.ownerDocument)&&this.highlights.length>0&&this.repaintHighlights(),found}return!1}computeSelectionAnchor(range){const root=this.contentRoot();if(!root)return null;const anchor=buildQuoteAnchor(range,this.markdownTextIndex(root).scope);return!supportsCustomHighlights(this.ownerDocument)&&this.highlights.length>0&&this.scheduleAfterUpdate(()=>this.repaintHighlights()),anchor}ensureHighlightHandle(){return this.highlightHandle??=acquireHighlightHandle(this,this.ownerDocument),this.highlightHandle}markdownTextIndex(root){const locale=this.effectiveLocale,cached=this.textQuoteIndexCache;if(cached?.root===root&&cached.locale===locale&&!cached.mappingDirty)return cached.index;if(cached?.mappingDirty){const handle=this.ensureHighlightHandle();for(const tone of["accent","success","warning","danger","neutral"])handle.setRanges(tone,[]);handle.setActive(null)}const markers=this.progressiveSession?this.renderedBlocks.length*2+8:0,scope=scopeFromElement(root,{maxTraversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes+markers});if(this.markdownTextScopeBuilds++,cached?.root===root&&cached.locale===locale&&cached.index.rebindScope(scope))return cached.mappingDirty=!1,cached.index;const index=createTextQuoteIndex(scope,locale);return this.textQuoteIndexCache={root,locale,index,mappingDirty:!1},index}markdownTextScopeBuildCount(){return this.markdownTextScopeBuilds}markdownTextQuoteScanCount(){return this.textQuoteIndexCache?.index.scanCount??0}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot();if(!root)return;if(this.highlights.length===0){this.highlightHandle?.release(),this.highlightHandle=void 0;return}if(this.streaming&&this.progressiveSession&&!supportsCustomHighlights(this.ownerDocument)){this.highlightHandle?.release(),this.highlightHandle=void 0;return}const index=this.markdownTextIndex(root);this.resolvedHighlightRanges=repaintMarkdownHighlights({locale:this.effectiveLocale,root,handle:this.ensureHighlightHandle(),highlights:this.highlights,activeHighlightId:this.activeHighlightId,index}),!supportsCustomHighlights(this.ownerDocument)&&this.textQuoteIndexCache&&(this.textQuoteIndexCache.mappingDirty=!0)}render(){const progressiveRendering=!!(this.progressiveSession&&(this.streaming||this.progressiveAdopted));return renderMarkdownContent({content:this.content??"",sanitized:normalizeMarkdownHtmlMode(this.htmlMode)==="sanitize",renderedHtml:this.renderedHtml,fallbackSegments:!progressiveRendering&&this.renderedHtml===null?this.fallbackCode.segments(this.content??""):null,progressive:progressiveRendering?{blocks:this.renderedBlocks,tail:this.streamingTail}:null,hostAriaLabel:this.getAttribute("aria-label"),isDarkTheme:this.isDarkTheme,onClick:this.onContentClick,liveRegion:this.renderAnchorLiveRegion(),maxHeight:this.maxHeight})}}__decorate([state()],MarkdownRuntimeBase.prototype,"renderedHtml",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"renderedBlocks",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"streamingTail",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"progressiveRevision",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"isDarkTheme",void 0);export{MarkdownRuntimeBase,createMarkdownVariantContext};
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteInteger}from"../../../internal/numbers.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights}from"../../../internal/text-highlights.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{devWarnOnce,warnDeprecatedUsage}from"../../../internal/dev-mode-attribute-warning.js";import{MarkdownCodeHeaderController,renderMarkdownCodeHeader}from"./markdown-code-header.js";import{MarkdownFallbackCodeScanner}from"./markdown-fallback-code.js";import{MarkdownProgressiveSession,markdownProgressiveEligible}from"./markdown-progressive.js";import{addFailedHighlightKey,applyMarkdownAriaBusy,applyMarkdownFragmentAnchor,applyMarkdownTextQuoteAnchor,beginMarkdownDepsLoad,getCachedHighlight,hitTestHighlightRanges,HIGHLIGHT_CACHE_MAX,internalLinkHrefFrom,markdownAnchorFromTarget,markdownTableRegionLabel,markdownHasTableWrappers,labelMarkdownTableWrappers,markdownHighlightConfigChanged,markdownLanguageSetChanged,markdownMathPeerError,markdownNeedsReparse,MarkdownOwnedAnimationFrameController,MarkdownParserController,normalizeMarkdownHtmlMode,normalizeMarkdownStreamingRender,createMarkdownRenderContext,finishMarkdownHtml,markdownSanitizerPolicy,normalizeMarkdownLeadingTabs,parseMarkdownDocument,processPendingHighlights,renderMarkdownContent,renderMarkdownDocument,repaintMarkdownHighlights,resolveMarkdownDarkTheme,setCachedHighlight}from"./markdown-shared.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_codeRegion,LYRA_DEFAULT_codeRegionWithLanguage,LYRA_DEFAULT_copiedToClipboard,LYRA_DEFAULT_copyCode,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_markdownTableRegion}from"../../../internal/default-strings.generated.js";const HIGHLIGHT_FAILURE_WARNING_KEY="lyra-markdown-highlight-failed",HIGHLIGHT_FAILURE_WARNING="<lr-markdown>/<lr-markdown-core>: Syntax highlighting could not complete. Code is rendered as plain text.";function keyboardHighlightIdFrom(ranges,event){const coordinateLess=event.clientX===0&&event.clientY===0&&event.screenX===0&&event.screenY===0;if(event.detail!==0&&!coordinateLess)return null;const anchor=event.composedPath().find(target=>markdownAnchorFromTarget(target)!==void 0);if(!anchor)return null;for(let index=ranges.length-1;index>=0;index--){const range=ranges[index];if(range)try{if(range.range.intersectsNode(anchor))return range.id}catch{}}return null}class LyraMarkdownRuntimeElement extends LyraElement{static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,codeRegion:LYRA_DEFAULT_codeRegion,codeRegionWithLanguage:LYRA_DEFAULT_codeRegionWithLanguage,copiedToClipboard:LYRA_DEFAULT_copiedToClipboard,copyCode:LYRA_DEFAULT_copyCode,copyFailed:LYRA_DEFAULT_copyFailed,markdownTableRegion:LYRA_DEFAULT_markdownTableRegion}}}function createMarkdownVariantContext(tag,katexState){return{tag,connectedInstances:new Set,sharedParser:new MarkdownParserController,katexState}}class MarkdownRuntimeBase extends DocumentAnchorTarget(LyraMarkdownRuntimeElement){constructor(){super(),this.anchorKinds=["fragment","text-quote"],this.renderedHtml=null,this.renderedBlocks=[],this.streamingTail=null,this.progressiveRevision=0,this.isDarkTheme=!1,this.boundLocalize=this.localize.bind(this),this.hasTableWrappers=!1,this.fallbackCode=new MarkdownFallbackCodeScanner,this.parser=new MarkdownParserController,this.headingTree=[],this.markdownTextScopeBuilds=0,this.resolvedHighlightRanges=[],this.mathFailureReported=!1,this.highlightCache=new Map,this.highlightToken=0,this.streamingRenderFrames=new MarkdownOwnedAnimationFrameController,this.failedHighlightKeys=new Set,this.inFlightHighlightKeys=new Map,this.progressiveAdopted=!1,this.progressiveRebuild=!1,this.progressiveInputGeneration=0,this.codeBlocks=[],this.handleKatexResolved=()=>{this.isConnected&&(this.progressiveSession&&this.streaming?(this.progressiveSession.invalidateMath(),this.scheduleStreamingRender()):this.renderMarkdown())},this.onContentClick=event=>{if(this.codeHeader.handleClick(event))return;const href=internalLinkHrefFrom(event,this.internalLinkPrefix);href!==null&&event.preventDefault();const highlightId=hitTestHighlightRanges(this.resolvedHighlightRanges,event.clientX,event.clientY)??keyboardHighlightIdFrom(this.resolvedHighlightRanges,event);highlightId&&this.emit("lr-highlight-activate",{highlightId}),href!==null&&this.emit("lr-link-click",{href})},new ThemeWatcher(this,()=>this.refreshTheme()),this.codeHeader=new MarkdownCodeHeaderController(this,{isEnabled:()=>this.codeBlockHeader||this.codeBlockChrome,contentVersion:()=>this.progressiveSession?this.renderedBlocks:this.renderedHtml,getContentRoot:()=>this.contentRoot(),localize:this.boundLocalize,buildHeader:(frame,language)=>renderMarkdownCodeHeader(frame,language),emitCopy:outcome=>this.emit("lr-copy",outcome),emitCopyError:outcome=>this.emit("lr-copy-error",outcome)})}get marked(){return this.parser.get(this.deps?.marked)}refreshTheme(){this.isDarkTheme=resolveMarkdownDarkTheme(this)}connectedCallback(){super.connectedCallback(),this.markdownVariant.connectedInstances.add(this),this.refreshTheme(),beginMarkdownDepsLoad(this,resolved=>{this.deps=resolved,this.renderMarkdown(),this.requestUpdate()})}disconnectedCallback(){this.markdownVariant.connectedInstances.delete(this),super.disconnectedCallback(),this.highlightToken++,this.cancelStreamingRender(),this.highlightHandle?.release(),this.highlightHandle=void 0,this.textQuoteIndexCache=void 0,this.fallbackCode.reset()}adoptedCallback(){super.adoptedCallback(),this.codeHeader.hostAdopted(),this.cancelStreamingRender(),this.streaming&&this.progressiveSession&&this.scheduleStreamingRender()}firstUpdated(changed){super.firstUpdated(changed);const contentRoot=this.renderRoot.querySelector('[part="content"]');contentRoot&&this.bindTextSelection(contentRoot)}willUpdate(changed){super.willUpdate(changed),changed.has("codeBlockChrome")&&this.codeBlockChrome===!0&&warnDeprecatedUsage(this,"property","codeBlockChrome","code-block-header");const active=this.shadowRoot?.activeElement,selector='[part~="code-block"], [part~="code-block-copy"], [part~="table-wrapper"]';if(active?.matches(selector)&&(this.rememberedFocus={node:active,index:[...this.renderRoot.querySelectorAll(selector)].indexOf(active),selector}),changed.has("math")&&(this.mathFailureReported=!1),!this.deps||!markdownNeedsReparse(changed))return;const progressive=normalizeMarkdownStreamingRender(this.streamingRender)==="progressive",configurationChanged=[...changed.keys()].some(key=>key!=="content"&&key!=="streaming"&&markdownNeedsReparse(new Map([[key,void 0]])));(markdownHighlightConfigChanged(changed)||!progressive&&(changed.has("content")||changed.has("streaming")))&&this.highlightToken++,markdownHighlightConfigChanged(changed)&&(this.failedHighlightKeys.clear(),markdownLanguageSetChanged(changed)&&this.highlightCache.clear()),progressive?configurationChanged&&(this.progressiveRebuild=!0):this.resetProgressiveMarkdown(),changed.has("content")&&this.progressiveInputGeneration++,this.streaming?(this.progressiveAdopted&&(this.progressiveSession?.resume(),this.progressiveAdopted=!1),this.progressiveSession?.update(this.content??""),this.progressiveSession&&this.syncProgressiveMarkdown(),this.scheduleStreamingRender()):(this.cancelStreamingRender(),(changed.has("content")&&!changed.has("streaming")||configurationChanged)&&this.resetProgressiveMarkdown(),this.renderMarkdown())}cancelStreamingRender(){const handle=this.streamingRenderRaf;this.streamingRenderRaf=void 0,!this.streamingRenderFrames.cancel()&&handle!==void 0&&this.ownerDocument.defaultView?.cancelAnimationFrame(handle)}scheduleStreamingRender(){if(this.streamingRenderRaf!==void 0)return;const view=this.ownerDocument.defaultView;if(!view){this.isConnected&&this.runStreamingFrame();return}const handle=this.streamingRenderFrames.request(view,()=>{this.streamingRenderRaf=void 0,this.isConnected&&this.ownerDocument.defaultView===view&&this.runStreamingFrame()});handle===void 0?this.isConnected&&this.runStreamingFrame():this.streamingRenderFrames.handle===handle&&(this.streamingRenderRaf=handle)}runStreamingFrame(){normalizeMarkdownStreamingRender(this.streamingRender)==="progressive"?this.renderProgressiveMarkdown():this.renderMarkdown()}async getUpdateComplete(){await super.getUpdateComplete();const generation=this.progressiveInputGeneration,remaining=(this.content?.length??0)-(this.progressiveSession?.end??0),cap=Math.ceil(Math.max(0,remaining)/65536)+2;for(let frames=0;frames<cap&&this.streamingRenderRaf!==void 0&&(await this.streamingRenderFrames.settled,await super.getUpdateComplete(),generation===this.progressiveInputGeneration);frames++);return super.getUpdateComplete()}updated(changed){super.updated(changed),applyMarkdownAriaBusy(this,!this.deps||this.streaming);const renderedChanged=changed.has("renderedHtml")||changed.has("renderedBlocks");if(renderedChanged&&(this.hasTableWrappers=markdownHasTableWrappers(this.contentRoot())),!this.hasTableWrappers)this.tableRegionLabel=void 0;else{const tableLabel=markdownTableRegionLabel(this.boundLocalize);(renderedChanged||tableLabel!==this.tableRegionLabel)&&(this.tableRegionLabel=tableLabel,labelMarkdownTableWrappers(this.contentRoot(),tableLabel))}const remembered=this.rememberedFocus;if(this.rememberedFocus=void 0,remembered&&!remembered.node.isConnected){let active=this.ownerDocument.activeElement;for(;active?.shadowRoot?.activeElement;)active=active.shadowRoot.activeElement;if(!active||active===this.ownerDocument.body||active===this.ownerDocument.documentElement){const target=this.renderRoot.querySelectorAll(remembered.selector)[remembered.index];target?target.focus({preventScroll:!0}):this.streaming&&(this.rememberedFocus=remembered)}}const locale=this.effectiveLocale,localeChanged=this.textQuoteLocale!==void 0&&this.textQuoteLocale!==locale;this.textQuoteLocale=locale;const renderedContentChanged=changed.has("renderedHtml")||changed.has("renderedBlocks")||changed.has("streamingTail")||changed.has("progressiveRevision");(localeChanged||renderedContentChanged||changed.has("content"))&&(this.textQuoteIndexCache=void 0),(renderedContentChanged||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),(changed.has("content")&&!(this.streaming&&this.streamingRender==="progressive"&&this.renderedHtml!==null)||renderedContentChanged)&&this.isConnected&&this.emit("lr-content-settled",null)}renderMarkdown(){if(this.streaming){if(normalizeMarkdownStreamingRender(this.streamingRender)==="progressive"){this.progressiveRebuild=!!this.progressiveSession,this.scheduleStreamingRender();return}this.renderedHtml=null,this.resetProgressiveMarkdown(),this.headingTree=[],this.codeHeader.setBlocks([]);return}const deps=this.deps;if(!deps)return;const session=this.progressiveSession;session?.update(this.content??""),session?.step(!0,!0),this.codeBlocks=[];const outcome=renderMarkdownDocument({tag:this.markdownVariant.tag,deps,htmlMode:normalizeMarkdownHtmlMode(this.htmlMode),math:this.math,codeBlockHeader:this.codeBlockHeader||this.codeBlockChrome,parse:(marked,pendingKeys,headingTreeOut)=>this.parseMarkdown(marked,pendingKeys,headingTreeOut),onParsed:()=>this.maybeLoadKatex(),isKatexConfirmedMissing:()=>this.markdownVariant.katexState.isConfirmedMissing()});if(outcome.headingTree&&(this.headingTree=outcome.headingTree),outcome.status==="fallback"){this.renderedHtml=null,this.resetProgressiveMarkdown(),this.codeHeader.setBlocks([]),this.emit("lr-render-error",{error:outcome.error});return}const mode=normalizeMarkdownHtmlMode(this.htmlMode);session&&!session.failed&&session.blocks.map(block=>block.html).join("")===outcome.html&&(mode!=="trusted"||!session.blocks.some(block=>block.hasRawHtml))&&(mode==="sanitize"||session.blocks.slice(0,-1).every(block=>block.balanced))?(this.progressiveAdopted=!0,this.syncProgressiveMarkdown()):this.resetProgressiveMarkdown(),this.renderedHtml=outcome.html,this.codeHeader.setBlocks(this.codeBlocks),outcome.mathFailed&&this.reportMathFailure(),outcome.pendingKeys.length>0&&this.highlightCode&&this.highlightPending(outcome.pendingKeys)}resetProgressiveMarkdown(){this.progressiveSession=void 0,this.progressiveAdopted=!1,this.progressiveRebuild=!1,this.renderedBlocks.length&&(this.renderedBlocks=[]),this.streamingTail=null}createProgressiveSession(previous){const deps=this.deps,mode=normalizeMarkdownHtmlMode(this.htmlMode);if(!deps?.marked||mode==="sanitize"&&!deps.DOMPurify)return;const context=createMarkdownRenderContext(this.markdownParseOptions(deps.marked,"",[],[],void 0,[]));if(!markdownProgressiveEligible(context.instance,this.gfm)){devWarnOnce("lyra-markdown-progressive-unavailable","<lr-markdown>: this parser configuration uses plain streaming.");return}const policy=markdownSanitizerPolicy({htmlMode:mode,math:this.math,codeBlockHeader:this.codeBlockHeader||this.codeBlockChrome}),activeHighlightKeys=new Set,session=new MarkdownProgressiveSession({parser:context.instance,gfm:this.gfm,tabSize:finiteInteger(this.tabSize,4,1,32),render:(source,rawSource,links,state2,slugger,prefix)=>{const pendingKeys=[],headings=[],records=[],options=this.markdownParseOptions(deps.marked,source,pendingKeys,headings,slugger,records,rawSource);options.codeBlockIndexOffset=prefix.length,options.activeHighlightKeys=activeHighlightKeys,options.highlightCodeOption=this.highlightCode;const result=createMarkdownRenderContext(options).render(source,{links,state:state2});return this.maybeLoadKatex(),{...result,rawHtml:result.html,html:finishMarkdownHtml(deps,policy,result.html),headings,codeBlocks:records,pendingKeys}}},previous?.blocks);return session.update(this.content??""),previous&&session.step(!1,!0,previous.end),session}renderProgressiveMarkdown(){const previous=this.progressiveSession;(!previous||this.progressiveRebuild)&&(this.progressiveSession=this.createProgressiveSession(previous),this.progressiveRebuild=!1);const session=this.progressiveSession;if(!session){this.renderedHtml=null,this.renderedBlocks=[],this.streamingTail=null,this.headingTree=[],this.codeHeader.setBlocks([]);return}session.update(this.content??""),session.step(),this.renderedHtml="",this.syncProgressiveMarkdown();const pending=session.nextHighlight();pending&&this.highlightCode&&this.highlightPending([pending]),session.pending&&this.scheduleStreamingRender()}syncProgressiveMarkdown(){const session=this.progressiveSession;if(!session)return;(session.blocks.length!==this.renderedBlocks.length||session.blocks.some((block,index)=>block.html!==this.renderedBlocks[index]?.html))&&(this.renderedBlocks=session.blocks.map((block,index)=>({id:`stream-${index}`,html:block.html})),this.progressiveRevision++);const tail=session.tail;(tail?.kind!==this.streamingTail?.kind||tail?.text!==this.streamingTail?.text)&&(this.streamingTail=tail),this.headingTree=session.headings,this.codeHeader.setBlocks(session.records)}progressiveStats(){return this.progressiveSession?.stats}maybeLoadKatex(){this.math&&this.markdownVariant.katexState.startLoad(this.handleKatexResolved)}reportMathFailure(){this.mathFailureReported||(this.mathFailureReported=!0,this.emit("lr-render-error",{error:markdownMathPeerError(this.markdownVariant.tag)}))}getCachedHighlight(key){return getCachedHighlight(this.highlightCache,key)}setCachedHighlight(key,html){return setCachedHighlight(this.highlightCache,key,html,HIGHLIGHT_CACHE_MAX)}async highlightPending(pendingKeys){const work=pendingKeys.filter(({key})=>this.inFlightHighlightKeys.get(key)!==this.highlightToken);if(work.length===0)return;const token=this.highlightToken;for(const{key}of work)this.inFlightHighlightKeys.set(key,token);const languages=this.languages,isCurrent=()=>token===this.highlightToken&&this.isConnected,tokenizeOne=async pending=>{const html=await this.tokenizePendingHighlight(pending,languages,isCurrent);!isCurrent()||html===void 0||(html===null||!this.setCachedHighlight(pending.key,html))&&addFailedHighlightKey(this.failedHighlightKeys,pending.key)};try{await processPendingHighlights(work,tokenizeOne)}catch{for(const{key}of work)addFailedHighlightKey(this.failedHighlightKeys,key);devWarnOnce(HIGHLIGHT_FAILURE_WARNING_KEY,HIGHLIGHT_FAILURE_WARNING)}finally{for(const{key}of work)this.inFlightHighlightKeys.get(key)===token&&this.inFlightHighlightKeys.delete(key)}this.isConnected&&(this.progressiveSession?(this.progressiveSession.invalidateHighlights(work.map(({key})=>key)),this.streaming?this.scheduleStreamingRender():this.renderMarkdown()):this.renderMarkdown())}parseMarkdown(marked,pendingKeys,headingTreeOut){const source=this.content??"";return parseMarkdownDocument(this.markdownParseOptions(marked,normalizeMarkdownLeadingTabs(source,finiteInteger(this.tabSize,4,1,32)),pendingKeys,headingTreeOut,void 0,this.codeBlocks,source))}markdownParseOptions(marked,content,pendingKeys,headingTreeOut,slugger,codeBlocksOut=[],rawContent=content){const variant=this.markdownVariant;return{marked,slugger,content,pendingKeys,headingTreeOut,codeBlocksOut,rawContent,markedConfigurations:[variant.sharedParser.get(marked)?.defaults,this.marked?.defaults],gfm:this.gfm,linkTarget:this.linkTarget,headingOffset:finiteInteger(this.headingOffset,0,0,6),escapeHtmlOption:normalizeMarkdownHtmlMode(this.htmlMode)==="escape",trustedHtmlOption:normalizeMarkdownHtmlMode(this.htmlMode)==="trusted",codeBlockHeaderOption:this.codeBlockHeader||this.codeBlockChrome,codeFrameNonce:this.codeBlockHeader||this.codeBlockChrome?this.codeHeader.nonce:void 0,tabSize:finiteInteger(this.tabSize,4,1,32),highlightCodeOption:this.highlightCode&&!this.streaming,getCachedHighlight:key=>this.getCachedHighlight(key),failedHighlightKeys:this.failedHighlightKeys,headingAnchorsOption:this.headingAnchors,mathOption:this.math,cachedKatex:this.math?variant.katexState.getIfLoaded():null}}getHeadingTree(){return[...this.headingTree]}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;if(anchor.kind==="fragment")return applyMarkdownFragmentAnchor(root,anchor,this.headingTree);if(anchor.kind==="text-quote"){const index=this.markdownTextIndex(root),found=applyMarkdownTextQuoteAnchor(root,anchor,this.effectiveLocale,index);return!supportsCustomHighlights(this.ownerDocument)&&this.highlights.length>0&&this.repaintHighlights(),found}return!1}computeSelectionAnchor(range){const root=this.contentRoot();if(!root)return null;const anchor=buildQuoteAnchor(range,this.markdownTextIndex(root).scope);return!supportsCustomHighlights(this.ownerDocument)&&this.highlights.length>0&&this.scheduleAfterUpdate(()=>this.repaintHighlights()),anchor}ensureHighlightHandle(){return this.highlightHandle??=acquireHighlightHandle(this,this.ownerDocument),this.highlightHandle}markdownTextIndex(root){const locale=this.effectiveLocale,cached=this.textQuoteIndexCache;if(cached?.root===root&&cached.locale===locale&&!cached.mappingDirty)return cached.index;if(cached?.mappingDirty){const handle=this.ensureHighlightHandle();for(const tone of["accent","success","warning","danger","neutral"])handle.setRanges(tone,[]);handle.setActive(null)}const markers=this.progressiveSession?this.renderedBlocks.length*2+8:0,scope=scopeFromElement(root,{maxTraversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes+markers});if(this.markdownTextScopeBuilds++,cached?.root===root&&cached.locale===locale&&cached.index.rebindScope(scope))return cached.mappingDirty=!1,cached.index;const index=createTextQuoteIndex(scope,locale);return this.textQuoteIndexCache={root,locale,index,mappingDirty:!1},index}markdownTextScopeBuildCount(){return this.markdownTextScopeBuilds}markdownTextQuoteScanCount(){return this.textQuoteIndexCache?.index.scanCount??0}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot();if(!root)return;if(this.highlights.length===0){this.highlightHandle?.release(),this.highlightHandle=void 0;return}if(this.streaming&&this.progressiveSession&&!supportsCustomHighlights(this.ownerDocument)){this.highlightHandle?.release(),this.highlightHandle=void 0;return}const index=this.markdownTextIndex(root);this.resolvedHighlightRanges=repaintMarkdownHighlights({locale:this.effectiveLocale,root,handle:this.ensureHighlightHandle(),highlights:this.highlights,activeHighlightId:this.activeHighlightId,index}),!supportsCustomHighlights(this.ownerDocument)&&this.textQuoteIndexCache&&(this.textQuoteIndexCache.mappingDirty=!0)}render(){const progressiveRendering=!!(this.progressiveSession&&(this.streaming||this.progressiveAdopted));return renderMarkdownContent({content:this.content??"",sanitized:normalizeMarkdownHtmlMode(this.htmlMode)==="sanitize",renderedHtml:this.renderedHtml,fallbackSegments:!progressiveRendering&&this.renderedHtml===null?this.fallbackCode.segments(this.content??""):null,progressive:progressiveRendering?{blocks:this.renderedBlocks,tail:this.streamingTail}:null,hostAriaLabel:this.getAttribute("aria-label"),isDarkTheme:this.isDarkTheme,onClick:this.onContentClick,liveRegion:this.renderAnchorLiveRegion(),maxHeight:this.maxHeight})}}__decorate([state()],MarkdownRuntimeBase.prototype,"renderedHtml",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"renderedBlocks",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"streamingTail",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"progressiveRevision",void 0),__decorate([state()],MarkdownRuntimeBase.prototype,"isDarkTheme",void 0);export{MarkdownRuntimeBase,createMarkdownVariantContext};
|
|
@@ -248,7 +248,9 @@ streamingRender:MarkdownStreamingRender;
|
|
|
248
248
|
* Custom code renderers and pre-escaped code bypass the header. In sanitize mode this also strips
|
|
249
249
|
* authored style elements; trusted mode has no guarantee against authored visual copy deception. */
|
|
250
250
|
codeBlockHeader:boolean;
|
|
251
|
-
/**
|
|
251
|
+
/** Deprecated compatibility spelling of `code-block-header`: either property enables the header.
|
|
252
|
+
* Setting it logs a one-time development warning.
|
|
253
|
+
* @deprecated Use `code-block-header` (`codeBlockHeader`); removal not before 23.0.0. */
|
|
252
254
|
codeBlockChrome:boolean;
|
|
253
255
|
/** Syntax-highlights fenced code blocks through the fine-grained Shiki core loader when
|
|
254
256
|
* `languages` supplies the matching grammar. The empty default language map means no fenced
|