@aceshooting/lyra-ui 28.1.0 → 28.1.2
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 +65 -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/span-waterfall/span-waterfall.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 +2 -2
- package/dist/components/charts/chart/box-plot.class.js +14 -14
- package/dist/components/charts/chart/chart.class.d.ts +2 -2
- package/dist/components/charts/chart/chart.class.js +14 -14
- 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/push-to-talk/push-to-talk.class.d.ts +2 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- 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/flow-canvas/flow-canvas.class.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 +2 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- 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/textarea/textarea.class.js +1 -1
- 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/details/accordion.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +3 -3
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- 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.d.ts +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/widget/widget.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/image-viewer/image-viewer.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.js +1 -1
- package/dist/components/overlays/overlay/popover.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/graph.class.d.ts +1 -1
- package/dist/components/retrieval/graph/graph.class.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/utility/tour/tour.class.js +4 -4
- 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/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/native-modal-carrier.js +2 -2
- 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/llms/components/lr-color-picker.md +2 -0
- package/llms/components/lr-commit-card.md +3 -2
- package/llms/components/lr-push-to-talk.md +3 -0
- 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.md +44 -0
- package/package.json +5 -5
- package/registrations.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,70 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 28.1.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- The release version stamp changes compressed bundle measurements by 1–3 bytes. Two direct-entry and five initial-marginal ceilings advance to those exact measurements without added allowance; bundle inputs and all passing ceilings remain unchanged.
|
|
8
|
+
|
|
9
|
+
- ea2a845: Avoid a redundant Chart.js update after accepted dataset legend actions in charts and box plots. Visibility still updates synchronously before the committed event; coalesced data changes, controlled resets, inherited context, accessible tables, and synchronization continue to reconcile normally.
|
|
10
|
+
|
|
11
|
+
Six aggregate bundle ceilings increase by 69–359 gzip bytes to their exact measured sizes, with no added headroom, for the peer and visibility checks that prevent duplicate updates. Individual-component and initial-route ceilings remain unchanged.
|
|
12
|
+
- 4ceefc4: Keep slotted accessible names current when responsive panels and widgets move between connected documents, and restore inherited locale updates for responsive panels. Owner-realm subscriptions now finish teardown before overlay teardown, allowing the connected destination to bind its own observations.
|
|
13
|
+
|
|
14
|
+
The connection cleanup ordering adds 28–33 gzip bytes to five aggregate entry bundles and 3 bytes to the component percentile. Their reviewed ceilings advance to those exact measurements without extra allowance; other bundle ceilings and measurement options are unchanged.
|
|
15
|
+
- 7a119cc: Keep textarea auto sizing, page allocation frames, and initial menu, popover, dropdown, and accordion ownership inactive while disconnected. Restore current content and geometry on reconnect, and ignore callbacks retired by reconnection or document adoption.
|
|
16
|
+
|
|
17
|
+
The lifecycle guards add 81 gzip bytes to the complete registration bundle and 30 bytes to the menu's initial route. Only breached bundle ceilings advance to their exact measured sizes, with no added allowance.
|
|
18
|
+
- b3cc650: Keep heatmap PNG export empty while detached, including when a pending update flushes after removal, and repaint current data on reconnect. Defer graph simulation and force updates until reconnect, then rebind the current renderer and its interaction targets. Six aggregate bundle ceilings rise only to their measured gzip bytes for these lifecycle guards; component, CSS, and initial-route ceilings remain unchanged.
|
|
19
|
+
- 829c00d: Keep image-viewer geometry observers, span-waterfall axis observers, and flow-canvas companion notifications inactive while detached, including pending updates that finish after removal. Restore current geometry and companion snapshots on reconnect, and ignore stale callbacks from a previous document or observation. Eight aggregate bundle ceilings increase only to the measured gzip bytes required by these lifecycle guards, without added headroom; passing component, CSS, and initial-route ceilings remain unchanged.
|
|
20
|
+
- e607435: Avoid development warnings for the standard `form` owner attribute on form-associated custom elements.
|
|
21
|
+
- bfd071f: Keep push-to-talk recording active when its optional audio-level analysis cannot initialize, including when level events are enabled during capture. Close partially initialized audio contexts without reporting a recorder failure or rejecting the component update; microphone capture and normal stop behavior remain available.
|
|
22
|
+
|
|
23
|
+
The optional-analysis guard adds 7–10 gzip bytes to five complete or conversation entry bundles. Their previously exact ceilings advance only to the reviewed measurements, with no extra allowance; passing ceilings and optional-peer exclusions remain unchanged.
|
|
24
|
+
- e449f0b: Restore the tour backdrop and spotlight cutout by rendering their shapes in the SVG namespace. Keep the spotlight aligned when its target resizes, and fill the backdrop when the target is missing.
|
|
25
|
+
|
|
26
|
+
Reuse one scrim, formatted progress text and scoped geometry lookups to reduce repeated rendering work. The corrected SVG rendering requires three additional gzip bytes in the complete registration bundle and four in the tour initial marginal bundle after these reductions. Their reviewed ceilings advance to exactly 1,269,107 and 18,769 bytes, with no additional allowance; other budgets and measurement inputs are unchanged.
|
|
27
|
+
- @aceshooting/lyra-translations@28.1.2
|
|
28
|
+
|
|
29
|
+
## 28.1.1
|
|
30
|
+
|
|
31
|
+
### Patch Changes
|
|
32
|
+
|
|
33
|
+
- 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.
|
|
34
|
+
- 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.
|
|
35
|
+
|
|
36
|
+
Reuse graph hull paths and bounded heatmap label measurements during painting, with invalidation when geometry or text settings change.
|
|
37
|
+
|
|
38
|
+
Keep command descriptions and shortcuts readable through command-palette highlight transitions.
|
|
39
|
+
|
|
40
|
+
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.
|
|
41
|
+
- 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.
|
|
42
|
+
|
|
43
|
+
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.
|
|
44
|
+
- 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.
|
|
45
|
+
|
|
46
|
+
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.
|
|
47
|
+
- 7a28693: Keep combobox `selectedRows` aligned with programmatically bound values when a search filters selected options out of the suggestion list.
|
|
48
|
+
- 6ea4454: Reduce temporary allocations when selecting a small number of values from a large option list.
|
|
49
|
+
|
|
50
|
+
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.
|
|
51
|
+
- 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.
|
|
52
|
+
|
|
53
|
+
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.
|
|
54
|
+
|
|
55
|
+
Resolve checkbox selection occurrences and gauge thresholds in linear passes, and reuse the inherited locale during neighbor sorting.
|
|
56
|
+
|
|
57
|
+
Index selected choices and hidden graph types once per render or search pass, preserving first-match labels, selection order, and current interaction state.
|
|
58
|
+
|
|
59
|
+
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.
|
|
60
|
+
|
|
61
|
+
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.
|
|
62
|
+
|
|
63
|
+
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.
|
|
64
|
+
|
|
65
|
+
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.
|
|
66
|
+
- @aceshooting/lyra-translations@28.1.1
|
|
67
|
+
|
|
3
68
|
## 28.1.0
|
|
4
69
|
|
|
5
70
|
### Minor 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{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteNumber,finiteRatio,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{formatShortDuration}from"../../../internal/duration.js";import{styles}from"./span-waterfall.styles.js";import{MAX_RENDERED_LYRA_SPANS,normalizeLyraSpans}from"../trace-tree/span.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_spanStartedAtOffset,LYRA_DEFAULT_spanWaterfall}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut}from"../../../internal/default-strings/shared.generated.js";const KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"},STATUS_TONE={success:"success",error:"danger",denied:"warning",running:"accent",pending:"neutral",incomplete:"neutral",unknown:"neutral"};function niceStep(span,count){if(span<=0)return 1;const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function axisTicks(start,end,count=5){const step=niceStep(end-start,count);if(!Number.isFinite(step)||step<=0)return[start,end];const first=Math.ceil(start/step)*step;if(!Number.isFinite(first))return[start,end];const ticks=[];for(let index=0;index<=count+2;index++){const value=first+index*step;if(!Number.isFinite(value)||value>end+step/2)break;const rounded=Math.round(value/step)*step;Number.isFinite(rounded)&&(ticks.length===0||rounded>ticks[ticks.length-1])&&ticks.push(rounded)}return ticks}class LyraSpanWaterfall extends LyraElement{constructor(){super(...arguments),this.spans=[],this.activeSpanId=null,this.viewStartMs=null,this.viewEndMs=null,this.withoutAxis=!1,this.focusedId=null,this.sortedActiveSpanId=null,this.sortedCache=[],this.sortedCacheTruncated=!1,this.sortedCacheExtentEndMs=0,this.axisSignature="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.onKeyDown=e=>{const view=this.viewWindow(),rows=this.sortedSpans().filter(span=>this.barGeometry(span,view).visible);if(rows.length===0)return;const currentIndex=rows.findIndex(s=>s.id===this.focusedId),idx=currentIndex>=0?currentIndex:0;switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,idx+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,idx-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case"Enter":case" ":e.preventDefault(),this.selectRow(rows[idx].id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,spanStartedAtOffset:LYRA_DEFAULT_spanStartedAtOffset,spanWaterfall:LYRA_DEFAULT_spanWaterfall,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.sortedCacheTruncated,this.hasUpdated&&(this.observeAxis(),this.fitAxisLabels())}disconnectedCallback(){this.axisObserver?.disconnect(),this.axisObserver=void 0,this.observedAxis=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}sortedSpans(){if(this.sortedSource===this.spans&&this.sortedActiveSpanId===this.activeSpanId)return this.sortedCache;this.sortedSource=this.spans,this.sortedActiveSpanId=this.activeSpanId;const projection=normalizeLyraSpans(this.spans,this.activeSpanId);return this.sortedCacheTruncated=projection.truncated,this.sortedCacheExtentEndMs=projection.extentEndMs,this.sortedCache=projection.spans.map((s,i)=>({s,i})).sort((a,b)=>a.s.startMs-b.s.startMs||a.i-b.i).map(x=>x.s),this.sortedCache}viewWindow(){this.sortedSpans();const fallbackEnd=Math.max(finiteNumber(this.sortedCacheExtentEndMs,0),1),start=this.viewStartMs==null?0:finiteRange(this.viewStartMs,0,0,Number.MAX_SAFE_INTEGER-1),end=this.viewEndMs==null?fallbackEnd:finiteRange(this.viewEndMs,fallbackEnd,0,Number.MAX_SAFE_INTEGER);return{start,end:end>start?end:start+1}}barGeometry(span,view){const endMs=span.endMs??(span.status==="running"?view.end:span.startMs),visible=span.startMs<=view.end&&endMs>=view.start,clampedStart=Math.max(view.start,span.startMs),clampedEnd=Math.min(view.end,Math.max(endMs,span.startMs)),startPct=finiteRatio(clampedStart,view.start,view.end)*100,endPct=finiteRatio(clampedEnd,view.start,view.end)*100;return{startPct,widthPct:Math.max(0,endPct-startPct),visible}}formatDuration(ms){return ms==null||!Number.isFinite(ms)?"":formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}projectionLimitText(){return this.localize("spanProjectionLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(MAX_RENDERED_LYRA_SPANS)})}focusRow(span){if(!span)return;const previous=this.renderRoot.querySelector('[part="bar"][tabindex="0"]');this.focusedId=span.id,previous?.setAttribute("tabindex","-1");const next=this.renderedBarById(span.id);next?.setAttribute("tabindex","0"),next?.focus()}selectRow(id){this.focusedId=id,this.emit("lr-span-select",{spanId:id})}willUpdate(changed){if(super.willUpdate(changed),(changed.has("spans")||changed.has("activeSpanId"))&&(this.sortedSource=void 0),changed.has("spans")||changed.has("viewStartMs")||changed.has("viewEndMs")||changed.has("activeSpanId")){const view=this.viewWindow(),ids=new Set(this.sortedSpans().filter(span=>this.barGeometry(span,view).visible).map(span=>span.id));(this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&ids.has(this.activeSpanId)?this.activeSpanId:this.sortedSpans()[0]?.id??null),this.focusedId!==null&&!ids.has(this.focusedId)&&(this.focusedId=this.sortedSpans().find(span=>ids.has(span.id))?.id??null),changed.has("activeSpanId")&&this.activeSpanId&&ids.has(this.activeSpanId)&&(this.focusedId=this.activeSpanId)}}renderedBarById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),changed.has("activeSpanId")&&this.activeSpanId){const bar=this.renderedBarById(this.activeSpanId);if(bar&&!bar.hidden){const reducedMotion=!bar.ownerDocument.defaultView||prefersReducedMotion(this);bar.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}this.limitAnnouncementInitialized&&this.sortedCacheTruncated&&!this.previouslyTruncated&&this.announcements.announcePolite(this.projectionLimitText()),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.sortedCacheTruncated,this.observeAxis();const view=this.viewWindow(),axisSignature=`${view.start}|${view.end}|${this.effectiveLocale}`;axisSignature!==this.axisSignature&&(this.axisSignature=axisSignature,this.fitAxisLabels())}observeAxis(){const axis=this.renderRoot.querySelector('[part="axis"]')??void 0;if(axis===this.observedAxis)return;this.axisObserver?.disconnect(),this.observedAxis=axis;const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver;!axis||!ResizeObserverCtor||(this.axisObserver??=new ResizeObserverCtor(()=>this.fitAxisLabels()),this.axisObserver.observe(axis))}fitAxisLabels(){const axis=this.renderRoot.querySelector('[part="axis"]');if(!axis)return;const ticks=Array.from(axis.querySelectorAll('[part="tick"]')),labels=ticks.map(tick=>tick.querySelector('[part="tick-label"]'));for(const tick of ticks)tick.removeAttribute("data-fit");for(const label of labels)label.removeAttribute("data-collapsed");const axisRect=axis.getBoundingClientRect();if(axisRect.width<=0)return;const rtl=this.ownerDocument.defaultView?.getComputedStyle(axis).direction==="rtl",span=rect=>rtl?{start:-rect.right,end:-rect.left}:{start:rect.left,end:rect.right},axisSpan=span(axisRect),rects=labels.map(label=>label.getBoundingClientRect());ticks.forEach((tick,index)=>{span(rects[index]).end>axisSpan.end+.5&&tick.setAttribute("data-fit","end")});const placed=labels.map(label=>{const{start,end}=span(label.getBoundingClientRect());return{label,start,end}}).sort((a,b)=>a.start-b.start),kept=[];placed.forEach((entry,index)=>{const isTerminal=index===placed.length-1;for(;kept.length>1&&isTerminal&&entry.start<kept[kept.length-1].end;)kept.pop().label.setAttribute("data-collapsed","");const previous=kept[kept.length-1];previous&&entry.start<previous.end?entry.label.setAttribute("data-collapsed",""):kept.push(entry)})}renderAxis(view){const ticks=axisTicks(view.start,view.end);return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteNumber,finiteRatio,finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{formatShortDuration}from"../../../internal/duration.js";import{styles}from"./span-waterfall.styles.js";import{MAX_RENDERED_LYRA_SPANS,normalizeLyraSpans}from"../trace-tree/span.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_spanKindAgent,LYRA_DEFAULT_spanKindEmbedding,LYRA_DEFAULT_spanKindLlm,LYRA_DEFAULT_spanKindOther,LYRA_DEFAULT_spanKindRetriever,LYRA_DEFAULT_spanKindTool,LYRA_DEFAULT_spanProjectionLimit,LYRA_DEFAULT_spanStartedAtOffset,LYRA_DEFAULT_spanWaterfall}from"../../../internal/default-strings/agent-tools.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_statusDenied,LYRA_DEFAULT_statusError,LYRA_DEFAULT_statusIncomplete,LYRA_DEFAULT_statusPending,LYRA_DEFAULT_statusRunning,LYRA_DEFAULT_statusSuccess,LYRA_DEFAULT_statusUnknown,LYRA_DEFAULT_tokensIn,LYRA_DEFAULT_tokensOut}from"../../../internal/default-strings/shared.generated.js";const KIND_LABEL_KEY={agent:"spanKindAgent",llm:"spanKindLlm",tool:"spanKindTool",retriever:"spanKindRetriever",embedding:"spanKindEmbedding",other:"spanKindOther"},STATUS_LABEL_KEY={pending:"statusPending",running:"statusRunning",success:"statusSuccess",error:"statusError",denied:"statusDenied",incomplete:"statusIncomplete",unknown:"statusUnknown"},STATUS_TONE={success:"success",error:"danger",denied:"warning",running:"accent",pending:"neutral",incomplete:"neutral",unknown:"neutral"};function niceStep(span,count){if(span<=0)return 1;const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function axisTicks(start,end,count=5){const step=niceStep(end-start,count);if(!Number.isFinite(step)||step<=0)return[start,end];const first=Math.ceil(start/step)*step;if(!Number.isFinite(first))return[start,end];const ticks=[];for(let index=0;index<=count+2;index++){const value=first+index*step;if(!Number.isFinite(value)||value>end+step/2)break;const rounded=Math.round(value/step)*step;Number.isFinite(rounded)&&(ticks.length===0||rounded>ticks[ticks.length-1])&&ticks.push(rounded)}return ticks}class LyraSpanWaterfall extends LyraElement{constructor(){super(...arguments),this.spans=[],this.activeSpanId=null,this.viewStartMs=null,this.viewEndMs=null,this.withoutAxis=!1,this.focusedId=null,this.sortedActiveSpanId=null,this.sortedCache=[],this.sortedCacheTruncated=!1,this.sortedCacheExtentEndMs=0,this.axisSignature="",this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitAnnouncementInitialized=!1,this.previouslyTruncated=!1,this.onKeyDown=e=>{const view=this.viewWindow(),rows=this.sortedSpans().filter(span=>this.barGeometry(span,view).visible);if(rows.length===0)return;const currentIndex=rows.findIndex(s=>s.id===this.focusedId),idx=currentIndex>=0?currentIndex:0;switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(rows[Math.min(rows.length-1,idx+1)]);break;case"ArrowUp":e.preventDefault(),this.focusRow(rows[Math.max(0,idx-1)]);break;case"Home":e.preventDefault(),this.focusRow(rows[0]);break;case"End":e.preventDefault(),this.focusRow(rows[rows.length-1]);break;case"Enter":case" ":e.preventDefault(),this.selectRow(rows[idx].id);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,spanKindAgent:LYRA_DEFAULT_spanKindAgent,spanKindEmbedding:LYRA_DEFAULT_spanKindEmbedding,spanKindLlm:LYRA_DEFAULT_spanKindLlm,spanKindOther:LYRA_DEFAULT_spanKindOther,spanKindRetriever:LYRA_DEFAULT_spanKindRetriever,spanKindTool:LYRA_DEFAULT_spanKindTool,spanProjectionLimit:LYRA_DEFAULT_spanProjectionLimit,spanStartedAtOffset:LYRA_DEFAULT_spanStartedAtOffset,spanWaterfall:LYRA_DEFAULT_spanWaterfall,statusDenied:LYRA_DEFAULT_statusDenied,statusError:LYRA_DEFAULT_statusError,statusIncomplete:LYRA_DEFAULT_statusIncomplete,statusPending:LYRA_DEFAULT_statusPending,statusRunning:LYRA_DEFAULT_statusRunning,statusSuccess:LYRA_DEFAULT_statusSuccess,statusUnknown:LYRA_DEFAULT_statusUnknown,tokensIn:LYRA_DEFAULT_tokensIn,tokensOut:LYRA_DEFAULT_tokensOut}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["spans"])}static{this.identityCollectionProperties=Object.freeze(["spans"])}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback(),this.limitAnnouncementInitialized=this.hasUpdated,this.previouslyTruncated=this.sortedCacheTruncated,this.hasUpdated&&(this.observeAxis(),this.fitAxisLabels())}disconnectedCallback(){this.axisObserver?.disconnect(),this.axisObserver=void 0,this.observedAxis=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}sortedSpans(){if(this.sortedSource===this.spans&&this.sortedActiveSpanId===this.activeSpanId)return this.sortedCache;this.sortedSource=this.spans,this.sortedActiveSpanId=this.activeSpanId;const projection=normalizeLyraSpans(this.spans,this.activeSpanId);return this.sortedCacheTruncated=projection.truncated,this.sortedCacheExtentEndMs=projection.extentEndMs,this.sortedCache=projection.spans.map((s,i)=>({s,i})).sort((a,b)=>a.s.startMs-b.s.startMs||a.i-b.i).map(x=>x.s),this.sortedCache}viewWindow(){this.sortedSpans();const fallbackEnd=Math.max(finiteNumber(this.sortedCacheExtentEndMs,0),1),start=this.viewStartMs==null?0:finiteRange(this.viewStartMs,0,0,Number.MAX_SAFE_INTEGER-1),end=this.viewEndMs==null?fallbackEnd:finiteRange(this.viewEndMs,fallbackEnd,0,Number.MAX_SAFE_INTEGER);return{start,end:end>start?end:start+1}}barGeometry(span,view){const endMs=span.endMs??(span.status==="running"?view.end:span.startMs),visible=span.startMs<=view.end&&endMs>=view.start,clampedStart=Math.max(view.start,span.startMs),clampedEnd=Math.min(view.end,Math.max(endMs,span.startMs)),startPct=finiteRatio(clampedStart,view.start,view.end)*100,endPct=finiteRatio(clampedEnd,view.start,view.end)*100;return{startPct,widthPct:Math.max(0,endPct-startPct),visible}}formatDuration(ms){return ms==null||!Number.isFinite(ms)?"":formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}projectionLimitText(){return this.localize("spanProjectionLimit",void 0,{count:getNumberFormat(this.effectiveLocale).format(MAX_RENDERED_LYRA_SPANS)})}focusRow(span){if(!span)return;const previous=this.renderRoot.querySelector('[part="bar"][tabindex="0"]');this.focusedId=span.id,previous?.setAttribute("tabindex","-1");const next=this.renderedBarById(span.id);next?.setAttribute("tabindex","0"),next?.focus()}selectRow(id){this.focusedId=id,this.emit("lr-span-select",{spanId:id})}willUpdate(changed){if(super.willUpdate(changed),(changed.has("spans")||changed.has("activeSpanId"))&&(this.sortedSource=void 0),changed.has("spans")||changed.has("viewStartMs")||changed.has("viewEndMs")||changed.has("activeSpanId")){const view=this.viewWindow(),ids=new Set(this.sortedSpans().filter(span=>this.barGeometry(span,view).visible).map(span=>span.id));(this.focusedId==null||!ids.has(this.focusedId))&&(this.focusedId=this.activeSpanId&&ids.has(this.activeSpanId)?this.activeSpanId:this.sortedSpans()[0]?.id??null),this.focusedId!==null&&!ids.has(this.focusedId)&&(this.focusedId=this.sortedSpans().find(span=>ids.has(span.id))?.id??null),changed.has("activeSpanId")&&this.activeSpanId&&ids.has(this.activeSpanId)&&(this.focusedId=this.activeSpanId)}}renderedBarById(id){const ownerCss=this.ownerDocument.defaultView?.CSS;return typeof ownerCss?.escape=="function"?this.renderRoot.querySelector(`[data-id="${ownerCss.escape(id)}"]`):Array.from(this.renderRoot.querySelectorAll("[data-id]")).find(element=>element.dataset.id===id)??null}updated(changed){if(super.updated(changed),changed.has("activeSpanId")&&this.activeSpanId){const bar=this.renderedBarById(this.activeSpanId);if(bar&&!bar.hidden){const reducedMotion=!bar.ownerDocument.defaultView||prefersReducedMotion(this);bar.scrollIntoView({block:"nearest",behavior:reducedMotion?"auto":"smooth"})}}this.limitAnnouncementInitialized&&this.sortedCacheTruncated&&!this.previouslyTruncated&&this.announcements.announcePolite(this.projectionLimitText()),this.limitAnnouncementInitialized=!0,this.previouslyTruncated=this.sortedCacheTruncated,this.observeAxis();const view=this.viewWindow(),axisSignature=`${view.start}|${view.end}|${this.effectiveLocale}`;axisSignature!==this.axisSignature&&(this.axisSignature=axisSignature,this.fitAxisLabels())}observeAxis(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]')??void 0;if(axis===this.observedAxis)return;this.axisObserver?.disconnect(),this.observedAxis=axis;const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(!axis||!ResizeObserverCtor)return;const observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.axisObserver!==observer||this.fitAxisLabels()});this.axisObserver=observer,observer.observe(axis)}fitAxisLabels(){if(!this.isConnected)return;const axis=this.renderRoot.querySelector('[part="axis"]');if(!axis)return;const ticks=Array.from(axis.querySelectorAll('[part="tick"]')),labels=ticks.map(tick=>tick.querySelector('[part="tick-label"]'));for(const tick of ticks)tick.removeAttribute("data-fit");for(const label of labels)label.removeAttribute("data-collapsed");const axisRect=axis.getBoundingClientRect();if(axisRect.width<=0)return;const rtl=this.ownerDocument.defaultView?.getComputedStyle(axis).direction==="rtl",span=rect=>rtl?{start:-rect.right,end:-rect.left}:{start:rect.left,end:rect.right},axisSpan=span(axisRect),rects=labels.map(label=>label.getBoundingClientRect());ticks.forEach((tick,index)=>{span(rects[index]).end>axisSpan.end+.5&&tick.setAttribute("data-fit","end")});const placed=labels.map(label=>{const{start,end}=span(label.getBoundingClientRect());return{label,start,end}}).sort((a,b)=>a.start-b.start),kept=[];placed.forEach((entry,index)=>{const isTerminal=index===placed.length-1;for(;kept.length>1&&isTerminal&&entry.start<kept[kept.length-1].end;)kept.pop().label.setAttribute("data-collapsed","");const previous=kept[kept.length-1];previous&&entry.start<previous.end?entry.label.setAttribute("data-collapsed",""):kept.push(entry)})}renderAxis(view){const ticks=axisTicks(view.start,view.end);return html`
|
|
2
2
|
<div part="axis" aria-hidden="true">
|
|
3
3
|
${ticks.map(t=>{const pct=finiteRatio(t,view.start,view.end)*100;return pct<0||pct>100?nothing:html`<span
|
|
4
4
|
part="tick"
|
|
@@ -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"
|
|
@@ -103,7 +103,7 @@ export interface LyraBoxPlotPointDetail{datasetIndex:number;index:number;label:s
|
|
|
103
103
|
* @status stable
|
|
104
104
|
* @since 4.0.0
|
|
105
105
|
*/
|
|
106
|
-
export declare class LyraBoxPlot extends LyraElement<LyraBoxPlotEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];protected static readonly immutableEventDetails:readonly string[];constructor();private readonly canvasTokens;labels:readonly string[];private _datasets;private datasetsSource;
|
|
106
|
+
export declare class LyraBoxPlot extends LyraElement<LyraBoxPlotEventMap>{protected static collectionSupport:import("../../../internal/lyra-element.js").LyraCollectionSupport;protected static readonly ownedCollectionProperties:readonly string[];static styles:import("lit").CSSResultGroup[];protected static readonly immutableEventDetails:readonly string[];constructor();private readonly canvasTokens;private appliedLegendVisibility?;labels:readonly string[];private _datasets;private datasetsSource;
|
|
107
107
|
/**
|
|
108
108
|
* Series with an array `data` payload. Malformed entries are dropped without hiding siblings.
|
|
109
109
|
* A bounded, clone-owned readonly snapshot: each series keeps at most its first
|
|
@@ -153,4 +153,4 @@ formatter?:LyraChartFormatter;private loading;private loadFailed;private canvasU
|
|
|
153
153
|
/** Re-reads canvas theme custom properties after an out-of-band ancestor theme change. */
|
|
154
154
|
refreshTheme():void;private seriesDisplayLabel;private formatValue;
|
|
155
155
|
/** Returns a spreadsheet-safe CSV snapshot or the current canvas PNG data URL. */
|
|
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 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;}}
|