@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{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{tag}from"../../../internal/prefix.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{configureTreeItemOwner,fromInteractiveDescendant,setTreeItemSelection,treeItemOwnerContext}from"./tree-owner-controller.js";import"./tree-item.class.js";import{TREE_MAX_RENDER_DEPTH,TREE_MAX_RENDER_NODES}from"./tree-types.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_noData,LYRA_DEFAULT_treeLimit,LYRA_DEFAULT_treeNodeMoved}from"../../../internal/default-strings.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]),TREE_BADGE_LIMIT=100,TREE_MAX_INSPECTED_POSITIONS=1e4,EMPTY_TREE_DATA=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function arrayLength(value){if(!Array.isArray(value))return 0;try{return Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.trunc(value.length)))}catch{return 0}}function normalizeBadges(value){if(!Array.isArray(value))return{truncated:value!==void 0};const badges=[],length=arrayLength(value);for(let index=0;index<Math.min(length,TREE_BADGE_LIMIT);index++){const raw=ownValue(value,String(index));if(!raw||typeof raw!="object"||Array.isArray(raw))continue;const text=ownValue(raw,"text");if(typeof text!="string")continue;const rawTone=ownValue(raw,"tone"),tone=rawTone==="brand"||rawTone==="success"||rawTone==="warning"||rawTone==="danger"?rawTone:"neutral",rawLabel=ownValue(raw,"label");badges.push(Object.freeze({text,tone,...typeof rawLabel=="string"?{label:rawLabel}:{}}))}return{badges:Object.freeze(badges),truncated:length>TREE_BADGE_LIMIT}}function sameIcon(left,right){if(Object.is(left,right))return!0;const a=left,b=right;if(!a||!b||typeof a!="object"||typeof b!="object"||a._$litType$===void 0||a._$litType$!==b._$litType$||a.strings!==b.strings)return!1;const leftValues=a.values??[],rightValues=b.values??[];return leftValues.length===rightValues.length&&leftValues.every((value,index)=>Object.is(value,rightValues[index]))}function sameBadges(left,right){return left===right?!0:!left||!right||left.length!==right.length?!1:left.every((badge,index)=>{const other=right[index];return badge.text===other.text&&badge.tone===other.tone&&badge.label===other.label})}function sameTreeNode(next,previous){if(next.id!==previous.id||next.label!==previous.label||next.selected!==previous.selected||next.disabled!==previous.disabled||next.lazy!==previous.lazy||next.description!==previous.description||next.accessibleLabel!==previous.accessibleLabel||!sameIcon(next.icon,previous.icon)||!sameBadges(next.badges,previous.badges))return!1;const children=next.children,previousChildren=previous.children;return!children||!previousChildren?children===void 0&&previousChildren===void 0:children.length===previousChildren.length&&children.every((child,index)=>child===previousChildren[index])}function indexTreeNodes(nodes){const byId=new Map,stack=[...nodes];for(;stack.length>0;){const node=stack.pop();byId.set(node.id,node),node.children&&stack.push(...node.children)}return byId}function normalizeTreeData(input,previous=EMPTY_TREE_DATA){if(!Array.isArray(input))return{data:EMPTY_TREE_DATA,declaredChildrenAtPath:new Map,declaredRootCount:0,truncated:input!=null,limitReached:!1};const root=[],declaredChildrenAtPath=new Map,created=[],rootLength=arrayLength(input);let truncated=!1,limitReached=!1,accepted=0,inspected=0;const seenIds=new Set,identityFilteredCollections=new Set,jobs=[{source:input,index:0,length:rootLength,target:root,parentPath:"",depth:0,ancestors:new Set}];for(;jobs.length>0;){const job=jobs[jobs.length-1];if(job.index>=job.length){jobs.pop();continue}if(accepted>=TREE_MAX_RENDER_NODES||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=TREE_MAX_RENDER_NODES;break}const raw=ownValue(job.source,String(job.index++));if(inspected++,inspected===TREE_MAX_INSPECTED_POSITIONS&&(truncated=!0),!raw||typeof raw!="object"||Array.isArray(raw)){truncated=!0,identityFilteredCollections.add(job.target);continue}const id=ownValue(raw,"id"),label=ownValue(raw,"label");if(typeof id!="string"||id.trim()===""||seenIds.has(id)||typeof label!="string"){truncated=!0,identityFilteredCollections.add(job.target);continue}seenIds.add(id);const node={id,label},selected=ownValue(raw,"selected"),disabled=ownValue(raw,"disabled"),lazy=ownValue(raw,"lazy");typeof selected=="boolean"&&(node.selected=selected),typeof disabled=="boolean"&&(node.disabled=disabled),typeof lazy=="boolean"&&(node.lazy=lazy);const icon=ownValue(raw,"icon");icon!==void 0&&(node.icon=icon);const description=ownValue(raw,"description");typeof description=="string"&&(node.description=description);const accessibleLabel=ownValue(raw,"accessibleLabel");typeof accessibleLabel=="string"&&(node.accessibleLabel=accessibleLabel);const normalizedBadges=normalizeBadges(ownValue(raw,"badges"));normalizedBadges.badges?.length&&(node.badges=normalizedBadges.badges),truncated||=normalizedBadges.truncated;const ownIndex=job.target.length,path=job.parentPath===""?String(ownIndex):`${job.parentPath}/${ownIndex}`;job.target.push(node),created.push(node),accepted++;const rawChildren=ownValue(raw,"children"),childCount=arrayLength(rawChildren);if(childCount===0)continue;if(declaredChildrenAtPath.set(path,childCount),job.depth>=TREE_MAX_RENDER_DEPTH||job.ancestors.has(raw)){truncated=!0;continue}const children=[];node.children=children;const ancestors=new Set(job.ancestors);ancestors.add(raw),jobs.push({source:rawChildren,index:0,length:childCount,target:children,parentPath:path,depth:job.depth+1,ancestors})}const previousById=previous.length>0?indexTreeNodes(previous):void 0,resolved=new Map,resolve=node=>resolved.get(node)??node;for(let index=created.length-1;index>=0;index--){const node=created[index];if(node.children){for(let child=0;child<node.children.length;child++)node.children[child]=resolve(node.children[child]);Object.freeze(node.children)}Object.freeze(node);const prior=previousById?.get(node.id);prior&&!(node.children&&identityFilteredCollections.has(node.children))&&sameTreeNode(node,prior)&&resolved.set(node,prior)}for(let index=0;index<root.length;index++)root[index]=resolve(root[index]);const normalizedJobs=root.map((node,index)=>({node,path:String(index)}));for(;normalizedJobs.length>0;){const{node,path}=normalizedJobs.pop(),children=node.children??[];identityFilteredCollections.has(children)&&declaredChildrenAtPath.set(path,children.length);for(let index=children.length-1;index>=0;index--)normalizedJobs.push({node:children[index],path:`${path}/${index}`})}return{data:Object.freeze(root),declaredChildrenAtPath,declaredRootCount:identityFilteredCollections.has(root)?root.length:rootLength,truncated,limitReached}}function isInertWithin(node,root){for(let current=node;current&¤t!==root;current=current.parentElement)if(current.hasAttribute("inert"))return!0;return!1}class LyraTree extends LyraElement{constructor(){super(...arguments),this._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.reorderable=!1,this._selection="single",this.activeId=null,this.hasAuthoredItems=!1,this.pendingFocusId=null,this.generatedNodes=new WeakSet,this.dataIdOwnerPaths=new Map,this.dataIdCollisions=new Set,this.selectionSyncPending=!0,this.dataSyncPending=!1,this.inertMutationPending=!1,this.dirtyConfigureRoots=new Set,this.lastFocusedNodeId=null,this.onTreeFocusIn=e=>{const path=e.composedPath(),owner=path.find(target=>target.localName===tag("tree"));if(owner&&owner!==this)return;const item=path.find(target=>target.nodeType===1&&target.localName===tag("tree-item"));item&&this.onItemFocus(item)},this.onItemFocus=element=>{const item=element;this.isNavigable(item)&&(this.lastFocusedNodeId=item.nodeId,this.activeId=item.nodeId)},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems(),wasAuthored&&!this.hasAuthoredItems&&(this.dataSyncPending=!0),this.selectionSyncPending=!0,this.requestUpdate()},this.childObserverGeneration=0,this.onChildMutations=allRecords=>{const records=allRecords.filter(record=>record.type!=="attributes"||record.oldValue!==null!==record.target.hasAttribute(record.attributeName??""));if(records.length!==0){if(records.some(record=>record.attributeName==="inert")&&(this.inertMutationPending=!0),records.every(record=>record.type==="attributes")){const itemTag=tag("tree-item");for(const record of records){const target=record.target;if(!(target instanceof Element)||target.localName!==itemTag)continue;const root=this.rootTreeItemAncestor(target);root&&this.dirtyConfigureRoots.add(root)}}else this.dirtyConfigureRoots.clear();this.onChildrenChanged()}},this.onNodeActivate=e=>{const node=this.eventNode(e);if(!node||node.isDisabled)return;this.selectionSyncPending=!0,this.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&(this.activeId=node.nodeId)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.activeId=node.nodeId,this.updateSelectionFrom(node)&&this.emit("lr-selection-change",Object.freeze({selection:this.selectedItems})))},this.onTreeKeyDown=e=>{const itemTag=tag("tree-item");if(fromInteractiveDescendant(e,target=>target.localName===itemTag))return;const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId),current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault(),this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}if(e.altKey)return;const rtl=this.effectiveDirection==="rtl",expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft",moved=resolveListMove(e.key,{count:visible.length,current:Math.max(currentIndex,0),orientation:"vertical",wrap:!1,clamp:!0});if(moved!==null){e.preventDefault(),this.focusNode(visible[moved]);return}switch(e.key){case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(!current.expanded)current.expand();else{const child=visible[currentIndex+1];child&&treeItemOwnerContext(child).depth>treeItemOwnerContext(current).depth&&this.focusNode(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&¤t.expanded)current.collapse();else for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&treeItemOwnerContext(sibling).depth<treeItemOwnerContext(current).depth){this.focusNode(sibling);break}}break;case"Enter":case" ":e.preventDefault(),current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,noData:LYRA_DEFAULT_noData,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-selection-change":Object.freeze(["selection"])})}static{this.styles=[LyraElement.styles,styles]}get data(){return this._data}set data(value){if(value===this._data||value===this.lastDataInput)return;this.lastDataInput=value,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data);this._data=normalized.data,this.declaredChildrenAtPath=normalized.declaredChildrenAtPath,this.declaredRootCount=normalized.declaredRootCount,this._dataTruncated=normalized.truncated,this._limitReached=normalized.limitReached,this.requestUpdate("data",previous)}get dataTruncated(){return this._dataTruncated}get selection(){return this._selection}set selection(value){const old=this._selection,normalized=TREE_SELECTIONS.has(value)?value:"single";old!==normalized&&(this._selection=normalized,this.selectionSyncPending=!0,this.requestUpdate("selection",old))}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&result.length<TREE_MAX_RENDER_NODES;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),result.push(node),depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return result}get selectedItems(){return Object.freeze(this.allNodeElements().filter(node=>node.selected))}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const expandIcon=this.iconSource("expand-icon"),collapseIcon=this.iconSource("collapse-icon"),roots=this.nodeElements,rootCount=this.hasAuthoredItems?roots.length:this.declaredRootCount,stack=[];for(let index=roots.length-1;index>=0;index--)stack.push({node:roots[index],ancestry:[],depth:0,setSize:rootCount,posInSet:index+1,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(index))});const seen=new Set;for(;stack.length>0&&seen.size<TREE_MAX_RENDER_NODES;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:this.activeId,ancestry:frame.ancestry,depth:frame.depth,setSize:frame.setSize,posInSet:frame.posInSet,selection:this.selection,ownsSelection:!0,identity:frame.identity,expandIcon,collapseIcon,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus}),frame.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(frame.node),declaredCount=frame.identity?.declaredChildrenAtPath.get(frame.identity.path)??frame.node.item?.children?.length??children.length,childAncestry=frame.node.item?[...frame.ancestry,frame.node.item]:frame.ancestry;for(let index=children.length-1;index>=0;index--){const identity=frame.identity?{path:`${frame.identity.path}/${index}`,ownerPaths:frame.identity.ownerPaths,collisionIds:frame.identity.collisionIds,declaredChildrenAtPath:frame.identity.declaredChildrenAtPath}:void 0;stack.push({node:children[index],ancestry:childAncestry,depth:frame.depth+1,setSize:declaredCount,posInSet:index+1,identity})}}}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=!1;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);this.setSelection(node,selected,!1),selected&&(kept=!0)}}setBranchSelection(node,selected,leavesOnly){const stack=[node],seen=new Set;for(;stack.length>0&&seen.size<TREE_MAX_RENDER_NODES;){const current=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&¤t.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1);for(let index=children.length-1;index>=0;index--)stack.push(children[index])}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1}],queued=new Set;for(;stack.length>0;){const entry=stack.pop();if(entry.visited){const current=entry.item;if(current.isDisabled){this.setSelection(current,!1,!1),states.set(current,"ignored");continue}const children2=this.childrenOf(current).filter(child=>!child.isDisabled);if(children2.length===0){leavesOnly&¤t.hasChildren?(this.setSelection(current,!1,!1),states.set(current,"none")):(this.setSelection(current,current.selected,!1),states.set(current,current.selected?"all":"none"));continue}const childStates=children2.map(child=>states.get(child)??"ignored").filter(state2=>state2!=="ignored");if(childStates.length===0){this.setSelection(current,!1,!1),states.set(current,"none");continue}const all=childStates.every(state2=>state2==="all"),none=childStates.every(state2=>state2==="none");this.setSelection(current,all,!all&&!none),states.set(current,all?"all":none?"none":"some");continue}if(queued.size>=TREE_MAX_RENDER_NODES||queued.has(entry.item))continue;queued.add(entry.item),stack.push({item:entry.item,visited:!0});const children=this.childrenOf(entry.item);for(let index=children.length-1;index>=0;index--)queued.has(children[index])||stack.push({item:children[index],visited:!1})}return states.get(node)??"none"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements())node.selected&&this.childrenOf(node).length>0&&this.setBranchSelection(node,!0,leavesOnly);for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){this.selection==="single"||this.selection==="leaf"?this.normalizeSingleSelection():this.normalizeMultipleSelection()}setSelection(node,selected,indeterminate){this.selectionBefore&&!this.selectionBefore.has(node)&&this.selectionBefore.set(node,[node.selected,node.indeterminate]),setTreeItemSelection(node,selected,indeterminate)}updateSelectionFrom(node){if(node.isDisabled||(this.selection==="single"||this.selection==="leaf")&&!this.selectableInSingleMode(node))return!1;const before=new Map;this.selectionBefore=before;try{if(this.selection==="single"||this.selection==="leaf")for(const candidate of this.allNodeElements())this.setSelection(candidate,candidate===node,!1);else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements)this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}finally{this.selectionBefore=void 0}for(const[candidate,[selected,indeterminate]]of before)if(candidate.selected!==selected||candidate.indeterminate!==indeterminate)return!0;return!1}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes)node.hasAttribute("slot")&&node.removeAttribute("slot");const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored)for(const node of nodes)this.generatedNodes.has(node)&&node.remove();this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&acc.length<TREE_MAX_RENDER_NODES;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),!this.isNavigable(node))||(acc.push(node),!node.expanded||depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return acc}findItem(items,id){const stack=[...items].reverse(),seen=new Set;for(;stack.length>0;){const item=stack.pop();if(!seen.has(item)){if(seen.add(item),item.id===id)return item;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push(child)}}}}isDuplicateDataPath(item,path){return this.dataIdCollisions.has(item.id)&&this.dataIdOwnerPaths.get(item.id)!==path}rebuildDataIdentity(){const ownerPaths=new Map,collisionIds=new Set,ancestry=new Set,stack=[{items:this.data,index:0,parentPath:"",depth:0}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame.index>=frame.items.length){frame.owner&&ancestry.delete(frame.owner),stack.pop();continue}const index=frame.index++,item=frame.items[index];if(!item)continue;const path=frame.parentPath===""?String(index):`${frame.parentPath}/${index}`;ownerPaths.has(item.id)?collisionIds.add(item.id):ownerPaths.set(item.id,path),!(frame.depth>=TREE_MAX_RENDER_DEPTH||ancestry.has(item)||!item.children?.length)&&(ancestry.add(item),stack.push({items:item.children,index:0,parentPath:path,depth:frame.depth+1,owner:item}))}this.dataIdOwnerPaths=ownerPaths,this.dataIdCollisions=collisionIds}treeIdentityAt(path){return{path,ownerPaths:this.dataIdOwnerPaths,collisionIds:this.dataIdCollisions,declaredChildrenAtPath:this.declaredChildrenAtPath}}firstEnabledId(items){for(let index=0;index<items.length;index++){const item=items[index];if(!(!item||item.disabled||this.isDuplicateDataPath(item,String(index))))return item.id}return null}isEnabledReachableId(items,id){const stack=items.map((item,index)=>({item,path:String(index)})).reverse(),seen=new Set;for(;stack.length>0;){const{item,path}=stack.pop();if(!seen.has(item)&&(seen.add(item),!(item.disabled||this.isDuplicateDataPath(item,path)))){if(item.id===id)return!0;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push({item:child,path:`${path}/${i}`})}}}return!1}findRenderedSiblings(node){const root=node.getRootNode(),shadowHost="host"in root?root.host:null,shadowParent=shadowHost?.localName===tag("tree-item")?shadowHost:null,lightParent=node.parentElement?.localName===tag("tree-item")?node.parentElement:null,parentItem=shadowParent??lightParent,siblings=parentItem?parentItem.childItems():this.nodeElements,index=siblings.indexOf(node);if(!(index<0))return{parent:parentItem,siblings,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=!1;const visible=this.visibleNodeElements();if(visible.some(node=>node.nodeId===this.activeId))return;const displaced=this.activeId;if(this.activeId=visible[0]?.nodeId??null,!inertMutation||this.activeId==null||displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument,active=deepActiveElementIn(ownerDocument),strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced||(this.pendingFocusId=this.activeId)}willUpdate(changed){if(super.willUpdate(changed),this.refreshAuthoredItems(),(changed.has("data")||changed.has("selection"))&&(this.selectionSyncPending=!0),this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=!1;const focused=this.deepFocusedNode(),focusedId=focused?.nodeId??null;this.rebuildDataIdentity(),this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId))&&(this.activeId=this.firstEnabledId(this.data)),this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}this.inertMutationPending&&this.resolveActiveFromDom()}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-tree-missing-accessible-name","<lr-tree> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){super.updated(changed);const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length;for(const node of this.dirtyConfigureRoots){const i=nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:this.activeId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:void 0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})}}else if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements,count=this.hasAuthoredItems?nodes.length:this.declaredRootCount;nodes.forEach((node,i)=>{configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:this.activeId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(i)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})})}targeted||(this.contextSyncPending=!0),this.dirtyConfigureRoots.clear(),this.scheduleTreeSync()}scheduleTreeSync(){this.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync())}async runTreeSync(){try{for(;this.syncRequested;)this.syncRequested=!1,await super.getUpdateComplete(),await cascadeUpdateComplete(this.nodeElements),this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{this.syncRunning=!1}}rootTreeItemAncestor(node){const itemTag=tag("tree-item");let current=node;for(;current&¤t.parentElement&¤t.parentElement!==this;)current=current.parentElement;return current&¤t.parentElement===this&¤t.localName===itemTag?current:null}connectedCallback(){super.connectedCallback(),this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback(),this.pendingReorder=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(!node.item)continue;const matches=existingById.get(node.item.id)??[];matches.push(node),existingById.set(node.item.id,matches)}let previousSibling=null;for(let index=0;index<this.data.length;index++){const item=this.data[index];let node=existingById.get(item.id)?.shift();node||(node=this.ownerDocument.createElement(tag("tree-item")),this.generatedNodes.add(node)),node.item=item,configureTreeItemOwner(node,{...treeItemOwnerContext(node),ancestry:[],depth:0,setSize:this.declaredRootCount,posInSet:index+1,selection:this.selection,ownsSelection:!0,identity:this.treeIdentityAt(String(index)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus});const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;targetPosition!==node&&this.insertBefore(node,targetPosition),previousSibling=node}for(const nodes of existingById.values())for(const node of nodes)node.remove()}focusNode(node){node&&(this.activeId=node.nodeId,node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=[...this.childrenOf(root)];for(let visited=0;stack.length>0&&visited<TREE_MAX_RENDER_NODES;visited++){const item=stack.pop();if(item.nodeId===id)return!0;stack.push(...this.childrenOf(item))}return!1}focusIsWithin(node){for(let current=deepActiveElementIn(this.ownerDocument);current;current=composedParentElement(current)){if(current===node)return!0;if(current===this)return!1}return!1}eventNode(e){const path=e.composedPath(),origin=path[0];if(origin?.nodeType===1&&origin.localName===tag("tree-item")){const treeTag=tag("tree");for(const target of path){if(target===this)return origin;if(target.localName===treeTag)return}return}const id=e.detail?.nodeId;return this.allNodeElements().find(candidate=>candidate.nodeId===id)}async getUpdateComplete(){let result=await super.getUpdateComplete();for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return await cascadeUpdateComplete(this.nodeElements),result}reportRefreshSelectionChange(){const before=this.selectionBeforeRefresh;if(before===void 0||this.isUpdatePending)return;this.selectionBeforeRefresh=void 0;const selection=this.selectedItems;selection.length===before.length&&selection.every((item,index)=>item.nodeId===before[index])||this.emit("lr-selection-change",Object.freeze({selection}))}restorePendingFocus(){if(this.pendingFocusId==null)return;const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}requestReorder(node,delta){const id=node.nodeId,found=this.findRenderedSiblings(node);if(!found)return;const{parent,siblings,index}=found,total=siblings.length,toIndex=index+delta;toIndex<0||toIndex>=total||(this.pendingReorder={node,parent,originalSiblings:[...siblings],targetSibling:siblings[toIndex],fromIndex:index,toIndex},this.emit("lr-reorder",{nodeId:id,parentNodeId:parent?.nodeId??null,fromIndex:index,toIndex}))}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const found=this.findRenderedSiblings(pending.node);if(!found){this.pendingReorder=void 0;return}(found.siblings.length!==pending.originalSiblings.length||found.siblings.some((node,index)=>node!==pending.originalSiblings[index]))&&(this.pendingReorder=void 0,!(found.parent!==pending.parent||found.index!==pending.toIndex||found.siblings[pending.fromIndex]!==pending.targetSibling)&&this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:pending.node.nodeLabel,index:this.formatCount(found.index+1),total:this.formatCount(found.siblings.length)}),{force:!0}))}async expandAll(){const queue=this.nodeElements.map(node=>({node,depth:0})),seen=new Set;this.bulkExpansions+=1;try{for(let index=0;index<queue.length&&seen.size<TREE_MAX_RENDER_NODES;index++){const{node,depth}=queue[index];seen.has(node)||(seen.add(node),node.isDisabled?node.expanded=!1:node.hasChildren&&node.expand(),await node.updateComplete,depth<TREE_MAX_RENDER_DEPTH&&queue.push(...this.childrenOf(node).map(child=>({node:child,depth:depth+1}))))}}finally{this.bulkExpansions-=1}this.bulkExpansions===0&&this.syncRequested&&this.scheduleTreeSync(),await this.updateComplete}async collapseAll(){const focused=this.deepFocusedNode(),topLevel=this.nodeElements,nodes=this.allNodeElements();for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.isDisabled?node.expanded=!1:node.collapse()}(this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId))||(this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)),focused&&(this.pendingFocusId=this.activeId),await cascadeUpdateComplete(topLevel)}render(){return html`
|
|
1
|
+
import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{tag}from"../../../internal/prefix.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{styles}from"./tree.styles.js";import{cascadeUpdateComplete}from"./update-cascade.js";import{configureTreeItemOwner,fromInteractiveDescendant,setTreeItemSelection,treeItemOwnerContext}from"./tree-owner-controller.js";import"./tree-item.class.js";import{TREE_MAX_RENDER_DEPTH,TREE_MAX_RENDER_NODES}from"./tree-types.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_treeLimit}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_noData,LYRA_DEFAULT_treeNodeMoved}from"../../../internal/default-strings/shared.generated.js";const TREE_SELECTIONS=new Set(["single","multiple","leaf","leaf-multiple"]),TREE_BADGE_LIMIT=100,TREE_MAX_INSPECTED_POSITIONS=1e4,EMPTY_TREE_DATA=Object.freeze([]);function ownValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function arrayLength(value){if(!Array.isArray(value))return 0;try{return Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,Math.trunc(value.length)))}catch{return 0}}function normalizeBadges(value){if(!Array.isArray(value))return{truncated:value!==void 0};const badges=[],length=arrayLength(value);for(let index=0;index<Math.min(length,TREE_BADGE_LIMIT);index++){const raw=ownValue(value,String(index));if(!raw||typeof raw!="object"||Array.isArray(raw))continue;const text=ownValue(raw,"text");if(typeof text!="string")continue;const rawTone=ownValue(raw,"tone"),tone=rawTone==="brand"||rawTone==="success"||rawTone==="warning"||rawTone==="danger"?rawTone:"neutral",rawLabel=ownValue(raw,"label");badges.push(Object.freeze({text,tone,...typeof rawLabel=="string"?{label:rawLabel}:{}}))}return{badges:Object.freeze(badges),truncated:length>TREE_BADGE_LIMIT}}function sameIcon(left,right){if(Object.is(left,right))return!0;const a=left,b=right;if(!a||!b||typeof a!="object"||typeof b!="object"||a._$litType$===void 0||a._$litType$!==b._$litType$||a.strings!==b.strings)return!1;const leftValues=a.values??[],rightValues=b.values??[];return leftValues.length===rightValues.length&&leftValues.every((value,index)=>Object.is(value,rightValues[index]))}function sameBadges(left,right){return left===right?!0:!left||!right||left.length!==right.length?!1:left.every((badge,index)=>{const other=right[index];return badge.text===other.text&&badge.tone===other.tone&&badge.label===other.label})}function sameTreeNode(next,previous){if(next.id!==previous.id||next.label!==previous.label||next.selected!==previous.selected||next.disabled!==previous.disabled||next.lazy!==previous.lazy||next.description!==previous.description||next.accessibleLabel!==previous.accessibleLabel||!sameIcon(next.icon,previous.icon)||!sameBadges(next.badges,previous.badges))return!1;const children=next.children,previousChildren=previous.children;return!children||!previousChildren?children===void 0&&previousChildren===void 0:children.length===previousChildren.length&&children.every((child,index)=>child===previousChildren[index])}function indexTreeNodes(nodes){const byId=new Map,stack=[...nodes];for(;stack.length>0;){const node=stack.pop();byId.set(node.id,node),node.children&&stack.push(...node.children)}return byId}function normalizeTreeData(input,previous=EMPTY_TREE_DATA){if(!Array.isArray(input))return{data:EMPTY_TREE_DATA,declaredChildrenAtPath:new Map,declaredRootCount:0,truncated:input!=null,limitReached:!1};const root=[],declaredChildrenAtPath=new Map,created=[],rootLength=arrayLength(input);let truncated=!1,limitReached=!1,accepted=0,inspected=0;const seenIds=new Set,identityFilteredCollections=new Set,jobs=[{source:input,index:0,length:rootLength,target:root,parentPath:"",depth:0,ancestors:new Set}];for(;jobs.length>0;){const job=jobs[jobs.length-1];if(job.index>=job.length){jobs.pop();continue}if(accepted>=TREE_MAX_RENDER_NODES||inspected>=TREE_MAX_INSPECTED_POSITIONS){truncated=!0,limitReached=accepted>=TREE_MAX_RENDER_NODES;break}const raw=ownValue(job.source,String(job.index++));if(inspected++,inspected===TREE_MAX_INSPECTED_POSITIONS&&(truncated=!0),!raw||typeof raw!="object"||Array.isArray(raw)){truncated=!0,identityFilteredCollections.add(job.target);continue}const id=ownValue(raw,"id"),label=ownValue(raw,"label");if(typeof id!="string"||id.trim()===""||seenIds.has(id)||typeof label!="string"){truncated=!0,identityFilteredCollections.add(job.target);continue}seenIds.add(id);const node={id,label},selected=ownValue(raw,"selected"),disabled=ownValue(raw,"disabled"),lazy=ownValue(raw,"lazy");typeof selected=="boolean"&&(node.selected=selected),typeof disabled=="boolean"&&(node.disabled=disabled),typeof lazy=="boolean"&&(node.lazy=lazy);const icon=ownValue(raw,"icon");icon!==void 0&&(node.icon=icon);const description=ownValue(raw,"description");typeof description=="string"&&(node.description=description);const accessibleLabel=ownValue(raw,"accessibleLabel");typeof accessibleLabel=="string"&&(node.accessibleLabel=accessibleLabel);const normalizedBadges=normalizeBadges(ownValue(raw,"badges"));normalizedBadges.badges?.length&&(node.badges=normalizedBadges.badges),truncated||=normalizedBadges.truncated;const ownIndex=job.target.length,path=job.parentPath===""?String(ownIndex):`${job.parentPath}/${ownIndex}`;job.target.push(node),created.push(node),accepted++;const rawChildren=ownValue(raw,"children"),childCount=arrayLength(rawChildren);if(childCount===0)continue;if(declaredChildrenAtPath.set(path,childCount),job.depth>=TREE_MAX_RENDER_DEPTH||job.ancestors.has(raw)){truncated=!0;continue}const children=[];node.children=children;const ancestors=new Set(job.ancestors);ancestors.add(raw),jobs.push({source:rawChildren,index:0,length:childCount,target:children,parentPath:path,depth:job.depth+1,ancestors})}const previousById=previous.length>0?indexTreeNodes(previous):void 0,resolved=new Map,resolve=node=>resolved.get(node)??node;for(let index=created.length-1;index>=0;index--){const node=created[index];if(node.children){for(let child=0;child<node.children.length;child++)node.children[child]=resolve(node.children[child]);Object.freeze(node.children)}Object.freeze(node);const prior=previousById?.get(node.id);prior&&!(node.children&&identityFilteredCollections.has(node.children))&&sameTreeNode(node,prior)&&resolved.set(node,prior)}for(let index=0;index<root.length;index++)root[index]=resolve(root[index]);const normalizedJobs=root.map((node,index)=>({node,path:String(index)}));for(;normalizedJobs.length>0;){const{node,path}=normalizedJobs.pop(),children=node.children??[];identityFilteredCollections.has(children)&&declaredChildrenAtPath.set(path,children.length);for(let index=children.length-1;index>=0;index--)normalizedJobs.push({node:children[index],path:`${path}/${index}`})}return{data:Object.freeze(root),declaredChildrenAtPath,declaredRootCount:identityFilteredCollections.has(root)?root.length:rootLength,truncated,limitReached}}function isInertWithin(node,root){for(let current=node;current&¤t!==root;current=current.parentElement)if(current.hasAttribute("inert"))return!0;return!1}class LyraTree extends LyraElement{constructor(){super(...arguments),this._data=EMPTY_TREE_DATA,this.lastDataInput=void 0,this.declaredChildrenAtPath=new Map,this.declaredRootCount=0,this._dataTruncated=!1,this._limitReached=!1,this.label="",this.reorderable=!1,this._selection="single",this.activeId=null,this.hasAuthoredItems=!1,this.pendingFocusId=null,this.generatedNodes=new WeakSet,this.dataIdOwnerPaths=new Map,this.dataIdCollisions=new Set,this.selectionSyncPending=!0,this.dataSyncPending=!1,this.inertMutationPending=!1,this.dirtyConfigureRoots=new Set,this.lastFocusedNodeId=null,this.onTreeFocusIn=e=>{const path=e.composedPath(),owner=path.find(target=>target.localName===tag("tree"));if(owner&&owner!==this)return;const item=path.find(target=>target.nodeType===1&&target.localName===tag("tree-item"));item&&this.onItemFocus(item)},this.onItemFocus=element=>{const item=element;this.isNavigable(item)&&(this.lastFocusedNodeId=item.nodeId,this.activeId=item.nodeId)},this.contextSyncPending=!0,this.bulkExpansions=0,this.syncRequested=!1,this.syncRunning=!1,this.requestContextSync=()=>{this.contextSyncPending=!0,this.scheduleTreeSync()},this.onChildrenChanged=()=>{const wasAuthored=this.hasAuthoredItems;this.refreshAuthoredItems(),wasAuthored&&!this.hasAuthoredItems&&(this.dataSyncPending=!0),this.selectionSyncPending=!0,this.requestUpdate()},this.childObserverGeneration=0,this.onChildMutations=allRecords=>{const records=allRecords.filter(record=>record.type!=="attributes"||record.oldValue!==null!==record.target.hasAttribute(record.attributeName??""));if(records.length!==0){if(records.some(record=>record.attributeName==="inert")&&(this.inertMutationPending=!0),records.every(record=>record.type==="attributes")){const itemTag=tag("tree-item");for(const record of records){const target=record.target;if(!(target instanceof Element)||target.localName!==itemTag)continue;const root=this.rootTreeItemAncestor(target);root&&this.dirtyConfigureRoots.add(root)}}else this.dirtyConfigureRoots.clear();this.onChildrenChanged()}},this.onNodeActivate=e=>{const node=this.eventNode(e);if(!node||node.isDisabled)return;this.selectionSyncPending=!0,this.requestUpdate();const expanded=e.detail?.expanded===!0;(this.focusIsWithin(node)||!expanded&&this.activeId!==node.nodeId&&this.subtreeHasId(node,this.activeId))&&(this.activeId=node.nodeId)},this.onNodeSelect=event=>{const node=this.eventNode(event);!node||node.isDisabled||(this.activeId=node.nodeId,this.updateSelectionFrom(node)&&this.emit("lr-selection-change",Object.freeze({selection:this.selectedItems})))},this.onTreeKeyDown=e=>{const itemTag=tag("tree-item");if(fromInteractiveDescendant(e,target=>target.localName===itemTag))return;const visible=this.visibleNodeElements();if(visible.length===0)return;const currentIndex=visible.findIndex(n=>n.nodeId===this.activeId),current=currentIndex>=0?visible[currentIndex]:visible[0];if(!current)return;if(this.reorderable&&(e.ctrlKey||e.metaKey)&&(e.key==="ArrowUp"||e.key==="ArrowDown")){e.preventDefault(),this.requestReorder(current,e.key==="ArrowDown"?1:-1);return}if(e.altKey)return;const rtl=this.effectiveDirection==="rtl",expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft",moved=resolveListMove(e.key,{count:visible.length,current:Math.max(currentIndex,0),orientation:"vertical",wrap:!1,clamp:!0});if(moved!==null){e.preventDefault(),this.focusNode(visible[moved]);return}switch(e.key){case expandKey:if(e.preventDefault(),!current.hasChildren)break;if(!current.expanded)current.expand();else{const child=visible[currentIndex+1];child&&treeItemOwnerContext(child).depth>treeItemOwnerContext(current).depth&&this.focusNode(child)}break;case collapseKey:if(e.preventDefault(),current.hasChildren&¤t.expanded)current.collapse();else for(let i=currentIndex-1;i>=0;i--){const sibling=visible[i];if(sibling&&treeItemOwnerContext(sibling).depth<treeItemOwnerContext(current).depth){this.focusNode(sibling);break}}break;case"Enter":case" ":e.preventDefault(),current.select();break;default:return}}}static{this.defaultStrings={...super.defaultStrings,noData:LYRA_DEFAULT_noData,treeLimit:LYRA_DEFAULT_treeLimit,treeNodeMoved:LYRA_DEFAULT_treeNodeMoved}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-selection-change":Object.freeze(["selection"])})}static{this.styles=[LyraElement.styles,styles]}get data(){return this._data}set data(value){if(value===this._data||value===this.lastDataInput)return;this.lastDataInput=value,this.hasUpdated&&this.selectionBeforeRefresh===void 0&&(this.selectionBeforeRefresh=this.selectedItems.map(item=>item.nodeId));const previous=this._data,normalized=normalizeTreeData(value,this._data);this._data=normalized.data,this.declaredChildrenAtPath=normalized.declaredChildrenAtPath,this.declaredRootCount=normalized.declaredRootCount,this._dataTruncated=normalized.truncated,this._limitReached=normalized.limitReached,this.requestUpdate("data",previous)}get dataTruncated(){return this._dataTruncated}get selection(){return this._selection}set selection(value){const old=this._selection,normalized=TREE_SELECTIONS.has(value)?value:"single";old!==normalized&&(this._selection=normalized,this.selectionSyncPending=!0,this.requestUpdate("selection",old))}get nodeElements(){return[...this.querySelectorAll(`:scope > ${tag("tree-item")}`)]}childrenOf(node){return node.childItems()}isNavigable(node){return!node.isDisabled&&!isInertWithin(node,this)}allNodeElements(){const result=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&result.length<TREE_MAX_RENDER_NODES;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),result.push(node),depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return result}get selectedItems(){return Object.freeze(this.allNodeElements().filter(node=>node.selected))}iconSource(name){return this.querySelector(`:scope > [slot="${name}"]`)}applyTreeContext(){const expandIcon=this.iconSource("expand-icon"),collapseIcon=this.iconSource("collapse-icon"),roots=this.nodeElements,rootCount=this.hasAuthoredItems?roots.length:this.declaredRootCount,stack=[];for(let index=roots.length-1;index>=0;index--)stack.push({node:roots[index],ancestry:[],depth:0,setSize:rootCount,posInSet:index+1,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(index))});const seen=new Set;for(;stack.length>0&&seen.size<TREE_MAX_RENDER_NODES;){const frame=stack.pop();if(seen.has(frame.node)||(seen.add(frame.node),configureTreeItemOwner(frame.node,{...treeItemOwnerContext(frame.node),activeId:this.activeId,ancestry:frame.ancestry,depth:frame.depth,setSize:frame.setSize,posInSet:frame.posInSet,selection:this.selection,ownsSelection:!0,identity:frame.identity,expandIcon,collapseIcon,syncOwner:this.requestContextSync,focusOwner:this.onItemFocus}),frame.depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(frame.node),declaredCount=frame.identity?.declaredChildrenAtPath.get(frame.identity.path)??frame.node.item?.children?.length??children.length,childAncestry=frame.node.item?[...frame.ancestry,frame.node.item]:frame.ancestry;for(let index=children.length-1;index>=0;index--){const identity=frame.identity?{path:`${frame.identity.path}/${index}`,ownerPaths:frame.identity.ownerPaths,collisionIds:frame.identity.collisionIds,declaredChildrenAtPath:frame.identity.declaredChildrenAtPath}:void 0;stack.push({node:children[index],ancestry:childAncestry,depth:frame.depth+1,setSize:declaredCount,posInSet:index+1,identity})}}}selectableInSingleMode(node){return!node.isDisabled&&(this.selection!=="leaf"||!node.hasChildren)}normalizeSingleSelection(){let kept=!1;for(const node of this.allNodeElements()){const selected=!kept&&node.selected&&this.selectableInSingleMode(node);this.setSelection(node,selected,!1),selected&&(kept=!0)}}setBranchSelection(node,selected,leavesOnly){const stack=[node],seen=new Set;for(;stack.length>0&&seen.size<TREE_MAX_RENDER_NODES;){const current=stack.pop();if(seen.has(current)||current.isDisabled)continue;seen.add(current);const children=this.childrenOf(current).filter(child=>!child.isDisabled);!leavesOnly||children.length===0?this.setSelection(current,leavesOnly&¤t.hasChildren?!1:selected,!1):this.setSelection(current,!1,!1);for(let index=children.length-1;index>=0;index--)stack.push(children[index])}}deriveMultipleSelection(node,leavesOnly){const states=new Map,stack=[{item:node,visited:!1}],queued=new Set;for(;stack.length>0;){const entry=stack.pop();if(entry.visited){const current=entry.item;if(current.isDisabled){this.setSelection(current,!1,!1),states.set(current,"ignored");continue}const children2=this.childrenOf(current).filter(child=>!child.isDisabled);if(children2.length===0){leavesOnly&¤t.hasChildren?(this.setSelection(current,!1,!1),states.set(current,"none")):(this.setSelection(current,current.selected,!1),states.set(current,current.selected?"all":"none"));continue}const childStates=children2.map(child=>states.get(child)??"ignored").filter(state2=>state2!=="ignored");if(childStates.length===0){this.setSelection(current,!1,!1),states.set(current,"none");continue}const all=childStates.every(state2=>state2==="all"),none=childStates.every(state2=>state2==="none");this.setSelection(current,all,!all&&!none),states.set(current,all?"all":none?"none":"some");continue}if(queued.size>=TREE_MAX_RENDER_NODES||queued.has(entry.item))continue;queued.add(entry.item),stack.push({item:entry.item,visited:!0});const children=this.childrenOf(entry.item);for(let index=children.length-1;index>=0;index--)queued.has(children[index])||stack.push({item:children[index],visited:!1})}return states.get(node)??"none"}normalizeMultipleSelection(){const leavesOnly=this.selection==="leaf-multiple";for(const node of this.allNodeElements())node.selected&&this.childrenOf(node).length>0&&this.setBranchSelection(node,!0,leavesOnly);for(const root of this.nodeElements)this.deriveMultipleSelection(root,leavesOnly)}normalizeSelection(){this.selection==="single"||this.selection==="leaf"?this.normalizeSingleSelection():this.normalizeMultipleSelection()}setSelection(node,selected,indeterminate){this.selectionBefore&&!this.selectionBefore.has(node)&&this.selectionBefore.set(node,[node.selected,node.indeterminate]),setTreeItemSelection(node,selected,indeterminate)}updateSelectionFrom(node){if(node.isDisabled||(this.selection==="single"||this.selection==="leaf")&&!this.selectableInSingleMode(node))return!1;const before=new Map;this.selectionBefore=before;try{if(this.selection==="single"||this.selection==="leaf")for(const candidate of this.allNodeElements())this.setSelection(candidate,candidate===node,!1);else{const select=node.indeterminate||!node.selected;this.setBranchSelection(node,select,this.selection==="leaf-multiple");for(const root of this.nodeElements)this.deriveMultipleSelection(root,this.selection==="leaf-multiple")}}finally{this.selectionBefore=void 0}for(const[candidate,[selected,indeterminate]]of before)if(candidate.selected!==selected||candidate.indeterminate!==indeterminate)return!0;return!1}refreshAuthoredItems(){const nodes=this.nodeElements;for(const node of nodes)node.hasAttribute("slot")&&node.removeAttribute("slot");const authored=nodes.some(node=>!this.generatedNodes.has(node));if(authored)for(const node of nodes)this.generatedNodes.has(node)&&node.remove();this.hasAuthoredItems=authored}visibleNodeElements(){const acc=[],seen=new Set,stack=this.nodeElements.map(node=>({node,depth:0})).reverse();for(;stack.length>0&&acc.length<TREE_MAX_RENDER_NODES;){const{node,depth}=stack.pop();if(seen.has(node)||(seen.add(node),!this.isNavigable(node))||(acc.push(node),!node.expanded||depth>=TREE_MAX_RENDER_DEPTH))continue;const children=this.childrenOf(node);for(let index=children.length-1;index>=0;index--)stack.push({node:children[index],depth:depth+1})}return acc}findItem(items,id){const stack=[...items].reverse(),seen=new Set;for(;stack.length>0;){const item=stack.pop();if(!seen.has(item)){if(seen.add(item),item.id===id)return item;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push(child)}}}}isDuplicateDataPath(item,path){return this.dataIdCollisions.has(item.id)&&this.dataIdOwnerPaths.get(item.id)!==path}rebuildDataIdentity(){const ownerPaths=new Map,collisionIds=new Set,ancestry=new Set,stack=[{items:this.data,index:0,parentPath:"",depth:0}];for(;stack.length>0;){const frame=stack[stack.length-1];if(frame.index>=frame.items.length){frame.owner&&ancestry.delete(frame.owner),stack.pop();continue}const index=frame.index++,item=frame.items[index];if(!item)continue;const path=frame.parentPath===""?String(index):`${frame.parentPath}/${index}`;ownerPaths.has(item.id)?collisionIds.add(item.id):ownerPaths.set(item.id,path),!(frame.depth>=TREE_MAX_RENDER_DEPTH||ancestry.has(item)||!item.children?.length)&&(ancestry.add(item),stack.push({items:item.children,index:0,parentPath:path,depth:frame.depth+1,owner:item}))}this.dataIdOwnerPaths=ownerPaths,this.dataIdCollisions=collisionIds}treeIdentityAt(path){return{path,ownerPaths:this.dataIdOwnerPaths,collisionIds:this.dataIdCollisions,declaredChildrenAtPath:this.declaredChildrenAtPath}}firstEnabledId(items){for(let index=0;index<items.length;index++){const item=items[index];if(!(!item||item.disabled||this.isDuplicateDataPath(item,String(index))))return item.id}return null}isEnabledReachableId(items,id){const stack=items.map((item,index)=>({item,path:String(index)})).reverse(),seen=new Set;for(;stack.length>0;){const{item,path}=stack.pop();if(!seen.has(item)&&(seen.add(item),!(item.disabled||this.isDuplicateDataPath(item,path)))){if(item.id===id)return!0;if(item.children)for(let i=item.children.length-1;i>=0;i--){const child=item.children[i];child&&stack.push({item:child,path:`${path}/${i}`})}}}return!1}findRenderedSiblings(node){const root=node.getRootNode(),shadowHost="host"in root?root.host:null,shadowParent=shadowHost?.localName===tag("tree-item")?shadowHost:null,lightParent=node.parentElement?.localName===tag("tree-item")?node.parentElement:null,parentItem=shadowParent??lightParent,siblings=parentItem?parentItem.childItems():this.nodeElements,index=siblings.indexOf(node);if(!(index<0))return{parent:parentItem,siblings,index}}deepFocusedNode(){const active=deepActiveElementIn(this.ownerDocument);if(!active||active.localName!==tag("tree-item"))return null;const node=active;return this.visibleNodeElements().some(n=>n.nodeId===node.nodeId)?node:null}resolveActiveFromDom(){const inertMutation=this.inertMutationPending;this.inertMutationPending=!1;const visible=this.visibleNodeElements();if(visible.some(node=>node.nodeId===this.activeId))return;const displaced=this.activeId;if(this.activeId=visible[0]?.nodeId??null,!inertMutation||this.activeId==null||displaced==null||displaced!==this.lastFocusedNodeId)return;const ownerDocument=this.ownerDocument,active=deepActiveElementIn(ownerDocument),strandedOnDisplaced=active?.nodeType===1&&active.localName===tag("tree-item")&&active.nodeId===displaced;active!==null&&active!==ownerDocument.body&&!strandedOnDisplaced||(this.pendingFocusId=this.activeId)}willUpdate(changed){if(super.willUpdate(changed),this.refreshAuthoredItems(),(changed.has("data")||changed.has("selection"))&&(this.selectionSyncPending=!0),this.hasAuthoredItems){this.resolveActiveFromDom();return}if(changed.has("data")||this.dataSyncPending){this.dataSyncPending=!1;const focused=this.deepFocusedNode(),focusedId=focused?.nodeId??null;this.rebuildDataIdentity(),this.syncNodes();const activeItem=this.activeId?this.findItem(this.data,this.activeId):void 0;(!this.activeId||!activeItem||activeItem.disabled||!this.isEnabledReachableId(this.data,this.activeId))&&(this.activeId=this.firstEnabledId(this.data)),this.pendingFocusId=focused==null?null:focusedId!=null&&this.findItem(this.data,focusedId)?focusedId:this.activeId}this.inertMutationPending&&this.resolveActiveFromDom()}firstUpdated(changed){super.firstUpdated(changed),hostAriaLabel(this)==null&&!this.label&&devWarnOnce("lyra-tree-missing-accessible-name","<lr-tree> has no accessible name: set `label` or a host `aria-label`.")}updated(changed){super.updated(changed);const targeted=changed.size===0&&this.hasAuthoredItems&&this.dirtyConfigureRoots.size>0;if(targeted){const nodes=this.nodeElements,count=nodes.length;for(const node of this.dirtyConfigureRoots){const i=nodes.indexOf(node);i<0||configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:this.activeId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:void 0,expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})}}else if(changed.has("activeId")||changed.has("data")||this.hasAuthoredItems){const nodes=this.nodeElements,count=this.hasAuthoredItems?nodes.length:this.declaredRootCount;nodes.forEach((node,i)=>{configureTreeItemOwner(node,{...treeItemOwnerContext(node),activeId:this.activeId,ancestry:[],depth:0,setSize:count,posInSet:i+1,selection:this.selection,ownsSelection:!0,identity:this.hasAuthoredItems?void 0:this.treeIdentityAt(String(i)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus})})}targeted||(this.contextSyncPending=!0),this.dirtyConfigureRoots.clear(),this.scheduleTreeSync()}scheduleTreeSync(){this.syncRequested=!0,!(this.syncRunning||this.bulkExpansions>0)&&(this.syncRunning=!0,this.syncTask=this.runTreeSync())}async runTreeSync(){try{for(;this.syncRequested;)this.syncRequested=!1,await super.getUpdateComplete(),await cascadeUpdateComplete(this.nodeElements),this.contextSyncPending&&(this.contextSyncPending=!1,this.applyTreeContext()),this.selectionSyncPending&&(this.selectionSyncPending=!1,this.normalizeSelection()),await cascadeUpdateComplete(this.nodeElements),this.reportRefreshSelectionChange(),this.confirmPendingReorder(),this.restorePendingFocus()}finally{this.syncRunning=!1}}rootTreeItemAncestor(node){const itemTag=tag("tree-item");let current=node;for(;current&¤t.parentElement&¤t.parentElement!==this;)current=current.parentElement;return current&¤t.parentElement===this&¤t.localName===itemTag?current:null}connectedCallback(){super.connectedCallback(),this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["selected","disabled","inert","lazy"]})}disconnectedCallback(){super.disconnectedCallback(),this.pendingReorder=void 0,this.resetChildObserver()}adoptedCallback(){super.adoptedCallback(),this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}syncNodes(){const existingById=new Map;for(const node of this.nodeElements){if(!node.item)continue;const matches=existingById.get(node.item.id)??[];matches.push(node),existingById.set(node.item.id,matches)}let previousSibling=null;for(let index=0;index<this.data.length;index++){const item=this.data[index];let node=existingById.get(item.id)?.shift();node||(node=this.ownerDocument.createElement(tag("tree-item")),this.generatedNodes.add(node)),node.item=item,configureTreeItemOwner(node,{...treeItemOwnerContext(node),ancestry:[],depth:0,setSize:this.declaredRootCount,posInSet:index+1,selection:this.selection,ownsSelection:!0,identity:this.treeIdentityAt(String(index)),expandIcon:this.iconSource("expand-icon"),collapseIcon:this.iconSource("collapse-icon"),syncOwner:this.requestContextSync,focusOwner:this.onItemFocus});const targetPosition=previousSibling?previousSibling.nextElementSibling:this.firstElementChild;targetPosition!==node&&this.insertBefore(node,targetPosition),previousSibling=node}for(const nodes of existingById.values())for(const node of nodes)node.remove()}focusNode(node){node&&(this.activeId=node.nodeId,node.focus())}subtreeHasId(root,id){if(id==null)return!1;const stack=[...this.childrenOf(root)];for(let visited=0;stack.length>0&&visited<TREE_MAX_RENDER_NODES;visited++){const item=stack.pop();if(item.nodeId===id)return!0;stack.push(...this.childrenOf(item))}return!1}focusIsWithin(node){for(let current=deepActiveElementIn(this.ownerDocument);current;current=composedParentElement(current)){if(current===node)return!0;if(current===this)return!1}return!1}eventNode(e){const path=e.composedPath(),origin=path[0];if(origin?.nodeType===1&&origin.localName===tag("tree-item")){const treeTag=tag("tree");for(const target of path){if(target===this)return origin;if(target.localName===treeTag)return}return}const id=e.detail?.nodeId;return this.allNodeElements().find(candidate=>candidate.nodeId===id)}async getUpdateComplete(){let result=await super.getUpdateComplete();for(;this.syncRunning||this.isUpdatePending;)this.syncRunning&&await this.syncTask,result=await super.getUpdateComplete();return await cascadeUpdateComplete(this.nodeElements),result}reportRefreshSelectionChange(){const before=this.selectionBeforeRefresh;if(before===void 0||this.isUpdatePending)return;this.selectionBeforeRefresh=void 0;const selection=this.selectedItems;selection.length===before.length&&selection.every((item,index)=>item.nodeId===before[index])||this.emit("lr-selection-change",Object.freeze({selection}))}restorePendingFocus(){if(this.pendingFocusId==null)return;const id=this.pendingFocusId;this.pendingFocusId=null;const visible=this.visibleNodeElements();(visible.find(n=>n.nodeId===id)??visible.find(n=>n.nodeId===this.activeId))?.focus()}requestReorder(node,delta){const id=node.nodeId,found=this.findRenderedSiblings(node);if(!found)return;const{parent,siblings,index}=found,total=siblings.length,toIndex=index+delta;toIndex<0||toIndex>=total||(this.pendingReorder={node,parent,originalSiblings:[...siblings],targetSibling:siblings[toIndex],fromIndex:index,toIndex},this.emit("lr-reorder",{nodeId:id,parentNodeId:parent?.nodeId??null,fromIndex:index,toIndex}))}confirmPendingReorder(){const pending=this.pendingReorder;if(!pending)return;const found=this.findRenderedSiblings(pending.node);if(!found){this.pendingReorder=void 0;return}(found.siblings.length!==pending.originalSiblings.length||found.siblings.some((node,index)=>node!==pending.originalSiblings[index]))&&(this.pendingReorder=void 0,!(found.parent!==pending.parent||found.index!==pending.toIndex||found.siblings[pending.fromIndex]!==pending.targetSibling)&&this.liveRegion?.announce(this.localize("treeNodeMoved",void 0,{label:pending.node.nodeLabel,index:this.formatCount(found.index+1),total:this.formatCount(found.siblings.length)}),{force:!0}))}async expandAll(){const queue=this.nodeElements.map(node=>({node,depth:0})),seen=new Set;this.bulkExpansions+=1;try{for(let index=0;index<queue.length&&seen.size<TREE_MAX_RENDER_NODES;index++){const{node,depth}=queue[index];seen.has(node)||(seen.add(node),node.isDisabled?node.expanded=!1:node.hasChildren&&node.expand(),await node.updateComplete,depth<TREE_MAX_RENDER_DEPTH&&queue.push(...this.childrenOf(node).map(child=>({node:child,depth:depth+1}))))}}finally{this.bulkExpansions-=1}this.bulkExpansions===0&&this.syncRequested&&this.scheduleTreeSync(),await this.updateComplete}async collapseAll(){const focused=this.deepFocusedNode(),topLevel=this.nodeElements,nodes=this.allNodeElements();for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.isDisabled?node.expanded=!1:node.collapse()}(this.hasAuthoredItems?topLevel.some(node=>this.isNavigable(node)&&node.nodeId===this.activeId):this.data.some(item=>!item.disabled&&item.id===this.activeId))||(this.activeId=this.hasAuthoredItems?topLevel.find(node=>this.isNavigable(node))?.nodeId??null:this.firstEnabledId(this.data)),focused&&(this.pendingFocusId=this.activeId),await cascadeUpdateComplete(topLevel)}render(){return html`
|
|
2
2
|
<div
|
|
3
3
|
part="base tree"
|
|
4
4
|
role="tree"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{isRtl}from"../../../internal/rtl.js";import{getScratchCtx}from"../../../internal/canvas.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteNumber,finiteRange}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{devWarn}from"../../../internal/dev-mode-attribute-warning.js";import{layoutWordCloud,MAX_FONT_SIZE_PX,MAX_WORDS,MIN_SANE_FONT_SIZE}from"./word-cloud-layout.js";import{styles}from"./word-cloud.styles.js";import{LYRA_DEFAULT_items,LYRA_DEFAULT_noData,LYRA_DEFAULT_paginationSummary,LYRA_DEFAULT_wordCloud,LYRA_DEFAULT_wordCloudLegend,LYRA_DEFAULT_wordCloudWord,LYRA_DEFAULT_wordCloudWordAnnouncement,LYRA_DEFAULT_wordCloudWords}from"../../../internal/default-strings.generated.js";const DEFAULT_MIN_FONT_SIZE=12,DEFAULT_MAX_FONT_SIZE=48,PALETTE_SIZE=8,FALLBACK_PALETTE=["#0969da","#1a7f37","#9a6700","#cf222e","#8250df","#bf3989","#0a7d91","#57606a"],DEFAULT_WORD_FONT_WEIGHT="600",NAV_KEYS=new Set(["ArrowRight","ArrowDown","ArrowLeft","ArrowUp","Home","End"]),FOCUS_RING_PAD=2,MAX_INPUT_WORDS=1e4,MAX_WORD_TEXT=256,MAX_TOTAL_WORD_TEXT=16384,MAX_LEGEND_ITEMS=100,MAX_LEGEND_TEXT=256,MAX_TOTAL_LEGEND_TEXT=8192,MAX_PALETTE_ITEMS=64;function warnSkippedWords(count,warnedSkipCounts){warnedSkipCounts.has(count)||(warnedSkipCounts.add(count),devWarn(`<lr-word-cloud> could not place ${count} word(s) (blank text, over the ${MAX_WORDS}-word cap, or the layout search was exhausted) -- they were dropped, not rendered.`))}function boundedText(value,limit){return value.length<=limit?value:`${value.slice(0,Math.max(0,limit-1))}…`}function normalizeWords(value){let input;try{input=Array.isArray(value)?value:[]}catch{input=[]}let inputCount=0;try{inputCount=Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,input.length))}catch{inputCount=0}const scanCount=Math.min(inputCount,MAX_INPUT_WORDS),words=[];let dropped=Math.max(0,inputCount-scanCount),truncated=0,characters=0;for(let index=0;index<scanCount;index++)try{const candidate=input[index];if(typeof candidate!="object"||candidate===null){dropped++;continue}const rawText=candidate.text,rawWeight=candidate.weight,rawColor=candidate.color,rawGroup=candidate.group;if(typeof rawText!="string"){dropped++;continue}const remaining=MAX_TOTAL_WORD_TEXT-characters;if(remaining<=0){dropped+=scanCount-index;break}const textLimit=Math.min(MAX_WORD_TEXT,remaining),text=boundedText(rawText,textLimit);if(!text.trim()){dropped++;continue}let itemTruncated=rawText.length>textLimit;characters+=text.length;const boundedOptionalText=raw=>{if(typeof raw!="string")return;const available=MAX_TOTAL_WORD_TEXT-characters;if(available<=0){raw.length>0&&(itemTruncated=!0);return}const limit=Math.min(MAX_WORD_TEXT,available),result=boundedText(raw,limit);return raw.length>limit&&(itemTruncated=!0),characters+=result.length,result},color=boundedOptionalText(rawColor),group=boundedOptionalText(rawGroup),word={text,weight:Math.max(0,finiteNumber(typeof rawWeight=="number"?rawWeight:0,0)),...color===void 0?{}:{color},...group===void 0?{}:{group}};itemTruncated&&truncated++,words.push(Object.freeze(word))}catch{dropped++}return{items:Object.freeze(words),dropped,truncated,inputCount}}function normalizeLegend(value){let input;try{input=Array.isArray(value)?value:[]}catch{input=[]}let inputCount=0;try{inputCount=Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,input.length))}catch{inputCount=0}const length=Math.min(inputCount,MAX_LEGEND_ITEMS),legend=[];let dropped=Math.max(0,inputCount-length),truncated=0,characters=0;for(let index=0;index<length;index++)try{const item=input[index];if(typeof item!="object"||item===null){dropped++;continue}const rawLabel=item.label,rawColor=item.color;if(typeof rawLabel!="string"||typeof rawColor!="string"){dropped++;continue}const remaining=MAX_TOTAL_LEGEND_TEXT-characters;if(remaining<=0){dropped+=length-index;break}const labelLimit=Math.min(MAX_LEGEND_TEXT,remaining),label=boundedText(rawLabel,labelLimit);if(!label.trim()){dropped++;continue}let itemTruncated=rawLabel.length>labelLimit;characters+=label.length;const colorRemaining=MAX_TOTAL_LEGEND_TEXT-characters,colorLimit=Math.min(MAX_WORD_TEXT,Math.max(0,colorRemaining)),color=colorLimit>0?boundedText(rawColor,colorLimit):"";rawColor.length>colorLimit&&(itemTruncated=!0),characters+=color.length,itemTruncated&&truncated++,legend.push(Object.freeze({label,color}))}catch{dropped++}return{items:Object.freeze(legend),dropped,truncated,inputCount}}function normalizePalette(value){let input;try{input=Array.isArray(value)?value:[]}catch{return}let length=0;try{length=Math.min(input.length,MAX_PALETTE_ITEMS)}catch{return}const palette=[];for(let index=0;index<length;index++)try{const entry=input[index];typeof entry=="string"&&palette.push(boundedText(entry,MAX_WORD_TEXT))}catch{}return Object.freeze(palette)}class LyraWordCloud extends LyraElement{static{this.defaultStrings={...super.defaultStrings,items:LYRA_DEFAULT_items,noData:LYRA_DEFAULT_noData,paginationSummary:LYRA_DEFAULT_paginationSummary,wordCloud:LYRA_DEFAULT_wordCloud,wordCloudLegend:LYRA_DEFAULT_wordCloudLegend,wordCloudWord:LYRA_DEFAULT_wordCloudWord,wordCloudWordAnnouncement:LYRA_DEFAULT_wordCloudWordAnnouncement,wordCloudWords:LYRA_DEFAULT_wordCloudWords}}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get words(){return this._words}set words(value){if(value===this._words||value===this.lastWordsInput)return;this.lastWordsInput=value;const previous=this._words,normalized=normalizeWords(value);this._words=normalized.items,this.inputDroppedCount=normalized.dropped,this.inputTruncatedCount=normalized.truncated,this.inputWordCount=normalized.inputCount,this.requestUpdate("words",previous)}get scale(){return this._scale}set scale(value){const normalized=value==="sqrt"?"sqrt":"linear",previous=this._scale;if(previous===normalized){value!==normalized&&this.requestUpdate("scale",previous);return}this._scale=normalized,this.requestUpdate("scale",previous)}get wordRotation(){return this._wordRotation}set wordRotation(value){const normalized=value==="mixed"?"mixed":"none",previous=this._wordRotation;if(previous===normalized){value!==normalized&&this.requestUpdate("wordRotation",previous);return}this._wordRotation=normalized,this.requestUpdate("wordRotation",previous)}get palette(){return this._palette}set palette(value){if(value===this._palette||value===this.lastPaletteInput)return;this.lastPaletteInput=value;const previous=this._palette;this._palette=normalizePalette(value),this.paint=void 0,this.requestUpdate("palette",previous)}get legend(){return this._legend}set legend(value){if(value===this._legend||value===this.lastLegendInput)return;this.lastLegendInput=value;const previous=this._legend,normalized=normalizeLegend(value);this._legend=normalized.items,this.legendDroppedCount=normalized.dropped,this.legendTruncatedCount=normalized.truncated,this.legendInputCount=normalized.inputCount,this.paint=void 0,this.requestUpdate("legend",previous)}constructor(){super(),this._words=[],this.inputDroppedCount=0,this.inputTruncatedCount=0,this.inputWordCount=0,this.minFontSize=DEFAULT_MIN_FONT_SIZE,this.maxFontSize=DEFAULT_MAX_FONT_SIZE,this._scale="linear",this._wordRotation="none",this._legend=[],this.legendDroppedCount=0,this.legendTruncatedCount=0,this.legendInputCount=0,this.withLegend=!1,this.cachedLayout={placed:[],skipped:[],skippedCount:0,width:0,height:0},this.order=[],this.focusedIndex=null,this.liveText="",this.pressedOriginalIndex=null,this.hoveredOriginalIndex=null,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.warnedSkipCounts=new Set,this.typographyThemeSignature="",this.paletteThemeSignature="",this.hasSyncedDescribedByElements=!1,this.onThemeInvalidated=()=>{const typography=`${this.fontWeight()}\0${this.fontFamily()}`,palette=this.paletteColors().join("\0");if(!this.typographyThemeSignature||typography!==this.typographyThemeSignature){this.refreshTheme();return}palette!==this.paletteThemeSignature&&(this.paletteThemeSignature=palette,this.paint=void 0,this.requestUpdate())},this.onSvgFocus=()=>{this.focusedIndex===null&&this.cachedLayout.placed.length>0&&(this.focusedIndex=0)},this.onSvgPointerDown=event=>{const word=this.nearestWord(event);if(!word)return;const index=this.wordIndex(word);index<0||(this.focusedIndex=index,this.pressedOriginalIndex=word.originalIndex,this.svgEl?.focus())},this.onSvgPointerMove=event=>{this.hoveredOriginalIndex=this.nearestWord(event)?.originalIndex??null},this.clearPointerPress=()=>{this.pressedOriginalIndex=null},this.onSvgPointerLeave=()=>{this.pressedOriginalIndex=null,this.hoveredOriginalIndex=null},this.onSvgClick=event=>{const word=this.nearestWord(event);word&&this.onWordClick(word)},this.onWordClick=word=>{const order=this.order,idx=order.findIndex(w=>w.originalIndex===word.originalIndex);this.focusedIndex=idx===-1?null:idx,idx!==-1&&this.announce(order[idx]),this.svgEl?.focus(),this.activate(word)},this.onKeyDown=e=>{const order=this.order;if(order.length===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedIndex!==null&&this.activate(order[this.focusedIndex]);return}if(!NAV_KEYS.has(e.key))return;if(e.preventDefault(),this.focusedIndex===null){const next2=e.key==="End"?order.length-1:0;this.focusedIndex=next2,this.announce(order[next2]);return}const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=this.focusedIndex;e.key===forwardKey||e.key==="ArrowDown"?next=Math.min(order.length-1,this.focusedIndex+1):e.key===backwardKey||e.key==="ArrowUp"?next=Math.max(0,this.focusedIndex-1):e.key==="Home"?next=0:e.key==="End"&&(next=order.length-1),this.focusedIndex=next,this.announce(order[next])},new ThemeWatcher(this,this.onThemeInvalidated)}disconnectedCallback(){super.disconnectedCallback(),this.focusedIndex=null,this.liveText="",this.pressedOriginalIndex=null,this.hoveredOriginalIndex=null}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");!describedBy&&!this.hasSyncedDescribedByElements||(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.svgEl,describedBy))}fontFamily(){return this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-font").trim()||"sans-serif"}fontWeight(){return this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-font-weight-semibold").trim()||DEFAULT_WORD_FONT_WEIGHT}paletteColors(){if(this.palette?.length){const colors2=this.palette.map(sanitizeCssColor).filter(color=>color!==void 0);if(colors2.length)return colors2}const cs=this.ownerDocument.defaultView?.getComputedStyle(this),colors=[];for(let i=0;i<PALETTE_SIZE;i++)colors.push(cs?.getPropertyValue(`--lr-word-cloud-color-${i+1}`).trim()||cs?.getPropertyValue(`--_lr-word-cloud-color-${i+1}-default`).trim()||FALLBACK_PALETTE[i]);return colors}resolvePaint(){const placed=this.cachedLayout.placed,colors=this.paletteColors(),groupColor=new Map,fills=placed.map(word=>{const ownColor=sanitizeCssColor(word.color);return ownColor||(word.group?(groupColor.has(word.group)||groupColor.set(word.group,colors[groupColor.size%colors.length]),groupColor.get(word.group)):colors[word.originalIndex%colors.length])}),entries=this.legendInputCount>0?this.legend:placed.reduce((items,word,index)=>{if(!word.group&&!word.color)return items;const label=word.group||word.text,color=fills[index];return items.some(item=>item.label===label&&item.color===color)||items.push({label,color}),items},[]);return{fills,legend:entries.map(({label,color})=>({label,color:sanitizeCssColor(color)??"transparent"}))}}willUpdate(changed){super.willUpdate(changed),(changed.has("words")||changed.has("minFontSize")||changed.has("maxFontSize")||changed.has("domain")||changed.has("scale")||changed.has("wordRotation"))&&this.relayout()}relayout(preserveInteraction=!1){const focusedOriginalIndex=preserveInteraction&&this.focusedIndex!==null?this.order[this.focusedIndex]?.originalIndex:void 0,priorLiveText=this.liveText,fontWeight=this.fontWeight(),fontFamily=this.fontFamily(),measureText=(text,fontSize)=>{const ctx=getScratchCtx(this.ownerDocument);return ctx?(ctx.font=`${fontWeight} ${fontSize}px ${fontFamily}`,ctx.measureText(text).width):text.length*fontSize*.6},minFontSize=finiteRange(this.minFontSize,DEFAULT_MIN_FONT_SIZE,MIN_SANE_FONT_SIZE,MAX_FONT_SIZE_PX),maxFontSize=finiteRange(this.maxFontSize,DEFAULT_MAX_FONT_SIZE,MIN_SANE_FONT_SIZE,MAX_FONT_SIZE_PX);this.cachedLayout=layoutWordCloud(this.words,{minFontSize,maxFontSize,domain:this.domain,scale:this.scale,wordRotation:this.wordRotation,measureText}),this.order=[...this.cachedLayout.placed].sort((a,b)=>a.originalIndex-b.originalIndex),this.paint=void 0;const skippedCount=this.inputDroppedCount+this.cachedLayout.skippedCount;if(skippedCount>0&&warnSkippedWords(skippedCount,this.warnedSkipCounts),focusedOriginalIndex!==void 0){const nextIndex=this.order.findIndex(word=>word.originalIndex===focusedOriginalIndex);this.focusedIndex=nextIndex<0?null:nextIndex,this.liveText=nextIndex<0?"":priorLiveText}else this.focusedIndex=null,this.liveText="";this.hoveredOriginalIndex=null}refreshTheme(){this.relayout(!0),this.captureThemeSignatures(),this.requestUpdate()}captureThemeSignatures(){this.typographyThemeSignature=`${this.fontWeight()}\0${this.fontFamily()}`,this.paletteThemeSignature=this.paletteColors().join("\0")}firstUpdated(changed){super.firstUpdated(changed),this.captureThemeSignatures()}activate(word){this.emit("lr-word-activate",Object.freeze({text:word.text,weight:word.weight,group:word.group}))}announce(word){const text=this.localize("wordCloudWordAnnouncement",void 0,{text:word.text,weight:getNumberFormat(this.effectiveLocale).format(word.weight)});this.liveText=text,this.announcements.announcePolite(text)}wordIndex(word){return this.order.findIndex(candidate=>candidate.originalIndex===word.originalIndex)}nearestWord(event){const svgElement=this.svgEl;if(!svgElement||this.cachedLayout.placed.length===0)return;let x,y;try{const matrix=svgElement.getScreenCTM(),DOMPointCtor=this.ownerDocument.defaultView?.DOMPoint;if(!matrix||!DOMPointCtor)throw new Error("No SVG transform");const point=new DOMPointCtor(event.clientX,event.clientY).matrixTransform(matrix.inverse());x=point.x,y=point.y}catch{const rect=svgElement.getBoundingClientRect();if(rect.width<=0||rect.height<=0)return;x=(event.clientX-rect.left)/rect.width*this.cachedLayout.width,y=(event.clientY-rect.top)/rect.height*this.cachedLayout.height}let nearest,distance=Number.POSITIVE_INFINITY;for(const word of this.cachedLayout.placed){const box=this.focusRingRect(word),dx=Math.max(box.x-x,0,x-box.x-box.width),dy=Math.max(box.y-y,0,y-box.y-box.height),candidateDistance=dx*dx+dy*dy;candidateDistance<distance&&(distance=candidateDistance,nearest=word)}return nearest}collectionSummary(shown,total,itemLabel){return this.localize("paginationSummary",void 0,{start:this.formatCount(shown===0?0:1),end:this.formatCount(shown),total:this.formatCount(total),itemLabel})}renderLegend(entries,explicitInput){if(!this.withLegend)return nothing;const hasLimit=explicitInput&&(this.legendDroppedCount>0||this.legendTruncatedCount>0);if(entries.length===0&&!hasLimit)return nothing;const limitText=hasLimit?this.collectionSummary(entries.length,this.legendInputCount,this.localize("items")):"";return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{isRtl}from"../../../internal/rtl.js";import{getScratchCtx}from"../../../internal/canvas.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteNumber,finiteRange}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{devWarn}from"../../../internal/dev-mode-attribute-warning.js";import{layoutWordCloud,MAX_FONT_SIZE_PX,MAX_WORDS,MIN_SANE_FONT_SIZE}from"./word-cloud-layout.js";import{styles}from"./word-cloud.styles.js";import{LYRA_DEFAULT_wordCloud,LYRA_DEFAULT_wordCloudLegend,LYRA_DEFAULT_wordCloudWord,LYRA_DEFAULT_wordCloudWordAnnouncement,LYRA_DEFAULT_wordCloudWords}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_items,LYRA_DEFAULT_noData,LYRA_DEFAULT_paginationSummary}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_MIN_FONT_SIZE=12,DEFAULT_MAX_FONT_SIZE=48,PALETTE_SIZE=8,FALLBACK_PALETTE=["#0969da","#1a7f37","#9a6700","#cf222e","#8250df","#bf3989","#0a7d91","#57606a"],DEFAULT_WORD_FONT_WEIGHT="600",NAV_KEYS=new Set(["ArrowRight","ArrowDown","ArrowLeft","ArrowUp","Home","End"]),FOCUS_RING_PAD=2,MAX_INPUT_WORDS=1e4,MAX_WORD_TEXT=256,MAX_TOTAL_WORD_TEXT=16384,MAX_LEGEND_ITEMS=100,MAX_LEGEND_TEXT=256,MAX_TOTAL_LEGEND_TEXT=8192,MAX_PALETTE_ITEMS=64;function warnSkippedWords(count,warnedSkipCounts){warnedSkipCounts.has(count)||(warnedSkipCounts.add(count),devWarn(`<lr-word-cloud> could not place ${count} word(s) (blank text, over the ${MAX_WORDS}-word cap, or the layout search was exhausted) -- they were dropped, not rendered.`))}function boundedText(value,limit){return value.length<=limit?value:`${value.slice(0,Math.max(0,limit-1))}…`}function normalizeWords(value){let input;try{input=Array.isArray(value)?value:[]}catch{input=[]}let inputCount=0;try{inputCount=Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,input.length))}catch{inputCount=0}const scanCount=Math.min(inputCount,MAX_INPUT_WORDS),words=[];let dropped=Math.max(0,inputCount-scanCount),truncated=0,characters=0;for(let index=0;index<scanCount;index++)try{const candidate=input[index];if(typeof candidate!="object"||candidate===null){dropped++;continue}const rawText=candidate.text,rawWeight=candidate.weight,rawColor=candidate.color,rawGroup=candidate.group;if(typeof rawText!="string"){dropped++;continue}const remaining=MAX_TOTAL_WORD_TEXT-characters;if(remaining<=0){dropped+=scanCount-index;break}const textLimit=Math.min(MAX_WORD_TEXT,remaining),text=boundedText(rawText,textLimit);if(!text.trim()){dropped++;continue}let itemTruncated=rawText.length>textLimit;characters+=text.length;const boundedOptionalText=raw=>{if(typeof raw!="string")return;const available=MAX_TOTAL_WORD_TEXT-characters;if(available<=0){raw.length>0&&(itemTruncated=!0);return}const limit=Math.min(MAX_WORD_TEXT,available),result=boundedText(raw,limit);return raw.length>limit&&(itemTruncated=!0),characters+=result.length,result},color=boundedOptionalText(rawColor),group=boundedOptionalText(rawGroup),word={text,weight:Math.max(0,finiteNumber(typeof rawWeight=="number"?rawWeight:0,0)),...color===void 0?{}:{color},...group===void 0?{}:{group}};itemTruncated&&truncated++,words.push(Object.freeze(word))}catch{dropped++}return{items:Object.freeze(words),dropped,truncated,inputCount}}function normalizeLegend(value){let input;try{input=Array.isArray(value)?value:[]}catch{input=[]}let inputCount=0;try{inputCount=Math.max(0,Math.min(Number.MAX_SAFE_INTEGER,input.length))}catch{inputCount=0}const length=Math.min(inputCount,MAX_LEGEND_ITEMS),legend=[];let dropped=Math.max(0,inputCount-length),truncated=0,characters=0;for(let index=0;index<length;index++)try{const item=input[index];if(typeof item!="object"||item===null){dropped++;continue}const rawLabel=item.label,rawColor=item.color;if(typeof rawLabel!="string"||typeof rawColor!="string"){dropped++;continue}const remaining=MAX_TOTAL_LEGEND_TEXT-characters;if(remaining<=0){dropped+=length-index;break}const labelLimit=Math.min(MAX_LEGEND_TEXT,remaining),label=boundedText(rawLabel,labelLimit);if(!label.trim()){dropped++;continue}let itemTruncated=rawLabel.length>labelLimit;characters+=label.length;const colorRemaining=MAX_TOTAL_LEGEND_TEXT-characters,colorLimit=Math.min(MAX_WORD_TEXT,Math.max(0,colorRemaining)),color=colorLimit>0?boundedText(rawColor,colorLimit):"";rawColor.length>colorLimit&&(itemTruncated=!0),characters+=color.length,itemTruncated&&truncated++,legend.push(Object.freeze({label,color}))}catch{dropped++}return{items:Object.freeze(legend),dropped,truncated,inputCount}}function normalizePalette(value){let input;try{input=Array.isArray(value)?value:[]}catch{return}let length=0;try{length=Math.min(input.length,MAX_PALETTE_ITEMS)}catch{return}const palette=[];for(let index=0;index<length;index++)try{const entry=input[index];typeof entry=="string"&&palette.push(boundedText(entry,MAX_WORD_TEXT))}catch{}return Object.freeze(palette)}class LyraWordCloud extends LyraElement{static{this.defaultStrings={...super.defaultStrings,items:LYRA_DEFAULT_items,noData:LYRA_DEFAULT_noData,paginationSummary:LYRA_DEFAULT_paginationSummary,wordCloud:LYRA_DEFAULT_wordCloud,wordCloudLegend:LYRA_DEFAULT_wordCloudLegend,wordCloudWord:LYRA_DEFAULT_wordCloudWord,wordCloudWordAnnouncement:LYRA_DEFAULT_wordCloudWordAnnouncement,wordCloudWords:LYRA_DEFAULT_wordCloudWords}}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get words(){return this._words}set words(value){if(value===this._words||value===this.lastWordsInput)return;this.lastWordsInput=value;const previous=this._words,normalized=normalizeWords(value);this._words=normalized.items,this.inputDroppedCount=normalized.dropped,this.inputTruncatedCount=normalized.truncated,this.inputWordCount=normalized.inputCount,this.requestUpdate("words",previous)}get scale(){return this._scale}set scale(value){const normalized=value==="sqrt"?"sqrt":"linear",previous=this._scale;if(previous===normalized){value!==normalized&&this.requestUpdate("scale",previous);return}this._scale=normalized,this.requestUpdate("scale",previous)}get wordRotation(){return this._wordRotation}set wordRotation(value){const normalized=value==="mixed"?"mixed":"none",previous=this._wordRotation;if(previous===normalized){value!==normalized&&this.requestUpdate("wordRotation",previous);return}this._wordRotation=normalized,this.requestUpdate("wordRotation",previous)}get palette(){return this._palette}set palette(value){if(value===this._palette||value===this.lastPaletteInput)return;this.lastPaletteInput=value;const previous=this._palette;this._palette=normalizePalette(value),this.paint=void 0,this.requestUpdate("palette",previous)}get legend(){return this._legend}set legend(value){if(value===this._legend||value===this.lastLegendInput)return;this.lastLegendInput=value;const previous=this._legend,normalized=normalizeLegend(value);this._legend=normalized.items,this.legendDroppedCount=normalized.dropped,this.legendTruncatedCount=normalized.truncated,this.legendInputCount=normalized.inputCount,this.paint=void 0,this.requestUpdate("legend",previous)}constructor(){super(),this._words=[],this.inputDroppedCount=0,this.inputTruncatedCount=0,this.inputWordCount=0,this.minFontSize=DEFAULT_MIN_FONT_SIZE,this.maxFontSize=DEFAULT_MAX_FONT_SIZE,this._scale="linear",this._wordRotation="none",this._legend=[],this.legendDroppedCount=0,this.legendTruncatedCount=0,this.legendInputCount=0,this.withLegend=!1,this.cachedLayout={placed:[],skipped:[],skippedCount:0,width:0,height:0},this.order=[],this.focusedIndex=null,this.liveText="",this.pressedOriginalIndex=null,this.hoveredOriginalIndex=null,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.warnedSkipCounts=new Set,this.typographyThemeSignature="",this.paletteThemeSignature="",this.hasSyncedDescribedByElements=!1,this.onThemeInvalidated=()=>{const typography=`${this.fontWeight()}\0${this.fontFamily()}`,palette=this.paletteColors().join("\0");if(!this.typographyThemeSignature||typography!==this.typographyThemeSignature){this.refreshTheme();return}palette!==this.paletteThemeSignature&&(this.paletteThemeSignature=palette,this.paint=void 0,this.requestUpdate())},this.onSvgFocus=()=>{this.focusedIndex===null&&this.cachedLayout.placed.length>0&&(this.focusedIndex=0)},this.onSvgPointerDown=event=>{const word=this.nearestWord(event);if(!word)return;const index=this.wordIndex(word);index<0||(this.focusedIndex=index,this.pressedOriginalIndex=word.originalIndex,this.svgEl?.focus())},this.onSvgPointerMove=event=>{this.hoveredOriginalIndex=this.nearestWord(event)?.originalIndex??null},this.clearPointerPress=()=>{this.pressedOriginalIndex=null},this.onSvgPointerLeave=()=>{this.pressedOriginalIndex=null,this.hoveredOriginalIndex=null},this.onSvgClick=event=>{const word=this.nearestWord(event);word&&this.onWordClick(word)},this.onWordClick=word=>{const order=this.order,idx=order.findIndex(w=>w.originalIndex===word.originalIndex);this.focusedIndex=idx===-1?null:idx,idx!==-1&&this.announce(order[idx]),this.svgEl?.focus(),this.activate(word)},this.onKeyDown=e=>{const order=this.order;if(order.length===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedIndex!==null&&this.activate(order[this.focusedIndex]);return}if(!NAV_KEYS.has(e.key))return;if(e.preventDefault(),this.focusedIndex===null){const next2=e.key==="End"?order.length-1:0;this.focusedIndex=next2,this.announce(order[next2]);return}const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=this.focusedIndex;e.key===forwardKey||e.key==="ArrowDown"?next=Math.min(order.length-1,this.focusedIndex+1):e.key===backwardKey||e.key==="ArrowUp"?next=Math.max(0,this.focusedIndex-1):e.key==="Home"?next=0:e.key==="End"&&(next=order.length-1),this.focusedIndex=next,this.announce(order[next])},new ThemeWatcher(this,this.onThemeInvalidated)}disconnectedCallback(){super.disconnectedCallback(),this.focusedIndex=null,this.liveText="",this.pressedOriginalIndex=null,this.hoveredOriginalIndex=null}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");!describedBy&&!this.hasSyncedDescribedByElements||(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.svgEl,describedBy))}fontFamily(){return this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-font").trim()||"sans-serif"}fontWeight(){return this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-font-weight-semibold").trim()||DEFAULT_WORD_FONT_WEIGHT}paletteColors(){if(this.palette?.length){const colors2=this.palette.map(sanitizeCssColor).filter(color=>color!==void 0);if(colors2.length)return colors2}const cs=this.ownerDocument.defaultView?.getComputedStyle(this),colors=[];for(let i=0;i<PALETTE_SIZE;i++)colors.push(cs?.getPropertyValue(`--lr-word-cloud-color-${i+1}`).trim()||cs?.getPropertyValue(`--_lr-word-cloud-color-${i+1}-default`).trim()||FALLBACK_PALETTE[i]);return colors}resolvePaint(){const placed=this.cachedLayout.placed,colors=this.paletteColors(),groupColor=new Map,fills=placed.map(word=>{const ownColor=sanitizeCssColor(word.color);return ownColor||(word.group?(groupColor.has(word.group)||groupColor.set(word.group,colors[groupColor.size%colors.length]),groupColor.get(word.group)):colors[word.originalIndex%colors.length])}),entries=this.legendInputCount>0?this.legend:placed.reduce((items,word,index)=>{if(!word.group&&!word.color)return items;const label=word.group||word.text,color=fills[index];return items.some(item=>item.label===label&&item.color===color)||items.push({label,color}),items},[]);return{fills,legend:entries.map(({label,color})=>({label,color:sanitizeCssColor(color)??"transparent"}))}}willUpdate(changed){super.willUpdate(changed),(changed.has("words")||changed.has("minFontSize")||changed.has("maxFontSize")||changed.has("domain")||changed.has("scale")||changed.has("wordRotation"))&&this.relayout()}relayout(preserveInteraction=!1){const focusedOriginalIndex=preserveInteraction&&this.focusedIndex!==null?this.order[this.focusedIndex]?.originalIndex:void 0,priorLiveText=this.liveText,fontWeight=this.fontWeight(),fontFamily=this.fontFamily(),measureText=(text,fontSize)=>{const ctx=getScratchCtx(this.ownerDocument);return ctx?(ctx.font=`${fontWeight} ${fontSize}px ${fontFamily}`,ctx.measureText(text).width):text.length*fontSize*.6},minFontSize=finiteRange(this.minFontSize,DEFAULT_MIN_FONT_SIZE,MIN_SANE_FONT_SIZE,MAX_FONT_SIZE_PX),maxFontSize=finiteRange(this.maxFontSize,DEFAULT_MAX_FONT_SIZE,MIN_SANE_FONT_SIZE,MAX_FONT_SIZE_PX);this.cachedLayout=layoutWordCloud(this.words,{minFontSize,maxFontSize,domain:this.domain,scale:this.scale,wordRotation:this.wordRotation,measureText}),this.order=[...this.cachedLayout.placed].sort((a,b)=>a.originalIndex-b.originalIndex),this.paint=void 0;const skippedCount=this.inputDroppedCount+this.cachedLayout.skippedCount;if(skippedCount>0&&warnSkippedWords(skippedCount,this.warnedSkipCounts),focusedOriginalIndex!==void 0){const nextIndex=this.order.findIndex(word=>word.originalIndex===focusedOriginalIndex);this.focusedIndex=nextIndex<0?null:nextIndex,this.liveText=nextIndex<0?"":priorLiveText}else this.focusedIndex=null,this.liveText="";this.hoveredOriginalIndex=null}refreshTheme(){this.relayout(!0),this.captureThemeSignatures(),this.requestUpdate()}captureThemeSignatures(){this.typographyThemeSignature=`${this.fontWeight()}\0${this.fontFamily()}`,this.paletteThemeSignature=this.paletteColors().join("\0")}firstUpdated(changed){super.firstUpdated(changed),this.captureThemeSignatures()}activate(word){this.emit("lr-word-activate",Object.freeze({text:word.text,weight:word.weight,group:word.group}))}announce(word){const text=this.localize("wordCloudWordAnnouncement",void 0,{text:word.text,weight:getNumberFormat(this.effectiveLocale).format(word.weight)});this.liveText=text,this.announcements.announcePolite(text)}wordIndex(word){return this.order.findIndex(candidate=>candidate.originalIndex===word.originalIndex)}nearestWord(event){const svgElement=this.svgEl;if(!svgElement||this.cachedLayout.placed.length===0)return;let x,y;try{const matrix=svgElement.getScreenCTM(),DOMPointCtor=this.ownerDocument.defaultView?.DOMPoint;if(!matrix||!DOMPointCtor)throw new Error("No SVG transform");const point=new DOMPointCtor(event.clientX,event.clientY).matrixTransform(matrix.inverse());x=point.x,y=point.y}catch{const rect=svgElement.getBoundingClientRect();if(rect.width<=0||rect.height<=0)return;x=(event.clientX-rect.left)/rect.width*this.cachedLayout.width,y=(event.clientY-rect.top)/rect.height*this.cachedLayout.height}let nearest,distance=Number.POSITIVE_INFINITY;for(const word of this.cachedLayout.placed){const box=this.focusRingRect(word),dx=Math.max(box.x-x,0,x-box.x-box.width),dy=Math.max(box.y-y,0,y-box.y-box.height),candidateDistance=dx*dx+dy*dy;candidateDistance<distance&&(distance=candidateDistance,nearest=word)}return nearest}collectionSummary(shown,total,itemLabel){return this.localize("paginationSummary",void 0,{start:this.formatCount(shown===0?0:1),end:this.formatCount(shown),total:this.formatCount(total),itemLabel})}renderLegend(entries,explicitInput){if(!this.withLegend)return nothing;const hasLimit=explicitInput&&(this.legendDroppedCount>0||this.legendTruncatedCount>0);if(entries.length===0&&!hasLimit)return nothing;const limitText=hasLimit?this.collectionSummary(entries.length,this.legendInputCount,this.localize("items")):"";return html`
|
|
2
2
|
${entries.length?html`<div
|
|
3
3
|
part="legend"
|
|
4
4
|
role="list"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var _a;import{__decorate}from"tslib";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{FORM_CONTROL_LABEL_FACTORY,LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{installFormControlInternalsCapture}from"../../../internal/form-control-labels.js";import{chevronIcon,spinnerIcon}from"../../../internal/icons.js";import{hasIconOnlyDefaultContent,IconOnlyLabelObserver}from"../../../internal/icon-only-content.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{syncAriaControlsElements}from"../../../internal/aria-reflection.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{sizes}from"../../../internal/sizes.styles.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{getFormOwner,setFormOwner}from"../../../internal/direct-form-associated.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{currentValidityValidator}from"../form-validator.js";import{findDefaultButton,isImplicitSubmission,submitFormImplicitly}from"../../../internal/submit-on-enter.js";import{createButtonExternalLabelController}from"./button-external-label.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";installFormControlInternalsCapture();const BUTTON_TYPE=literalSetConverter(["button","submit","reset"],"button"),IMPLICIT_SUBMIT_INPUT=/^(text|search|url|tel|email|password|date|month|week|time|datetime-local|number)$/;class LyraButton extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","loading","href","value")]}static{this.styles=[LyraElement.styles,sizes,variants,styles]}static{this.formAssociated=!0}static{this[_a]=createButtonExternalLabelController}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.requestUpdate("disabled",old),this.updateValidity(),this.syncButtonStates()}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}constructor(){super(),this._fieldsetDisabled=!1,this._disabled=!1,this._name="",this._value="",this._required=!1,this._variant="neutral",this._type="button",this.injectedHostTabIndex=!1,this.implicitForm=null,this.localDescriptionIds="",this.customValidityMessage="",this.reflectingCustomError=!1,this.accessibleLabel=null,this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerPressed=null,this.pressed=null,this.triggerCurrent=null,this.triggerControls=null,this.triggerDescribedBy=null,this.appearance="accent",this.size="m",this.pill=!1,this.circle=!1,this.outline=!1,this.withCaret=!1,this.withStart=!1,this.withEnd=!1,this.wrap=!1,this.formNoValidate=!1,this.loading=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.isIconButton=!1,this.iconOnlyObserver=new IconOnlyLabelObserver(this,()=>this.labelEl,()=>this.isIconButton,next=>{this.isIconButton=next,this.syncButtonStates()}),this.onFormKeyDown=event=>{const field=event.target,form=this.implicitForm;!form||!isImplicitSubmission(event)||!(field instanceof HTMLInputElement)||!IMPLICIT_SUBMIT_INPUT.test(field.type)||field.form!==form||this.baseEl?.localName==="a"||findDefaultButton(form)!==this||(event.preventDefault(),submitFormImplicitly(form))},this.onClick=event=>{if(this.type!=="submit"&&this.type!=="reset")return;const ownerWindow=this.ownerDocument.defaultView;let settled=!1;const finish=()=>{settled||(settled=!0,ownerWindow?.removeEventListener("click",finishAtWindow),!(event.defaultPrevented||this.effectiveDisabled||this.loading)&&this.runClickDefaultAction())},finishAtWindow=candidate=>{candidate===event&&finish()};ownerWindow?.addEventListener("click",finishAtWindow),queueMicrotask(finish)},this.onFocusChange=event=>{relayNativeEvent(this,event)},this.onAdornmentSlotChange=()=>{this.syncAdornmentSlots()},this.onDefaultSlotChange=()=>{this.isIconButton=hasIconOnlyDefaultContent(this),this.syncButtonStates()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),customError:()=>this.customValidityMessage}),this.internals=this.validityController.formInternals,this.updateValidity(),this.syncButtonStates()}get variant(){return this._variant}set variant(next){next==="primary"?this._variant="brand":next==="default"||next==="text"?this._variant="neutral":this._variant=next,next==="text"&&(this.appearance="plain")}get caret(){return this.withCaret}set caret(next){this.withCaret=!!next}get type(){return this._type}set type(next){const old=this._type;this._type=BUTTON_TYPE.normalize(typeof next=="string"?next.toLowerCase():next),this.requestUpdate("type",old)}get value(){return this._value}set value(next){this._value=next??"",this.updateValidity()}get required(){return this._required}set required(next){this._required=!!next,this.updateValidity()}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}click(){this.effectiveDisabled||this.loading||this.baseEl?.click()}focus(options){!this.effectiveDisabled&&!this.loading&&this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[(_a=FORM_CONTROL_LABEL_FACTORY,VALIDITY_ANCHOR)](){return this.baseEl??null}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.internals.reportValidity()}setCustomValidity(message){const old=this.customValidityMessage||null,next=message??"";if(this.customValidityMessage=next,this.validityController.setCustomValidity(this.isValidationBarred?"":next),!this.reflectingCustomError){this.reflectingCustomError=!0;try{next?this.setAttribute("custom-error",next):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}}this.requestUpdate("customError",old)}resetValidity(){this.customValidityMessage="",this.validityController.setCustomValidity(""),this.updateValidity()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?state2:""}syncImplicitSubmission(form=this.getForm()){const next=this.type==="submit"&&this.isConnected?form:null;next!==this.implicitForm&&(this.implicitForm?.removeEventListener("keydown",this.onFormKeyDown),this.implicitForm=next,next?.addEventListener("keydown",this.onFormKeyDown))}formAssociatedCallback(form){this.syncImplicitSubmission(form)}runClickDefaultAction(){if(this.type==="submit"){const form=this.getForm();if(!form)return;this.hasSubmitterOverrides?this.submitAsNamedSubmitter(form):form.requestSubmit()}else this.type==="reset"&&this.getForm()?.reset()}get hasSubmitterOverrides(){return!!(this.name||this.value||this.formNoValidate)||this.formAction!==void 0||this.formEnctype!==void 0||this.formMethod!==void 0||this.formTarget!==void 0}submitAsNamedSubmitter(form){const submitter=this.ownerDocument.createElement("button");submitter.type="submit",submitter.hidden=!0,submitter.tabIndex=-1,this.name&&(submitter.name=this.name,submitter.value=this.value),this.formAction!==void 0&&submitter.setAttribute("formaction",this.formAction),this.formEnctype!==void 0&&submitter.setAttribute("formenctype",this.formEnctype),this.formMethod!==void 0&&submitter.setAttribute("formmethod",this.formMethod),this.formNoValidate&&(submitter.formNoValidate=!0),this.formTarget!==void 0&&submitter.setAttribute("formtarget",this.formTarget),this.parentElement&&this.closest("form")===form?this.insertAdjacentElement("afterend",submitter):form.append(submitter);try{form.requestSubmit(submitter)}finally{submitter.remove()}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.updateValidity(),this.syncButtonStates(),this.requestUpdate())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements(),this.syncImplicitSubmission(),this.updateValidity(),this.syncButtonStates(),this.hasUpdated&&this.iconOnlyObserver.arm()}disconnectedCallback(){this.releaseExternalDescription(),this.syncImplicitSubmission(null),this.iconOnlyObserver.disarm(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed);const focusedControl=shadowFocusTarget(this);changed.has("loading")&&this.loading&&focusedControl!==null&&focusedControl===this.baseEl&&(this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0),HTMLElement.prototype.focus.call(this,{preventScroll:!0})),this.hasUpdated||this.seedFirstRenderState(()=>{this.syncAdornmentSlots(),this.isIconButton=hasIconOnlyDefaultContent(this)})}syncAdornmentSlots(){const collection=this.children,children=collection?Array.from(collection):[];this.hasStartSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="start"||slot==="prefix"}),this.hasEndSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="end"||slot==="suffix"})}get labelGrows(){return this.withCaret||this.hasEndSlot||this.withEnd}updated(changed){if(super.updated(changed),changed.has("type")&&this.syncImplicitSubmission(),changed.has("loading")&&!this.loading&&this.injectedHostTabIndex){const parked=this.ownerDocument.activeElement===this&&!shadowFocusTarget(this);this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1,parked&&this.baseEl?.focus({preventScroll:!0})}syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements(),this.iconOnlyObserver.arm(),this.updateValidity(),this.syncButtonStates()}updateValidity(){if(this.validityController){if(this.isValidationBarred){this.validityController.setCustomValidity(""),this.validityController.setValidity({});return}this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.validityController.setCustomValidity(this.customValidityMessage)}}get isValidationBarred(){return this.effectiveDisabled||this.loading||this.baseEl?.localName==="a"}syncButtonStates(){this.internals&&(setCustomState(this.internals,"disabled",this.effectiveDisabled||this.loading),setCustomState(this.internals,"icon-button",this.isIconButton),setCustomState(this.internals,"link",this.baseEl?.localName==="a"),setCustomState(this.internals,"loading",this.loading))}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}render(){const pressed=this.pressed==="mixed"?"mixed":typeof this.pressed=="boolean"?String(this.pressed):["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,content=html`
|
|
1
|
+
var _a;import{__decorate}from"tslib";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{FORM_CONTROL_LABEL_FACTORY,LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{installFormControlInternalsCapture}from"../../../internal/form-control-labels.js";import{chevronIcon,spinnerIcon}from"../../../internal/icons.js";import{hasIconOnlyDefaultContent,IconOnlyLabelObserver}from"../../../internal/icon-only-content.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{syncAriaControlsElements}from"../../../internal/aria-reflection.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{sizes}from"../../../internal/sizes.styles.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{getFormOwner,setFormOwner}from"../../../internal/direct-form-associated.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{currentValidityValidator}from"../form-validator.js";import{findDefaultButton,isImplicitSubmission,submitFormImplicitly}from"../../../internal/submit-on-enter.js";import{createButtonExternalLabelController}from"./button-external-label.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlInternalsCapture();const BUTTON_TYPE=literalSetConverter(["button","submit","reset"],"button"),IMPLICIT_SUBMIT_INPUT=/^(text|search|url|tel|email|password|date|month|week|time|datetime-local|number)$/;class LyraButton extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","loading","href","value")]}static{this.styles=[LyraElement.styles,sizes,variants,styles]}static{this.formAssociated=!0}static{this[_a]=createButtonExternalLabelController}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.requestUpdate("disabled",old),this.updateValidity(),this.syncButtonStates()}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}constructor(){super(),this._fieldsetDisabled=!1,this._disabled=!1,this._name="",this._value="",this._required=!1,this._variant="neutral",this._type="button",this.injectedHostTabIndex=!1,this.implicitForm=null,this.localDescriptionIds="",this.customValidityMessage="",this.reflectingCustomError=!1,this.accessibleLabel=null,this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerPressed=null,this.pressed=null,this.triggerCurrent=null,this.triggerControls=null,this.triggerDescribedBy=null,this.appearance="accent",this.size="m",this.pill=!1,this.circle=!1,this.outline=!1,this.withCaret=!1,this.withStart=!1,this.withEnd=!1,this.wrap=!1,this.formNoValidate=!1,this.loading=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.isIconButton=!1,this.iconOnlyObserver=new IconOnlyLabelObserver(this,()=>this.labelEl,()=>this.isIconButton,next=>{this.isIconButton=next,this.syncButtonStates()}),this.onFormKeyDown=event=>{const field=event.target,form=this.implicitForm;!form||!isImplicitSubmission(event)||!(field instanceof HTMLInputElement)||!IMPLICIT_SUBMIT_INPUT.test(field.type)||field.form!==form||this.baseEl?.localName==="a"||findDefaultButton(form)!==this||(event.preventDefault(),submitFormImplicitly(form))},this.onClick=event=>{if(this.type!=="submit"&&this.type!=="reset")return;const ownerWindow=this.ownerDocument.defaultView;let settled=!1;const finish=()=>{settled||(settled=!0,ownerWindow?.removeEventListener("click",finishAtWindow),!(event.defaultPrevented||this.effectiveDisabled||this.loading)&&this.runClickDefaultAction())},finishAtWindow=candidate=>{candidate===event&&finish()};ownerWindow?.addEventListener("click",finishAtWindow),queueMicrotask(finish)},this.onFocusChange=event=>{relayNativeEvent(this,event)},this.onAdornmentSlotChange=()=>{this.syncAdornmentSlots()},this.onDefaultSlotChange=()=>{this.isIconButton=hasIconOnlyDefaultContent(this),this.syncButtonStates()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),customError:()=>this.customValidityMessage}),this.internals=this.validityController.formInternals,this.updateValidity(),this.syncButtonStates()}get variant(){return this._variant}set variant(next){next==="primary"?this._variant="brand":next==="default"||next==="text"?this._variant="neutral":this._variant=next,next==="text"&&(this.appearance="plain")}get caret(){return this.withCaret}set caret(next){this.withCaret=!!next}get type(){return this._type}set type(next){const old=this._type;this._type=BUTTON_TYPE.normalize(typeof next=="string"?next.toLowerCase():next),this.requestUpdate("type",old)}get value(){return this._value}set value(next){this._value=next??"",this.updateValidity()}get required(){return this._required}set required(next){this._required=!!next,this.updateValidity()}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}click(){this.effectiveDisabled||this.loading||this.baseEl?.click()}focus(options){!this.effectiveDisabled&&!this.loading&&this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[(_a=FORM_CONTROL_LABEL_FACTORY,VALIDITY_ANCHOR)](){return this.baseEl??null}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.internals.reportValidity()}setCustomValidity(message){const old=this.customValidityMessage||null,next=message??"";if(this.customValidityMessage=next,this.validityController.setCustomValidity(this.isValidationBarred?"":next),!this.reflectingCustomError){this.reflectingCustomError=!0;try{next?this.setAttribute("custom-error",next):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}}this.requestUpdate("customError",old)}resetValidity(){this.customValidityMessage="",this.validityController.setCustomValidity(""),this.updateValidity()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?state2:""}syncImplicitSubmission(form=this.getForm()){const next=this.type==="submit"&&this.isConnected?form:null;next!==this.implicitForm&&(this.implicitForm?.removeEventListener("keydown",this.onFormKeyDown),this.implicitForm=next,next?.addEventListener("keydown",this.onFormKeyDown))}formAssociatedCallback(form){this.syncImplicitSubmission(form)}runClickDefaultAction(){if(this.type==="submit"){const form=this.getForm();if(!form)return;this.hasSubmitterOverrides?this.submitAsNamedSubmitter(form):form.requestSubmit()}else this.type==="reset"&&this.getForm()?.reset()}get hasSubmitterOverrides(){return!!(this.name||this.value||this.formNoValidate)||this.formAction!==void 0||this.formEnctype!==void 0||this.formMethod!==void 0||this.formTarget!==void 0}submitAsNamedSubmitter(form){const submitter=this.ownerDocument.createElement("button");submitter.type="submit",submitter.hidden=!0,submitter.tabIndex=-1,this.name&&(submitter.name=this.name,submitter.value=this.value),this.formAction!==void 0&&submitter.setAttribute("formaction",this.formAction),this.formEnctype!==void 0&&submitter.setAttribute("formenctype",this.formEnctype),this.formMethod!==void 0&&submitter.setAttribute("formmethod",this.formMethod),this.formNoValidate&&(submitter.formNoValidate=!0),this.formTarget!==void 0&&submitter.setAttribute("formtarget",this.formTarget),this.parentElement&&this.closest("form")===form?this.insertAdjacentElement("afterend",submitter):form.append(submitter);try{form.requestSubmit(submitter)}finally{submitter.remove()}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.updateValidity(),this.syncButtonStates(),this.requestUpdate())}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements(),this.syncImplicitSubmission(),this.updateValidity(),this.syncButtonStates(),this.hasUpdated&&this.iconOnlyObserver.arm()}disconnectedCallback(){this.releaseExternalDescription(),this.syncImplicitSubmission(null),this.iconOnlyObserver.disarm(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed);const focusedControl=shadowFocusTarget(this);changed.has("loading")&&this.loading&&focusedControl!==null&&focusedControl===this.baseEl&&(this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0),HTMLElement.prototype.focus.call(this,{preventScroll:!0})),this.hasUpdated||this.seedFirstRenderState(()=>{this.syncAdornmentSlots(),this.isIconButton=hasIconOnlyDefaultContent(this)})}syncAdornmentSlots(){const collection=this.children,children=collection?Array.from(collection):[];this.hasStartSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="start"||slot==="prefix"}),this.hasEndSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="end"||slot==="suffix"})}get labelGrows(){return this.withCaret||this.hasEndSlot||this.withEnd}updated(changed){if(super.updated(changed),changed.has("type")&&this.syncImplicitSubmission(),changed.has("loading")&&!this.loading&&this.injectedHostTabIndex){const parked=this.ownerDocument.activeElement===this&&!shadowFocusTarget(this);this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1,parked&&this.baseEl?.focus({preventScroll:!0})}syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements(),this.iconOnlyObserver.arm(),this.updateValidity(),this.syncButtonStates()}updateValidity(){if(this.validityController){if(this.isValidationBarred){this.validityController.setCustomValidity(""),this.validityController.setValidity({});return}this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.validityController.setCustomValidity(this.customValidityMessage)}}get isValidationBarred(){return this.effectiveDisabled||this.loading||this.baseEl?.localName==="a"}syncButtonStates(){this.internals&&(setCustomState(this.internals,"disabled",this.effectiveDisabled||this.loading),setCustomState(this.internals,"icon-button",this.isIconButton),setCustomState(this.internals,"link",this.baseEl?.localName==="a"),setCustomState(this.internals,"loading",this.loading))}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}render(){const pressed=this.pressed==="mixed"?"mixed":typeof this.pressed=="boolean"?String(this.pressed):["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,content=html`
|
|
2
2
|
<span
|
|
3
3
|
part="start prefix"
|
|
4
4
|
?hidden=${!(this.hasStartSlot||this.withStart)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{tag}from"../../../internal/prefix.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_checkboxRequired
|
|
1
|
+
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{html,svg,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{tag}from"../../../internal/prefix.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_checkboxRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
part="checkmark checked-icon"
|
|
4
4
|
width="1em"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";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{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();const DUPLICATE_VALUE_WARNING_KEY="lyra-checkbox-group-duplicate-child-values",DUPLICATE_VALUE_WARNING="<lr-checkbox-group>: duplicate child values make submitted FormData ambiguous; give each child a distinct value.";class LyraCheckboxGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-checkbox-group-toggle-request"])}static{this.identityEventDetailProperties=Object.freeze({"lr-checkbox-group-toggle-request":Object.freeze(["option"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}set value(next){markVetoGuardWrite(this.toggleGuard);const requested=Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[];if(this.boxes.length===0){this.pendingValues=requested;return}this.pendingValues=void 0,this.applyValues(requested)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this.childObserverGeneration=0,this.childControllers=new Map,this.toggleGuard=new VetoWriteGuard,this.authoredChildSizes=new Map,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.syncQueued=!1,this.suppressCheckboxSync=!1,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const value=this.value,detail=()=>Object.freeze({value:Object.freeze([...value])});emitValueEvents(this,"input",detail(),detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail(),detail2=>this.emit("lr-change",detail2))},this.onChildToggleRequest=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),this.effectiveDisabled))return;const option=event.target,proposed=event.detail.checked;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-checkbox-group-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.cachedBoxes=void 0,this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals}checkboxGroupOwner(element){const group=element.closest(tag("checkbox-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName===tag("checkbox")&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}syncBoxes(){return this.cachedBoxes||(this.cachedBoxes=this.boxes,queueMicrotask(()=>{this.cachedBoxes=void 0})),this.cachedBoxes}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}sync(){const next=[],seen=new Set;for(const box of this.syncBoxes()){const value=box.value??box.getAttribute("value")??"on";seen.has(value)&&devWarnOnce(DUPLICATE_VALUE_WARNING_KEY,DUPLICATE_VALUE_WARNING),seen.add(value),box.checked&&next.push(value)}const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}scheduleSync(){this.syncQueued||(this.syncQueued=!0,queueMicrotask(()=>{this.syncQueued=!1,this.isConnected&&this.sync()}))}notifyCheckboxStateChange(checkbox){this.suppressCheckboxSync||this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}projectedValue(option,proposed){return Object.freeze(this.boxes.filter(box=>box===option?proposed:box.checked).map(box=>box.value??"on"))}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.scheduleSync()}};box.addController(controller),this.childControllers.set(box,controller)}}applyValues(values){const remaining=[...values];this.suppressCheckboxSync=!0;try{for(const box of this.boxes){const value=box.value??"on",index=remaining.indexOf(value);box.checked=index>=0,index>=0&&remaining.splice(index,1)}}finally{this.suppressCheckboxSync=!1}this.sync()}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const values=this.pendingRestoreValues;return this.pendingRestoreValues=void 0,this.hasInteracted=!1,this.applyValues(values),!0}applyPendingValues(){if(this.pendingValues===void 0||this.boxes.length===0)return!1;const values=this.pendingValues;return this.pendingValues=void 0,this.applyValues(values),!0}connectedCallback(){super.connectedCallback(),this.cachedBoxes=void 0,this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("lr-input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.hasUpdated?this.onSlotChange():(this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()),this.armChildObserver(),this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseExternalDescription(),this.releaseRequiredDescription(),this.cachedBoxes=void 0,this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.resetChildObserver(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription(),this.syncExternalDescription()}syncExternalDescription(){const target=this.renderRoot.querySelector("fieldset");if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.suppressCheckboxSync=!0;try{this.boxes.forEach(box=>box.resetFromGroup())}finally{this.suppressCheckboxSync=!1}this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.propagateDisabled(),this.sync(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`<fieldset
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";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{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{LYRA_DEFAULT_checkboxGroupRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const DUPLICATE_VALUE_WARNING_KEY="lyra-checkbox-group-duplicate-child-values",DUPLICATE_VALUE_WARNING="<lr-checkbox-group>: duplicate child values make submitted FormData ambiguous; give each child a distinct value.";class LyraCheckboxGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,fieldRequired:LYRA_DEFAULT_fieldRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-checkbox-group-toggle-request"])}static{this.identityEventDetailProperties=Object.freeze({"lr-checkbox-group-toggle-request":Object.freeze(["option"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0},orientation:{reflect:!0},value:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.sync(),this.requestUpdate("name",old)}get value(){return Object.freeze([...this._value])}set value(next){markVetoGuardWrite(this.toggleGuard);const requested=Array.isArray(next)?next.filter(entry=>typeof entry=="string"):[];if(this.boxes.length===0){this.pendingValues=requested;return}this.pendingValues=void 0,this.applyValues(requested)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.sync(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.propagateDisabled(),this.sync(),this.requestUpdate("disabled",old)}constructor(){super(),this.orientation="vertical",this.label="",this.hint="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("checkbox-group-label"),this.hintId=nextId("checkbox-group-hint"),this.errorId=nextId("checkbox-group-error"),this.requiredDescriptionId=nextId("checkbox-group-required"),this._fieldsetDisabled=!1,this._name="",this._required=!1,this._disabled=!1,this._value=[],this.childObserverGeneration=0,this.childControllers=new Map,this.toggleGuard=new VetoWriteGuard,this.authoredChildSizes=new Map,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.syncQueued=!1,this.suppressCheckboxSync=!1,this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),event.type!=="change"||this.effectiveDisabled))return;this.hasInteracted=!0,this.sync();const value=this.value,detail=()=>Object.freeze({value:Object.freeze([...value])});emitValueEvents(this,"input",detail(),detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",detail(),detail2=>this.emit("lr-change",detail2))},this.onChildToggleRequest=event=>{if(!this.isOwnedCheckbox(event.target)||(event.stopImmediatePropagation(),this.effectiveDisabled))return;const option=event.target,proposed=event.detail.checked;let allowed=!1;requestThenCommit({requestDetail:{value:this.projectedValue(option,proposed),previousValue:this.value,option},emitRequest:(detail,init)=>this.emit("lr-checkbox-group-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{allowed=!0}}),allowed||event.preventDefault()},this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}for(const record of records){if(record.attributeName!=="size"||!this.isOwnedCheckbox(record.target))continue;const box=record.target;this.size!==void 0&&box.size!==this.size&&this.authoredChildSizes.set(box,box.size)}records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))&&this.propagateSize(),records.some(record=>this.isOwnedCheckbox(record.target))&&this.sync()},this.onSlotChange=()=>{this.cachedBoxes=void 0,this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals}checkboxGroupOwner(element){const group=element.closest(tag("checkbox-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="error"?null:group}ownsCheckbox(element){return element.localName===tag("checkbox")&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}syncBoxes(){return this.cachedBoxes||(this.cachedBoxes=this.boxes,queueMicrotask(()=>{this.cachedBoxes=void 0})),this.cachedBoxes}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){for(const box of this.boxes)if(this.authoredChildSizes.has(box)||this.authoredChildSizes.set(box,box.size),this.size===void 0||this.size===null){const authored=this.authoredChildSizes.get(box);authored!==void 0&&box.size!==authored&&(box.size=authored),this.authoredChildSizes.delete(box)}else box.size!==this.size&&(box.size=this.size)}sync(){const next=[],seen=new Set;for(const box of this.syncBoxes()){const value=box.value??box.getAttribute("value")??"on";seen.has(value)&&devWarnOnce(DUPLICATE_VALUE_WARNING_KEY,DUPLICATE_VALUE_WARNING),seen.add(value),box.checked&&next.push(value)}const old=this._value;this._value=next,this.requestUpdate("value",old);const data=new FormData;this.name&&next.forEach(value=>data.append(this.name,value)),this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next)),!this.barredFromValidation&&this.required&&next.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("checkboxGroupRequired")):this.validityController.setValidity({}),this.reflectValidityStates()}scheduleSync(){this.syncQueued||(this.syncQueued=!0,queueMicrotask(()=>{this.syncQueued=!1,this.isConnected&&this.sync()}))}notifyCheckboxStateChange(checkbox){this.suppressCheckboxSync||this.isConnected&&this.ownsCheckbox(checkbox)&&this.sync()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.hasInteracted&&!this.internals.validity.valid),syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}projectedValue(option,proposed){return Object.freeze(this.boxes.filter(box=>box===option?proposed:box.checked).map(box=>box.value??"on"))}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller),this.childControllers.delete(box);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize),this.authoredChildSizes.delete(box);const nextOwner=this.checkboxGroupOwner(box);(!nextOwner||nextOwner===this)&&box.setGroupDisabled?.(!1)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!="function")continue;const controller={hostUpdated:()=>{this.isConnected&&this.ownsCheckbox(box)&&this.scheduleSync()}};box.addController(controller),this.childControllers.set(box,controller)}}applyValues(values){const remaining=[...values];this.suppressCheckboxSync=!0;try{for(const box of this.boxes){const value=box.value??"on",index=remaining.indexOf(value);box.checked=index>=0,index>=0&&remaining.splice(index,1)}}finally{this.suppressCheckboxSync=!1}this.sync()}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return!1;const values=this.pendingRestoreValues;return this.pendingRestoreValues=void 0,this.hasInteracted=!1,this.applyValues(values),!0}applyPendingValues(){if(this.pendingValues===void 0||this.boxes.length===0)return!1;const values=this.pendingValues;return this.pendingValues=void 0,this.applyValues(values),!0}connectedCallback(){super.connectedCallback(),this.cachedBoxes=void 0,this.addEventListener("input",this.onChildEvent,{capture:!0}),this.addEventListener("lr-input",this.onChildEvent,{capture:!0}),this.addEventListener("change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-change",this.onChildEvent,{capture:!0}),this.addEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.hasUpdated?this.onSlotChange():(this.reconcileChildControllers(),!this.applyPendingRestore()&&!this.applyPendingValues()&&this.sync(),this.propagateDisabled(),this.propagateSize()),this.armChildObserver(),this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration,observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onChildMutations(records)});this.childObserver=observer,this.childObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.releaseExternalDescription(),this.releaseRequiredDescription(),this.cachedBoxes=void 0,this.removeEventListener("input",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-input",this.onChildEvent,{capture:!0}),this.removeEventListener("change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-change",this.onChildEvent,{capture:!0}),this.removeEventListener("lr-checkbox-toggle-request",this.onChildToggleRequest,{capture:!0}),this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller),box.setGroupDisabled?.(!1);const authoredSize=this.authoredChildSizes.get(box);authoredSize!==void 0&&box.size!==authoredSize&&(box.size=authoredSize)}this.childControllers.clear(),this.authoredChildSizes.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.resetChildObserver(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}resetChildObserver(){this.childObserverGeneration+=1,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0}firstUpdated(changed){super.firstUpdated(changed),this.addEventListener("blur",event=>{const blurredControl=event.target;(typeof blurredControl?.matches=="function"?blurredControl.matches(":disabled"):this.effectiveDisabled)||(this.hasInteracted=!0),this.sync()},!0)}updated(changed){super.updated(changed),changed.has("size")&&this.propagateSize(),this.syncRequiredDescription(),this.syncExternalDescription()}syncExternalDescription(){const target=this.renderRoot.querySelector("fieldset");if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncRequiredDescription(){const target=this.renderRoot.querySelector("fieldset"),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}[VALIDITY_ANCHOR](){const first=this.firstEnabledBox();return resolveValidityAnchor(first)??first??null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}firstEnabledBox(){return this.boxes.find(box=>!box.effectiveDisabled&&!box.matches(":disabled"))}focus(options){this.liveDisabled||this.firstEnabledBox()?.focus(options)}blur(){this.boxes.find(box=>box.matches(":focus-within"))?.blur()}click(){this.liveDisabled||this.firstEnabledBox()?.click()}formResetCallback(){this.suppressCheckboxSync=!0;try{this.boxes.forEach(box=>box.resetFromGroup())}finally{this.suppressCheckboxSync=!1}this.hasInteracted=!1,this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2),this.applyPendingRestore()}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.propagateDisabled(),this.sync(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasHint=this.hasHintSlot||!!this.hint||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`<fieldset
|
|
2
2
|
part="form-control"
|
|
3
3
|
?disabled=${this.effectiveDisabled}
|
|
4
4
|
aria-label=${hostAriaLabel(this)??nothing}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{styles}from"./code-editor.styles.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{autocorrectConverter,normalizeAutocorrect}from"../../../internal/converters.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_codeEditorLabel
|
|
1
|
+
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{styles}from"./code-editor.styles.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{autocorrectConverter,normalizeAutocorrect}from"../../../internal/converters.js";import{lengthLimitConverter,lengthViolations,normalizeLengthLimit}from"../../../internal/length-constraints.js";import{dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_codeEditorLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";class LyraCodeEditorBase extends LyraElement{}class LyraCodeEditor extends FormAssociated(LyraCodeEditorBase){constructor(){super(...arguments),this.language="",this.withoutLineNumbers=!1,this._tabSize=2,this.tabSizeAssigned=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.readonly=!1,this._rows=4,this.cols=20,this.resize="both",this.size="m",this.wrapValue="off",this.spellcheck=!1,this.autofocus=!1,this.title="",this.autocapitalize="off",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.autocorrectValue=!1,this.accessibleLabel="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.gutterWindowStart=0,this.caretOffset=0,this.onInput=event=>{if(this.liveDisabled){event.stopPropagation();return}this.value=event.target.value,this.syncCaretOffset(),this.fitToContent(),relayNativeEvent(this,event),this.emit("lr-input",{value:this.value})},this.onChange=event=>{if(this.liveDisabled){event.stopPropagation();return}this.value=event.target.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value})},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}const textarea=event.target;queueMicrotask(()=>{this.isConnected&&this.textarea===textarea&&shadowFocusTarget(this)===textarea&&this.syncCaretOffset()}),relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.tabBypassArmed=!1,relayNativeEvent(this,event)},this.tabBypassArmed=!1,this.onKeyDown=event=>{if(!this.liveDisabled){if(event.key==="Escape"){this.tabBypassArmed=!0;return}if(event.key==="Tab"){if(event.shiftKey)return;if(this.tabBypassArmed){this.tabBypassArmed=!1;return}if(this.readonly)return;event.preventDefault();const target=event.target,start=target.selectionStart;target.setRangeText(" ".repeat(this.indentWidth),start,target.selectionEnd,"end"),this.value=target.value,dispatchNativeInputEvent(this,{data:" ".repeat(this.indentWidth),inputType:"insertText"}),this.emit("lr-input",{value:this.value});return}this.tabBypassArmed=!1}},this.onCaretChange=()=>{this.syncCaretOffset()},this.onEditorScroll=()=>{if(this.syncGutterInlinePosition(),this.withoutLineNumbers||!this.editor||!this.textarea)return;const computed=this.ownerDocument.defaultView?.getComputedStyle(this.textarea),lineHeight=computed?Number.parseFloat(computed.lineHeight):Number.NaN;if(!Number.isFinite(lineHeight)||lineHeight<=0)return;let firstVisible=Math.floor(this.editor.scrollTop/lineHeight);if(this.wrapsText){const offsets=this.lineStarts();let low=0,high=offsets.length-1;for(;low<high;){const middle=Math.ceil((low+high)/2);this.wrappedLineOffset(offsets[middle])<=this.editor.scrollTop?low=middle:high=middle-1}firstVisible=low}const next=Math.max(0,firstVisible-20);next!==this.gutterWindowStart&&(this.gutterWindowStart=next)}}static{this.defaultStrings={...super.defaultStrings,codeEditorLabel:LYRA_DEFAULT_codeEditorLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,styles]}get tabSize(){return this._tabSize}set tabSize(value){const old=this._tabSize;this.tabSizeAssigned=value!=null,this._tabSize=finiteInteger(value,2,1,16),this.requestUpdate("tabSize",old)}get indentWidth(){if(this.tabSizeAssigned||!this.textarea)return this._tabSize;const resolved=getComputedStyle(this.textarea).tabSize.trim();return/^\d+(?:\.\d+)?$/.test(resolved)?finiteInteger(Number(resolved),this._tabSize,1,16):this._tabSize}get rows(){return this._rows}set rows(next){const previous=this._rows;this._rows=finiteInteger(next,4,1),this.requestUpdate("rows",previous)}get minlength(){return this._minlength}set minlength(next){const previous=this._minlength;this._minlength=normalizeLengthLimit(next),this.requestUpdate("minlength",previous)}get maxlength(){return this._maxlength}set maxlength(next){const previous=this._maxlength;this._maxlength=normalizeLengthLimit(next),this.requestUpdate("maxlength",previous)}get wrap(){return this.wrapValue}set wrap(next){const old=this.wrapValue;this.wrapValue=next==="soft"||next==="hard"?next:"off",this.syncSubmissionValue(),this.requestUpdate("wrap",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}connectedCallback(){super.connectedCallback(),this.hasUpdated&&(this.syncExternalDescription(),this.observeTextGeometry())}disconnectedCallback(){this.textGeometryObserver?.disconnect(),this.textGeometryObserver=void 0,this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.textGeometryObserver?.disconnect(),this.textGeometryObserver=void 0,this.isConnected&&this.hasUpdated&&(this.syncExternalDescription(),this.observeTextGeometry())}syncExternalDescription(){if(!this.isConnected)return;const owner=this.textarea;owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}formResetCallback(){super.formResetCallback(),this.touched=!1}get value(){return super.value}set value(next){super.value=this.normalizeLineEndings(next),this.syncSubmissionValue()}get defaultValue(){return super.defaultValue}set defaultValue(next){super.defaultValue=this.normalizeLineEndings(next),this.syncSubmissionValue()}normalizeLineEndings(value){return String(value??"").replace(/\r\n?/g,`
|
|
2
2
|
`)}submissionValue(){if(this.wrap!=="hard")return this.value;const view=this.ownerDocument?.defaultView;if(!view?.FormData)return this.value;const form=this.ownerDocument.createElement("form"),textarea=this.ownerDocument.createElement("textarea");textarea.name="value",textarea.wrap="hard",textarea.cols=finiteInteger(this.cols,20,1,1e6),textarea.value=this.value,form.append(textarea),(this.isConnected?this.ownerDocument.body:null)?.append(form);try{const serialized=new view.FormData(form).get("value");return typeof serialized=="string"?serialized:this.value}catch{return this.value}finally{form.remove()}}syncSubmissionValue(){this.internals&&this.internals.setFormValue(this.submissionValue(),this.value)}get input(){return this.textarea??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.textarea?.click()}focus(options){this.liveDisabled||this.textarea?.focus(options)}blur(){this.textarea?.blur()}select(){this.textarea?.select(),this.syncCaretOffset()}get selectionStart(){return this.textarea?.selectionStart??null}set selectionStart(value){this.textarea&&(this.textarea.selectionStart=value??0,this.syncCaretOffset())}get selectionEnd(){return this.textarea?.selectionEnd??null}set selectionEnd(value){this.textarea&&(this.textarea.selectionEnd=value??0,this.syncCaretOffset())}get selectionDirection(){return this.textarea?.selectionDirection??null}set selectionDirection(value){this.textarea&&(this.textarea.selectionDirection=value??"none",this.syncCaretOffset())}setSelectionRange(start,end,direction){this.textarea?.setSelectionRange(start,end,direction),this.syncCaretOffset()}setRangeText(replacement,start,end,selectionMode){const textarea=this.textarea;textarea&&(textarea.setRangeText(replacement,start??textarea.selectionStart,end??textarea.selectionEnd,selectionMode),this.value=textarea.value,this.syncCaretOffset(),this.fitToContent())}scrollPosition(position){const editor=this.editor;if(editor){if(position===void 0)return{top:editor.scrollTop,left:editor.scrollLeft};position.top!==void 0&&(editor.scrollTop=finiteNumber(position.top,editor.scrollTop)),position.left!==void 0&&(editor.scrollLeft=finiteNumber(position.left,editor.scrollLeft)),this.syncGutterInlinePosition()}}syncCaretOffset(){const textarea=this.textarea;if(!textarea)return;const next=finiteInteger(textarea.selectionEnd,0,0,this.value.length);if(next===this.caretOffset){this.scrollCaretIntoView();return}this.caretOffset=next}scrollCaretIntoView(){const editor=this.editor,marker=this.caretMeasure;if(!editor||!marker)return;const frame=editor.getBoundingClientRect();let caret=marker.getBoundingClientRect(),text=marker.nextSibling;for(;text&&(text.nodeType!==3||!text.textContent);)text=text.nextSibling;if(text){const range=this.ownerDocument.createRange();range.setStart(text,0),text.textContent?.startsWith(`
|
|
3
3
|
`)?range.setEnd(text,1):range.collapse(!0);const measured=range.getBoundingClientRect();measured.height>0&&(caret=measured)}const gutterWidth=this.gutter?.getBoundingClientRect().width??0,viewportLeft=frame.left+editor.clientLeft,viewportTop=frame.top+editor.clientTop,textLeft=viewportLeft+(this.effectiveDirection==="rtl"?0:gutterWidth),textRight=viewportLeft+editor.clientWidth-(this.effectiveDirection==="rtl"?gutterWidth:0),viewportBottom=viewportTop+editor.clientHeight,left=caret.left<textLeft?caret.left-textLeft:caret.right>textRight?caret.right-textRight:0,top=caret.top<viewportTop?caret.top-viewportTop:caret.bottom>viewportBottom?caret.bottom-viewportBottom:0;left===0&&top===0||(editor.scrollBy({left:finiteNumber(left,0),top:finiteNumber(top,0)}),this.syncGutterInlinePosition())}updated(changed){super.updated(changed),this.syncExternalDescription(),this.textarea&&this.textarea.value!==this.value&&(this.textarea.value=this.value),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("minlength")||changed.has("maxlength")||changed.has("readonly"))&&(this.updateValidity(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)),(changed.has("wrap")||changed.has("cols"))&&this.syncSubmissionValue(),(changed.has("resize")||changed.has("value")||changed.has("rows")||changed.has("cols"))&&this.fitToContent(),this.syncGutterInlinePosition(),this.observeTextGeometry(),this.syncGutterGeometry(),(changed.has("caretOffset")||changed.has("value"))&&this.scrollCaretIntoView()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}const native=this.textarea;native&&native.value!==this.value&&(native.value=this.value);const own=lengthViolations(this.value,this.minlength,this.maxlength),tooShort=!!native?.validity.tooShort||own.tooShort,tooLong=!!native?.validity.tooLong||own.tooLong;this[SET_ANCHORED_VALIDITY](tooShort||tooLong?{tooShort,tooLong}:{},tooShort||tooLong?native?.validationMessage||this.localize("valueInvalid"):"")}countLines(){if(this.withoutLineNumbers)return 0;let count=1;for(let index=0;index<this.value.length;index++)this.value.charCodeAt(index)===10&&count++;return count}syncGutterInlinePosition(){const editor=this.editor,gutter=this.gutter;!editor||!gutter||gutter.style.setProperty("--_lr-code-editor-gutter-scroll-translation",`${finiteNumber(editor.scrollLeft,0)}px`)}get wrapsText(){return this.wrap==="soft"||this.wrap==="hard"}lineStarts(){if(this.wrappedLineStarts?.value===this.value)return this.wrappedLineStarts.offsets;const offsets=[0];for(let index=0;index<this.value.length;index++)this.value.charCodeAt(index)===10&&offsets.push(index+1);return this.wrappedLineStarts={value:this.value,offsets},offsets}wrappedLineOffset(offset){const measure=this.renderRoot.querySelector(".editor-measure");if(!measure)return 0;const nodes=Array.from(measure.childNodes).filter(node=>node.nodeType===3),range=this.ownerDocument.createRange(),first=nodes.find(node=>(node.textContent?.length??0)>0);if(!first)return 0;range.setStart(first,0),range.setEnd(first,1);const firstTop=range.getBoundingClientRect().top;let remaining=offset;for(const node of nodes){const length=node.textContent?.length??0;if(remaining<length)return range.setStart(node,remaining),range.setEnd(node,remaining+1),range.getBoundingClientRect().top-firstTop;remaining-=length}return 0}syncGutterGeometry(){if(this.withoutLineNumbers)return;const lines=this.renderRoot.querySelectorAll(".gutter-line"),start=Math.min(this.gutterWindowStart,Math.max(0,this.countLines()-1)),offsets=this.wrapsText?this.lineStarts():void 0,positions=offsets?Array.from(lines,(_line,index)=>this.wrappedLineOffset(offsets[start+index]??0)):void 0,height=this.renderRoot.querySelector(".editor-measure")?.getBoundingClientRect().height;height!==void 0&&this.gutter?.style.setProperty("block-size",`${height}px`),lines.forEach((line,index)=>{line.style.insetBlockStart=positions?`${positions[index]}px`:`calc(var(--lr-code-editor-line-height, var(--_lr-code-editor-line-height)) * ${start+index}em)`})}observeTextGeometry(){if(this.withoutLineNumbers||!this.isConnected){this.textGeometryObserver?.disconnect(),this.textGeometryObserver=void 0;return}if(this.textGeometryObserver)return;const measure=this.renderRoot.querySelector(".editor-measure"),ownerDocument=this.ownerDocument,Observer=ownerDocument.defaultView?.ResizeObserver;if(!measure||!Observer)return;const observer=new Observer(()=>{!this.isConnected||this.ownerDocument!==ownerDocument||this.textGeometryObserver!==observer||(this.onEditorScroll(),this.syncGutterGeometry())});this.textGeometryObserver=observer,observer.observe(measure)}gutterRows(lineCount){const start=Math.min(this.gutterWindowStart,Math.max(0,lineCount-1)),end=Math.min(lineCount,start+200),rows=Array.from({length:end-start},(_value,offset)=>{const index=start+offset;return html`<span
|
|
4
4
|
class="gutter-line"
|
|
@@ -198,13 +198,14 @@ static get validators():LyraFormValidator<LyraColorPicker>[];static styles:impor
|
|
|
198
198
|
/** Server-rendering hint that the `label` slot is populated before client slot observation. */
|
|
199
199
|
withLabel:boolean;
|
|
200
200
|
/** Server-rendering hint that the `hint` slot is populated before client slot observation. */
|
|
201
|
-
withHint:boolean;errorText:string;accessibleLabel:string;
|
|
201
|
+
withHint:boolean;errorText:string;accessibleLabel:string;private _readonly;
|
|
202
202
|
/** Forwards native read-only behavior to the internal value field and blocks every other
|
|
203
203
|
* value-committing affordance (the popup panel opening, the saturation/hue/opacity handles,
|
|
204
204
|
* palette swatches, the eyedropper, and Enter/blur-driven text commits) while leaving the
|
|
205
205
|
* control focusable, its value selectable/copyable, and its current value submitted with the
|
|
206
|
-
* form -- mirroring `lr-input`'s `readonly`.
|
|
207
|
-
|
|
206
|
+
* form -- mirroring `lr-input`'s `readonly`.
|
|
207
|
+
* @default false */
|
|
208
|
+
get readonly():boolean;set readonly(next:boolean);
|
|
208
209
|
/** Visible-swatch size — the library-wide `2xs`–`xl` ladder shared with `lr-input`/`lr-select`.
|
|
209
210
|
* The interactive trigger retains the shared `--lr-icon-button-size` minimum target even when
|
|
210
211
|
* the visible swatch is denser. The Web Awesome / Shoelace spellings `small`/`medium`/`large`
|
|
@@ -258,7 +259,10 @@ get hoist():boolean;set hoist(next:boolean);
|
|
|
258
259
|
/** Preferred panel placement; the resolved side still flips to stay in the viewport. */
|
|
259
260
|
placement:Placement;private _open;
|
|
260
261
|
/** Whether the popup panel is open. The panel remains visible in `inline` mode. */
|
|
261
|
-
get open():boolean;set open(next:boolean);private applyOpenState;private hasLabel;private hasHint;private hasError;private hasEyeDropper;private color;private valueNeedsParse;private pendingInput;private localDescriptionIds;private externalDescriptionLease?;private get liveDisabled();private syncExternalDescription;private releaseExternalDescription;private hintId;private errorId;private labelId;private valueTextId;private triggerId;private panelId;private drag?;private dragWindow?;private dragChanged;private keyboardChanged;private cleanupPositioner?;private overlayHandle?;private restoreFocusOnClose;private lightDismissDocument?;private eyeDropperAbort?;private eyeDropperGeneration;private suppressDisconnectedClose;private pendingPlacementEffects;private interactionGeneration;private hasRenderedOnce;constructor();connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;get value():string;set value(next:string|null);
|
|
262
|
+
get open():boolean;set open(next:boolean);private applyOpenState;private hasLabel;private hasHint;private hasError;private hasEyeDropper;private color;private valueNeedsParse;private pendingInput;private localDescriptionIds;private externalDescriptionLease?;private get liveDisabled();private syncExternalDescription;private releaseExternalDescription;private hintId;private errorId;private labelId;private valueTextId;private triggerId;private panelId;private drag?;private dragWindow?;private dragChanged;private keyboardChanged;private cleanupPositioner?;private overlayHandle?;private restoreFocusOnClose;private lightDismissDocument?;private eyeDropperAbort?;private eyeDropperGeneration;private suppressDisconnectedClose;private pendingPlacementEffects;private interactionGeneration;private hasRenderedOnce;constructor();connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;get value():string;set value(next:string|null);
|
|
263
|
+
/** Disables the control and retires any pending screen-color selection.
|
|
264
|
+
* @default false */
|
|
265
|
+
get disabled():boolean;set disabled(next:boolean);formDisabledCallback(disabled:boolean):void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;
|
|
262
266
|
/** Opens the popup panel. A no-op while disabled; inline visibility is unchanged. */
|
|
263
267
|
show():void;
|
|
264
268
|
/** Closes the popup panel, returning focus to its trigger; inline visibility is unchanged. */
|