@aceshooting/lyra-ui 28.0.0 → 28.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/dist/components/agent-tools/commit-card/commit-card.class.d.ts +2 -2
- package/dist/components/agent-tools/commit-card/commit-card.class.js +7 -8
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +4 -4
- package/dist/components/charts/chart/box-plot.class.d.ts +5 -3
- package/dist/components/charts/chart/box-plot.class.js +18 -17
- package/dist/components/charts/chart/chart.class.d.ts +6 -4
- package/dist/components/charts/chart/chart.class.js +19 -18
- package/dist/components/charts/chart/lite-chart.class.d.ts +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +8 -8
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/data-grid/data-grid-processing.js +1 -1
- package/dist/components/data/gauge/gauge.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
- package/dist/components/data/heatmap/heatmap-label-cache.js +1 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +3 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/data/stat/stat.class.d.ts +11 -9
- package/dist/components/data/stat/stat.class.js +4 -2
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +2 -4
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/select/select.class.js +4 -3
- package/dist/components/forms/toggle-group/toggle-group.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/menubar/menubar.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.d.ts +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.d.ts +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +4 -4
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/default-strings/charts.generated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- package/dist/internal/nonmodal-overlay-manager.js +1 -1
- package/dist/internal/open-overlay-ancestors.js +1 -0
- package/dist/internal/open-overlay-raise.styles.js +1 -1
- package/dist/internal/overlay-manager.d.ts +2 -0
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/testing/happy-dom-shims.d.ts +3 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-box-plot.md +5 -0
- package/llms/components/lr-chart.md +6 -0
- package/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-heatmap.md +10 -2
- package/llms/components/lr-select.md +2 -0
- package/llms/components/lr-stat.md +4 -0
- package/llms/peers.md +1 -1
- package/llms/shared/ai-and-peers.md +44 -0
- package/llms/shared/testing-and-utilities.md +14 -1
- package/llms/shared.md +58 -1
- package/locales.json +138 -138
- package/package.json +7 -6
- package/registrations.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,56 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 28.1.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 992d6a2: Close entity-chip and citation-badge previews in the same update when their last assigned content is removed alongside a label change. Clear the preview description while preserving keyboard focus.
|
|
8
|
+
- 07d9075: Add scoped command discovery, search excerpts, a document outline, bounded document checks, comments and qualified tracked-text review to the DOCX editor. Add table formatting, insertion into qualified styled paragraphs and table-cell boundaries, and byte-only image replacement that preserves picture geometry and descriptions. New reports use revision-scoped identifiers, and editing actions retain their original selection intent.
|
|
9
|
+
|
|
10
|
+
Reuse graph hull paths and bounded heatmap label measurements during painting, with invalidation when geometry or text settings change.
|
|
11
|
+
|
|
12
|
+
Keep command descriptions and shortcuts readable through command-palette highlight transitions.
|
|
13
|
+
|
|
14
|
+
The production gzip cost is 376 bytes for the data family, 105 bytes for retrieval and 1 byte for layout. Complete registration adds 512 bytes; the standard and CDN autoloaders add 464 and 477 bytes, and SSR registration adds 496 bytes. Only these seven breached bundle ceilings move to their exact measured sizes, without extra allowance, for bounded text/path reuse and highlighted text contrast. Other bundle canaries and optional-peer exclusions remain unchanged.
|
|
15
|
+
- c529f00: Normalize a navigation item's initial open state when its panel is removed before the first render, without emitting a toggle for a panel that was never shown.
|
|
16
|
+
|
|
17
|
+
Preserve the inherited lifecycle API and focus repair ordering by normalizing after slot presence refresh. The five affected bundle ceilings record the measured correctness fix with no added allowance; the complete bundle grows by 40 gzip bytes.
|
|
18
|
+
- 7a28693: Keep newer dialogs interactive when an underlying overlay's native dialog is closed externally, and restore the underlying overlay after the covering dialogs leave. Cancel deferred restoration when its owner closes or disconnects.
|
|
19
|
+
|
|
20
|
+
Allow an already-mounted overlay to become interactive above another modal without inheriting the lower overlay's temporary inert state. Preserve explicitly authored inert states and restore them when overlays close.
|
|
21
|
+
- 7a28693: Keep combobox `selectedRows` aligned with programmatically bound values when a search filters selected options out of the suggestion list.
|
|
22
|
+
- 6ea4454: Reduce temporary allocations when selecting a small number of values from a large option list.
|
|
23
|
+
|
|
24
|
+
The allocation guard adds 15 gzip bytes to the direct select entry, 22 to its initial marginal route, and 17 to the complete registration barrel. Only breached bundle ceilings advance to their exact reviewed measurements, with no added allowance. The release version stamp adds one byte to the menu and tour marginal routes and two bytes to entity-chip; those three ceilings also match their exact measured sizes.
|
|
25
|
+
- b582d6d: Reduce repeated option catalog scans, project only needed combobox rows, and skip unnecessary adornment serialization. Preserve duplicate selection identities, current option metadata, and form behavior.
|
|
26
|
+
|
|
27
|
+
Reuse accessible chart table rows during caption, description, and keyboard announcement updates while retaining explicit refresh and data-dependent invalidation. Avoid sorting non-median data-grid aggregates, normalize search text once, and resolve filter collators only when needed.
|
|
28
|
+
|
|
29
|
+
Resolve checkbox selection occurrences and gauge thresholds in linear passes, and reuse the inherited locale during neighbor sorting.
|
|
30
|
+
|
|
31
|
+
Index selected choices and hidden graph types once per render or search pass, preserving first-match labels, selection order, and current interaction state.
|
|
32
|
+
|
|
33
|
+
Replace repeated membership searches during retrieval, form, file, feedback, and layout updates with bounded lookup indexes. Preserve duplicate identities, validation priority, focus recovery, and source order, and release stale retrieval indexes when their content disappears.
|
|
34
|
+
|
|
35
|
+
Normalize picker searches once per pass, find synchronized chart points without sorting, and avoid repeated toolbar ownership scans. Keep toggle matching and batched tree metadata updates linear while preserving empty and singleton fast paths.
|
|
36
|
+
|
|
37
|
+
Keep virtualized emoji options connected while they own focus or the active-descendant reference. Correct metric, commit-summary, PDF zoom, and required-button accessibility semantics while preserving localized text and descriptions.
|
|
38
|
+
|
|
39
|
+
Keep bundle ceilings tied to exact reviewed gzip measurements for the added lookup indexes, chart caches, retained focus rows, and accessible descriptions, without extra allowance. Preserve passing ceilings, peer exclusions, and CSS budgets.
|
|
40
|
+
- @aceshooting/lyra-translations@28.1.1
|
|
41
|
+
|
|
42
|
+
## 28.1.0
|
|
43
|
+
|
|
44
|
+
### Minor Changes
|
|
45
|
+
|
|
46
|
+
- be521ef: Add independent heatmap hover-ring styling while preserving keyboard focus feedback. Contain deferred fitted heatmap frames after their allocation shrinks, preserve chart data when a canvas context cannot initialize, and keep anchored overlays above sticky cells when composed through shadow roots. The Happy DOM setup helper now supplies missing shadow-root stylesheet collections and HTML direction hints.
|
|
47
|
+
|
|
48
|
+
Review bundled-size allowances for the added overlay ancestry tracking, canvas fallback, and heatmap containment. Only exceeded JavaScript and component aggregate limits advance to their measured sizes; existing passing limits, optional-peer exclusions, and CSS budgets remain unchanged.
|
|
49
|
+
|
|
50
|
+
### Patch Changes
|
|
51
|
+
|
|
52
|
+
- @aceshooting/lyra-translations@28.1.0
|
|
53
|
+
|
|
3
54
|
## 28.0.0
|
|
4
55
|
|
|
5
56
|
### Major Changes
|
|
@@ -44,8 +44,8 @@ status?:GitStatus;}export interface LyraCommitCardEventMap{'lr-file-select':Cust
|
|
|
44
44
|
* @csspart file - A file row; carries `data-status`.
|
|
45
45
|
* @csspart file-path - A file row's path text.
|
|
46
46
|
* @csspart file-status - The one-letter git-status badge inside `[part="file-path"]`, present only
|
|
47
|
-
* when that file has a `status`.
|
|
48
|
-
*
|
|
47
|
+
* when that file has a `status`. Includes visually hidden localized text (`Modified`, `Added`,
|
|
48
|
+
* ...) in the file button's name; the visual letter is hidden from assistive technology.
|
|
49
49
|
* @csspart file-additions - A file row's additions count.
|
|
50
50
|
* @csspart file-deletions - A file row's deletions count.
|
|
51
51
|
* @csspart limit - Visible notice when the expanded file list exceeds the render cap.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./commit-card.styles.js";import{agentActionButtonStyles}from"../agent-action-button.styles.js";import{GIT_STATUSES}from"../../data/file-tree/file-tree.class.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{overallSemanticLabel,overallSemanticRole}from"../semantic-owner.js";import{firstByIdentity}from"../collection-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{LYRA_DEFAULT_commitCardCopyHash,LYRA_DEFAULT_commitCardDiffSummary,LYRA_DEFAULT_commitCardFilesLimit,LYRA_DEFAULT_commitCardHideFiles,LYRA_DEFAULT_commitCardLabel,LYRA_DEFAULT_commitCardShowFiles}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_gitStatusAdded,LYRA_DEFAULT_gitStatusConflicted,LYRA_DEFAULT_gitStatusDeleted,LYRA_DEFAULT_gitStatusIgnored,LYRA_DEFAULT_gitStatusModified,LYRA_DEFAULT_gitStatusRenamed,LYRA_DEFAULT_gitStatusUntracked,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const GIT_STATUS_LETTER={added:"A",modified:"M",deleted:"D",renamed:"R",untracked:"U",conflicted:"C",ignored:"!"},MAX_DATE_EPOCH_MS=864e13,MAX_RENDERED_FILES=500,GIT_STATUS_KEY={added:"gitStatusAdded",modified:"gitStatusModified",deleted:"gitStatusDeleted",renamed:"gitStatusRenamed",untracked:"gitStatusUntracked",conflicted:"gitStatusConflicted",ignored:"gitStatusIgnored"};class LyraCommitCard extends LyraElement{constructor(){super(...arguments),this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.hash="",this.message="",this.author="",this.files=[],this.filesExpanded=!1,this.withoutCopyButton=!1,this.size="m",this.frame="card",this.copyStatus="rest",this.copyGeneration=0,this.onCopy=()=>{this.copyHash()},this.toggleFiles=()=>{const expanded=!this.filesExpanded;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||(this.filesExpanded=expanded,this.emit("lr-toggle",{expanded,collapsed:!expanded}))}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,commitCardCopyHash:LYRA_DEFAULT_commitCardCopyHash,commitCardDiffSummary:LYRA_DEFAULT_commitCardDiffSummary,commitCardFilesLimit:LYRA_DEFAULT_commitCardFilesLimit,commitCardHideFiles:LYRA_DEFAULT_commitCardHideFiles,commitCardLabel:LYRA_DEFAULT_commitCardLabel,commitCardShowFiles:LYRA_DEFAULT_commitCardShowFiles,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,gitStatusAdded:LYRA_DEFAULT_gitStatusAdded,gitStatusConflicted:LYRA_DEFAULT_gitStatusConflicted,gitStatusDeleted:LYRA_DEFAULT_gitStatusDeleted,gitStatusIgnored:LYRA_DEFAULT_gitStatusIgnored,gitStatusModified:LYRA_DEFAULT_gitStatusModified,gitStatusRenamed:LYRA_DEFAULT_gitStatusRenamed,gitStatusUntracked:LYRA_DEFAULT_gitStatusUntracked,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["files"])}static{this.styles=[LyraElement.styles,styles,agentActionButtonStyles]}updated(changed){super.updated(changed);const truncated=this.filesExpanded&&this.normalizedFiles.length>MAX_RENDERED_FILES;this.limitAnnouncementInitialized&&truncated&&!this.previouslyTruncated&&this.limitAnnouncements.announcePolite(this.localize("commitCardFilesLimit",void 0,{count:this.formatCount(MAX_RENDERED_FILES)})),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=truncated}get normalizedFiles(){return firstByIdentity(Array.isArray(this.files)?this.files:[],file=>file.path).map(file=>{if(file.status===void 0||GIT_STATUSES.has(file.status))return file;const retained={...file};return delete retained.status,retained})}disconnectedCallback(){super.disconnectedCallback(),this.resetCopyFeedback()}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.resetCopyFeedback()}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get subject(){return(this.message??"").split(`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{styles}from"./commit-card.styles.js";import{agentActionButtonStyles}from"../agent-action-button.styles.js";import{GIT_STATUSES}from"../../data/file-tree/file-tree.class.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{overallSemanticLabel,overallSemanticRole}from"../semantic-owner.js";import{firstByIdentity}from"../collection-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{LYRA_DEFAULT_commitCardCopyHash,LYRA_DEFAULT_commitCardDiffSummary,LYRA_DEFAULT_commitCardFilesLimit,LYRA_DEFAULT_commitCardHideFiles,LYRA_DEFAULT_commitCardLabel,LYRA_DEFAULT_commitCardShowFiles}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_gitStatusAdded,LYRA_DEFAULT_gitStatusConflicted,LYRA_DEFAULT_gitStatusDeleted,LYRA_DEFAULT_gitStatusIgnored,LYRA_DEFAULT_gitStatusModified,LYRA_DEFAULT_gitStatusRenamed,LYRA_DEFAULT_gitStatusUntracked,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";const GIT_STATUS_LETTER={added:"A",modified:"M",deleted:"D",renamed:"R",untracked:"U",conflicted:"C",ignored:"!"},MAX_DATE_EPOCH_MS=864e13,MAX_RENDERED_FILES=500,GIT_STATUS_KEY={added:"gitStatusAdded",modified:"gitStatusModified",deleted:"gitStatusDeleted",renamed:"gitStatusRenamed",untracked:"gitStatusUntracked",conflicted:"gitStatusConflicted",ignored:"gitStatusIgnored"};class LyraCommitCard extends LyraElement{constructor(){super(...arguments),this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.hash="",this.message="",this.author="",this.files=[],this.filesExpanded=!1,this.withoutCopyButton=!1,this.size="m",this.frame="card",this.copyStatus="rest",this.copyGeneration=0,this.onCopy=()=>{this.copyHash()},this.toggleFiles=()=>{const expanded=!this.filesExpanded;this.emit("lr-toggle-request",{expanded},{cancelable:!0}).defaultPrevented||(this.filesExpanded=expanded,this.emit("lr-toggle",{expanded,collapsed:!expanded}))}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,commitCardCopyHash:LYRA_DEFAULT_commitCardCopyHash,commitCardDiffSummary:LYRA_DEFAULT_commitCardDiffSummary,commitCardFilesLimit:LYRA_DEFAULT_commitCardFilesLimit,commitCardHideFiles:LYRA_DEFAULT_commitCardHideFiles,commitCardLabel:LYRA_DEFAULT_commitCardLabel,commitCardShowFiles:LYRA_DEFAULT_commitCardShowFiles,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,gitStatusAdded:LYRA_DEFAULT_gitStatusAdded,gitStatusConflicted:LYRA_DEFAULT_gitStatusConflicted,gitStatusDeleted:LYRA_DEFAULT_gitStatusDeleted,gitStatusIgnored:LYRA_DEFAULT_gitStatusIgnored,gitStatusModified:LYRA_DEFAULT_gitStatusModified,gitStatusRenamed:LYRA_DEFAULT_gitStatusRenamed,gitStatusUntracked:LYRA_DEFAULT_gitStatusUntracked,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["files"])}static{this.styles=[LyraElement.styles,srOnly,styles,agentActionButtonStyles]}updated(changed){super.updated(changed);const truncated=this.filesExpanded&&this.normalizedFiles.length>MAX_RENDERED_FILES;this.limitAnnouncementInitialized&&truncated&&!this.previouslyTruncated&&this.limitAnnouncements.announcePolite(this.localize("commitCardFilesLimit",void 0,{count:this.formatCount(MAX_RENDERED_FILES)})),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=truncated}get normalizedFiles(){return firstByIdentity(Array.isArray(this.files)?this.files:[],file=>file.path).map(file=>{if(file.status===void 0||GIT_STATUSES.has(file.status))return file;const retained={...file};return delete retained.status,retained})}disconnectedCallback(){super.disconnectedCallback(),this.resetCopyFeedback()}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted(),this.resetCopyFeedback()}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}get subject(){return(this.message??"").split(`
|
|
2
2
|
`)[0]??""}get body(){return(this.message??"").split(`
|
|
3
3
|
`).slice(1).join(`
|
|
4
4
|
`).trim()}get validTimestamp(){if(!(this.timestamp==null||!Number.isFinite(this.timestamp)||this.timestamp>MAX_DATE_EPOCH_MS))return finiteRange(this.timestamp,this.timestamp,0)}get totals(){return this.normalizedFiles.reduce((acc,file)=>({additions:finiteCount(acc.additions+finiteCount(file.additions)),deletions:finiteCount(acc.deletions+finiteCount(file.deletions))}),{additions:0,deletions:0})}async copyHash(){const text=this.hash,owner=this.isConnected?this.ownerDocument.defaultView:null,generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyStatus="rest";const outcome=await writeClipboardText(owner,text);if(!(!owner||!this.isCurrentCopy(generation,owner))){if(!outcome.ok){this.showCopyStatus("error",generation,owner),this.emit("lr-error"),this.emit("lr-copy-error",outcome);return}this.showCopyStatus("success",generation,owner),this.emit("lr-copy",outcome)}}isCurrentCopy(generation,owner){return this.isConnected&&generation===this.copyGeneration&&this.ownerDocument.defaultView===owner}showCopyStatus(status,generation,owner){this.copyStatus=status,this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{this.copyTimer?.owner!==owner||this.copyTimer.handle!==handle||this.copyTimer.generation!==generation||generation!==this.copyGeneration||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.copyTimer=void 0,this.copyStatus="rest")},1500),this.copyTimer={owner,handle,generation}}render(){const files=this.normalizedFiles,{additions,deletions}=this.totals,timestamp=this.validTimestamp;return html`
|
|
@@ -17,11 +17,10 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
17
17
|
>${getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(new Date(timestamp))}</time
|
|
18
18
|
></span
|
|
19
19
|
>`:nothing}
|
|
20
|
-
${files.length>0?html`<span
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
<span part="additions">+${this.formatCount(additions)}</span> <span part="deletions">-${this.formatCount(deletions)}</span>
|
|
20
|
+
${files.length>0?html`<span part="diffstat"
|
|
21
|
+
><span class="sr-only">${this.localize("commitCardDiffSummary",void 0,{additions:this.formatCount(additions),deletions:this.formatCount(deletions),files:this.formatCount(files.length)})}</span><span aria-hidden="true"
|
|
22
|
+
><span part="additions">+${this.formatCount(additions)}</span> <span part="deletions">-${this.formatCount(deletions)}</span></span
|
|
23
|
+
>
|
|
25
24
|
</span>`:nothing}
|
|
26
25
|
${!this.withoutCopyButton&&this.hash?html`<button
|
|
27
26
|
part="copy-button"
|
|
@@ -52,8 +51,8 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
52
51
|
@click=${()=>this.emit("lr-file-select",{filePath:f.path})}
|
|
53
52
|
>
|
|
54
53
|
<span part="file-path" dir="ltr"
|
|
55
|
-
>${f.status?html`<span part="file-status"
|
|
56
|
-
>${GIT_STATUS_LETTER[f.status]}</span
|
|
54
|
+
>${f.status?html`<span part="file-status"
|
|
55
|
+
><span aria-hidden="true">${GIT_STATUS_LETTER[f.status]}</span><span class="sr-only">${this.localize(GIT_STATUS_KEY[f.status])}</span></span
|
|
57
56
|
> `:""}${f.path}</span
|
|
58
57
|
>
|
|
59
58
|
<span class="file-stats">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import"../../forms/input/input.class.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getCollator,getNumberFormat}from"../../../internal/intl-cache.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{styles}from"./eval-dataset.styles.js";import{agentActionButtonStyles}from"../agent-action-button.styles.js";import{firstByIdentity}from"../collection-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_evalDatasetAddExample,LYRA_DEFAULT_evalDatasetColumnExpectedOutput,LYRA_DEFAULT_evalDatasetColumnInput,LYRA_DEFAULT_evalDatasetColumnTags,LYRA_DEFAULT_evalDatasetEmpty,LYRA_DEFAULT_evalDatasetImportLabel,LYRA_DEFAULT_evalDatasetLabel,LYRA_DEFAULT_evalDatasetLimit,LYRA_DEFAULT_evalDatasetNoMatches,LYRA_DEFAULT_evalDatasetRemoveExample,LYRA_DEFAULT_evalDatasetSearchLabel,LYRA_DEFAULT_evalDatasetTagFilterLabel}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const MAX_RENDERED_EXAMPLES=100,rowKey=row=>row.id;class LyraEvalDataset extends LyraElement{constructor(){super(...arguments),this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.examplesTruncated=!1,this.examples=[],this.searchable=!1,this.autocomplete="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.inputMode="",this.enterKeyHint="",this.accept="",this.exportFormats=["csv","json"],this.disabled=!1,this.label="",this.searchText="",this.activeTags=new Set,this.selectedId=null,this.normalizedCache=[],this.visibleExamples=[],this.onAddClick=()=>{this.disabled||this.emit("lr-example-add-request")},this.onRemoveClick=()=>{this.disabled||this.selectedId===null||this.emit("lr-example-remove-request",{exampleId:this.selectedId})},this.onGridRowActivate=e=>{if(e.stopPropagation(),this.disabled)return;const id=e.detail.row.id;this.selectedId=id,this.emit("lr-example-select",{exampleId:id})},this.onFiles=e=>{e.stopPropagation(),!(this.disabled||e.detail.files.length===0)&&this.emit("lr-import-request",{files:[...e.detail.files]})},this.onExportButtonExport=e=>{e.preventDefault(),e.stopPropagation(),!this.disabled&&this.emit("lr-export-request",{format:e.detail.format})},this.gateDisabledClear={handleEvent:event=>{this.disabled&&event.stopPropagation()},capture:!0}}static{this.defaultStrings={...super.defaultStrings,evalDatasetAddExample:LYRA_DEFAULT_evalDatasetAddExample,evalDatasetColumnExpectedOutput:LYRA_DEFAULT_evalDatasetColumnExpectedOutput,evalDatasetColumnInput:LYRA_DEFAULT_evalDatasetColumnInput,evalDatasetColumnTags:LYRA_DEFAULT_evalDatasetColumnTags,evalDatasetEmpty:LYRA_DEFAULT_evalDatasetEmpty,evalDatasetImportLabel:LYRA_DEFAULT_evalDatasetImportLabel,evalDatasetLabel:LYRA_DEFAULT_evalDatasetLabel,evalDatasetLimit:LYRA_DEFAULT_evalDatasetLimit,evalDatasetNoMatches:LYRA_DEFAULT_evalDatasetNoMatches,evalDatasetRemoveExample:LYRA_DEFAULT_evalDatasetRemoveExample,evalDatasetSearchLabel:LYRA_DEFAULT_evalDatasetSearchLabel,evalDatasetTagFilterLabel:LYRA_DEFAULT_evalDatasetTagFilterLabel,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["examples","exportFormats"])}static{this.identityCollectionProperties=Object.freeze(["examples"])}static{this.styles=[LyraElement.styles,styles,agentActionButtonStyles]}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted()}updated(changed){if(super.updated(changed),this.limitAnnouncementInitialized&&this.examplesTruncated&&!this.previouslyTruncated){const truncation=publicCollectionTruncation(this,"examples");truncation&&this.limitAnnouncements.announcePolite(this.localize("evalDatasetLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(truncation.retained)}))}this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.examplesTruncated}static{this.immutableEventDetails=Object.freeze(["lr-import-request"])}get normalizedExamples(){if(this.normalizedFor!==this.examples){this.normalizedFor=this.examples;const deduped=firstByIdentity(Array.isArray(this.examples)?this.examples:[],example=>example.id);this.normalizedCache=deduped.map(example=>Array.isArray(example.tags)?example:{...example,tags:void 0})}return this.normalizedCache}willUpdate(changed){if(super.willUpdate(changed),changed.has("searchable")&&!this.searchable&&(this.searchText=""),changed.has("examples")){this.selectedId!==null&&!this.normalizedExamples.some(example=>example.id===this.selectedId)&&this.clearSelection();const available=this.allTags();[...this.activeTags].some(tag=>!available.
|
|
1
|
+
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import"../../forms/input/input.class.js";import{collectionSupport,publicCollectionTruncation}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getCollator,getNumberFormat}from"../../../internal/intl-cache.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{styles}from"./eval-dataset.styles.js";import{agentActionButtonStyles}from"../agent-action-button.styles.js";import{firstByIdentity}from"../collection-identity.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_evalDatasetAddExample,LYRA_DEFAULT_evalDatasetColumnExpectedOutput,LYRA_DEFAULT_evalDatasetColumnInput,LYRA_DEFAULT_evalDatasetColumnTags,LYRA_DEFAULT_evalDatasetEmpty,LYRA_DEFAULT_evalDatasetImportLabel,LYRA_DEFAULT_evalDatasetLabel,LYRA_DEFAULT_evalDatasetLimit,LYRA_DEFAULT_evalDatasetNoMatches,LYRA_DEFAULT_evalDatasetRemoveExample,LYRA_DEFAULT_evalDatasetSearchLabel,LYRA_DEFAULT_evalDatasetTagFilterLabel}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const MAX_RENDERED_EXAMPLES=100,rowKey=row=>row.id;class LyraEvalDataset extends LyraElement{constructor(){super(...arguments),this.limitAnnouncements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.examplesTruncated=!1,this.examples=[],this.searchable=!1,this.autocomplete="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.inputMode="",this.enterKeyHint="",this.accept="",this.exportFormats=["csv","json"],this.disabled=!1,this.label="",this.searchText="",this.activeTags=new Set,this.selectedId=null,this.normalizedCache=[],this.visibleExamples=[],this.onAddClick=()=>{this.disabled||this.emit("lr-example-add-request")},this.onRemoveClick=()=>{this.disabled||this.selectedId===null||this.emit("lr-example-remove-request",{exampleId:this.selectedId})},this.onGridRowActivate=e=>{if(e.stopPropagation(),this.disabled)return;const id=e.detail.row.id;this.selectedId=id,this.emit("lr-example-select",{exampleId:id})},this.onFiles=e=>{e.stopPropagation(),!(this.disabled||e.detail.files.length===0)&&this.emit("lr-import-request",{files:[...e.detail.files]})},this.onExportButtonExport=e=>{e.preventDefault(),e.stopPropagation(),!this.disabled&&this.emit("lr-export-request",{format:e.detail.format})},this.gateDisabledClear={handleEvent:event=>{this.disabled&&event.stopPropagation()},capture:!0}}static{this.defaultStrings={...super.defaultStrings,evalDatasetAddExample:LYRA_DEFAULT_evalDatasetAddExample,evalDatasetColumnExpectedOutput:LYRA_DEFAULT_evalDatasetColumnExpectedOutput,evalDatasetColumnInput:LYRA_DEFAULT_evalDatasetColumnInput,evalDatasetColumnTags:LYRA_DEFAULT_evalDatasetColumnTags,evalDatasetEmpty:LYRA_DEFAULT_evalDatasetEmpty,evalDatasetImportLabel:LYRA_DEFAULT_evalDatasetImportLabel,evalDatasetLabel:LYRA_DEFAULT_evalDatasetLabel,evalDatasetLimit:LYRA_DEFAULT_evalDatasetLimit,evalDatasetNoMatches:LYRA_DEFAULT_evalDatasetNoMatches,evalDatasetRemoveExample:LYRA_DEFAULT_evalDatasetRemoveExample,evalDatasetSearchLabel:LYRA_DEFAULT_evalDatasetSearchLabel,evalDatasetTagFilterLabel:LYRA_DEFAULT_evalDatasetTagFilterLabel,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["examples","exportFormats"])}static{this.identityCollectionProperties=Object.freeze(["examples"])}static{this.styles=[LyraElement.styles,styles,agentActionButtonStyles]}adoptedCallback(){super.adoptedCallback(),this.limitAnnouncements.adopted()}updated(changed){if(super.updated(changed),this.limitAnnouncementInitialized&&this.examplesTruncated&&!this.previouslyTruncated){const truncation=publicCollectionTruncation(this,"examples");truncation&&this.limitAnnouncements.announcePolite(this.localize("evalDatasetLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(truncation.retained)}))}this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.examplesTruncated}static{this.immutableEventDetails=Object.freeze(["lr-import-request"])}get normalizedExamples(){if(this.normalizedFor!==this.examples){this.normalizedFor=this.examples;const deduped=firstByIdentity(Array.isArray(this.examples)?this.examples:[],example=>example.id);this.normalizedCache=deduped.map(example=>Array.isArray(example.tags)?example:{...example,tags:void 0})}return this.normalizedCache}willUpdate(changed){if(super.willUpdate(changed),changed.has("searchable")&&!this.searchable&&(this.searchText=""),changed.has("examples")){this.selectedId!==null&&!this.normalizedExamples.some(example=>example.id===this.selectedId)&&this.clearSelection();const available=new Set(this.allTags());[...this.activeTags].some(tag=>!available.has(tag))&&(this.activeTags=new Set([...this.activeTags].filter(tag=>available.has(tag))))}this.visibleExamples=this.filterExamples(),(changed.has("examples")||changed.has("searchText")||changed.has("activeTags")||changed.has("searchable"))&&this.selectedId!==null&&!this.visibleExamples.some(example=>example.id===this.selectedId)&&this.clearSelection()}clearSelection(){this.selectedId=null,this.emit("lr-example-select",{exampleId:null})}allTags(){const tags=new Set;for(const example of this.normalizedExamples)for(const tag of example.tags??[])tags.add(tag);return[...tags].sort(getCollator(this.effectiveLocale).compare)}filterExamples(){const query=this.searchText.trim().toLocaleLowerCase(this.effectiveLocale);return this.normalizedExamples.filter(example=>this.activeTags.size>0&&!(example.tags??[]).some(tag=>this.activeTags.has(tag))?!1:query===""?!0:[example.input,example.expectedOutput??"",...example.tags??[]].join(" ").toLocaleLowerCase(this.effectiveLocale).includes(query))}buildColumns(){const labels=[this.localize("evalDatasetColumnInput"),this.localize("evalDatasetColumnExpectedOutput"),this.localize("evalDatasetColumnTags")],key=labels.join("\0");return this.columnsCache?.key!==key&&(this.columnsCache={key,columns:this.createColumns(labels)}),this.columnsCache.columns}selectedKeys(){return this.selectedKeysCache?.id!==this.selectedId&&(this.selectedKeysCache={id:this.selectedId,keys:this.selectedId===null?new Set:new Set([this.selectedId])}),this.selectedKeysCache.keys}createColumns([inputLabel,expectedLabel,tagsLabel]){return[{key:"input",label:inputLabel,sortable:!0,sortValue:row=>row.input,cell:row=>row.input},{key:"expectedOutput",label:expectedLabel,sortable:!0,sortValue:row=>row.expectedOutput??"",cell:row=>row.expectedOutput??""},{key:"tags",label:tagsLabel,sortable:!0,sortValue:row=>(row.tags??[]).join(", "),cell:row=>(row.tags??[]).join(", ")}]}onTagChipToggle(tag,e){if(e.stopPropagation(),this.disabled)return;const next=new Set(this.activeTags);e.detail.selected?next.add(tag):next.delete(tag),this.activeTags=next}stopOwnedEvent(event){event.stopPropagation()}renderToolbar(){return html`
|
|
2
2
|
<div part="toolbar">
|
|
3
3
|
<button part="add-button" data-agent-action="brand" type="button" ?disabled=${this.disabled} @click=${this.onAddClick}>
|
|
4
4
|
${this.localize("evalDatasetAddExample")}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import{__decorate}from"tslib";import{snapshotStructuredData,isSnapshotArrayIndex as isArrayIndex}from"../../../internal/structured-snapshot.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteCount}from"../../../internal/numbers.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import"../../overlays/badge/badge.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./schema-viewer.styles.js";import{overallSemanticLabel}from"../semantic-owner.js";import{LYRA_DEFAULT_schemaViewerCircular,LYRA_DEFAULT_schemaViewerEmpty,LYRA_DEFAULT_schemaViewerIssueLimit,LYRA_DEFAULT_schemaViewerLabel,LYRA_DEFAULT_schemaViewerLimit,LYRA_DEFAULT_schemaViewerRequired,LYRA_DEFAULT_schemaViewerType}from"../../../internal/default-strings/agent-tools.generated.js";const MAX_RENDERED_SCHEMA_NODES=500,MAX_RENDERED_SCHEMA_ISSUES=500,MAX_SCHEMA_DEPTH=100,MAX_CONSTRAINT_VALUES=50,MAX_CONSTRAINT_VALUE_CHARACTERS=1e3,MAX_CONSTRAINT_OBJECT_NODES=50;function constraintValue(value){const seen=new Set;let remaining=MAX_CONSTRAINT_OBJECT_NODES;const visit=(candidate,depth)=>{if(remaining--<=0)return"…";if(candidate===null)return"null";if(typeof candidate=="string")return JSON.stringify(candidate.slice(0,MAX_CONSTRAINT_VALUE_CHARACTERS));if(typeof candidate=="number"||typeof candidate=="boolean")return String(candidate);if(typeof candidate=="bigint")return`${candidate.toString()}n`;if(candidate===void 0)return"undefined";if(typeof candidate!="object")return String(candidate);if(seen.has(candidate))return"[Circular]";if(depth>=3)return Array.isArray(candidate)?"[…]":"{…}";seen.add(candidate);let result;if(Array.isArray(candidate)){const values=candidate.slice(0,MAX_CONSTRAINT_VALUES).map(item=>visit(item,depth+1));result=`[${values.join(", ")}${candidate.length>values.length?", …":""}]`}else{const entries=Object.entries(candidate).slice(0,MAX_CONSTRAINT_VALUES);result=`{${entries.map(([key,item])=>`${JSON.stringify(key)}: ${visit(item,depth+1)}`).join(", ")}${Object.keys(candidate).length>entries.length?", …":""}}`}return seen.delete(candidate),result.slice(0,MAX_CONSTRAINT_VALUE_CHARACTERS)};return visit(value,0)}function isReadonlyArray(value){return Array.isArray(value)}function schemaStructure(depth){return{shape:"record",depth,child:(key,value)=>{if((key==="properties"||key==="items"||key==="allOf"||key==="anyOf"||key==="oneOf")&&depth>=MAX_SCHEMA_DEPTH)return;if(key==="properties")return{shape:"record",depth:depth+1,container:!1,child:()=>schemaStructure(depth+1)};let array=!1;try{array=Array.isArray(value)}catch{}return key==="allOf"||key==="anyOf"||key==="oneOf"||key==="items"&&array?{shape:"array",depth:depth+1,container:!1,child:index=>isArrayIndex(index)?schemaStructure(depth+1):{depth:depth+1}}:key==="items"?schemaStructure(depth+1):{depth:depth+1}}}}function snapshotSchema(value){return snapshotStructuredData(value,{profile:"schema",structure:schemaStructure(0)}).value??null}class LyraJsonSchemaViewer extends LyraElement{constructor(){super(...arguments),this.schemaValue=null,this.lastSchemaInput=null,this.focusStopPath=null,this.issues=[],this.selectedPath=null,this.maxDepth=20,this.label="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.previousNodeLimitText="",this.previousIssueLimitText="",this.suppressNextLimitAnnouncement=!0,this.onTreeFocusIn=event=>{const trigger=event.target?.closest('[part~="node-trigger"]');trigger&&(this.focusStopPath=trigger.dataset.path??null,this.syncFocusStop())},this.onTreeKeyDown=event=>{if(event.defaultPrevented||event.altKey||event.ctrlKey||event.metaKey)return;const triggers=this.nodeTriggers(),current=event.target?.closest('[part~="node-trigger"]'),index=current?triggers.indexOf(current):-1;if(index<0)return;const target=event.key==="ArrowDown"?triggers[Math.min(triggers.length-1,index+1)]:event.key==="ArrowUp"?triggers[Math.max(0,index-1)]:event.key==="Home"?triggers[0]:event.key==="End"?triggers[triggers.length-1]:void 0;target&&(event.preventDefault(),target.focus())}}static{this.defaultStrings={...super.defaultStrings,schemaViewerCircular:LYRA_DEFAULT_schemaViewerCircular,schemaViewerEmpty:LYRA_DEFAULT_schemaViewerEmpty,schemaViewerIssueLimit:LYRA_DEFAULT_schemaViewerIssueLimit,schemaViewerLabel:LYRA_DEFAULT_schemaViewerLabel,schemaViewerLimit:LYRA_DEFAULT_schemaViewerLimit,schemaViewerRequired:LYRA_DEFAULT_schemaViewerRequired,schemaViewerType:LYRA_DEFAULT_schemaViewerType}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["issues"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-schema-select"])}static{this.identityEventDetailProperties=Object.freeze({"lr-schema-select":Object.freeze(["schema"])})}get schema(){return this.schemaValue}set schema(value){if(value===this.schemaValue||value===this.lastSchemaInput)return;this.lastSchemaInput=value;const previous=this.schemaValue;this.schemaValue=snapshotSchema(value),this.requestUpdate("schema",previous)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextLimitAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){super.disconnectedCallback(),this.suppressNextLimitAnnouncement=!0}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(_changed){super.updated(_changed),this.syncFocusStop();const nodeText=this.renderRoot.querySelector('[part="limit"]')?.textContent?.trim()??"",issueText=this.renderRoot.querySelector('[part="issue-limit"]')?.textContent?.trim()??"";this.suppressNextLimitAnnouncement||(nodeText&&nodeText!==this.previousNodeLimitText&&this.announcements.announcePolite(nodeText),issueText&&issueText!==this.previousIssueLimitText&&this.announcements.announcePolite(issueText)),this.previousNodeLimitText=nodeText,this.previousIssueLimitText=issueText,this.suppressNextLimitAnnouncement=!1}nodeTriggers(){return Array.from(this.renderRoot.querySelectorAll('[part~="node-trigger"]'))}syncFocusStop(){const triggers=this.nodeTriggers(),stop=triggers.find(trigger=>trigger.dataset.path===this.focusStopPath)??triggers.find(trigger=>trigger.dataset.path===this.selectedPath)??triggers[0];for(const trigger of triggers)trigger.tabIndex=trigger===stop?0:-1}pointerSegment(value){return value.replace(/~/g,"~0").replace(/\//g,"~1")}decodePointerSegment(segment){return segment.replace(/~1/g,"/").replace(/~0/g,"~")}resolvedSelectionPathChain(){const selectedPath=this.selectedPath,root=this.schema;if(selectedPath==null||!root||typeof root!="object")return new Set;if(selectedPath==="")return new Set([""]);if(!selectedPath.startsWith("/"))return new Set;const segments=selectedPath.split("/").slice(1),maxDepth=finiteCount(this.maxDepth,20,MAX_SCHEMA_DEPTH),chain=new Set([""]),visited=new Set([root]);let node=root,path="",depth=0,index=0;for(;index<segments.length;){if(depth>=maxDepth)return new Set;const kind=segments[index];let next,nextPath,consumed=0;if(kind==="properties"){const keySegment=segments[index+1];if(keySegment!==void 0){const candidate=node.properties?.[this.decodePointerSegment(keySegment)];candidate&&(next=candidate,nextPath=`${path}/properties/${keySegment}`,consumed=2)}}else if(kind==="allOf"||kind==="anyOf"||kind==="oneOf"){const idxSegment=segments[index+1];if(idxSegment!==void 0&&isArrayIndex(idxSegment)){const list=node[kind],candidate=Array.isArray(list)?list[Number(idxSegment)]:void 0;candidate&&(next=candidate,nextPath=`${path}/${kind}/${idxSegment}`,consumed=2)}}else if(kind==="items")if(isReadonlyArray(node.items)){const idxSegment=segments[index+1];if(idxSegment!==void 0&&isArrayIndex(idxSegment)){const candidate=node.items[Number(idxSegment)];candidate&&(next=candidate,nextPath=`${path}/items/${idxSegment}`,consumed=2)}}else node.items&&(next=node.items,nextPath=`${path}/items`,consumed=1);if(!next||nextPath===void 0||visited.has(next))return new Set;visited.add(next),node=next,path=nextPath,chain.add(path),depth+=1,index+=consumed}return path===selectedPath?chain:new Set}constraints(schema){const rows=["format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","minProperties","maxProperties"].flatMap(key=>schema[key]==null?[]:[`${key}: ${constraintValue(schema[key])}`]);if(schema.enum){const values=schema.enum.slice(0,MAX_CONSTRAINT_VALUES).map(constraintValue);rows.push(`enum: [${values.join(", ")}${schema.enum.length>values.length?", …":""}]`)}if(Object.prototype.hasOwnProperty.call(schema,"const")&&rows.push(`const: ${constraintValue(schema.const)}`),Object.prototype.hasOwnProperty.call(schema,"default")&&rows.push(`default: ${constraintValue(schema.default)}`),schema.examples){const examples=schema.examples.slice(0,MAX_CONSTRAINT_VALUES).map(constraintValue);rows.push(`examples: [${examples.join(", ")}${schema.examples.length>examples.length?", …":""}]`)}return schema.$ref&&rows.push(`$ref: ${schema.$ref.slice(0,MAX_CONSTRAINT_VALUE_CHARACTERS)}`),rows}renderNode(name,schema,path,required,depth,ancestors,budget,issuesByPath){if(!budget.reservedPaths.has(path)){if(budget.remaining<=0)return budget.truncated=!0,nothing;budget.remaining--}const selected=path===this.selectedPath;if(ancestors.has(schema))return html`<li part="node">
|
|
2
2
|
<span part="description">${this.localize("schemaViewerCircular")}</span>
|
|
3
|
-
</li>`;const nextAncestors=new Set(ancestors).add(schema),type=isReadonlyArray(schema.type)?schema.type.join(" | "):schema.type??(schema.properties?"object":""),constraints=this.constraints(schema),issues=issuesByPath.get(path)??[],children=[];let pendingReservedChild=budget.reservedPaths.has(path)&&path!==this.selectedPath;const addChild=child=>pendingReservedChild&&budget.reservedPaths.has(child.path)
|
|
3
|
+
</li>`;const nextAncestors=new Set(ancestors).add(schema),type=isReadonlyArray(schema.type)?schema.type.join(" | "):schema.type??(schema.properties?"object":""),constraints=this.constraints(schema),issues=issuesByPath.get(path)??[],children=[];let pendingReservedChild=budget.reservedPaths.has(path)&&path!==this.selectedPath;const requiredKeys=Array.isArray(schema.required)?schema.required:void 0;let requiredLookups=0,requiredMembership;const addChild=(child,requiredKey)=>{if(pendingReservedChild&&budget.reservedPaths.has(child.path))pendingReservedChild=!1;else if(children.length>=budget.remaining)return budget.truncated=!0,pendingReservedChild;return requiredKey!==void 0&&requiredKeys&&(requiredLookups+=1,child.required=requiredLookups===1?requiredKeys.includes(requiredKey):(requiredMembership??=new Set(requiredKeys)).has(requiredKey)),children.push(child),!0};if(depth<finiteCount(this.maxDepth,20,MAX_SCHEMA_DEPTH)){const properties=schema.properties??{};for(const key in properties){if(!Object.prototype.hasOwnProperty.call(properties,key))continue;const node=properties[key];if(node&&!addChild({name:key,node,path:`${path}/properties/${this.pointerSegment(key)}`,required:!1},key))break}for(const keyword of["allOf","anyOf","oneOf"]){const nodes=schema[keyword]??[];for(const key of Object.keys(nodes)){if(!isArrayIndex(key))continue;const index=Number(key),node=nodes[index];if(node&&!addChild({name:`${keyword}[${index}]`,node,path:`${path}/${keyword}/${index}`,required:!1}))break}}if(isReadonlyArray(schema.items))for(const key of Object.keys(schema.items)){if(!isArrayIndex(key))continue;const index=Number(key),node=schema.items[index];if(node&&!addChild({name:`items[${index}]`,node,path:`${path}/items/${index}`,required:!1}))break}else schema.items&&addChild({name:"items",node:schema.items,path:`${path}/items`,required:!1})}return html`
|
|
4
4
|
<li part=${selected?"node node-selected":"node"} style=${`--_lr-schema-depth:${depth}`}>
|
|
5
5
|
<button
|
|
6
6
|
part="node-trigger"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{nextId}from"../../../internal/a11y.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import{EMPTY_SCHEMA,MAX_ENUM_OPTIONS,MAX_SCHEMA_FIELDS,snapshotFormValue,snapshotSchema}from"./tool-param-snapshot.js";import{toolParamChoices,toolParamConstraintFailure,validToolParamConstraints}from"./tool-param-constraints.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/input/number-input.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamBooleanFalse,LYRA_DEFAULT_toolParamBooleanTrue,LYRA_DEFAULT_toolParamBooleanUnset,LYRA_DEFAULT_toolParamFormat,LYRA_DEFAULT_toolParamInvalidConstraint,LYRA_DEFAULT_toolParamInvalidSelection,LYRA_DEFAULT_toolParamMaxItems,LYRA_DEFAULT_toolParamMaxLength,LYRA_DEFAULT_toolParamMaximum,LYRA_DEFAULT_toolParamMinItems,LYRA_DEFAULT_toolParamMinLength,LYRA_DEFAULT_toolParamMinimum,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_toolParamSchemaLimit,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LISTED_CHOICES=10;function sameErrors(left,right){const keys=Object.keys(left);return keys.length===Object.keys(right).length&&keys.every(key=>left[key]===right[key])}class LyraToolParamForm extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamBooleanFalse:LYRA_DEFAULT_toolParamBooleanFalse,toolParamBooleanTrue:LYRA_DEFAULT_toolParamBooleanTrue,toolParamBooleanUnset:LYRA_DEFAULT_toolParamBooleanUnset,toolParamFormat:LYRA_DEFAULT_toolParamFormat,toolParamInvalidConstraint:LYRA_DEFAULT_toolParamInvalidConstraint,toolParamInvalidSelection:LYRA_DEFAULT_toolParamInvalidSelection,toolParamMaxItems:LYRA_DEFAULT_toolParamMaxItems,toolParamMaxLength:LYRA_DEFAULT_toolParamMaxLength,toolParamMaximum:LYRA_DEFAULT_toolParamMaximum,toolParamMinItems:LYRA_DEFAULT_toolParamMinItems,toolParamMinLength:LYRA_DEFAULT_toolParamMinLength,toolParamMinimum:LYRA_DEFAULT_toolParamMinimum,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,toolParamSchemaLimit:LYRA_DEFAULT_toolParamSchemaLimit,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-validity-change","lr-input","lr-change"])}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},schema:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this._errors=Object.create(null),this._formError="",this.showFormError=!1,this.touchedFields=new Set,this.baseId=nextId("tool-param-form"),this._fieldsetDisabled=!1,this._name="",this._schema=EMPTY_SCHEMA,this.schemaInputShapeError="",this.schemaInputExceededLimits=!1,this._value=Object.freeze({}),this.lastSchemaInput=EMPTY_SCHEMA,this.lastValueInput=this._value,this.valueInputInvalid=!1,this.valueInputTruncated=!1,this.defaultValueSnapshot=Object.freeze({}),this.defaultValueCaptured=!1,this._effectiveValue=Object.freeze({}),this._validityFlags={},this._disabled=!1,this.hasInteracted=!1,this.visibleErrorSnapshot=new Map,this.suppressNextErrorAnnouncement=!0,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.syncValidityCustomStates())},this.onValueCommit=event=>{event.stopPropagation(),this.effectiveDisabled||emitValueEvents(this,"change",{value:this.effectiveValue},detail=>this.emit("lr-change",detail))},this.stopNestedControlEvent=e=>{e.stopPropagation()},this.onFieldFocus=event=>{relayNativeEvent(this,event)},this.onFieldBlur=event=>{relayNativeEvent(this,event)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.syncFormState()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset.key===key);if(field)return field}}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&!!this._errors[key])}firstMissingPropertyError(){if(!this.renderRoot)return;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset.key===key);if(error)return error}}focusFirstControl(options){if(!this.renderRoot)return;const controls=this.renderRoot.querySelectorAll(`input.control, ${tag("select")}, ${tag("number-input")}`);for(const control of controls)if(!(control.disabled||control.getAttribute("aria-disabled")==="true")){control.focus(options);return}}click(){this.effectiveDisabled||this.focusFirstControl()}focus(options){this.effectiveDisabled||this.focusFirstControl(options)}blur(){const active=deepActiveElementIn(this.isConnected?this.shadowRoot:null);active&&typeof active.blur=="function"&&active.blur()}connectedCallback(){this.defaultValueCaptured||(this.defaultValueSnapshot=this._value,this.defaultValueCaptured=!0),super.connectedCallback(),this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})),this.hasUpdated&&(this.suppressNextErrorAnnouncement=!0,this.requestUpdate()),this.syncFormState()}disconnectedCallback(){super.disconnectedCallback(),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.suppressNextErrorAnnouncement=!0}get effectiveValue(){return this._effectiveValue}get schemaProperties(){return this._schema.properties}get requiredKeys(){return this._schema.required??Object.freeze([])}resolveEffectiveValue(){const props=this.schemaProperties,out={...this.value};for(const[key,prop]of Object.entries(props)){const fallback=prop.const!==void 0?prop.const:prop.default;!Object.prototype.hasOwnProperty.call(this.value,key)&&fallback!==void 0&&Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:fallback})}return snapshotFormValue(out).value}get schema(){return this._schema}set schema(next){if(next===this._schema||next===this.lastSchemaInput)return;this.lastSchemaInput=next;const old=this._schema,snapshot=snapshotSchema(next);this._schema=snapshot.schema,this.schemaInputShapeError=snapshot.shapeError,this.schemaInputExceededLimits=snapshot.exceededLimits,this.syncFormState(),this.requestUpdate("schema",old)}get value(){return this._value}set value(next){next===this._value||next===this.lastValueInput||(this.lastValueInput=next,this.applyValue(next))}applyValue(next){const old=this._value,snapshot=snapshotFormValue(next);this._value=snapshot.value,this.valueInputInvalid=snapshot.invalid,this.valueInputTruncated=snapshot.truncated,this.syncFormState(),this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.applyValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&(this.validityController.customValidityMessage||this._formError)&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}get formError(){return this._formError}selectionMessage(prop){const choices=prop.type==="string"?toolParamChoices(prop):void 0;return!choices||choices.length===0||choices.length>MAX_LISTED_CHOICES?this.localize("toolParamInvalidSelection"):this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(choices.map(choice=>choice.label))})}computeValidation(effective){const props=this.schemaProperties,required=new Set(this.requiredKeys),out=Object.create(null),flags={},addError=(key,message)=>{Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"&&type!=="array"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)})),flags.customError=!0;continue}if(!validToolParamConstraints(prop)){addError(key,this.localize("toolParamInvalidConstraint")),flags.customError=!0;continue}if(!(Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0)){required.has(key)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);continue}const v=effective[key];if(type==="string"&&typeof v!="string"){addError(key,this.localize("fieldMustBeString")),flags.typeMismatch=!0;continue}if(type==="number"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber")),flags.typeMismatch=!0;continue}if(type==="integer"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger")),flags.typeMismatch=!0;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger")),flags.stepMismatch=!0;continue}if(type==="boolean"&&typeof v!="boolean"){addError(key,this.localize("fieldMustBeBoolean")),flags.typeMismatch=!0;continue}const constraint=toolParamConstraintFailure(prop,v);if(constraint){const number=getNumberFormat(this.effectiveLocale),message=constraint==="minLength"?this.localize("toolParamMinLength",void 0,{count:number.format(prop.minLength)}):constraint==="maxLength"?this.localize("toolParamMaxLength",void 0,{count:number.format(prop.maxLength)}):constraint==="minimum"?this.localize("toolParamMinimum",void 0,{value:number.format(prop.minimum)}):constraint==="maximum"?this.localize("toolParamMaximum",void 0,{value:number.format(prop.maximum)}):constraint==="minItems"?this.localize("toolParamMinItems",void 0,{count:number.format(prop.minItems)}):constraint==="maxItems"?this.localize("toolParamMaxItems",void 0,{count:number.format(prop.maxItems)}):constraint==="format"?this.localize("toolParamFormat",void 0,{format:prop.format}):this.selectionMessage(prop);addError(key,message),flags.customError=!0;continue}prop.const!==void 0&&v!==prop.const&&(addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)})),flags.customError=!0)}for(const key of required)Object.prototype.hasOwnProperty.call(props,key)||(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);return{errors:out,flags}}checkValidity(){return this.validityController.checkValidity(()=>this.syncFormState())}reportValidity(){this.validityController.syncConstraints(),this.hasInteracted=!0,this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])),this._formError&&(this.showFormError=!0),this.requestUpdate();const valid=this.internals.reportValidity();return!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0&&this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor(),error?.focus()}),valid}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.hasInteracted=!1,this.applyValue(this.defaultValueSnapshot),this.touchedFields=new Set,this.showFormError=!1}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.applyValue(restored)}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.applyValidity(),this.requestUpdate())}schemaShapeError(){return this.schemaInputShapeError==="object"?this.localize("schemaMustBeObject"):this.schemaInputShapeError==="properties"?this.localize("schemaPropertiesMustBeFlat"):this.schemaInputExceededLimits?this.localize("toolParamSchemaLimit",void 0,{fields:getNumberFormat(this.effectiveLocale).format(MAX_SCHEMA_FIELDS),options:getNumberFormat(this.effectiveLocale).format(MAX_ENUM_OPTIONS)}):""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value=="number"&&!Number.isFinite(value))throw new TypeError("Non-finite numbers are not JSON values.");return value});if(typeof serialized!="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue),this.applyValidity()}applyValidity(){if(this.validityController){if(this.barredFromValidation||Object.keys(this._validityFlags).length===0)this.validityController.setValidity({});else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates(),this.publishValiditySnapshot()}}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective=Object.freeze({}),errors={},flags={},formError="",formValue=null;try{if(formError=this.schemaShapeError(),this.valueInputInvalid||this.valueInputTruncated)throw new TypeError("The value could not be retained within the public snapshot boundary.");effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors,flags=validation.flags,formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable"),formValue=null}formError&&(flags.customError=!0,formValue=null),this._effectiveValue=effective,sameErrors(this._errors,errors)||(this._errors=errors),this._formError=formError,this._validityFlags=flags,this.syncInternals(formValue)}updated(changed){if(super.updated(changed),this.publishValiditySnapshot(),changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]=="function").map(element=>element.updateComplete).filter(update=>update!==void 0);nestedUpdates.length>0&&Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}const currentErrors=this.visibleErrors();if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors)this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)&&freshMessages.push(text);freshMessages.length>0&&this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors,this.suppressNextErrorAnnouncement=!1}visibleErrors(){const visible=new Map;for(const key of Object.keys(this.schemaProperties)){const message=this.touchedFields.has(key)?this._errors[key]:void 0;message&&visible.set(key,message)}for(const key of this.missingRequiredKeys)this.touchedFields.has(key)&&visible.set(key,this.localize("toolParamMissingProperty",void 0,{key}));return this.showFormError&&this._formError&&visible.set("form",this._formError),visible}setFieldValue(key,val,committed=!1){if(this.effectiveDisabled)return;this.hasInteracted=!0,this.applyValue({...this.value,[key]:val});const detail={value:this.effectiveValue};emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),committed&&emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2))}markTouched(key){this.hasInteracted=!0,this.syncValidityCustomStates(),!this.touchedFields.has(key)&&(this.touchedFields=new Set(this.touchedFields).add(key))}onTextInput(key,e){e.stopPropagation(),this.setFieldValue(key,e.target.value)}onNumberInput(key,e){e.stopPropagation();const n=e.target.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation(),this.setFieldValue(key,e.target.value,!0)}onBooleanSelectChange(key,e){e.stopPropagation();const value=e.target.value;if(value===""){if(this.effectiveDisabled)return;if(this.hasInteracted=!0,this.schemaProperties[key]?.default!==void 0)this.applyValue({...this.value,[key]:void 0});else{const next={...this.value};Reflect.deleteProperty(next,key),this.applyValue(next)}const detail={value:this.effectiveValue};emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2));return}this.setFieldValue(key,value==="true",!0)}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){const choices=toolParamChoices(prop);if((prop.type==="string"||prop.type==="array")&&choices&&choices.length>0)return html`<lr-select
|
|
1
|
+
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{nextId}from"../../../internal/a11y.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import{EMPTY_SCHEMA,MAX_ENUM_OPTIONS,MAX_SCHEMA_FIELDS,snapshotFormValue,snapshotSchema}from"./tool-param-snapshot.js";import{toolParamChoices,toolParamConstraintFailure,validToolParamConstraints}from"./tool-param-constraints.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/input/number-input.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamBooleanFalse,LYRA_DEFAULT_toolParamBooleanTrue,LYRA_DEFAULT_toolParamBooleanUnset,LYRA_DEFAULT_toolParamFormat,LYRA_DEFAULT_toolParamInvalidConstraint,LYRA_DEFAULT_toolParamInvalidSelection,LYRA_DEFAULT_toolParamMaxItems,LYRA_DEFAULT_toolParamMaxLength,LYRA_DEFAULT_toolParamMaximum,LYRA_DEFAULT_toolParamMinItems,LYRA_DEFAULT_toolParamMinLength,LYRA_DEFAULT_toolParamMinimum,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_toolParamSchemaLimit,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LISTED_CHOICES=10;function sameErrors(left,right){const keys=Object.keys(left);return keys.length===Object.keys(right).length&&keys.every(key=>left[key]===right[key])}class LyraToolParamForm extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamBooleanFalse:LYRA_DEFAULT_toolParamBooleanFalse,toolParamBooleanTrue:LYRA_DEFAULT_toolParamBooleanTrue,toolParamBooleanUnset:LYRA_DEFAULT_toolParamBooleanUnset,toolParamFormat:LYRA_DEFAULT_toolParamFormat,toolParamInvalidConstraint:LYRA_DEFAULT_toolParamInvalidConstraint,toolParamInvalidSelection:LYRA_DEFAULT_toolParamInvalidSelection,toolParamMaxItems:LYRA_DEFAULT_toolParamMaxItems,toolParamMaxLength:LYRA_DEFAULT_toolParamMaxLength,toolParamMaximum:LYRA_DEFAULT_toolParamMaximum,toolParamMinItems:LYRA_DEFAULT_toolParamMinItems,toolParamMinLength:LYRA_DEFAULT_toolParamMinLength,toolParamMinimum:LYRA_DEFAULT_toolParamMinimum,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,toolParamSchemaLimit:LYRA_DEFAULT_toolParamSchemaLimit,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,styles]}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-validity-change","lr-input","lr-change"])}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},schema:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(){super(),this._errors=Object.create(null),this._formError="",this.showFormError=!1,this.touchedFields=new Set,this.baseId=nextId("tool-param-form"),this._fieldsetDisabled=!1,this._name="",this._schema=EMPTY_SCHEMA,this.schemaInputShapeError="",this.schemaInputExceededLimits=!1,this._value=Object.freeze({}),this.lastSchemaInput=EMPTY_SCHEMA,this.lastValueInput=this._value,this.valueInputInvalid=!1,this.valueInputTruncated=!1,this.defaultValueSnapshot=Object.freeze({}),this.defaultValueCaptured=!1,this._effectiveValue=Object.freeze({}),this._validityFlags={},this._disabled=!1,this.hasInteracted=!1,this.visibleErrorSnapshot=new Map,this.suppressNextErrorAnnouncement=!0,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.syncValidityCustomStates())},this.onValueCommit=event=>{event.stopPropagation(),this.effectiveDisabled||emitValueEvents(this,"change",{value:this.effectiveValue},detail=>this.emit("lr-change",detail))},this.stopNestedControlEvent=e=>{e.stopPropagation()},this.onFieldFocus=event=>{relayNativeEvent(this,event)},this.onFieldBlur=event=>{relayNativeEvent(this,event)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.syncFormState()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return;const[firstKey,...remainingKeys]=Object.keys(this._errors);if(firstKey===void 0)return;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]')),first=fields.find(candidate=>candidate.dataset.key===firstKey);if(first||remainingKeys.length===0)return first;const byKey=new Map;for(const field of fields){const key=field.dataset.key;key!==void 0&&!byKey.has(key)&&byKey.set(key,field)}for(const key of remainingKeys){const field=byKey.get(key);if(field)return field}}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&!!this._errors[key])}firstMissingPropertyError(){if(!this.renderRoot)return;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset.key===key);if(error)return error}}focusFirstControl(options){if(!this.renderRoot)return;const controls=this.renderRoot.querySelectorAll(`input.control, ${tag("select")}, ${tag("number-input")}`);for(const control of controls)if(!(control.disabled||control.getAttribute("aria-disabled")==="true")){control.focus(options);return}}click(){this.effectiveDisabled||this.focusFirstControl()}focus(options){this.effectiveDisabled||this.focusFirstControl(options)}blur(){const active=deepActiveElementIn(this.isConnected?this.shadowRoot:null);active&&typeof active.blur=="function"&&active.blur()}connectedCallback(){this.defaultValueCaptured||(this.defaultValueSnapshot=this._value,this.defaultValueCaptured=!0),super.connectedCallback(),this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})),this.hasUpdated&&(this.suppressNextErrorAnnouncement=!0,this.requestUpdate()),this.syncFormState()}disconnectedCallback(){super.disconnectedCallback(),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.suppressNextErrorAnnouncement=!0}get effectiveValue(){return this._effectiveValue}get schemaProperties(){return this._schema.properties}get requiredKeys(){return this._schema.required??Object.freeze([])}resolveEffectiveValue(){const props=this.schemaProperties,out={...this.value};for(const[key,prop]of Object.entries(props)){const fallback=prop.const!==void 0?prop.const:prop.default;!Object.prototype.hasOwnProperty.call(this.value,key)&&fallback!==void 0&&Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:fallback})}return snapshotFormValue(out).value}get schema(){return this._schema}set schema(next){if(next===this._schema||next===this.lastSchemaInput)return;this.lastSchemaInput=next;const old=this._schema,snapshot=snapshotSchema(next);this._schema=snapshot.schema,this.schemaInputShapeError=snapshot.shapeError,this.schemaInputExceededLimits=snapshot.exceededLimits,this.syncFormState(),this.requestUpdate("schema",old)}get value(){return this._value}set value(next){next===this._value||next===this.lastValueInput||(this.lastValueInput=next,this.applyValue(next))}applyValue(next){const old=this._value,snapshot=snapshotFormValue(next);this._value=snapshot.value,this.valueInputInvalid=snapshot.invalid,this.valueInputTruncated=snapshot.truncated,this.syncFormState(),this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.applyValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&(this.validityController.customValidityMessage||this._formError)&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}get formError(){return this._formError}selectionMessage(prop){const choices=prop.type==="string"?toolParamChoices(prop):void 0;return!choices||choices.length===0||choices.length>MAX_LISTED_CHOICES?this.localize("toolParamInvalidSelection"):this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(choices.map(choice=>choice.label))})}computeValidation(effective){const props=this.schemaProperties,required=new Set(this.requiredKeys),out=Object.create(null),flags={},addError=(key,message)=>{Object.defineProperty(out,key,{configurable:!0,enumerable:!0,writable:!0,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"&&type!=="array"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)})),flags.customError=!0;continue}if(!validToolParamConstraints(prop)){addError(key,this.localize("toolParamInvalidConstraint")),flags.customError=!0;continue}if(!(Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0)){required.has(key)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);continue}const v=effective[key];if(type==="string"&&typeof v!="string"){addError(key,this.localize("fieldMustBeString")),flags.typeMismatch=!0;continue}if(type==="number"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber")),flags.typeMismatch=!0;continue}if(type==="integer"&&(typeof v!="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger")),flags.typeMismatch=!0;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger")),flags.stepMismatch=!0;continue}if(type==="boolean"&&typeof v!="boolean"){addError(key,this.localize("fieldMustBeBoolean")),flags.typeMismatch=!0;continue}const constraint=toolParamConstraintFailure(prop,v);if(constraint){const number=getNumberFormat(this.effectiveLocale),message=constraint==="minLength"?this.localize("toolParamMinLength",void 0,{count:number.format(prop.minLength)}):constraint==="maxLength"?this.localize("toolParamMaxLength",void 0,{count:number.format(prop.maxLength)}):constraint==="minimum"?this.localize("toolParamMinimum",void 0,{value:number.format(prop.minimum)}):constraint==="maximum"?this.localize("toolParamMaximum",void 0,{value:number.format(prop.maximum)}):constraint==="minItems"?this.localize("toolParamMinItems",void 0,{count:number.format(prop.minItems)}):constraint==="maxItems"?this.localize("toolParamMaxItems",void 0,{count:number.format(prop.maxItems)}):constraint==="format"?this.localize("toolParamFormat",void 0,{format:prop.format}):this.selectionMessage(prop);addError(key,message),flags.customError=!0;continue}prop.const!==void 0&&v!==prop.const&&(addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)})),flags.customError=!0)}for(const key of required)Object.prototype.hasOwnProperty.call(props,key)||(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0)&&(addError(key,this.localize("fieldRequired")),flags.valueMissing=!0);return{errors:out,flags}}checkValidity(){return this.validityController.checkValidity(()=>this.syncFormState())}reportValidity(){this.validityController.syncConstraints(),this.hasInteracted=!0,this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])),this._formError&&(this.showFormError=!0),this.requestUpdate();const valid=this.internals.reportValidity();return!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0&&this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor(),error?.focus()}),valid}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncValidityCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.hasInteracted=!1,this.applyValue(this.defaultValueSnapshot),this.touchedFields=new Set,this.showFormError=!1}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.applyValue(restored)}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.applyValidity(),this.requestUpdate())}schemaShapeError(){return this.schemaInputShapeError==="object"?this.localize("schemaMustBeObject"):this.schemaInputShapeError==="properties"?this.localize("schemaPropertiesMustBeFlat"):this.schemaInputExceededLimits?this.localize("toolParamSchemaLimit",void 0,{fields:getNumberFormat(this.effectiveLocale).format(MAX_SCHEMA_FIELDS),options:getNumberFormat(this.effectiveLocale).format(MAX_ENUM_OPTIONS)}):""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value=="number"&&!Number.isFinite(value))throw new TypeError("Non-finite numbers are not JSON values.");return value});if(typeof serialized!="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue),this.applyValidity()}applyValidity(){if(this.validityController){if(this.barredFromValidation||Object.keys(this._validityFlags).length===0)this.validityController.setValidity({});else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates(),this.publishValiditySnapshot()}}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective=Object.freeze({}),errors={},flags={},formError="",formValue=null;try{if(formError=this.schemaShapeError(),this.valueInputInvalid||this.valueInputTruncated)throw new TypeError("The value could not be retained within the public snapshot boundary.");effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors,flags=validation.flags,formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable"),formValue=null}formError&&(flags.customError=!0,formValue=null),this._effectiveValue=effective,sameErrors(this._errors,errors)||(this._errors=errors),this._formError=formError,this._validityFlags=flags,this.syncInternals(formValue)}updated(changed){if(super.updated(changed),this.publishValiditySnapshot(),changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]=="function").map(element=>element.updateComplete).filter(update=>update!==void 0);nestedUpdates.length>0&&Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}const currentErrors=this.visibleErrors();if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors)this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)&&freshMessages.push(text);freshMessages.length>0&&this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors,this.suppressNextErrorAnnouncement=!1}visibleErrors(){const visible=new Map;for(const key of Object.keys(this.schemaProperties)){const message=this.touchedFields.has(key)?this._errors[key]:void 0;message&&visible.set(key,message)}for(const key of this.missingRequiredKeys)this.touchedFields.has(key)&&visible.set(key,this.localize("toolParamMissingProperty",void 0,{key}));return this.showFormError&&this._formError&&visible.set("form",this._formError),visible}setFieldValue(key,val,committed=!1){if(this.effectiveDisabled)return;this.hasInteracted=!0,this.applyValue({...this.value,[key]:val});const detail={value:this.effectiveValue};emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),committed&&emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2))}markTouched(key){this.hasInteracted=!0,this.syncValidityCustomStates(),!this.touchedFields.has(key)&&(this.touchedFields=new Set(this.touchedFields).add(key))}onTextInput(key,e){e.stopPropagation(),this.setFieldValue(key,e.target.value)}onNumberInput(key,e){e.stopPropagation();const n=e.target.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation(),this.setFieldValue(key,e.target.value,!0)}onBooleanSelectChange(key,e){e.stopPropagation();const value=e.target.value;if(value===""){if(this.effectiveDisabled)return;if(this.hasInteracted=!0,this.schemaProperties[key]?.default!==void 0)this.applyValue({...this.value,[key]:void 0});else{const next={...this.value};Reflect.deleteProperty(next,key),this.applyValue(next)}const detail={value:this.effectiveValue};emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2));return}this.setFieldValue(key,value==="true",!0)}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){const choices=toolParamChoices(prop);if((prop.type==="string"||prop.type==="array")&&choices&&choices.length>0)return html`<lr-select
|
|
2
2
|
id=${fieldId}
|
|
3
3
|
.label=${label}
|
|
4
4
|
.hint=${prop.description??""}
|
|
@@ -80,7 +80,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
|
|
|
80
80
|
<lr-option value="">${this.localize("toolParamBooleanUnset")}</lr-option>
|
|
81
81
|
<lr-option value="true">${this.localize("toolParamBooleanTrue")}</lr-option>
|
|
82
82
|
<lr-option value="false">${this.localize("toolParamBooleanFalse")}</lr-option>
|
|
83
|
-
</lr-select>`}return html`<p part="unsupported" class="unsupported" id=${fieldId}>${this.localize("unsupportedFieldType",void 0,{type:String(prop.type)})}</p>`}renderField(key,prop,index){const
|
|
83
|
+
</lr-select>`}return html`<p part="unsupported" class="unsupported" id=${fieldId}>${this.localize("unsupportedFieldType",void 0,{type:String(prop.type)})}</p>`}renderField(key,prop,index,required){const label=prop.title??key,fieldId=`${this.baseId}-f${index}`,descId=prop.description?`${fieldId}-desc`:"",fieldError=this._errors[key],errId=fieldError?`${fieldId}-err`:"",describedBy=[descId,this.touchedFields.has(key)?errId:""].filter(Boolean).join(" "),hasError=this.touchedFields.has(key)&&!!fieldError,errorMessage=hasError?fieldError??"":"",effective=this._effectiveValue[key],isBoolean=prop.type==="boolean",isComposedSelect=(prop.type==="string"||prop.type==="array")&&!!toolParamChoices(prop)?.length,isComposedNumber=prop.type==="number"||prop.type==="integer",ownsChrome=!isBoolean&&!isComposedSelect&&!isComposedNumber;return html`
|
|
84
84
|
<div part="field" class="field" data-key=${key} data-type=${prop.type} ?data-required=${required}
|
|
85
85
|
@focusout=${()=>this.markTouched(key)}
|
|
86
86
|
>
|
|
@@ -89,13 +89,13 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
|
|
|
89
89
|
${prop.description&&ownsChrome?html`<p part="description" id=${descId}>${prop.description}</p>`:nothing}
|
|
90
90
|
${hasError&&ownsChrome?html`<p part="error" id=${errId}>${fieldError}</p>`:nothing}
|
|
91
91
|
</div>
|
|
92
|
-
`}render(){const props=this.schemaProperties,entries=Object.entries(props),missingRequiredKeys=this.missingRequiredKeys.filter(key=>this.touchedFields.has(key)),hostLabel=this.getAttribute("aria-label"),groupInvalid=this.hasInteracted&&!this.barredFromValidation&&!this.internals.validity.valid;return html`<div
|
|
92
|
+
`}render(){const props=this.schemaProperties,entries=Object.entries(props),required=entries.length>1?new Set(this.requiredKeys):void 0,missingRequiredKeys=this.missingRequiredKeys.filter(key=>this.touchedFields.has(key)),hostLabel=this.getAttribute("aria-label"),groupInvalid=this.hasInteracted&&!this.barredFromValidation&&!this.internals.validity.valid;return html`<div
|
|
93
93
|
part="base"
|
|
94
94
|
role="group"
|
|
95
95
|
aria-label=${hostLabel??nothing}
|
|
96
96
|
aria-invalid=${groupInvalid?"true":"false"}
|
|
97
97
|
>
|
|
98
|
-
${entries.length===0?html`<p part="empty">${this.localize("noData")}</p>`:entries.map(([key,prop],i)=>this.renderField(key,prop,i))}
|
|
98
|
+
${entries.length===0?html`<p part="empty">${this.localize("noData")}</p>`:entries.map(([key,prop],i)=>this.renderField(key,prop,i,required?required.has(key):this.requiredKeys.includes(key)))}
|
|
99
99
|
${missingRequiredKeys.map(key=>html`<p
|
|
100
100
|
part="error"
|
|
101
101
|
class="form-error missing-property-error"
|
|
@@ -62,7 +62,9 @@ export interface LyraBoxPlotPointDetail{datasetIndex:number;index:number;label:s
|
|
|
62
62
|
* @cssprop [--lr-box-plot-fill-color-8=var(--lr-color-chart-8)] - Eighth series box-fill and
|
|
63
63
|
* legend-swatch color.
|
|
64
64
|
* @csspart error - Static visible error shown instead of the canvas when the optional box-plot
|
|
65
|
-
* peer fails to load
|
|
65
|
+
* peer fails to load or the canvas context is unavailable. Canvas failure keeps the data table
|
|
66
|
+
* visible and retries on data updates or `refreshTheme()`; its transition is announced through
|
|
67
|
+
* a shared light-DOM alert.
|
|
66
68
|
* @csspart data-truncation - Explanation shown when the generated accessible alternative samples
|
|
67
69
|
* more than 1,000 records.
|
|
68
70
|
* @event lr-legend-visibility-change-request - Cancelable proposed DOM legend visibility change.
|
|
@@ -147,8 +149,8 @@ dataTableToggle:boolean;private dataTableExpandedOverride;private readonly dataT
|
|
|
147
149
|
valueFormatter?:LyraChartValueFormatter;
|
|
148
150
|
/** Unified context-object formatter shared with the other chart surfaces. The tooltip lists all
|
|
149
151
|
* five statistics, each formatted with its own `statistic`. */
|
|
150
|
-
formatter?:LyraChartFormatter;private loading;private loadFailed;private visible;private keyboardDatumIndex;private keyboardDatumAnnouncement;private intersectionObserver?;private intersectionGeneration;private readonly reducedMotionWatch;private canvasEl?;private chart?;private stopAnnotationRegistrationWatch?;private chartJsModule?;private loadGeneration;private descriptionId;private lastDrawnDirection?;private lastDrawnLocale?;private readonly announcements;private lastDataTruncationAnnouncement;private isMounting;connectedCallback():void;private onBoxPlotPluginLoaded;disconnectedCallback():void;adoptedCallback():void;private armReducedMotionWatcher;private disarmReducedMotionWatcher;private get ownerWindow();private effectiveHiddenDatasetIndexes;private applyDatasetVisibility;protected updated(changed:PropertyValues):void;private themeColors;private seriesColor;private seriesBorderColor;private seriesFillColor;private forcedColorFill;private styleColor;private styleNumber;private readonly tooltipIsolationPlugin;private buildConfig;private draw;private drawIfVisible;private rebuildAfterAnnotationRegistration;
|
|
152
|
+
formatter?:LyraChartFormatter;private loading;private loadFailed;private canvasUnavailable;private visible;private keyboardDatumIndex;private keyboardDatumAnnouncement;private intersectionObserver?;private intersectionGeneration;private readonly reducedMotionWatch;private canvasEl?;private chart?;private stopAnnotationRegistrationWatch?;private chartJsModule?;private loadGeneration;private descriptionId;private lastDrawnDirection?;private lastDrawnLocale?;private readonly announcements;private lastDataTruncationAnnouncement;private isMounting;connectedCallback():void;private onBoxPlotPluginLoaded;disconnectedCallback():void;adoptedCallback():void;private armReducedMotionWatcher;private disarmReducedMotionWatcher;private get ownerWindow();private effectiveHiddenDatasetIndexes;private applyDatasetVisibility;protected updated(changed:PropertyValues):void;private themeColors;private seriesColor;private seriesBorderColor;private seriesFillColor;private forcedColorFill;private styleColor;private styleNumber;private readonly tooltipIsolationPlugin;private buildConfig;private draw;private setCanvasUnavailable;private drawIfVisible;private rebuildAfterAnnotationRegistration;
|
|
151
153
|
/** Re-reads canvas theme custom properties after an out-of-band ancestor theme change. */
|
|
152
154
|
refreshTheme():void;private seriesDisplayLabel;private formatValue;
|
|
153
155
|
/** Returns a spreadsheet-safe CSV snapshot or the current canvas PNG data URL. */
|
|
154
|
-
exportData(format:'csv'|'png'):string;private boxPlotDescription;private boxDatums;private boxStatistics;private boxAnnouncement;private activateBox;private handlePointClick;private showKeyboardBox;private keyboardBoxShown;private readonly onCanvasBlur;private onCanvasFocus;private onCanvasKeyDown;private validPoint;private accessibleName;private dataTableSample;private generatedDataIsSampled;private dataTruncationMessage;private renderDataTable;private hasCustomDataTable;private toggleDataset;private renderLegend;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-box-plot':LyraBoxPlot;}}
|
|
156
|
+
exportData(format:'csv'|'png'):string;private boxPlotDescription;private boxDatums;private boxStatistics;private boxAnnouncement;private activateBox;private handlePointClick;private showKeyboardBox;private keyboardBoxShown;private readonly onCanvasBlur;private onCanvasFocus;private onCanvasKeyDown;private validPoint;private accessibleName;private dataTableSample;private generatedDataIsSampled;private dataTruncationMessage;private dataTableRows?;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;private renderDataTableRows;private renderDataTable;private hasCustomDataTable;private toggleDataset;private renderLegend;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-box-plot':LyraBoxPlot;}}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){if(super.updated(changed),!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){return!this.ownerWindow||!forcedColorsActive(this.ownerWindow)?background:createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG))}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}this.chart=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate()}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??formatChartValue(value,this.effectiveLocale)}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
|
|
2
|
-
`)}boxPlotDescription(){if(this.description)return this.description;const summaries=this.dataTableSample().seriesIndexes.map(index=>{const series=this.datasets[index];let count=0,first=0,last=0,min=0,minIndex=0,max=0,maxIndex=0;for(const[pointIndex,point]of series.data.entries())this.validPoint(point)&&(count===0&&(first=point.median,min=point.median,minIndex=pointIndex,max=point.median,maxIndex=pointIndex),last=point.median,point.median<min&&(min=point.median,minIndex=pointIndex),point.median>max&&(max=point.median,maxIndex=pointIndex),count++);if(count===0)return this.localize("chartSeriesNoData",void 0,{label:this.seriesDisplayLabel(series)});const trend=last>first?this.localize("chartTrendIncreasing"):last<first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat");return this.localize("boxPlotSeriesSummary",void 0,{label:this.seriesDisplayLabel(series),count:getNumberFormat(this.effectiveLocale).format(count),min:this.formatValue(min,"spoken",{datasetIndex:index,index:minIndex,label:this.labels[minIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),max:this.formatValue(max,"spoken",{datasetIndex:index,index:maxIndex,label:this.labels[maxIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),trend})});return summaries.length?this.localize("boxPlotSummaryWithData",void 0,{summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("boxPlotSummaryEmpty")}boxDatums(){const sample=this.dataTableSample(),datums=[];for(const datasetIndex of sample.seriesIndexes){const series=this.datasets[datasetIndex];if(series)for(const index of sample.rowIndexes){const point=series.data[index];this.validPoint(point)&&datums.push({datasetIndex,index,label:this.labels[index]||void 0,value:summaryOf(point)})}}return datums}boxStatistics(point){return[["min",this.localize("boxPlotMin"),point.min],["q1",this.localize("boxPlotQ1"),point.q1],["median",this.localize("boxPlotMedian"),point.median],["q3",this.localize("boxPlotQ3"),point.q3],["max",this.localize("boxPlotMax"),point.max]]}boxAnnouncement(datum,position,total){const numberFormat=getNumberFormat(this.effectiveLocale),point=datum.value,summary=(point?this.boxStatistics(point):[]).filter(([,,value])=>Number.isFinite(value)).map(([statistic,label,value])=>this.localize("chartValueLabel",void 0,{label,value:this.formatValue(value,"spoken",{datasetIndex:datum.datasetIndex,index:datum.index,label:datum.label,seriesLabel:this.datasets[datum.datasetIndex]?.label,statistic,axis:"y"})})).join(this.localize("chartSummarySeparator"));return this.localize("liteChartMarkSummary",void 0,{series:this.datasets[datum.datasetIndex]?.label||this.localize("chartSeriesLabel"),label:datum.label??this.localize("chartPointLabel",void 0,{n:numberFormat.format(datum.index+1)}),value:summary,index:numberFormat.format(position+1),total:numberFormat.format(total)})}activateBox(datum){const datums=this.boxDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.boxAnnouncement(datum,position,datums.length)),this.emit("lr-datum-activate",{...datum,kind:"box"}),this.emit("lr-point-activate",{...datum})}handlePointClick(event,chart){const hit=chart.getElementsAtEventForMode?.(event,"nearest",{intersect:!0},!0)?.[0];if(!hit)return;const sample=this.dataTableSample(),datasetIndex=sample.seriesIndexes[hit.datasetIndex],index=sample.rowIndexes[hit.index];if(datasetIndex===void 0||index===void 0)return;const point=this.datasets[datasetIndex]?.data[index];this.activateBox({datasetIndex,index,label:this.labels[index]||void 0,value:this.validPoint(point)?summaryOf(point):null})}showKeyboardBox(datum){if(!this.chart||!datum&&!this.keyboardBoxShown)return;const sample=this.dataTableSample();this.keyboardBoxShown=showChartActiveDatum(this.chart,datum&&{datasetIndex:sample.seriesIndexes.indexOf(datum.datasetIndex),index:sample.rowIndexes.indexOf(datum.index)})}onCanvasFocus(event){const datums=this.boxDatums();datums.length&&(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),isKeyboardFocusEvent(event)&&this.showKeyboardBox(datums[this.keyboardDatumIndex]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[this.keyboardDatumIndex],this.keyboardDatumIndex,datums.length))}onCanvasKeyDown(event){const datums=this.boxDatums();if(!datums.length)return;if(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),event.key==="Enter"||event.key===" "){event.preventDefault(),this.activateBox(datums[this.keyboardDatumIndex]);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=this.keyboardDatumIndex;if(event.key===forward||event.key==="ArrowDown")next=Math.min(datums.length-1,next+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,next-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=datums.length-1;else return;event.preventDefault(),this.keyboardDatumIndex=next,this.showKeyboardBox(datums[next]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[next],next,datums.length)}validPoint(point){return!!point&&[point.min,point.q1,point.median,point.q3,point.max].every(Number.isFinite)&&point.min<=point.q1&&point.q1<=point.median&&point.median<=point.q3&&point.q3<=point.max}accessibleName(fallback){return this.getAttribute("aria-label")??this.label??fallback}dataTableSample(){let rowCount=this.labels.length;for(const series of this.datasets)rowCount=Math.max(rowCount,series.data.length);const indexes=sampleChartTableIndexes(rowCount,this.datasets.length);return{rowCount,seriesCount:this.datasets.length,...indexes}}generatedDataIsSampled(){const sample=this.dataTableSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){if(super.updated(changed),!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){return!this.ownerWindow||!forcedColorsActive(this.ownerWindow)?background:createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG))}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate()}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??formatChartValue(value,this.effectiveLocale)}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
|
|
2
|
+
`)}boxPlotDescription(){if(this.description)return this.description;const summaries=this.dataTableSample().seriesIndexes.map(index=>{const series=this.datasets[index];let count=0,first=0,last=0,min=0,minIndex=0,max=0,maxIndex=0;for(const[pointIndex,point]of series.data.entries())this.validPoint(point)&&(count===0&&(first=point.median,min=point.median,minIndex=pointIndex,max=point.median,maxIndex=pointIndex),last=point.median,point.median<min&&(min=point.median,minIndex=pointIndex),point.median>max&&(max=point.median,maxIndex=pointIndex),count++);if(count===0)return this.localize("chartSeriesNoData",void 0,{label:this.seriesDisplayLabel(series)});const trend=last>first?this.localize("chartTrendIncreasing"):last<first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat");return this.localize("boxPlotSeriesSummary",void 0,{label:this.seriesDisplayLabel(series),count:getNumberFormat(this.effectiveLocale).format(count),min:this.formatValue(min,"spoken",{datasetIndex:index,index:minIndex,label:this.labels[minIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),max:this.formatValue(max,"spoken",{datasetIndex:index,index:maxIndex,label:this.labels[maxIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),trend})});return summaries.length?this.localize("boxPlotSummaryWithData",void 0,{summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("boxPlotSummaryEmpty")}boxDatums(){const sample=this.dataTableSample(),datums=[];for(const datasetIndex of sample.seriesIndexes){const series=this.datasets[datasetIndex];if(series)for(const index of sample.rowIndexes){const point=series.data[index];this.validPoint(point)&&datums.push({datasetIndex,index,label:this.labels[index]||void 0,value:summaryOf(point)})}}return datums}boxStatistics(point){return[["min",this.localize("boxPlotMin"),point.min],["q1",this.localize("boxPlotQ1"),point.q1],["median",this.localize("boxPlotMedian"),point.median],["q3",this.localize("boxPlotQ3"),point.q3],["max",this.localize("boxPlotMax"),point.max]]}boxAnnouncement(datum,position,total){const numberFormat=getNumberFormat(this.effectiveLocale),point=datum.value,summary=(point?this.boxStatistics(point):[]).filter(([,,value])=>Number.isFinite(value)).map(([statistic,label,value])=>this.localize("chartValueLabel",void 0,{label,value:this.formatValue(value,"spoken",{datasetIndex:datum.datasetIndex,index:datum.index,label:datum.label,seriesLabel:this.datasets[datum.datasetIndex]?.label,statistic,axis:"y"})})).join(this.localize("chartSummarySeparator"));return this.localize("liteChartMarkSummary",void 0,{series:this.datasets[datum.datasetIndex]?.label||this.localize("chartSeriesLabel"),label:datum.label??this.localize("chartPointLabel",void 0,{n:numberFormat.format(datum.index+1)}),value:summary,index:numberFormat.format(position+1),total:numberFormat.format(total)})}activateBox(datum){const datums=this.boxDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.boxAnnouncement(datum,position,datums.length)),this.emit("lr-datum-activate",{...datum,kind:"box"}),this.emit("lr-point-activate",{...datum})}handlePointClick(event,chart){const hit=chart.getElementsAtEventForMode?.(event,"nearest",{intersect:!0},!0)?.[0];if(!hit)return;const sample=this.dataTableSample(),datasetIndex=sample.seriesIndexes[hit.datasetIndex],index=sample.rowIndexes[hit.index];if(datasetIndex===void 0||index===void 0)return;const point=this.datasets[datasetIndex]?.data[index];this.activateBox({datasetIndex,index,label:this.labels[index]||void 0,value:this.validPoint(point)?summaryOf(point):null})}showKeyboardBox(datum){if(!this.chart||!datum&&!this.keyboardBoxShown)return;const sample=this.dataTableSample();this.keyboardBoxShown=showChartActiveDatum(this.chart,datum&&{datasetIndex:sample.seriesIndexes.indexOf(datum.datasetIndex),index:sample.rowIndexes.indexOf(datum.index)})}onCanvasFocus(event){const datums=this.boxDatums();datums.length&&(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),isKeyboardFocusEvent(event)&&this.showKeyboardBox(datums[this.keyboardDatumIndex]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[this.keyboardDatumIndex],this.keyboardDatumIndex,datums.length))}onCanvasKeyDown(event){const datums=this.boxDatums();if(!datums.length)return;if(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),event.key==="Enter"||event.key===" "){event.preventDefault(),this.activateBox(datums[this.keyboardDatumIndex]);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=this.keyboardDatumIndex;if(event.key===forward||event.key==="ArrowDown")next=Math.min(datums.length-1,next+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,next-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=datums.length-1;else return;event.preventDefault(),this.keyboardDatumIndex=next,this.showKeyboardBox(datums[next]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[next],next,datums.length)}validPoint(point){return!!point&&[point.min,point.q1,point.median,point.q3,point.max].every(Number.isFinite)&&point.min<=point.q1&&point.q1<=point.median&&point.median<=point.q3&&point.q3<=point.max}accessibleName(fallback){return this.getAttribute("aria-label")??this.label??fallback}dataTableSample(){let rowCount=this.labels.length;for(const series of this.datasets)rowCount=Math.max(rowCount,series.data.length);const indexes=sampleChartTableIndexes(rowCount,this.datasets.length);return{rowCount,seriesCount:this.datasets.length,...indexes}}generatedDataIsSampled(){const sample=this.dataTableSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}requestUpdate(...args){args[0]!=="keyboardDatumAnnouncement"&&(this.dataTableRows=void 0),super.requestUpdate(...args)}renderDataTableRows(){if(this.dataTableRows)return this.dataTableRows;const numberFormat=getNumberFormat(this.effectiveLocale),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",sample=this.dataTableSample();return this.dataTableRows=sample.seriesIndexes.flatMap(seriesIndex=>{const series=this.datasets[seriesIndex];return sample.rowIndexes.map(index=>{const point=series.data[index],metadata={datasetIndex:seriesIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};return this.validPoint(point)?html`
|
|
3
|
+
<tr>
|
|
4
|
+
<th scope="row">${isolateHtml(this.labels[index]||this.localize("chartPointLabel",void 0,{n:numberFormat.format(index+1)}),direction)}</th>
|
|
5
|
+
<td>${isolateHtml(this.seriesDisplayLabel(series),direction)}</td>
|
|
6
|
+
<td>${isolateHtml(this.formatValue(point.min,"table",{...metadata,statistic:"min"}),direction)}</td>
|
|
7
|
+
<td>${isolateHtml(this.formatValue(point.q1,"table",{...metadata,statistic:"q1"}),direction)}</td>
|
|
8
|
+
<td>${isolateHtml(this.formatValue(point.median,"table",{...metadata,statistic:"median"}),direction)}</td>
|
|
9
|
+
<td>${isolateHtml(this.formatValue(point.q3,"table",{...metadata,statistic:"q3"}),direction)}</td>
|
|
10
|
+
<td>${isolateHtml(this.formatValue(point.max,"table",{...metadata,statistic:"max"}),direction)}</td>
|
|
11
|
+
</tr>
|
|
12
|
+
`:nothing})})}renderDataTable(){return html`
|
|
3
13
|
<table class=${this.dataTableVisible?"":"sr-only"}>
|
|
4
14
|
<caption>${this.accessibleName(this.localize("boxPlotData"))}</caption>
|
|
5
15
|
<thead>
|
|
@@ -14,17 +24,7 @@ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}
|
|
|
14
24
|
</tr>
|
|
15
25
|
</thead>
|
|
16
26
|
<tbody>
|
|
17
|
-
${
|
|
18
|
-
<tr>
|
|
19
|
-
<th scope="row">${isolateHtml(this.labels[index]||this.localize("chartPointLabel",void 0,{n:numberFormat.format(index+1)}),direction)}</th>
|
|
20
|
-
<td>${isolateHtml(this.seriesDisplayLabel(series),direction)}</td>
|
|
21
|
-
<td>${isolateHtml(this.formatValue(point.min,"table",{...metadata,statistic:"min"}),direction)}</td>
|
|
22
|
-
<td>${isolateHtml(this.formatValue(point.q1,"table",{...metadata,statistic:"q1"}),direction)}</td>
|
|
23
|
-
<td>${isolateHtml(this.formatValue(point.median,"table",{...metadata,statistic:"median"}),direction)}</td>
|
|
24
|
-
<td>${isolateHtml(this.formatValue(point.q3,"table",{...metadata,statistic:"q3"}),direction)}</td>
|
|
25
|
-
<td>${isolateHtml(this.formatValue(point.max,"table",{...metadata,statistic:"max"}),direction)}</td>
|
|
26
|
-
</tr>
|
|
27
|
-
`:nothing})})}
|
|
27
|
+
${this.renderDataTableRows()}
|
|
28
28
|
</tbody>
|
|
29
29
|
</table>
|
|
30
30
|
`}hasCustomDataTable(){return hasSlottedChartDataTable(this)}toggleDataset(index){if(!this.chart||index<0||index>=this.datasets.length)return;const hidden=this.effectiveHiddenDatasetIndexes(),wasHidden=hidden.includes(index),nextHidden=wasHidden?hidden.filter(candidate=>candidate!==index):[...hidden,index].sort((left,right)=>left-right),visible=wasHidden;this.emit("lr-legend-visibility-change-request",legendVisibilityDetail(index,visible,nextHidden),{cancelable:!0}).defaultPrevented||(this.hiddenDatasets=nextHidden,this.applyDatasetVisibility(),this.chart.update("none"),this.requestUpdate(),this.emit("lr-legend-visibility-change",legendVisibilityDetail(index,visible,nextHidden)))}renderLegend(){if(!this.withLegend)return nothing;const palette=this.canvasTokens.palette(),forced=forcedColorsActive(this.ownerWindow),controlledHidden=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length),controlledHiddenSet=controlledHidden===void 0?void 0:new Set(controlledHidden),sample=this.dataTableSample();return html`
|
|
@@ -59,7 +59,8 @@ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}
|
|
|
59
59
|
part="base"
|
|
60
60
|
data-legend-position=${this.withLegend?chartChromeLegendPlacement(this.legendPosition):nothing}
|
|
61
61
|
>
|
|
62
|
-
|
|
62
|
+
${this.canvasUnavailable?html`<div part="error">${this.localize("chartRenderUnavailable")}</div>`:nothing}
|
|
63
|
+
<div part="plot" ?hidden=${this.canvasUnavailable}>
|
|
63
64
|
<canvas
|
|
64
65
|
part="canvas"
|
|
65
66
|
role="application"
|
|
@@ -72,11 +73,11 @@ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}
|
|
|
72
73
|
@keydown=${this.onCanvasKeyDown}
|
|
73
74
|
></canvas>
|
|
74
75
|
</div>
|
|
75
|
-
${this.renderLegend()}
|
|
76
|
+
${this.canvasUnavailable?nothing:this.renderLegend()}
|
|
76
77
|
<p part="description" id=${this.descriptionId} class="sr-only">${description}</p>
|
|
77
78
|
<p class="sr-only" aria-hidden="true">${this.keyboardDatumAnnouncement}</p>
|
|
78
79
|
${this.dataTruncationMessage()?html`<p part="data-truncation">${this.dataTruncationMessage()}</p>`:nothing}
|
|
79
|
-
${this.dataTableToggle?html`<button
|
|
80
|
+
${this.dataTableToggle&&!this.canvasUnavailable?html`<button
|
|
80
81
|
part="data-table-toggle"
|
|
81
82
|
type="button"
|
|
82
83
|
aria-expanded=${this.dataTableVisible?"true":"false"}
|
|
@@ -88,7 +89,7 @@ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}
|
|
|
88
89
|
<div
|
|
89
90
|
id=${this.dataTableId}
|
|
90
91
|
part="data-table"
|
|
91
|
-
?data-visually-hidden=${!this.dataTableVisible}
|
|
92
|
+
?data-visually-hidden=${!this.dataTableVisible&&!this.canvasUnavailable}
|
|
92
93
|
>
|
|
93
94
|
<slot name="data-table" @slotchange=${()=>this.requestUpdate()}></slot>
|
|
94
95
|
${hasCustomDataTable?nothing:this.renderDataTable()}
|