@aceshooting/lyra-ui 27.0.0 → 28.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -63
- package/README.md +7 -3
- package/dist/cli/css-declarations.mjs +1 -0
- package/dist/cli/lyra-rename-ledger.mjs +1 -1
- package/dist/cli/migrate-wa.mjs +9 -4
- package/dist/cli/migration-contract.json +1 -1
- package/dist/cli/migration-renames.mjs +2 -2
- package/dist/cli/migration-theme-scopes.mjs +3 -0
- package/dist/cli/theme-scope-vocabulary.generated.mjs +1 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-question/agent-question.class.js +1 -1
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +1 -1
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +1 -1
- package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
- package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
- package/dist/components/agent-tools/budget-meter/budget-meter.class.js +1 -1
- package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +1 -1
- package/dist/components/agent-tools/connector-manager/connector-manager.class.js +1 -1
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
- package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
- package/dist/components/agent-tools/permission-grant/permission-grant.class.js +1 -1
- package/dist/components/agent-tools/permission-rules/permission-rules.class.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
- package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
- package/dist/components/agent-tools/result-card/result-field.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/stack-trace/stack-trace.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/terminal/terminal.class.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-result-view/tool-result-view.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/box-plot.class.js +1 -1
- package/dist/components/charts/chart/chart-token-cache.js +2 -2
- package/dist/components/charts/chart/chart.class.d.ts +1 -1
- package/dist/components/charts/chart/chart.class.js +3 -3
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/conversation/agent-workspace/agent-workspace.class.js +1 -1
- package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
- package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/conversation-item/conversation-item.class.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/handoff-divider/handoff-divider.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.js +1 -1
- package/dist/components/conversation/prompt-queue/prompt-queue.class.js +1 -1
- package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
- package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/stream-status/stream-status.class.js +1 -1
- package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/conversation/typing-indicator/typing-indicator.class.js +1 -1
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/calendar/calendar.class.js +1 -1
- package/dist/components/data/condition-builder/condition-builder.class.js +1 -1
- package/dist/components/data/context-meter/context-meter.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +2 -2
- package/dist/components/data/data-grid/data-grid.class.js +3 -3
- package/dist/components/data/document-library/document-library.class.js +1 -1
- package/dist/components/data/env-list/env-list.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.d.ts +2 -2
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-controls/flow-controls.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/flow-node/flow-node.class.js +1 -1
- package/dist/components/data/flow-run-status/flow-run-status.class.js +1 -1
- package/dist/components/data/funnel/funnel.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.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.d.ts +2 -0
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/pagination/pagination.styles.js +1 -1
- package/dist/components/data/sequence-strip/sequence-strip.class.js +1 -1
- package/dist/components/data/sparkline/sparkline.class.js +1 -1
- package/dist/components/data/stat/stat.class.js +1 -1
- package/dist/components/data/table/table.class.d.ts +23 -2
- package/dist/components/data/table/table.class.js +5 -3
- package/dist/components/data/table/table.styles.js +1 -1
- package/dist/components/data/timeline/timeline.class.js +1 -1
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/data/word-cloud/word-cloud.class.js +1 -1
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.d.ts +8 -4
- package/dist/components/forms/color-picker/color-picker.class.js +2 -2
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/country-picker/country-picker.class.js +1 -1
- package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-picker.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +7 -4
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
- package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -0
- package/dist/components/forms/icon-button/icon-button.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
- package/dist/components/forms/input/input-shared.js +1 -1
- package/dist/components/forms/input/input.class.js +1 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/number-input.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.js +1 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +4 -4
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +70 -7
- package/dist/components/layout/app-rail/app-rail.class.js +16 -4
- package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/breadcrumb/breadcrumb.class.js +1 -1
- package/dist/components/layout/card/card.class.js +1 -1
- package/dist/components/layout/carousel/carousel.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.class.js +1 -1
- package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
- package/dist/components/layout/details/accordion-item.class.js +1 -1
- package/dist/components/layout/details/details.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +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/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-item.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
- package/dist/components/layout/scroller/scroller.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +7 -4
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/split-panel/split-panel.class.js +1 -1
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/tab-group/tab.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/av-player/av-player.class.js +1 -1
- package/dist/components/media/avatar-group/avatar-group.class.js +1 -1
- package/dist/components/media/drop-zone/drop-zone.class.js +1 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
- package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -1
- package/dist/components/media/image-viewer/image-viewer.class.js +4 -2
- package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox.class.js +1 -1
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/media/media-card/media-card.class.js +1 -1
- package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
- package/dist/components/media/qr-code/qr-code.class.d.ts +2 -2
- package/dist/components/media/qr-code/qr-code.class.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video/video.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/media/zoomable-frame/zoomable-frame.class.js +1 -1
- package/dist/components/overlays/alert/alert.class.js +1 -1
- package/dist/components/overlays/badge/tag.class.js +1 -1
- package/dist/components/overlays/callout/callout.class.js +1 -1
- package/dist/components/overlays/chip/chip-group.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/context-menu/context-menu.class.js +1 -1
- package/dist/components/overlays/dialog/confirm.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/overlays/kbd/kbd.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-bar.class.js +1 -1
- package/dist/components/overlays/progress/progress-ring.class.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/overlays/skeleton/skeleton.class.js +1 -1
- package/dist/components/overlays/spinner/spinner.class.js +1 -1
- package/dist/components/overlays/toast/toast-item.class.js +1 -1
- package/dist/components/overlays/toast/toast.class.js +1 -1
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +1 -1
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
- package/dist/components/retrieval/community-card/community-card.class.js +1 -1
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +1 -1
- package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +1 -1
- package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +1 -1
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/node-palette/node-palette.class.js +1 -1
- package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
- package/dist/components/retrieval/rag-answer/rag-answer.class.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/research-progress/research-progress.class.js +1 -1
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-card/source-card.class.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.js +1 -1
- package/dist/components/utility/diff-view/diff-view.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.js +1 -1
- package/dist/components/utility/icon/icon.class.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/utility/poll-status/poll-status.class.js +1 -1
- package/dist/components/utility/random-content/random-content.class.js +1 -1
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +2 -2
- package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
- package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.class.js +1 -1
- package/dist/components/viewers/highlight-layer/highlight-layer.class.js +1 -1
- package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
- package/dist/components/viewers/include/include.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/page-rail/page-rail.class.d.ts +1 -1
- package/dist/components/viewers/page-rail/page-rail.class.js +3 -3
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
- package/dist/events.d.ts +6 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/collection-snapshot.js +1 -1
- package/dist/internal/default-strings/agent-tools.generated.js +1 -0
- package/dist/internal/default-strings/charts.generated.js +1 -0
- package/dist/internal/default-strings/conversation.generated.js +1 -0
- package/dist/internal/default-strings/data.generated.js +1 -0
- package/dist/internal/default-strings/forms.generated.js +1 -0
- package/dist/internal/default-strings/layout.generated.js +1 -0
- package/dist/internal/default-strings/media.generated.js +1 -0
- package/dist/internal/default-strings/overlays.generated.js +1 -0
- package/dist/internal/default-strings/retrieval.generated.js +1 -0
- package/dist/internal/default-strings/shared.generated.js +1 -0
- package/dist/internal/default-strings/utility.generated.js +1 -0
- package/dist/internal/default-strings/viewers.generated.js +5 -0
- package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.production.js +1 -1
- package/dist/internal/document-tokens.d.ts +11 -0
- package/dist/internal/document-tokens.generated.js +15 -0
- package/dist/internal/document-tokens.js +3 -0
- package/dist/internal/form-associated.d.ts +1 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/glass-surface.styles.js +1 -1
- package/dist/internal/host-tokens.styles.js +1 -0
- package/dist/internal/image-zoom.js +1 -0
- package/dist/internal/intl-cache.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/lyra-element.d.ts +4 -2
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/opaque-content-border.styles.js +1 -1
- package/dist/internal/open-overlay-raise.styles.js +1 -0
- package/dist/internal/optional-peer-failure.js +1 -0
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/prefix.js +1 -1
- package/dist/internal/specialist-host-tokens.styles.js +1 -0
- package/dist/internal/specialist-tokens.generated.js +2 -0
- package/dist/internal/step-value.js +1 -1
- package/dist/internal/theme-observation.js +1 -1
- package/dist/internal/theme-scopes.d.ts +11 -0
- package/dist/internal/theme-scopes.js +1 -0
- package/dist/looks/shadcn.css +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/styles/design-tokens.css +1 -1
- package/dist/styles/tokens-root.css +1 -1
- package/dist/surfaces/glass.css +1 -1
- package/dist/testing/happy-dom-shims.d.ts +21 -2
- package/dist/testing/happy-dom-shims.js +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/interaction-drivers.d.ts +66 -7
- package/dist/testing/interaction-drivers.js +1 -1
- package/dist/testing/jsdom-shims.d.ts +70 -0
- package/dist/testing/jsdom-shims.js +1 -0
- package/dist/theme/look-inputs.d.ts +1 -1
- package/dist/theme/look-inputs.js +37 -41
- package/dist/theme/theme.d.ts +13 -0
- package/dist/theme/theme.js +1 -1
- package/dist/theme.css +1 -1
- package/dist/utilities/index.d.ts +1 -1
- package/dist/utilities/index.js +1 -1
- package/dist/utilities/scoped-registry.d.ts +3 -0
- package/dist/utilities/scoped-registry.js +1 -1
- package/dist/utilities/theme-scopes.d.ts +1 -0
- package/dist/utilities/theme-scopes.js +1 -0
- package/dist/utilities/tokens.d.ts +1 -0
- package/dist/utilities/tokens.js +1 -0
- package/llms/components/lr-app-rail.md +51 -4
- package/llms/components/lr-emoji-picker.md +13 -8
- package/llms/components/lr-icon-button.md +13 -1
- package/llms/components/lr-image-viewer.md +8 -0
- package/llms/components/lr-pagination.md +4 -2
- package/llms/components/lr-segmented.md +7 -3
- package/llms/components/lr-table.md +14 -12
- package/llms/components/lr-thread-list.md +4 -3
- package/llms/migration.md +9 -0
- package/llms/peers.md +1 -1
- package/llms/shared/events-and-types.md +41 -0
- package/llms/shared/frameworks-and-ssr.md +16 -0
- package/llms/shared/imports-and-registration.md +4 -3
- package/llms/shared/native-styles-and-utilities.md +38 -3
- package/llms/shared/styles-and-tokens.md +242 -102
- package/llms/shared/testing-and-utilities.md +90 -6
- package/llms/shared.md +431 -114
- package/llms/tokens.md +31 -49
- package/locales.json +138 -138
- package/package.json +14 -7
- package/registrations.json +1 -1
- package/dist/internal/default-strings.generated.js +0 -5
- package/dist/internal/specialist-tokens.styles.js +0 -1
- package/dist/internal/tokens/palette.styles.js +0 -1
- package/dist/internal/tokens.styles.js +0 -1
|
@@ -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{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{styles}from"./prompt-queue.styles.js";import{LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_moveDown,LYRA_DEFAULT_moveUp,LYRA_DEFAULT_promptInputAttachments,LYRA_DEFAULT_promptQueueActionLabel,LYRA_DEFAULT_promptQueueEmpty,LYRA_DEFAULT_promptQueueItemLabel,LYRA_DEFAULT_promptQueueLabel,LYRA_DEFAULT_promptQueueSendNow,LYRA_DEFAULT_remove}from"../../../internal/default-strings.generated.js";const MAX_PROJECTED_QUEUE_ITEMS=1e4,MAX_PROJECTED_QUEUE_ATTACHMENTS=1e4,EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS=Object.freeze([]);function descriptorValue(value,property2){return getOwnDataDescriptor(value,property2)}function valueOfDescriptor(descriptor){return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectPromptQueueAttachment(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const idDescriptor=descriptorValue(value,"id"),nameDescriptor=descriptorValue(value,"name"),mimeTypeDescriptor=descriptorValue(value,"mimeType"),uriDescriptor=descriptorValue(value,"uri"),versionDescriptor=descriptorValue(value,"version");if([idDescriptor,nameDescriptor,mimeTypeDescriptor,uriDescriptor,versionDescriptor].some(descriptor=>descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return;const id=valueOfDescriptor(idDescriptor),name=valueOfDescriptor(nameDescriptor);if(typeof id!="string"||id.trim().length===0||typeof name!="string")return;const mimeType=valueOfDescriptor(mimeTypeDescriptor),uri=valueOfDescriptor(uriDescriptor),version=valueOfDescriptor(versionDescriptor);return Object.freeze({id,name,...typeof mimeType=="string"?{mimeType}:{},...typeof uri=="string"?{uri}:{},...typeof version=="string"?{version}:{}})}catch{return}}function projectPromptQueueAttachments(value){try{if(!Array.isArray(value))return;const lengthDescriptor=descriptorValue(value,"length");if(lengthDescriptor===MISSING_OWN_DATA_DESCRIPTOR||lengthDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return;const attachments=[],length=Math.min(lengthDescriptor.value,MAX_PROJECTED_QUEUE_ATTACHMENTS);for(let index=0;index<length;index+=1){const descriptor=descriptorValue(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const attachment=projectPromptQueueAttachment(descriptor.value);attachment&&attachments.push(attachment)}return Object.freeze(attachments)}catch{return}}function projectPromptQueueItem(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const idDescriptor=descriptorValue(value,"id"),valueDescriptor=descriptorValue(value,"value"),attachmentsDescriptor=descriptorValue(value,"attachments"),createdAtDescriptor=descriptorValue(value,"createdAt"),metadataDescriptor=descriptorValue(value,"metadata");if([idDescriptor,valueDescriptor,attachmentsDescriptor,createdAtDescriptor,metadataDescriptor].some(descriptor=>descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return;const id=valueOfDescriptor(idDescriptor),prompt=valueOfDescriptor(valueDescriptor);if(typeof id!="string"||id.trim().length===0||typeof prompt!="string")return;const attachmentsValue=valueOfDescriptor(attachmentsDescriptor),attachments=attachmentsDescriptor===MISSING_OWN_DATA_DESCRIPTOR||attachmentsValue===void 0?void 0:projectPromptQueueAttachments(attachmentsValue),createdAt=valueOfDescriptor(createdAtDescriptor),metadata=valueOfDescriptor(metadataDescriptor);return Object.freeze({source:value,id,value:prompt,...attachments===void 0?{}:{attachments},...typeof createdAt=="number"&&Number.isFinite(createdAt)?{createdAt}:{},...metadata!==void 0?{metadata}:{}})}catch{return}}function projectPromptQueueItems(value){try{if(!Array.isArray(value))return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS;const lengthDescriptor=descriptorValue(value,"length");if(lengthDescriptor===MISSING_OWN_DATA_DESCRIPTOR||lengthDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS;const items=[],seen=new Set,length=Math.min(lengthDescriptor.value,MAX_PROJECTED_QUEUE_ITEMS);for(let index=0;index<length;index+=1){const descriptor=descriptorValue(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const item=projectPromptQueueItem(descriptor.value);!item||seen.has(item.id)||(seen.add(item.id),items.push(item))}return Object.freeze(items)}catch{return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS}}function toDocumentRef(attachment){return Object.freeze({id:attachment.id,name:attachment.name,...attachment.mimeType===void 0?{}:{mimeType:attachment.mimeType},...attachment.uri===void 0?{}:{uri:attachment.uri},...attachment.version===void 0?{}:{version:attachment.version}})}function toPromptQueueItem(item,value=item.value){return Object.freeze({id:item.id,value,...item.attachments===void 0?{}:{attachments:Object.freeze(item.attachments.map(toDocumentRef))},...item.createdAt===void 0?{}:{createdAt:item.createdAt},...item.metadata===void 0?{}:{metadata:item.metadata}})}class LyraPromptQueue extends LyraElement{constructor(){super(...arguments),this.items=[],this.readonly=!1,this.disabled=!1,this.accessibleLabel=null,this.headingLevel="3",this.canonicalItemsBySource=new WeakMap,this.containNativeEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,moveDown:LYRA_DEFAULT_moveDown,moveUp:LYRA_DEFAULT_moveUp,promptInputAttachments:LYRA_DEFAULT_promptInputAttachments,promptQueueActionLabel:LYRA_DEFAULT_promptQueueActionLabel,promptQueueEmpty:LYRA_DEFAULT_promptQueueEmpty,promptQueueItemLabel:LYRA_DEFAULT_promptQueueItemLabel,promptQueueLabel:LYRA_DEFAULT_promptQueueLabel,promptQueueSendNow:LYRA_DEFAULT_promptQueueSendNow,remove:LYRA_DEFAULT_remove}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-queue-change","lr-send-now"])}static{this.identityEventDetailProperties=Object.freeze({"lr-send-now":Object.freeze(["item"])})}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-queue-change":Object.freeze(["items"])})}canonicalItemsFor(source){if(source===null||typeof source!="object"&&typeof source!="function")return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS;const cached=this.canonicalItemsBySource.get(source);if(cached)return cached;const result=projectPromptQueueItems(source);return this.canonicalItemsBySource.set(source,result),result}cachedCanonicalItemsFor(source){return source!==null&&(typeof source=="object"||typeof source=="function")?this.canonicalItemsBySource.get(source)??EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS:EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS}get effectiveItems(){return this.canonicalItemsFor(this.items)}willUpdate(changed){if(super.willUpdate(changed),!changed.has("items")&&!changed.has("readonly")&&!changed.has("disabled"))return;const focusedControl=shadowFocusTarget(this),action=focusedControl?.getAttribute("data-action")??void 0,editorFocused=focusedControl?.getAttribute("part")==="editor";if(!action&&!editorFocused)return;const focusedItem=focusedControl?.closest("[data-id]"),focusedId=focusedItem?.dataset.id;if(!focusedId||!focusedControl)return;const previousItems=changed.has("items")?this.cachedCanonicalItemsFor(changed.get("items")):EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS,items=this.effectiveItems,previousIndex=previousItems.findIndex(item=>item.id===focusedId),index=items.findIndex(item=>item.id===focusedId),rowRemoved=changed.has("items")&&index<0,rowMoved=!!action&&changed.has("items")&&index>=0&&index!==previousIndex,editorRemoved=editorFocused&&changed.has("readonly")&&this.readonly,controlDisabled=changed.has("disabled")&&this.disabled;if(!rowRemoved&&!rowMoved&&!editorRemoved&&!controlDisabled)return;const target=rowRemoved?items[Math.min(Math.max(previousIndex,0),items.length-1)]:items.find(item=>item.id===focusedId),rowActions=focusedItem?.querySelectorAll("[data-action]")??[];this.pendingRemovalFocus={targetId:target?.id,action,actionIndex:action?[...rowActions].findIndex(candidate=>candidate===focusedControl):-1,origin:focusedControl}}updated(changed){super.updated(changed);const pending=this.pendingRemovalFocus;if(!pending)return;this.pendingRemovalFocus=void 0;const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);if(internalActive!==null&&internalActive!==pending.origin||documentActive!==null&&documentActive!==this&&documentActive!==this.ownerDocument.body)return;if(!pending.targetId){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}const actions=[...[...this.shadowRoot?.querySelectorAll("[data-id]")??[]].find(item=>item.dataset.id===pending.targetId)?.querySelectorAll("[data-action]")??[]],isEnabled=candidate=>candidate.disabled!==!0&&candidate.getAttribute("aria-disabled")!=="true",equivalentAction=pending.action?actions.find(candidate=>candidate.dataset.action===pending.action&&isEnabled(candidate)):void 0;if(equivalentAction){equivalentAction.focus();return}const preferredIndex=pending.actionIndex>=0?pending.actionIndex:0;for(let distance=0;distance<actions.length;distance++){const before=actions[preferredIndex-distance];if(before&&isEnabled(before)){before.focus();return}const after=actions[preferredIndex+distance];if(after&&isEnabled(after)){after.focus();return}}this.shadowRoot?.querySelector('[part="base"]')?.focus()}emitChange(items,reason,itemId){this.disabled||this.emit("lr-queue-change",{items,reason,itemId})}edit(item,value){this.disabled||this.readonly||this.emitChange(this.effectiveItems.map(candidate=>toPromptQueueItem(candidate,candidate.id===item.id?value:candidate.value)),"edit",item.id)}removeItem(item){this.disabled||this.emitChange(this.effectiveItems.filter(candidate=>candidate.id!==item.id).map(candidate=>toPromptQueueItem(candidate)),"remove",item.id)}move(item,offset){if(this.disabled)return;const items=this.effectiveItems,index=items.findIndex(candidate=>candidate.id===item.id),target=index+offset;if(index<0||target<0||target>=items.length)return;const next=[...items],[moved]=next.splice(index,1);moved&&(next.splice(target,0,moved),this.emitChange(next.map(candidate=>toPromptQueueItem(candidate)),"reorder",item.id))}sendNow(item){this.disabled||this.emit("lr-send-now",{item:toPromptQueueItem(item)})}renderItem(item,index,itemCount){const formattedIndex=getNumberFormat(this.effectiveLocale).format(index+1),editorLabel=this.localize("promptQueueItemLabel",void 0,{index:formattedIndex}),actionLabel=action=>this.localize("promptQueueActionLabel",void 0,{action,index:formattedIndex});return html`<li part="item" data-id=${item.id}>
|
|
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{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{styles}from"./prompt-queue.styles.js";import{LYRA_DEFAULT_promptInputAttachments,LYRA_DEFAULT_promptQueueActionLabel,LYRA_DEFAULT_promptQueueEmpty,LYRA_DEFAULT_promptQueueItemLabel,LYRA_DEFAULT_promptQueueLabel,LYRA_DEFAULT_promptQueueSendNow}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_attachmentUntitledFile,LYRA_DEFAULT_moveDown,LYRA_DEFAULT_moveUp,LYRA_DEFAULT_remove}from"../../../internal/default-strings/shared.generated.js";const MAX_PROJECTED_QUEUE_ITEMS=1e4,MAX_PROJECTED_QUEUE_ATTACHMENTS=1e4,EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS=Object.freeze([]);function descriptorValue(value,property2){return getOwnDataDescriptor(value,property2)}function valueOfDescriptor(descriptor){return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectPromptQueueAttachment(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const idDescriptor=descriptorValue(value,"id"),nameDescriptor=descriptorValue(value,"name"),mimeTypeDescriptor=descriptorValue(value,"mimeType"),uriDescriptor=descriptorValue(value,"uri"),versionDescriptor=descriptorValue(value,"version");if([idDescriptor,nameDescriptor,mimeTypeDescriptor,uriDescriptor,versionDescriptor].some(descriptor=>descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return;const id=valueOfDescriptor(idDescriptor),name=valueOfDescriptor(nameDescriptor);if(typeof id!="string"||id.trim().length===0||typeof name!="string")return;const mimeType=valueOfDescriptor(mimeTypeDescriptor),uri=valueOfDescriptor(uriDescriptor),version=valueOfDescriptor(versionDescriptor);return Object.freeze({id,name,...typeof mimeType=="string"?{mimeType}:{},...typeof uri=="string"?{uri}:{},...typeof version=="string"?{version}:{}})}catch{return}}function projectPromptQueueAttachments(value){try{if(!Array.isArray(value))return;const lengthDescriptor=descriptorValue(value,"length");if(lengthDescriptor===MISSING_OWN_DATA_DESCRIPTOR||lengthDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return;const attachments=[],length=Math.min(lengthDescriptor.value,MAX_PROJECTED_QUEUE_ATTACHMENTS);for(let index=0;index<length;index+=1){const descriptor=descriptorValue(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const attachment=projectPromptQueueAttachment(descriptor.value);attachment&&attachments.push(attachment)}return Object.freeze(attachments)}catch{return}}function projectPromptQueueItem(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const idDescriptor=descriptorValue(value,"id"),valueDescriptor=descriptorValue(value,"value"),attachmentsDescriptor=descriptorValue(value,"attachments"),createdAtDescriptor=descriptorValue(value,"createdAt"),metadataDescriptor=descriptorValue(value,"metadata");if([idDescriptor,valueDescriptor,attachmentsDescriptor,createdAtDescriptor,metadataDescriptor].some(descriptor=>descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return;const id=valueOfDescriptor(idDescriptor),prompt=valueOfDescriptor(valueDescriptor);if(typeof id!="string"||id.trim().length===0||typeof prompt!="string")return;const attachmentsValue=valueOfDescriptor(attachmentsDescriptor),attachments=attachmentsDescriptor===MISSING_OWN_DATA_DESCRIPTOR||attachmentsValue===void 0?void 0:projectPromptQueueAttachments(attachmentsValue),createdAt=valueOfDescriptor(createdAtDescriptor),metadata=valueOfDescriptor(metadataDescriptor);return Object.freeze({source:value,id,value:prompt,...attachments===void 0?{}:{attachments},...typeof createdAt=="number"&&Number.isFinite(createdAt)?{createdAt}:{},...metadata!==void 0?{metadata}:{}})}catch{return}}function projectPromptQueueItems(value){try{if(!Array.isArray(value))return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS;const lengthDescriptor=descriptorValue(value,"length");if(lengthDescriptor===MISSING_OWN_DATA_DESCRIPTOR||lengthDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS;const items=[],seen=new Set,length=Math.min(lengthDescriptor.value,MAX_PROJECTED_QUEUE_ITEMS);for(let index=0;index<length;index+=1){const descriptor=descriptorValue(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const item=projectPromptQueueItem(descriptor.value);!item||seen.has(item.id)||(seen.add(item.id),items.push(item))}return Object.freeze(items)}catch{return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS}}function toDocumentRef(attachment){return Object.freeze({id:attachment.id,name:attachment.name,...attachment.mimeType===void 0?{}:{mimeType:attachment.mimeType},...attachment.uri===void 0?{}:{uri:attachment.uri},...attachment.version===void 0?{}:{version:attachment.version}})}function toPromptQueueItem(item,value=item.value){return Object.freeze({id:item.id,value,...item.attachments===void 0?{}:{attachments:Object.freeze(item.attachments.map(toDocumentRef))},...item.createdAt===void 0?{}:{createdAt:item.createdAt},...item.metadata===void 0?{}:{metadata:item.metadata}})}class LyraPromptQueue extends LyraElement{constructor(){super(...arguments),this.items=[],this.readonly=!1,this.disabled=!1,this.accessibleLabel=null,this.headingLevel="3",this.canonicalItemsBySource=new WeakMap,this.containNativeEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentUntitledFile:LYRA_DEFAULT_attachmentUntitledFile,moveDown:LYRA_DEFAULT_moveDown,moveUp:LYRA_DEFAULT_moveUp,promptInputAttachments:LYRA_DEFAULT_promptInputAttachments,promptQueueActionLabel:LYRA_DEFAULT_promptQueueActionLabel,promptQueueEmpty:LYRA_DEFAULT_promptQueueEmpty,promptQueueItemLabel:LYRA_DEFAULT_promptQueueItemLabel,promptQueueLabel:LYRA_DEFAULT_promptQueueLabel,promptQueueSendNow:LYRA_DEFAULT_promptQueueSendNow,remove:LYRA_DEFAULT_remove}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["items"])}static{this.identityCollectionProperties=Object.freeze(["items"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-queue-change","lr-send-now"])}static{this.identityEventDetailProperties=Object.freeze({"lr-send-now":Object.freeze(["item"])})}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-queue-change":Object.freeze(["items"])})}canonicalItemsFor(source){if(source===null||typeof source!="object"&&typeof source!="function")return EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS;const cached=this.canonicalItemsBySource.get(source);if(cached)return cached;const result=projectPromptQueueItems(source);return this.canonicalItemsBySource.set(source,result),result}cachedCanonicalItemsFor(source){return source!==null&&(typeof source=="object"||typeof source=="function")?this.canonicalItemsBySource.get(source)??EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS:EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS}get effectiveItems(){return this.canonicalItemsFor(this.items)}willUpdate(changed){if(super.willUpdate(changed),!changed.has("items")&&!changed.has("readonly")&&!changed.has("disabled"))return;const focusedControl=shadowFocusTarget(this),action=focusedControl?.getAttribute("data-action")??void 0,editorFocused=focusedControl?.getAttribute("part")==="editor";if(!action&&!editorFocused)return;const focusedItem=focusedControl?.closest("[data-id]"),focusedId=focusedItem?.dataset.id;if(!focusedId||!focusedControl)return;const previousItems=changed.has("items")?this.cachedCanonicalItemsFor(changed.get("items")):EMPTY_CANONICAL_PROMPT_QUEUE_ITEMS,items=this.effectiveItems,previousIndex=previousItems.findIndex(item=>item.id===focusedId),index=items.findIndex(item=>item.id===focusedId),rowRemoved=changed.has("items")&&index<0,rowMoved=!!action&&changed.has("items")&&index>=0&&index!==previousIndex,editorRemoved=editorFocused&&changed.has("readonly")&&this.readonly,controlDisabled=changed.has("disabled")&&this.disabled;if(!rowRemoved&&!rowMoved&&!editorRemoved&&!controlDisabled)return;const target=rowRemoved?items[Math.min(Math.max(previousIndex,0),items.length-1)]:items.find(item=>item.id===focusedId),rowActions=focusedItem?.querySelectorAll("[data-action]")??[];this.pendingRemovalFocus={targetId:target?.id,action,actionIndex:action?[...rowActions].findIndex(candidate=>candidate===focusedControl):-1,origin:focusedControl}}updated(changed){super.updated(changed);const pending=this.pendingRemovalFocus;if(!pending)return;this.pendingRemovalFocus=void 0;const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);if(internalActive!==null&&internalActive!==pending.origin||documentActive!==null&&documentActive!==this&&documentActive!==this.ownerDocument.body)return;if(!pending.targetId){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}const actions=[...[...this.shadowRoot?.querySelectorAll("[data-id]")??[]].find(item=>item.dataset.id===pending.targetId)?.querySelectorAll("[data-action]")??[]],isEnabled=candidate=>candidate.disabled!==!0&&candidate.getAttribute("aria-disabled")!=="true",equivalentAction=pending.action?actions.find(candidate=>candidate.dataset.action===pending.action&&isEnabled(candidate)):void 0;if(equivalentAction){equivalentAction.focus();return}const preferredIndex=pending.actionIndex>=0?pending.actionIndex:0;for(let distance=0;distance<actions.length;distance++){const before=actions[preferredIndex-distance];if(before&&isEnabled(before)){before.focus();return}const after=actions[preferredIndex+distance];if(after&&isEnabled(after)){after.focus();return}}this.shadowRoot?.querySelector('[part="base"]')?.focus()}emitChange(items,reason,itemId){this.disabled||this.emit("lr-queue-change",{items,reason,itemId})}edit(item,value){this.disabled||this.readonly||this.emitChange(this.effectiveItems.map(candidate=>toPromptQueueItem(candidate,candidate.id===item.id?value:candidate.value)),"edit",item.id)}removeItem(item){this.disabled||this.emitChange(this.effectiveItems.filter(candidate=>candidate.id!==item.id).map(candidate=>toPromptQueueItem(candidate)),"remove",item.id)}move(item,offset){if(this.disabled)return;const items=this.effectiveItems,index=items.findIndex(candidate=>candidate.id===item.id),target=index+offset;if(index<0||target<0||target>=items.length)return;const next=[...items],[moved]=next.splice(index,1);moved&&(next.splice(target,0,moved),this.emitChange(next.map(candidate=>toPromptQueueItem(candidate)),"reorder",item.id))}sendNow(item){this.disabled||this.emit("lr-send-now",{item:toPromptQueueItem(item)})}renderItem(item,index,itemCount){const formattedIndex=getNumberFormat(this.effectiveLocale).format(index+1),editorLabel=this.localize("promptQueueItemLabel",void 0,{index:formattedIndex}),actionLabel=action=>this.localize("promptQueueActionLabel",void 0,{action,index:formattedIndex});return html`<li part="item" data-id=${item.id}>
|
|
2
2
|
${this.readonly?html`<span part="value">${item.value}</span>`:html`<lr-textarea
|
|
3
3
|
part="editor"
|
|
4
4
|
.value=${item.value}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../utility/live-region/live-region.class.js";import{finiteDuration,MAX_TIMEOUT_MS}from"../../../internal/numbers.js";import{formatMediaTime}from"../../../internal/media-time.js";import{styles}from"./push-to-talk.styles.js";import{literalSetConverter}from"../../../internal/converters.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{OwnedFrame,OwnedInterval,OwnedTimeout}from"../../../internal/owned-timer.js";import{LYRA_DEFAULT_pushToTalkCancelled,LYRA_DEFAULT_pushToTalkDenied,LYRA_DEFAULT_pushToTalkError,LYRA_DEFAULT_pushToTalkHold,LYRA_DEFAULT_pushToTalkRequesting,LYRA_DEFAULT_pushToTalkStart,LYRA_DEFAULT_pushToTalkStarted,LYRA_DEFAULT_pushToTalkStop,LYRA_DEFAULT_pushToTalkStopped,LYRA_DEFAULT_pushToTalkUnsupported}from"../../../internal/default-strings.generated.js";const PUSH_TO_TALK_MODE=literalSetConverter(["hold","toggle"],"hold"),CANDIDATE_MIME_TYPES=["audio/webm;codecs=opus","audio/webm","audio/mp4"];function isPushToTalkSupported(owner){const runtime=owner;return!!runtime?.MediaRecorder&&typeof runtime.navigator.mediaDevices?.getUserMedia=="function"}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../utility/live-region/live-region.class.js";import{finiteDuration,MAX_TIMEOUT_MS}from"../../../internal/numbers.js";import{formatMediaTime}from"../../../internal/media-time.js";import{styles}from"./push-to-talk.styles.js";import{literalSetConverter}from"../../../internal/converters.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{OwnedFrame,OwnedInterval,OwnedTimeout}from"../../../internal/owned-timer.js";import{LYRA_DEFAULT_pushToTalkCancelled,LYRA_DEFAULT_pushToTalkDenied,LYRA_DEFAULT_pushToTalkError,LYRA_DEFAULT_pushToTalkHold,LYRA_DEFAULT_pushToTalkRequesting,LYRA_DEFAULT_pushToTalkStart,LYRA_DEFAULT_pushToTalkStarted,LYRA_DEFAULT_pushToTalkStop,LYRA_DEFAULT_pushToTalkStopped,LYRA_DEFAULT_pushToTalkUnsupported}from"../../../internal/default-strings/conversation.generated.js";const PUSH_TO_TALK_MODE=literalSetConverter(["hold","toggle"],"hold"),CANDIDATE_MIME_TYPES=["audio/webm;codecs=opus","audio/webm","audio/mp4"];function isPushToTalkSupported(owner){const runtime=owner;return!!runtime?.MediaRecorder&&typeof runtime.navigator.mediaDevices?.getUserMedia=="function"}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg width="1em" height="1em" viewBox=${ICON_VIEW_BOX} fill="none" stroke="currentColor"
|
|
3
3
|
stroke-width=${ICON_STROKE_WIDTH} stroke-linecap="round" stroke-linejoin="round"
|
|
4
4
|
aria-hidden="true" focusable="false">${paths}</svg>
|
|
@@ -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{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import"../audio-visualizer/audio-visualizer.class.js";import"../push-to-talk/push-to-talk.class.js";import"../transcript-feed/transcript-feed.class.js";import"../../overlays/badge/badge.class.js";import{styles}from"./realtime-session.styles.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_realtimeSessionConnect,LYRA_DEFAULT_realtimeSessionConnected,LYRA_DEFAULT_realtimeSessionConnecting,LYRA_DEFAULT_realtimeSessionConnectionFailed,LYRA_DEFAULT_realtimeSessionDisconnect,LYRA_DEFAULT_realtimeSessionDisconnected,LYRA_DEFAULT_realtimeSessionError,LYRA_DEFAULT_realtimeSessionInterrupt,LYRA_DEFAULT_realtimeSessionLabel,LYRA_DEFAULT_realtimeSessionMute,LYRA_DEFAULT_realtimeSessionReconnecting,LYRA_DEFAULT_realtimeSessionUnmute}from"../../../internal/default-strings.generated.js";const CONNECTION_STATE=literalSetConverter(["disconnected","connecting","connected","reconnecting","error"],"disconnected"),VOICE_STATE=literalSetConverter(["idle","listening","thinking","speaking"],"idle"),STATE_VARIANT={disconnected:"neutral",connecting:"brand",connected:"success",reconnecting:"warning",error:"danger"};class LyraRealtimeSession extends LyraElement{static{this.defaultStrings={...super.defaultStrings,realtimeSessionConnect:LYRA_DEFAULT_realtimeSessionConnect,realtimeSessionConnected:LYRA_DEFAULT_realtimeSessionConnected,realtimeSessionConnecting:LYRA_DEFAULT_realtimeSessionConnecting,realtimeSessionConnectionFailed:LYRA_DEFAULT_realtimeSessionConnectionFailed,realtimeSessionDisconnect:LYRA_DEFAULT_realtimeSessionDisconnect,realtimeSessionDisconnected:LYRA_DEFAULT_realtimeSessionDisconnected,realtimeSessionError:LYRA_DEFAULT_realtimeSessionError,realtimeSessionInterrupt:LYRA_DEFAULT_realtimeSessionInterrupt,realtimeSessionLabel:LYRA_DEFAULT_realtimeSessionLabel,realtimeSessionMute:LYRA_DEFAULT_realtimeSessionMute,realtimeSessionReconnecting:LYRA_DEFAULT_realtimeSessionReconnecting,realtimeSessionUnmute:LYRA_DEFAULT_realtimeSessionUnmute}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["entries"])}static{this.appendOrderedCollectionProperties=Object.freeze(["entries"])}static{this.styles=[LyraElement.styles,styles]}get state(){return this._state}set state(next){const normalized=CONNECTION_STATE.normalize(next),old=this._state;old!==normalized&&(this._state=normalized,this.requestUpdate("state",old))}get voiceState(){return this._voiceState}set voiceState(next){const normalized=VOICE_STATE.normalize(next),old=this._voiceState;old!==normalized&&(this._voiceState=normalized,this.requestUpdate("voiceState",old))}constructor(){super(),this._state="disconnected",this._voiceState="idle",this.level=null,this.stream=null,this.sessionId="",this.entries=[],this.muted=!1,this.withoutCapture=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.suppressNextStateAnnouncement=!0,this.containNativeEvent=event=>{event.stopPropagation()},this.requestUpdate("state",void 0),this.requestUpdate("voiceState",void 0)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextStateAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){super.disconnectedCallback(),this.suppressNextStateAnnouncement=!0}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed);const stateChanged=changed.has("state"),captureHidden=changed.has("withoutCapture")&&changed.get("withoutCapture")===!1&&this.withoutCapture,captureDisabled=changed.has("muted")&&changed.get("muted")===!1&&this.muted;if(!stateChanged&&!captureHidden&&!captureDisabled)return;const focused=this.shadowRoot?shadowFocusTarget(this):activeElementIn(this.ownerDocument),focusedPart=focused?.getAttribute("part")??null;if(!focused)return;if(captureDisabled&&!stateChanged&&!captureHidden&&focusedPart==="capture"){this.transferActionFocus={target:"mute",origin:focused};return}(captureHidden&&!stateChanged?focusedPart==="capture":focused.closest('[part="controls"]')!==null||focusedPart==="connect"||focusedPart==="disconnect"||focusedPart==="mute"||focusedPart==="interrupt"||focusedPart==="capture")&&(this.transferActionFocus={target:"connection",origin:focused})}updated(changed){super.updated(changed);const stateChanged=changed.has("state");stateChanged&&!this.suppressNextStateAnnouncement&&(this.state==="error"?this.announcements.announceAssertive(this.localize("realtimeSessionConnectionFailed")):this.announcements.announcePolite(this.stateLabel()));const pending=this.transferActionFocus;if((stateChanged||changed.has("withoutCapture")||changed.has("muted"))&&pending){this.transferActionFocus=void 0;const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);if((internalActive===null||internalActive===pending.origin)&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body)){const selector=pending.target==="mute"?'[part="mute"]':'[part="connect"], [part="disconnect"]';this.renderRoot.querySelector(selector)?.focus()}}this.suppressNextStateAnnouncement=!1}stateLabel(){switch(this.state){case"disconnected":return this.localize("realtimeSessionDisconnected");case"connecting":return this.localize("realtimeSessionConnecting");case"connected":return this.localize("realtimeSessionConnected");case"reconnecting":return this.localize("realtimeSessionReconnecting");case"error":return this.localize("realtimeSessionError")}}render(){const label=this.getAttribute("aria-label")??(this.label==null?this.localize("realtimeSessionLabel"):this.label),active=this.state==="connected",safeLevel=this.level==null?null:finiteRange(this.level,0,0,1);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{LyraElement}from"../../../internal/lyra-element.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import"../audio-visualizer/audio-visualizer.class.js";import"../push-to-talk/push-to-talk.class.js";import"../transcript-feed/transcript-feed.class.js";import"../../overlays/badge/badge.class.js";import{styles}from"./realtime-session.styles.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_realtimeSessionConnect,LYRA_DEFAULT_realtimeSessionConnected,LYRA_DEFAULT_realtimeSessionConnecting,LYRA_DEFAULT_realtimeSessionConnectionFailed,LYRA_DEFAULT_realtimeSessionDisconnect,LYRA_DEFAULT_realtimeSessionDisconnected,LYRA_DEFAULT_realtimeSessionError,LYRA_DEFAULT_realtimeSessionInterrupt,LYRA_DEFAULT_realtimeSessionLabel,LYRA_DEFAULT_realtimeSessionMute,LYRA_DEFAULT_realtimeSessionReconnecting,LYRA_DEFAULT_realtimeSessionUnmute}from"../../../internal/default-strings/conversation.generated.js";const CONNECTION_STATE=literalSetConverter(["disconnected","connecting","connected","reconnecting","error"],"disconnected"),VOICE_STATE=literalSetConverter(["idle","listening","thinking","speaking"],"idle"),STATE_VARIANT={disconnected:"neutral",connecting:"brand",connected:"success",reconnecting:"warning",error:"danger"};class LyraRealtimeSession extends LyraElement{static{this.defaultStrings={...super.defaultStrings,realtimeSessionConnect:LYRA_DEFAULT_realtimeSessionConnect,realtimeSessionConnected:LYRA_DEFAULT_realtimeSessionConnected,realtimeSessionConnecting:LYRA_DEFAULT_realtimeSessionConnecting,realtimeSessionConnectionFailed:LYRA_DEFAULT_realtimeSessionConnectionFailed,realtimeSessionDisconnect:LYRA_DEFAULT_realtimeSessionDisconnect,realtimeSessionDisconnected:LYRA_DEFAULT_realtimeSessionDisconnected,realtimeSessionError:LYRA_DEFAULT_realtimeSessionError,realtimeSessionInterrupt:LYRA_DEFAULT_realtimeSessionInterrupt,realtimeSessionLabel:LYRA_DEFAULT_realtimeSessionLabel,realtimeSessionMute:LYRA_DEFAULT_realtimeSessionMute,realtimeSessionReconnecting:LYRA_DEFAULT_realtimeSessionReconnecting,realtimeSessionUnmute:LYRA_DEFAULT_realtimeSessionUnmute}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["entries"])}static{this.appendOrderedCollectionProperties=Object.freeze(["entries"])}static{this.styles=[LyraElement.styles,styles]}get state(){return this._state}set state(next){const normalized=CONNECTION_STATE.normalize(next),old=this._state;old!==normalized&&(this._state=normalized,this.requestUpdate("state",old))}get voiceState(){return this._voiceState}set voiceState(next){const normalized=VOICE_STATE.normalize(next),old=this._voiceState;old!==normalized&&(this._voiceState=normalized,this.requestUpdate("voiceState",old))}constructor(){super(),this._state="disconnected",this._voiceState="idle",this.level=null,this.stream=null,this.sessionId="",this.entries=[],this.muted=!1,this.withoutCapture=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.suppressNextStateAnnouncement=!0,this.containNativeEvent=event=>{event.stopPropagation()},this.requestUpdate("state",void 0),this.requestUpdate("voiceState",void 0)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.suppressNextStateAnnouncement=!0,this.requestUpdate())}disconnectedCallback(){super.disconnectedCallback(),this.suppressNextStateAnnouncement=!0}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed);const stateChanged=changed.has("state"),captureHidden=changed.has("withoutCapture")&&changed.get("withoutCapture")===!1&&this.withoutCapture,captureDisabled=changed.has("muted")&&changed.get("muted")===!1&&this.muted;if(!stateChanged&&!captureHidden&&!captureDisabled)return;const focused=this.shadowRoot?shadowFocusTarget(this):activeElementIn(this.ownerDocument),focusedPart=focused?.getAttribute("part")??null;if(!focused)return;if(captureDisabled&&!stateChanged&&!captureHidden&&focusedPart==="capture"){this.transferActionFocus={target:"mute",origin:focused};return}(captureHidden&&!stateChanged?focusedPart==="capture":focused.closest('[part="controls"]')!==null||focusedPart==="connect"||focusedPart==="disconnect"||focusedPart==="mute"||focusedPart==="interrupt"||focusedPart==="capture")&&(this.transferActionFocus={target:"connection",origin:focused})}updated(changed){super.updated(changed);const stateChanged=changed.has("state");stateChanged&&!this.suppressNextStateAnnouncement&&(this.state==="error"?this.announcements.announceAssertive(this.localize("realtimeSessionConnectionFailed")):this.announcements.announcePolite(this.stateLabel()));const pending=this.transferActionFocus;if((stateChanged||changed.has("withoutCapture")||changed.has("muted"))&&pending){this.transferActionFocus=void 0;const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument);if((internalActive===null||internalActive===pending.origin)&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body)){const selector=pending.target==="mute"?'[part="mute"]':'[part="connect"], [part="disconnect"]';this.renderRoot.querySelector(selector)?.focus()}}this.suppressNextStateAnnouncement=!1}stateLabel(){switch(this.state){case"disconnected":return this.localize("realtimeSessionDisconnected");case"connecting":return this.localize("realtimeSessionConnecting");case"connected":return this.localize("realtimeSessionConnected");case"reconnecting":return this.localize("realtimeSessionReconnecting");case"error":return this.localize("realtimeSessionError")}}render(){const label=this.getAttribute("aria-label")??(this.label==null?this.localize("realtimeSessionLabel"):this.label),active=this.state==="connected",safeLevel=this.level==null?null:finiteRange(this.level,0,0,1);return html`
|
|
2
2
|
<section
|
|
3
3
|
part="base"
|
|
4
4
|
aria-label=${label}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{composedParentElement}from"../../../internal/active-element.js";import{isEditableKeyEventTarget}from"../../../internal/hotkey.js";import{RovingToolbarController,leaseTabIndex,observeStopChanges}from"../../../internal/roving-toolbar.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets,isSemanticActionElement}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{finiteAdd,finiteMidpoint,finiteRange}from"../../../internal/numbers.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./selection-toolbar.styles.js";import{isLibraryPromotedAndShowing,needsTopLayerEscape,promoteToTopLayer,stripStaleTopLayer}from"../../../internal/top-layer-escape.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings.generated.js";const COMPOSITE_ROLES=new Set(["menu","menubar","listbox","tree","treegrid","grid","tablist","radiogroup"]);function insideComposite(element,root){for(let node=composedParentElement(element);node&&node!==root;node=composedParentElement(node))if(COMPOSITE_ROLES.has(node.getAttribute("role")??""))return!0;return!1}const SELECTION_ACTIONS=["ask","quote","cite","copy"],DEFAULT_PLACEMENT_GAP_PX=8;class LyraSelectionToolbar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}constructor(){super(),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="toolbar"][role="toolbar"]')),this.open=!1,this.text="",this.anchor=null,this.rect=null,this.actions=["ask","quote","cite","copy"],this.accessibleLabel=null,this.copyFailed=!1,this.activeActionIndex=0,this.lifecycleGeneration=0,this.positioningGeneration=0,this.rovingGeneration=0,this.managedActionStops=new Set,this.actionTabIndexLeases=new WeakMap,this.rovingToolbar=new RovingToolbarController,this.onActionsSlotChange=()=>{this.syncRovingStops()},this.onActionMutations=records=>{this.syncRovingStops()},this.onToolbarFocusIn=event=>{const buttons=this.actionButtons(),path=event.composedPath(),index=buttons.findIndex(button=>path.includes(button));if(index<0){this.focusedAction=void 0;return}const origin=path[0],stop=origin?.nodeType===1&&typeof origin.focus=="function"?origin:buttons[index],toolbar=this.toolbar,repair=stop&&toolbar?captureComposedFocusRepair(stop,toolbar):null;this.focusedAction=stop&&repair?{action:this.actionForStop(stop),index,repair,stop}:void 0,this.syncRovingStops(index)},this.containNativeEvent=event=>{event.stopPropagation()},this.onToolbarFocusOut=event=>{const destination=event.relatedTarget;destination&&destination.nodeType===1&&!composedContains(this,destination)&&(this.focusedAction=void 0)},this.onToolbarKeyDown=event=>{if(event.defaultPrevented||isEditableKeyEventTarget(event))return;const buttons=this.actionButtons();if(buttons.length===0)return;const path=event.composedPath(),originIndex=buttons.findIndex(button=>path.includes(button));if(originIndex<0&&path[0]!==event.currentTarget)return;const currentIndex=originIndex>=0?originIndex:this.activeActionIndex,next=this.rovingToolbar.move(event,buttons.length,currentIndex,this.effectiveDirection);if(next===null)return;event.preventDefault(),this.focusedAction=void 0;const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView;this.syncRovingStops(next).then(button=>{!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)||button.focus()})},this.updateToolbarPosition=()=>{const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const viewport=this.viewportBounds(view),maxEdge=finiteMidpoint(0,Math.min(viewport.width,viewport.height)),gap=finiteRange(this.placementGapPx(),DEFAULT_PLACEMENT_GAP_PX,0,maxEdge),edge=gap,fallbackInline=finiteMidpoint(viewport.left,viewport.right),rect=this.rect?this.safeRect(this.rect):{left:fallbackInline,top:viewport.top,width:0,height:0,right:fallbackInline,bottom:viewport.top,inlineCenter:fallbackInline},doubleEdge=finiteAdd(edge,edge),maxInlineSize=finiteRange(finiteAdd(viewport.width,-doubleEdge),0,0,Number.MAX_VALUE),maxBlockSize=finiteRange(finiteAdd(viewport.height,-doubleEdge),0,0,Number.MAX_VALUE);toolbar.style.setProperty("--_lr-selection-toolbar-max-inline-size",this.px(maxInlineSize)),toolbar.style.setProperty("--_lr-selection-toolbar-max-block-size",this.px(maxBlockSize));const width=finiteRange(toolbar.offsetWidth,0,0,Number.MAX_VALUE),height=finiteRange(toolbar.offsetHeight,0,0,Number.MAX_VALUE),desiredInline=finiteRange(rect.inlineCenter,viewport.left,viewport.left,viewport.right),anchorBlock=finiteRange(rect.top,viewport.top,viewport.top,viewport.bottom),desiredLeft=finiteAdd(desiredInline,-finiteMidpoint(0,width)),minLeft=finiteAdd(viewport.left,edge),maxLeft=Math.max(minLeft,finiteAdd(finiteAdd(viewport.right,-width),-edge)),left=finiteRange(desiredLeft,minLeft,minLeft,maxLeft),above=finiteAdd(finiteAdd(rect.top,-height),-gap),below=finiteAdd(rect.bottom,gap),minTop=finiteAdd(viewport.top,edge),desiredTop=above>=minTop?above:below,maxTop=Math.max(minTop,finiteAdd(finiteAdd(viewport.bottom,-height),-edge)),top=finiteRange(desiredTop,minTop,minTop,maxTop),logicalInline=this.effectiveDirection==="rtl"?finiteAdd(viewport.layoutWidth,-desiredInline):desiredInline;toolbar.style.setProperty("--_lr-selection-toolbar-inline-start",this.px(logicalInline)),toolbar.style.setProperty("--_lr-selection-toolbar-block-start",this.px(anchorBlock)),toolbar.style.setProperty("--_lr-selection-toolbar-inline-shift",this.px(finiteAdd(left,-desiredLeft))),toolbar.style.setProperty("--_lr-selection-toolbar-block-shift",this.px(finiteAdd(top,-finiteAdd(anchorBlock,-height)))),toolbar.toggleAttribute("data-positioned",!0)},new GlassScrollLayer(this,'[part="toolbar"]')}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["anchor","actions"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-action"])}get effectiveActions(){const seen=new Set,actions=[];for(const value of this.actions){if(typeof value!="string"||!SELECTION_ACTIONS.includes(value)||seen.has(value))continue;const action=value;seen.add(action),actions.push(action)}return actions}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.syncOpenLifecycle(),this.syncRovingStops())}disconnectedCallback(){this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning()}willUpdate(changed){if(super.willUpdate(changed),this.copyFailed&&(changed.has("text")||changed.has("open")&&this.open)&&(this.copyFailed=!1),!changed.has("actions"))return;const active=deepActiveElementIn(this.ownerDocument),toolbar=this.toolbar;if(!active||!toolbar)return;const index=this.actionButtons().indexOf(active);if(index<0)return;const repair=captureComposedFocusRepair(active,toolbar);repair&&(this.pendingActionFocus={action:this.actionForStop(active),index,repair,stop:active})}updated(changed){if(super.updated(changed),this.open&&this.text&&this.escapeTrappingAncestor(),(changed.has("open")||changed.has("text"))&&this.syncOpenLifecycle(),this.open&&this.text&&(changed.has("rect")||changed.has("actions"))&&this.updateToolbarPosition(),this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){const pending=changed.has("actions")?this.pendingActionFocus:void 0;if(this.pendingActionFocus=void 0,!pending){this.syncRovingStops();return}this.syncRovingStops(pending.index,pending)}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}if(!this.open||!this.text){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}this.overlay?.isActive()?this.overlay.resume():this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss()}),this.startPositioning()}dismiss(){this.open&&(this.open=!1,this.emit("lr-dismiss",null))}async activate(action){const text=this.text,anchor=this.anchor,generation=this.lifecycleGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;if(this.copyFailed=!1,action==="copy"){const outcome=await writeClipboardText(owner,text);if(!this.isCurrentLifecycle(generation,owner))return;if(!outcome.ok){this.copyFailed=!0,this.sink?.announce(this.localize("copyFailed")),this.emit("lr-error",null),this.emit("lr-copy-error",outcome);return}this.emit("lr-copy",outcome)}this.isCurrentLifecycle(generation,owner)&&this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){const toolbar=this.toolbar;return toolbar?collectComposedFocusTargets(toolbar,{mode:"programmatic",includeRoot:!1}).elements.filter(button=>(!!isSemanticActionElement(button)||this.hasAuthoredActionTabIndex(button))&&!insideComposite(button,toolbar)):[]}actionRoots(){const builtIn=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)],slot=this.renderRoot.querySelector('slot[name="actions"]');return[...builtIn,...slot?.assignedElements({flatten:!0})??[]]}actionForStop(stop){const action=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)].find(button=>composedContains(button,stop))?.getAttribute("data-action");return action&&SELECTION_ACTIONS.includes(action)?action:void 0}ownsActionButton(button){return this.actionButtons().includes(button)}async syncRovingStops(preferredIndex=this.activeActionIndex,requestedRepair){const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView,request=++this.rovingGeneration;if(!owner||!this.isConnected)return;const roots=this.actionRoots();await Promise.all(roots.map(root=>root.updateComplete)),await Promise.resolve();const buttons=this.actionButtons();if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)))return;const focused=requestedRepair??this.focusedAction,exactIndex=focused?buttons.indexOf(focused.stop):-1,retainedIndex=exactIndex>=0?exactIndex:focused?.action?buttons.findIndex(button=>this.actionForStop(button)===focused.action):-1,targetIndex=retainedIndex>=0?retainedIndex:Math.min(focused?Math.max(0,focused.index):Math.max(0,preferredIndex),Math.max(0,buttons.length-1));this.setRovingStops(buttons,targetIndex);const target=buttons[targetIndex];return focused&&target!==focused.stop&&(applyComposedFocusRepair(focused.repair,target??this.toolbar??null),this.focusedAction===focused&&(this.focusedAction=void 0)),target}hasAuthoredActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);return lease?lease.hasAuthored(button):button.hasAttribute("tabindex")}writeActionTabIndex(button,tabIndex){let lease=this.actionTabIndexLeases.get(button);lease||this.actionTabIndexLeases.set(button,lease=leaseTabIndex()),lease.set(button,tabIndex)}releaseActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);lease&&(lease.release(),this.actionTabIndexLeases.delete(button))}releaseManagedActionStops(){for(const button of this.managedActionStops)this.releaseActionTabIndex(button);this.managedActionStops.clear()}setRovingStops(buttons,index){this.actionObserver?.disconnect();for(const previous of this.managedActionStops)buttons.includes(previous)||this.releaseActionTabIndex(previous);this.activeActionIndex=buttons.length===0?0:Math.min(Math.max(0,index),buttons.length-1),buttons.forEach((button,buttonIndex)=>{this.writeActionTabIndex(button,buttonIndex===this.activeActionIndex?0:-1)}),this.managedActionStops=new Set(buttons),this.observeActionChanges(buttons)}observeActionChanges(buttons){this.actionObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver,toolbar=this.toolbar;if(!Observer||!toolbar||!this.isConnected){this.actionObserver=void 0;return}const observer=new Observer(this.onActionMutations),roots=new Set([toolbar,...this.actionRoots()]);for(const button of buttons){let current=button;for(;current&¤t!==this;){const root=current.getRootNode();root.nodeType===11&&"host"in root&&roots.add(root),current=composedParentElement(current)}}const options=observeStopChanges();for(const root of roots)observer.observe(root,options);this.actionObserver=observer}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}actionLabel(action){switch(action){case"ask":return this.localize("selectionAsk");case"quote":return this.localize("selectionQuote");case"cite":return this.localize("selectionCite");case"copy":return this.localize(this.copyFailed?"copyFailed":"copy")}}safeRect(rect){const left=finiteRange(rect.left,0,-Number.MAX_VALUE,Number.MAX_VALUE),top=finiteRange(rect.top,0,-Number.MAX_VALUE,Number.MAX_VALUE),width=finiteRange(rect.width,0,0,Number.MAX_VALUE),height=finiteRange(rect.height,0,0,Number.MAX_VALUE),right=finiteAdd(left,width),bottom=finiteAdd(top,height);return{left,top,width,height,right,bottom,inlineCenter:finiteMidpoint(left,right)}}viewportBounds(view){const layoutWidth=finiteRange(view.innerWidth,0,0,Number.MAX_VALUE),layoutHeight=finiteRange(view.innerHeight,0,0,Number.MAX_VALUE),viewport=view.visualViewport,left=finiteRange(viewport?.offsetLeft??0,0,0,Number.MAX_VALUE),top=finiteRange(viewport?.offsetTop??0,0,0,Number.MAX_VALUE),width=finiteRange(viewport?.width??layoutWidth,layoutWidth,0,Number.MAX_VALUE),height=finiteRange(viewport?.height??layoutHeight,layoutHeight,0,Number.MAX_VALUE);return{left,top,width,height,right:finiteAdd(left,width),bottom:finiteAdd(top,height),layoutWidth}}px(value){return`${finiteRange(value,0,-Number.MAX_VALUE,Number.MAX_VALUE)}px`}placementGapPx(){const computed=this.ownerDocument.defaultView?.getComputedStyle(this),publicValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-selection-toolbar-placement-gap").trim()??"",{host:this});if(publicValue!==void 0)return finiteRange(publicValue,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE);const tokenValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-space-s").trim()??"",{host:this});return finiteRange(tokenValue??DEFAULT_PLACEMENT_GAP_PX,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE)}startPositioning(){this.retirePositioning();const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration,update=()=>{generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar||this.updateToolbarPosition()};let resizeFrame;const scheduleResizeUpdate=()=>{resizeFrame===void 0&&(resizeFrame=view.requestAnimationFrame(()=>{resizeFrame=void 0,update()}))},observer=typeof view.ResizeObserver>"u"?void 0:new view.ResizeObserver(scheduleResizeUpdate);observer?.observe(toolbar),view.addEventListener("resize",update),view.visualViewport?.addEventListener("resize",update),view.visualViewport?.addEventListener("scroll",update),update(),this.stopPositioning=()=>{observer?.disconnect(),resizeFrame!==void 0&&view.cancelAnimationFrame(resizeFrame),resizeFrame=void 0,view.removeEventListener("resize",update),view.visualViewport?.removeEventListener("resize",update),view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0,stop?.()}escapeTrappingAncestor(){const toolbar=this.toolbar;!toolbar||isLibraryPromotedAndShowing(toolbar)||(needsTopLayerEscape(toolbar)?promoteToTopLayer(toolbar):stripStaleTopLayer(toolbar))}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel??(this.label==null?this.localize("selectionToolbarLabel"):this.label);return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{composedParentElement}from"../../../internal/active-element.js";import{isEditableKeyEventTarget}from"../../../internal/hotkey.js";import{RovingToolbarController,leaseTabIndex,observeStopChanges}from"../../../internal/roving-toolbar.js";import{applyComposedFocusRepair,captureComposedFocusRepair,collectComposedFocusTargets,isSemanticActionElement}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{finiteAdd,finiteMidpoint,finiteRange}from"../../../internal/numbers.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./selection-toolbar.styles.js";import{isLibraryPromotedAndShowing,needsTopLayerEscape,promoteToTopLayer,stripStaleTopLayer}from"../../../internal/top-layer-escape.js";import{LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const COMPOSITE_ROLES=new Set(["menu","menubar","listbox","tree","treegrid","grid","tablist","radiogroup"]);function insideComposite(element,root){for(let node=composedParentElement(element);node&&node!==root;node=composedParentElement(node))if(COMPOSITE_ROLES.has(node.getAttribute("role")??""))return!0;return!1}const SELECTION_ACTIONS=["ask","quote","cite","copy"],DEFAULT_PLACEMENT_GAP_PX=8;class LyraSelectionToolbar extends LyraElement{static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}constructor(){super(),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="toolbar"][role="toolbar"]')),this.open=!1,this.text="",this.anchor=null,this.rect=null,this.actions=["ask","quote","cite","copy"],this.accessibleLabel=null,this.copyFailed=!1,this.activeActionIndex=0,this.lifecycleGeneration=0,this.positioningGeneration=0,this.rovingGeneration=0,this.managedActionStops=new Set,this.actionTabIndexLeases=new WeakMap,this.rovingToolbar=new RovingToolbarController,this.onActionsSlotChange=()=>{this.syncRovingStops()},this.onActionMutations=records=>{this.syncRovingStops()},this.onToolbarFocusIn=event=>{const buttons=this.actionButtons(),path=event.composedPath(),index=buttons.findIndex(button=>path.includes(button));if(index<0){this.focusedAction=void 0;return}const origin=path[0],stop=origin?.nodeType===1&&typeof origin.focus=="function"?origin:buttons[index],toolbar=this.toolbar,repair=stop&&toolbar?captureComposedFocusRepair(stop,toolbar):null;this.focusedAction=stop&&repair?{action:this.actionForStop(stop),index,repair,stop}:void 0,this.syncRovingStops(index)},this.containNativeEvent=event=>{event.stopPropagation()},this.onToolbarFocusOut=event=>{const destination=event.relatedTarget;destination&&destination.nodeType===1&&!composedContains(this,destination)&&(this.focusedAction=void 0)},this.onToolbarKeyDown=event=>{if(event.defaultPrevented||isEditableKeyEventTarget(event))return;const buttons=this.actionButtons();if(buttons.length===0)return;const path=event.composedPath(),originIndex=buttons.findIndex(button=>path.includes(button));if(originIndex<0&&path[0]!==event.currentTarget)return;const currentIndex=originIndex>=0?originIndex:this.activeActionIndex,next=this.rovingToolbar.move(event,buttons.length,currentIndex,this.effectiveDirection);if(next===null)return;event.preventDefault(),this.focusedAction=void 0;const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView;this.syncRovingStops(next).then(button=>{!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)||button.focus()})},this.updateToolbarPosition=()=>{const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const viewport=this.viewportBounds(view),maxEdge=finiteMidpoint(0,Math.min(viewport.width,viewport.height)),gap=finiteRange(this.placementGapPx(),DEFAULT_PLACEMENT_GAP_PX,0,maxEdge),edge=gap,fallbackInline=finiteMidpoint(viewport.left,viewport.right),rect=this.rect?this.safeRect(this.rect):{left:fallbackInline,top:viewport.top,width:0,height:0,right:fallbackInline,bottom:viewport.top,inlineCenter:fallbackInline},doubleEdge=finiteAdd(edge,edge),maxInlineSize=finiteRange(finiteAdd(viewport.width,-doubleEdge),0,0,Number.MAX_VALUE),maxBlockSize=finiteRange(finiteAdd(viewport.height,-doubleEdge),0,0,Number.MAX_VALUE);toolbar.style.setProperty("--_lr-selection-toolbar-max-inline-size",this.px(maxInlineSize)),toolbar.style.setProperty("--_lr-selection-toolbar-max-block-size",this.px(maxBlockSize));const width=finiteRange(toolbar.offsetWidth,0,0,Number.MAX_VALUE),height=finiteRange(toolbar.offsetHeight,0,0,Number.MAX_VALUE),desiredInline=finiteRange(rect.inlineCenter,viewport.left,viewport.left,viewport.right),anchorBlock=finiteRange(rect.top,viewport.top,viewport.top,viewport.bottom),desiredLeft=finiteAdd(desiredInline,-finiteMidpoint(0,width)),minLeft=finiteAdd(viewport.left,edge),maxLeft=Math.max(minLeft,finiteAdd(finiteAdd(viewport.right,-width),-edge)),left=finiteRange(desiredLeft,minLeft,minLeft,maxLeft),above=finiteAdd(finiteAdd(rect.top,-height),-gap),below=finiteAdd(rect.bottom,gap),minTop=finiteAdd(viewport.top,edge),desiredTop=above>=minTop?above:below,maxTop=Math.max(minTop,finiteAdd(finiteAdd(viewport.bottom,-height),-edge)),top=finiteRange(desiredTop,minTop,minTop,maxTop),logicalInline=this.effectiveDirection==="rtl"?finiteAdd(viewport.layoutWidth,-desiredInline):desiredInline;toolbar.style.setProperty("--_lr-selection-toolbar-inline-start",this.px(logicalInline)),toolbar.style.setProperty("--_lr-selection-toolbar-block-start",this.px(anchorBlock)),toolbar.style.setProperty("--_lr-selection-toolbar-inline-shift",this.px(finiteAdd(left,-desiredLeft))),toolbar.style.setProperty("--_lr-selection-toolbar-block-shift",this.px(finiteAdd(top,-finiteAdd(anchorBlock,-height)))),toolbar.toggleAttribute("data-positioned",!0)},new GlassScrollLayer(this,'[part="toolbar"]')}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["anchor","actions"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-action"])}get effectiveActions(){const seen=new Set,actions=[];for(const value of this.actions){if(typeof value!="string"||!SELECTION_ACTIONS.includes(value)||seen.has(value))continue;const action=value;seen.add(action),actions.push(action)}return actions}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.hasUpdated&&(this.syncOpenLifecycle(),this.syncRovingStops())}disconnectedCallback(){this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.lifecycleGeneration++,this.rovingGeneration++,this.pendingActionFocus=void 0,this.focusedAction=void 0,this.actionObserver?.disconnect(),this.actionObserver=void 0,this.releaseManagedActionStops(),this.retirePositioning()}willUpdate(changed){if(super.willUpdate(changed),this.copyFailed&&(changed.has("text")||changed.has("open")&&this.open)&&(this.copyFailed=!1),!changed.has("actions"))return;const active=deepActiveElementIn(this.ownerDocument),toolbar=this.toolbar;if(!active||!toolbar)return;const index=this.actionButtons().indexOf(active);if(index<0)return;const repair=captureComposedFocusRepair(active,toolbar);repair&&(this.pendingActionFocus={action:this.actionForStop(active),index,repair,stop:active})}updated(changed){if(super.updated(changed),this.open&&this.text&&this.escapeTrappingAncestor(),(changed.has("open")||changed.has("text"))&&this.syncOpenLifecycle(),this.open&&this.text&&(changed.has("rect")||changed.has("actions"))&&this.updateToolbarPosition(),this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){const pending=changed.has("actions")?this.pendingActionFocus:void 0;if(this.pendingActionFocus=void 0,!pending){this.syncRovingStops();return}this.syncRovingStops(pending.index,pending)}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}if(!this.open||!this.text){this.retirePositioning(),this.overlay?.deactivate(),this.overlay=void 0,this.releaseManagedActionStops();return}this.overlay?.isActive()?this.overlay.resume():this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss()}),this.startPositioning()}dismiss(){this.open&&(this.open=!1,this.emit("lr-dismiss",null))}async activate(action){const text=this.text,anchor=this.anchor,generation=this.lifecycleGeneration,owner=this.isConnected?this.ownerDocument.defaultView:null;if(this.copyFailed=!1,action==="copy"){const outcome=await writeClipboardText(owner,text);if(!this.isCurrentLifecycle(generation,owner))return;if(!outcome.ok){this.copyFailed=!0,this.sink?.announce(this.localize("copyFailed")),this.emit("lr-error",null),this.emit("lr-copy-error",outcome);return}this.emit("lr-copy",outcome)}this.isCurrentLifecycle(generation,owner)&&this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){const toolbar=this.toolbar;return toolbar?collectComposedFocusTargets(toolbar,{mode:"programmatic",includeRoot:!1}).elements.filter(button=>(!!isSemanticActionElement(button)||this.hasAuthoredActionTabIndex(button))&&!insideComposite(button,toolbar)):[]}actionRoots(){const builtIn=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)],slot=this.renderRoot.querySelector('slot[name="actions"]');return[...builtIn,...slot?.assignedElements({flatten:!0})??[]]}actionForStop(stop){const action=[...this.renderRoot.querySelectorAll(`${tag("button")}[data-action]`)].find(button=>composedContains(button,stop))?.getAttribute("data-action");return action&&SELECTION_ACTIONS.includes(action)?action:void 0}ownsActionButton(button){return this.actionButtons().includes(button)}async syncRovingStops(preferredIndex=this.activeActionIndex,requestedRepair){const generation=this.lifecycleGeneration,owner=this.ownerDocument.defaultView,request=++this.rovingGeneration;if(!owner||!this.isConnected)return;const roots=this.actionRoots();await Promise.all(roots.map(root=>root.updateComplete)),await Promise.resolve();const buttons=this.actionButtons();if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.ownsActionButton(button)))return;const focused=requestedRepair??this.focusedAction,exactIndex=focused?buttons.indexOf(focused.stop):-1,retainedIndex=exactIndex>=0?exactIndex:focused?.action?buttons.findIndex(button=>this.actionForStop(button)===focused.action):-1,targetIndex=retainedIndex>=0?retainedIndex:Math.min(focused?Math.max(0,focused.index):Math.max(0,preferredIndex),Math.max(0,buttons.length-1));this.setRovingStops(buttons,targetIndex);const target=buttons[targetIndex];return focused&&target!==focused.stop&&(applyComposedFocusRepair(focused.repair,target??this.toolbar??null),this.focusedAction===focused&&(this.focusedAction=void 0)),target}hasAuthoredActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);return lease?lease.hasAuthored(button):button.hasAttribute("tabindex")}writeActionTabIndex(button,tabIndex){let lease=this.actionTabIndexLeases.get(button);lease||this.actionTabIndexLeases.set(button,lease=leaseTabIndex()),lease.set(button,tabIndex)}releaseActionTabIndex(button){const lease=this.actionTabIndexLeases.get(button);lease&&(lease.release(),this.actionTabIndexLeases.delete(button))}releaseManagedActionStops(){for(const button of this.managedActionStops)this.releaseActionTabIndex(button);this.managedActionStops.clear()}setRovingStops(buttons,index){this.actionObserver?.disconnect();for(const previous of this.managedActionStops)buttons.includes(previous)||this.releaseActionTabIndex(previous);this.activeActionIndex=buttons.length===0?0:Math.min(Math.max(0,index),buttons.length-1),buttons.forEach((button,buttonIndex)=>{this.writeActionTabIndex(button,buttonIndex===this.activeActionIndex?0:-1)}),this.managedActionStops=new Set(buttons),this.observeActionChanges(buttons)}observeActionChanges(buttons){this.actionObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver,toolbar=this.toolbar;if(!Observer||!toolbar||!this.isConnected){this.actionObserver=void 0;return}const observer=new Observer(this.onActionMutations),roots=new Set([toolbar,...this.actionRoots()]);for(const button of buttons){let current=button;for(;current&¤t!==this;){const root=current.getRootNode();root.nodeType===11&&"host"in root&&roots.add(root),current=composedParentElement(current)}}const options=observeStopChanges();for(const root of roots)observer.observe(root,options);this.actionObserver=observer}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}actionLabel(action){switch(action){case"ask":return this.localize("selectionAsk");case"quote":return this.localize("selectionQuote");case"cite":return this.localize("selectionCite");case"copy":return this.localize(this.copyFailed?"copyFailed":"copy")}}safeRect(rect){const left=finiteRange(rect.left,0,-Number.MAX_VALUE,Number.MAX_VALUE),top=finiteRange(rect.top,0,-Number.MAX_VALUE,Number.MAX_VALUE),width=finiteRange(rect.width,0,0,Number.MAX_VALUE),height=finiteRange(rect.height,0,0,Number.MAX_VALUE),right=finiteAdd(left,width),bottom=finiteAdd(top,height);return{left,top,width,height,right,bottom,inlineCenter:finiteMidpoint(left,right)}}viewportBounds(view){const layoutWidth=finiteRange(view.innerWidth,0,0,Number.MAX_VALUE),layoutHeight=finiteRange(view.innerHeight,0,0,Number.MAX_VALUE),viewport=view.visualViewport,left=finiteRange(viewport?.offsetLeft??0,0,0,Number.MAX_VALUE),top=finiteRange(viewport?.offsetTop??0,0,0,Number.MAX_VALUE),width=finiteRange(viewport?.width??layoutWidth,layoutWidth,0,Number.MAX_VALUE),height=finiteRange(viewport?.height??layoutHeight,layoutHeight,0,Number.MAX_VALUE);return{left,top,width,height,right:finiteAdd(left,width),bottom:finiteAdd(top,height),layoutWidth}}px(value){return`${finiteRange(value,0,-Number.MAX_VALUE,Number.MAX_VALUE)}px`}placementGapPx(){const computed=this.ownerDocument.defaultView?.getComputedStyle(this),publicValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-selection-toolbar-placement-gap").trim()??"",{host:this});if(publicValue!==void 0)return finiteRange(publicValue,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE);const tokenValue=resolveCssTokenLength(computed?.getPropertyValue("--lr-space-s").trim()??"",{host:this});return finiteRange(tokenValue??DEFAULT_PLACEMENT_GAP_PX,DEFAULT_PLACEMENT_GAP_PX,0,Number.MAX_VALUE)}startPositioning(){this.retirePositioning();const toolbar=this.toolbar,view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration,update=()=>{generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar||this.updateToolbarPosition()};let resizeFrame;const scheduleResizeUpdate=()=>{resizeFrame===void 0&&(resizeFrame=view.requestAnimationFrame(()=>{resizeFrame=void 0,update()}))},observer=typeof view.ResizeObserver>"u"?void 0:new view.ResizeObserver(scheduleResizeUpdate);observer?.observe(toolbar),view.addEventListener("resize",update),view.visualViewport?.addEventListener("resize",update),view.visualViewport?.addEventListener("scroll",update),update(),this.stopPositioning=()=>{observer?.disconnect(),resizeFrame!==void 0&&view.cancelAnimationFrame(resizeFrame),resizeFrame=void 0,view.removeEventListener("resize",update),view.visualViewport?.removeEventListener("resize",update),view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0,stop?.()}escapeTrappingAncestor(){const toolbar=this.toolbar;!toolbar||isLibraryPromotedAndShowing(toolbar)||(needsTopLayerEscape(toolbar)?promoteToTopLayer(toolbar):stripStaleTopLayer(toolbar))}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel??(this.label==null?this.localize("selectionToolbarLabel"):this.label);return html`<div
|
|
2
2
|
part="toolbar"
|
|
3
3
|
role="toolbar"
|
|
4
4
|
aria-label=${label}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../utility/live-region/live-region.class.js";import{finiteDuration,MAX_TIMEOUT_MS}from"../../../internal/numbers.js";import{OwnedTimeout}from"../../../internal/owned-timer.js";import{literalSetConverter}from"../../../internal/converters.js";import{styles}from"./stream-status.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../utility/live-region/live-region.class.js";import{finiteDuration,MAX_TIMEOUT_MS}from"../../../internal/numbers.js";import{OwnedTimeout}from"../../../internal/owned-timer.js";import{literalSetConverter}from"../../../internal/converters.js";import{styles}from"./stream-status.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_streamInterrupted,LYRA_DEFAULT_streamRecoverAnnounce,LYRA_DEFAULT_streamResume,LYRA_DEFAULT_streamStallAnnounce,LYRA_DEFAULT_streamStallClearedAnnounce,LYRA_DEFAULT_streamStalled,LYRA_DEFAULT_streamStatusConnecting,LYRA_DEFAULT_streamStatusIdle,LYRA_DEFAULT_streamStatusStalled}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_statusRunning}from"../../../internal/default-strings/shared.generated.js";const STREAM_CONNECTION_STATE=literalSetConverter(["idle","connecting","streaming","interrupted"],"idle");function isRealMessageNode(n){if(n.nodeType!==Node.ELEMENT_NODE)return(n.textContent??"").trim().length>0;const slot=n.getAttribute("slot");return slot===null||slot===""}class LyraStreamStatus extends LyraElement{static{this.defaultStrings={...super.defaultStrings,statusRunning:LYRA_DEFAULT_statusRunning,streamInterrupted:LYRA_DEFAULT_streamInterrupted,streamRecoverAnnounce:LYRA_DEFAULT_streamRecoverAnnounce,streamResume:LYRA_DEFAULT_streamResume,streamStallAnnounce:LYRA_DEFAULT_streamStallAnnounce,streamStallClearedAnnounce:LYRA_DEFAULT_streamStallClearedAnnounce,streamStalled:LYRA_DEFAULT_streamStalled,streamStatusConnecting:LYRA_DEFAULT_streamStatusConnecting,streamStatusIdle:LYRA_DEFAULT_streamStatusIdle,streamStatusStalled:LYRA_DEFAULT_streamStatusStalled}}static{this.styles=[LyraElement.styles,styles]}get connectionState(){return this._connectionState}set connectionState(next){const normalized=STREAM_CONNECTION_STATE.normalize(next),old=this._connectionState;old!==normalized&&(this._stalled=!1,this._connectionState=normalized,this.requestUpdate("connectionState",old))}get phase(){return this._stalled&&this.connectionState==="streaming"?"stalled":this.connectionState}constructor(){super(),this._connectionState="idle",this.stallThresholdMs=1e4,this.resumable=!1,this.disabled=!1,this._stalled=!1,this.stallTimer=new OwnedTimeout(this),this.hasActionsSlot=!1,this.hasMessageContent=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onMessageSlotChange=e=>{this.hasMessageContent=e.target.assignedNodes({flatten:!0}).some(isRealMessageNode)},this.resumeDispatching=!1,this.resumeFocused=!1,this.requestUpdate("connectionState",void 0)}willUpdate(changed){super.willUpdate(changed),this.resumeFocused=shadowFocusTarget(this)?.getAttribute("part")==="resume",this.hasUpdated||(this.hasActionsSlot=this.hasSlotted("actions"),this.hasMessageContent=Array.from(this.childNodes).some(isRealMessageNode))}updated(changed){super.updated(changed);const previous=this.lastRenderedPhase,current=this.phase;this.lastRenderedPhase=current,this.toggleAttribute("data-stalled",current==="stalled"),current==="streaming"&&(previous!==current||changed.has("stallThresholdMs"))?this.armStallTimer():current!=="streaming"&&this.disarmStallTimer(),this.onPhaseChanged(previous,current),this.resumeFocused&&!this.renderRoot.querySelector('[part="resume"]')&&this.renderRoot.querySelector('[part="base"]')?.focus()}connectedCallback(){super.connectedCallback(),this.phaseAtDisconnect!==void 0&&(this.phase!==this.phaseAtDisconnect&&(this.lastRenderedPhase=this.phase),this.phaseAtDisconnect=void 0),this.phase==="streaming"&&this.armStallTimer()}disconnectedCallback(){this.phaseAtDisconnect=this.phase,this.disarmStallTimer(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.disarmStallTimer(),this.isConnected&&this.phase==="streaming"&&this.armStallTimer()}recordActivity(){this.phase==="streaming"?this.armStallTimer():this.phase==="stalled"&&(this._stalled=!1)}markStalled(){this.connectionState!=="streaming"||this._stalled||(this.disarmStallTimer(),this._stalled=!0)}onPhaseChanged(previous,current){if(!(previous===void 0||previous===current)){if(current==="stalled"&&previous!=="stalled")this.emit("lr-stall",null),this.announceTransition("assertive",this.localize("streamStallAnnounce"));else if(previous==="stalled"&¤t!=="stalled"){this.emit("lr-recover",null);const text=current==="streaming"?this.localize("streamRecoverAnnounce"):this.localize("streamStallClearedAnnounce");this.announceTransition("polite",text)}}}armStallTimer(){if(this.disarmStallTimer(),!this.isConnected||this.phase!=="streaming")return;const threshold=this.stallThresholdMs;if(!Number.isFinite(threshold)||threshold<=0)return;const delay=finiteDuration(threshold,threshold,0,MAX_TIMEOUT_MS);this.stallTimer.schedule(delay,()=>{this.phase==="streaming"&&this.markStalled()})}disarmStallTimer(){this.stallTimer.cancel()}announceTransition(mode,text){const region=this.liveRegion;region&&(region.mode=mode,region.announce(text,{force:!0}))}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}get phaseText(){switch(this.phase){case"connecting":return this.localize("streamStatusConnecting");case"streaming":return this.localize("statusRunning");case"stalled":return this.localize("streamStatusStalled");case"interrupted":return this.localize("streamInterrupted");default:return this.localize("streamStatusIdle")}}requestResume(){if(!(this.resumeDispatching||this.disabled||!this.resumable||this.phase!=="interrupted")){this.resumeDispatching=!0;try{this.emit("lr-resume",null)}finally{this.resumeDispatching=!1}}}render(){return html`
|
|
2
2
|
<div part="base" tabindex="-1">
|
|
3
3
|
<span part="indicator" aria-hidden="true"></span>
|
|
4
4
|
<span part="phase">${this.phaseText}</span>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{styles}from"./suggestion-chips.styles.js";import{applyComposedFocusRepair,captureComposedFocusRepair}from"../../../internal/focus-navigation.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{RovingToolbarController}from"../../../internal/roving-toolbar.js";import{LYRA_DEFAULT_suggestionsLabel}from"../../../internal/default-strings.generated.js";class LyraSuggestionChips extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="group"]')),this.suggestions=[],this.wrap=!1,this.activeIndex=0,this.rovingToolbar=new RovingToolbarController,this.focusRepairGeneration=0,this.stopEvent=e=>e.stopPropagation(),this.onKeyDown=e=>{const suggestions=this.effectiveSuggestions,target=this.rovingToolbar.move(e,suggestions.length,this.activeIndex,this.effectiveDirection,index=>!this.isSuggestionDisabled(suggestions[index]));if(target===null){(e.key==="ArrowLeft"||e.key==="ArrowRight"||e.key==="Home"||e.key==="End")&&suggestions.length>0&&suggestions.every(item=>this.isSuggestionDisabled(item))&&e.preventDefault();return}e.preventDefault(),this.activeIndex=target,this.focusChip(target)}}static{this.defaultStrings={...super.defaultStrings,suggestionsLabel:LYRA_DEFAULT_suggestionsLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["suggestions"])}static{this.styles=[LyraElement.styles,styles]}normalizeSuggestions(items){const seen=new Set,normalized=[];for(const suggestion of items??[]){let suggestionId,label;try{suggestionId=suggestion?.suggestionId,label=suggestion?.label}catch{continue}typeof suggestionId!="string"||suggestionId.trim()===""||typeof label!="string"||label.trim()===""||seen.has(suggestionId)||(seen.add(suggestionId),normalized.push(suggestion))}return normalized}get effectiveSuggestions(){return this.normalizeSuggestions(this.suggestions)}disconnectedCallback(){this.focusRepairGeneration++,this.pendingFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.focusRepairGeneration++,this.pendingFocus=void 0}willUpdate(changed){if(super.willUpdate(changed),changed.has("suggestions")||changed.has("wrap")){const active=deepActiveElementIn(this.ownerDocument),activeElement=active?.nodeType===1&&"dataset"in active?active:null,suggestionId=activeElement?.dataset.suggestionId,repair=activeElement?captureComposedFocusRepair(this,activeElement):null,generation=++this.focusRepairGeneration;this.pendingFocus=suggestionId&&repair?{suggestionId,index:this.activeIndex,repair,generation}:void 0}if(changed.has("suggestions")){const previous=this.normalizeSuggestions(changed.get("suggestions")),current=this.effectiveSuggestions,activeId=this.pendingFocus?.suggestionId??previous[this.activeIndex]?.suggestionId,remapped=activeId?current.findIndex(suggestion=>suggestion.suggestionId===activeId):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(0,current.length-1))}}updated(changed){super.updated(changed);const pending=this.pendingFocus;this.pendingFocus=void 0,pending&&this.restorePendingFocus(pending)}async restorePendingFocus(pending){if(await this.renderRoot.querySelector(tag("scroller"))?.updateComplete,await Promise.resolve(),pending.generation!==this.focusRepairGeneration||!this.isConnected)return;const buttons=this.chipButtons(),target=buttons.find(button=>button.dataset.suggestionId===pending.suggestionId)??buttons[Math.min(pending.index,Math.max(0,buttons.length-1))]??null;applyComposedFocusRepair(pending.repair,target)}select(suggestion){suggestion.disabled||this.emit("lr-suggestion-select",{suggestionId:suggestion.suggestionId,label:suggestion.label})}chipButtons(){return[...this.renderRoot.querySelectorAll('[part~="chip"]')]}focusChip(index){this.chipButtons()[index]?.focus()}onChipFocus(index){this.activeIndex=index}isSuggestionDisabled(suggestion){return suggestion?.disabled===!0}effectiveActiveIndex(suggestions){const count=suggestions.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!this.isSuggestionDisabled(suggestions[clamped]))return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!this.isSuggestionDisabled(suggestions[forward]))return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!this.isSuggestionDisabled(suggestions[backward]))return backward;return-1}renderChip(suggestion,index,activeIndex){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{styles}from"./suggestion-chips.styles.js";import{applyComposedFocusRepair,captureComposedFocusRepair}from"../../../internal/focus-navigation.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{RovingToolbarController}from"../../../internal/roving-toolbar.js";import{LYRA_DEFAULT_suggestionsLabel}from"../../../internal/default-strings/conversation.generated.js";class LyraSuggestionChips extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="group"]')),this.suggestions=[],this.wrap=!1,this.activeIndex=0,this.rovingToolbar=new RovingToolbarController,this.focusRepairGeneration=0,this.stopEvent=e=>e.stopPropagation(),this.onKeyDown=e=>{const suggestions=this.effectiveSuggestions,target=this.rovingToolbar.move(e,suggestions.length,this.activeIndex,this.effectiveDirection,index=>!this.isSuggestionDisabled(suggestions[index]));if(target===null){(e.key==="ArrowLeft"||e.key==="ArrowRight"||e.key==="Home"||e.key==="End")&&suggestions.length>0&&suggestions.every(item=>this.isSuggestionDisabled(item))&&e.preventDefault();return}e.preventDefault(),this.activeIndex=target,this.focusChip(target)}}static{this.defaultStrings={...super.defaultStrings,suggestionsLabel:LYRA_DEFAULT_suggestionsLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["suggestions"])}static{this.styles=[LyraElement.styles,styles]}normalizeSuggestions(items){const seen=new Set,normalized=[];for(const suggestion of items??[]){let suggestionId,label;try{suggestionId=suggestion?.suggestionId,label=suggestion?.label}catch{continue}typeof suggestionId!="string"||suggestionId.trim()===""||typeof label!="string"||label.trim()===""||seen.has(suggestionId)||(seen.add(suggestionId),normalized.push(suggestion))}return normalized}get effectiveSuggestions(){return this.normalizeSuggestions(this.suggestions)}disconnectedCallback(){this.focusRepairGeneration++,this.pendingFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted(),this.focusRepairGeneration++,this.pendingFocus=void 0}willUpdate(changed){if(super.willUpdate(changed),changed.has("suggestions")||changed.has("wrap")){const active=deepActiveElementIn(this.ownerDocument),activeElement=active?.nodeType===1&&"dataset"in active?active:null,suggestionId=activeElement?.dataset.suggestionId,repair=activeElement?captureComposedFocusRepair(this,activeElement):null,generation=++this.focusRepairGeneration;this.pendingFocus=suggestionId&&repair?{suggestionId,index:this.activeIndex,repair,generation}:void 0}if(changed.has("suggestions")){const previous=this.normalizeSuggestions(changed.get("suggestions")),current=this.effectiveSuggestions,activeId=this.pendingFocus?.suggestionId??previous[this.activeIndex]?.suggestionId,remapped=activeId?current.findIndex(suggestion=>suggestion.suggestionId===activeId):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(0,current.length-1))}}updated(changed){super.updated(changed);const pending=this.pendingFocus;this.pendingFocus=void 0,pending&&this.restorePendingFocus(pending)}async restorePendingFocus(pending){if(await this.renderRoot.querySelector(tag("scroller"))?.updateComplete,await Promise.resolve(),pending.generation!==this.focusRepairGeneration||!this.isConnected)return;const buttons=this.chipButtons(),target=buttons.find(button=>button.dataset.suggestionId===pending.suggestionId)??buttons[Math.min(pending.index,Math.max(0,buttons.length-1))]??null;applyComposedFocusRepair(pending.repair,target)}select(suggestion){suggestion.disabled||this.emit("lr-suggestion-select",{suggestionId:suggestion.suggestionId,label:suggestion.label})}chipButtons(){return[...this.renderRoot.querySelectorAll('[part~="chip"]')]}focusChip(index){this.chipButtons()[index]?.focus()}onChipFocus(index){this.activeIndex=index}isSuggestionDisabled(suggestion){return suggestion?.disabled===!0}effectiveActiveIndex(suggestions){const count=suggestions.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!this.isSuggestionDisabled(suggestions[clamped]))return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!this.isSuggestionDisabled(suggestions[forward]))return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!this.isSuggestionDisabled(suggestions[backward]))return backward;return-1}renderChip(suggestion,index,activeIndex){return html`
|
|
2
2
|
<button
|
|
3
3
|
type="button"
|
|
4
4
|
part="chip"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{archiveIcon,chevronIcon,closeIcon,pinIcon,trashIcon}from"../../../internal/icons.js";import{styles}from"./thread-list.styles.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{calendarDaysAgo,startOfLocalDay}from"../../../internal/group-by-recency.js";import{optionalSizeConverter}from"../../../internal/variants.js";import{getDateTimeFormat,getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_archiveConversation,
|
|
1
|
+
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{tag}from"../../../internal/prefix.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{archiveIcon,chevronIcon,closeIcon,pinIcon,trashIcon}from"../../../internal/icons.js";import{styles}from"./thread-list.styles.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{calendarDaysAgo,startOfLocalDay}from"../../../internal/group-by-recency.js";import{optionalSizeConverter}from"../../../internal/variants.js";import{getDateTimeFormat,getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_archiveConversation,LYRA_DEFAULT_deleteConversation,LYRA_DEFAULT_pinConversation,LYRA_DEFAULT_searchThreads,LYRA_DEFAULT_threadGroupArchived,LYRA_DEFAULT_threadGroupCollapse,LYRA_DEFAULT_threadGroupExpand,LYRA_DEFAULT_threadGroupPinned,LYRA_DEFAULT_threadGroupPrevious30Days,LYRA_DEFAULT_threadGroupPrevious7Days,LYRA_DEFAULT_threadGroupToday,LYRA_DEFAULT_threadGroupYesterday,LYRA_DEFAULT_threadListEmpty,LYRA_DEFAULT_threadListLabel,LYRA_DEFAULT_threadListMatchAnnounce,LYRA_DEFAULT_unarchiveConversation,LYRA_DEFAULT_unpinConversation}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_retry,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";function defaultFilter(thread,query2,locale){const intlLocale=resolveIntlLocale(locale);return thread.title.toLocaleLowerCase(intlLocale).includes(query2)||(thread.excerpt??"").toLocaleLowerCase(intlLocale).includes(query2)}const THREADS_AND_SLOTTED_CONTENT_WARNING_KEY="lyra-thread-list:threads-and-slotted-content",THREADS_AND_SLOTTED_CONTENT_WARNING="<lr-thread-list>: both `threads` and slotted content were supplied; `threads` data mode wins and the default slot is ignored.",canonicalThreadSnapshots=new WeakMap,sourceThreadByProjection=new WeakMap;function normalizeProjectedTimestamp(value){if(!(typeof value!="string"&&typeof value!="number"&&(value===null||typeof value!="object")))return normalizeLyraTimestamp(value)}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectThread(value){if(!isSafeNonArrayObject(value))return;const id=getOwnDataDescriptor(value,"id"),title=getOwnDataDescriptor(value,"title"),excerpt=getOwnDataDescriptor(value,"excerpt"),timestamp=getOwnDataDescriptor(value,"timestamp"),pinned=getOwnDataDescriptor(value,"pinned"),archived=getOwnDataDescriptor(value,"archived");if(id===MISSING_OWN_DATA_DESCRIPTOR||id===UNSAFE_OWN_DATA_DESCRIPTOR||title===MISSING_OWN_DATA_DESCRIPTOR||title===UNSAFE_OWN_DATA_DESCRIPTOR||typeof id.value!="string"||id.value.trim().length===0||typeof title.value!="string")return;const thread=Object.freeze({id:id.value,title:title.value,excerpt:excerpt===MISSING_OWN_DATA_DESCRIPTOR||excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"?void 0:excerpt.value,timestamp:timestamp===MISSING_OWN_DATA_DESCRIPTOR||timestamp===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:normalizeProjectedTimestamp(timestamp.value),pinned:pinned===MISSING_OWN_DATA_DESCRIPTOR||pinned===UNSAFE_OWN_DATA_DESCRIPTOR||typeof pinned.value!="boolean"?!1:pinned.value,archived:archived===MISSING_OWN_DATA_DESCRIPTOR||archived===UNSAFE_OWN_DATA_DESCRIPTOR||typeof archived.value!="boolean"?!1:archived.value});return sourceThreadByProjection.set(thread,value),thread}function canonicalThreads(values){const cached=canonicalThreadSnapshots.get(values);if(cached)return cached;const projected=[],seen=new Set;for(const value of values){const thread=projectThread(value);!thread||seen.has(thread.id)||(seen.add(thread.id),projected.push(thread))}const snapshot=Object.freeze(projected);return canonicalThreadSnapshots.set(values,snapshot),snapshot}class LyraThreadList extends LyraElement{constructor(){super(...arguments),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part="base"][role="region"]')),this.threads=[],this.activeConversationId="",this.searchable=!1,this.size="m",this.grouping="date",this.collapsedGroupIds=[],this.rowActions=[],this.withArchived=!1,this.withoutRename=!1,this.stickyGroups=!1,this.error=!1,this.errorDescription="",this.stickyGroupItems=new Map,this.searchText="",this.hasEmptySlot=!1,this.hasDefaultSlotContent=!1,this.focusTaskGeneration=0,this.injectedListItemRoles=new Set,this.onSearchInput=e=>{e.stopPropagation(),this.setSearchText(e.target.value)},this.onClearSearch=()=>{this.searchText!==""&&(this.setSearchText(""),this.searchInputEl?.focus())},this.onSearchKeyDown=e=>{if(e.key!=="ArrowDown")return;const focusGeneration=++this.focusTaskGeneration,rows=this.navigableRows(),list=this.virtualListEl,items=list?.items??[],first=items[items.findIndex(item=>item.kind==="thread")],firstId=first?.kind==="thread"?first.thread.id:void 0;rows[0]&&(!this.dataMode||rows[0].conversationId===firstId)?(e.preventDefault(),this.selectButtonEl(rows[0])?.focus()):this.dataMode&&list?.scrollContainer&&firstId!==void 0&&(e.preventDefault(),this.focusVirtualThreadFromItemIndex(list,items,0,1,focusGeneration))},this.onSearchFocus=event=>{relayNativeEvent(this,event)},this.onSearchBlur=event=>{relayNativeEvent(this,event)},this.onListKeyDown=e=>{if(e.key!=="ArrowDown"&&e.key!=="ArrowUp"&&e.key!=="Home"&&e.key!=="End"||e.defaultPrevented)return;const origin=e.composedPath()[0];if(origin?.nodeType===1&&origin.closest('[part="group-toggle"]'))return;const focusGeneration=++this.focusTaskGeneration,list=this.virtualListEl;if(this.dataMode&&(e.key==="Home"||e.key==="End")&&list?.scrollContainer){const items2=list.items;e.preventDefault(),this.focusVirtualThreadFromItemIndex(list,items2,e.key==="Home"?0:items2.length-1,e.key==="Home"?1:-1,focusGeneration);return}const rows=this.navigableRows();if(rows.length===0)return;const currentIndex=this.focusedRowIndex(rows);let targetIndex;if(e.key==="Home"?targetIndex=0:e.key==="End"?targetIndex=rows.length-1:e.key==="ArrowDown"?targetIndex=currentIndex<0?0:currentIndex+1:targetIndex=currentIndex<0?rows.length-1:currentIndex-1,e.preventDefault(),targetIndex>=0&&targetIndex<rows.length){this.selectButtonEl(rows[targetIndex])?.focus();return}if(!list?.scrollContainer)return;const currentRow=rows[currentIndex];if(!currentRow)return;const items=list.items,currentItemIndex=items.findIndex(item=>item.kind==="thread"&&item.thread.id===currentRow.conversationId);if(currentItemIndex<0)return;const direction=e.key==="ArrowDown"?1:-1;this.focusVirtualThreadFromItemIndex(list,items,currentItemIndex+direction,direction,focusGeneration)},this.renderRow=item=>{const thread=item,source=this.sourceThread(thread),row=html`
|
|
2
2
|
<lr-conversation-item
|
|
3
3
|
exportparts="base:row-item-base, base-menu-open:row-item-base-menu-open, active-indicator:row-item-active-indicator, select-button:row-item-select-button, start:row-item-start, content:row-item-content, label:row-item-label, label-input:row-item-label-input, rename-button:row-item-rename-button, excerpt:row-item-excerpt, meta:row-item-meta, timestamp:row-item-timestamp, actions:row-item-actions"
|
|
4
4
|
conversation-id=${thread.id}
|
|
@@ -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{AnnouncementSinkController}from"../../../internal/announcer.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{srOnly}from"../../../internal/a11y.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{styles}from"./transcript-feed.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{
|
|
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{AnnouncementSinkController}from"../../../internal/announcer.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{srOnly}from"../../../internal/a11y.js";import{captureComposedFocusRepair,applyComposedFocusRepair}from"../../../internal/focus-navigation.js";import{styles}from"./transcript-feed.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{normalizeLyraTimestamp}from"../timestamp.js";import{LYRA_DEFAULT_transcriptFeedEmpty,LYRA_DEFAULT_transcriptFeedInterim,LYRA_DEFAULT_transcriptFeedLabel}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_jumpToLatest}from"../../../internal/default-strings/shared.generated.js";const NEAR_BOTTOM_PX=48;class LyraTranscriptFeed extends LyraElement{constructor(){super(...arguments),this.entries=[],this.follow=!0,this.withTimestamps=!1,this.maxRenderedEntries=500,this.sessionId="",this.accessibleLabel=null,this._isFirstUpdate=!0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.announcedFinalIds=new Set,this.sessionChanged=!1,this.pendingSessionBaseline=!1,this.onScroll=e=>{const base=e.currentTarget,atBottom=base.scrollHeight-base.scrollTop-base.clientHeight<=NEAR_BOTTOM_PX;atBottom!==this.follow&&(this.follow=atBottom,this.emit("lr-follow-change",{following:atBottom}))},this.onJumpClick=()=>{const jump=this.renderRoot.querySelector('[part="jump-button"]'),base=this.renderRoot.querySelector('[part="base"]'),repair=jump?captureComposedFocusRepair(jump,base):null,changed=!this.follow;this.scrollToBottom(),changed&&this.emit("lr-follow-change",{following:!0}),repair&&this.updateComplete.then(()=>{this.isConnected&&this.follow&&applyComposedFocusRepair(repair)})}}static{this.defaultStrings={...super.defaultStrings,jumpToLatest:LYRA_DEFAULT_jumpToLatest,transcriptFeedEmpty:LYRA_DEFAULT_transcriptFeedEmpty,transcriptFeedInterim:LYRA_DEFAULT_transcriptFeedInterim,transcriptFeedLabel:LYRA_DEFAULT_transcriptFeedLabel}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["entries"])}static{this.appendOrderedCollectionProperties=Object.freeze(["entries"])}static{this.styles=[LyraElement.styles,srOnly,styles]}get effectiveMaxRenderedEntries(){return finiteCount(this.maxRenderedEntries,500)}get normalizedEntries(){const source=this.entries;if(this.normalizedMemo?.source===source)return this.normalizedMemo.entries;const seen=new Set,entries=source.filter(entry=>entry===null||typeof entry!="object"||typeof entry.id!="string"||entry.id.trim().length===0||typeof entry.text!="string"||seen.has(entry.id)?!1:(seen.add(entry.id),!0));return this.normalizedMemo={source,entries},entries}get renderedEntries(){const entries=this.normalizedEntries,maxRenderedEntries=this.effectiveMaxRenderedEntries;return maxRenderedEntries>0&&entries.length>maxRenderedEntries?entries.slice(-maxRenderedEntries):entries}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.sessionChanged=changed.has("sessionId")&&this.hasUpdated,this.sessionChanged&&(this.announcedFinalIds.clear(),this.pendingSessionBaseline=!0)}updated(changed){super.updated(changed),changed.has("entries")&&(this.follow&&this.scrollToBottom(),this.announceFinalizedEntries())}announceFinalizedEntries(){const alreadyAnnounced=this.announcedFinalIds,fresh=[];for(const entry of this.normalizedEntries)entry.interim||alreadyAnnounced.has(entry.id)||(alreadyAnnounced.add(entry.id),fresh.push(entry.text));const establishesBaseline=this._isFirstUpdate||this.sessionChanged||this.pendingSessionBaseline;if(this.pendingSessionBaseline=!1,establishesBaseline)return;const sink=this.announcements.current("polite");if(sink)for(const text of fresh){const message=text.replace(/\s+/g," ").trim();message&&sink.announce(message)}}scrollToBottom(){this.follow=!0;const base=this.renderRoot.querySelector('[part="base"]');base&&(base.scrollTop=base.scrollHeight)}showSpeakerFor(list,index){const prev=list[index-1],current=list[index];return!prev||prev.speaker!==current.speaker}renderEntry(entry,showSpeaker,interim,format){const parts=["entry"];interim&&parts.push("interim");const date=format&&entry.timestamp!=null?normalizeLyraTimestamp(entry.timestamp):null;return html`
|
|
2
2
|
<div part=${parts.join(" ")} ?data-interim=${interim}>
|
|
3
3
|
${showSpeaker&&typeof entry.speaker=="string"&&entry.speaker?html`<span part="speaker">${entry.speaker}</span>`:nothing}
|
|
4
4
|
<span part="text" dir="auto">${entry.text}</span>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./typing-indicator.styles.js";import{LYRA_DEFAULT_thinking}from"../../../internal/default-strings.generated.js";class LyraTypingIndicator extends LyraElement{constructor(){super(...arguments),this.shape="dots",this.label="",this.size="m",this.labelPlacement="none",this.appliedAriaLabel=null,this.explicitAriaLabel=null}static{this.defaultStrings={...super.defaultStrings,thinking:LYRA_DEFAULT_thinking}}static{this.styles=[LyraElement.styles,styles,srOnly]}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.hasUpdated&&this.announce()}disconnectedCallback(){super.disconnectedCallback(),this.sink?.release(),this.sink=void 0,this.announcedLabel=void 0}updated(changed){super.updated(changed),this.announce()}announce(){const label=this.accessibleLabel;label!==this.announcedLabel&&(this.announcedLabel=label,this.sink?.announce(label))}get accessibleLabel(){if(this.explicitAriaLabel!==null)return this.explicitAriaLabel;const trimmed=(this.label??"").trim();return trimmed===""?this.localize("thinking"):trimmed}willUpdate(changed){super.willUpdate(changed),this.setAttribute("role","status");const currentAriaLabel=this.getAttribute("aria-label");currentAriaLabel!==this.appliedAriaLabel&&(this.explicitAriaLabel=currentAriaLabel),this.setAttribute("aria-label",this.accessibleLabel),this.appliedAriaLabel=this.accessibleLabel}render(){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./typing-indicator.styles.js";import{LYRA_DEFAULT_thinking}from"../../../internal/default-strings/shared.generated.js";class LyraTypingIndicator extends LyraElement{constructor(){super(...arguments),this.shape="dots",this.label="",this.size="m",this.labelPlacement="none",this.appliedAriaLabel=null,this.explicitAriaLabel=null}static{this.defaultStrings={...super.defaultStrings,thinking:LYRA_DEFAULT_thinking}}static{this.styles=[LyraElement.styles,styles,srOnly]}connectedCallback(){super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.hasUpdated&&this.announce()}disconnectedCallback(){super.disconnectedCallback(),this.sink?.release(),this.sink=void 0,this.announcedLabel=void 0}updated(changed){super.updated(changed),this.announce()}announce(){const label=this.accessibleLabel;label!==this.announcedLabel&&(this.announcedLabel=label,this.sink?.announce(label))}get accessibleLabel(){if(this.explicitAriaLabel!==null)return this.explicitAriaLabel;const trimmed=(this.label??"").trim();return trimmed===""?this.localize("thinking"):trimmed}willUpdate(changed){super.willUpdate(changed),this.setAttribute("role","status");const currentAriaLabel=this.getAttribute("aria-label");currentAriaLabel!==this.appliedAriaLabel&&(this.explicitAriaLabel=currentAriaLabel),this.setAttribute("aria-label",this.accessibleLabel),this.appliedAriaLabel=this.accessibleLabel}render(){return html`
|
|
2
2
|
<span part="base" aria-hidden="true">${this.renderShape()}</span>
|
|
3
3
|
${this.labelPlacement==="after"?html`<span part="label" aria-hidden="true">${this.accessibleLabel}</span>`:html`<span class="sr-only">${this.accessibleLabel}</span>`}
|
|
4
4
|
`}renderShape(){switch(this.shape){case"pulse":return html`<span part="pulse"></span>`;case"cursor":return html`<span part="cursor"></span>`;default:return html`<span part="dot"></span><span part="dot"></span><span part="dot"></span>`}}}__decorate([property({reflect:!0})],LyraTypingIndicator.prototype,"shape",void 0),__decorate([property()],LyraTypingIndicator.prototype,"label",void 0),__decorate([property({reflect:!0})],LyraTypingIndicator.prototype,"size",void 0),__decorate([property({attribute:"label-placement",reflect:!0})],LyraTypingIndicator.prototype,"labelPlacement",void 0);export{LyraTypingIndicator};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{finiteCount}from"../../../internal/numbers.js";import{styles}from"./usage-badge.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveIdReferencesIn,updateDescriptionBaseline}from"../../../internal/aria-reflection.js";import{formatShortDuration,safeDurationMs}from"../../../internal/duration.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{finiteCount}from"../../../internal/numbers.js";import{styles}from"./usage-badge.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveIdReferencesIn,updateDescriptionBaseline}from"../../../internal/aria-reflection.js";import{formatShortDuration,safeDurationMs}from"../../../internal/duration.js";import{LYRA_DEFAULT_usageBadgeCostLabel,LYRA_DEFAULT_usageBadgeLabel,LYRA_DEFAULT_usageBadgeLatencyLabel,LYRA_DEFAULT_usageBadgeTokensIn,LYRA_DEFAULT_usageBadgeTokensInLabel,LYRA_DEFAULT_usageBadgeTokensOut,LYRA_DEFAULT_usageBadgeTokensOutLabel,LYRA_DEFAULT_usageBadgeTotalTokensLabel}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_durationMilliseconds,LYRA_DEFAULT_durationSeconds}from"../../../internal/default-strings/shared.generated.js";class LyraUsageBadge extends LyraElement{constructor(){super(...arguments),this.costText="",this.summary="",this.abbreviate=!1,this.tooltipOpen=!1,this.focusDescribed=!1,this.hasDetailsSlot=!1,this.hasSummarySlot=!1,this.detailsText="",this.tooltipId=nextId("usage-badge-tooltip"),this.hostDescribed=!1,this.hovering=!1,this.focused=!1,this.onDetailsSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.hasDetailsSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="details"),this.detailsText=assigned.slice(0,64).map(element=>{const renderedText=element.innerText;return typeof renderedText=="string"?renderedText:element.textContent??""}).join(" ").replace(/\s+/g," ").trim().slice(0,4096),this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onSummarySlotChange=()=>{this.hasSummarySlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="summary"),this.hasInteractiveTooltip||this.closeTooltipLifecycle()},this.onMouseEnter=()=>{this.hovering=!0,this.showTooltip()},this.onMouseLeave=()=>{this.hovering=!1,!this.focused&&this.hideTooltip()},this.onFocus=event=>{this.focusDescribed=!0,isKeyboardFocusEvent(event)&&(this.focused=!0,this.showTooltip())},this.onBlur=()=>{this.focused=!1,this.focusDescribed=!1,!this.hovering&&this.hideTooltip()},this.onKeyDown=e=>{e.key!=="Escape"||e.isComposing||e.keyCode===229||(this.tooltipOpening&&this.cancelTooltipOpening(),this.tooltipOpen&&this.tooltipOverlay?.isTopmost()&&(e.preventDefault(),this.hideTooltip()))}}static{this.defaultStrings={...super.defaultStrings,durationMilliseconds:LYRA_DEFAULT_durationMilliseconds,durationSeconds:LYRA_DEFAULT_durationSeconds,usageBadgeCostLabel:LYRA_DEFAULT_usageBadgeCostLabel,usageBadgeLabel:LYRA_DEFAULT_usageBadgeLabel,usageBadgeLatencyLabel:LYRA_DEFAULT_usageBadgeLatencyLabel,usageBadgeTokensIn:LYRA_DEFAULT_usageBadgeTokensIn,usageBadgeTokensInLabel:LYRA_DEFAULT_usageBadgeTokensInLabel,usageBadgeTokensOut:LYRA_DEFAULT_usageBadgeTokensOut,usageBadgeTokensOutLabel:LYRA_DEFAULT_usageBadgeTokensOutLabel,usageBadgeTotalTokensLabel:LYRA_DEFAULT_usageBadgeTotalTokensLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{const children=Array.from(this.children);this.hasDetailsSlot=children.some(child=>child.getAttribute("slot")==="details"),this.hasSummarySlot=children.some(child=>child.getAttribute("slot")==="summary")}),this.hasUpdated&&(changed.has("tokensIn")||changed.has("tokensOut")||changed.has("costText")||changed.has("latencyMs")||changed.has("summary"))&&!this.hasInteractiveTooltip&&this.closeTooltipLifecycle()}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby"),base=this.renderRoot.querySelector('[part="base"]');if(base&&"ariaDescribedByElements"in base&&(describedBy||this.hostDescribed)){const tooltip=this.describesTooltip?this.renderRoot.querySelector('[part="tooltip"]'):null,elements=resolveIdReferencesIn(this.getRootNode(),describedBy);tooltip&&elements.push(tooltip),updateDescriptionBaseline(base,()=>{base.ariaDescribedByElements=elements.length?elements:null}),this.hostDescribed=!!describedBy}changed.has("tooltipOpen")&&(this.tooltipOverlay?.deactivate({restoreFocus:!1}),this.tooltipOverlay=void 0,this.tooltipOpen&&this.isConnected&&(this.tooltipOverlay=this.tooltipRuntime?.activateUsageBadgeOverlay(this,()=>this.hideTooltip(),this.tooltipOrder),this.tooltipOrder=void 0))}disconnectedCallback(){super.disconnectedCallback(),this.closeTooltipLifecycle()}get hasTokensIn(){return this.tokensIn!=null&&Number.isFinite(this.tokensIn)}get hasTokensOut(){return this.tokensOut!=null&&Number.isFinite(this.tokensOut)}get hasCost(){return(this.costText??"").length>0}get validLatencyMs(){return safeDurationMs(this.latencyMs)??void 0}get hasLatency(){return this.validLatencyMs!==void 0}get hasVisibleContent(){return this.hasTokensIn||this.hasTokensOut||this.hasCost||this.hasLatency}get hasVisibleSummary(){return(this.summary??"").length>0||this.hasSummarySlot}get hasDisplayContent(){return this.hasVisibleContent||this.hasVisibleSummary}get hasTooltipContent(){return this.hasVisibleContent||this.hasDetailsSlot}get hasInteractiveTooltip(){return this.hasDisplayContent&&this.hasTooltipContent}formatTokenCount(n){return getNumberFormat(this.effectiveLocale,this.abbreviate?{notation:"compact"}:{}).format(n)}formatTokenCountFull(n){return getNumberFormat(this.effectiveLocale).format(n)}localizedDuration(ms){return this.formatLatency?this.formatLatency(ms):formatShortDuration(this.localize.bind(this),this.effectiveLocale,ms)}loadTooltipOverlayRuntime(){return import("./usage-badge-overlay-runtime.js")}getUpdateComplete(){return this.tooltipOpening?this.waitForTooltipOpening():super.getUpdateComplete()}async waitForTooltipOpening(){let complete=await super.getUpdateComplete();for(;this.tooltipOpening;)await this.tooltipOpening.ready,complete=await super.getUpdateComplete();return complete}cancelTooltipOpening(){this.tooltipOpening?.cancel(),this.tooltipOpening=void 0,this.tooltipOrder=void 0}showTooltip(){if(!this.hasInteractiveTooltip||this.tooltipOpen||this.tooltipOpening||!this.isConnected)return;const document=this.ownerDocument,order=reserveOverlayOrder(document);if(this.tooltipRuntime){this.tooltipOrder=order,this.tooltipOpen=!0;return}let settle;const opening={ready:new Promise(resolve=>{settle=resolve}),cancel:settle};this.tooltipOpening=opening,this.loadTooltipOverlayRuntime().then(runtime=>{this.tooltipOpening!==opening||!this.isConnected||this.ownerDocument!==document||!this.hasInteractiveTooltip||!this.hovering&&!this.focused||!this.renderRoot.querySelector('[part="base"]')?.getClientRects().length||(this.tooltipRuntime=runtime,this.tooltipOrder=order,this.tooltipOpen=!0)},()=>{}).finally(()=>{this.tooltipOpening===opening&&(this.tooltipOpening=void 0),settle()})}hideTooltip(){this.cancelTooltipOpening(),this.tooltipOpen=!1,this.tooltipOverlay?.deactivate({restoreFocus:!1}),this.tooltipOverlay=void 0}closeTooltipLifecycle(){this.hideTooltip(),this.hovering=!1,this.focused=!1,this.focusDescribed=!1}get describesTooltip(){return this.hasInteractiveTooltip&&(this.tooltipOpen||this.focusDescribed)}render(){const interactive=this.hasInteractiveTooltip,tokensIn=this.hasTokensIn?finiteCount(this.tokensIn):void 0,tokensOut=this.hasTokensOut?finiteCount(this.tokensOut):void 0,hasBoth=tokensIn!==void 0&&tokensOut!==void 0;return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base"
|
|
4
4
|
role=${interactive?"group":nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraCatalogPickerElement}from"../catalog-picker-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{autocorrectConverter,normalizeAutocorrect,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();class LyraVoicePicker extends LyraCatalogPickerElement{constructor(){super(...arguments),this.provider="",this.allowCustom=!1,this.readonly=!1,this.withoutPreview=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.slotPresence=new SlotPresenceController(this),this.previewingId=null,this.listId=nextId("voice-picker-list"),this.controlId=nextId("voice-picker-control"),this.pendingPreviewId=null,this.previewGeneration=0,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,isReadonly:()=>this.readonly,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label,entry.language??"",entry.description??""],emitInput:detail=>this.emit("lr-input",detail),emitChange:detail=>this.emit("lr-change",detail),beforeValueChange:value=>{const previewTarget=this.internalPreviewTargetId;previewTarget!==null&&previewTarget!==value&&this.stopInternalPreview()},beforeActiveIndexChange:next=>this.reconcilePreviewForActiveIndex(next),afterQueryChange:()=>this.reconcilePreviewVisibility(this.open,this.catalogPicker.filteredEntries),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state2,oldValue)=>{state2==="open"?(this.catalogPicker.open||this.reconcilePreviewVisibility(!1,[]),this.requestUpdate("open",oldValue)):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)}}),this.onAudioEnded=event=>{event.currentTarget===this.audioEl&&this.stopInternalPreview()},this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio,isDomErrorEvent=direct.localName!=="audio",audioLike=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget,failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause=="function"&&typeof audioLike.removeEventListener=="function"?audioLike:void 0;if(!failedAudio||(failedAudio.removeEventListener("ended",this.onAudioEnded),failedAudio.removeEventListener("error",this.onAudioLoadFailure),failedAudio.pause(),failedAudio!==this.audioEl))return;const pendingVoiceId=this.pendingPreviewId;this.previewGeneration++,this.audioEl=void 0,this.pendingPreviewId=null,isDomErrorEvent&&this.previewingId===null&&pendingVoiceId!==null&&(this.previewingId=pendingVoiceId,this.emit("lr-preview-change",{voiceId:pendingVoiceId})),this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))},this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;candidate&&(this.internalPreviewTargetId===candidate?this.stopInternalPreview():this.requestPreview(candidate))},this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation(),this.internalPreviewTargetId===entry.id?this.stopInternalPreview():this.requestPreview(entry.id)},this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onControlBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onControlFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)}}static{this.defaultStrings={...super.defaultStrings,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.properties={value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!1,useDefault:!0,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}get catalogEditing(){return this.catalogPicker}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);const switchingMode=this.prepareModeFocus(this.closedMode);if(this.catalogPicker.suppressControlEvents=switchingMode,this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value,rows=this.closedMode?this.effectiveEntries:this.filteredEntries;this.catalogPicker.reconcileRows(activeValue,this.open&&(changed.has("value")||changed.has("allowCustom")||switchingMode),!1),this.reconcilePreviewVisibility(this.open,rows)}changed.has("catalog")&&this.internalPreviewTargetId!==null&&this.stopInternalPreview(),changed.has("withoutPreview")&&this.withoutPreview&&this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}requiredMessage(){return this.localize("voicePickerRequired")}releaseOnDisable(){super.releaseOnDisable(),this.stopInternalPreview()}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state2,_mode){this.catalogPicker.restoreState(state2)}formDisabledCallback(disabled){this.formDisabledChanged(disabled)}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}updated(changed){super.updated(changed),this.syncCatalogDescription(this.controlId);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("readonly")||changed.has("touched")||changed.has("value"))&&(changed.has("readonly")&&this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),this.publishValidityStates(),this.finishModeFocus("voice-picker-mode-focus"),this.catalogPicker.suppressControlEvents=!1}get internalPreviewTargetId(){return this.pendingPreviewId??this.previewingId}reconcilePreviewVisibility(open,rows){const target=this.internalPreviewTargetId;if(target===null)return;const standaloneCandidate=open&&this.activeIndex>=0?rows[this.activeIndex]?.id??this.value:this.value,hasVisibleRow=open&&rows.some(entry=>entry.id===target&&!!entry.previewUrl);target!==standaloneCandidate&&!hasVisibleRow&&this.stopInternalPreview()}reconcilePreviewForActiveIndex(next){const target=this.internalPreviewTargetId;if(target!==null){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries,nextCandidate=this.open&&next>=0?rows[next]?.id??this.value:this.value;target!==nextCandidate&&this.stopInternalPreview()}}get previewCandidateId(){return this.open&&this.activeIndex>=0?(this.closedMode?this.effectiveEntries:this.filteredEntries)[this.activeIndex]?.id??this.value:this.value}requestPreview(voiceId){if(!voiceId)return;const currentTarget=this.internalPreviewTargetId;currentTarget!==null&¤tTarget!==voiceId&&this.stopInternalPreview();const previewUrl=this.effectiveEntries.find(e=>e.id===voiceId)?.previewUrl;!this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:!0}).defaultPrevented&&previewUrl&&this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe,audio.addEventListener("ended",this.onAudioEnded),audio.addEventListener("error",this.onAudioLoadFailure);const generation=++this.previewGeneration;this.audioEl=audio,this.pendingPreviewId=voiceId;let playResult;try{playResult=audio.play()}catch{this.onAudioLoadFailure(audio);return}Promise.resolve(playResult).then(()=>{generation!==this.previewGeneration||audio!==this.audioEl||this.pendingPreviewId!==voiceId||(this.pendingPreviewId=null,this.previewingId=voiceId,this.emit("lr-preview-change",{voiceId}))},()=>this.onAudioLoadFailure(audio))}stopInternalPreview(){const hadTarget=this.internalPreviewTargetId!==null||this.audioEl!==void 0;this.audioEl&&(this.audioEl.removeEventListener("ended",this.onAudioEnded),this.audioEl.removeEventListener("error",this.onAudioLoadFailure),this.audioEl.pause(),this.audioEl=void 0),hadTarget&&this.previewGeneration++,this.pendingPreviewId=null,this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))}get previewButtonLabel(){const candidate=this.previewCandidateId,playing=this.previewingId!==null&&this.previewingId===candidate,name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value,meta=[entry.language,entry.description].filter(Boolean).join(" · ");return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{nativeAutocorrectAttribute}from"../../../internal/native-text-control.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraCatalogPickerElement}from"../catalog-picker-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{autocorrectConverter,normalizeAutocorrect,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{CatalogPickerController}from"../../../internal/catalog-picker.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings/conversation.generated.js";import{LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraVoicePicker extends LyraCatalogPickerElement{constructor(){super(...arguments),this.provider="",this.allowCustom=!1,this.readonly=!1,this.withoutPreview=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.size="m",this.slotPresence=new SlotPresenceController(this),this.previewingId=null,this.listId=nextId("voice-picker-list"),this.controlId=nextId("voice-picker-control"),this.pendingPreviewId=null,this.previewGeneration=0,this.catalogPicker=new CatalogPickerController(this,{catalog:()=>this.catalog,allowCustom:()=>this.allowCustom,isReadonly:()=>this.readonly,locale:()=>this.effectiveLocale,searchableFields:entry=>[entry.id,entry.label,entry.language??"",entry.description??""],emitInput:detail=>this.emit("lr-input",detail),emitChange:detail=>this.emit("lr-change",detail),beforeValueChange:value=>{const previewTarget=this.internalPreviewTargetId;previewTarget!==null&&previewTarget!==value&&this.stopInternalPreview()},beforeActiveIndexChange:next=>this.reconcilePreviewForActiveIndex(next),afterQueryChange:()=>this.reconcilePreviewVisibility(this.open,this.catalogPicker.filteredEntries),onValueChange:(value,oldValue)=>{this.internals.setFormValue(value),this.updateValidity(),this.requestUpdate("value",oldValue)},onDefaultValueChange:(_value,oldValue)=>this.requestUpdate("defaultValue",oldValue),onStateChange:(state2,oldValue)=>{state2==="open"?(this.catalogPicker.open||this.reconcilePreviewVisibility(!1,[]),this.requestUpdate("open",oldValue)):this.requestUpdate()},onControlFocus:event=>this.captureModeFocus(event),onControlBlur:event=>{this.effectiveDisabled||(this.touched=!0),this.retireModeFocusAfterBlur(event)}}),this.onAudioEnded=event=>{event.currentTarget===this.audioEl&&this.stopInternalPreview()},this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio,isDomErrorEvent=direct.localName!=="audio",audioLike=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget,failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause=="function"&&typeof audioLike.removeEventListener=="function"?audioLike:void 0;if(!failedAudio||(failedAudio.removeEventListener("ended",this.onAudioEnded),failedAudio.removeEventListener("error",this.onAudioLoadFailure),failedAudio.pause(),failedAudio!==this.audioEl))return;const pendingVoiceId=this.pendingPreviewId;this.previewGeneration++,this.audioEl=void 0,this.pendingPreviewId=null,isDomErrorEvent&&this.previewingId===null&&pendingVoiceId!==null&&(this.previewingId=pendingVoiceId,this.emit("lr-preview-change",{voiceId:pendingVoiceId})),this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))},this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;candidate&&(this.internalPreviewTargetId===candidate?this.stopInternalPreview():this.requestPreview(candidate))},this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation(),this.internalPreviewTargetId===entry.id?this.stopInternalPreview():this.requestPreview(entry.id)},this.onTriggerClick=()=>{this.effectiveDisabled||(this.open?this.hide():this.show())},this.onControlBlur=event=>{this.catalogPicker.handleControlBlur(event)},this.onControlFocus=event=>{this.catalogPicker.handleControlFocus(event)},this.onTriggerKeyDown=e=>{this.catalogPicker.handleTriggerKeyDown(e)},this.onComboMouseDown=e=>{this.catalogPicker.handleComboMouseDown(e)},this.onInputFocus=event=>{this.catalogPicker.handleInputFocus(event)},this.onInput=e=>{this.catalogPicker.handleInput(e)},this.onInputKeyDown=e=>{this.catalogPicker.handleInputKeyDown(e)},this.onListboxMouseDown=e=>{this.catalogPicker.handleListboxMouseDown(e)},this.onListboxClick=e=>{this.catalogPicker.handleListboxClick(e)}}static{this.defaultStrings={...super.defaultStrings,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["catalog"])}static{this.properties={value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!1,useDefault:!0,noAccessor:!0}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get open(){return this.catalogPicker.open}set open(next){this.catalogPicker.setOpen(next)}get activeIndex(){return this.catalogPicker.activeIndex}get query(){return this.catalogPicker.query}get catalogEditing(){return this.catalogPicker}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.catalogPicker.connected(this.hasUpdated)}willUpdate(changed){super.willUpdate(changed);const switchingMode=this.prepareModeFocus(this.closedMode);if(this.catalogPicker.suppressControlEvents=switchingMode,this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset.value,rows=this.closedMode?this.effectiveEntries:this.filteredEntries;this.catalogPicker.reconcileRows(activeValue,this.open&&(changed.has("value")||changed.has("allowCustom")||switchingMode),!1),this.reconcilePreviewVisibility(this.open,rows)}changed.has("catalog")&&this.internalPreviewTargetId!==null&&this.stopInternalPreview(),changed.has("withoutPreview")&&this.withoutPreview&&this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.disconnected()}adoptedCallback(){super.adoptedCallback(),this.stopInternalPreview(),this.clearModeFocus(),this.catalogPicker.adopted()}get value(){return this.catalogPicker.value}set value(next){this.catalogPicker.value=next}get defaultValue(){return this.catalogPicker.defaultValue}set defaultValue(next){this.catalogPicker.defaultValue=next}requiredMessage(){return this.localize("voicePickerRequired")}releaseOnDisable(){super.releaseOnDisable(),this.stopInternalPreview()}formResetCallback(){this.touched=!1,this.catalogPicker.resetValue()}formStateRestoreCallback(state2,_mode){this.catalogPicker.restoreState(state2)}formDisabledCallback(disabled){this.formDisabledChanged(disabled)}get closedMode(){return this.catalogPicker.closedMode}get effectiveEntries(){return this.catalogPicker.effectiveEntries}get filteredEntries(){return this.catalogPicker.filteredEntries}labelFor(id){return this.catalogPicker.labelFor(id)}show(){this.catalogPicker.show()}hide(){this.catalogPicker.hide()}updated(changed){super.updated(changed),this.syncCatalogDescription(this.controlId);const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));this.catalogPicker.updated(reposition),(changed.has("required")||changed.has("readonly")||changed.has("touched")||changed.has("value"))&&(changed.has("readonly")&&this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),this.publishValidityStates(),this.finishModeFocus("voice-picker-mode-focus"),this.catalogPicker.suppressControlEvents=!1}get internalPreviewTargetId(){return this.pendingPreviewId??this.previewingId}reconcilePreviewVisibility(open,rows){const target=this.internalPreviewTargetId;if(target===null)return;const standaloneCandidate=open&&this.activeIndex>=0?rows[this.activeIndex]?.id??this.value:this.value,hasVisibleRow=open&&rows.some(entry=>entry.id===target&&!!entry.previewUrl);target!==standaloneCandidate&&!hasVisibleRow&&this.stopInternalPreview()}reconcilePreviewForActiveIndex(next){const target=this.internalPreviewTargetId;if(target!==null){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries,nextCandidate=this.open&&next>=0?rows[next]?.id??this.value:this.value;target!==nextCandidate&&this.stopInternalPreview()}}get previewCandidateId(){return this.open&&this.activeIndex>=0?(this.closedMode?this.effectiveEntries:this.filteredEntries)[this.activeIndex]?.id??this.value:this.value}requestPreview(voiceId){if(!voiceId)return;const currentTarget=this.internalPreviewTargetId;currentTarget!==null&¤tTarget!==voiceId&&this.stopInternalPreview();const previewUrl=this.effectiveEntries.find(e=>e.id===voiceId)?.previewUrl;!this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:!0}).defaultPrevented&&previewUrl&&this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe,audio.addEventListener("ended",this.onAudioEnded),audio.addEventListener("error",this.onAudioLoadFailure);const generation=++this.previewGeneration;this.audioEl=audio,this.pendingPreviewId=voiceId;let playResult;try{playResult=audio.play()}catch{this.onAudioLoadFailure(audio);return}Promise.resolve(playResult).then(()=>{generation!==this.previewGeneration||audio!==this.audioEl||this.pendingPreviewId!==voiceId||(this.pendingPreviewId=null,this.previewingId=voiceId,this.emit("lr-preview-change",{voiceId}))},()=>this.onAudioLoadFailure(audio))}stopInternalPreview(){const hadTarget=this.internalPreviewTargetId!==null||this.audioEl!==void 0;this.audioEl&&(this.audioEl.removeEventListener("ended",this.onAudioEnded),this.audioEl.removeEventListener("error",this.onAudioLoadFailure),this.audioEl.pause(),this.audioEl=void 0),hadTarget&&this.previewGeneration++,this.pendingPreviewId=null,this.previewingId!==null&&(this.previewingId=null,this.emit("lr-preview-change",{voiceId:null}))}get previewButtonLabel(){const candidate=this.previewCandidateId,playing=this.previewingId!==null&&this.previewingId===candidate,name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.id===this.value,meta=[entry.language,entry.description].filter(Boolean).join(" · ");return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -1,2 +1,2 @@
|
|
|
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{literalSetConverter}from"../../../internal/converters.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{addMonthsClampingDay,formatISO,localDate,monthMatrix,parseISO,resolveFirstDayOfWeek,weekdayLabels}from"../../forms/date-picker/calendar-core.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{styles}from"./calendar.styles.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_calendarEmpty,LYRA_DEFAULT_calendarEventsOverflow,LYRA_DEFAULT_calendarLabel,LYRA_DEFAULT_calendarNextMonth,LYRA_DEFAULT_calendarPreviousMonth}from"../../../internal/default-strings.generated.js";const monthStart=date=>localDate(date.getFullYear(),date.getMonth(),1),MAX_DAY_CELL_EVENTS=4,MAX_AGENDA_EVENTS=500,canonicalEventSnapshots=new WeakMap;function normalizeCalendarEventDate(value){if(typeof value=="string"){const date=parseISO(value);return date?formatISO(date):void 0}if(typeof value=="number"){if(!Number.isFinite(value))return;const date=new Date(value);return Number.isNaN(date.getTime())?void 0:formatISO(date)}if(!(value===null||typeof value!="object"))try{const epoch=Date.prototype.getTime.call(value);return Number.isFinite(epoch)?formatISO(new Date(epoch)):void 0}catch{return}}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectCalendarEvent(value){if(!isSafeNonArrayObject(value))return;const date=getOwnDataDescriptor(value,"date"),title=getOwnDataDescriptor(value,"title"),color=getOwnDataDescriptor(value,"color");if(date===MISSING_OWN_DATA_DESCRIPTOR||date===UNSAFE_OWN_DATA_DESCRIPTOR||title===MISSING_OWN_DATA_DESCRIPTOR||title===UNSAFE_OWN_DATA_DESCRIPTOR||typeof title.value!="string"||title.value.trim().length===0)return;const normalizedDate=normalizeCalendarEventDate(date.value);if(normalizedDate)return Object.freeze({source:value,date:normalizedDate,title:title.value,color:color===MISSING_OWN_DATA_DESCRIPTOR||color===UNSAFE_OWN_DATA_DESCRIPTOR||typeof color.value!="string"?void 0:color.value})}function canonicalCalendarEvents(values){const cached=canonicalEventSnapshots.get(values);if(cached)return cached;const projected=[];for(const value of values){const event=projectCalendarEvent(value);event&&projected.push(event)}const snapshot=Object.freeze(projected);return canonicalEventSnapshots.set(values,snapshot),snapshot}const CALENDAR_VIEW=literalSetConverter(["month","agenda"],"month");class LyraCalendar extends LyraElement{constructor(){super(...arguments),this.events=[],this.value="",this.viewDate=formatISO(new Date).slice(0,7)+"-01",this._view="month",this.firstDayOfWeek="auto",this.accessibleLabel="",this.focusedDate=""}static{this.defaultStrings={...super.defaultStrings,calendarEmpty:LYRA_DEFAULT_calendarEmpty,calendarEventsOverflow:LYRA_DEFAULT_calendarEventsOverflow,calendarLabel:LYRA_DEFAULT_calendarLabel,calendarNextMonth:LYRA_DEFAULT_calendarNextMonth,calendarPreviousMonth:LYRA_DEFAULT_calendarPreviousMonth}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["events"])}static{this.identityCollectionProperties=Object.freeze(["events"])}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(value){const normalized=CALENDAR_VIEW.normalizeReflected(this,"view",value),previous=this._view;previous!==normalized&&(this._view=normalized,this.requestUpdate("view",previous))}get viewStart(){const parsed=parseISO(this.viewDate);return monthStart(parsed||new Date)}get normalizedFirstDayOfWeek(){return resolveFirstDayOfWeek(this.firstDayOfWeek,this.effectiveLocale)}changeMonth(delta){const next=localDate(this.viewStart.getFullYear(),this.viewStart.getMonth()+delta,1);this.viewDate=formatISO(next),this.emit("lr-view-change",{viewDate:this.viewDate})}selectDate(date){this.value=date,this.focusedDate=date,this.emit("lr-date-select",{date})}get effectiveEvents(){return canonicalCalendarEvents(this.events)}cachedBuckets(events){return this.buckets?.[0]!==events&&(this.buckets=[events,this.bucketEventsByDate(events)]),this.buckets[1]}bucketEventsByDate(events){const buckets=new Map;for(const event of events){const bucket=buckets.get(event.date);bucket?bucket.push(event):buckets.set(event.date,[event])}return buckets}weeks(){const start=this.viewStart;return monthMatrix(start.getFullYear(),start.getMonth(),this.normalizedFirstDayOfWeek)}gridBounds(weeks){return[weeks[0][0],weeks[weeks.length-1][6]]}onDayKeyDown(event,date){const rtl=this.effectiveDirection==="rtl",year=date.getFullYear(),month=date.getMonth(),day=date.getDate();let next;switch(event.key){case"ArrowLeft":next=localDate(year,month,day+(rtl?1:-1));break;case"ArrowRight":next=localDate(year,month,day+(rtl?-1:1));break;case"ArrowUp":next=localDate(year,month,day-7);break;case"ArrowDown":next=localDate(year,month,day+7);break;case"PageUp":next=addMonthsClampingDay(date,-1);break;case"PageDown":next=addMonthsClampingDay(date,1);break;case"Home":next=localDate(year,month,1);break;case"End":next=localDate(year,month+1,0);break;case"Enter":case" ":event.preventDefault(),this.selectDate(formatISO(date));return;default:return}event.preventDefault();const[gridFirst,gridLast]=this.gridBounds(this.weeks());(next<gridFirst||next>gridLast)&&(this.viewDate=formatISO(monthStart(next)),this.emit("lr-view-change",{viewDate:this.viewDate})),this.focusedDate=formatISO(next),queueMicrotask(()=>this.renderRoot.querySelector(`[data-date="${this.focusedDate}"]`)?.focus())}weekdays(){return weekdayLabels(this.normalizedFirstDayOfWeek,"short",this.effectiveLocale)}render(){const start=this.viewStart,weeks=this.weeks(),monthTitle=getDateTimeFormat(this.effectiveLocale,{month:"long",year:"numeric"}).format(start),today=formatISO(new Date),label=hostAriaLabel(this)??this.localize("calendarLabel"),dayLabelFmt=getDateTimeFormat(this.effectiveLocale,{dateStyle:"full"}),agendaDateFmt=getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium"}),dayNumberFmt=getNumberFormat(this.effectiveLocale),events=this.effectiveEvents,monthPrefix=formatISO(start).slice(0,7),agenda=this.view==="agenda"?events.filter(event=>event.date.startsWith(monthPrefix)).sort((a,b)=>a.date<b.date?-1:a.date>b.date?1:0):[],agendaTruncated=agenda.length>MAX_AGENDA_EVENTS,renderedAgenda=agenda.slice(0,MAX_AGENDA_EVENTS),eventsByDate=this.view==="month"?this.cachedBuckets(events):void 0,[gridFirst,gridLast]=this.gridBounds(weeks),rawAnchor=this.focusedDate||this.value||today,rawAnchorDate=parseISO(rawAnchor),anchor=rawAnchorDate&&rawAnchorDate>=gridFirst&&rawAnchorDate<=gridLast?rawAnchor:formatISO(start);return html`<section aria-label=${label}><header part="header navigation"><button part="nav previous-button" type="button" aria-label=${this.localize("calendarPreviousMonth")} @click=${()=>this.changeMonth(-1)}><span part="nav-glyph" aria-hidden="true">‹</span></button><span part="title">${monthTitle}</span><button part="nav next-button" type="button" aria-label=${this.localize("calendarNextMonth")} @click=${()=>this.changeMonth(1)}><span part="nav-glyph" aria-hidden="true">›</span></button></header>
|
|
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{literalSetConverter}from"../../../internal/converters.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{addMonthsClampingDay,formatISO,localDate,monthMatrix,parseISO,resolveFirstDayOfWeek,weekdayLabels}from"../../forms/date-picker/calendar-core.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{styles}from"./calendar.styles.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_calendarEmpty,LYRA_DEFAULT_calendarEventsOverflow,LYRA_DEFAULT_calendarLabel,LYRA_DEFAULT_calendarNextMonth,LYRA_DEFAULT_calendarPreviousMonth}from"../../../internal/default-strings/data.generated.js";const monthStart=date=>localDate(date.getFullYear(),date.getMonth(),1),MAX_DAY_CELL_EVENTS=4,MAX_AGENDA_EVENTS=500,canonicalEventSnapshots=new WeakMap;function normalizeCalendarEventDate(value){if(typeof value=="string"){const date=parseISO(value);return date?formatISO(date):void 0}if(typeof value=="number"){if(!Number.isFinite(value))return;const date=new Date(value);return Number.isNaN(date.getTime())?void 0:formatISO(date)}if(!(value===null||typeof value!="object"))try{const epoch=Date.prototype.getTime.call(value);return Number.isFinite(epoch)?formatISO(new Date(epoch)):void 0}catch{return}}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectCalendarEvent(value){if(!isSafeNonArrayObject(value))return;const date=getOwnDataDescriptor(value,"date"),title=getOwnDataDescriptor(value,"title"),color=getOwnDataDescriptor(value,"color");if(date===MISSING_OWN_DATA_DESCRIPTOR||date===UNSAFE_OWN_DATA_DESCRIPTOR||title===MISSING_OWN_DATA_DESCRIPTOR||title===UNSAFE_OWN_DATA_DESCRIPTOR||typeof title.value!="string"||title.value.trim().length===0)return;const normalizedDate=normalizeCalendarEventDate(date.value);if(normalizedDate)return Object.freeze({source:value,date:normalizedDate,title:title.value,color:color===MISSING_OWN_DATA_DESCRIPTOR||color===UNSAFE_OWN_DATA_DESCRIPTOR||typeof color.value!="string"?void 0:color.value})}function canonicalCalendarEvents(values){const cached=canonicalEventSnapshots.get(values);if(cached)return cached;const projected=[];for(const value of values){const event=projectCalendarEvent(value);event&&projected.push(event)}const snapshot=Object.freeze(projected);return canonicalEventSnapshots.set(values,snapshot),snapshot}const CALENDAR_VIEW=literalSetConverter(["month","agenda"],"month");class LyraCalendar extends LyraElement{constructor(){super(...arguments),this.events=[],this.value="",this.viewDate=formatISO(new Date).slice(0,7)+"-01",this._view="month",this.firstDayOfWeek="auto",this.accessibleLabel="",this.focusedDate=""}static{this.defaultStrings={...super.defaultStrings,calendarEmpty:LYRA_DEFAULT_calendarEmpty,calendarEventsOverflow:LYRA_DEFAULT_calendarEventsOverflow,calendarLabel:LYRA_DEFAULT_calendarLabel,calendarNextMonth:LYRA_DEFAULT_calendarNextMonth,calendarPreviousMonth:LYRA_DEFAULT_calendarPreviousMonth}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["events"])}static{this.identityCollectionProperties=Object.freeze(["events"])}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(value){const normalized=CALENDAR_VIEW.normalizeReflected(this,"view",value),previous=this._view;previous!==normalized&&(this._view=normalized,this.requestUpdate("view",previous))}get viewStart(){const parsed=parseISO(this.viewDate);return monthStart(parsed||new Date)}get normalizedFirstDayOfWeek(){return resolveFirstDayOfWeek(this.firstDayOfWeek,this.effectiveLocale)}changeMonth(delta){const next=localDate(this.viewStart.getFullYear(),this.viewStart.getMonth()+delta,1);this.viewDate=formatISO(next),this.emit("lr-view-change",{viewDate:this.viewDate})}selectDate(date){this.value=date,this.focusedDate=date,this.emit("lr-date-select",{date})}get effectiveEvents(){return canonicalCalendarEvents(this.events)}cachedBuckets(events){return this.buckets?.[0]!==events&&(this.buckets=[events,this.bucketEventsByDate(events)]),this.buckets[1]}bucketEventsByDate(events){const buckets=new Map;for(const event of events){const bucket=buckets.get(event.date);bucket?bucket.push(event):buckets.set(event.date,[event])}return buckets}weeks(){const start=this.viewStart;return monthMatrix(start.getFullYear(),start.getMonth(),this.normalizedFirstDayOfWeek)}gridBounds(weeks){return[weeks[0][0],weeks[weeks.length-1][6]]}onDayKeyDown(event,date){const rtl=this.effectiveDirection==="rtl",year=date.getFullYear(),month=date.getMonth(),day=date.getDate();let next;switch(event.key){case"ArrowLeft":next=localDate(year,month,day+(rtl?1:-1));break;case"ArrowRight":next=localDate(year,month,day+(rtl?-1:1));break;case"ArrowUp":next=localDate(year,month,day-7);break;case"ArrowDown":next=localDate(year,month,day+7);break;case"PageUp":next=addMonthsClampingDay(date,-1);break;case"PageDown":next=addMonthsClampingDay(date,1);break;case"Home":next=localDate(year,month,1);break;case"End":next=localDate(year,month+1,0);break;case"Enter":case" ":event.preventDefault(),this.selectDate(formatISO(date));return;default:return}event.preventDefault();const[gridFirst,gridLast]=this.gridBounds(this.weeks());(next<gridFirst||next>gridLast)&&(this.viewDate=formatISO(monthStart(next)),this.emit("lr-view-change",{viewDate:this.viewDate})),this.focusedDate=formatISO(next),queueMicrotask(()=>this.renderRoot.querySelector(`[data-date="${this.focusedDate}"]`)?.focus())}weekdays(){return weekdayLabels(this.normalizedFirstDayOfWeek,"short",this.effectiveLocale)}render(){const start=this.viewStart,weeks=this.weeks(),monthTitle=getDateTimeFormat(this.effectiveLocale,{month:"long",year:"numeric"}).format(start),today=formatISO(new Date),label=hostAriaLabel(this)??this.localize("calendarLabel"),dayLabelFmt=getDateTimeFormat(this.effectiveLocale,{dateStyle:"full"}),agendaDateFmt=getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium"}),dayNumberFmt=getNumberFormat(this.effectiveLocale),events=this.effectiveEvents,monthPrefix=formatISO(start).slice(0,7),agenda=this.view==="agenda"?events.filter(event=>event.date.startsWith(monthPrefix)).sort((a,b)=>a.date<b.date?-1:a.date>b.date?1:0):[],agendaTruncated=agenda.length>MAX_AGENDA_EVENTS,renderedAgenda=agenda.slice(0,MAX_AGENDA_EVENTS),eventsByDate=this.view==="month"?this.cachedBuckets(events):void 0,[gridFirst,gridLast]=this.gridBounds(weeks),rawAnchor=this.focusedDate||this.value||today,rawAnchorDate=parseISO(rawAnchor),anchor=rawAnchorDate&&rawAnchorDate>=gridFirst&&rawAnchorDate<=gridLast?rawAnchor:formatISO(start);return html`<section aria-label=${label}><header part="header navigation"><button part="nav previous-button" type="button" aria-label=${this.localize("calendarPreviousMonth")} @click=${()=>this.changeMonth(-1)}><span part="nav-glyph" aria-hidden="true">‹</span></button><span part="title">${monthTitle}</span><button part="nav next-button" type="button" aria-label=${this.localize("calendarNextMonth")} @click=${()=>this.changeMonth(1)}><span part="nav-glyph" aria-hidden="true">›</span></button></header>
|
|
2
2
|
${this.view==="agenda"?html`<div part="agenda">${agenda.length?html`${renderedAgenda.map(event=>{const date=parseISO(event.date),bg=event.color?sanitizeCssColor(event.color):void 0;return html`<button part="agenda-event" type="button" style=${styleMap(bg?{"--_lr-calendar-agenda-event-background":bg,"--_lr-calendar-agenda-event-foreground":"var(--lr-color-on-brand)"}:{})} @click=${()=>this.emit("lr-event-select",{event:event.source})}><strong>${date?agendaDateFmt.format(date):event.date}</strong> ${event.title}</button>`})}${agendaTruncated?html`<span part="agenda-limit">${this.localize("calendarEventsOverflow",void 0,{n:getNumberFormat(this.effectiveLocale).format(agenda.length-MAX_AGENDA_EVENTS)})}</span>`:nothing}`:html`<p part="empty">${this.localize("calendarEmpty")}</p>`}</div>`:html`<div part="weekdays">${this.weekdays().map(day=>html`<span part="weekday">${day}</span>`)}</div><div part="grid" role="grid" aria-label=${monthTitle}>${weeks.map(week=>html`<div part="week" role="row">${week.map(date=>{const dateIso=formatISO(date),dayEvents=eventsByDate?.get(dateIso)??[],dayTruncated=dayEvents.length>MAX_DAY_CELL_EVENTS;return html`<div part="day" role="gridcell" data-date=${dateIso} data-outside=${date.getMonth()!==start.getMonth()?"true":"false"} data-today=${dateIso===today?"true":"false"} data-selected=${dateIso===this.value?"true":"false"} aria-selected=${dateIso===this.value?"true":"false"} aria-current=${dateIso===today?"date":nothing} aria-label=${dayLabelFmt.format(date)} tabindex=${dateIso===anchor?"0":"-1"} @click=${event=>{(event.target===event.currentTarget||event.target.getAttribute("part")==="date")&&this.selectDate(dateIso)}} @keydown=${event=>{event.target===event.currentTarget&&this.onDayKeyDown(event,date)}}><span part="date">${dayNumberFmt.format(date.getDate())}</span>${dayEvents.slice(0,MAX_DAY_CELL_EVENTS).map(item=>{const bg=item.color?sanitizeCssColor(item.color):void 0;return html`<button part="event" type="button" style=${styleMap(bg?{backgroundColor:bg}:{})} @click=${event=>{event.stopPropagation(),this.emit("lr-event-select",{event:item.source})}}>${item.title}</button>`})}${dayTruncated?html`<span part="event-limit">${this.localize("calendarEventsOverflow",void 0,{n:getNumberFormat(this.effectiveLocale).format(dayEvents.length-MAX_DAY_CELL_EVENTS)})}</span>`:nothing}</div>`})}</div>`)}</div>`}</section>`}}__decorate([property({attribute:!1})],LyraCalendar.prototype,"events",void 0),__decorate([property()],LyraCalendar.prototype,"value",void 0),__decorate([property({attribute:"view-date"})],LyraCalendar.prototype,"viewDate",void 0),__decorate([property({reflect:!0,converter:CALENDAR_VIEW})],LyraCalendar.prototype,"view",null),__decorate([property({attribute:"first-day-of-week"})],LyraCalendar.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"aria-label"})],LyraCalendar.prototype,"accessibleLabel",void 0),__decorate([state()],LyraCalendar.prototype,"focusedDate",void 0);export{LyraCalendar};
|