@aceshooting/lyra-ui 27.0.0 → 28.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -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.d.ts +4 -2
- package/dist/components/charts/chart/box-plot.class.js +6 -5
- package/dist/components/charts/chart/chart-token-cache.js +2 -2
- package/dist/components/charts/chart/chart.class.d.ts +6 -4
- package/dist/components/charts/chart/chart.class.js +8 -7
- 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.d.ts +2 -1
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.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/nonmodal-overlay-manager.js +1 -1
- package/dist/internal/opaque-content-border.styles.js +1 -1
- package/dist/internal/open-overlay-ancestors.js +1 -0
- 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 +22 -1
- 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-box-plot.md +5 -0
- package/llms/components/lr-chart.md +6 -0
- package/llms/components/lr-emoji-picker.md +13 -8
- package/llms/components/lr-heatmap.md +10 -2
- 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 +104 -7
- package/llms/shared.md +445 -115
- package/llms/tokens.md +31 -49
- package/locales.json +138 -138
- package/package.json +16 -8
- 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{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{syncAriaControlsElements,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_iconButtonLabel}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]),SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-")||isUnsafeSvgCloneElement(node.localName))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,node.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of node.childNodes)if(child.nodeType===3)copy.append(child.cloneNode(!0));else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);childCopy&©.append(childCopy)}return copy}function namesControl(nodes){for(const node of nodes){if(node.nodeType===3){if(node.textContent?.trim())return!0;continue}const el=node;if(!(el.nodeType!==1||el.hasAttribute("hidden")||el.getAttribute("aria-hidden")==="true")&&(el.getAttribute("aria-label")?.trim()||el.getAttribute("alt")?.trim()||namesControl((el.shadowRoot??el).childNodes)))return!0}return!1}class LyraIconButton extends LyraElement{constructor(){super(...arguments),this._disabled=!1,this.toolbarAction=this.createToolbarAction(),this.icon="",this.accessibleLabel="",this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerControls=null,this.triggerDescribedBy=null,this.triggerPressed=null,this.triggerCurrent=null,this.label="",this.hasBareGeometry=!1,this.contentNamed=!1,this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{relayNativeEvent(this,event)},this.onSlotChange=e=>{this.onSlotChangeFromSlot(e.target)}}static{this.defaultStrings={...super.defaultStrings,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,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.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled}get name(){return this.icon}set name(next){this.icon=next??""}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}get control(){return this.baseEl??null}click(){this.effectiveDisabled||this.baseEl?.click()}focus(options){this.effectiveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}onSlotChangeFromSlot(slot){const assigned=slot.assignedNodes({flatten:!0});this.hasBareGeometry=assigned.some(node=>node.nodeType===1&&needsSvgNamespaceFallback(node)),this.contentNamed=namesControl(assigned)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.slotEl;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onSlotChangeFromSlot(s))})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{this.contentNamed=namesControl(this.childNodes)})}updated(changed){super.updated(changed),this.syncFallbackGeometry(),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements()}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"),this.externalLabelLease?this.externalLabelLease.update(target):this.externalLabelLease=acquireResolvedAriaRelationship(this,target,"aria-labelledby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0,this.externalLabelLease?.release(),this.externalLabelLease=void 0}getToolbarActions(){return[this.toolbarAction]}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1;const releaseTabIndex=()=>{const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"icon-button",get disabled(){return host.effectiveDisabled||!host.baseEl},focus(options){host.focus(options)},setTabIndex(tabIndex){const trigger=host.baseEl;if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const control=host.baseEl;return path.includes(host)||control!=null&&path.includes(control)}}}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:!0})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);copy&&svgEl.append(copy)}}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,label=hostAriaLabel(this)??(this.label||(this.contentNamed?nothing:this.localize("iconButtonLabel"))),content=html`${this.icon||this.src?html`<lr-icon
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{syncAriaControlsElements,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_iconButtonLabel}from"../../../internal/default-strings/forms.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]),SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-")||isUnsafeSvgCloneElement(node.localName))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,node.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of node.childNodes)if(child.nodeType===3)copy.append(child.cloneNode(!0));else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);childCopy&©.append(childCopy)}return copy}function namesControl(nodes){for(const node of nodes){if(node.nodeType===3){if(node.textContent?.trim())return!0;continue}const el=node;if(!(el.nodeType!==1||el.hasAttribute("hidden")||el.getAttribute("aria-hidden")==="true")&&(el.getAttribute("aria-label")?.trim()||el.getAttribute("alt")?.trim()||namesControl((el.shadowRoot??el).childNodes)))return!0}return!1}class LyraIconButton extends LyraElement{constructor(){super(...arguments),this._disabled=!1,this.toolbarAction=this.createToolbarAction(),this.icon="",this.accessibleLabel="",this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerControls=null,this.triggerDescribedBy=null,this.triggerPressed=null,this.triggerCurrent=null,this.label="",this.hasBareGeometry=!1,this.contentNamed=!1,this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{relayNativeEvent(this,event)},this.onSlotChange=e=>{this.onSlotChangeFromSlot(e.target)}}static{this.defaultStrings={...super.defaultStrings,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,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.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled}get name(){return this.icon}set name(next){this.icon=next??""}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}get control(){return this.baseEl??null}click(){this.effectiveDisabled||this.baseEl?.click()}focus(options){this.effectiveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}onSlotChangeFromSlot(slot){const assigned=slot.assignedNodes({flatten:!0});this.hasBareGeometry=assigned.some(node=>node.nodeType===1&&needsSvgNamespaceFallback(node)),this.contentNamed=namesControl(assigned)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements()}firstUpdated(changed){super.firstUpdated(changed);const slot=this.slotEl;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.onSlotChangeFromSlot(s))})}disconnectedCallback(){this.toolbarAction.releaseTabIndex?.(),this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){this.toolbarAction.releaseTabIndex?.(),super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed),this.seedFirstRenderState(()=>{this.contentNamed=namesControl(this.childNodes)})}updated(changed){super.updated(changed),this.syncFallbackGeometry(),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements()}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"),this.externalLabelLease?this.externalLabelLease.update(target):this.externalLabelLease=acquireResolvedAriaRelationship(this,target,"aria-labelledby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0,this.externalLabelLease?.release(),this.externalLabelLease=void 0}getToolbarActions(){return[this.toolbarAction]}createToolbarAction(){const host=this;let leasedTrigger,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1;const releaseTabIndex=()=>{const target=leasedTrigger;target&&target.getAttribute("tabindex")===lastManagedTabIndex&&(authoredTabIndex===null?target.removeAttribute("tabindex"):target.setAttribute("tabindex",authoredTabIndex)),leasedTrigger=void 0,authoredTabIndex=null,lastManagedTabIndex=null,consumerOwnsTabIndex=!1};return{id:"icon-button",get disabled(){return host.effectiveDisabled||!host.baseEl},focus(options){host.focus(options)},setTabIndex(tabIndex){const trigger=host.baseEl;if(!trigger){releaseTabIndex();return}if(leasedTrigger!==trigger&&(releaseTabIndex(),leasedTrigger=trigger,authoredTabIndex=trigger.getAttribute("tabindex")),consumerOwnsTabIndex||lastManagedTabIndex!==null&&trigger.getAttribute("tabindex")!==lastManagedTabIndex){consumerOwnsTabIndex=!0;return}trigger.tabIndex=tabIndex,lastManagedTabIndex=trigger.getAttribute("tabindex")},releaseTabIndex,matchesEventPath(path){const control=host.baseEl;return path.includes(host)||control!=null&&path.includes(control)}}}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:!0})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);copy&&svgEl.append(copy)}}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,label=hostAriaLabel(this)??(this.label||(this.contentNamed?nothing:this.localize("iconButtonLabel"))),content=html`${this.icon||this.src?html`<lr-icon
|
|
2
2
|
name=${this.icon||nothing}
|
|
3
3
|
library=${this.library||nothing}
|
|
4
4
|
src=${this.src||nothing}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{iconAction,iconActionHover,iconActionActive}from"../../../internal/icon-action.styles.js";import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: inline-flex; --_lr-icon-button-radius-default: var(--lr-radius); } [part~='button'] { ${iconHitTarget} ${iconAction} } [part~='button']:not(:disabled):not([aria-disabled='true']):hover { ${iconActionHover} } [part~='button']:not(:disabled):not([aria-disabled='true']):active { ${iconActionActive} } [part~='button']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part~='button']:disabled, [part~='button'][aria-disabled='true'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } lr-icon { inline-size: var(--lr-icon-size, var(--lr-size-1-25rem)); block-size: var(--lr-icon-size, var(--lr-size-1-25rem)); } [part='fallback'] { display: block; inline-size: var(--lr-icon-size, var(--lr-size-1-25rem)); block-size: var(--lr-icon-size, var(--lr-size-1-25rem)); color: inherit; } `;export{styles};
|
|
1
|
+
import{iconAction,iconActionHover,iconActionActive}from"../../../internal/icon-action.styles.js";import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";const styles=css` :host { display: inline-flex; --_lr-icon-button-radius-default: var(--lr-radius); } [part~='button'] { ${iconHitTarget} ${iconAction} } [part~='button'] { padding-inline: var(--lr-icon-button-padding-inline, 0); } [part~='button']:not(:disabled):not([aria-disabled='true']):hover { ${iconActionHover} } [part~='button']:not(:disabled):not([aria-disabled='true']):active { ${iconActionActive} } [part~='button']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part~='button']:disabled, [part~='button'][aria-disabled='true'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } lr-icon { inline-size: var(--lr-icon-size, var(--lr-size-1-25rem)); block-size: var(--lr-icon-size, var(--lr-size-1-25rem)); } [part='fallback'] { display: block; inline-size: var(--lr-icon-size, var(--lr-size-1-25rem)); block-size: var(--lr-icon-size, var(--lr-size-1-25rem)); color: inherit; } `;export{styles};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.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{setCustomState}from"../../../internal/custom-states.js";import{lengthLimitConverter,lengthViolations}from"../../../internal/length-constraints.js";import{MatchConstraintController}from"../../../internal/match-constraint.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{sizes}from"../../../internal/sizes.styles.js";import{srOnly}from"../../../internal/a11y.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_matchMismatch,LYRA_DEFAULT_showPassword,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const boundConverter={fromAttribute:value=>value==null?null:/^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?\s*$/i.test(value)?Number(value):value};let temporalProbe;function temporalProbeFor(doc,type){if(!(type!=="date"&&type!=="time"&&type!=="datetime-local"))return temporalProbe??=doc.createElement("input"),temporalProbe.type=type,temporalProbe}const INPUT_TYPES=new Set(["text","password","email","number","time","search","date","datetime-local","tel","url"]),LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInputShared extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,matchMismatch:LYRA_DEFAULT_matchMismatch,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}get value(){return super.value}set value(next){const normalized=next??"";super.value=normalized,this.settlingValueFromInput||this.settledDebounce.cancelIfChanged(normalized)}get type(){return this._type}set type(next){const old=this._type;this._type=INPUT_TYPES.has(next)?next:"text",old!==this._type&&this.requestUpdate("type",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 hidesSpinButtons(){return this.withoutSpinButtons}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}get inputId(){return this.id||"input"}constructor(){super(),this._type="text",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.placeholder="",this.clearable=!1,this.withClear=!1,this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.autocomplete="",this.title="",this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.inputMode="",this.enterKeyHint="",this.passwordToggle=!1,this.passwordVisible=!1,this.withoutSpinButtons=!1,this.match=null,this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.settlingValueFromInput=!1,this.settledDebounce=new DebounceController(0,value=>{this.emit("lr-input-settled",{value})}),this.matchController=new MatchConstraintController(this,()=>this.match,()=>this.updateValidity()),this.hostDescription=new HostDescriptionController(this,()=>this.inputEl??null,()=>{const description=this.renderRoot.querySelector("#input-required");return this.required&&description?[description]:[]}),this.onInput=event=>{this.inputEl&&(this.settlingValueFromInput=!0,this.value=this.inputEl.value,this.settlingValueFromInput=!1,relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}),this.isDebounced()?(this.settledDebounce.delayMs=this.effectiveDebounceMs,this.settledDebounce.push(this.value)):this.settledDebounce.cancel())},this.onChange=event=>{this.inputEl&&(this.settledDebounce.flush(),this.value=this.inputEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{this.effectiveDisabled||(this.touched=!0),this.settledDebounce.flush(),relayNativeEvent(this,event)},this.onKeyDown=event=>{this.effectiveDisabled||this.readonly||(event.key==="Enter"&&this.settledDebounce.flush(),submitOnEnter(this,event))},this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible},this.onClear=()=>{this.effectiveDisabled||this.readonly||this.value===""||(this.value="",this.inputEl&&(this.inputEl.value=""),dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}),this.emit("lr-clear"),this.inputEl?.focus())},this.addEventListener("invalid",()=>{this.touched=!0})}disconnectedCallback(){this.settledDebounce.cancel(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}formResetCallback(){super.formResetCallback(),this.touched=!1}get input(){return this.inputEl??null}click(){this.effectiveDisabled||this.inputEl?.click()}focus(options){this.effectiveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsDate):null}set valueAsDate(next){const native=this.inputEl;native&&(native.valueAsDate=next,this.value=native.value)}get valueAsLocalDate(){const utc=this.valueAsUTCDate;if(!utc)return null;const local=new Date;return this.type!=="time"&&local.setFullYear(utc.getUTCFullYear(),utc.getUTCMonth(),utc.getUTCDate()),local.setHours(utc.getUTCHours(),utc.getUTCMinutes(),utc.getUTCSeconds(),utc.getUTCMilliseconds()),local}set valueAsLocalDate(next){this.valueAsUTCDate=isDateObject(next)?new Date(next.getTime()-next.getTimezoneOffset()*6e4):null}get valueAsUTCDate(){const probe=temporalProbeFor(this.ownerDocument,this.type);return probe?(probe.value=this.value,Number.isNaN(probe.valueAsNumber)?null:new Date(probe.valueAsNumber)):null}set valueAsUTCDate(next){const probe=temporalProbeFor(this.ownerDocument,this.type);if(!probe)return;const ms=isDateObject(next)?next.getTime():NaN;probe.value="",Number.isNaN(ms)||(probe.valueAsNumber=this.type==="time"?(ms%864e5+864e5)%864e5:ms),this.value=probe.value}get valueAsNumber(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsNumber):Number.NaN}set valueAsNumber(next){const native=this.inputEl;native&&(native.valueAsNumber=next,this.value=native.value)}showPicker(){const native=this.inputEl;if(!(!native||this.effectiveDisabled||this.readonly)&&"showPicker"in HTMLInputElement.prototype)try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count!==0){native.type=this.type,native.min=this.min==null?"":String(this.min),native.max=this.max==null?"":String(this.max),native.step=this.step==null?"":String(this.step),native.value=this.value;try{direction==="up"?native.stepUp(count):native.stepDown(count)}catch{return}this.value!==native.value&&(this.value=native.value)}}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.value=input.value)}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){this.required&&this.value===""?this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired")):this.matchMismatches()?this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch")):this[SET_ANCHORED_VALIDITY]({});return}native.value!==this.value&&(native.value=this.value);const sanitizedAway=this.value!==""&&native.value==="",v=native.validity,own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:!1,tooLong:!1},tooShort=v.tooShort||own.tooShort,tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:!0},this.localize("valueInvalid"));return}if(this.matchMismatches()){this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}matchMismatches(){if(!this.match)return!1;const targetValue=this.matchController.targetValue;return targetValue!==null&&targetValue!==this.value}updated(changed){super.updated(changed),changed.has("value")&&setCustomState(this.internals,"blank",this.value===""),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("match")||changed.has("readonly"))&&this.updateValidity()}get effectiveDebounceMs(){return finiteDuration(this.debounce??0,0)}isDebounced(){return this.effectiveDebounceMs>0}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" "),isPassword=this.type==="password",showPasswordToggle=isPassword&&this.passwordToggle,nativeType=isPassword&&this.passwordVisible?"text":this.type,canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.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{setCustomState}from"../../../internal/custom-states.js";import{lengthLimitConverter,lengthViolations}from"../../../internal/length-constraints.js";import{MatchConstraintController}from"../../../internal/match-constraint.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{sizes}from"../../../internal/sizes.styles.js";import{srOnly}from"../../../internal/a11y.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_matchMismatch,LYRA_DEFAULT_showPassword}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const boundConverter={fromAttribute:value=>value==null?null:/^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?\s*$/i.test(value)?Number(value):value};let temporalProbe;function temporalProbeFor(doc,type){if(!(type!=="date"&&type!=="time"&&type!=="datetime-local"))return temporalProbe??=doc.createElement("input"),temporalProbe.type=type,temporalProbe}const INPUT_TYPES=new Set(["text","password","email","number","time","search","date","datetime-local","tel","url"]),LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInputShared extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,matchMismatch:LYRA_DEFAULT_matchMismatch,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}get value(){return super.value}set value(next){const normalized=next??"";super.value=normalized,this.settlingValueFromInput||this.settledDebounce.cancelIfChanged(normalized)}get type(){return this._type}set type(next){const old=this._type;this._type=INPUT_TYPES.has(next)?next:"text",old!==this._type&&this.requestUpdate("type",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 hidesSpinButtons(){return this.withoutSpinButtons}get defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}get inputId(){return this.id||"input"}constructor(){super(),this._type="text",this.size="m",this.appearance="outlined",this.filled=!1,this.pill=!1,this.placeholder="",this.clearable=!1,this.withClear=!1,this.readonly=!1,this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel=null,this.autocomplete="",this.title="",this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.inputMode="",this.enterKeyHint="",this.passwordToggle=!1,this.passwordVisible=!1,this.withoutSpinButtons=!1,this.match=null,this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.settlingValueFromInput=!1,this.settledDebounce=new DebounceController(0,value=>{this.emit("lr-input-settled",{value})}),this.matchController=new MatchConstraintController(this,()=>this.match,()=>this.updateValidity()),this.hostDescription=new HostDescriptionController(this,()=>this.inputEl??null,()=>{const description=this.renderRoot.querySelector("#input-required");return this.required&&description?[description]:[]}),this.onInput=event=>{this.inputEl&&(this.settlingValueFromInput=!0,this.value=this.inputEl.value,this.settlingValueFromInput=!1,relayNativeEvent(this,event),this.emit("lr-input",{value:this.value}),this.isDebounced()?(this.settledDebounce.delayMs=this.effectiveDebounceMs,this.settledDebounce.push(this.value)):this.settledDebounce.cancel())},this.onChange=event=>{this.inputEl&&(this.settledDebounce.flush(),this.value=this.inputEl.value,relayNativeEvent(this,event),this.emit("lr-change",{value:this.value}))},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{this.effectiveDisabled||(this.touched=!0),this.settledDebounce.flush(),relayNativeEvent(this,event)},this.onKeyDown=event=>{this.effectiveDisabled||this.readonly||(event.key==="Enter"&&this.settledDebounce.flush(),submitOnEnter(this,event))},this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible},this.onClear=()=>{this.effectiveDisabled||this.readonly||this.value===""||(this.value="",this.inputEl&&(this.inputEl.value=""),dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}),this.emit("lr-clear"),this.inputEl?.focus())},this.addEventListener("invalid",()=>{this.touched=!0})}disconnectedCallback(){this.settledDebounce.cancel(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}formResetCallback(){super.formResetCallback(),this.touched=!1}get input(){return this.inputEl??null}click(){this.effectiveDisabled||this.inputEl?.click()}focus(options){this.effectiveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsDate):null}set valueAsDate(next){const native=this.inputEl;native&&(native.valueAsDate=next,this.value=native.value)}get valueAsLocalDate(){const utc=this.valueAsUTCDate;if(!utc)return null;const local=new Date;return this.type!=="time"&&local.setFullYear(utc.getUTCFullYear(),utc.getUTCMonth(),utc.getUTCDate()),local.setHours(utc.getUTCHours(),utc.getUTCMinutes(),utc.getUTCSeconds(),utc.getUTCMilliseconds()),local}set valueAsLocalDate(next){this.valueAsUTCDate=isDateObject(next)?new Date(next.getTime()-next.getTimezoneOffset()*6e4):null}get valueAsUTCDate(){const probe=temporalProbeFor(this.ownerDocument,this.type);return probe?(probe.value=this.value,Number.isNaN(probe.valueAsNumber)?null:new Date(probe.valueAsNumber)):null}set valueAsUTCDate(next){const probe=temporalProbeFor(this.ownerDocument,this.type);if(!probe)return;const ms=isDateObject(next)?next.getTime():NaN;probe.value="",Number.isNaN(ms)||(probe.valueAsNumber=this.type==="time"?(ms%864e5+864e5)%864e5:ms),this.value=probe.value}get valueAsNumber(){const native=this.inputEl;return native?(native.value!==this.value&&(native.value=this.value),native.valueAsNumber):Number.NaN}set valueAsNumber(next){const native=this.inputEl;native&&(native.valueAsNumber=next,this.value=native.value)}showPicker(){const native=this.inputEl;if(!(!native||this.effectiveDisabled||this.readonly)&&"showPicker"in HTMLInputElement.prototype)try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count!==0){native.type=this.type,native.min=this.min==null?"":String(this.min),native.max=this.max==null?"":String(this.max),native.step=this.step==null?"":String(this.step),native.value=this.value;try{direction==="up"?native.stepUp(count):native.stepDown(count)}catch{return}this.value!==native.value&&(this.value=native.value)}}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value??0)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value??0)}get selectionDirection(){return this.inputEl?.selectionDirection??null}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value??"none")}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.value=input.value)}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){this.required&&this.value===""?this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired")):this.matchMismatches()?this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch")):this[SET_ANCHORED_VALIDITY]({});return}native.value!==this.value&&(native.value=this.value);const sanitizedAway=this.value!==""&&native.value==="",v=native.validity,own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:!1,tooLong:!1},tooShort=v.tooShort||own.tooShort,tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:!0},this.localize("valueInvalid"));return}if(this.matchMismatches()){this[SET_ANCHORED_VALIDITY]({customError:!0},this.localize("matchMismatch"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}matchMismatches(){if(!this.match)return!1;const targetValue=this.matchController.targetValue;return targetValue!==null&&targetValue!==this.value}updated(changed){super.updated(changed),changed.has("value")&&setCustomState(this.internals,"blank",this.value===""),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("match")||changed.has("readonly"))&&this.updateValidity()}get effectiveDebounceMs(){return finiteDuration(this.debounce??0,0)}isDebounced(){return this.effectiveDebounceMs>0}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" "),isPassword=this.type==="password",showPasswordToggle=isPassword&&this.passwordToggle,nativeType=isPassword&&this.passwordVisible?"text":this.type,canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label
|
|
4
4
|
part="form-control-label"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{property}from"lit/decorators.js";import{LyraInputShared,createInputValidators}from"./input-shared.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";class LyraInput extends LyraInputShared{constructor(){super(...arguments),this.noSpinButtons=!1}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}get hidesSpinButtons(){return this.withoutSpinButtons||this.noSpinButtons}static get validators(){return createInputValidators()}}__decorate([property({type:Boolean,attribute:"no-spin-buttons"})],LyraInput.prototype,"noSpinButtons",void 0);export{LyraInput};
|
|
1
|
+
import{__decorate}from"tslib";import{property}from"lit/decorators.js";import{LyraInputShared,createInputValidators}from"./input-shared.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";class LyraInput extends LyraInputShared{constructor(){super(...arguments),this.noSpinButtons=!1}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}get hidesSpinButtons(){return this.withoutSpinButtons||this.noSpinButtons}static get validators(){return createInputValidators()}}__decorate([property({type:Boolean,attribute:"no-spin-buttons"})],LyraInput.prototype,"noSpinButtons",void 0);export{LyraInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{property}from"lit/decorators.js";import{LyraInputShared,createInputValidators}from"./input-shared.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";const timeBoundConverter={fromAttribute:value=>value??void 0};class LyraNativeTimeInput extends LyraInputShared{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return createInputValidators()}get inputWrapperParts(){return`${super.inputWrapperParts} time-input`}constructor(){super(),this.appearance="filled-outlined",this.type="time"}connectedCallback(){super.connectedCallback(),this.type="time"}}__decorate([property({reflect:!0})],LyraNativeTimeInput.prototype,"appearance",void 0),__decorate([property({converter:timeBoundConverter})],LyraNativeTimeInput.prototype,"min",void 0),__decorate([property({converter:timeBoundConverter})],LyraNativeTimeInput.prototype,"max",void 0);export{LyraNativeTimeInput};
|
|
1
|
+
import{__decorate}from"tslib";import{property}from"lit/decorators.js";import{LyraInputShared,createInputValidators}from"./input-shared.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const timeBoundConverter={fromAttribute:value=>value??void 0};class LyraNativeTimeInput extends LyraInputShared{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return createInputValidators()}get inputWrapperParts(){return`${super.inputWrapperParts} time-input`}constructor(){super(),this.appearance="filled-outlined",this.type="time"}connectedCallback(){super.connectedCallback(),this.type="time"}}__decorate([property({reflect:!0})],LyraNativeTimeInput.prototype,"appearance",void 0),__decorate([property({converter:timeBoundConverter})],LyraNativeTimeInput.prototype,"min",void 0),__decorate([property({converter:timeBoundConverter})],LyraNativeTimeInput.prototype,"max",void 0);export{LyraNativeTimeInput};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{chevronIcon}from"../../../internal/icons.js";import{presenceTrueDefaultBooleanConverter}from"../../../internal/converters.js";import{LyraInput}from"./input.class.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{styles as numberInputStyles}from"./number-input.styles.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{chevronIcon}from"../../../internal/icons.js";import{presenceTrueDefaultBooleanConverter}from"../../../internal/converters.js";import{LyraInput}from"./input.class.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{styles as numberInputStyles}from"./number-input.styles.js";import{LYRA_DEFAULT_numberInputDecrease,LYRA_DEFAULT_numberInputIncrease}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";class LyraNumberInput extends LyraInput{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,numberInputDecrease:LYRA_DEFAULT_numberInputDecrease,numberInputIncrease:LYRA_DEFAULT_numberInputIncrease}}static get validators(){return super.validators}static{this.styles=[...LyraInput.styles,numberInputStyles]}get inputWrapperParts(){return`${super.inputWrapperParts} number-input`}constructor(){super(),this.withoutSteppers=!1,this.appearance="outlined",this.inputMode="numeric",this.step=1,this.withoutSpinButtons=!0,this.onFocusWithin=()=>{setCustomState(this.internals,"focused",!0)},this.onBlurWithin=()=>{setCustomState(this.internals,"focused",!1)},this.onStepUp=()=>{this.stepFromButton("up")},this.onStepDown=()=>{this.stepFromButton("down")},this.type="number",this.addEventListener("focusin",this.onFocusWithin),this.addEventListener("focusout",this.onBlurWithin)}connectedCallback(){super.connectedCallback(),this.type="number",this.syncMappedStates()}syncMappedStates(){setCustomState(this.internals,"blank",this.value==="")}stepFromButton(direction){if(this.effectiveDisabled||this.readonly)return;const before=this.value;direction==="up"?this.stepUp():this.stepDown(),this.value!==before&&(dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.input?.focus()}renderControls(){if(this.withoutSteppers)return nothing;const inert=this.effectiveDisabled||this.readonly;return html`
|
|
2
2
|
<button
|
|
3
3
|
part="stepper stepper-decrement stepper-down"
|
|
4
4
|
type="button"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour,wrapTimeMilliseconds}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get hasStartSlot(){return this.slotPresence.has("start")}get hasEndSlot(){return this.slotPresence.has("end")}get hasFooterSlot(){return this.slotPresence.has("footer")}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.clearable=!1,this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.popupHidden=!0,this.popupPositioned=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.genuineValue="",this.digitBuffer="",this.inputDigitLocale="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="popup"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocumentPointerDown(event)}),this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part~="input"]'),()=>{const description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);return this.required&&description?[description]:[]}),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},new GlassScrollLayer(this,'[part="popup"]',()=>this.open),this.addEventListener("invalid",()=>{this.touched=!0})}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.forceClose(!1),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute";const committed=this.committedValue;committed!==this.value&&(super.value=committed),this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){this.genuineValue=normalizeTimeValue(next);const normalized=this.committedValue;this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}get valueAsLocalDate(){return this.valueAsDate}set valueAsLocalDate(next){this.valueAsDate=next}get valueAsUTCDate(){const parsed=parseTimeValue(this.value);return parsed?new Date(parsed.milliseconds):null}set valueAsUTCDate(next){this.value=timeValueFromMilliseconds(wrapTimeMilliseconds(isDateObject(next)?next.getTime():NaN))}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}padToStepPrecision(value){return value&&this.numericStep<60&&parseTimeValue(value)?.precision==="minute"?`${value}:00`:value}get committedValue(){return this.padToStepPrecision(this.genuineValue)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get segmentModel(){const locale=this.effectiveLocale,key=`${locale}|${this.hourFormat}|${this.includeSeconds}`;if(this.segmentModelCache?.key!==key){const pattern=localeTimePattern(locale,this.hourFormat,this.includeSeconds),order=pattern.filter(part=>part.type!=="literal").map(part=>part.type);this.segmentModelCache={key,pattern,order,twelveHour:order.includes("dayPeriod")}}return this.segmentModelCache}get pattern(){return this.segmentModel.pattern}get segmentOrder(){return this.segmentModel.order}get periodLabels(){const model=this.segmentModel;return model.labels??=dayPeriodLabels(this.effectiveLocale)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentModel.twelveHour}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"};const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){return this.numberFormatter(minimumIntegerDigits)(value)}numberFormatter(minimumIntegerDigits){try{const formatter=getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1});return value=>formatter.format(value)}catch{return value=>String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;const locale=this.effectiveLocale;if(this.inputDigitMap&&this.inputDigitLocale===locale)return this.inputDigitMap.get(key);const digits=new Map;try{const formatter=getNumberFormat(locale,{useGrouping:!1});for(let value=0;value<=9;value++){const integer=formatter.formatToParts(value).find(part=>part.type==="integer")?.value;integer!==void 0&&!digits.has(integer)&&digits.set(integer,String(value))}this.inputDigitLocale=locale,this.inputDigitMap=digits}catch{}return digits.get(key)}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=this.periodLabels;return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod")return this.draft.dayPeriod?this.periodLabels[this.draft.dayPeriod]:"--";const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,this.genuineValue=next,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=shadowFocusTarget(this);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&(this.liveDisabled||this.readonly)?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{const positioned=await waitForDeferredPlacement(()=>this.cleanupPositioner);return stale()||!this.open?!1:positioned?(this.popupPositioned=!0,!0):(this.forceClose(!1),!1)},conceal:()=>{this.popupHidden=!0}})}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const operation=this.cleanupPositioner;operation.ready.then(positioned=>{positioned&&this.cleanupPositioner===operation&&this.open&&this.isConnected&&(this.popupPositioned=!0)})}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment)}),this.popupController.bindPointer(),this.updateComplete.then(()=>{const option=this.renderRoot.querySelector('[part~="column-item-selected"]'),column=option?.closest('[part="column"]');if(!option||!column)return;const offset=option.getBoundingClientRect().top-column.getBoundingClientRect().top;column.scrollTop+=offset-(column.clientHeight-option.offsetHeight)/2}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){super.willUpdate(changed),this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focused=orderKey!==this.segmentOrderKey?shadowFocusTarget(this):null,focusedSegment=typeof focused?.getAttribute=="function"?focused.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey,changed.has("open")&&(this.popupPositioned=!1),this.open&&(this.popupHidden=!1)}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid);const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.popupHidden=!0,this.popupController.cancel(),this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour,wrapTimeMilliseconds}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{isDateObject}from"../../../internal/dom-guards.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get hasStartSlot(){return this.slotPresence.has("start")}get hasEndSlot(){return this.slotPresence.has("end")}get hasFooterSlot(){return this.slotPresence.has("footer")}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.clearable=!1,this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.popupHidden=!0,this.popupPositioned=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.genuineValue="",this.digitBuffer="",this.inputDigitLocale="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="popup"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocumentPointerDown(event)}),this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector('[part~="input"]'),()=>{const description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);return this.required&&description?[description]:[]}),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},new GlassScrollLayer(this,'[part="popup"]',()=>this.open),this.addEventListener("invalid",()=>{this.touched=!0})}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.forceClose(!1),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute";const committed=this.committedValue;committed!==this.value&&(super.value=committed),this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){this.genuineValue=normalizeTimeValue(next);const normalized=this.committedValue;this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}get valueAsLocalDate(){return this.valueAsDate}set valueAsLocalDate(next){this.valueAsDate=next}get valueAsUTCDate(){const parsed=parseTimeValue(this.value);return parsed?new Date(parsed.milliseconds):null}set valueAsUTCDate(next){this.value=timeValueFromMilliseconds(wrapTimeMilliseconds(isDateObject(next)?next.getTime():NaN))}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}padToStepPrecision(value){return value&&this.numericStep<60&&parseTimeValue(value)?.precision==="minute"?`${value}:00`:value}get committedValue(){return this.padToStepPrecision(this.genuineValue)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get segmentModel(){const locale=this.effectiveLocale,key=`${locale}|${this.hourFormat}|${this.includeSeconds}`;if(this.segmentModelCache?.key!==key){const pattern=localeTimePattern(locale,this.hourFormat,this.includeSeconds),order=pattern.filter(part=>part.type!=="literal").map(part=>part.type);this.segmentModelCache={key,pattern,order,twelveHour:order.includes("dayPeriod")}}return this.segmentModelCache}get pattern(){return this.segmentModel.pattern}get segmentOrder(){return this.segmentModel.order}get periodLabels(){const model=this.segmentModel;return model.labels??=dayPeriodLabels(this.effectiveLocale)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentModel.twelveHour}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"};const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){return this.numberFormatter(minimumIntegerDigits)(value)}numberFormatter(minimumIntegerDigits){try{const formatter=getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1});return value=>formatter.format(value)}catch{return value=>String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;const locale=this.effectiveLocale;if(this.inputDigitMap&&this.inputDigitLocale===locale)return this.inputDigitMap.get(key);const digits=new Map;try{const formatter=getNumberFormat(locale,{useGrouping:!1});for(let value=0;value<=9;value++){const integer=formatter.formatToParts(value).find(part=>part.type==="integer")?.value;integer!==void 0&&!digits.has(integer)&&digits.set(integer,String(value))}this.inputDigitLocale=locale,this.inputDigitMap=digits}catch{}return digits.get(key)}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=this.periodLabels;return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod")return this.draft.dayPeriod?this.periodLabels[this.draft.dayPeriod]:"--";const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,this.genuineValue=next,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=shadowFocusTarget(this);active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&(this.liveDisabled||this.readonly)?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{const positioned=await waitForDeferredPlacement(()=>this.cleanupPositioner);return stale()||!this.open?!1:positioned?(this.popupPositioned=!0,!0):(this.forceClose(!1),!1)},conceal:()=>{this.popupHidden=!0}})}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const operation=this.cleanupPositioner;operation.ready.then(positioned=>{positioned&&this.cleanupPositioner===operation&&this.open&&this.isConnected&&(this.popupPositioned=!0)})}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment)}),this.popupController.bindPointer(),this.updateComplete.then(()=>{const option=this.renderRoot.querySelector('[part~="column-item-selected"]'),column=option?.closest('[part="column"]');if(!option||!column)return;const offset=option.getBoundingClientRect().top-column.getBoundingClientRect().top;column.scrollTop+=offset-(column.clientHeight-option.offsetHeight)/2}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){super.willUpdate(changed),this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focused=orderKey!==this.segmentOrderKey?shadowFocusTarget(this):null,focusedSegment=typeof focused?.getAttribute=="function"?focused.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey,changed.has("open")&&(this.popupPositioned=!1),this.open&&(this.popupHidden=!1)}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid);const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.popupHidden=!0,this.popupController.cancel(),this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="segment"
|
|
4
4
|
role="spinbutton"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlace as place,awaitPopupAnimations,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();const MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1,this.clearSearch()),this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.closeSettleToken=0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeBuffer=new TypeAheadBuffer(this),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=shadowFocusTarget(this)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&shadowFocusTarget(this)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries,move=()=>resolveListMove(e,{count:rows.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;default:this.typeBuffer.accepts(e)&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.composedPath()[0]!==this.searchElement&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},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,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.closeSettleToken++,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.typeBuffer.clear(),this.activeScrollGeneration+=1,this.open=!1}adoptedCallback(){this.closeSettleToken++,this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.popupController.unbindPointer(),this.overlayHandle?.suspend(),this.typeBuffer.clear(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&shadowFocusTarget(this)===this.searchElement&&this.focus()),changed.has("open")&&this.open&&this.setActiveIndex(this.visibleEntries.findIndex(row=>row.tag===this._value)),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this.validityController?.reflectingDisabled||(disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales,cached=this.entriesCache;if(cached&&cached.raw===raw&&cached.tick===this.registryTick)return cached.rows;const rows=raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}));return this.entriesCache={raw,tick:this.registryTick,rows},rows}normalizeSearch(text,locale=this.effectiveLocale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries,query2=this.searchable?this.normalizeSearch(this.searchQuery):"";if(!query2)return rows;const cached=this.visibleCache;if(cached&&cached.rows===rows&&cached.query===this.searchQuery&&cached.locale===this.effectiveLocale)return cached.result;let names;try{names=getDisplayNames(this.effectiveLocale,{type:"language"})}catch{}let englishNames;try{englishNames=getDisplayNames("en",{type:"language"})}catch{}const invariantQuery=this.normalizeSearch(this.searchQuery,"en"),result=rows.filter(row=>{let localizedName="";try{localizedName=names?.of(row.tag)??""}catch{}let englishName="";try{englishName=englishNames?.of(row.tag)??""}catch{}return[row.label,localeNativeName(row.tag),localizedName].some(text=>this.normalizeSearch(text).includes(query2))||[row.tag,englishName].some(text=>this.normalizeSearch(text,"en").includes(invariantQuery))});return this.visibleCache={rows,query:this.searchQuery,locale:this.effectiveLocale,result},result}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=shadowFocusTarget(this);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||shadowFocusTarget(this)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}dismissFromEscape(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}this.deactivatePopupOverlay(!0),this.hide()}}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(!1);return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}async settleClosedLayout(){const token=++this.closeSettleToken;await awaitPopupAnimations(this,()=>this.renderRoot.querySelector('[part="listbox"]'),()=>this.closeSettleToken===token)&&(this.listboxHidden=!0)}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),changed.has("open")&&(this.open?this.closeSettleToken++:this.settleClosedLayout()),this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&shadowFocusTarget(this)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){if(tag===this._value&&tag===getLyraLocale()){this.hide();return}this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag);const committed=Object.freeze({...detail,direction:getLyraLocaleDirection(tag)});emitValueEvents(this,"input",committed,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",committed,detail2=>this.emit("lr-change",detail2)),searchFocus&&this.isConnected&&this.searchable&&shadowFocusTarget(this)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),match=this.typeBuffer.match(rows,currentIndex,row=>row.label,this.effectiveLocale);match!==null&&(this.open?this.setActiveIndex(match):this.commit(rows[match].tag))}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`),popup=this.renderRoot.querySelector('[part="listbox"]');row&&popup&&revealRow(popup,row,this.searchElement?.offsetHeight)})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlace as place,awaitPopupAnimations,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocale,getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1,this.clearSearch()),this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.closeSettleToken=0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeBuffer=new TypeAheadBuffer(this),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=shadowFocusTarget(this)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&shadowFocusTarget(this)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries,move=()=>resolveListMove(e,{count:rows.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(move()??-1),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1));break;default:this.typeBuffer.accepts(e)&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.composedPath()[0]!==this.searchElement&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},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,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.closeSettleToken++,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.typeBuffer.clear(),this.activeScrollGeneration+=1,this.open=!1}adoptedCallback(){this.closeSettleToken++,this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.popupController.unbindPointer(),this.overlayHandle?.suspend(),this.typeBuffer.clear(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&shadowFocusTarget(this)===this.searchElement&&this.focus()),changed.has("open")&&this.open&&this.setActiveIndex(this.visibleEntries.findIndex(row=>row.tag===this._value)),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this.validityController?.reflectingDisabled||(disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales,cached=this.entriesCache;if(cached&&cached.raw===raw&&cached.tick===this.registryTick)return cached.rows;const rows=raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}));return this.entriesCache={raw,tick:this.registryTick,rows},rows}normalizeSearch(text,locale=this.effectiveLocale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries,query2=this.searchable?this.normalizeSearch(this.searchQuery):"";if(!query2)return rows;const cached=this.visibleCache;if(cached&&cached.rows===rows&&cached.query===this.searchQuery&&cached.locale===this.effectiveLocale)return cached.result;let names;try{names=getDisplayNames(this.effectiveLocale,{type:"language"})}catch{}let englishNames;try{englishNames=getDisplayNames("en",{type:"language"})}catch{}const invariantQuery=this.normalizeSearch(this.searchQuery,"en"),result=rows.filter(row=>{let localizedName="";try{localizedName=names?.of(row.tag)??""}catch{}let englishName="";try{englishName=englishNames?.of(row.tag)??""}catch{}return[row.label,localeNativeName(row.tag),localizedName].some(text=>this.normalizeSearch(text).includes(query2))||[row.tag,englishName].some(text=>this.normalizeSearch(text,"en").includes(invariantQuery))});return this.visibleCache={rows,query:this.searchQuery,locale:this.effectiveLocale,result},result}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=shadowFocusTarget(this);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||shadowFocusTarget(this)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}dismissFromEscape(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}this.deactivatePopupOverlay(!0),this.hide()}}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.popupController.unbindPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(!1);return}this.activatePopupOverlay(),this.popupController.bindPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}async settleClosedLayout(){const token=++this.closeSettleToken;await awaitPopupAnimations(this,()=>this.renderRoot.querySelector('[part="listbox"]'),()=>this.closeSettleToken===token)&&(this.listboxHidden=!0)}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),changed.has("open")&&(this.open?this.closeSettleToken++:this.settleClosedLayout()),this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&shadowFocusTarget(this)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){if(tag===this._value&&tag===getLyraLocale()){this.hide();return}this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&shadowFocusTarget(this)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag);const committed=Object.freeze({...detail,direction:getLyraLocaleDirection(tag)});emitValueEvents(this,"input",committed,detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",committed,detail2=>this.emit("lr-change",detail2)),searchFocus&&this.isConnected&&this.searchable&&shadowFocusTarget(this)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),match=this.typeBuffer.match(rows,currentIndex,row=>row.label,this.effectiveLocale);match!==null&&(this.open?this.setActiveIndex(match):this.commit(rows[match].tag))}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`),popup=this.renderRoot.querySelector('[part="listbox"]');row&&popup&&revealRow(popup,row,this.searchElement?.offsetHeight)})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{setNativeRangeText}from"../../../internal/native-text-control.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.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{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{submitFormImplicitly,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{currentValidityValidator}from"../form-validator.js";import{declaredDefaultConverter,literalSetConverter}from"../../../internal/converters.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const APPEARANCE=literalSetConverter(["outlined","filled","filled-outlined","contained"],"outlined"),ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,scrollOverflowFadeStyles,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._appearance="outlined",this.autofocus=!1,this.autosubmit=!1,this.size="m",this.length=DEFAULT_LENGTH,this.format="",this.type="numeric",this.case="preserve",this.mask=!1,this.withMask=!1,this.readonly=!1,this.autocomplete="one-time-code",this.focused=!1,this.slotPresence=new SlotPresenceController(this),this.touched=!1,this.labelId=nextId("otp-input-label"),this.hintId=nextId("otp-input-hint"),this.errorId=nextId("otp-input-error"),this.activeSegmentIndex=0,this.segmentValues=[],this.rawValue="",this.segmentEditPendingChange=!1,this.autosubmitToken=0,this.hostDescription=new HostDescriptionController(this,()=>this.control??null),this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previousFilled=this.filledSegmentCount,layoutChanged=Array.from({length:this.renderedSegmentCount},(_,index)=>next[index]??"").some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next&&(this.control.value=next),next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=!0,this.value=next,relayNativeEvent(this,event),this.emit("lr-input",{value:next}),this.completeIfTransition(previousFilled)},this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1,delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){this.readonly||submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),this.setActiveSegment(selection.first);return}const changed=!!values2[this.activeSegmentIndex];values2[this.activeSegmentIndex]="",changed&&this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),event.key==="Backspace"&&this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues(),targetIndex=selection?.first??this.activeSegmentIndex;if(selection)for(const index of selection.indices)values[index]="";values[targetIndex]=accepted,this.commitSegmentEdit(values,"insertText",accepted),this.setActiveSegment(targetIndex+1)},this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");if(event.preventDefault(),!pasted)return;const values=Array.from({length:this.renderedSegmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted),this.setActiveSegment(Math.min(pasted.length,this.renderedSegmentCount-1))},this.onChange=event=>{this.segmentEditPendingChange=!1;const value=this.value;relayNativeEvent(this,event),this.emit("lr-change",{value})},this.onFocus=event=>{this.focused=!0,relayNativeEvent(this,event)},this.onBlur=event=>{this.focused=!1,this.effectiveDisabled||(this.touched=!0),this.flushPendingChange(),relayNativeEvent(this,event)},observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="segments"]'))}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();form&&submitFormImplicitly(form)}completeIfTransition(previousFilled){if(previousFilled>=this.renderedSegmentCount||this.filledSegmentCount!==this.renderedSegmentCount)return;const completionValue=this.value,token=this.autosubmitToken,completeEvent=this.emit("lr-complete",{value:completionValue},{cancelable:!0});this.autosubmit&&setTimeout(()=>{token!==this.autosubmitToken||completeEvent.defaultPrevented||!this.isConnected||!this.autosubmit||this.effectiveDisabled||this.readonly||this.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue,this.control&&(this.control.value=nextValue),this.touched=!0,dispatchNativeInputEvent(this,{data,inputType}),this.emit("lr-input",{value:nextValue}),this.segmentEditPendingChange=!0,this.completeIfTransition(previousFilled),this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart,end=this.control?.selectionEnd;if(start==null||end===void 0||end===null||start===end)return null;const indices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0).slice(start,end),first=indices[0];return first===void 0?null:{indices,first}}segmentIndexAtCompactOffset(offset){const values=this.normalizedSegmentValues();let occupied=0;for(let index=0;index<values.length;index+=1){if(occupied>=offset)return index;values[index]&&(occupied+=1)}return Math.max(0,values.length-1)}syncActiveSegmentFromSelection(){const control=this.control;if(!control||control.selectionStart===null)return;const selected=this.selectedSegmentRange;this.activeSegmentIndex=selected?.first??this.segmentIndexAtCompactOffset(control.selectionStart)}get selectionStart(){return this.control?.selectionStart??null}set selectionStart(value){this.control&&(this.control.selectionStart=value,this.syncActiveSegmentFromSelection())}get selectionEnd(){return this.control?.selectionEnd??null}set selectionEnd(value){this.control&&(this.control.selectionEnd=value,this.syncActiveSegmentFromSelection())}get selectionDirection(){return this.control?.selectionDirection??null}set selectionDirection(value){this.control&&(this.control.selectionDirection=value)}focus(options){this.effectiveDisabled||this.control?.focus(options)}blur(){this.control?.blur()}click(){this.effectiveDisabled||this.control?.click()}select(){this.control?.select()}setSelectionRange(start,end,direction){this.control&&(this.control.setSelectionRange(start,end,direction),this.syncActiveSegmentFromSelection())}setRangeText(replacement,start,end,selectMode){const control=this.control;if(!control)return;const selectionPrefixLength=(value,offset)=>{if(offset===null)return null;const boundedOffset=Math.min(MAX_VALUE_SOURCE_LENGTH,Math.max(0,offset));return this.sanitize(value.slice(0,boundedOffset)).length},currentRaw=control.value,currentSelectionStart=selectionPrefixLength(currentRaw,control.selectionStart),currentSelectionEnd=selectionPrefixLength(currentRaw,control.selectionEnd),currentSelectionDirection=control.selectionDirection,boundedCurrent=this.sanitize(currentRaw);currentRaw!==boundedCurrent&&(control.value=boundedCurrent,currentSelectionStart!==null&¤tSelectionEnd!==null&&control.setSelectionRange(currentSelectionStart,currentSelectionEnd,currentSelectionDirection??void 0));const boundedReplacement=this.sanitize(replacement);setNativeRangeText(control,boundedReplacement,start,end,selectMode);const raw=control.value,selectionStart=selectionPrefixLength(raw,control.selectionStart),selectionEnd=selectionPrefixLength(raw,control.selectionEnd),selectionDirection=control.selectionDirection,normalized=this.sanitize(raw);this.value=normalized,control.value=normalized,selectionStart!==null&&selectionEnd!==null&&control.setSelectionRange(selectionStart,selectionEnd,selectionDirection??void 0),this.syncActiveSegmentFromSelection()}clear(){!this.value||this.effectiveDisabled||this.readonly||(this.value="",this.control&&(this.control.value=""),dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),this.emit("lr-input",{value:""}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:""}),this.emit("lr-clear"))}formResetCallback(){this.autosubmitToken+=1,super.formResetCallback(),this.touched=!1,this.segmentEditPendingChange=!1}formStateRestoreCallback(state2,reason){this.autosubmitToken+=1,super.formStateRestoreCallback(state2,reason)}disconnectedCallback(){super.disconnectedCallback(),this.autosubmitToken+=1}reportValidity(){return this.touched=!0,super.reportValidity()}firstUpdated(changed){super.firstUpdated(changed),this.autofocus&&this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}updated(changed){super.updated(changed),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"blank",this.value.length===0),setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--filled",this.filledSegmentCount===this.renderedSegmentCount),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.renderedSegmentCount,filled=this.filledSegmentCount,complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:!0},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){if(!this.segmentEditPendingChange)return;this.segmentEditPendingChange=!1;const value=this.value;dispatchNativeEvent(this,"change"),this.emit("lr-change",{value})}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot||this.withLabel,hasHint=!!this.hint||this.hasHintSlot||this.withHint,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),labelledBy=hasLabel&&!this.getAttribute("aria-label")?this.labelId:nothing;let segmentIndex=-1;return html`
|
|
1
|
+
import{__decorate}from"tslib";import{setNativeRangeText}from"../../../internal/native-text-control.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.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{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{submitFormImplicitly,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{currentValidityValidator}from"../form-validator.js";import{declaredDefaultConverter,literalSetConverter}from"../../../internal/converters.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{scrollOverflowFadeStyles}from"../../../internal/scroll-overflow.styles.js";import{LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";const APPEARANCE=literalSetConverter(["outlined","filled","filled-outlined","contained"],"outlined"),ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,scrollOverflowFadeStyles,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._appearance="outlined",this.autofocus=!1,this.autosubmit=!1,this.size="m",this.length=DEFAULT_LENGTH,this.format="",this.type="numeric",this.case="preserve",this.mask=!1,this.withMask=!1,this.readonly=!1,this.autocomplete="one-time-code",this.focused=!1,this.slotPresence=new SlotPresenceController(this),this.touched=!1,this.labelId=nextId("otp-input-label"),this.hintId=nextId("otp-input-hint"),this.errorId=nextId("otp-input-error"),this.activeSegmentIndex=0,this.segmentValues=[],this.rawValue="",this.segmentEditPendingChange=!1,this.autosubmitToken=0,this.hostDescription=new HostDescriptionController(this,()=>this.control??null),this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previousFilled=this.filledSegmentCount,layoutChanged=Array.from({length:this.renderedSegmentCount},(_,index)=>next[index]??"").some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next&&(this.control.value=next),next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=!0,this.value=next,relayNativeEvent(this,event),this.emit("lr-input",{value:next}),this.completeIfTransition(previousFilled)},this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1,delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){this.readonly||submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),this.setActiveSegment(selection.first);return}const changed=!!values2[this.activeSegmentIndex];values2[this.activeSegmentIndex]="",changed&&this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),event.key==="Backspace"&&this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues(),targetIndex=selection?.first??this.activeSegmentIndex;if(selection)for(const index of selection.indices)values[index]="";values[targetIndex]=accepted,this.commitSegmentEdit(values,"insertText",accepted),this.setActiveSegment(targetIndex+1)},this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");if(event.preventDefault(),!pasted)return;const values=Array.from({length:this.renderedSegmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted),this.setActiveSegment(Math.min(pasted.length,this.renderedSegmentCount-1))},this.onChange=event=>{this.segmentEditPendingChange=!1;const value=this.value;relayNativeEvent(this,event),this.emit("lr-change",{value})},this.onFocus=event=>{this.focused=!0,relayNativeEvent(this,event)},this.onBlur=event=>{this.focused=!1,this.effectiveDisabled||(this.touched=!0),this.flushPendingChange(),relayNativeEvent(this,event)},observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="segments"]'))}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();form&&submitFormImplicitly(form)}completeIfTransition(previousFilled){if(previousFilled>=this.renderedSegmentCount||this.filledSegmentCount!==this.renderedSegmentCount)return;const completionValue=this.value,token=this.autosubmitToken,completeEvent=this.emit("lr-complete",{value:completionValue},{cancelable:!0});this.autosubmit&&setTimeout(()=>{token!==this.autosubmitToken||completeEvent.defaultPrevented||!this.isConnected||!this.autosubmit||this.effectiveDisabled||this.readonly||this.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue,this.control&&(this.control.value=nextValue),this.touched=!0,dispatchNativeInputEvent(this,{data,inputType}),this.emit("lr-input",{value:nextValue}),this.segmentEditPendingChange=!0,this.completeIfTransition(previousFilled),this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart,end=this.control?.selectionEnd;if(start==null||end===void 0||end===null||start===end)return null;const indices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0).slice(start,end),first=indices[0];return first===void 0?null:{indices,first}}segmentIndexAtCompactOffset(offset){const values=this.normalizedSegmentValues();let occupied=0;for(let index=0;index<values.length;index+=1){if(occupied>=offset)return index;values[index]&&(occupied+=1)}return Math.max(0,values.length-1)}syncActiveSegmentFromSelection(){const control=this.control;if(!control||control.selectionStart===null)return;const selected=this.selectedSegmentRange;this.activeSegmentIndex=selected?.first??this.segmentIndexAtCompactOffset(control.selectionStart)}get selectionStart(){return this.control?.selectionStart??null}set selectionStart(value){this.control&&(this.control.selectionStart=value,this.syncActiveSegmentFromSelection())}get selectionEnd(){return this.control?.selectionEnd??null}set selectionEnd(value){this.control&&(this.control.selectionEnd=value,this.syncActiveSegmentFromSelection())}get selectionDirection(){return this.control?.selectionDirection??null}set selectionDirection(value){this.control&&(this.control.selectionDirection=value)}focus(options){this.effectiveDisabled||this.control?.focus(options)}blur(){this.control?.blur()}click(){this.effectiveDisabled||this.control?.click()}select(){this.control?.select()}setSelectionRange(start,end,direction){this.control&&(this.control.setSelectionRange(start,end,direction),this.syncActiveSegmentFromSelection())}setRangeText(replacement,start,end,selectMode){const control=this.control;if(!control)return;const selectionPrefixLength=(value,offset)=>{if(offset===null)return null;const boundedOffset=Math.min(MAX_VALUE_SOURCE_LENGTH,Math.max(0,offset));return this.sanitize(value.slice(0,boundedOffset)).length},currentRaw=control.value,currentSelectionStart=selectionPrefixLength(currentRaw,control.selectionStart),currentSelectionEnd=selectionPrefixLength(currentRaw,control.selectionEnd),currentSelectionDirection=control.selectionDirection,boundedCurrent=this.sanitize(currentRaw);currentRaw!==boundedCurrent&&(control.value=boundedCurrent,currentSelectionStart!==null&¤tSelectionEnd!==null&&control.setSelectionRange(currentSelectionStart,currentSelectionEnd,currentSelectionDirection??void 0));const boundedReplacement=this.sanitize(replacement);setNativeRangeText(control,boundedReplacement,start,end,selectMode);const raw=control.value,selectionStart=selectionPrefixLength(raw,control.selectionStart),selectionEnd=selectionPrefixLength(raw,control.selectionEnd),selectionDirection=control.selectionDirection,normalized=this.sanitize(raw);this.value=normalized,control.value=normalized,selectionStart!==null&&selectionEnd!==null&&control.setSelectionRange(selectionStart,selectionEnd,selectionDirection??void 0),this.syncActiveSegmentFromSelection()}clear(){!this.value||this.effectiveDisabled||this.readonly||(this.value="",this.control&&(this.control.value=""),dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),this.emit("lr-input",{value:""}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:""}),this.emit("lr-clear"))}formResetCallback(){this.autosubmitToken+=1,super.formResetCallback(),this.touched=!1,this.segmentEditPendingChange=!1}formStateRestoreCallback(state2,reason){this.autosubmitToken+=1,super.formStateRestoreCallback(state2,reason)}disconnectedCallback(){super.disconnectedCallback(),this.autosubmitToken+=1}reportValidity(){return this.touched=!0,super.reportValidity()}firstUpdated(changed){super.firstUpdated(changed),this.autofocus&&this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}updated(changed){super.updated(changed),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"blank",this.value.length===0),setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--filled",this.filledSegmentCount===this.renderedSegmentCount),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.renderedSegmentCount,filled=this.filledSegmentCount,complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:!0},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){if(!this.segmentEditPendingChange)return;this.segmentEditPendingChange=!1;const value=this.value;dispatchNativeEvent(this,"change"),this.emit("lr-change",{value})}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot||this.withLabel,hasHint=!!this.hint||this.hasHintSlot||this.withHint,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),labelledBy=hasLabel&&!this.getAttribute("aria-label")?this.labelId:nothing;let segmentIndex=-1;return html`
|
|
2
2
|
<div part="base form-control">
|
|
3
3
|
<label part="label form-control-label" id=${this.labelId} for="control" ?hidden=${!hasLabel}>
|
|
4
4
|
${this.label}<slot name="label"></slot>
|