@aceshooting/lyra-ui 19.0.1 → 20.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 +153 -0
- package/custom-elements.json +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +14 -4
- package/dist/components/agent-tools/activity-feed/activity-feed.styles.js +1 -1
- package/dist/components/agent-tools/approval-queue/approval-queue.class.d.ts +1 -0
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +4 -3
- package/dist/components/agent-tools/approval-queue/approval-queue.styles.js +1 -1
- package/dist/components/agent-tools/artifact-panel/artifact-panel.class.d.ts +3 -1
- package/dist/components/agent-tools/context-inspector/context-inspector.class.d.ts +1 -0
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +4 -3
- package/dist/components/agent-tools/context-inspector/context-inspector.styles.js +1 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.d.ts +1 -0
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +4 -3
- package/dist/components/agent-tools/evaluation-run/evaluation-run.styles.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.d.ts +1 -0
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +4 -3
- package/dist/components/agent-tools/policy-summary/policy-summary.styles.js +1 -1
- package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.d.ts +10 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +3 -3
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.d.ts +6 -3
- package/dist/components/agent-tools/thinking-panel/thinking-panel.styles.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +14 -3
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +12 -2
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +3 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +15 -3
- package/dist/components/charts/chart/box-plot.class.js +3 -3
- package/dist/components/charts/chart/box-plot.styles.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +23 -5
- package/dist/components/charts/chart/chart.class.js +2 -2
- package/dist/components/charts/chart/chart.styles.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.js +1 -1
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/audio-visualizer/audio-visualizer.class.d.ts +4 -2
- package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
- package/dist/components/conversation/branch-picker/branch-picker.class.d.ts +4 -2
- package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
- package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +4 -3
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.d.ts +6 -11
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-shared.d.ts +29 -1
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/code-block.class.d.ts +6 -11
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-shared.js +2 -2
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +4 -2
- package/dist/components/conversation/message-actions/message-actions.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +17 -2
- package/dist/components/conversation/model-select/model-select.class.js +1 -0
- package/dist/components/conversation/model-select/model-select.styles.js +1 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +5 -1
- package/dist/components/conversation/prompt-input/prompt-input.class.js +2 -2
- package/dist/components/conversation/prompt-queue/prompt-queue.class.d.ts +6 -1
- package/dist/components/conversation/prompt-queue/prompt-queue.class.js +2 -2
- package/dist/components/conversation/realtime-session/realtime-session.class.d.ts +5 -1
- package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +13 -2
- package/dist/components/conversation/voice-picker/voice-picker.class.js +5 -3
- package/dist/components/conversation/voice-picker/voice-picker.styles.js +1 -1
- package/dist/components/data/calendar/calendar.class.d.ts +9 -0
- package/dist/components/data/calendar/calendar.class.js +2 -2
- package/dist/components/data/calendar/calendar.styles.js +1 -1
- package/dist/components/data/condition-builder/condition-builder.class.d.ts +5 -1
- package/dist/components/data/context-meter/context-meter.class.d.ts +4 -0
- package/dist/components/data/context-meter/context-meter.styles.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +8 -2
- package/dist/components/data/data-grid/data-grid.class.js +1 -2
- package/dist/components/data/flow-node/flow-node.class.d.ts +7 -4
- package/dist/components/data/flow-node/flow-node.styles.js +1 -1
- package/dist/components/data/funnel/funnel.class.d.ts +5 -0
- package/dist/components/data/funnel/funnel.class.js +4 -3
- package/dist/components/data/funnel/funnel.styles.js +1 -1
- package/dist/components/data/gauge/gauge.class.d.ts +12 -1
- package/dist/components/data/gauge/gauge.styles.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +50 -13
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
- package/dist/components/data/graph-query-builder/graph-query-builder.styles.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +27 -9
- package/dist/components/data/heatmap/heatmap.class.js +5 -3
- package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +2 -0
- package/dist/components/data/sequence-strip/sequence-strip.styles.js +1 -1
- package/dist/components/data/table/table.class.d.ts +8 -0
- package/dist/components/data/table/table.class.js +2 -1
- package/dist/components/data/tree/tree.class.d.ts +20 -1
- package/dist/components/data/tree/tree.class.js +1 -1
- package/dist/components/data/word-cloud/word-cloud.class.d.ts +4 -1
- package/dist/components/data/word-cloud/word-cloud.class.js +2 -2
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +11 -8
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.styles.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +2 -2
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.d.ts +2 -0
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.styles.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.d.ts +11 -1
- package/dist/components/forms/color-picker/color-picker.class.js +4 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +67 -18
- package/dist/components/forms/combobox/combobox.class.js +7 -6
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +22 -2
- package/dist/components/forms/date-picker/date-input.class.js +4 -2
- package/dist/components/forms/date-picker/date-input.styles.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +18 -4
- package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +18 -4
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.styles.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +11 -1
- package/dist/components/forms/input/time-input.class.js +4 -3
- package/dist/components/forms/input/time-input.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +17 -3
- package/dist/components/forms/locale-picker/locale-picker.class.js +3 -2
- package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.d.ts +13 -5
- package/dist/components/forms/otp-input/otp-input.class.js +2 -2
- package/dist/components/forms/otp-input/otp-input.styles.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.d.ts +10 -3
- package/dist/components/forms/phone-input/phone-input.class.js +6 -2
- package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +1 -1
- package/dist/components/forms/radio/radio-group.class.js +2 -2
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +9 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +5 -3
- package/dist/components/forms/select/select.class.d.ts +4 -0
- package/dist/components/forms/select/select.styles.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +5 -1
- package/dist/components/forms/slider/slider.class.js +3 -3
- package/dist/components/forms/switch/switch.class.d.ts +6 -5
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +2 -2
- package/dist/components/forms/token-input/token-input.class.d.ts +13 -3
- package/dist/components/forms/token-input/token-input.class.js +3 -1
- package/dist/components/layout/carousel/carousel.class.d.ts +4 -1
- package/dist/components/layout/carousel/carousel.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.class.d.ts +8 -2
- package/dist/components/layout/command-palette/command-palette.class.js +1 -1
- package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
- package/dist/components/layout/details/accordion.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +10 -7
- package/dist/components/layout/dock-panel/dock-panel.class.js +2 -2
- package/dist/components/layout/dock-panel/dock-panel.styles.js +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +13 -3
- package/dist/components/layout/menu/menu.class.js +4 -3
- package/dist/components/layout/menu/menu.styles.js +1 -1
- package/dist/components/layout/page/page.class.d.ts +7 -1
- package/dist/components/layout/reorder-list/reorder-list.class.d.ts +1 -1
- package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +2 -0
- package/dist/components/layout/segmented/segmented.styles.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +15 -2
- package/dist/components/layout/widget/widget.class.js +1 -1
- package/dist/components/layout/widget/widget.styles.js +1 -1
- package/dist/components/media/avatar/avatar.class.d.ts +4 -0
- package/dist/components/media/avatar/avatar.styles.js +1 -1
- package/dist/components/media/avatar-group/avatar-group.class.d.ts +8 -1
- package/dist/components/media/avatar-group/avatar-group.styles.js +1 -1
- package/dist/components/media/drop-zone/drop-zone.class.d.ts +10 -4
- package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
- package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/map/map.class.d.ts +19 -5
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/video-playlist/video-playlist.class.d.ts +6 -3
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/overlays/callout/callout.class.d.ts +4 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +4 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/overlays/overlay/popover.class.d.ts +9 -1
- package/dist/components/overlays/overlay/popover.class.js +3 -2
- package/dist/components/overlays/overlay/tooltip.class.d.ts +14 -4
- package/dist/components/overlays/overlay/tooltip.class.js +3 -2
- package/dist/components/overlays/popup/popup.class.d.ts +15 -1
- package/dist/components/overlays/popup/popup.class.js +3 -3
- package/dist/components/overlays/popup/popup.styles.js +1 -1
- package/dist/components/overlays/progress/progress-bar.class.d.ts +2 -0
- package/dist/components/overlays/progress/progress.styles.js +1 -1
- package/dist/components/retrieval/citation-badge/citation-badge.class.d.ts +4 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.d.ts +4 -0
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +4 -3
- package/dist/components/retrieval/claim-evidence/claim-evidence.styles.js +1 -1
- package/dist/components/retrieval/community-card/community-card.class.d.ts +6 -1
- package/dist/components/retrieval/community-card/community-card.styles.js +1 -1
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.d.ts +9 -1
- package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +4 -3
- package/dist/components/retrieval/entity-card/entity-card.styles.js +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +4 -2
- package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +2 -2
- package/dist/components/retrieval/graph-legend/graph-legend.class.d.ts +18 -4
- package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.d.ts +7 -0
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +4 -3
- package/dist/components/retrieval/grounding-summary/grounding-summary.styles.js +1 -1
- package/dist/components/retrieval/memory-panel/memory-panel.class.d.ts +6 -0
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +4 -3
- package/dist/components/retrieval/memory-panel/memory-panel.styles.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +17 -1
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/retrieval/mind-map/mind-map.class.d.ts +8 -1
- package/dist/components/retrieval/mind-map/mind-map.class.js +3 -2
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +5 -0
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +6 -5
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.styles.js +1 -1
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +5 -5
- package/dist/components/retrieval/retrieval-compare/retrieval-compare.styles.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.d.ts +21 -2
- package/dist/components/retrieval/source-list/source-list.class.js +2 -2
- package/dist/components/retrieval/source-list/source-list.styles.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.d.ts +3 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +2 -2
- package/dist/components/utility/diff-view/diff-view.class.d.ts +105 -8
- package/dist/components/utility/diff-view/diff-view.class.js +21 -5
- package/dist/components/utility/diff-view/diff-view.styles.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +26 -2
- package/dist/components/utility/export-button/export-button.class.js +4 -2
- package/dist/components/utility/export-button/export-button.styles.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +19 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +3 -2
- package/dist/components/utility/mention-popover/mention-popover.styles.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +1 -3
- package/dist/components/utility/tour/tour.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.d.ts +20 -3
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-view.styles.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-viewer.class.d.ts +5 -0
- package/dist/components/viewers/geojson-view/geojson-viewer.class.js +6 -3
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +7 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +7 -1
- package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
- package/dist/components/viewers/xml-viewer/xml-viewer.class.d.ts +5 -0
- package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +79 -30
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/aria-reflection.js +1 -1
- package/dist/internal/catalog-picker.d.ts +14 -3
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/default-strings.generated.d.ts +1 -1
- package/dist/internal/default-strings.generated.js +2 -2
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +2 -2
- package/dist/internal/lyra-element.d.ts +17 -0
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/translations/ar/agent-tools.js +1 -1
- package/dist/translations/ar/data.js +1 -1
- package/dist/translations/ar/retrieval.js +1 -1
- package/dist/translations/ar/shared.js +1 -1
- package/dist/translations/ar/viewers.js +1 -1
- package/dist/translations/de/agent-tools.js +1 -1
- package/dist/translations/de/data.js +1 -1
- package/dist/translations/de/retrieval.js +1 -1
- package/dist/translations/de/shared.js +1 -1
- package/dist/translations/de/viewers.js +1 -1
- package/dist/translations/es/agent-tools.js +1 -1
- package/dist/translations/es/data.js +1 -1
- package/dist/translations/es/retrieval.js +1 -1
- package/dist/translations/es/shared.js +1 -1
- package/dist/translations/es/viewers.js +1 -1
- package/dist/translations/fa/agent-tools.js +1 -1
- package/dist/translations/fa/data.js +1 -1
- package/dist/translations/fa/retrieval.js +1 -1
- package/dist/translations/fa/shared.js +1 -1
- package/dist/translations/fa/viewers.js +1 -1
- package/dist/translations/fr/agent-tools.js +1 -1
- package/dist/translations/fr/data.js +1 -1
- package/dist/translations/fr/retrieval.js +1 -1
- package/dist/translations/fr/shared.js +1 -1
- package/dist/translations/fr/viewers.js +1 -1
- package/dist/translations/he/agent-tools.js +1 -1
- package/dist/translations/he/data.js +1 -1
- package/dist/translations/he/retrieval.js +1 -1
- package/dist/translations/he/shared.js +1 -1
- package/dist/translations/he/viewers.js +1 -1
- package/dist/translations/it/agent-tools.js +1 -1
- package/dist/translations/it/data.js +1 -1
- package/dist/translations/it/retrieval.js +1 -1
- package/dist/translations/it/shared.js +1 -1
- package/dist/translations/it/viewers.js +1 -1
- package/dist/translations/ja/agent-tools.js +1 -1
- package/dist/translations/ja/data.js +1 -1
- package/dist/translations/ja/retrieval.js +1 -1
- package/dist/translations/ja/shared.js +1 -1
- package/dist/translations/ja/viewers.js +1 -1
- package/dist/translations/pt-BR/agent-tools.js +1 -1
- package/dist/translations/pt-BR/data.js +1 -1
- package/dist/translations/pt-BR/retrieval.js +1 -1
- package/dist/translations/pt-BR/shared.js +1 -1
- package/dist/translations/pt-BR/viewers.js +1 -1
- package/dist/translations/ro/agent-tools.js +1 -1
- package/dist/translations/ro/data.js +1 -1
- package/dist/translations/ro/retrieval.js +1 -1
- package/dist/translations/ro/shared.js +1 -1
- package/dist/translations/ro/viewers.js +1 -1
- package/dist/translations/ru/agent-tools.js +1 -1
- package/dist/translations/ru/data.js +1 -1
- package/dist/translations/ru/retrieval.js +1 -1
- package/dist/translations/ru/shared.js +1 -1
- package/dist/translations/ru/viewers.js +1 -1
- package/dist/translations/zh-CN/agent-tools.js +1 -1
- package/dist/translations/zh-CN/data.js +1 -1
- package/dist/translations/zh-CN/retrieval.js +1 -1
- package/dist/translations/zh-CN/shared.js +1 -1
- package/dist/translations/zh-CN/viewers.js +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-activity-feed.md +20 -9
- package/llms/components/lr-approval-queue.md +3 -2
- package/llms/components/lr-archive-viewer.md +8 -1
- package/llms/components/lr-artifact-panel.md +3 -1
- package/llms/components/lr-audio-visualizer.md +3 -1
- package/llms/components/lr-avatar-group.md +13 -6
- package/llms/components/lr-avatar.md +6 -2
- package/llms/components/lr-bar-chart.md +6 -3
- package/llms/components/lr-box-plot.md +6 -2
- package/llms/components/lr-branch-picker.md +3 -1
- package/llms/components/lr-bubble-chart.md +6 -3
- package/llms/components/lr-calendar.md +10 -3
- package/llms/components/lr-carousel.md +4 -2
- package/llms/components/lr-chart.md +12 -4
- package/llms/components/lr-chat-viewport.md +3 -2
- package/llms/components/lr-checkbox.md +8 -5
- package/llms/components/lr-citation-badge.md +2 -0
- package/llms/components/lr-claim-evidence.md +6 -2
- package/llms/components/lr-code-editor.md +3 -1
- package/llms/components/lr-color-picker.md +20 -8
- package/llms/components/lr-combobox.md +26 -3
- package/llms/components/lr-command-palette.md +6 -3
- package/llms/components/lr-community-card.md +7 -4
- package/llms/components/lr-context-inspector.md +3 -2
- package/llms/components/lr-context-meter.md +13 -5
- package/llms/components/lr-data-grid.md +2 -0
- package/llms/components/lr-date-input.md +12 -3
- package/llms/components/lr-date-picker.md +11 -2
- package/llms/components/lr-diff-view.md +46 -5
- package/llms/components/lr-doughnut-chart.md +6 -3
- package/llms/components/lr-drop-zone.md +7 -3
- package/llms/components/lr-embedding-explorer.md +8 -2
- package/llms/components/lr-emoji-picker.md +5 -1
- package/llms/components/lr-entity-chip.md +2 -0
- package/llms/components/lr-eval-run.md +3 -2
- package/llms/components/lr-export-button.md +5 -2
- package/llms/components/lr-flow-node.md +7 -4
- package/llms/components/lr-funnel.md +7 -2
- package/llms/components/lr-gauge.md +7 -2
- package/llms/components/lr-geojson-view.md +10 -2
- package/llms/components/lr-geojson-viewer.md +10 -2
- package/llms/components/lr-graph-legend.md +6 -3
- package/llms/components/lr-graph-query-builder.md +21 -11
- package/llms/components/lr-grounding-summary.md +8 -2
- package/llms/components/lr-heatmap.md +5 -2
- package/llms/components/lr-histogram.md +4 -2
- package/llms/components/lr-json-schema-viewer.md +7 -5
- package/llms/components/lr-line-chart.md +6 -3
- package/llms/components/lr-locale-picker.md +4 -1
- package/llms/components/lr-map.md +5 -3
- package/llms/components/lr-memory-panel.md +6 -2
- package/llms/components/lr-mention-popover.md +7 -4
- package/llms/components/lr-message-actions.md +3 -1
- package/llms/components/lr-message-parts.md +8 -2
- package/llms/components/lr-mind-map.md +11 -2
- package/llms/components/lr-option.md +25 -2
- package/llms/components/lr-otp-input.md +3 -1
- package/llms/components/lr-phone-input.md +9 -5
- package/llms/components/lr-pie-chart.md +6 -3
- package/llms/components/lr-polar-area-chart.md +6 -3
- package/llms/components/lr-policy-summary.md +3 -2
- package/llms/components/lr-progress-bar.md +4 -1
- package/llms/components/lr-prompt-input.md +4 -1
- package/llms/components/lr-prompt-queue.md +5 -2
- package/llms/components/lr-radar-chart.md +6 -3
- package/llms/components/lr-rag-eval-dashboard.md +7 -2
- package/llms/components/lr-realtime-session.md +3 -1
- package/llms/components/lr-rubric-form.md +6 -1
- package/llms/components/lr-scatter-chart.md +6 -3
- package/llms/components/lr-segmented.md +3 -1
- package/llms/components/lr-select.md +7 -1
- package/llms/components/lr-selection-toolbar.md +4 -1
- package/llms/components/lr-sequence-strip.md +7 -3
- package/llms/components/lr-source-card.md +16 -1
- package/llms/components/lr-source-list.md +17 -2
- package/llms/components/lr-source-picker.md +3 -1
- package/llms/components/lr-subagent-panel.md +6 -3
- package/llms/components/lr-switch.md +4 -3
- package/llms/components/lr-table.md +6 -1
- package/llms/components/lr-thinking-panel.md +8 -5
- package/llms/components/lr-token-input.md +15 -1
- package/llms/components/lr-tool-call-chip.md +2 -0
- package/llms/components/lr-tool-param-form.md +15 -4
- package/llms/components/lr-tooltip.md +8 -4
- package/llms/components/lr-trace-tree.md +7 -4
- package/llms/components/lr-video-playlist.md +7 -5
- package/llms/components/lr-voice-picker.md +7 -4
- package/llms/components/lr-widget.md +15 -2
- package/llms/migration.md +4 -4
- package/llms-full.txt +552 -159
- package/package.json +10 -8
- package/registrations.json +1 -1
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -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{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{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{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.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.rawValue="",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.applyLabelSlotAssignment(event.target)},this.onHintSlotChange=event=>{this.applyHintSlotAssignment(event.target)},this.onErrorSlotChange=event=>{this.applyErrorSlotAssignment(event.target)}}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,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();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(){this.releaseExternalDescription(),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");const labelSlot=this.labelSlotEl,hintSlot=this.hintSlotEl,errorSlot=this.errorSlotEl;queueMicrotask(()=>{collectInitialSlotAssignment(labelSlot,slot=>this.applyLabelSlotAssignment(slot)),collectInitialSlotAssignment(hintSlot,slot=>this.applyHintSlotAssignment(slot)),collectInitialSlotAssignment(errorSlot,slot=>this.applyErrorSlotAssignment(slot))})}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this.control??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--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"))}applyLabelSlotAssignment(slot){this.hasLabelSlot=slot.assignedNodes({flatten:!0}).length>0}applyHintSlotAssignment(slot){this.hasHintSlot=slot.assignedNodes({flatten:!0}).length>0}applyErrorSlotAssignment(slot){this.hasErrorSlot=slot.assignedNodes({flatten:!0}).length>0}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot,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`
|
|
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{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{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,literalSetConverter}from"../../../internal/converters.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const APPEARANCE=literalSetConverter(["outlined","filled","filled-outlined","contained"],"outlined"),ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get appearance(){return this._appearance}set appearance(next){const normalized=APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;this._appearance=normalized,normalized!==old&&this.requestUpdate("appearance",old)}constructor(){super(),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.rawValue="",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.applyLabelSlotAssignment(event.target)},this.onHintSlotChange=event=>{this.applyHintSlotAssignment(event.target)},this.onErrorSlotChange=event=>{this.applyErrorSlotAssignment(event.target)},observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part~="segments"]'))}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();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(){this.releaseExternalDescription(),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");const labelSlot=this.labelSlotEl,hintSlot=this.hintSlotEl,errorSlot=this.errorSlotEl;queueMicrotask(()=>{collectInitialSlotAssignment(labelSlot,slot=>this.applyLabelSlotAssignment(slot)),collectInitialSlotAssignment(hintSlot,slot=>this.applyHintSlotAssignment(slot)),collectInitialSlotAssignment(errorSlot,slot=>this.applyErrorSlotAssignment(slot))})}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this.control??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--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"))}applyLabelSlotAssignment(slot){this.hasLabelSlot=slot.assignedNodes({flatten:!0}).length>0}applyHintSlotAssignment(slot){this.hasHintSlot=slot.assignedNodes({flatten:!0}).length>0}applyErrorSlotAssignment(slot){this.hasErrorSlot=slot.assignedNodes({flatten:!0}).length>0}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot,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>
|
|
@@ -46,4 +46,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
46
46
|
${this.hint}<slot name="hint" ?hidden=${!!this.hint} @slotchange=${this.onHintSlotChange}></slot>
|
|
47
47
|
</div>
|
|
48
48
|
</div>
|
|
49
|
-
`}}__decorate([property()],LyraOtpInput.prototype,"label",void 0),__decorate([property()],LyraOtpInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraOtpInput.prototype,"errorText",void 0),__decorate([property({reflect:!0,converter:
|
|
49
|
+
`}}__decorate([property()],LyraOtpInput.prototype,"label",void 0),__decorate([property()],LyraOtpInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraOtpInput.prototype,"errorText",void 0),__decorate([property({reflect:!0,converter:APPEARANCE})],LyraOtpInput.prototype,"appearance",null),__decorate([property({type:Boolean})],LyraOtpInput.prototype,"autofocus",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"autosubmit",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraOtpInput.prototype,"size",void 0),__decorate([property({type:Number,reflect:!0,converter:declaredDefaultConverter(DEFAULT_LENGTH)})],LyraOtpInput.prototype,"length",void 0),__decorate([property()],LyraOtpInput.prototype,"format",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("numeric")})],LyraOtpInput.prototype,"type",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("preserve")})],LyraOtpInput.prototype,"case",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"mask",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"with-mask"})],LyraOtpInput.prototype,"withMask",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"readonly",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("one-time-code")})],LyraOtpInput.prototype,"autocomplete",void 0),__decorate([state()],LyraOtpInput.prototype,"focused",void 0),__decorate([state()],LyraOtpInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"touched",void 0),__decorate([query('[part="control"]')],LyraOtpInput.prototype,"control",void 0),__decorate([query('slot[name="label"]')],LyraOtpInput.prototype,"labelSlotEl",void 0),__decorate([query('slot[name="hint"]')],LyraOtpInput.prototype,"hintSlotEl",void 0),__decorate([query('slot[name="error"]')],LyraOtpInput.prototype,"errorSlotEl",void 0),__decorate([state()],LyraOtpInput.prototype,"activeSegmentIndex",void 0);export{LyraOtpInput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; --_lr-otp-input-mask-char-default: '•'; --_lr-otp-input-segment-fill-default: transparent; --_lr-otp-input-segment-border-color-default: var(--lr-color-border); --_lr-otp-input-segment-radius-default: var( --segment-border-radius, var(--lr-form-control-radius, var(--lr-radius)) ); } :host([appearance='filled']) { --_lr-otp-input-segment-fill-default: var(--lr-color-surface-raised); --_lr-otp-input-segment-border-color-default: transparent; } :host([appearance='filled-outlined']) { --_lr-otp-input-segment-fill-default: var(--lr-color-surface-raised); --_lr-otp-input-segment-border-color-default: var(--lr-color-border); } :host([appearance='contained']) { --_lr-otp-input-segment-fill-default: transparent; --_lr-otp-input-segment-border-color-default: transparent; --_lr-otp-input-segment-radius-default: 0; } [part~='base'] { display: flex; flex-direction: column; gap: var(--lr-space-2xs); min-inline-size: 0; max-inline-size: 100%; } [part~='label'] { font-size: var(--lr-font-size-sm); font-weight: var(--lr-font-weight-medium); color: var(--lr-color-text); overflow-wrap: anywhere; } [part~='label'][hidden], [part='hint'][hidden], [part='error'][hidden] { display: none; } ${formControlRequiredMarker} [part~='segments'] { position: relative; display: flex; align-items: center; gap: var(--segment-gap, var(--lr-space-xs)); inline-size: fit-content; min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); max-inline-size: 100%; box-sizing: border-box; overflow-inline: auto; overflow-block: hidden; } :host([appearance='contained']) [part~='segments'] { gap: 0; border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--segment-border-radius, var(--lr-form-control-radius, var(--lr-radius))); background: var(--lr-color-surface-raised); } [part='control'] { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; margin: 0; padding: 0; border: none; background: none; color: transparent; caret-color: transparent; font: inherit; letter-spacing: 0; opacity: 0; cursor: text; } :host(:disabled) [part='control'] { cursor: not-allowed; } [part~='segment'] { display: flex; align-items: center; justify-content: center; box-sizing: border-box; flex: 0 0 auto; inline-size: var(--segment-size, var(--lr-otp-input-segment-size)); block-size: var(--segment-size, var(--lr-otp-input-segment-size)); padding: 0; border: var(--lr-border-width-thin) solid var(--lr-otp-input-segment-border-color, var(--_lr-otp-input-segment-border-color-default)); border-radius: var(--lr-otp-input-segment-radius, var(--_lr-otp-input-segment-radius-default)); background: var(--lr-otp-input-segment-fill, var(--_lr-otp-input-segment-fill-default)); color: var(--lr-color-text); font-variant-numeric: tabular-nums; font-size: var(--lr-form-control-font-size, var(--lr-font-size-m)); line-height: var(--lr-line-height-snug); transition: border-color var(--lr-transition-fast), box-shadow var(--lr-transition-fast); } [part~='active'] { border-color: var(--lr-otp-input-active-border-color, var(--lr-focus-ring-color)); box-shadow: 0 0 0 var(--lr-focus-ring-width) var(--lr-otp-input-active-ring-color, var(--lr-focus-ring-color)); } [part~='invalid'] { border-color: var(--lr-otp-input-invalid-border-color, var(--lr-color-danger)); } :host(:disabled) [part~='segment'] { opacity: var(--lr-opacity-disabled); } [part~='segment-literal'] { flex: 0 0 auto; color: var(--lr-color-text-quiet); user-select: none; } [part~='masked']::after, [part~='placeholder-mask']::after { content: var(--mask-char, var(--lr-otp-input-mask-char, var(--_lr-otp-input-mask-char-default))); } [part~='placeholder-mask'] { color: var(--lr-color-text-quiet); } [part='hint'] { font-size: var(--lr-font-size-sm); color: var(--lr-color-text-quiet); overflow-wrap: anywhere; } [part='error'] { font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); overflow-wrap: anywhere; } @media (prefers-reduced-motion: reduce) { [part~='segment'] { transition: none; } } `;export{styles};
|
|
1
|
+
import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; --_lr-otp-input-mask-char-default: '•'; --_lr-otp-input-segment-fill-default: transparent; --_lr-otp-input-segment-border-color-default: var(--lr-color-border); --_lr-otp-input-segment-radius-default: var( --segment-border-radius, var(--lr-form-control-radius, var(--lr-radius)) ); } :host([appearance='filled']) { --_lr-otp-input-segment-fill-default: var(--lr-color-surface-raised); --_lr-otp-input-segment-border-color-default: transparent; } :host([appearance='filled-outlined']) { --_lr-otp-input-segment-fill-default: var(--lr-color-surface-raised); --_lr-otp-input-segment-border-color-default: var(--lr-color-border); } :host([appearance='contained']) { --_lr-otp-input-segment-fill-default: transparent; --_lr-otp-input-segment-border-color-default: transparent; --_lr-otp-input-segment-radius-default: 0; } [part~='base'] { display: flex; flex-direction: column; gap: var(--lr-space-2xs); min-inline-size: 0; max-inline-size: 100%; } [part~='label'] { font-size: var(--lr-font-size-sm); font-weight: var(--lr-font-weight-medium); color: var(--lr-color-text); overflow-wrap: anywhere; } [part~='label'][hidden], [part='hint'][hidden], [part='error'][hidden] { display: none; } ${formControlRequiredMarker} [part~='segments'] { position: relative; display: flex; align-items: center; gap: var(--segment-gap, var(--lr-space-xs)); inline-size: fit-content; min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); max-inline-size: 100%; box-sizing: border-box; overflow-inline: auto; overflow-block: hidden; } :host([appearance='contained']) [part~='segments'] { gap: 0; border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--segment-border-radius, var(--lr-form-control-radius, var(--lr-radius))); background: var(--lr-color-surface-raised); } [part~='segments'][data-scroll-overflow]:where([data-scroll-start][data-scroll-end]) { -webkit-mask-image: linear-gradient( to right, transparent, var(--lr-mask-opaque) var(--lr-scroll-fade-size), var(--lr-mask-opaque) calc(100% - var(--lr-scroll-fade-size)), transparent ); mask-image: linear-gradient( to right, transparent, var(--lr-mask-opaque) var(--lr-scroll-fade-size), var(--lr-mask-opaque) calc(100% - var(--lr-scroll-fade-size)), transparent ); } [part~='segments'][data-scroll-overflow]:where( [data-scroll-end]:not([data-scroll-start]) ) { -webkit-mask-image: linear-gradient( to right, var(--lr-mask-opaque), var(--lr-mask-opaque) calc(100% - var(--lr-scroll-fade-size)), transparent ); mask-image: linear-gradient( to right, var(--lr-mask-opaque), var(--lr-mask-opaque) calc(100% - var(--lr-scroll-fade-size)), transparent ); } [part~='segments'][data-scroll-overflow]:where( [data-scroll-start]:not([data-scroll-end]) ) { -webkit-mask-image: linear-gradient( to right, transparent, var(--lr-mask-opaque) var(--lr-scroll-fade-size), var(--lr-mask-opaque) ); mask-image: linear-gradient( to right, transparent, var(--lr-mask-opaque) var(--lr-scroll-fade-size), var(--lr-mask-opaque) ); } :host(:dir(rtl)) [part~='segments'][data-scroll-overflow]:where( [data-scroll-end]:not([data-scroll-start]) ) { -webkit-mask-image: linear-gradient( to right, transparent, var(--lr-mask-opaque) var(--lr-scroll-fade-size), var(--lr-mask-opaque) ); mask-image: linear-gradient( to right, transparent, var(--lr-mask-opaque) var(--lr-scroll-fade-size), var(--lr-mask-opaque) ); } :host(:dir(rtl)) [part~='segments'][data-scroll-overflow]:where( [data-scroll-start]:not([data-scroll-end]) ) { -webkit-mask-image: linear-gradient( to right, var(--lr-mask-opaque), var(--lr-mask-opaque) calc(100% - var(--lr-scroll-fade-size)), transparent ); mask-image: linear-gradient( to right, var(--lr-mask-opaque), var(--lr-mask-opaque) calc(100% - var(--lr-scroll-fade-size)), transparent ); } [part='control'] { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; margin: 0; padding: 0; border: none; background: none; color: transparent; caret-color: transparent; font: inherit; letter-spacing: 0; opacity: 0; cursor: text; } :host(:disabled) [part='control'] { cursor: not-allowed; } [part~='segment'] { display: flex; align-items: center; justify-content: center; box-sizing: border-box; flex: 0 0 auto; inline-size: var(--segment-size, var(--lr-otp-input-segment-size)); block-size: var(--segment-size, var(--lr-otp-input-segment-size)); padding: 0; border: var(--lr-border-width-thin) solid var(--lr-otp-input-segment-border-color, var(--_lr-otp-input-segment-border-color-default)); border-radius: var(--lr-otp-input-segment-radius, var(--_lr-otp-input-segment-radius-default)); background: var(--lr-otp-input-segment-fill, var(--_lr-otp-input-segment-fill-default)); color: var(--lr-color-text); font-variant-numeric: tabular-nums; font-size: var(--lr-form-control-font-size, var(--lr-font-size-m)); line-height: var(--lr-line-height-snug); transition: border-color var(--lr-transition-fast), box-shadow var(--lr-transition-fast); } [part~='active'] { border-color: var(--lr-otp-input-active-border-color, var(--lr-focus-ring-color)); box-shadow: 0 0 0 var(--lr-focus-ring-width) var(--lr-otp-input-active-ring-color, var(--lr-focus-ring-color)); } [part~='invalid'] { border-color: var(--lr-otp-input-invalid-border-color, var(--lr-color-danger)); } :host(:disabled) [part~='segment'] { opacity: var(--lr-opacity-disabled); } [part~='segment-literal'] { flex: 0 0 auto; color: var(--lr-color-text-quiet); user-select: none; } [part~='masked']::after, [part~='placeholder-mask']::after { content: var(--mask-char, var(--lr-otp-input-mask-char, var(--_lr-otp-input-mask-char-default))); } [part~='placeholder-mask'] { color: var(--lr-color-text-quiet); } [part='hint'] { font-size: var(--lr-font-size-sm); color: var(--lr-color-text-quiet); overflow-wrap: anywhere; } [part='error'] { font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); overflow-wrap: anywhere; } @media (prefers-reduced-motion: reduce) { [part~='segment'] { transition: none; } } `;export{styles};
|
|
@@ -93,6 +93,11 @@ inputValue:string;country:string;valid:boolean;status:LyraPhoneNumberStatus;}exp
|
|
|
93
93
|
* @slot hint - Custom hint content.
|
|
94
94
|
* @slot error - Custom error content.
|
|
95
95
|
* @slot country-prefix - Optional visual displayed before the country selector, such as a flag.
|
|
96
|
+
* @slot start - Alias for `country-prefix`, matching the leading-adornment slot name every other
|
|
97
|
+
* forms/ single-line field (`lr-input`, `lr-select`, `lr-combobox`, ...) uses. Content projected
|
|
98
|
+
* into either slot renders in the same wrapper before the country selector.
|
|
99
|
+
* @slot end - Optional trailing adornment after the telephone input, such as a paste or copy
|
|
100
|
+
* action, matching the trailing-adornment slot name every other forms/ single-line field uses.
|
|
96
101
|
* @event input - Native `InputEvent` fired for user edits and country changes.
|
|
97
102
|
* @event change - Native `Event` fired when the telephone input commits or the country changes.
|
|
98
103
|
* @event lr-input - Lyra input alias; detail contains the canonical and display values.
|
|
@@ -105,7 +110,9 @@ inputValue:string;country:string;valid:boolean;status:LyraPhoneNumberStatus;}exp
|
|
|
105
110
|
* @csspart form-control - The outer form-control wrapper.
|
|
106
111
|
* @csspart form-control-label - The visible label.
|
|
107
112
|
* @csspart input-wrapper - The country selector and telephone input wrapper.
|
|
108
|
-
* @csspart country-prefix - Optional country adornment slot wrapper
|
|
113
|
+
* @csspart country-prefix - Optional country adornment slot wrapper; also receives the `start`
|
|
114
|
+
* alias slot's projected content.
|
|
115
|
+
* @csspart end - Optional trailing adornment slot wrapper, after the telephone input.
|
|
109
116
|
* @csspart country - The country selector region (invisible native select over the visual trigger).
|
|
110
117
|
* @csspart country-select - The native country selector, stretched invisibly over the trigger.
|
|
111
118
|
* @csspart country-trigger - The visible, decorative closed-state trigger.
|
|
@@ -219,7 +226,7 @@ autocapitalize:string;
|
|
|
219
226
|
* `HTMLElement.autocorrect` IDL member, which would conflict with this `string`-typed reactive
|
|
220
227
|
* property; the explicit `attribute: 'autocorrect'` mapping preserves the standard lowercase
|
|
221
228
|
* `autocorrect` wire name in both Lit and the rendered attribute. */
|
|
222
|
-
autoCorrect:string;private inputElement?;private editableValue;private status;private touched;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private hasCountryPrefixSlot;private inputId;private hintId;private errorId;private explicitCountry;
|
|
229
|
+
autoCorrect:string;private inputElement?;private editableValue;private status;private touched;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private hasCountryPrefixSlot;private hasEndSlot;private inputId;private hintId;private errorId;private explicitCountry;
|
|
223
230
|
/** Currently selected ISO 3166-1 alpha-2 country code. */
|
|
224
231
|
get country():string;set country(next:string);
|
|
225
232
|
/** The underlying telephone input for platform-specific integrations. */
|
|
@@ -262,7 +269,7 @@ protected updateValidity():void;adoptedCallback():void;disconnectedCallback():vo
|
|
|
262
269
|
* more here than elsewhere: this field's `inputmode="tel"` keyboards are exactly the ones an IME
|
|
263
270
|
* candidate list sits on top of.
|
|
264
271
|
*/
|
|
265
|
-
private onKeyDown;private onFocus;private onBlur;private onLabelSlotChange;private onHintSlotChange;private onErrorSlotChange;private onCountryPrefixSlotChange;
|
|
272
|
+
private onKeyDown;private onFocus;private onBlur;private onLabelSlotChange;private onHintSlotChange;private onErrorSlotChange;private onCountryPrefixSlotChange;private onEndSlotChange;
|
|
266
273
|
/** Reads both component state and the UA's synchronous fieldset cascade before public actions. */
|
|
267
274
|
private get liveDisabled();
|
|
268
275
|
/** Activate the internal telephone input unless the form control is effectively disabled. */
|
|
@@ -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{observeReactivePropertyWrites}from"../../../internal/reactive-property-writes.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{declaredDefaultConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{resolveOptionalPeerCapability}from"../../../internal/optional-peer-capabilities.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_phoneInputLabel,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";function isLibphonenumberModule(candidate){const api=candidate;return(typeof api=="object"||typeof api=="function")&&api!==null&&typeof api.getCountries=="function"&&typeof api.getCountryCallingCode=="function"&&typeof api.parsePhoneNumberFromString=="function"}async function loadLibphonenumberAdapter(loader){const raw=await loader(),resolved=resolveOptionalPeerCapability(raw,isLibphonenumberModule);if(!resolved)throw new TypeError("Invalid optional peer for <lr-phone-input>: the module passed to loadLibphonenumberAdapter() does not expose the getCountries/getCountryCallingCode/parsePhoneNumberFromString capability libphonenumber-js provides.");const module=resolved;return{countries:Object.freeze(module.getCountries().map(code=>Object.freeze({code:normalizeCountry(code),callingCode:module.getCountryCallingCode(code)}))),parse(input,country){const raw2=input.trim();if(!raw2)return{status:"empty"};const normalizedCountry=country?normalizeCountry(country):void 0,phone=module.parsePhoneNumberFromString(raw2,normalizedCountry);if(!phone)return{status:module.validatePhoneNumberLength?.(raw2,normalizedCountry)==="TOO_SHORT"||isDialLike(raw2)?"incomplete":"invalid",formatted:raw2};const formatted=raw2.startsWith("+")?phone.formatInternational():phone.formatNational();if(phone.isValid())return{status:"valid",e164:phone.number,formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry};const length=module.validatePhoneNumberLength?.(raw2,normalizedCountry);return{status:length==="TOO_SHORT"||!length&&!phone.isPossible()?"incomplete":"invalid",formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}}}class LyraPhoneInputBase extends LyraElement{}const E164_RE=/^\+[1-9]\d{1,14}$/,DIAL_LIKE_RE=/^[+\d\s().-]+$/;function normalizeCountry(country){return country.trim().toUpperCase()}function isDialLike(value){return DIAL_LIKE_RE.test(value.trim())}function digitsBefore(value,index){let count=0;for(let i=0;i<index&&i<value.length;i++)/\d/.test(value[i])&&count++;return count}function indexAfterDigits(value,digitCount){if(digitCount<=0)return 0;let count=0;for(let i=0;i<value.length;i++)if(/\d/.test(value[i])&&(count++,count===digitCount))return i+1;return value.length}function fallbackParse(input){const raw=input.trim();if(!raw)return{status:"empty"};const compact=raw.replace(/[\s().-]/g,"");return E164_RE.test(compact)?{status:"valid",e164:compact,formatted:raw}:isDialLike(raw)?{status:"incomplete",formatted:raw}:{status:"invalid",formatted:raw}}function normalizeParseResult(result,input){try{if(result===null||typeof result!="object")return{status:"invalid",formatted:input};const record=result,status=record.status;if(status!=="empty"&&status!=="incomplete"&&status!=="invalid"&&status!=="valid")return{status:"invalid",formatted:input};const formatted=record.formatted;if(formatted!==void 0&&typeof formatted!="string")return{status:"invalid",formatted:input};const rawCountry=record.country;if(rawCountry!==void 0&&typeof rawCountry!="string")return{status:"invalid",formatted:formatted??input};const country=typeof rawCountry=="string"&&/^[A-Za-z]{2}$/.test(rawCountry.trim())?normalizeCountry(rawCountry):void 0,metadata={...formatted===void 0?{}:{formatted},...country===void 0?{}:{country}};if(status==="valid"){const e164=record.e164;return typeof e164!="string"||!E164_RE.test(e164)?{status:"invalid",formatted:formatted??input,...country?{country}:{}}:{status,e164,...metadata}}return{status,...metadata}}catch{return{status:"invalid",formatted:input}}}const MAX_PHONE_COUNTRIES=512;function normalizeCountryCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[],seen=new Set;let length=0;try{length=Math.min(source.length,MAX_PHONE_COUNTRIES)}catch{return Object.freeze(rows)}for(let index=0;index<length;index+=1)try{const item=source[index];if(item===null||typeof item!="object")continue;const candidate=item,rawCode=candidate.code,rawCallingCode=candidate.callingCode,rawLabel=candidate.label;if(typeof rawCode!="string"||typeof rawCallingCode!="string")continue;const code=normalizeCountry(rawCode),callingCode=rawCallingCode.replace(/^\+/,"");if(!/^[A-Z]{2}$/.test(code)||!/^[1-9]\d{0,2}$/.test(callingCode)||seen.has(code)||rawLabel!==void 0&&typeof rawLabel!="string")continue;seen.add(code),rows.push(Object.freeze({code,callingCode,...rawLabel===void 0?{}:{label:rawLabel}}))}catch{}return Object.freeze(rows)}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){constructor(){super(...arguments),this.flags=!1,this.adapterCountries=Object.freeze([]),this.defaultCountry="",this.label="",this.hint="",this.errorText="",this.placeholder="",this.size="m",this.pill=!1,this.accessibleLabel=null,this.countryLabel="Select",this.countryLabelAuthored=!1,this.phoneLabel="",this.incompleteText="This phone number is incomplete.",this.incompleteTextAuthored=!1,this.invalidText="The value is invalid.",this.invalidTextAuthored=!1,this.autocomplete="tel",this.inputmode="tel",this.enterkeyhint="",this.readonly=!1,this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.editableValue="",this.status="empty",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasCountryPrefixSlot=!1,this.inputId=nextId("phone-input"),this.hintId=nextId("phone-hint"),this.errorId=nextId("phone-error"),this.explicitCountry="",this.onInput=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}const input=event.currentTarget,caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret),relayNativeEvent(this,event),this.emit("lr-input",this.eventDetail)},this.onChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.touched=!0,relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onCountryChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.country=normalizeCountry(event.currentTarget.value),this.applyParsed(this.editableValue,this.parse(this.editableValue)),dispatchNativeInputEvent(this),this.emit("lr-input",this.eventDetail),relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onKeyDown=event=>{this.liveDisabled||submitOnEnter(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onLabelSlotChange=()=>{this.hasLabelSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="label")},this.onHintSlotChange=()=>{this.hasHintSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="hint")},this.onErrorSlotChange=()=>{this.hasErrorSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="error")},this.onCountryPrefixSlotChange=()=>{this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix")}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,phoneInputLabel:LYRA_DEFAULT_phoneInputLabel,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:!0}}}get adapter(){return this._adapter}set adapter(next){const previous=this._adapter;this._adapter=next,this.adapterCountries=normalizeCountryCatalog(next?.countries),this.requestUpdate("adapter",previous)}get countries(){return this._countries}set countries(next){const previous=this._countries;this._countries=next===void 0?void 0:normalizeCountryCatalog(next),this.requestUpdate("countries",previous)}get country(){return this.resolveCountry(this.availableCountries)}set country(next){const old=this.country;this.explicitCountry=normalizeCountry(next??""),this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"",parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){return this.countries??this.adapterCountries}resolveCountry(rows){const codes=rows.map(row=>row.code),explicit=normalizeCountry(this.explicitCountry),preferred=normalizeCountry(this.defaultCountry??"");return codes.includes(explicit)?explicit:codes.includes(preferred)?preferred:codes[0]??""}parse(input){if(!this.adapter)return fallbackParse(input);try{const parse=this.adapter.parse;return typeof parse!="function"?{status:"invalid",formatted:input}:normalizeParseResult(parse.call(this.adapter,input,this.country||void 0),input)}catch{return{status:"invalid",formatted:input}}}reconcileCountryCatalog(){this.explicitCountry=this.resolveCountry(this.availableCountries)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw,this.status=parsed.status,parsed.country&&(this.country=normalizeCountry(parsed.country)),super.value=parsed.status==="valid"?parsed.e164:"",this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value!==this.editableValue&&(input.value=this.editableValue,digitsBeforeCaret!=null)){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}static get observedAttributes(){const attributes=super.observedAttributes;return observeReactivePropertyWrites(this.prototype,["countryLabel","incompleteText","invalidText"],(instance,name,value)=>{const authored=value!=null;let ownershipChanged=!1;switch(name){case"countryLabel":if(instance.countryLabelAuthored===void 0)return;ownershipChanged=authored!==instance.countryLabelAuthored,instance.countryLabelAuthored=authored;break;case"incompleteText":if(instance.incompleteTextAuthored===void 0)return;ownershipChanged=authored!==instance.incompleteTextAuthored,instance.incompleteTextAuthored=authored;break;case"invalidText":if(instance.invalidTextAuthored===void 0)return;ownershipChanged=authored!==instance.invalidTextAuthored,instance.invalidTextAuthored=authored;break}ownershipChanged&&instance.requestUpdate(),name!=="countryLabel"&&instance.hasUpdated&&instance.updateValidity()}),attributes}attributeChangedCallback(name,oldValue,newValue){if(super.attributeChangedCallback(name,oldValue,newValue),newValue===null){if(name==="country-label")this.countryLabelAuthored=!1;else if(name==="incomplete-text")this.incompleteTextAuthored=!1;else if(name==="invalid-text")this.invalidTextAuthored=!1;else return;this.requestUpdate(),this.hasUpdated&&this.updateValidity()}}get effectiveCountryLabel(){return this.countryLabelAuthored?this.countryLabel:this.localize("select")}effectivePhoneLabel(hasLabel){return this.accessibleLabel!==null?this.accessibleLabel:this.phoneLabel?this.phoneLabel:hasLabel?nothing:this.placeholder||this.localize("phoneInputLabel")}get incompleteMessage(){return(this.incompleteTextAuthored?this.incompleteText:"")||this.localize("phoneInputIncomplete")}get invalidMessage(){return(this.invalidTextAuthored?this.invalidText:"")||this.localize("valueInvalid")}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.status==="empty"?(flags.valueMissing=!0,message=this.localize("fieldRequired")):this.status==="incomplete"?(flags.badInput=!0,message=this.incompleteMessage):this.status==="invalid"&&(flags.typeMismatch=!0,message=this.invalidMessage),this[SET_ANCHORED_VALIDITY](flags,message)}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}syncExternalDescription(){if(!this.isConnected)return;const target=this.inputElement??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}willUpdate(changed){super.willUpdate(changed),this.flags&&!LyraPhoneInput.flagRegistration&&(LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})),this.hasUpdated||(this.hasLabelSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="error"),this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix")),(!this.hasUpdated||changed.has("countries")||changed.has("adapter")||changed.has("country")||changed.has("defaultCountry"))&&this.reconcileCountryCatalog(),(changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue&&this.applyParsed(this.editableValue,this.parse(this.editableValue))}updated(changed){if(super.updated(changed),this.syncExternalDescription(),changed.has("strings")&&this.updateValidity(),changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status")){const invalid=this.touched&&!this.internals.validity.valid;this.toggleAttribute("data-invalid",invalid),invalid?this.setAttribute("aria-invalid","true"):this.removeAttribute("aria-invalid")}}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode);const caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.explicitCountry="",this.reconcileCountryCatalog(),super.formResetCallback(),this.touched=!1}render(){const hasLabel=!!(this.label||this.hasLabelSlot),validationError=this.touched?this.validationMessage:"",renderedError=this.errorText||validationError,hasHint=!!(this.hint||this.hasHintSlot),hasError=!!(renderedError||this.hasErrorSlot),describedBy=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" "),rows=this.availableCountries,current=rows.find(row=>row.code===this.country);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{observeReactivePropertyWrites}from"../../../internal/reactive-property-writes.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{declaredDefaultConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{resolveOptionalPeerCapability}from"../../../internal/optional-peer-capabilities.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_phoneInputLabel,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";function isLibphonenumberModule(candidate){const api=candidate;return(typeof api=="object"||typeof api=="function")&&api!==null&&typeof api.getCountries=="function"&&typeof api.getCountryCallingCode=="function"&&typeof api.parsePhoneNumberFromString=="function"}async function loadLibphonenumberAdapter(loader){const raw=await loader(),resolved=resolveOptionalPeerCapability(raw,isLibphonenumberModule);if(!resolved)throw new TypeError("Invalid optional peer for <lr-phone-input>: the module passed to loadLibphonenumberAdapter() does not expose the getCountries/getCountryCallingCode/parsePhoneNumberFromString capability libphonenumber-js provides.");const module=resolved;return{countries:Object.freeze(module.getCountries().map(code=>Object.freeze({code:normalizeCountry(code),callingCode:module.getCountryCallingCode(code)}))),parse(input,country){const raw2=input.trim();if(!raw2)return{status:"empty"};const normalizedCountry=country?normalizeCountry(country):void 0,phone=module.parsePhoneNumberFromString(raw2,normalizedCountry);if(!phone)return{status:module.validatePhoneNumberLength?.(raw2,normalizedCountry)==="TOO_SHORT"||isDialLike(raw2)?"incomplete":"invalid",formatted:raw2};const formatted=raw2.startsWith("+")?phone.formatInternational():phone.formatNational();if(phone.isValid())return{status:"valid",e164:phone.number,formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry};const length=module.validatePhoneNumberLength?.(raw2,normalizedCountry);return{status:length==="TOO_SHORT"||!length&&!phone.isPossible()?"incomplete":"invalid",formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}}}class LyraPhoneInputBase extends LyraElement{}const E164_RE=/^\+[1-9]\d{1,14}$/,DIAL_LIKE_RE=/^[+\d\s().-]+$/;function normalizeCountry(country){return country.trim().toUpperCase()}function isDialLike(value){return DIAL_LIKE_RE.test(value.trim())}function digitsBefore(value,index){let count=0;for(let i=0;i<index&&i<value.length;i++)/\d/.test(value[i])&&count++;return count}function indexAfterDigits(value,digitCount){if(digitCount<=0)return 0;let count=0;for(let i=0;i<value.length;i++)if(/\d/.test(value[i])&&(count++,count===digitCount))return i+1;return value.length}function fallbackParse(input){const raw=input.trim();if(!raw)return{status:"empty"};const compact=raw.replace(/[\s().-]/g,"");return E164_RE.test(compact)?{status:"valid",e164:compact,formatted:raw}:isDialLike(raw)?{status:"incomplete",formatted:raw}:{status:"invalid",formatted:raw}}function normalizeParseResult(result,input){try{if(result===null||typeof result!="object")return{status:"invalid",formatted:input};const record=result,status=record.status;if(status!=="empty"&&status!=="incomplete"&&status!=="invalid"&&status!=="valid")return{status:"invalid",formatted:input};const formatted=record.formatted;if(formatted!==void 0&&typeof formatted!="string")return{status:"invalid",formatted:input};const rawCountry=record.country;if(rawCountry!==void 0&&typeof rawCountry!="string")return{status:"invalid",formatted:formatted??input};const country=typeof rawCountry=="string"&&/^[A-Za-z]{2}$/.test(rawCountry.trim())?normalizeCountry(rawCountry):void 0,metadata={...formatted===void 0?{}:{formatted},...country===void 0?{}:{country}};if(status==="valid"){const e164=record.e164;return typeof e164!="string"||!E164_RE.test(e164)?{status:"invalid",formatted:formatted??input,...country?{country}:{}}:{status,e164,...metadata}}return{status,...metadata}}catch{return{status:"invalid",formatted:input}}}const MAX_PHONE_COUNTRIES=512;function normalizeCountryCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[],seen=new Set;let length=0;try{length=Math.min(source.length,MAX_PHONE_COUNTRIES)}catch{return Object.freeze(rows)}for(let index=0;index<length;index+=1)try{const item=source[index];if(item===null||typeof item!="object")continue;const candidate=item,rawCode=candidate.code,rawCallingCode=candidate.callingCode,rawLabel=candidate.label;if(typeof rawCode!="string"||typeof rawCallingCode!="string")continue;const code=normalizeCountry(rawCode),callingCode=rawCallingCode.replace(/^\+/,"");if(!/^[A-Z]{2}$/.test(code)||!/^[1-9]\d{0,2}$/.test(callingCode)||seen.has(code)||rawLabel!==void 0&&typeof rawLabel!="string")continue;seen.add(code),rows.push(Object.freeze({code,callingCode,...rawLabel===void 0?{}:{label:rawLabel}}))}catch{}return Object.freeze(rows)}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){constructor(){super(...arguments),this.flags=!1,this.adapterCountries=Object.freeze([]),this.defaultCountry="",this.label="",this.hint="",this.errorText="",this.placeholder="",this.size="m",this.pill=!1,this.accessibleLabel=null,this.countryLabel="Select",this.countryLabelAuthored=!1,this.phoneLabel="",this.incompleteText="This phone number is incomplete.",this.incompleteTextAuthored=!1,this.invalidText="The value is invalid.",this.invalidTextAuthored=!1,this.autocomplete="tel",this.inputmode="tel",this.enterkeyhint="",this.readonly=!1,this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.editableValue="",this.status="empty",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasCountryPrefixSlot=!1,this.hasEndSlot=!1,this.inputId=nextId("phone-input"),this.hintId=nextId("phone-hint"),this.errorId=nextId("phone-error"),this.explicitCountry="",this.onInput=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}const input=event.currentTarget,caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret),relayNativeEvent(this,event),this.emit("lr-input",this.eventDetail)},this.onChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.touched=!0,relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onCountryChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.country=normalizeCountry(event.currentTarget.value),this.applyParsed(this.editableValue,this.parse(this.editableValue)),dispatchNativeInputEvent(this),this.emit("lr-input",this.eventDetail),relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onKeyDown=event=>{this.liveDisabled||submitOnEnter(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onLabelSlotChange=()=>{this.hasLabelSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="label")},this.onHintSlotChange=()=>{this.hasHintSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="hint")},this.onErrorSlotChange=()=>{this.hasErrorSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="error")},this.onCountryPrefixSlotChange=()=>{this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix"||child.getAttribute("slot")==="start")},this.onEndSlotChange=()=>{this.hasEndSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="end")}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,phoneInputLabel:LYRA_DEFAULT_phoneInputLabel,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:!0}}}get adapter(){return this._adapter}set adapter(next){const previous=this._adapter;this._adapter=next,this.adapterCountries=normalizeCountryCatalog(next?.countries),this.requestUpdate("adapter",previous)}get countries(){return this._countries}set countries(next){const previous=this._countries;this._countries=next===void 0?void 0:normalizeCountryCatalog(next),this.requestUpdate("countries",previous)}get country(){return this.resolveCountry(this.availableCountries)}set country(next){const old=this.country;this.explicitCountry=normalizeCountry(next??""),this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"",parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){return this.countries??this.adapterCountries}resolveCountry(rows){const codes=rows.map(row=>row.code),explicit=normalizeCountry(this.explicitCountry),preferred=normalizeCountry(this.defaultCountry??"");return codes.includes(explicit)?explicit:codes.includes(preferred)?preferred:codes[0]??""}parse(input){if(!this.adapter)return fallbackParse(input);try{const parse=this.adapter.parse;return typeof parse!="function"?{status:"invalid",formatted:input}:normalizeParseResult(parse.call(this.adapter,input,this.country||void 0),input)}catch{return{status:"invalid",formatted:input}}}reconcileCountryCatalog(){this.explicitCountry=this.resolveCountry(this.availableCountries)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw,this.status=parsed.status,parsed.country&&(this.country=normalizeCountry(parsed.country)),super.value=parsed.status==="valid"?parsed.e164:"",this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value!==this.editableValue&&(input.value=this.editableValue,digitsBeforeCaret!=null)){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}static get observedAttributes(){const attributes=super.observedAttributes;return observeReactivePropertyWrites(this.prototype,["countryLabel","incompleteText","invalidText"],(instance,name,value)=>{const authored=value!=null;let ownershipChanged=!1;switch(name){case"countryLabel":if(instance.countryLabelAuthored===void 0)return;ownershipChanged=authored!==instance.countryLabelAuthored,instance.countryLabelAuthored=authored;break;case"incompleteText":if(instance.incompleteTextAuthored===void 0)return;ownershipChanged=authored!==instance.incompleteTextAuthored,instance.incompleteTextAuthored=authored;break;case"invalidText":if(instance.invalidTextAuthored===void 0)return;ownershipChanged=authored!==instance.invalidTextAuthored,instance.invalidTextAuthored=authored;break}ownershipChanged&&instance.requestUpdate(),name!=="countryLabel"&&instance.hasUpdated&&instance.updateValidity()}),attributes}attributeChangedCallback(name,oldValue,newValue){if(super.attributeChangedCallback(name,oldValue,newValue),newValue===null){if(name==="country-label")this.countryLabelAuthored=!1;else if(name==="incomplete-text")this.incompleteTextAuthored=!1;else if(name==="invalid-text")this.invalidTextAuthored=!1;else return;this.requestUpdate(),this.hasUpdated&&this.updateValidity()}}get effectiveCountryLabel(){return this.countryLabelAuthored?this.countryLabel:this.localize("select")}effectivePhoneLabel(hasLabel){return this.accessibleLabel!==null?this.accessibleLabel:this.phoneLabel?this.phoneLabel:hasLabel?nothing:this.placeholder||this.localize("phoneInputLabel")}get incompleteMessage(){return(this.incompleteTextAuthored?this.incompleteText:"")||this.localize("phoneInputIncomplete")}get invalidMessage(){return(this.invalidTextAuthored?this.invalidText:"")||this.localize("valueInvalid")}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.status==="empty"?(flags.valueMissing=!0,message=this.localize("fieldRequired")):this.status==="incomplete"?(flags.badInput=!0,message=this.incompleteMessage):this.status==="invalid"&&(flags.typeMismatch=!0,message=this.invalidMessage),this[SET_ANCHORED_VALIDITY](flags,message)}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}syncExternalDescription(){if(!this.isConnected)return;const target=this.inputElement??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}willUpdate(changed){super.willUpdate(changed),this.flags&&!LyraPhoneInput.flagRegistration&&(LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasLabelSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="error"),this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix"||child.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="end")}),(!this.hasUpdated||changed.has("countries")||changed.has("adapter")||changed.has("country")||changed.has("defaultCountry"))&&this.reconcileCountryCatalog(),(changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue&&this.applyParsed(this.editableValue,this.parse(this.editableValue))}updated(changed){if(super.updated(changed),this.syncExternalDescription(),changed.has("strings")&&this.updateValidity(),changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status")){const invalid=this.touched&&!this.internals.validity.valid;this.toggleAttribute("data-invalid",invalid),invalid?this.setAttribute("aria-invalid","true"):this.removeAttribute("aria-invalid")}}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode);const caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.explicitCountry="",this.reconcileCountryCatalog(),super.formResetCallback(),this.touched=!1}render(){const hasLabel=!!(this.label||this.hasLabelSlot),validationError=this.touched?this.validationMessage:"",renderedError=this.errorText||validationError,hasHint=!!(this.hint||this.hasHintSlot),hasError=!!(renderedError||this.hasErrorSlot),describedBy=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" "),rows=this.availableCountries,current=rows.find(row=>row.code===this.country);return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for=${this.inputId} ?hidden=${!hasLabel}>
|
|
4
4
|
<slot name="label" @slotchange=${this.onLabelSlotChange}>${this.label}</slot>
|
|
@@ -6,6 +6,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
6
6
|
<div part="input-wrapper">
|
|
7
7
|
<span part="country-prefix" ?hidden=${!this.hasCountryPrefixSlot}>
|
|
8
8
|
<slot name="country-prefix" @slotchange=${this.onCountryPrefixSlotChange}></slot>
|
|
9
|
+
<slot name="start" @slotchange=${this.onCountryPrefixSlotChange}></slot>
|
|
9
10
|
</span>
|
|
10
11
|
<span part="country">
|
|
11
12
|
<select
|
|
@@ -54,6 +55,9 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
54
55
|
@focus=${this.onFocus}
|
|
55
56
|
@blur=${this.onBlur}
|
|
56
57
|
/>
|
|
58
|
+
<span part="end" ?hidden=${!this.hasEndSlot}>
|
|
59
|
+
<slot name="end" @slotchange=${this.onEndSlotChange}></slot>
|
|
60
|
+
</span>
|
|
57
61
|
</div>
|
|
58
62
|
<div id=${this.hintId} part="hint" ?hidden=${!hasHint}>
|
|
59
63
|
<slot name="hint" @slotchange=${this.onHintSlotChange}>${this.hint}</slot>
|
|
@@ -62,4 +66,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
62
66
|
<slot name="error" @slotchange=${this.onErrorSlotChange}>${renderedError}</slot>
|
|
63
67
|
</div>
|
|
64
68
|
</div>
|
|
65
|
-
`}}__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"flags",void 0),__decorate([property({attribute:!1})],LyraPhoneInput.prototype,"adapter",null),__decorate([property({attribute:!1})],LyraPhoneInput.prototype,"countries",null),__decorate([property({attribute:"default-country"})],LyraPhoneInput.prototype,"defaultCountry",void 0),__decorate([property()],LyraPhoneInput.prototype,"label",void 0),__decorate([property()],LyraPhoneInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraPhoneInput.prototype,"errorText",void 0),__decorate([property()],LyraPhoneInput.prototype,"placeholder",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("m")})],LyraPhoneInput.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"pill",void 0),__decorate([property({attribute:"aria-label"})],LyraPhoneInput.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"country-label",useDefault:!0})],LyraPhoneInput.prototype,"countryLabel",void 0),__decorate([property({attribute:"phone-label"})],LyraPhoneInput.prototype,"phoneLabel",void 0),__decorate([property({attribute:"incomplete-text",useDefault:!0})],LyraPhoneInput.prototype,"incompleteText",void 0),__decorate([property({attribute:"invalid-text",useDefault:!0})],LyraPhoneInput.prototype,"invalidText",void 0),__decorate([property({useDefault:!0})],LyraPhoneInput.prototype,"autocomplete",void 0),__decorate([property({useDefault:!0})],LyraPhoneInput.prototype,"inputmode",void 0),__decorate([property()],LyraPhoneInput.prototype,"enterkeyhint",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"readonly",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"autofocus",void 0),__decorate([property({converter:spellcheckConverter})],LyraPhoneInput.prototype,"spellcheck",void 0),__decorate([property()],LyraPhoneInput.prototype,"autocapitalize",void 0),__decorate([property({attribute:"autocorrect"})],LyraPhoneInput.prototype,"autoCorrect",void 0),__decorate([query('input[part="input"]')],LyraPhoneInput.prototype,"inputElement",void 0),__decorate([state()],LyraPhoneInput.prototype,"editableValue",void 0),__decorate([state()],LyraPhoneInput.prototype,"status",void 0),__decorate([state()],LyraPhoneInput.prototype,"touched",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasCountryPrefixSlot",void 0);export{LyraPhoneInput,loadLibphonenumberAdapter};
|
|
69
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"flags",void 0),__decorate([property({attribute:!1})],LyraPhoneInput.prototype,"adapter",null),__decorate([property({attribute:!1})],LyraPhoneInput.prototype,"countries",null),__decorate([property({attribute:"default-country"})],LyraPhoneInput.prototype,"defaultCountry",void 0),__decorate([property()],LyraPhoneInput.prototype,"label",void 0),__decorate([property()],LyraPhoneInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraPhoneInput.prototype,"errorText",void 0),__decorate([property()],LyraPhoneInput.prototype,"placeholder",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("m")})],LyraPhoneInput.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"pill",void 0),__decorate([property({attribute:"aria-label"})],LyraPhoneInput.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"country-label",useDefault:!0})],LyraPhoneInput.prototype,"countryLabel",void 0),__decorate([property({attribute:"phone-label"})],LyraPhoneInput.prototype,"phoneLabel",void 0),__decorate([property({attribute:"incomplete-text",useDefault:!0})],LyraPhoneInput.prototype,"incompleteText",void 0),__decorate([property({attribute:"invalid-text",useDefault:!0})],LyraPhoneInput.prototype,"invalidText",void 0),__decorate([property({useDefault:!0})],LyraPhoneInput.prototype,"autocomplete",void 0),__decorate([property({useDefault:!0})],LyraPhoneInput.prototype,"inputmode",void 0),__decorate([property()],LyraPhoneInput.prototype,"enterkeyhint",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"readonly",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraPhoneInput.prototype,"autofocus",void 0),__decorate([property({converter:spellcheckConverter})],LyraPhoneInput.prototype,"spellcheck",void 0),__decorate([property()],LyraPhoneInput.prototype,"autocapitalize",void 0),__decorate([property({attribute:"autocorrect"})],LyraPhoneInput.prototype,"autoCorrect",void 0),__decorate([query('input[part="input"]')],LyraPhoneInput.prototype,"inputElement",void 0),__decorate([state()],LyraPhoneInput.prototype,"editableValue",void 0),__decorate([state()],LyraPhoneInput.prototype,"status",void 0),__decorate([state()],LyraPhoneInput.prototype,"touched",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasCountryPrefixSlot",void 0),__decorate([state()],LyraPhoneInput.prototype,"hasEndSlot",void 0);export{LyraPhoneInput,loadLibphonenumberAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; min-inline-size: 0; --_lr-phone-input-padding-block-default: var(--lr-form-control-padding-block); --_lr-phone-input-font-size-default: var(--lr-font-size-md-sm); --_lr-phone-input-flag-size-default: var(--lr-font-size-lg); --_lr-phone-input-glyph-size-default: var(--lr-font-size-md-sm); --_lr-phone-input-gap-default: var(--lr-space-xs); --_lr-phone-input-radius-default: var(--lr-radius); --_lr-phone-input-control-min-height-default: var(--lr-form-control-height); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([pill]) { --_lr-phone-input-radius-default: var(--lr-radius-pill); } :host([size='2xs']) { --_lr-phone-input-font-size-default: var(--lr-font-size-2xs); --_lr-phone-input-flag-size-default: var(--lr-font-size-sm); --_lr-phone-input-glyph-size-default: var(--lr-font-size-2xs); } :host([size='xs']) { --_lr-phone-input-font-size-default: var(--lr-font-size-xs); --_lr-phone-input-flag-size-default: var(--lr-font-size-md-sm); --_lr-phone-input-glyph-size-default: var(--lr-font-size-xs); } :host([size='s']), :host([size='small']) { --_lr-phone-input-font-size-default: var(--lr-font-size-sm); --_lr-phone-input-flag-size-default: var(--lr-font-size-m); --_lr-phone-input-glyph-size-default: var(--lr-font-size-sm); } :host([size='l']), :host([size='large']) { --_lr-phone-input-font-size-default: var(--lr-font-size-lg); --_lr-phone-input-flag-size-default: var(--lr-font-size-xl); --_lr-phone-input-glyph-size-default: var(--lr-font-size-lg); } :host([size='xl']) { --_lr-phone-input-font-size-default: var(--lr-font-size-xl); --_lr-phone-input-flag-size-default: var(--lr-font-size-2xl); --_lr-phone-input-glyph-size-default: var(--lr-font-size-xl); } [part='form-control'] { min-inline-size: 0; } [part='form-control-label'] { display: block; margin-block-end: var(--lr-space-xs); color: var(--lr-color-text); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); } [part='form-control-label'][hidden], [part='country-prefix'][hidden], [part='hint'][hidden], [part='error'][hidden] { display: none; } ${formControlRequiredMarker} [part='input-wrapper'] { display: flex; align-items: center; box-sizing: border-box; min-inline-size: 0; inline-size: 100%; min-block-size: var(--lr-phone-input-control-height, var(--lr-phone-input-control-min-height, var(--_lr-phone-input-control-min-height-default))); block-size: var(--lr-phone-input-control-height, auto); font-size: var(--lr-phone-input-font-size, var(--_lr-phone-input-font-size-default)); border: var(--lr-border-width-thin) solid var(--lr-phone-input-border-color, var(--lr-color-border)); border-radius: var(--lr-phone-input-radius, var(--_lr-phone-input-radius-default)); background: var(--lr-phone-input-fill, var(--lr-color-surface)); color: var(--lr-color-text); } [part='input-wrapper']:focus-within { border-color: var(--lr-phone-input-focus-border-color, var(--lr-color-brand)); outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); ${formControlFocusHalo} } :host([data-invalid]) [part='input-wrapper'] { border-color: var(--lr-phone-input-invalid-border-color, var(--lr-color-danger)); } :host(:disabled) [part='input-wrapper'] { cursor: not-allowed; opacity: var(--lr-opacity-disabled); } [part='country-prefix'] { display: inline-flex; flex: 0 0 auto; align-items: center; padding-inline-start: var(--lr-space-s); } [part='country'] { position: relative; display: inline-flex; align-items: stretch; flex: 0 0 auto; align-self: stretch; min-block-size: var(--lr-icon-button-size); border-inline-end: var(--lr-border-width-thin) solid var(--lr-color-border); } [part='country-select'] { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; margin: 0; padding: 0; border: none; appearance: none; opacity: 0; color: inherit; font: inherit; cursor: pointer; } [part='country-select']:disabled { cursor: not-allowed; } [part='country-select'] option { background: var(--lr-color-surface); color: var(--lr-color-text); } [part='country-trigger'] { display: inline-flex; align-items: center; gap: var(--lr-phone-input-gap, var(--_lr-phone-input-gap-default)); padding-inline: var(--lr-space-s); border-start-start-radius: var(--lr-phone-input-radius, var(--_lr-phone-input-radius-default)); border-end-start-radius: var(--lr-phone-input-radius, var(--_lr-phone-input-radius-default)); transition: background-color var(--lr-transition-fast); } [part='country-select']:not(:disabled):hover + [part='country-trigger'] { background: var(--lr-phone-input-country-hover-bg, var(--lr-color-brand-quiet)); } [part='country-select']:not(:disabled):active + [part='country-trigger'] { background: color-mix( in oklab, var(--lr-phone-input-country-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='country-select']:focus-visible + [part='country-trigger'] { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part='flag'] { font-size: var(--lr-phone-input-flag-size, var(--_lr-phone-input-flag-size-default)); } [part='country-code'] { font-size: var(--lr-phone-input-font-size, var(--_lr-phone-input-font-size-default)); font-weight: var(--lr-font-weight-semibold); } [part='country-code'][data-placeholder] { color: var(--lr-color-text-quiet); font-weight: var(--lr-font-weight-normal); } [part='expand-icon'] { display: inline-flex; align-items: center; justify-content: center; color: var(--lr-color-text-quiet); font-size: var(--lr-phone-input-glyph-size, var(--_lr-phone-input-glyph-size-default)); line-height: var(--lr-line-height-none); } [part='expand-icon'] svg { transform: rotate(90deg); } [part='input']:focus { outline: none; } [part='calling-code'] { flex: 0 0 auto; padding-inline-start: var(--lr-space-s); color: var(--lr-color-text-quiet); direction: ltr; font-size: var(--lr-phone-input-font-size, var(--_lr-phone-input-font-size-default)); unicode-bidi: isolate; } [part='input'] { flex: 1 1 auto; min-inline-size: 0; inline-size: 100%; padding-block: var(--lr-phone-input-padding-block, var(--_lr-phone-input-padding-block-default)); padding-inline: var(--lr-space-s); border: none; background: transparent; color: inherit; font: inherit; text-align: start; } [part='input']::placeholder { color: var(--lr-color-text-quiet); } [part='hint'], [part='error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); } [part='hint'] { color: var(--lr-color-text-quiet); } [part='error'] { color: var(--lr-color-danger); } @media (forced-colors: active) { [part='country-select']:not(:disabled):hover + [part='country-trigger'] { outline-color: Highlight; outline-style: dashed; outline-width: var(--lr-border-width-thin); outline-offset: calc(-1 * var(--lr-border-width-thin)); } [part='country-select']:not(:disabled):active + [part='country-trigger'] { outline-color: Highlight; outline-style: solid; outline-width: var(--lr-border-width-thick); outline-offset: calc(-1 * var(--lr-border-width-thick)); } } [part='form-control'], [part='form-control-label'], [part='hint'], [part='error'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } `;export{styles};
|
|
1
|
+
import{css}from"lit";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; min-inline-size: 0; --_lr-phone-input-padding-block-default: var(--lr-form-control-padding-block); --_lr-phone-input-font-size-default: var(--lr-font-size-md-sm); --_lr-phone-input-flag-size-default: var(--lr-font-size-lg); --_lr-phone-input-glyph-size-default: var(--lr-font-size-md-sm); --_lr-phone-input-gap-default: var(--lr-space-xs); --_lr-phone-input-radius-default: var(--lr-radius); --_lr-phone-input-control-min-height-default: var(--lr-form-control-height); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([pill]) { --_lr-phone-input-radius-default: var(--lr-radius-pill); } :host([size='2xs']) { --_lr-phone-input-font-size-default: var(--lr-font-size-2xs); --_lr-phone-input-flag-size-default: var(--lr-font-size-sm); --_lr-phone-input-glyph-size-default: var(--lr-font-size-2xs); } :host([size='xs']) { --_lr-phone-input-font-size-default: var(--lr-font-size-xs); --_lr-phone-input-flag-size-default: var(--lr-font-size-md-sm); --_lr-phone-input-glyph-size-default: var(--lr-font-size-xs); } :host([size='s']), :host([size='small']) { --_lr-phone-input-font-size-default: var(--lr-font-size-sm); --_lr-phone-input-flag-size-default: var(--lr-font-size-m); --_lr-phone-input-glyph-size-default: var(--lr-font-size-sm); } :host([size='l']), :host([size='large']) { --_lr-phone-input-font-size-default: var(--lr-font-size-lg); --_lr-phone-input-flag-size-default: var(--lr-font-size-xl); --_lr-phone-input-glyph-size-default: var(--lr-font-size-lg); } :host([size='xl']) { --_lr-phone-input-font-size-default: var(--lr-font-size-xl); --_lr-phone-input-flag-size-default: var(--lr-font-size-2xl); --_lr-phone-input-glyph-size-default: var(--lr-font-size-xl); } [part='form-control'] { min-inline-size: 0; } [part='form-control-label'] { display: block; margin-block-end: var(--lr-space-xs); color: var(--lr-color-text); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); } [part='form-control-label'][hidden], [part='country-prefix'][hidden], [part='end'][hidden], [part='hint'][hidden], [part='error'][hidden] { display: none; } ${formControlRequiredMarker} [part='input-wrapper'] { display: flex; align-items: center; box-sizing: border-box; min-inline-size: 0; inline-size: 100%; min-block-size: var(--lr-phone-input-control-height, var(--lr-phone-input-control-min-height, var(--_lr-phone-input-control-min-height-default))); block-size: var(--lr-phone-input-control-height, auto); font-size: var(--lr-phone-input-font-size, var(--_lr-phone-input-font-size-default)); border: var(--lr-border-width-thin) solid var(--lr-phone-input-border-color, var(--lr-color-border)); border-radius: var(--lr-phone-input-radius, var(--_lr-phone-input-radius-default)); background: var(--lr-phone-input-fill, var(--lr-color-surface)); color: var(--lr-color-text); } [part='input-wrapper']:focus-within { border-color: var(--lr-phone-input-focus-border-color, var(--lr-color-brand)); outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); ${formControlFocusHalo} } :host([data-invalid]) [part='input-wrapper'] { border-color: var(--lr-phone-input-invalid-border-color, var(--lr-color-danger)); } :host(:disabled) [part='input-wrapper'] { cursor: not-allowed; opacity: var(--lr-opacity-disabled); } [part='country-prefix'] { display: inline-flex; flex: 0 0 auto; align-items: center; padding-inline-start: var(--lr-space-s); } [part='country'] { position: relative; display: inline-flex; align-items: stretch; flex: 0 0 auto; align-self: stretch; min-block-size: var(--lr-icon-button-size); border-inline-end: var(--lr-border-width-thin) solid var(--lr-color-border); } [part='country-select'] { position: absolute; inset: 0; inline-size: 100%; block-size: 100%; margin: 0; padding: 0; border: none; appearance: none; opacity: 0; color: inherit; font: inherit; cursor: pointer; } [part='country-select']:disabled { cursor: not-allowed; } [part='country-select'] option { background: var(--lr-color-surface); color: var(--lr-color-text); } [part='country-trigger'] { display: inline-flex; align-items: center; gap: var(--lr-phone-input-gap, var(--_lr-phone-input-gap-default)); padding-inline: var(--lr-space-s); border-start-start-radius: var(--lr-phone-input-radius, var(--_lr-phone-input-radius-default)); border-end-start-radius: var(--lr-phone-input-radius, var(--_lr-phone-input-radius-default)); transition: background-color var(--lr-transition-fast); } [part='country-select']:not(:disabled):hover + [part='country-trigger'] { background: var(--lr-phone-input-country-hover-bg, var(--lr-color-brand-quiet)); } [part='country-select']:not(:disabled):active + [part='country-trigger'] { background: color-mix( in oklab, var(--lr-phone-input-country-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='country-select']:focus-visible + [part='country-trigger'] { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part='flag'] { font-size: var(--lr-phone-input-flag-size, var(--_lr-phone-input-flag-size-default)); } [part='country-code'] { font-size: var(--lr-phone-input-font-size, var(--_lr-phone-input-font-size-default)); font-weight: var(--lr-font-weight-semibold); } [part='country-code'][data-placeholder] { color: var(--lr-color-text-quiet); font-weight: var(--lr-font-weight-normal); } [part='expand-icon'] { display: inline-flex; align-items: center; justify-content: center; color: var(--lr-color-text-quiet); font-size: var(--lr-phone-input-glyph-size, var(--_lr-phone-input-glyph-size-default)); line-height: var(--lr-line-height-none); } [part='expand-icon'] svg { transform: rotate(90deg); } [part='input']:focus { outline: none; } [part='calling-code'] { flex: 0 0 auto; padding-inline-start: var(--lr-space-s); color: var(--lr-color-text-quiet); direction: ltr; font-size: var(--lr-phone-input-font-size, var(--_lr-phone-input-font-size-default)); unicode-bidi: isolate; } [part='input'] { flex: 1 1 auto; min-inline-size: 0; inline-size: 100%; padding-block: var(--lr-phone-input-padding-block, var(--_lr-phone-input-padding-block-default)); padding-inline: var(--lr-space-s); border: none; background: transparent; color: inherit; font: inherit; text-align: start; } [part='input']::placeholder { color: var(--lr-color-text-quiet); } [part='end'] { display: inline-flex; flex: 0 0 auto; align-items: center; padding-inline-end: var(--lr-space-s); } [part='hint'], [part='error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); } [part='hint'] { color: var(--lr-color-text-quiet); } [part='error'] { color: var(--lr-color-danger); } @media (forced-colors: active) { [part='country-select']:not(:disabled):hover + [part='country-trigger'] { outline-color: Highlight; outline-style: dashed; outline-width: var(--lr-border-width-thin); outline-offset: calc(-1 * var(--lr-border-width-thin)); } [part='country-select']:not(:disabled):active + [part='country-trigger'] { outline-color: Highlight; outline-style: solid; outline-width: var(--lr-border-width-thick); outline-offset: calc(-1 * var(--lr-border-width-thick)); } } [part='form-control'], [part='form-control-label'], [part='hint'], [part='error'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } `;export{styles};
|
|
@@ -57,7 +57,7 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
|
|
|
57
57
|
*/
|
|
58
58
|
export declare class LyraRadioGroup extends LyraElement<LyraRadioGroupEventMap>{protected static readonly immutableEventDetails:readonly string[];protected static readonly identityEventDetailProperties:Readonly<{'lr-input':readonly string[];'lr-change':readonly string[];}>;
|
|
59
59
|
/** Public WA-compatible intrinsic validator catalog. */
|
|
60
|
-
static get validators():LyraFormValidator<LyraRadioGroup>[];static formAssociated:boolean;static styles:import("lit").CSSResultGroup[];static properties:{name:{reflect:boolean;noAccessor:boolean;converter:import("lit").ComplexAttributeConverter<string,unknown>;};value:{attribute:boolean;noAccessor:boolean;};defaultValue:{attribute:string;reflect:boolean;useDefault:boolean;noAccessor:boolean;};customError:{attribute:string;reflect:boolean;noAccessor:boolean;};required:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};disabled:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};orientation:{reflect:boolean;converter:import("
|
|
60
|
+
static get validators():LyraFormValidator<LyraRadioGroup>[];static formAssociated:boolean;static styles:import("lit").CSSResultGroup[];static properties:{name:{reflect:boolean;noAccessor:boolean;converter:import("lit").ComplexAttributeConverter<string,unknown>;};value:{attribute:boolean;noAccessor:boolean;};defaultValue:{attribute:string;reflect:boolean;useDefault:boolean;noAccessor:boolean;};customError:{attribute:string;reflect:boolean;noAccessor:boolean;};required:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};disabled:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};orientation:{reflect:boolean;converter:import("../../../internal/converters.js").LiteralSetConverter<LyraOrientation>;};form:{noAccessor:boolean;};};
|
|
61
61
|
/**
|
|
62
62
|
* Size of the group's own chrome, on the library's shared ladder. Accepts both spellings of every
|
|
63
63
|
* tier — `2xs`/`xs`/`s`/`m`/`l`/`xl` and Web Awesome's `small`/`medium`/`large` — so migrating
|
|
@@ -1,11 +1,11 @@
|
|
|
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{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{isStaticValidityCheckInProgress,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}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.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}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.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncRadios(),this.updateValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.syncRadios(),this.updateValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}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}constructor(){super(),this.size="m",this.orientation="vertical",this.label="",this.hint="",this.helpText="",this.shoelaceDefaultValue="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;isStaticValidityCheckInProgress(this)||(this.hasInteracted=!0),this.reflectValidityStates(),this.requestUpdate(),this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"],"Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument&&this.syncRadios()})},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),this.addEventListener("invalid",this.onInvalid,!0),this.syncFormState(),this.updateValidity()}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot?.querySelector('[role="radiogroup"]')??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.releaseExternalDescription(),this.resetMembershipObserver(),this.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)&&(this.defaultValue=this.shoelaceDefaultValue,this.hadShoelaceDefaultValue=this.hasAttribute("default-value"))}updated(changed){super.updated(changed),this.syncExternalDescription(),this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired,this.pendingSelection=desired,this.syncFormState(),this.updateValidity(),this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=!0;try{for(const radio of radios)radio.checked!==(radio===match)&&(radio.checked=radio===match)}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));let checked=radios.filter(radio=>radio.checked),checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked!==(radio===checkedRadio)&&(radio.checked=radio===checkedRadio);checked=checkedRadio?[checkedRadio]:[],this.pendingSelection=void 0}else checkedRadio=preferred?.checked&¤t.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.scheduleRunProjection()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked!==(candidate===radio)&&(candidate.checked=candidate===radio)}finally{this.syncingRadios=!1}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("radioRequired"):""),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.hasInteracted=!0,this.updateValidity(),this.requestUpdate(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state2=="string"?state2:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncRadios(),this.updateValidity(),this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;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{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{isStaticValidityCheckInProgress,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")],RADIO_GROUP_ORIENTATION=literalSetConverter(["horizontal","vertical"],"vertical");class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:RADIO_GROUP_ORIENTATION},form:{noAccessor:!0}}}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.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}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.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncRadios(),this.updateValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.syncRadios(),this.updateValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}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}constructor(){super(),this.size="m",this.orientation="vertical",this.label="",this.hint="",this.helpText="",this.shoelaceDefaultValue="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;isStaticValidityCheckInProgress(this)||(this.hasInteracted=!0),this.reflectValidityStates(),this.requestUpdate(),this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"],"Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument&&this.syncRadios()})},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),this.addEventListener("invalid",this.onInvalid,!0),this.syncFormState(),this.updateValidity()}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot?.querySelector('[role="radiogroup"]')??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated?(this.syncExternalDescription(),this.syncSupportSlots()):this.seedFirstRenderState(()=>this.syncSupportSlots()),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.releaseExternalDescription(),this.resetMembershipObserver(),this.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)&&(this.defaultValue=this.shoelaceDefaultValue,this.hadShoelaceDefaultValue=this.hasAttribute("default-value"))}updated(changed){super.updated(changed),this.syncExternalDescription(),this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired,this.pendingSelection=desired,this.syncFormState(),this.updateValidity(),this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=!0;try{for(const radio of radios)radio.checked!==(radio===match)&&(radio.checked=radio===match)}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));let checked=radios.filter(radio=>radio.checked),checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked!==(radio===checkedRadio)&&(radio.checked=radio===checkedRadio);checked=checkedRadio?[checkedRadio]:[],this.pendingSelection=void 0}else checkedRadio=preferred?.checked&¤t.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.scheduleRunProjection()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked!==(candidate===radio)&&(candidate.checked=candidate===radio)}finally{this.syncingRadios=!1}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("radioRequired"):""),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.hasInteracted=!0,this.updateValidity(),this.requestUpdate(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state2=="string"?state2:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.syncRadios(),this.updateValidity(),this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,ariaOrientation=RADIO_GROUP_ORIENTATION.normalize(this.orientation);return html`
|
|
2
2
|
<div part="base" role="radiogroup"
|
|
3
3
|
aria-label=${hasAccessibleLabel?this.accessibleLabel:nothing}
|
|
4
4
|
aria-labelledby=${!hasAccessibleLabel&&hasLabel?this.labelId:nothing}
|
|
5
5
|
aria-describedby=${described}
|
|
6
6
|
aria-required=${this.required?"true":"false"}
|
|
7
7
|
aria-disabled=${this.effectiveDisabled?"true":"false"}
|
|
8
|
-
aria-orientation=${
|
|
8
|
+
aria-orientation=${ariaOrientation}
|
|
9
9
|
aria-invalid=${hasError||this.hasInteracted&&!this.internals.validity.valid?"true":"false"}
|
|
10
10
|
@keydown=${this.onKeyDown}>
|
|
11
11
|
<div part="form-control">
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import'../../layout/segmented/segmented.class.js';import'../slider/slider.class.js';import'../select/select.class.js';import'../combobox/option.class.js';import'../checkbox/checkbox.class.js';import'../checkbox-group/checkbox-group.class.js';import'../textarea/textarea.class.js';import{type FormOwnerValue}from'../../../internal/form-associated.js';export interface RubricKeyOption{readonly value:string;readonly label?:string;readonly description?:string;
|
|
1
|
+
import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from'../../../internal/lyra-element.js';import'../../layout/segmented/segmented.class.js';import'../slider/slider.class.js';import'../select/select.class.js';import'../combobox/option.class.js';import'../checkbox/checkbox.class.js';import'../checkbox-group/checkbox-group.class.js';import'../textarea/textarea.class.js';import{type FormOwnerValue}from'../../../internal/form-associated.js';export interface RubricKeyOption{readonly value:string;readonly label?:string;readonly description?:string;
|
|
2
|
+
/** Optional decorative leading visual, rendered into `<lr-option>`'s `start` slot (single-select)
|
|
3
|
+
* or inline before the label (multiple-select). Deliberately general Lit content rather than an
|
|
4
|
+
* icon-name string, matching `LyraFilterBarOption.icon`/`LyraSegmentedItem.icon`. Rendered
|
|
5
|
+
* inert and `aria-hidden`, so it never contributes to the option's accessible name. */
|
|
6
|
+
readonly icon?:unknown;}interface RubricKeyBase{readonly key:string;readonly label?:string;readonly description?:string;readonly required?:boolean;}export interface ScoreRubricKey extends RubricKeyBase{readonly type:'score';readonly min?:number;readonly max?:number;readonly step?:number;}export interface CategoryRubricKey extends RubricKeyBase{readonly type:'category';readonly options?:readonly RubricKeyOption[];readonly multiple?:boolean;}export interface CommentRubricKey extends RubricKeyBase{readonly type:'comment';readonly placeholder?:string;}
|
|
2
7
|
/** Discriminated, immutable field schema; each variant exposes only meaningful configuration. */
|
|
3
8
|
export type RubricKey=ScoreRubricKey|CategoryRubricKey|CommentRubricKey;export type RubricValue=Readonly<Record<string,number|string|readonly string[]|undefined>>;export interface LyraRubricFormEventMap{'lr-invalid':CustomEvent<null>;'lr-input':CustomEvent<Readonly<{value:RubricValue;}>>;'lr-validity-change':CustomEvent<{readonly valid:boolean;readonly errors:Readonly<Record<string,string>>;}>;'lr-submit':CustomEvent<Readonly<{value:RubricValue;itemId:string;}>>;'lr-skip':CustomEvent<{itemId:string;}>;}
|
|
4
9
|
/**
|
|
@@ -198,6 +203,9 @@ setCustomValidity(message:string):void;formResetCallback():void;formStateRestore
|
|
|
198
203
|
* produces the same result on a second call.
|
|
199
204
|
*/
|
|
200
205
|
private applyAggregateSlotAssignment;private markTouched;private submit;private skip;private focusFirstControl;
|
|
206
|
+
/** Moves focus to the first rendered field, matching {@link click}'s target -- the same forwarder
|
|
207
|
+
* every other Lyra form control uses so the global `autofocus` attribute reaches it too. */
|
|
208
|
+
focus(options?:FocusOptions):void;
|
|
201
209
|
/** Forwards host clicks to the first rendered field, so programmatic and `<label>`-driven
|
|
202
210
|
* interactions target the active rubric field. */
|
|
203
211
|
click():void;private externalDescriptionLease?;private syncExternalDescription;private releaseExternalDescription;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private renderScoreControl;private renderCategoryControl;private renderCommentControl;private renderField;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-rubric-form':LyraRubricForm;}}export{};
|