@aceshooting/lyra-ui 9.1.1 → 11.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +785 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +13 -0
- package/dist/cli/migrate-wa.mjs +216 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.styles.js +0 -16
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.styles.js +7 -5
- package/dist/components/agent-tools/agent-run/agent-run.class.js +2 -2
- package/dist/components/agent-tools/agent-run/agent-run.styles.js +0 -13
- package/dist/components/agent-tools/agent-trace/agent-trace.styles.js +7 -4
- package/dist/components/agent-tools/approval-queue/approval-queue.styles.js +7 -5
- package/dist/components/agent-tools/artifact-panel/artifact-panel.styles.js +0 -3
- package/dist/components/agent-tools/browser-frame/browser-frame.styles.js +3 -5
- package/dist/components/agent-tools/commit-card/commit-card.styles.js +0 -10
- package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +11 -6
- package/dist/components/agent-tools/confirm-bar/confirm-bar.styles.js +0 -46
- package/dist/components/agent-tools/eval-dataset/eval-dataset.styles.js +0 -7
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +2 -2
- package/dist/components/agent-tools/prompt-studio/prompt-studio.styles.js +0 -15
- package/dist/components/agent-tools/result-card/result-card.styles.js +0 -7
- package/dist/components/agent-tools/result-card/result-field.styles.js +0 -5
- package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +0 -3
- package/dist/components/agent-tools/span-waterfall/span-waterfall.styles.js +0 -15
- package/dist/components/agent-tools/stack-trace/stack-trace.styles.js +0 -20
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +0 -3
- package/dist/components/agent-tools/task-list/task-list.styles.js +0 -15
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +11 -6
- package/dist/components/agent-tools/terminal/terminal.class.js +4 -4
- package/dist/components/agent-tools/terminal/terminal.styles.js +0 -46
- package/dist/components/agent-tools/test-results/test-results.class.js +2 -2
- package/dist/components/agent-tools/test-results/test-results.styles.js +0 -5
- package/dist/components/agent-tools/thinking-panel/thinking-panel.styles.js +0 -41
- package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.styles.js +0 -41
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.styles.js +0 -30
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +6 -6
- package/dist/components/agent-tools/tool-param-form/tool-param-form.styles.js +0 -5
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.styles.js +0 -20
- package/dist/components/agent-tools/tool-result-view/tool-result-view.styles.js +0 -4
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.styles.js +0 -21
- package/dist/components/agent-tools/trace-tree/trace-tree.styles.js +7 -31
- package/dist/components/charts/chart/box-plot.class.d.ts +27 -0
- package/dist/components/charts/chart/box-plot.class.js +14 -4
- package/dist/components/charts/chart/box-plot.styles.js +28 -20
- package/dist/components/charts/chart/chart-colors.d.ts +1 -1
- package/dist/components/charts/chart/chart-colors.js +1 -1
- package/dist/components/charts/chart/chart-core-loader.d.ts +1 -0
- package/dist/components/charts/chart/chart-core-loader.js +1 -1
- package/dist/components/charts/chart/chart-feature-loader.d.ts +35 -0
- package/dist/components/charts/chart/chart-feature-loader.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +120 -0
- package/dist/components/charts/chart/chart.class.js +16 -6
- package/dist/components/charts/chart/chart.styles.js +28 -27
- package/dist/components/charts/chart/lite-chart.class.d.ts +20 -1
- package/dist/components/charts/chart/lite-chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart.styles.js +0 -27
- package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +20 -0
- package/dist/components/conversation/agent-workspace/agent-workspace.class.js +3 -1
- package/dist/components/conversation/agent-workspace/agent-workspace.styles.js +3 -0
- package/dist/components/conversation/audio-visualizer/audio-visualizer.styles.js +0 -7
- package/dist/components/conversation/branch-picker/branch-picker.styles.js +0 -3
- package/dist/components/conversation/chat-composer/chat-composer.styles.js +0 -51
- package/dist/components/conversation/chat-message/chat-message.styles.js +7 -35
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +0 -33
- package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
- package/dist/components/conversation/checkpoint/checkpoint.styles.js +0 -3
- package/dist/components/conversation/code-block/code-block-shared.d.ts +5 -2
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.styles.js +4 -95
- package/dist/components/conversation/code-block/code-loader.d.ts +11 -0
- package/dist/components/conversation/code-block/code-loader.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +12 -0
- package/dist/components/conversation/code-block/shiki-types.js +1 -1
- package/dist/components/conversation/conversation-item/conversation-item.styles.js +8 -54
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
- package/dist/components/conversation/generation-metrics/generation-metrics.styles.js +0 -17
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown.styles.js +0 -41
- package/dist/components/conversation/message-actions/message-actions.styles.js +0 -3
- package/dist/components/conversation/message-feedback/message-feedback.styles.js +0 -35
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +1 -1
- package/dist/components/conversation/message-parts/message-parts.styles.js +0 -5
- package/dist/components/conversation/model-select/model-select.class.js +3 -3
- package/dist/components/conversation/model-select/model-select.styles.js +12 -47
- package/dist/components/conversation/model-settings-panel/model-settings-panel.styles.js +0 -6
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +3 -0
- package/dist/components/conversation/prompt-input/prompt-input.styles.js +0 -10
- package/dist/components/conversation/push-to-talk/push-to-talk.styles.js +0 -8
- package/dist/components/conversation/selection-toolbar/selection-toolbar.styles.js +1 -11
- package/dist/components/conversation/stream-status/stream-status.styles.js +0 -16
- package/dist/components/conversation/streaming-text/streaming-text.styles.js +0 -15
- package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +0 -5
- package/dist/components/conversation/thread-list/thread-list.styles.js +0 -23
- package/dist/components/conversation/transcript-feed/transcript-feed.class.d.ts +16 -4
- package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
- package/dist/components/conversation/transcript-feed/transcript-feed.styles.js +0 -1
- package/dist/components/conversation/typing-indicator/typing-indicator.styles.js +0 -23
- package/dist/components/conversation/usage-badge/usage-badge.styles.js +0 -3
- package/dist/components/conversation/voice-picker/voice-picker.class.js +3 -3
- package/dist/components/conversation/voice-picker/voice-picker.styles.js +9 -29
- package/dist/components/conversation/widget-renderer/resolve.d.ts +2 -0
- package/dist/components/conversation/widget-renderer/resolve.js +1 -1
- package/dist/components/data/calendar/calendar.class.d.ts +15 -2
- package/dist/components/data/calendar/calendar.class.js +2 -2
- package/dist/components/data/calendar/calendar.styles.js +2 -28
- package/dist/components/data/condition-builder/condition-builder.class.d.ts +10 -6
- package/dist/components/data/condition-builder/condition-builder.class.js +2 -2
- package/dist/components/data/condition-builder/condition-builder.styles.js +0 -6
- package/dist/components/data/context-meter/context-meter.styles.js +0 -24
- package/dist/components/data/data-grid/data-grid.class.js +3 -3
- package/dist/components/data/data-grid/data-grid.styles.js +0 -22
- package/dist/components/data/document-library/document-library.class.js +2 -2
- package/dist/components/data/document-library/document-library.styles.js +0 -4
- package/dist/components/data/env-list/env-list.class.js +1 -1
- package/dist/components/data/env-list/env-list.styles.js +7 -4
- package/dist/components/data/file-tree/file-tree.class.d.ts +12 -0
- package/dist/components/data/flow-canvas/flow-canvas.styles.js +12 -19
- package/dist/components/data/flow-controls/flow-controls.class.js +2 -2
- package/dist/components/data/flow-controls/flow-controls.styles.js +3 -36
- package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.styles.js +0 -9
- package/dist/components/data/flow-node/flow-node.styles.js +0 -23
- package/dist/components/data/flow-run-status/flow-run-status.class.js +1 -1
- package/dist/components/data/flow-run-status/flow-run-status.styles.js +0 -7
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -7
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.styles.js +0 -10
- package/dist/components/data/heatmap/heatmap-scale.d.ts +20 -0
- package/dist/components/data/heatmap/heatmap-scale.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +117 -1
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/heatmap/heatmap.styles.js +0 -54
- package/dist/components/data/pagination/pagination.styles.js +23 -46
- package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +34 -1
- package/dist/components/data/sequence-strip/sequence-strip.class.js +5 -2
- package/dist/components/data/sequence-strip/sequence-strip.styles.js +14 -20
- package/dist/components/data/sparkline/sparkline.class.js +1 -1
- package/dist/components/data/stat/stat.styles.js +0 -67
- package/dist/components/data/table/table.class.d.ts +42 -3
- package/dist/components/data/table/table.class.js +4 -4
- package/dist/components/data/table/table.styles.js +20 -91
- package/dist/components/data/timeline/timeline-item.styles.js +0 -30
- package/dist/components/data/timeline/timeline.class.d.ts +89 -1
- package/dist/components/data/timeline/timeline.class.js +2 -2
- package/dist/components/data/timeline/timeline.styles.js +111 -31
- package/dist/components/data/tree/tree-item.styles.js +1 -28
- package/dist/components/data/tree/tree.class.js +2 -2
- package/dist/components/data/tree/tree.styles.js +0 -6
- package/dist/components/data/word-cloud/word-cloud.styles.js +0 -5
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/button/button.styles.js +0 -105
- package/dist/components/forms/checkbox/checkbox.class.d.ts +3 -0
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.styles.js +0 -39
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +21 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.styles.js +0 -18
- package/dist/components/forms/code-editor/code-editor.styles.js +0 -30
- package/dist/components/forms/color-picker/color-picker.class.js +2 -2
- package/dist/components/forms/color-picker/color-picker.styles.js +0 -69
- package/dist/components/forms/combobox/combobox.class.d.ts +71 -3
- package/dist/components/forms/combobox/combobox.class.js +5 -3
- package/dist/components/forms/combobox/combobox.styles.js +31 -111
- package/dist/components/forms/combobox/option.styles.js +7 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.styles.js +12 -67
- package/dist/components/forms/date-picker/date-picker.class.d.ts +47 -0
- package/dist/components/forms/date-picker/date-picker.class.js +36 -22
- package/dist/components/forms/date-picker/date-picker.styles.js +82 -29
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +6 -3
- package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +8 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.styles.js +3 -41
- package/dist/components/forms/icon-button/icon-button.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.styles.js +0 -16
- package/dist/components/forms/input/input.styles.js +0 -54
- package/dist/components/forms/input/number-input.styles.d.ts +4 -5
- package/dist/components/forms/input/number-input.styles.js +0 -11
- package/dist/components/forms/input/time-input-shared.d.ts +11 -0
- package/dist/components/forms/input/time-input-shared.js +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +11 -2
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/input/time-input.styles.js +0 -6
- package/dist/components/forms/locale-picker/locale-picker.class.js +2 -2
- package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -26
- package/dist/components/forms/otp-input/otp-input.class.js +3 -3
- package/dist/components/forms/otp-input/otp-input.styles.js +0 -16
- package/dist/components/forms/phone-input/phone-input.class.d.ts +9 -1
- package/dist/components/forms/phone-input/phone-input.class.js +2 -2
- package/dist/components/forms/phone-input/phone-input.styles.js +0 -37
- package/dist/components/forms/radio/radio-button.styles.js +1 -30
- package/dist/components/forms/radio/radio-group.styles.js +0 -4
- package/dist/components/forms/radio/radio.styles.js +0 -44
- package/dist/components/forms/rubric-form/rubric-form.styles.js +0 -5
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/select/select.styles.js +14 -114
- package/dist/components/forms/slider/slider.styles.js +0 -55
- package/dist/components/forms/swatch-picker/swatch-picker.class.d.ts +0 -11
- package/dist/components/forms/swatch-picker/swatch-picker.class.js +2 -2
- package/dist/components/forms/swatch-picker/swatch-picker.styles.js +0 -77
- package/dist/components/forms/switch/switch.class.d.ts +3 -0
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +0 -37
- package/dist/components/forms/textarea/textarea.styles.js +0 -28
- package/dist/components/forms/time-range/time-range.styles.js +12 -84
- package/dist/components/forms/token-input/token-input.class.d.ts +23 -9
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/forms/token-input/token-input.styles.js +1 -54
- package/dist/components/layout/app-rail/app-rail-item.class.js +2 -2
- package/dist/components/layout/app-rail/app-rail-item.styles.js +0 -13
- package/dist/components/layout/app-rail/app-rail.class.d.ts +5 -0
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.styles.js +0 -46
- package/dist/components/layout/button-group/button-group.styles.js +0 -6
- package/dist/components/layout/card/card.class.d.ts +12 -0
- package/dist/components/layout/card/card.styles.js +3 -11
- package/dist/components/layout/carousel/carousel.styles.js +0 -1
- package/dist/components/layout/command-palette/command-palette.class.d.ts +8 -0
- package/dist/components/layout/command-palette/command-palette.class.js +3 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -13
- package/dist/components/layout/control-group/control-group.styles.js +0 -7
- package/dist/components/layout/dashboard-grid/dashboard-grid.styles.js +6 -25
- package/dist/components/layout/details/accordion.class.d.ts +13 -0
- package/dist/components/layout/details/accordion.class.js +1 -1
- package/dist/components/layout/details/details.class.js +1 -1
- package/dist/components/layout/details/details.styles.js +0 -12
- package/dist/components/layout/dock-panel/dock-panel.styles.js +0 -45
- package/dist/components/layout/drilldown-panel/drilldown-panel.class.d.ts +2 -0
- package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +2 -2
- package/dist/components/layout/drilldown-panel/drilldown-panel.styles.js +0 -4
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.styles.js +0 -9
- package/dist/components/layout/menu/menu-item.class.d.ts +5 -0
- package/dist/components/layout/menu/menu-item.class.js +1 -1
- package/dist/components/layout/menu/menu-item.styles.js +0 -49
- package/dist/components/layout/menu/menu-label.styles.js +0 -2
- package/dist/components/layout/menu/menu.styles.js +0 -18
- package/dist/components/layout/multi-split/multi-split.styles.js +0 -63
- package/dist/components/layout/page/page.class.d.ts +4 -0
- package/dist/components/layout/page/page.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-item.styles.js +0 -4
- package/dist/components/layout/responsive-panel/responsive-panel.styles.js +0 -27
- package/dist/components/layout/scroller/scroller.styles.js +0 -20
- package/dist/components/layout/segmented/segmented.class.d.ts +7 -1
- package/dist/components/layout/segmented/segmented.class.js +1 -1
- package/dist/components/layout/segmented/segmented.styles.js +69 -37
- package/dist/components/layout/split-panel/split-panel.styles.js +1 -7
- package/dist/components/layout/stepper/stepper.class.d.ts +8 -1
- package/dist/components/layout/stepper/stepper.class.js +1 -1
- package/dist/components/layout/stepper/stepper.styles.js +140 -41
- package/dist/components/layout/tab-group/tab-group.class.d.ts +4 -1
- package/dist/components/layout/tab-group/tab-group.styles.js +9 -75
- package/dist/components/layout/tab-group/tab.styles.js +0 -2
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +4 -4
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.styles.js +0 -68
- package/dist/components/layout/widget/widget.class.d.ts +5 -1
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/layout/widget/widget.styles.js +97 -40
- package/dist/components/media/animated-image/animated-image.class.d.ts +3 -0
- package/dist/components/media/animated-image/animated-image.class.js +1 -1
- package/dist/components/media/animated-image/animated-image.styles.js +0 -28
- package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
- package/dist/components/media/attachment-chip/attachment-chip.styles.js +0 -31
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +0 -40
- package/dist/components/media/av-player/av-player.class.d.ts +5 -6
- package/dist/components/media/av-player/av-player.class.js +1 -1
- package/dist/components/media/av-player/av-player.styles.js +0 -45
- package/dist/components/media/avatar/avatar.styles.js +3 -16
- package/dist/components/media/file-icon/file-icon.class.d.ts +1 -2
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +12 -0
- package/dist/components/media/file-input/file-input.styles.js +3 -24
- package/dist/components/media/flag/flag.class.d.ts +23 -1
- package/dist/components/media/flag/flag.class.js +4 -2
- package/dist/components/media/flag/flag.styles.js +7 -1
- package/dist/components/media/flag/language-map.d.ts +10 -0
- package/dist/components/media/flag/language-map.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.styles.js +4 -33
- package/dist/components/media/image-viewer/image-viewer.class.js +0 -2
- package/dist/components/media/image-viewer/image-viewer.styles.js +7 -27
- package/dist/components/media/lightbox/lightbox.class.js +0 -2
- package/dist/components/media/lightbox/lightbox.styles.js +0 -21
- package/dist/components/media/map/map-loader.d.ts +19 -1
- package/dist/components/media/map/map-loader.js +1 -1
- package/dist/components/media/map/map.class.d.ts +178 -1
- package/dist/components/media/map/map.class.js +15 -3
- package/dist/components/media/map/map.styles.js +20 -17
- package/dist/components/media/media-card/media-card.class.d.ts +14 -3
- package/dist/components/media/media-card/media-card.class.js +1 -1
- package/dist/components/media/media-card/media-card.styles.js +2 -28
- package/dist/components/media/pan-zoom/pan-zoom.styles.js +0 -3
- package/dist/components/media/qr-code/qr-code.class.d.ts +3 -2
- package/dist/components/media/qr-code/qr-code.class.js +2 -2
- package/dist/components/media/qr-code/qr-code.styles.js +0 -3
- package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +2 -0
- package/dist/components/media/sequence-playback/sequence-playback.class.js +2 -1
- package/dist/components/media/sequence-playback/sequence-playback.styles.js +0 -19
- package/dist/components/media/video/video.class.d.ts +23 -2
- package/dist/components/media/video/video.class.js +3 -3
- package/dist/components/media/video/video.styles.js +4 -2
- package/dist/components/media/zoomable-frame/zoomable-frame.class.d.ts +3 -2
- package/dist/components/media/zoomable-frame/zoomable-frame.class.js +2 -2
- package/dist/components/media/zoomable-frame/zoomable-frame.styles.js +0 -5
- package/dist/components/overlays/alert/alert.styles.js +4 -2
- package/dist/components/overlays/badge/badge.styles.js +4 -48
- package/dist/components/overlays/badge/tag.styles.js +0 -14
- package/dist/components/overlays/callout/callout.styles.js +0 -11
- package/dist/components/overlays/chip/chip-group.styles.js +0 -18
- package/dist/components/overlays/chip/chip.styles.js +6 -69
- package/dist/components/overlays/dialog/confirm.d.ts +1 -4
- package/dist/components/overlays/dialog/confirm.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +32 -9
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.styles.js +0 -43
- package/dist/components/overlays/drawer/drawer.class.d.ts +2 -2
- package/dist/components/overlays/drawer/drawer.styles.js +0 -9
- package/dist/components/overlays/empty/empty.styles.js +0 -12
- package/dist/components/overlays/kbd/kbd.styles.js +0 -8
- package/dist/components/overlays/overlay/dropdown.class.d.ts +1 -6
- package/dist/components/overlays/overlay/dropdown.class.js +2 -2
- package/dist/components/overlays/overlay/overlay.styles.js +0 -28
- package/dist/components/overlays/overlay/popover.class.d.ts +28 -4
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/overlays/overlay/tooltip.class.d.ts +10 -0
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/popup/popup.class.d.ts +1 -0
- package/dist/components/overlays/popup/popup.class.js +1 -1
- package/dist/components/overlays/popup/popup.styles.js +0 -15
- package/dist/components/overlays/progress/progress-ring.class.d.ts +9 -1
- package/dist/components/overlays/progress/progress-ring.class.js +3 -3
- package/dist/components/overlays/progress/progress.styles.js +0 -21
- package/dist/components/overlays/rating/rating.styles.js +0 -25
- package/dist/components/overlays/skeleton/skeleton.styles.js +0 -4
- package/dist/components/overlays/spinner/spinner.styles.js +0 -3
- package/dist/components/overlays/toast/toast-item.styles.js +3 -45
- package/dist/components/retrieval/chunk-inspector/chunk-inspector.styles.js +0 -35
- package/dist/components/retrieval/citation-badge/citation-badge.class.d.ts +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +3 -3
- package/dist/components/retrieval/citation-badge/citation-badge.styles.js +0 -20
- package/dist/components/retrieval/claim-evidence/claim-evidence.styles.js +0 -8
- package/dist/components/retrieval/community-card/community-card.class.d.ts +1 -0
- package/dist/components/retrieval/community-card/community-card.styles.js +0 -6
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.styles.js +8 -12
- package/dist/components/retrieval/entity-card/entity-card.class.d.ts +4 -3
- package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
- package/dist/components/retrieval/entity-card/entity-card.styles.js +0 -12
- package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +10 -4
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +3 -3
- package/dist/components/retrieval/entity-chip/entity-chip.styles.js +6 -9
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.d.ts +19 -5
- package/dist/components/retrieval/graph/graph.class.d.ts +5 -0
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph/graph.styles.js +0 -30
- package/dist/components/retrieval/graph-legend/graph-legend.styles.js +0 -3
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +0 -25
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.d.ts +2 -0
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.styles.js +0 -7
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +20 -6
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +0 -16
- package/dist/components/retrieval/mind-map/mind-map.class.d.ts +5 -3
- package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.styles.js +0 -2
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +3 -2
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.styles.js +0 -30
- package/dist/components/retrieval/node-palette/node-palette.styles.js +0 -11
- package/dist/components/retrieval/path-strip/path-strip.styles.js +0 -10
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.d.ts +12 -3
- package/dist/components/retrieval/provenance-panel/provenance-panel.styles.js +0 -2
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +3 -2
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +2 -2
- package/dist/components/retrieval/retrieval-results/retrieval-results.styles.js +0 -28
- package/dist/components/retrieval/retrieval-search/retrieval-search.styles.js +0 -4
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.styles.js +0 -2
- package/dist/components/retrieval/source-card/source-card.styles.js +0 -13
- package/dist/components/retrieval/source-list/source-list.styles.js +0 -7
- package/dist/components/retrieval/source-picker/source-picker.styles.js +0 -7
- package/dist/components/utility/copy-button/copy-button.styles.js +0 -10
- package/dist/components/utility/diff-view/diff-view.styles.js +0 -14
- package/dist/components/utility/export-button/export-button.styles.js +0 -22
- package/dist/components/utility/icon/icon.styles.js +0 -6
- package/dist/components/utility/json-viewer/json-viewer.styles.js +2 -48
- package/dist/components/utility/known-date/known-date.class.d.ts +7 -3
- package/dist/components/utility/known-date/known-date.styles.js +10 -51
- package/dist/components/utility/live-region/live-region.styles.js +0 -4
- package/dist/components/utility/mention-popover/mention-popover.styles.js +0 -25
- package/dist/components/utility/poll-status/poll-status.styles.js +0 -4
- package/dist/components/utility/random-content/random-content.class.d.ts +22 -0
- package/dist/components/utility/random-content/random-content.class.js +3 -2
- package/dist/components/utility/random-content/random-content.styles.js +6 -13
- package/dist/components/utility/tour/tour.class.d.ts +4 -2
- package/dist/components/utility/tour/tour.class.js +3 -3
- package/dist/components/utility/tour/tour.styles.js +0 -13
- package/dist/components/utility/visually-hidden/visually-hidden.styles.js +0 -5
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.styles.d.ts +2 -2
- package/dist/components/viewers/archive-viewer/archive-viewer.styles.js +0 -10
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.styles.js +0 -19
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.styles.js +0 -15
- package/dist/components/viewers/document-compare/document-compare.styles.js +0 -3
- package/dist/components/viewers/document-preview/document-preview.styles.js +0 -25
- package/dist/components/viewers/document-viewer/document-viewer.class.d.ts +2 -1
- package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
- package/dist/components/viewers/document-viewer/document-viewer.styles.js +0 -5
- package/dist/components/viewers/docx-viewer/docx-viewer.styles.js +0 -17
- package/dist/components/viewers/ebook-viewer/ebook-viewer.styles.js +0 -4
- package/dist/components/viewers/email-viewer/email-viewer.styles.js +0 -7
- package/dist/components/viewers/geojson-view/geojson-view.styles.js +0 -5
- package/dist/components/viewers/highlight-layer/highlight-layer.styles.js +0 -3
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.styles.js +0 -38
- package/dist/components/viewers/page-rail/page-rail.class.js +1 -1
- package/dist/components/viewers/page-rail/page-rail.styles.js +0 -13
- package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +13 -2
- package/dist/components/viewers/pdf-viewer/pdf-loader.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +32 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +4 -4
- package/dist/components/viewers/pdf-viewer/pdf-viewer.styles.js +1 -27
- package/dist/components/viewers/pptx-viewer/pptx-viewer.styles.js +0 -3
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.styles.js +0 -14
- package/dist/components/viewers/svg-viewer/svg-viewer.styles.js +0 -7
- package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +2 -24
- package/dist/custom-elements-jsx.d.ts +72 -40
- package/dist/events.d.ts +43 -33
- package/dist/internal/agent-status-variants.d.ts +18 -0
- package/dist/internal/agent-status-variants.js +1 -0
- package/dist/internal/announcer.d.ts +8 -3
- package/dist/internal/announcer.js +1 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/canvas-color.d.ts +16 -0
- package/dist/internal/canvas-color.js +1 -1
- package/dist/internal/catalog-picker.d.ts +0 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/default-strings.generated.d.ts +1 -0
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +27 -4
- package/dist/internal/dev-mode-attribute-warning.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +13 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/media-controller.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/scroll-overflow.d.ts +35 -13
- package/dist/internal/scroll-overflow.js +1 -1
- package/dist/internal/sizes.styles.js +0 -2
- package/dist/internal/specialist-tokens.styles.js +6 -11
- package/dist/internal/text-highlights.d.ts +4 -1
- package/dist/internal/text-highlights.js +1 -1
- package/dist/internal/tokens/palette.styles.js +0 -15
- package/dist/internal/tokens.styles.js +20 -113
- package/dist/lyra.d.ts +9 -6
- package/dist/styles/reservations.css +82 -0
- package/dist/svelte.d.ts +72 -40
- package/dist/translations/ar.js +1 -1
- package/dist/translations/de.js +1 -1
- package/dist/translations/es.js +1 -1
- package/dist/translations/fa.js +1 -1
- package/dist/translations/fr.js +1 -1
- package/dist/translations/he.js +1 -1
- package/dist/translations/ja.js +1 -1
- package/dist/translations/pt-BR.js +1 -1
- package/dist/translations/ru.js +1 -1
- package/dist/translations/zh-CN.js +1 -1
- package/dist/vue.d.ts +72 -40
- package/llms/components/lr-accordion-item.md +12 -3
- package/llms/components/lr-accordion.md +11 -2
- package/llms/components/lr-agent-eval-dashboard.md +1 -1
- package/llms/components/lr-agent-trace.md +3 -1
- package/llms/components/lr-agent-workspace.md +20 -0
- package/llms/components/lr-artifact-panel.md +10 -4
- package/llms/components/lr-attachment-chip.md +7 -4
- package/llms/components/lr-attachment-trigger.md +7 -4
- package/llms/components/lr-av-player.md +3 -1
- package/llms/components/lr-avatar.md +6 -6
- package/llms/components/lr-bar-chart.md +8 -6
- package/llms/components/lr-box-plot.md +15 -4
- package/llms/components/lr-browser-frame.md +7 -3
- package/llms/components/lr-bubble-chart.md +8 -6
- package/llms/components/lr-calendar.md +9 -2
- package/llms/components/lr-card.md +24 -0
- package/llms/components/lr-chart.md +45 -11
- package/llms/components/lr-chat-viewport.md +7 -2
- package/llms/components/lr-checkbox-group.md +13 -5
- package/llms/components/lr-checkbox.md +5 -2
- package/llms/components/lr-checkpoint.md +6 -2
- package/llms/components/lr-combobox.md +47 -8
- package/llms/components/lr-command-palette.md +4 -1
- package/llms/components/lr-confirm-bar.md +7 -3
- package/llms/components/lr-context-meter.md +12 -11
- package/llms/components/lr-conversation-item.md +7 -4
- package/llms/components/lr-date-input.md +22 -2
- package/llms/components/lr-date-picker.md +23 -3
- package/llms/components/lr-details.md +11 -2
- package/llms/components/lr-dialog.md +16 -10
- package/llms/components/lr-dock-panel.md +7 -10
- package/llms/components/lr-document-preview.md +6 -1
- package/llms/components/lr-document-viewer.md +3 -2
- package/llms/components/lr-doughnut-chart.md +8 -6
- package/llms/components/lr-drawer.md +3 -3
- package/llms/components/lr-entity-card.md +3 -3
- package/llms/components/lr-entity-chip.md +1 -1
- package/llms/components/lr-entity-dossier.md +4 -1
- package/llms/components/lr-file-input.md +2 -2
- package/llms/components/lr-flag.md +30 -8
- package/llms/components/lr-heatmap.md +46 -0
- package/llms/components/lr-histogram.md +7 -4
- package/llms/components/lr-icon.md +1 -1
- package/llms/components/lr-json-schema-viewer.md +2 -1
- package/llms/components/lr-knowledge-graph-explorer.md +8 -3
- package/llms/components/lr-known-date.md +4 -2
- package/llms/components/lr-line-chart.md +8 -6
- package/llms/components/lr-lite-chart.md +16 -6
- package/llms/components/lr-map.md +91 -10
- package/llms/components/lr-markdown-core.md +3 -2
- package/llms/components/lr-media-card.md +28 -12
- package/llms/components/lr-message-parts.md +2 -1
- package/llms/components/lr-model-select.md +9 -10
- package/llms/components/lr-model-settings-panel.md +9 -9
- package/llms/components/lr-neighbor-list.md +1 -1
- package/llms/components/lr-notebook-viewer.md +6 -3
- package/llms/components/lr-option.md +46 -7
- package/llms/components/lr-pdf-viewer.md +62 -2
- package/llms/components/lr-pie-chart.md +8 -6
- package/llms/components/lr-polar-area-chart.md +8 -6
- package/llms/components/lr-popover.md +25 -1
- package/llms/components/lr-progress-ring.md +8 -1
- package/llms/components/lr-prompt-studio.md +1 -1
- package/llms/components/lr-provenance-panel.md +4 -2
- package/llms/components/lr-qr-code.md +1 -1
- package/llms/components/lr-radar-chart.md +8 -6
- package/llms/components/lr-rag-eval-dashboard.md +2 -2
- package/llms/components/lr-random-content.md +13 -0
- package/llms/components/lr-reorder-item.md +6 -1
- package/llms/components/lr-reorder-list.md +6 -1
- package/llms/components/lr-responsive-panel.md +11 -7
- package/llms/components/lr-scatter-chart.md +8 -6
- package/llms/components/lr-sequence-strip.md +16 -2
- package/llms/components/lr-slider.md +12 -5
- package/llms/components/lr-sparkline.md +1 -1
- package/llms/components/lr-suggestion-chips.md +7 -2
- package/llms/components/lr-swatch-picker.md +5 -5
- package/llms/components/lr-switch.md +5 -2
- package/llms/components/lr-table.md +30 -4
- package/llms/components/lr-terminal.md +3 -1
- package/llms/components/lr-thread-list.md +8 -8
- package/llms/components/lr-time-input.md +6 -1
- package/llms/components/lr-timeline-item.md +24 -0
- package/llms/components/lr-timeline.md +25 -1
- package/llms/components/lr-token-input.md +7 -2
- package/llms/components/lr-tool-approval-dialog.md +7 -8
- package/llms/components/lr-tool-call-chip.md +5 -1
- package/llms/components/lr-tool-param-form.md +14 -12
- package/llms/components/lr-tool-result-dialog.md +11 -9
- package/llms/components/lr-tool-result-view.md +7 -6
- package/llms/components/lr-tool-select-dialog.md +18 -16
- package/llms/components/lr-trace-tree.md +3 -1
- package/llms/components/lr-usage-badge.md +4 -1
- package/llms/components/lr-video-playlist.md +1 -1
- package/llms/components/lr-virtual-list.md +22 -14
- package/llms/components/lr-voice-picker.md +8 -5
- package/llms/components/lr-widget-renderer.md +3 -3
- package/llms/components/lr-widget.md +1 -1
- package/llms/components/lr-word-cloud.md +6 -2
- package/llms/peers.md +12 -2
- package/llms/shared.md +70 -2
- package/llms/tokens.md +15 -1
- package/llms-full.txt +1335 -306
- package/package.json +17 -5
- package/vscode-css-data.json +93 -2
- package/vscode-html-data.json +513 -59
- package/web-types.json +457 -72
|
@@ -6,8 +6,6 @@ import{css}from"lit";const styles=css`
|
|
|
6
6
|
align-items: center;
|
|
7
7
|
justify-content: center;
|
|
8
8
|
border: none;
|
|
9
|
-
/* Invisible while the background is none; it exists so the pressed fill below (and the focus
|
|
10
|
-
ring, which follows the same corner) is a rounded chip rather than a hard rectangle. */
|
|
11
9
|
border-radius: var(--lr-radius);
|
|
12
10
|
background: none;
|
|
13
11
|
cursor: pointer;
|
|
@@ -22,10 +20,6 @@ import{css}from"lit";const styles=css`
|
|
|
22
20
|
[part~='stepper-up']:not(:disabled):hover {
|
|
23
21
|
color: var(--lr-input-action-hover-color, var(--lr-color-text));
|
|
24
22
|
}
|
|
25
|
-
/* Pressed. A stepper is the one control here a user holds down and repeats, so the press state
|
|
26
|
-
doing more than the hover is not decoration: it is the only confirmation that the auto-repeat
|
|
27
|
-
is running. Same quiet-to-full text step as the hover, plus a fill mixing the page surface
|
|
28
|
-
toward --lr-color-mix-partner at the stronger active share. */
|
|
29
23
|
[part~='stepper-down']:not(:disabled):active,
|
|
30
24
|
[part~='stepper-up']:not(:disabled):active {
|
|
31
25
|
color: var(--lr-input-action-active-color, var(--lr-input-action-hover-color, var(--lr-color-text)));
|
|
@@ -43,11 +37,6 @@ import{css}from"lit";const styles=css`
|
|
|
43
37
|
[part~='stepper-up']:disabled {
|
|
44
38
|
cursor: not-allowed;
|
|
45
39
|
}
|
|
46
|
-
/* The shared chevron glyph points inline-end, so each stepper rotates it onto the block axis.
|
|
47
|
-
The rotation is applied to the svg rather than the button because the button owns the focus
|
|
48
|
-
ring and the hit area, and neither should turn with the glyph. Rotating the wrapping part --
|
|
49
|
-
internal/icons.ts's usual advice -- exists for RTL *mirroring*; both rotations here are
|
|
50
|
-
block-axis, so nothing flips under RTL either way. */
|
|
51
40
|
[part~='stepper-up'] slot > svg {
|
|
52
41
|
transform: rotate(-90deg);
|
|
53
42
|
}
|
|
@@ -19,6 +19,17 @@ export type TimePatternPart = {
|
|
|
19
19
|
export declare function parseTimeValue(value: string): ParsedTimeValue | undefined;
|
|
20
20
|
/** Normalizes a public string/Date value without applying timezone or elapsed-time arithmetic. */
|
|
21
21
|
export declare function normalizeTimeValue(value: string | Date | null | undefined): string;
|
|
22
|
+
/**
|
|
23
|
+
* Formats milliseconds since local midnight as the canonical wire value, the inverse of
|
|
24
|
+
* `parseTimeValue(...).milliseconds`.
|
|
25
|
+
*
|
|
26
|
+
* Arithmetic rather than a round-trip through a `Date`: building a local `Date` at midnight and
|
|
27
|
+
* adding an offset lands on the wrong clock time on the days a zone shifts, which is exactly the
|
|
28
|
+
* kind of once-a-year bug nobody reproduces. Anything outside a single day -- negative, a full day
|
|
29
|
+
* or more, or non-finite -- yields `''`, matching how a native time input rejects an out-of-range
|
|
30
|
+
* `valueAsNumber` rather than silently wrapping it into a different time.
|
|
31
|
+
*/
|
|
32
|
+
export declare function timeValueFromMilliseconds(value: number): string;
|
|
22
33
|
export declare function to24Hour(hour: number, dayPeriod: 'am' | 'pm'): number;
|
|
23
34
|
/** Implements HTML time's ordinary range and its useful reversed-bound overnight range. */
|
|
24
35
|
export declare function isTimeInRange(value: string, min: string, max: string): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{isDateObject}from"../../../internal/dom-guards.js";const DAY_MILLISECONDS=1440*60*1e3,TIME_VALUE_PATTERN=/^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/,pad=(value,length=2)=>String(value).padStart(length,"0");function parseTimeValue(value){const match=TIME_VALUE_PATTERN.exec(value);if(!match)return;const hour=Number(match[1]),minute=Number(match[2]),second=match[3]===void 0?0:Number(match[3]),millisecond=match[4]===void 0?0:Number(match[4].padEnd(3,"0"));if(!(hour>23||minute>59||second>59))return{hour,minute,second,millisecond,precision:match[4]===void 0?match[3]===void 0?"minute":"second":"millisecond",milliseconds:((hour*60+minute)*60+second)*1e3+millisecond}}function normalizeTimeValue(value){if(value==null)return"";if(isDateObject(value)){if(!Number.isFinite(value.getTime()))return"";const base2=`${pad(value.getHours())}:${pad(value.getMinutes())}`;return value.getMilliseconds()!==0?`${base2}:${pad(value.getSeconds())}.${pad(value.getMilliseconds(),3)}`:value.getSeconds()===0?base2:`${base2}:${pad(value.getSeconds())}`}const parsed=parseTimeValue(value);if(!parsed)return"";const base=`${pad(parsed.hour)}:${pad(parsed.minute)}`;if(parsed.precision==="minute")return base;const seconds=`${base}:${pad(parsed.second)}`;return parsed.precision==="second"?seconds:`${seconds}.${pad(parsed.millisecond,3)}`}function to24Hour(hour,dayPeriod){const normalizedHour=hour%12;return dayPeriod==="pm"?normalizedHour+12:normalizedHour}function isTimeInRange(value,min,max){const parsedValue=parseTimeValue(value);if(!parsedValue)return!1;const parsedMin=min===""?void 0:parseTimeValue(min),parsedMax=max===""?void 0:parseTimeValue(max);return parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?parsedValue.milliseconds>=parsedMin.milliseconds||parsedValue.milliseconds<=parsedMax.milliseconds:!(parsedMin&&parsedValue.milliseconds<parsedMin.milliseconds||parsedMax&&parsedValue.milliseconds>parsedMax.milliseconds)}function timeStepBaseMilliseconds(min,defaultValue=""){return parseTimeValue(min)?.milliseconds??parseTimeValue(defaultValue)?.milliseconds??0}function hasTimeStepMismatch(value,step,min,defaultValue=""){if(step==="any")return!1;const parsedValue=parseTimeValue(value);if(!parsedValue)return!1;const numericStep=Number(step),stepMilliseconds=(Number.isFinite(numericStep)&&numericStep>0?numericStep:60)*1e3,stepBase=timeStepBaseMilliseconds(min,defaultValue),remainder=((parsedValue.milliseconds-stepBase)%stepMilliseconds+stepMilliseconds)%stepMilliseconds;return remainder>1e-6&&stepMilliseconds-remainder>1e-6}function localeHour12(locale,hourFormat){if(hourFormat!=="auto")return hourFormat==="12";try{return getDateTimeFormat(locale,{hour:"numeric"}).resolvedOptions().hour12??!1}catch{return!1}}function localeTimePattern(locale,hourFormat,includeSeconds){const hour12=localeHour12(locale,hourFormat);try{return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit",...includeSeconds?{second:"2-digit"}:{},hour12,timeZone:"UTC"}).formatToParts(new Date(Date.UTC(2020,0,1,13,5,9))).flatMap(part=>part.type==="hour"||part.type==="minute"||part.type==="second"||part.type==="dayPeriod"?[{type:part.type,value:part.value}]:part.type==="literal"?[{type:"literal",value:part.value}]:[])}catch{return[{type:"hour",value:hour12?"1":"13"},{type:"literal",value:":"},{type:"minute",value:"05"},...includeSeconds?[{type:"literal",value:":"},{type:"second",value:"09"}]:[],...hour12?[{type:"literal",value:" "},{type:"dayPeriod",value:"PM"}]:[]]}}function dayPeriodLabels(locale){const labelAt=hour=>{try{return getDateTimeFormat(locale,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(new Date(Date.UTC(2020,0,1,hour))).find(part=>part.type==="dayPeriod")?.value}catch{return}};return{am:labelAt(1)??"AM",pm:labelAt(13)??"PM"}}function wrapTimeMilliseconds(value){return(value%DAY_MILLISECONDS+DAY_MILLISECONDS)%DAY_MILLISECONDS}export{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeStepBaseMilliseconds,to24Hour,wrapTimeMilliseconds};
|
|
1
|
+
import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{isDateObject}from"../../../internal/dom-guards.js";const DAY_MILLISECONDS=1440*60*1e3,TIME_VALUE_PATTERN=/^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/,pad=(value,length=2)=>String(value).padStart(length,"0");function parseTimeValue(value){const match=TIME_VALUE_PATTERN.exec(value);if(!match)return;const hour=Number(match[1]),minute=Number(match[2]),second=match[3]===void 0?0:Number(match[3]),millisecond=match[4]===void 0?0:Number(match[4].padEnd(3,"0"));if(!(hour>23||minute>59||second>59))return{hour,minute,second,millisecond,precision:match[4]===void 0?match[3]===void 0?"minute":"second":"millisecond",milliseconds:((hour*60+minute)*60+second)*1e3+millisecond}}function normalizeTimeValue(value){if(value==null)return"";if(isDateObject(value)){if(!Number.isFinite(value.getTime()))return"";const base2=`${pad(value.getHours())}:${pad(value.getMinutes())}`;return value.getMilliseconds()!==0?`${base2}:${pad(value.getSeconds())}.${pad(value.getMilliseconds(),3)}`:value.getSeconds()===0?base2:`${base2}:${pad(value.getSeconds())}`}const parsed=parseTimeValue(value);if(!parsed)return"";const base=`${pad(parsed.hour)}:${pad(parsed.minute)}`;if(parsed.precision==="minute")return base;const seconds=`${base}:${pad(parsed.second)}`;return parsed.precision==="second"?seconds:`${seconds}.${pad(parsed.millisecond,3)}`}function timeValueFromMilliseconds(value){if(!Number.isFinite(value)||value<0||value>=DAY_MILLISECONDS)return"";const total=Math.trunc(value),hour=Math.floor(total/36e5),minute=Math.floor(total/6e4)%60,second=Math.floor(total/1e3)%60,millisecond=total%1e3,base=`${pad(hour)}:${pad(minute)}`;return millisecond!==0?`${base}:${pad(second)}.${pad(millisecond,3)}`:second===0?base:`${base}:${pad(second)}`}function to24Hour(hour,dayPeriod){const normalizedHour=hour%12;return dayPeriod==="pm"?normalizedHour+12:normalizedHour}function isTimeInRange(value,min,max){const parsedValue=parseTimeValue(value);if(!parsedValue)return!1;const parsedMin=min===""?void 0:parseTimeValue(min),parsedMax=max===""?void 0:parseTimeValue(max);return parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?parsedValue.milliseconds>=parsedMin.milliseconds||parsedValue.milliseconds<=parsedMax.milliseconds:!(parsedMin&&parsedValue.milliseconds<parsedMin.milliseconds||parsedMax&&parsedValue.milliseconds>parsedMax.milliseconds)}function timeStepBaseMilliseconds(min,defaultValue=""){return parseTimeValue(min)?.milliseconds??parseTimeValue(defaultValue)?.milliseconds??0}function hasTimeStepMismatch(value,step,min,defaultValue=""){if(step==="any")return!1;const parsedValue=parseTimeValue(value);if(!parsedValue)return!1;const numericStep=Number(step),stepMilliseconds=(Number.isFinite(numericStep)&&numericStep>0?numericStep:60)*1e3,stepBase=timeStepBaseMilliseconds(min,defaultValue),remainder=((parsedValue.milliseconds-stepBase)%stepMilliseconds+stepMilliseconds)%stepMilliseconds;return remainder>1e-6&&stepMilliseconds-remainder>1e-6}function localeHour12(locale,hourFormat){if(hourFormat!=="auto")return hourFormat==="12";try{return getDateTimeFormat(locale,{hour:"numeric"}).resolvedOptions().hour12??!1}catch{return!1}}function localeTimePattern(locale,hourFormat,includeSeconds){const hour12=localeHour12(locale,hourFormat);try{return getDateTimeFormat(locale,{hour:"numeric",minute:"2-digit",...includeSeconds?{second:"2-digit"}:{},hour12,timeZone:"UTC"}).formatToParts(new Date(Date.UTC(2020,0,1,13,5,9))).flatMap(part=>part.type==="hour"||part.type==="minute"||part.type==="second"||part.type==="dayPeriod"?[{type:part.type,value:part.value}]:part.type==="literal"?[{type:"literal",value:part.value}]:[])}catch{return[{type:"hour",value:hour12?"1":"13"},{type:"literal",value:":"},{type:"minute",value:"05"},...includeSeconds?[{type:"literal",value:":"},{type:"second",value:"09"}]:[],...hour12?[{type:"literal",value:" "},{type:"dayPeriod",value:"PM"}]:[]]}}function dayPeriodLabels(locale){const labelAt=hour=>{try{return getDateTimeFormat(locale,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(new Date(Date.UTC(2020,0,1,hour))).find(part=>part.type==="dayPeriod")?.value}catch{return}};return{am:labelAt(1)??"AM",pm:labelAt(13)??"PM"}}function wrapTimeMilliseconds(value){return(value%DAY_MILLISECONDS+DAY_MILLISECONDS)%DAY_MILLISECONDS}export{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeStepBaseMilliseconds,timeValueFromMilliseconds,to24Hour,wrapTimeMilliseconds};
|
|
@@ -239,10 +239,19 @@ export declare class LyraTimeInput extends LyraTimeInput_base {
|
|
|
239
239
|
set disabled(next: boolean);
|
|
240
240
|
get value(): string;
|
|
241
241
|
set value(next: string | Date | null);
|
|
242
|
-
/** Milliseconds since local midnight, or `NaN` while blank/incomplete.
|
|
242
|
+
/** Milliseconds since local midnight, or `NaN` while blank/incomplete.
|
|
243
|
+
*
|
|
244
|
+
* Assigning sets `value` from the same scale. `NaN`, a negative number, or a full day or more
|
|
245
|
+
* clears the field rather than wrapping, matching how a native time input treats an
|
|
246
|
+
* out-of-range `valueAsNumber`. Assignment is silent, like the native property. */
|
|
243
247
|
get valueAsNumber(): number;
|
|
244
|
-
|
|
248
|
+
set valueAsNumber(next: number);
|
|
249
|
+
/** A Date carrying the selected local clock fields on today's local calendar date.
|
|
250
|
+
*
|
|
251
|
+
* Assigning reads the same local clock fields back off the given Date, so it round-trips with
|
|
252
|
+
* the getter; `null` or an invalid Date clears the field. Assignment is silent. */
|
|
245
253
|
get valueAsDate(): Date | null;
|
|
254
|
+
set valueAsDate(next: Date | null);
|
|
246
255
|
private get numericStep();
|
|
247
256
|
private get includeSeconds();
|
|
248
257
|
private get pattern();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};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{acquireAriaDescription}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{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/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,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,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,popover:LYRA_DEFAULT_popover,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}}}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.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,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.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"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}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.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 parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",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){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}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}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}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.segmentOrder.includes("dayPeriod")}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"},this.secondsVisible=this.numericStep<60||parsed.precision!=="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){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);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"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[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,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=this.shadowRoot?.activeElement;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.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))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment),modal:!1,trapFocus:!1}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0,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()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}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){if(super.willUpdate(changed),!this.hasUpdated){const slots=Array.from(this.children??[]).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label"),this.hasHintSlot=slots.includes("hint"),this.hasErrorSlot=slots.includes("error"),this.hasStartSlot=slots.includes("start"),this.hasEndSlot=slots.includes("end"),this.hasFooterSlot=slots.includes("footer")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}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),this.syncRequiredDescription();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.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};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{acquireAriaDescription}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{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/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}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,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,popover:LYRA_DEFAULT_popover,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}}}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.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,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.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"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}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.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 parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",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){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),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 numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}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.segmentOrder.includes("dayPeriod")}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"},this.secondsVisible=this.numericStep<60||parsed.precision!=="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){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);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"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[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,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=this.shadowRoot?.activeElement;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.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))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment),modal:!1,trapFocus:!1}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0,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()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}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){if(super.willUpdate(changed),!this.hasUpdated){const slots=Array.from(this.children??[]).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label"),this.hasHintSlot=slots.includes("hint"),this.hasErrorSlot=slots.includes("error"),this.hasStartSlot=slots.includes("start"),this.hasEndSlot=slots.includes("end"),this.hasFooterSlot=slots.includes("footer")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}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),this.syncRequiredDescription();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.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}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"
|
|
@@ -113,12 +113,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
113
113
|
font-variant-numeric: tabular-nums;
|
|
114
114
|
user-select: none;
|
|
115
115
|
}
|
|
116
|
-
/* :host(:not(:disabled)), not [part='segment']:not(:disabled) -- a segment is
|
|
117
|
-
<span part="segment" role="spinbutton">, which can never itself match :disabled. This is a
|
|
118
|
-
form-associated custom element (static formAssociated = true), so the UA computes its
|
|
119
|
-
disabled state (and therefore :disabled/:enabled matching on the host) from its own disabled
|
|
120
|
-
content attribute *or* an ancestor <fieldset disabled>'s cascade, the same way lr-time-range's
|
|
121
|
-
[part^='handle']:hover is gated. */
|
|
122
116
|
:host(:not(:disabled)) [part='segment']:hover {
|
|
123
117
|
background: var(--lr-time-input-segment-hover-bg, var(--lr-color-brand-quiet));
|
|
124
118
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{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{declaredDefaultConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired}from"../../../internal/default-strings.generated.js";const MAX_LOCALE_ENTRIES=512;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 LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,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 locales(){return this._locales}set locales(next){const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}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.requestUpdate("open",old)}constructor(){super(),this.showFlags=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),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.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this.activeScrollGeneration=0,this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));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&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&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.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.clearTypeAheadTimer(),this.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"))}get value(){return this._value}set value(next){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??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._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.isBarred()?this.validityController.setValidity({}):this.required&&!this._value?this.validityController.setValidity({valueMissing:!0},this.localize("localePickerRequired")):this.validityController.setValidity({}),this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,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._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return 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;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}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)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox))}updated(changed){super.updated(changed),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")))&&this.syncPopup(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}commit(tag){const previousValue=this._value;this.value=tag,this.hide(),this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:!0}).defaultPrevented||setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow,this.typeAheadTimer=ownerWindow.setTimeout(()=>{this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||(this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0,this.typeAheadBuffer="")},500)}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),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}setActiveIndex(index){const last=this.normalizedEntries.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(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{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{declaredDefaultConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired}from"../../../internal/default-strings.generated.js";const MAX_LOCALE_ENTRIES=512;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 LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,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 locales(){return this._locales}set locales(next){const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}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.requestUpdate("open",old)}constructor(){super(),this.showFlags=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),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.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this.activeScrollGeneration=0,this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));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&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&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.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.clearTypeAheadTimer(),this.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"))}get value(){return this._value}set value(next){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??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._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.isBarred()?this.validityController.setValidity({}):this.required&&!this._value?this.validityController.setValidity({valueMissing:!0},this.localize("localePickerRequired")):this.validityController.setValidity({}),this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,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._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return 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;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}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)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox))}updated(changed){super.updated(changed),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")))&&this.syncPopup(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}commit(tag){const previousValue=this._value;this.value=tag,this.hide(),this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:!0}).defaultPrevented||setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow,this.typeAheadTimer=ownerWindow.setTimeout(()=>{this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||(this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0,this.typeAheadBuffer="")},500)}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),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}setActiveIndex(index){const last=this.normalizedEntries.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(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}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"
|
|
@@ -25,7 +25,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
25
25
|
aria-expanded=${this.open?"true":"false"}
|
|
26
26
|
aria-controls=${this.listId}
|
|
27
27
|
aria-activedescendant=${activeId}
|
|
28
|
-
aria-label=${this
|
|
28
|
+
aria-label=${hostAriaLabel(this)??(hasLabel?nothing:this.localize("localePickerLabel"))}
|
|
29
29
|
aria-describedby=${describedBy||nothing}
|
|
30
30
|
aria-required=${this.required?"true":"false"}
|
|
31
31
|
aria-invalid=${this.touched&&!this.internals.validity.valid?"true":"false"}
|
|
@@ -2,25 +2,12 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
2
2
|
:host {
|
|
3
3
|
display: block;
|
|
4
4
|
--_lr-locale-picker-trigger-padding-default: var(--lr-space-xs) var(--lr-space-s);
|
|
5
|
-
/* Height and text size come from the ONE shared form-control ladder (internal/sizes.styles.ts)
|
|
6
|
-
rather than a private copy of the same six values. The ladder matches both spellings of every
|
|
7
|
-
tier in one selector list, so size="small" and size="s" resolve identically here with no
|
|
8
|
-
per-component alias rules. */
|
|
9
5
|
--_lr-locale-picker-trigger-min-height-default: var(--lr-form-control-height);
|
|
10
6
|
--_lr-locale-picker-font-size-default: var(--lr-form-control-font-size);
|
|
11
7
|
--_lr-locale-picker-expand-size-default: var(--lr-size-1-75rem);
|
|
12
8
|
--_lr-locale-picker-gap-default: var(--lr-space-xs);
|
|
13
9
|
--_lr-locale-picker-radius-default: var(--lr-form-control-radius);
|
|
14
|
-
|
|
15
|
-
identical convention: it is a consumer-facing escape hatch consumed only through the
|
|
16
|
-
var() fallback on [part='trigger'] below, so leaving it genuinely undeclared keeps that
|
|
17
|
-
fallback arm live. */
|
|
18
|
-
}
|
|
19
|
-
/* What remains per tier is this component's OWN geometry -- trigger density and the decorative
|
|
20
|
-
expand glyph -- which is not a form-control height/text ladder and so is not part of the shared
|
|
21
|
-
one. Each tier matches both spellings for the same reason sizes.styles.ts does: the shared
|
|
22
|
-
ladder accepts size="small", and a trigger whose density silently ignored it would be worse than
|
|
23
|
-
one that never accepted it. */
|
|
10
|
+
}
|
|
24
11
|
:host([size='2xs']) {
|
|
25
12
|
--_lr-locale-picker-trigger-padding-default: var(--lr-size-0-0625rem) var(--lr-space-2xs);
|
|
26
13
|
--_lr-locale-picker-expand-size-default: var(--lr-size-1rem);
|
|
@@ -48,9 +35,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
48
35
|
font-size: var(--lr-font-size-md-sm);
|
|
49
36
|
font-weight: var(--lr-font-weight-semibold);
|
|
50
37
|
}
|
|
51
|
-
/* :empty never matches here -- the part always contains a literal <slot> child element
|
|
52
|
-
regardless of assigned content -- so real emptiness is tracked via hasLabelSlot/label.length
|
|
53
|
-
and reflected via the hidden attribute instead (same fix as lr-select's identical part). */
|
|
54
38
|
[part='form-control-label'][hidden] {
|
|
55
39
|
display: none;
|
|
56
40
|
}
|
|
@@ -79,15 +63,9 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
79
63
|
outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);
|
|
80
64
|
outline-offset: var(--lr-focus-ring-offset);
|
|
81
65
|
}
|
|
82
|
-
/* :where() zeroes the wrapped selectors' specificity contribution, keeping this at (0,1,0) --
|
|
83
|
-
matches lr-select's/lr-model-select's fixed convention, so a consumer's own
|
|
84
|
-
::part(trigger):hover override ((0,1,1)) still wins without needing !important. */
|
|
85
66
|
:where([part='trigger']):hover:where(:not(:disabled)) {
|
|
86
67
|
background: var(--lr-locale-picker-trigger-hover-bg, var(--lr-color-brand-quiet));
|
|
87
68
|
}
|
|
88
|
-
/* Pressed mixes that same hover tint one shared step further toward the text colour, and stays
|
|
89
|
-
inside the identical :where()/:not(:disabled) wrapping so it neither out-specifies a
|
|
90
|
-
consumer's ::part(trigger):active nor fires on a disabled trigger. */
|
|
91
69
|
:where([part='trigger']):active:where(:not(:disabled)) {
|
|
92
70
|
background: color-mix(
|
|
93
71
|
in oklab,
|
|
@@ -143,7 +121,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
143
121
|
background: var(--lr-color-surface);
|
|
144
122
|
border: var(--lr-border-width-thin) solid var(--lr-color-border);
|
|
145
123
|
border-radius: var(--lr-locale-picker-radius, var(--_lr-locale-picker-radius-default));
|
|
146
|
-
/* Anchored overlay: a positioner-placed listbox floating over page content, not a modal layer. */
|
|
147
124
|
box-shadow: var(--lr-shadow-m);
|
|
148
125
|
visibility: hidden;
|
|
149
126
|
opacity: 0;
|
|
@@ -188,8 +165,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
188
165
|
[part='option'][data-active] {
|
|
189
166
|
background: var(--lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet));
|
|
190
167
|
}
|
|
191
|
-
/* Mixing the hover tint itself (not the bare token) keeps a consumer who retinted
|
|
192
|
-
--lr-locale-picker-option-active-bg in charge of both states. */
|
|
193
168
|
[part='option']:active {
|
|
194
169
|
background: color-mix(
|
|
195
170
|
in oklab,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};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{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{findImplicitSubmitter,isNativeSubmitter,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}from"../../../internal/converters.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const 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,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments),this.label="",this.hint="",this.errorText="",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.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,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.segmentEditPendingChange=!1,this.autosubmitToken=0,this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previous=this.value,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),previous&&!next&&this.emit("lr-clear"),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,relayNativeEvent(this,event)},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)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:!0}).length>0}}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 input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1;const normalized=this.sanitize(next??"");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();if(!form)return;const submitter=findImplicitSubmitter(form);submitter?isNativeSubmitter(submitter)?form.requestSubmit(submitter):submitter.click():form.requestSubmit()}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.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousValue=this.value,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.segmentEditPendingChange=!0,previousValue&&!nextValue&&this.emit("lr-clear"),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);start===void 0||end===void 0?control.setRangeText(boundedReplacement):control.setRangeText(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(){const hadValue=this.value.length>0;this.value="",this.control&&(this.control.value=""),this.focus(),hadValue&&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")}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.value);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,"--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(){this.segmentEditPendingChange&&(this.segmentEditPendingChange=!1,dispatchNativeEvent(this,"change"))}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&!this.readonly&&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,hasHint=!!this.hint||this.hasHintSlot,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" ");let segmentIndex=-1;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};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{findImplicitSubmitter,isNativeSubmitter,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}from"../../../internal/converters.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const 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,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments),this.label="",this.hint="",this.errorText="",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.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,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.segmentEditPendingChange=!1,this.autosubmitToken=0,this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previous=this.value,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),previous&&!next&&this.emit("lr-clear"),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,relayNativeEvent(this,event)},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)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:!0}).length>0}}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 input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1;const normalized=this.sanitize(next??"");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();if(!form)return;const submitter=findImplicitSubmitter(form);submitter?isNativeSubmitter(submitter)?form.requestSubmit(submitter):submitter.click():form.requestSubmit()}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.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousValue=this.value,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.segmentEditPendingChange=!0,previousValue&&!nextValue&&this.emit("lr-clear"),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);start===void 0||end===void 0?control.setRangeText(boundedReplacement):control.setRangeText(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(){const hadValue=this.value.length>0;this.value="",this.control&&(this.control.value=""),this.focus(),hadValue&&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")}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.value);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,"--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(){this.segmentEditPendingChange&&(this.segmentEditPendingChange=!1,dispatchNativeEvent(this,"change"))}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&!this.readonly&&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,hasHint=!!this.hint||this.hasHintSlot,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" ?hidden=${!!this.label} @slotchange=${this.onLabelSlotChange}></slot>
|
|
@@ -20,8 +20,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
20
20
|
?disabled=${this.effectiveDisabled}
|
|
21
21
|
?readonly=${this.readonly}
|
|
22
22
|
?required=${this.required}
|
|
23
|
-
aria-label=${this
|
|
24
|
-
aria-labelledby=${
|
|
23
|
+
aria-label=${hostAriaLabel(this)??(hasLabel?nothing:this.localize("otpInputLabel"))}
|
|
24
|
+
aria-labelledby=${labelledBy}
|
|
25
25
|
aria-describedby=${describedBy||nothing}
|
|
26
26
|
aria-invalid=${ariaInvalid?"true":"false"}
|
|
27
27
|
@input=${this.onInput}
|
|
@@ -42,10 +42,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
42
42
|
}
|
|
43
43
|
${formControlRequiredMarker}
|
|
44
44
|
|
|
45
|
-
/* One real <input> stretched invisibly across the presentational segments. It remains the native
|
|
46
|
-
integration point for SMS autofill, IME composition, mobile keyboards and selection, while the
|
|
47
|
-
fixed-cell key/paste handlers map editing intents into the visual model. One field also keeps
|
|
48
|
-
the control to one tab stop, which is what the WAI-ARIA text-input pattern expects. */
|
|
49
45
|
[part~='segments'] {
|
|
50
46
|
position: relative;
|
|
51
47
|
display: flex;
|
|
@@ -74,8 +70,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
74
70
|
padding: 0;
|
|
75
71
|
border: none;
|
|
76
72
|
background: none;
|
|
77
|
-
/* Transparent rather than hidden: a hidden input cannot receive focus or show a native
|
|
78
|
-
autofill affordance, and opacity: 0 keeps it a real, focusable text field. */
|
|
79
73
|
color: transparent;
|
|
80
74
|
caret-color: transparent;
|
|
81
75
|
font: inherit;
|
|
@@ -83,8 +77,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
83
77
|
opacity: 0;
|
|
84
78
|
cursor: text;
|
|
85
79
|
}
|
|
86
|
-
/* :disabled, not [disabled] -- only the native pseudo-class tracks disablement cascaded from an
|
|
87
|
-
ancestor <fieldset disabled>, which never touches this element's own attribute. */
|
|
88
80
|
:host(:disabled) [part='control'] {
|
|
89
81
|
cursor: not-allowed;
|
|
90
82
|
}
|
|
@@ -107,7 +99,6 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
107
99
|
line-height: var(--lr-line-height-snug);
|
|
108
100
|
transition: border-color var(--lr-transition-fast), box-shadow var(--lr-transition-fast);
|
|
109
101
|
}
|
|
110
|
-
/* State in the part name -- ::part(segment)[data-active] never matches. */
|
|
111
102
|
[part~='active'] {
|
|
112
103
|
border-color: var(--lr-otp-input-active-border-color, var(--lr-focus-ring-color));
|
|
113
104
|
box-shadow: 0 0 0 var(--lr-focus-ring-width) var(--lr-otp-input-active-ring-color, var(--lr-focus-ring-color));
|
|
@@ -125,17 +116,10 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
|
|
|
125
116
|
user-select: none;
|
|
126
117
|
}
|
|
127
118
|
|
|
128
|
-
/* Masking is display-only: the real characters stay in value and in the input the screen
|
|
129
|
-
reader reads, exactly like a password field's dots. Generated content rather than rendered
|
|
130
|
-
text, so the glyph can never reach an accessible name -- the segment boxes are aria-hidden
|
|
131
|
-
and ::after content is not exposed to assistive technology in the first place.
|
|
132
|
-
The placeholder-mask token is the same glyph in a segment that holds nothing yet, so the
|
|
133
|
-
field reads as a fixed-length code before any entry. */
|
|
134
119
|
[part~='masked']::after,
|
|
135
120
|
[part~='placeholder-mask']::after {
|
|
136
121
|
content: var(--mask-char, var(--lr-otp-input-mask-char, var(--_lr-otp-input-mask-char-default)));
|
|
137
122
|
}
|
|
138
|
-
/* An unentered glyph is a placeholder, so it sits quieter than an entered character. */
|
|
139
123
|
[part~='placeholder-mask'] {
|
|
140
124
|
color: var(--lr-color-text-quiet);
|
|
141
125
|
}
|
|
@@ -57,10 +57,18 @@ export interface LibphonenumberModuleLike<CountryCode extends string = string> {
|
|
|
57
57
|
* Keeping the loader consumer-supplied avoids a static import, so neither the
|
|
58
58
|
* dependency nor its numbering metadata enters Lyra's base bundle.
|
|
59
59
|
*
|
|
60
|
+
* Accepts either the module namespace directly (named exports, as `libphonenumber-js`'s own type
|
|
61
|
+
* declarations describe it) or a `{ default: {...} }`-wrapped namespace, since some bundler/CJS
|
|
62
|
+
* interop configurations resolve it that way -- the same normalization `map-loader.ts` and
|
|
63
|
+
* `spreadsheet-loader.ts` apply to their own optional peers. Rejects (with a descriptive `TypeError`
|
|
64
|
+
* naming the missing capability, not an incidental "not a function" deep inside this function) a
|
|
65
|
+
* resolved value that has neither shape, or is missing a required method, rather than silently
|
|
66
|
+
* calling into `undefined`.
|
|
67
|
+
*
|
|
60
68
|
* @example
|
|
61
69
|
* `el.adapter = await loadLibphonenumberAdapter(() => import('libphonenumber-js/min'))`
|
|
62
70
|
*/
|
|
63
|
-
export declare function loadLibphonenumberAdapter<CountryCode extends string>(loader: () => Promise<
|
|
71
|
+
export declare function loadLibphonenumberAdapter<CountryCode extends string = string>(loader: () => Promise<unknown>): Promise<LyraPhoneNumberAdapter>;
|
|
64
72
|
export interface LyraPhoneInputEventDetail {
|
|
65
73
|
/** Canonical E.164 value, or an empty string until the current input is valid. */
|
|
66
74
|
value: string;
|