@funstack/ui 0.1.0-alpha.17 → 0.1.0-alpha.19
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/dist/accordion/accordion-item.mjs +1 -1
- package/dist/accordion/accordion-panel.mjs +1 -1
- package/dist/accordion/accordion-root.d.mts.map +1 -1
- package/dist/accordion/accordion-root.mjs +35 -38
- package/dist/accordion/accordion-root.mjs.map +1 -1
- package/dist/accordion/accordion-trigger.mjs +1 -1
- package/dist/button/button.d.mts +18 -11
- package/dist/button/button.d.mts.map +1 -1
- package/dist/button/button.mjs +32 -16
- package/dist/button/button.mjs.map +1 -1
- package/dist/checkbox/checkbox.mjs +1 -1
- package/dist/checkbox/checkbox.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-item.mjs +3 -3
- package/dist/checkbox-group/checkbox-group-item.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-parent.mjs +3 -3
- package/dist/checkbox-group/checkbox-group-parent.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.d.mts.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.mjs +15 -12
- package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -1
- package/dist/combobox/combobox-context.mjs.map +1 -1
- package/dist/combobox/combobox-input.mjs +2 -2
- package/dist/combobox/combobox-input.mjs.map +1 -1
- package/dist/combobox/combobox-keyboard.mjs +81 -0
- package/dist/combobox/combobox-keyboard.mjs.map +1 -0
- package/dist/combobox/combobox-popup.mjs +3 -3
- package/dist/combobox/combobox-popup.mjs.map +1 -1
- package/dist/combobox/combobox-root.d.mts.map +1 -1
- package/dist/combobox/combobox-root.mjs +44 -129
- package/dist/combobox/combobox-root.mjs.map +1 -1
- package/dist/combobox/combobox-trigger.d.mts.map +1 -1
- package/dist/combobox/combobox-trigger.mjs +2 -9
- package/dist/combobox/combobox-trigger.mjs.map +1 -1
- package/dist/combobox/use-active-option.mjs +49 -0
- package/dist/combobox/use-active-option.mjs.map +1 -0
- package/dist/combobox/use-combobox-form.mjs +3 -5
- package/dist/combobox/use-combobox-form.mjs.map +1 -1
- package/dist/combobox/use-combobox-text.mjs +43 -0
- package/dist/combobox/use-combobox-text.mjs.map +1 -0
- package/dist/combobox/use-option-registry.mjs +7 -17
- package/dist/combobox/use-option-registry.mjs.map +1 -1
- package/dist/dialog/dialog-close.mjs +2 -2
- package/dist/dialog/dialog-close.mjs.map +1 -1
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-dismiss.mjs +108 -0
- package/dist/dialog/dialog-dismiss.mjs.map +1 -0
- package/dist/dialog/dialog-form.mjs +4 -4
- package/dist/dialog/dialog-form.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +73 -161
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-root.d.mts.map +1 -1
- package/dist/dialog/dialog-root.mjs +4 -3
- package/dist/dialog/dialog-root.mjs.map +1 -1
- package/dist/dialog/dialog-trigger.mjs +11 -8
- package/dist/dialog/dialog-trigger.mjs.map +1 -1
- package/dist/docs/components/accordion.md +1 -1
- package/dist/docs/components/button.md +13 -10
- package/dist/docs/components/dialog.md +4 -4
- package/dist/docs/components/field.md +4 -3
- package/dist/docs/components/popover.md +4 -4
- package/dist/docs/components/toast.md +8 -5
- package/dist/docs/concepts/browser-owned-state.md +1 -1
- package/dist/docs/roadmap.md +9 -1
- package/dist/field/field-control.d.mts +1 -1
- package/dist/field/field-control.mjs +2 -2
- package/dist/field/field-control.mjs.map +1 -1
- package/dist/field/field-description.d.mts +1 -1
- package/dist/field/field-description.mjs +1 -1
- package/dist/field/field-description.mjs.map +1 -1
- package/dist/field/field-error.d.mts +1 -1
- package/dist/field/field-error.mjs +1 -1
- package/dist/field/field-error.mjs.map +1 -1
- package/dist/field/field-label.d.mts +1 -1
- package/dist/field/field-label.mjs +1 -1
- package/dist/field/field-label.mjs.map +1 -1
- package/dist/field/field-root.d.mts +2 -2
- package/dist/field/field-root.d.mts.map +1 -1
- package/dist/field/field-root.mjs +4 -4
- package/dist/field/field-root.mjs.map +1 -1
- package/dist/field/index.d.mts +2 -2
- package/dist/form/form-root.d.mts +1 -1
- package/dist/form/form-root.d.mts.map +1 -1
- package/dist/form/form-root.mjs +14 -4
- package/dist/form/form-root.mjs.map +1 -1
- package/dist/form/form-submit.d.mts +7 -3
- package/dist/form/form-submit.d.mts.map +1 -1
- package/dist/form/form-submit.mjs +11 -7
- package/dist/form/form-submit.mjs.map +1 -1
- package/dist/form/index.d.mts +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/internal/{action-details.mjs → action/action-details.mjs} +1 -1
- package/dist/internal/action/action-details.mjs.map +1 -0
- package/dist/internal/{call-urgent-handler.mjs → action/call-urgent-handler.mjs} +5 -10
- package/dist/internal/action/call-urgent-handler.mjs.map +1 -0
- package/dist/internal/{report-dropped.mjs → action/report-dropped.mjs} +3 -21
- package/dist/internal/action/report-dropped.mjs.map +1 -0
- package/dist/internal/{use-action-trigger.mjs → action/use-action-trigger.mjs} +3 -2
- package/dist/internal/action/use-action-trigger.mjs.map +1 -0
- package/dist/internal/action/use-connected.mjs +24 -0
- package/dist/internal/action/use-connected.mjs.map +1 -0
- package/dist/internal/{use-controllable-action.mjs → action/use-controllable-action.mjs} +20 -32
- package/dist/internal/action/use-controllable-action.mjs.map +1 -0
- package/dist/internal/action/use-pure-trigger.mjs +34 -0
- package/dist/internal/action/use-pure-trigger.mjs.map +1 -0
- package/dist/internal/action/use-step-commit.mjs +147 -0
- package/dist/internal/action/use-step-commit.mjs.map +1 -0
- package/dist/internal/{field-context.d.mts → form/field-context.d.mts} +1 -1
- package/dist/internal/form/field-context.d.mts.map +1 -0
- package/dist/internal/{field-context.mjs → form/field-context.mjs} +2 -2
- package/dist/internal/form/field-context.mjs.map +1 -0
- package/dist/internal/{focus-first-invalid.mjs → form/focus-first-invalid.mjs} +3 -3
- package/dist/internal/form/focus-first-invalid.mjs.map +1 -0
- package/dist/internal/{form-status-watcher.mjs → form/form-status-watcher.mjs} +1 -1
- package/dist/internal/form/form-status-watcher.mjs.map +1 -0
- package/dist/internal/{group-member.mjs → form/group-member.mjs} +2 -2
- package/dist/internal/form/group-member.mjs.map +1 -0
- package/dist/internal/{sync-presence.mjs → form/sync-presence.mjs} +1 -1
- package/dist/internal/form/sync-presence.mjs.map +1 -0
- package/dist/internal/{use-checkable-input.mjs → form/use-checkable-input.mjs} +5 -5
- package/dist/internal/form/use-checkable-input.mjs.map +1 -0
- package/dist/internal/{use-field-control.mjs → form/use-field-control.mjs} +3 -3
- package/dist/internal/form/use-field-control.mjs.map +1 -0
- package/dist/internal/{use-fieldset-group.mjs → form/use-fieldset-group.mjs} +3 -3
- package/dist/internal/form/use-fieldset-group.mjs.map +1 -0
- package/dist/internal/{use-form-owner-event.mjs → form/use-form-owner-event.mjs} +1 -1
- package/dist/internal/form/use-form-owner-event.mjs.map +1 -0
- package/dist/internal/{use-form-reset.mjs → form/use-form-reset.mjs} +15 -3
- package/dist/internal/form/use-form-reset.mjs.map +1 -0
- package/dist/internal/{use-native-checked.mjs → form/use-native-checked.mjs} +5 -4
- package/dist/internal/form/use-native-checked.mjs.map +1 -0
- package/dist/internal/{use-native-group-reconciliation.mjs → form/use-native-group-reconciliation.mjs} +8 -8
- package/dist/internal/form/use-native-group-reconciliation.mjs.map +1 -0
- package/dist/internal/{use-native-select-value.mjs → form/use-native-select-value.mjs} +2 -2
- package/dist/internal/form/use-native-select-value.mjs.map +1 -0
- package/dist/internal/{validity.d.mts → form/validity.d.mts} +1 -1
- package/dist/internal/form/validity.d.mts.map +1 -0
- package/dist/internal/{validity.mjs → form/validity.mjs} +1 -1
- package/dist/internal/form/validity.mjs.map +1 -0
- package/dist/internal/{anchor-position.d.mts → overlay/anchor-position.d.mts} +1 -1
- package/dist/internal/overlay/anchor-position.d.mts.map +1 -0
- package/dist/internal/{anchor-position.mjs → overlay/anchor-position.mjs} +1 -1
- package/dist/internal/overlay/anchor-position.mjs.map +1 -0
- package/dist/internal/{content-focus-probe.mjs → overlay/content-focus-probe.mjs} +1 -1
- package/dist/internal/overlay/content-focus-probe.mjs.map +1 -0
- package/dist/internal/{css-transition-cut.mjs → overlay/css-transition-cut.mjs} +1 -1
- package/dist/internal/overlay/css-transition-cut.mjs.map +1 -0
- package/dist/internal/{focus-visible.mjs → overlay/focus-visible.mjs} +1 -1
- package/dist/internal/overlay/focus-visible.mjs.map +1 -0
- package/dist/internal/{invokers.mjs → overlay/invokers.mjs} +1 -1
- package/dist/internal/overlay/invokers.mjs.map +1 -0
- package/dist/internal/{modal-registry.mjs → overlay/modal-registry.mjs} +1 -1
- package/dist/internal/overlay/modal-registry.mjs.map +1 -0
- package/dist/internal/{overlay-popup.mjs → overlay/overlay-popup.mjs} +3 -3
- package/dist/internal/overlay/overlay-popup.mjs.map +1 -0
- package/dist/internal/overlay/overlay-show.mjs +73 -0
- package/dist/internal/overlay/overlay-show.mjs.map +1 -0
- package/dist/internal/{popover-open.mjs → overlay/popover-open.mjs} +1 -1
- package/dist/internal/overlay/popover-open.mjs.map +1 -0
- package/dist/internal/{trigger-ref.mjs → overlay/trigger-ref.mjs} +1 -1
- package/dist/internal/overlay/trigger-ref.mjs.map +1 -0
- package/dist/internal/overlay/use-apply-open-state.mjs +44 -0
- package/dist/internal/overlay/use-apply-open-state.mjs.map +1 -0
- package/dist/internal/{use-exit-animation.mjs → overlay/use-exit-animation.mjs} +2 -2
- package/dist/internal/overlay/use-exit-animation.mjs.map +1 -0
- package/dist/internal/{use-interest-dismiss.mjs → overlay/use-interest-dismiss.mjs} +1 -1
- package/dist/internal/overlay/use-interest-dismiss.mjs.map +1 -0
- package/dist/internal/{use-modal-registration.mjs → overlay/use-modal-registration.mjs} +1 -1
- package/dist/internal/overlay/use-modal-registration.mjs.map +1 -0
- package/dist/internal/{use-overlay-close.mjs → overlay/use-overlay-close.mjs} +14 -13
- package/dist/internal/overlay/use-overlay-close.mjs.map +1 -0
- package/dist/internal/overlay/use-overlay-root.d.mts +2 -0
- package/dist/internal/{use-overlay-root.mjs → overlay/use-overlay-root.mjs} +44 -28
- package/dist/internal/overlay/use-overlay-root.mjs.map +1 -0
- package/dist/internal/{use-popover-popup.mjs → overlay/use-popover-popup.mjs} +74 -63
- package/dist/internal/overlay/use-popover-popup.mjs.map +1 -0
- package/dist/internal/{use-popover-trigger.d.mts → overlay/use-popover-trigger.d.mts} +3 -3
- package/dist/internal/overlay/use-popover-trigger.d.mts.map +1 -0
- package/dist/internal/{use-popover-trigger.mjs → overlay/use-popover-trigger.mjs} +47 -26
- package/dist/internal/overlay/use-popover-trigger.mjs.map +1 -0
- package/dist/internal/{use-resolved-placement.mjs → overlay/use-resolved-placement.mjs} +2 -2
- package/dist/internal/overlay/use-resolved-placement.mjs.map +1 -0
- package/dist/internal/render-element.mjs +47 -9
- package/dist/internal/render-element.mjs.map +1 -1
- package/dist/internal/transition-boundary.mjs +4 -8
- package/dist/internal/transition-boundary.mjs.map +1 -1
- package/dist/internal/use-mount-fixed.mjs +22 -0
- package/dist/internal/use-mount-fixed.mjs.map +1 -0
- package/dist/internal/use-register-count.mjs +4 -1
- package/dist/internal/use-register-count.mjs.map +1 -1
- package/dist/internal/use-render.mjs +2 -2
- package/dist/internal/use-render.mjs.map +1 -1
- package/dist/internal/use-roving-focus.mjs.map +1 -1
- package/dist/menu/menu-checkbox-item.mjs +2 -2
- package/dist/menu/menu-checkbox-item.mjs.map +1 -1
- package/dist/menu/menu-context.d.mts +1 -1
- package/dist/menu/menu-context.mjs.map +1 -1
- package/dist/menu/menu-gestures.mjs +1 -1
- package/dist/menu/menu-gestures.mjs.map +1 -1
- package/dist/menu/menu-item.d.mts.map +1 -1
- package/dist/menu/menu-item.mjs +9 -10
- package/dist/menu/menu-item.mjs.map +1 -1
- package/dist/menu/menu-outside.mjs +1 -1
- package/dist/menu/menu-outside.mjs.map +1 -1
- package/dist/menu/menu-popup.d.mts +1 -1
- package/dist/menu/menu-popup.d.mts.map +1 -1
- package/dist/menu/menu-popup.mjs +10 -6
- package/dist/menu/menu-popup.mjs.map +1 -1
- package/dist/menu/menu-radio-group.mjs +2 -2
- package/dist/menu/menu-radio-group.mjs.map +1 -1
- package/dist/menu/menu-root.mjs +2 -2
- package/dist/menu/menu-root.mjs.map +1 -1
- package/dist/menu/menu-submenu-trigger.mjs +3 -3
- package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
- package/dist/menu/menu-trigger.d.mts +1 -1
- package/dist/menu/menu-trigger.mjs +3 -3
- package/dist/menu/menu-trigger.mjs.map +1 -1
- package/dist/number-field/number-field-input.mjs +1 -1
- package/dist/number-field/number-field-input.mjs.map +1 -1
- package/dist/number-field/number-field-root.d.mts.map +1 -1
- package/dist/number-field/number-field-root.mjs +43 -107
- package/dist/number-field/number-field-root.mjs.map +1 -1
- package/dist/popover/popover-close.mjs +3 -3
- package/dist/popover/popover-close.mjs.map +1 -1
- package/dist/popover/popover-context.mjs.map +1 -1
- package/dist/popover/popover-popup.d.mts +1 -1
- package/dist/popover/popover-popup.mjs +3 -3
- package/dist/popover/popover-popup.mjs.map +1 -1
- package/dist/popover/popover-root.mjs +2 -2
- package/dist/popover/popover-root.mjs.map +1 -1
- package/dist/popover/popover-trigger.d.mts +1 -1
- package/dist/popover/popover-trigger.mjs +1 -1
- package/dist/popover/popover-trigger.mjs.map +1 -1
- package/dist/radio-group/radio-group-item.mjs +3 -3
- package/dist/radio-group/radio-group-item.mjs.map +1 -1
- package/dist/radio-group/radio-group-root.d.mts.map +1 -1
- package/dist/radio-group/radio-group-root.mjs +5 -5
- package/dist/radio-group/radio-group-root.mjs.map +1 -1
- package/dist/select/select-group-label.d.mts.map +1 -1
- package/dist/select/select-group-label.mjs +3 -1
- package/dist/select/select-group-label.mjs.map +1 -1
- package/dist/select/select-option.mjs +1 -1
- package/dist/select/select-option.mjs.map +1 -1
- package/dist/select/select-root.d.mts.map +1 -1
- package/dist/select/select-root.mjs +7 -7
- package/dist/select/select-root.mjs.map +1 -1
- package/dist/select/select-trigger.d.mts.map +1 -1
- package/dist/select/select-trigger.mjs +3 -1
- package/dist/select/select-trigger.mjs.map +1 -1
- package/dist/select/select-value.mjs +3 -6
- package/dist/select/select-value.mjs.map +1 -1
- package/dist/slider/slider-root.d.mts.map +1 -1
- package/dist/slider/slider-root.mjs +38 -104
- package/dist/slider/slider-root.mjs.map +1 -1
- package/dist/slider/use-thumb-registry.mjs.map +1 -1
- package/dist/switch/switch.mjs +1 -1
- package/dist/switch/switch.mjs.map +1 -1
- package/dist/tabs/tabs-panel.mjs +1 -1
- package/dist/tabs/tabs-panel.mjs.map +1 -1
- package/dist/tabs/tabs-root.d.mts.map +1 -1
- package/dist/tabs/tabs-root.mjs +4 -4
- package/dist/tabs/tabs-root.mjs.map +1 -1
- package/dist/{internal → tabs}/use-until-found.mjs +1 -1
- package/dist/tabs/use-until-found.mjs.map +1 -0
- package/dist/toast/toast-action.d.mts +13 -3
- package/dist/toast/toast-action.d.mts.map +1 -1
- package/dist/toast/toast-action.mjs +23 -13
- package/dist/toast/toast-action.mjs.map +1 -1
- package/dist/toast/toast-close.d.mts +13 -2
- package/dist/toast/toast-close.d.mts.map +1 -1
- package/dist/toast/toast-close.mjs +16 -6
- package/dist/toast/toast-close.mjs.map +1 -1
- package/dist/toast/toast-root.mjs +1 -1
- package/dist/toast/toast-root.mjs.map +1 -1
- package/dist/toast/toast-viewport.d.mts.map +1 -1
- package/dist/toast/toast-viewport.mjs +48 -143
- package/dist/toast/toast-viewport.mjs.map +1 -1
- package/dist/toast/use-modal-portal-host.mjs +1 -1
- package/dist/toast/use-modal-portal-host.mjs.map +1 -1
- package/dist/toast/use-toast-announcements.mjs +46 -0
- package/dist/toast/use-toast-announcements.mjs.map +1 -0
- package/dist/toast/use-toast-focus.mjs +75 -0
- package/dist/toast/use-toast-focus.mjs.map +1 -0
- package/dist/toast/use-toast-pauses.mjs +58 -0
- package/dist/toast/use-toast-pauses.mjs.map +1 -0
- package/dist/toggle/toggle.mjs +2 -2
- package/dist/toggle/toggle.mjs.map +1 -1
- package/dist/toggle-group/toggle-group-root.d.mts.map +1 -1
- package/dist/toggle-group/toggle-group-root.mjs +5 -5
- package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
- package/dist/tooltip/tooltip-context.d.mts +1 -1
- package/dist/tooltip/tooltip-context.mjs.map +1 -1
- package/dist/tooltip/tooltip-popup.mjs +1 -1
- package/dist/tooltip/tooltip-popup.mjs.map +1 -1
- package/dist/tooltip/tooltip-root.d.mts.map +1 -1
- package/dist/tooltip/tooltip-root.mjs +9 -4
- package/dist/tooltip/tooltip-root.mjs.map +1 -1
- package/dist/tooltip/tooltip-trigger.mjs +1 -1
- package/dist/tooltip/tooltip-trigger.mjs.map +1 -1
- package/dist/{internal → tooltip}/tooltip-warm.mjs +1 -1
- package/dist/tooltip/tooltip-warm.mjs.map +1 -0
- package/dist/tooltip/use-tooltip-interaction.mjs +2 -2
- package/dist/tooltip/use-tooltip-interaction.mjs.map +1 -1
- package/package.json +1 -1
- package/skills/funstack-ui-knowledge/SKILL.md +1 -1
- package/dist/internal/action-details.mjs.map +0 -1
- package/dist/internal/anchor-position.d.mts.map +0 -1
- package/dist/internal/anchor-position.mjs.map +0 -1
- package/dist/internal/call-urgent-handler.mjs.map +0 -1
- package/dist/internal/content-focus-probe.mjs.map +0 -1
- package/dist/internal/css-transition-cut.mjs.map +0 -1
- package/dist/internal/field-context.d.mts.map +0 -1
- package/dist/internal/field-context.mjs.map +0 -1
- package/dist/internal/focus-first-invalid.mjs.map +0 -1
- package/dist/internal/focus-visible.mjs.map +0 -1
- package/dist/internal/form-status-watcher.mjs.map +0 -1
- package/dist/internal/group-member.mjs.map +0 -1
- package/dist/internal/invokers.mjs.map +0 -1
- package/dist/internal/modal-registry.mjs.map +0 -1
- package/dist/internal/overlay-popup.mjs.map +0 -1
- package/dist/internal/popover-open.mjs.map +0 -1
- package/dist/internal/report-dropped.mjs.map +0 -1
- package/dist/internal/sync-presence.mjs.map +0 -1
- package/dist/internal/tooltip-warm.mjs.map +0 -1
- package/dist/internal/trigger-ref.mjs.map +0 -1
- package/dist/internal/use-action-trigger.mjs.map +0 -1
- package/dist/internal/use-checkable-input.mjs.map +0 -1
- package/dist/internal/use-controllable-action.mjs.map +0 -1
- package/dist/internal/use-exit-animation.mjs.map +0 -1
- package/dist/internal/use-field-control.mjs.map +0 -1
- package/dist/internal/use-fieldset-group.mjs.map +0 -1
- package/dist/internal/use-form-owner-event.mjs.map +0 -1
- package/dist/internal/use-form-reset.mjs.map +0 -1
- package/dist/internal/use-interest-dismiss.mjs.map +0 -1
- package/dist/internal/use-modal-registration.mjs.map +0 -1
- package/dist/internal/use-native-checked.mjs.map +0 -1
- package/dist/internal/use-native-group-reconciliation.mjs.map +0 -1
- package/dist/internal/use-native-select-value.mjs.map +0 -1
- package/dist/internal/use-overlay-close.mjs.map +0 -1
- package/dist/internal/use-overlay-root.d.mts +0 -2
- package/dist/internal/use-overlay-root.mjs.map +0 -1
- package/dist/internal/use-popover-popup.mjs.map +0 -1
- package/dist/internal/use-popover-trigger.d.mts.map +0 -1
- package/dist/internal/use-popover-trigger.mjs.map +0 -1
- package/dist/internal/use-resolved-placement.mjs.map +0 -1
- package/dist/internal/use-until-found.mjs.map +0 -1
- package/dist/internal/validity.d.mts.map +0 -1
- package/dist/internal/validity.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox.mjs","names":[],"sources":["../../src/checkbox/checkbox.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentPropsWithRef, CSSProperties, ViewTransitionClass } from \"react\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type {\n ActionDetails,\n ChangeAction,\n ChangeReason,\n RenderProp,\n StateValue,\n} from \"../internal/types.js\";\nimport { useCheckableInput } from \"../internal/use-checkable-input.js\";\nimport { useRender } from \"../internal/use-render.js\";\n\n/** State of `Checkbox`, passed to the function forms of `className`, `style` and `render`. */\nexport interface CheckboxState {\n /** Optimistic checked state: what the user sees, including an in-flight change. */\n readonly checked: boolean;\n /**\n * The `indeterminate` prop, suspended while an action is in flight: `false` whenever `pending`\n * is true, so that the attribute, the DOM property and `:indeterminate` always agree.\n */\n readonly indeterminate: boolean;\n /** An action dispatched by this Checkbox is in flight (including the resulting render). */\n readonly pending: boolean;\n /** The `disabled` prop (or the enclosing `Field.Root`'s). */\n readonly disabled: boolean;\n}\n\n/** Details passed as the second argument of `checkedChangeAction`. */\nexport interface CheckboxCheckedChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user toggled the box (click, Space, label click); `event` is the native\n * `click` event. `\"platform\"`: the browser changed the value itself: a form reset (`event` is\n * the `reset` event) or a click before hydration / Firefox form-state restoration found on\n * mount (`event` is `undefined`).\n */\n readonly reason: ChangeReason;\n}\n\n/**\n * Props of `Checkbox`.\n *\n * @see https://ui.funstack.work/components/checkbox\n */\nexport interface CheckboxProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"type\"\n | \"checked\"\n | \"defaultChecked\"\n | \"onChange\"\n | \"aria-checked\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Controlled checked state. `undefined` means uncontrolled. */\n checked?: boolean;\n /**\n * Initial checked state in uncontrolled mode. Also the value a form reset\n * returns to: the latest prop value is mirrored into the input's `defaultChecked`.\n *\n * @defaultValue `false`\n */\n defaultChecked?: boolean;\n /**\n * Controlled-only mixed state (APG tri-state checkbox), derived by the parent from other state;\n * there is no `defaultIndeterminate` and no action. Rendered as `el.indeterminate`,\n * `data-indeterminate` and `:indeterminate`, except while an action is pending. Clicking a\n * mixed box dispatches `checked: true` (for the usual unchecked + mixed representation). Does\n * not affect what the form submits.\n *\n * @defaultValue `false`\n */\n indeterminate?: boolean;\n /**\n * Called with the next checked state on every change. Runs inside the Checkbox's transition;\n * may be sync or async (also a Server Function). Rejections reach the nearest Error Boundary.\n * Also called with `details.reason === \"platform\"` for a form reset or a pre-hydration click.\n *\n * A `setState` placed after your own `await` is not a Transition update; wrap it in\n * `startTransition` (React limitation). `details.event.preventDefault()` is not a veto and is\n * unsupported here; use controlled mode to veto a change.\n */\n checkedChangeAction?: ChangeAction<boolean, CheckboxCheckedChangeDetails>;\n /**\n * Renders a natively disabled input; never dispatches.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Submitted as the input's value when checked.\n *\n * @defaultValue `\"on\"` (platform)\n */\n value?: string;\n /**\n * Forwarded as `default` to the Checkbox's `<ViewTransition>`. Default: no boundary. Animates the\n * commit that ends an action, not the optimistic flip; animate the flip with CSS on `:checked`.\n *\n * Static: setting or unsetting it remounts the element. Any value, `\"none\"` included, makes a\n * mount or `<Activity>` reveal inside a transition start a document view transition (a ~250 ms\n * page cross-fade that the next transition waits for).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxState>;\n /**\n * Replace the rendered element (element form) or take over rendering (function form). Must keep\n * an `<input type=\"checkbox\">`.\n */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, CheckboxState>;\n}\n\n/**\n * A checkbox (WAI-ARIA \"Checkbox\" pattern, dual- and mixed-state). Renders\n * `<input type=\"checkbox\">` whose DOM `checked` is the optimistic state; the input carries\n * `data-pending` while `checkedChangeAction` is in flight and takes part in forms natively.\n *\n * Owned keys (a `render` element's value is overridden): `type`, `checked`, `defaultChecked`,\n * `indeterminate` (stripped), `aria-checked` (always removed), `disabled`, `data-checked`,\n * `data-indeterminate`, `data-pending`, `data-disabled`; inside a `Field.Root` also `id`,\n * `name`, `required`, `aria-invalid`, `aria-describedby` (token-merged) and `data-invalid`, and\n * `disabled` / `name` / `required` default from the Field. `role` passes through. Event handlers\n * are merged rather than owned: a `render` element's own `onChange` (or `onClick`) runs first,\n * then the library's; an `onClick` that calls `preventDefault()` cancels the change (nothing is\n * dispatched).\n *\n * @see https://ui.funstack.work/components/checkbox\n */\nexport function Checkbox({\n checked,\n defaultChecked,\n indeterminate = false,\n checkedChangeAction,\n disabled,\n transition,\n className,\n style,\n render,\n ...rest\n}: CheckboxProps) {\n const input = useCheckableInput({\n component: \"Checkbox\",\n checked,\n defaultChecked,\n checkedChangeAction,\n disabled,\n own: rest,\n transitionTypes: (next) => transitionTypes(\"checkbox\", next ? \"check\" : \"uncheck\"),\n indeterminate,\n });\n\n const state: CheckboxState = {\n checked: input.optimistic,\n indeterminate: input.shownIndeterminate,\n pending: input.pending,\n disabled: input.disabled,\n };\n\n const element = useRender<ComponentPropsWithRef<\"input\">, CheckboxState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n ref: input.ref,\n // Pass-through layer: a `render` element's own props win over these (`role` included).\n props: rest,\n libraryProps: input.libraryProps,\n });\n\n return useTransitionBoundary(\"Checkbox\", transition, element);\n}\n\nCheckbox.displayName = \"Checkbox\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqIA,SAAgB,SAAS,EACvB,SACA,gBACA,gBAAgB,OAChB,qBACA,UACA,YACA,WACA,OACA,QACA,GAAG,QACa;CAChB,MAAM,QAAQ,kBAAkB;EAC9B,WAAW;EACX;EACA;EACA;EACA;EACA,KAAK;EACL,kBAAkB,SAAS,gBAAgB,YAAY,OAAO,UAAU,SAAS;EACjF;CACF,CAAC;CAED,MAAM,QAAuB;EAC3B,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,SAAS,MAAM;EACf,UAAU,MAAM;CAClB;CAEA,MAAM,UAAU,UAAyD;EACvE,gBAAgB;EAChB;EACA;EACA;EACA;EACA,UAAU,KAAA;EACV,KAAK,MAAM;EAEX,OAAO;EACP,cAAc,MAAM;CACtB,CAAC;CAED,OAAO,sBAAsB,YAAY,YAAY,OAAO;AAC9D;AAEA,SAAS,cAAc"}
|
|
1
|
+
{"version":3,"file":"checkbox.mjs","names":[],"sources":["../../src/checkbox/checkbox.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentPropsWithRef, CSSProperties, ViewTransitionClass } from \"react\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type {\n ActionDetails,\n ChangeAction,\n ChangeReason,\n RenderProp,\n StateValue,\n} from \"../internal/types.js\";\nimport { useCheckableInput } from \"../internal/form/use-checkable-input.js\";\nimport { useRender } from \"../internal/use-render.js\";\n\n/** State of `Checkbox`, passed to the function forms of `className`, `style` and `render`. */\nexport interface CheckboxState {\n /** Optimistic checked state: what the user sees, including an in-flight change. */\n readonly checked: boolean;\n /**\n * The `indeterminate` prop, suspended while an action is in flight: `false` whenever `pending`\n * is true, so that the attribute, the DOM property and `:indeterminate` always agree.\n */\n readonly indeterminate: boolean;\n /** An action dispatched by this Checkbox is in flight (including the resulting render). */\n readonly pending: boolean;\n /** The `disabled` prop (or the enclosing `Field.Root`'s). */\n readonly disabled: boolean;\n}\n\n/** Details passed as the second argument of `checkedChangeAction`. */\nexport interface CheckboxCheckedChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user toggled the box (click, Space, label click); `event` is the native\n * `click` event. `\"platform\"`: the browser changed the value itself: a form reset (`event` is\n * the `reset` event) or a click before hydration / Firefox form-state restoration found on\n * mount (`event` is `undefined`).\n */\n readonly reason: ChangeReason;\n}\n\n/**\n * Props of `Checkbox`.\n *\n * @see https://ui.funstack.work/components/checkbox\n */\nexport interface CheckboxProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"type\"\n | \"checked\"\n | \"defaultChecked\"\n | \"onChange\"\n | \"aria-checked\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Controlled checked state. `undefined` means uncontrolled. */\n checked?: boolean;\n /**\n * Initial checked state in uncontrolled mode. Also the value a form reset\n * returns to: the latest prop value is mirrored into the input's `defaultChecked`.\n *\n * @defaultValue `false`\n */\n defaultChecked?: boolean;\n /**\n * Controlled-only mixed state (APG tri-state checkbox), derived by the parent from other state;\n * there is no `defaultIndeterminate` and no action. Rendered as `el.indeterminate`,\n * `data-indeterminate` and `:indeterminate`, except while an action is pending. Clicking a\n * mixed box dispatches `checked: true` (for the usual unchecked + mixed representation). Does\n * not affect what the form submits.\n *\n * @defaultValue `false`\n */\n indeterminate?: boolean;\n /**\n * Called with the next checked state on every change. Runs inside the Checkbox's transition;\n * may be sync or async (also a Server Function). Rejections reach the nearest Error Boundary.\n * Also called with `details.reason === \"platform\"` for a form reset or a pre-hydration click.\n *\n * A `setState` placed after your own `await` is not a Transition update; wrap it in\n * `startTransition` (React limitation). `details.event.preventDefault()` is not a veto and is\n * unsupported here; use controlled mode to veto a change.\n */\n checkedChangeAction?: ChangeAction<boolean, CheckboxCheckedChangeDetails>;\n /**\n * Renders a natively disabled input; never dispatches.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Submitted as the input's value when checked.\n *\n * @defaultValue `\"on\"` (platform)\n */\n value?: string;\n /**\n * Forwarded as `default` to the Checkbox's `<ViewTransition>`. Default: no boundary. Animates the\n * commit that ends an action, not the optimistic flip; animate the flip with CSS on `:checked`.\n *\n * Static: setting or unsetting it remounts the element. Any value, `\"none\"` included, makes a\n * mount or `<Activity>` reveal inside a transition start a document view transition (a ~250 ms\n * page cross-fade that the next transition waits for).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxState>;\n /**\n * Replace the rendered element (element form) or take over rendering (function form). Must keep\n * an `<input type=\"checkbox\">`.\n */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, CheckboxState>;\n}\n\n/**\n * A checkbox (WAI-ARIA \"Checkbox\" pattern, dual- and mixed-state). Renders\n * `<input type=\"checkbox\">` whose DOM `checked` is the optimistic state; the input carries\n * `data-pending` while `checkedChangeAction` is in flight and takes part in forms natively.\n *\n * Owned keys (a `render` element's value is overridden): `type`, `checked`, `defaultChecked`,\n * `indeterminate` (stripped), `aria-checked` (always removed), `disabled`, `data-checked`,\n * `data-indeterminate`, `data-pending`, `data-disabled`; inside a `Field.Root` also `id`,\n * `name`, `required`, `aria-invalid`, `aria-describedby` (token-merged) and `data-invalid`, and\n * `disabled` / `name` / `required` default from the Field. `role` passes through. Event handlers\n * are merged rather than owned: a `render` element's own `onChange` (or `onClick`) runs first,\n * then the library's; an `onClick` that calls `preventDefault()` cancels the change (nothing is\n * dispatched).\n *\n * @see https://ui.funstack.work/components/checkbox\n */\nexport function Checkbox({\n checked,\n defaultChecked,\n indeterminate = false,\n checkedChangeAction,\n disabled,\n transition,\n className,\n style,\n render,\n ...rest\n}: CheckboxProps) {\n const input = useCheckableInput({\n component: \"Checkbox\",\n checked,\n defaultChecked,\n checkedChangeAction,\n disabled,\n own: rest,\n transitionTypes: (next) => transitionTypes(\"checkbox\", next ? \"check\" : \"uncheck\"),\n indeterminate,\n });\n\n const state: CheckboxState = {\n checked: input.optimistic,\n indeterminate: input.shownIndeterminate,\n pending: input.pending,\n disabled: input.disabled,\n };\n\n const element = useRender<ComponentPropsWithRef<\"input\">, CheckboxState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n ref: input.ref,\n // Pass-through layer: a `render` element's own props win over these (`role` included).\n props: rest,\n libraryProps: input.libraryProps,\n });\n\n return useTransitionBoundary(\"Checkbox\", transition, element);\n}\n\nCheckbox.displayName = \"Checkbox\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqIA,SAAgB,SAAS,EACvB,SACA,gBACA,gBAAgB,OAChB,qBACA,UACA,YACA,WACA,OACA,QACA,GAAG,QACa;CAChB,MAAM,QAAQ,kBAAkB;EAC9B,WAAW;EACX;EACA;EACA;EACA;EACA,KAAK;EACL,kBAAkB,SAAS,gBAAgB,YAAY,OAAO,UAAU,SAAS;EACjF;CACF,CAAC;CAED,MAAM,QAAuB;EAC3B,SAAS,MAAM;EACf,eAAe,MAAM;EACrB,SAAS,MAAM;EACf,UAAU,MAAM;CAClB;CAEA,MAAM,UAAU,UAAyD;EACvE,gBAAgB;EAChB;EACA;EACA;EACA;EACA,UAAU,KAAA;EACV,KAAK,MAAM;EAEX,OAAO;EACP,cAAc,MAAM;CACtB,CAAC;CAED,OAAO,sBAAsB,YAAY,YAAY,OAAO;AAC9D;AAEA,SAAS,cAAc"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useTransitionBoundary } from "../internal/transition-boundary.mjs";
|
|
3
3
|
import { useRender } from "../internal/use-render.mjs";
|
|
4
|
-
import { syncPresences } from "../internal/sync-presence.mjs";
|
|
5
|
-
import { useNativeChecked } from "../internal/use-native-checked.mjs";
|
|
6
|
-
import { groupMemberProps } from "../internal/group-member.mjs";
|
|
4
|
+
import { syncPresences } from "../internal/form/sync-presence.mjs";
|
|
5
|
+
import { useNativeChecked } from "../internal/form/use-native-checked.mjs";
|
|
6
|
+
import { groupMemberProps } from "../internal/form/group-member.mjs";
|
|
7
7
|
import { useCheckboxGroupContext } from "./checkbox-group-context.mjs";
|
|
8
8
|
import { useLayoutEffect } from "react";
|
|
9
9
|
//#region src/checkbox-group/checkbox-group-item.tsx
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox-group-item.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-item.tsx"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ViewTransitionClass } from \"react\";\nimport { groupMemberProps } from \"../internal/group-member.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useNativeChecked } from \"../internal/use-native-checked.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useCheckboxGroupContext } from \"./checkbox-group-context.js\";\nimport { syncPresences } from \"../internal/sync-presence.js\";\n\n/**\n * State of `CheckboxGroup.Item`, passed to the function forms of `className`, `style` and `render`.\n */\nexport interface CheckboxGroupItemState {\n /** The Item's `value` prop. */\n readonly value: string;\n /** Optimistic: true as soon as the user checks this box, before the action settles. */\n readonly checked: boolean;\n /** The Root is pending and this box's optimistic state differs from its committed state. */\n readonly pending: boolean;\n /** Disabled by its own prop or by `Root disabled`. */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `CheckboxGroup.Item`.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport interface CheckboxGroupItemProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"type\"\n | \"name\"\n | \"value\"\n | \"checked\"\n | \"defaultChecked\"\n | \"defaultValue\"\n | \"form\"\n | \"required\"\n | \"aria-checked\"\n | \"onChange\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** The value this box contributes when checked. Must be unique within the Root. */\n value: string;\n /**\n * Native `disabled`: unfocusable, never dispatches, barred from constraint validation. A\n * `Parent` leaves a disabled Item's value alone and derives its state without it; a checked\n * disabled Item does not satisfy the group's `required`.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Forwarded to the Item's `<ViewTransition default>`. Default: no boundary. Fires only on the\n * commit that settles the action (or rolls it back), never on the optimistic check; animate the\n * check itself with CSS on `:checked`.\n *\n * Static: setting or unsetting it remounts the element. Any value, `\"none\"` included, makes a\n * mount or `<Activity>` reveal inside a transition start a document view transition (a ~250 ms\n * page cross-fade that the next transition waits for).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxGroupItemState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxGroupItemState>;\n /** Replace the rendered element. Must keep an `<input>`; the library sets `type=\"checkbox\"`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, CheckboxGroupItemState>;\n}\n\n/**\n * One `<input type=\"checkbox\">` of the group, checked while its `value` is in the group's set.\n * Its DOM `checked` is the optimistic state (`checked={optimistic.has(value)}`): react-dom\n * restores a controlled input to its props after every event, and only the sync-lane optimistic\n * value survives that restore.\n *\n * Owned keys (conventions 1.2; a `render` element's value is overridden): `type`, `name`,\n * `value`, `checked`, `defaultChecked` (never rendered), `disabled`, `form`, `required`\n * (computed by the Root from its `required` prop), `aria-checked` (removed), `data-checked`,\n * `data-pending`, `data-disabled`; inside a `Field.Root` also `aria-invalid` (the Field's).\n * `onChange` is merged: a `render` element's own handler runs\n * first, then the library's. `role` passes through.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport function CheckboxGroupItem({\n value,\n disabled: disabledProp = false,\n transition,\n className,\n style,\n render,\n ...rest\n}: CheckboxGroupItemProps) {\n const ctx = useCheckboxGroupContext(\"CheckboxGroup.Item\");\n const checked = ctx.optimistic.has(value);\n const pending = ctx.state.pending && checked !== ctx.committed.has(value);\n const disabled = ctx.state.disabled || disabledProp;\n const required = ctx.required;\n\n // The Root needs every Item's own `disabled` for the Parents and `required` (design 6.2, 7).\n const { registerItem } = ctx;\n useLayoutEffect(() => registerItem(value, disabledProp), [registerItem, value, disabledProp]);\n\n // Group mode: element check and re-apply only; the Root reports the residual paths once.\n const inputRef = useNativeChecked({\n type: \"checkbox\",\n component: \"CheckboxGroup.Item\",\n checked,\n group: true,\n onItemMounted: (el) => {\n // Hydration keeps server attributes that differ from the client render (React only warns).\n // An Item hydrating after its Root can render a different state than the server did (a\n // click on an already hydrated box), and stale attributes would stay until the next change.\n if (el !== null) {\n syncPresences(el, {\n \"data-checked\": checked,\n \"data-pending\": pending,\n \"data-disabled\": disabled,\n required,\n });\n }\n ctx.onItemMounted(el);\n },\n defaultChecked: ctx.defaultValue === undefined ? undefined : ctx.defaultValue.has(value),\n });\n\n const state: CheckboxGroupItemState = { value, checked, pending, disabled };\n\n const element = useRender<ComponentPropsWithRef<\"input\">, CheckboxGroupItemState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n ref: inputRef,\n // Pass-through layer: a `render` element's own props win over these.\n props: rest,\n libraryProps: groupMemberProps({\n type: \"checkbox\",\n component: \"CheckboxGroup.Item\",\n name: ctx.name,\n form: ctx.form,\n value,\n required,\n checked,\n pending,\n effectiveDisabled: disabled,\n ownDisabled: disabledProp,\n // Inside a Field (owned there): the group's invalid state, since the fieldset cannot carry it.\n invalid: ctx.fieldInvalid,\n activate: (event) => ctx.toggle(value, !checked, event),\n }),\n });\n\n return useTransitionBoundary(\"CheckboxGroup.Item\", transition, element);\n}\n\nCheckboxGroupItem.displayName = \"CheckboxGroupItem\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyFA,SAAgB,kBAAkB,EAChC,OACA,UAAU,eAAe,OACzB,YACA,WACA,OACA,QACA,GAAG,QACsB;CACzB,MAAM,MAAM,wBAAwB,oBAAoB;CACxD,MAAM,UAAU,IAAI,WAAW,IAAI,KAAK;CACxC,MAAM,UAAU,IAAI,MAAM,WAAW,YAAY,IAAI,UAAU,IAAI,KAAK;CACxE,MAAM,WAAW,IAAI,MAAM,YAAY;CACvC,MAAM,WAAW,IAAI;CAGrB,MAAM,EAAE,iBAAiB;CACzB,sBAAsB,aAAa,OAAO,YAAY,GAAG;EAAC;EAAc;EAAO;CAAY,CAAC;CAG5F,MAAM,WAAW,iBAAiB;EAChC,MAAM;EACN,WAAW;EACX;EACA,OAAO;EACP,gBAAgB,OAAO;GAIrB,IAAI,OAAO,MACT,cAAc,IAAI;IAChB,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB;GACF,CAAC;GAEH,IAAI,cAAc,EAAE;EACtB;EACA,gBAAgB,IAAI,iBAAiB,KAAA,IAAY,KAAA,IAAY,IAAI,aAAa,IAAI,KAAK;CACzF,CAAC;CAID,MAAM,UAAU,UAAkE;EAChF,gBAAgB;EAChB;EACA,OAAA;GALsC;GAAO;GAAS;GAAS;EAK3D;EACJ;EACA;EACA,UAAU,KAAA;EACV,KAAK;EAEL,OAAO;EACP,cAAc,iBAAiB;GAC7B,MAAM;GACN,WAAW;GACX,MAAM,IAAI;GACV,MAAM,IAAI;GACV;GACA;GACA;GACA;GACA,mBAAmB;GACnB,aAAa;GAEb,SAAS,IAAI;GACb,WAAW,UAAU,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK;EACxD,CAAC;CACH,CAAC;CAED,OAAO,sBAAsB,sBAAsB,YAAY,OAAO;AACxE;AAEA,kBAAkB,cAAc"}
|
|
1
|
+
{"version":3,"file":"checkbox-group-item.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-item.tsx"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ViewTransitionClass } from \"react\";\nimport { groupMemberProps } from \"../internal/form/group-member.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useNativeChecked } from \"../internal/form/use-native-checked.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useCheckboxGroupContext } from \"./checkbox-group-context.js\";\nimport { syncPresences } from \"../internal/form/sync-presence.js\";\n\n/**\n * State of `CheckboxGroup.Item`, passed to the function forms of `className`, `style` and `render`.\n */\nexport interface CheckboxGroupItemState {\n /** The Item's `value` prop. */\n readonly value: string;\n /** Optimistic: true as soon as the user checks this box, before the action settles. */\n readonly checked: boolean;\n /** The Root is pending and this box's optimistic state differs from its committed state. */\n readonly pending: boolean;\n /** Disabled by its own prop or by `Root disabled`. */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `CheckboxGroup.Item`.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport interface CheckboxGroupItemProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"type\"\n | \"name\"\n | \"value\"\n | \"checked\"\n | \"defaultChecked\"\n | \"defaultValue\"\n | \"form\"\n | \"required\"\n | \"aria-checked\"\n | \"onChange\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** The value this box contributes when checked. Must be unique within the Root. */\n value: string;\n /**\n * Native `disabled`: unfocusable, never dispatches, barred from constraint validation. A\n * `Parent` leaves a disabled Item's value alone and derives its state without it; a checked\n * disabled Item does not satisfy the group's `required`.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Forwarded to the Item's `<ViewTransition default>`. Default: no boundary. Fires only on the\n * commit that settles the action (or rolls it back), never on the optimistic check; animate the\n * check itself with CSS on `:checked`.\n *\n * Static: setting or unsetting it remounts the element. Any value, `\"none\"` included, makes a\n * mount or `<Activity>` reveal inside a transition start a document view transition (a ~250 ms\n * page cross-fade that the next transition waits for).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxGroupItemState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxGroupItemState>;\n /** Replace the rendered element. Must keep an `<input>`; the library sets `type=\"checkbox\"`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, CheckboxGroupItemState>;\n}\n\n/**\n * One `<input type=\"checkbox\">` of the group, checked while its `value` is in the group's set.\n * Its DOM `checked` is the optimistic state (`checked={optimistic.has(value)}`): react-dom\n * restores a controlled input to its props after every event, and only the sync-lane optimistic\n * value survives that restore.\n *\n * Owned keys (conventions 1.2; a `render` element's value is overridden): `type`, `name`,\n * `value`, `checked`, `defaultChecked` (never rendered), `disabled`, `form`, `required`\n * (computed by the Root from its `required` prop), `aria-checked` (removed), `data-checked`,\n * `data-pending`, `data-disabled`; inside a `Field.Root` also `aria-invalid` (the Field's).\n * `onChange` is merged: a `render` element's own handler runs\n * first, then the library's. `role` passes through.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport function CheckboxGroupItem({\n value,\n disabled: disabledProp = false,\n transition,\n className,\n style,\n render,\n ...rest\n}: CheckboxGroupItemProps) {\n const ctx = useCheckboxGroupContext(\"CheckboxGroup.Item\");\n const checked = ctx.optimistic.has(value);\n const pending = ctx.state.pending && checked !== ctx.committed.has(value);\n const disabled = ctx.state.disabled || disabledProp;\n const required = ctx.required;\n\n // The Root needs every Item's own `disabled` for the Parents and `required` (design 6.2, 7).\n const { registerItem } = ctx;\n useLayoutEffect(() => registerItem(value, disabledProp), [registerItem, value, disabledProp]);\n\n // Group mode: element check and re-apply only; the Root reports the residual paths once.\n const inputRef = useNativeChecked({\n type: \"checkbox\",\n component: \"CheckboxGroup.Item\",\n checked,\n group: true,\n onItemMounted: (el) => {\n // Hydration keeps server attributes that differ from the client render (React only warns).\n // An Item hydrating after its Root can render a different state than the server did (a\n // click on an already hydrated box), and stale attributes would stay until the next change.\n if (el !== null) {\n syncPresences(el, {\n \"data-checked\": checked,\n \"data-pending\": pending,\n \"data-disabled\": disabled,\n required,\n });\n }\n ctx.onItemMounted(el);\n },\n defaultChecked: ctx.defaultValue === undefined ? undefined : ctx.defaultValue.has(value),\n });\n\n const state: CheckboxGroupItemState = { value, checked, pending, disabled };\n\n const element = useRender<ComponentPropsWithRef<\"input\">, CheckboxGroupItemState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n ref: inputRef,\n // Pass-through layer: a `render` element's own props win over these.\n props: rest,\n libraryProps: groupMemberProps({\n type: \"checkbox\",\n component: \"CheckboxGroup.Item\",\n name: ctx.name,\n form: ctx.form,\n value,\n required,\n checked,\n pending,\n effectiveDisabled: disabled,\n ownDisabled: disabledProp,\n // Inside a Field (owned there): the group's invalid state, since the fieldset cannot carry it.\n invalid: ctx.fieldInvalid,\n activate: (event) => ctx.toggle(value, !checked, event),\n }),\n });\n\n return useTransitionBoundary(\"CheckboxGroup.Item\", transition, element);\n}\n\nCheckboxGroupItem.displayName = \"CheckboxGroupItem\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyFA,SAAgB,kBAAkB,EAChC,OACA,UAAU,eAAe,OACzB,YACA,WACA,OACA,QACA,GAAG,QACsB;CACzB,MAAM,MAAM,wBAAwB,oBAAoB;CACxD,MAAM,UAAU,IAAI,WAAW,IAAI,KAAK;CACxC,MAAM,UAAU,IAAI,MAAM,WAAW,YAAY,IAAI,UAAU,IAAI,KAAK;CACxE,MAAM,WAAW,IAAI,MAAM,YAAY;CACvC,MAAM,WAAW,IAAI;CAGrB,MAAM,EAAE,iBAAiB;CACzB,sBAAsB,aAAa,OAAO,YAAY,GAAG;EAAC;EAAc;EAAO;CAAY,CAAC;CAG5F,MAAM,WAAW,iBAAiB;EAChC,MAAM;EACN,WAAW;EACX;EACA,OAAO;EACP,gBAAgB,OAAO;GAIrB,IAAI,OAAO,MACT,cAAc,IAAI;IAChB,gBAAgB;IAChB,gBAAgB;IAChB,iBAAiB;IACjB;GACF,CAAC;GAEH,IAAI,cAAc,EAAE;EACtB;EACA,gBAAgB,IAAI,iBAAiB,KAAA,IAAY,KAAA,IAAY,IAAI,aAAa,IAAI,KAAK;CACzF,CAAC;CAID,MAAM,UAAU,UAAkE;EAChF,gBAAgB;EAChB;EACA,OAAA;GALsC;GAAO;GAAS;GAAS;EAK3D;EACJ;EACA;EACA,UAAU,KAAA;EACV,KAAK;EAEL,OAAO;EACP,cAAc,iBAAiB;GAC7B,MAAM;GACN,WAAW;GACX,MAAM,IAAI;GACV,MAAM,IAAI;GACV;GACA;GACA;GACA;GACA,mBAAmB;GACnB,aAAa;GAEb,SAAS,IAAI;GACb,WAAW,UAAU,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK;EACxD,CAAC;CACH,CAAC;CAED,OAAO,sBAAsB,sBAAsB,YAAY,OAAO;AACxE;AAEA,kBAAkB,cAAc"}
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
import { dataAttr } from "../internal/data-attr.mjs";
|
|
3
3
|
import { useTransitionBoundary } from "../internal/transition-boundary.mjs";
|
|
4
4
|
import { useRender } from "../internal/use-render.mjs";
|
|
5
|
-
import { syncPresences } from "../internal/sync-presence.mjs";
|
|
6
|
-
import { useFormReset } from "../internal/use-form-reset.mjs";
|
|
7
|
-
import { guardCheckableChange, useNativeChecked } from "../internal/use-native-checked.mjs";
|
|
5
|
+
import { syncPresences } from "../internal/form/sync-presence.mjs";
|
|
6
|
+
import { useFormReset } from "../internal/form/use-form-reset.mjs";
|
|
7
|
+
import { guardCheckableChange, useNativeChecked } from "../internal/form/use-native-checked.mjs";
|
|
8
8
|
import { enabledValues, useCheckboxGroupContext } from "./checkbox-group-context.mjs";
|
|
9
9
|
import { useHydratedMount } from "../internal/use-hydrated-mount.mjs";
|
|
10
10
|
import { useCallback, useLayoutEffect, useMemo, useRef } from "react";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox-group-parent.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-parent.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\nimport type { ChangeEvent, ComponentPropsWithRef, CSSProperties, ViewTransitionClass } from \"react\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useHydratedMount } from \"../internal/use-hydrated-mount.js\";\nimport { guardCheckableChange, useNativeChecked } from \"../internal/use-native-checked.js\";\nimport { useFormReset } from \"../internal/use-form-reset.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { enabledValues, useCheckboxGroupContext } from \"./checkbox-group-context.js\";\nimport type { CheckboxGroupPatch } from \"./checkbox-group-context.js\";\nimport { syncPresences } from \"../internal/sync-presence.js\";\n\n/**\n * State of `CheckboxGroup.Parent`, passed to the function forms of `className`, `style` and\n * `render`.\n */\nexport interface CheckboxGroupParentState {\n /** The Parent's `values` prop: the Items it checks and unchecks. */\n readonly values: readonly string[];\n /** Every value in `values` is optimistically checked (`false` when `values` is empty). */\n readonly checked: boolean;\n /**\n * Some but not all of `values` are optimistically checked. Never true together with\n * `checked`. Not suspended while pending (it is derived from optimistic state).\n */\n readonly indeterminate: boolean;\n /** The Root is pending and at least one of `values` differs between optimistic and committed. */\n readonly pending: boolean;\n /** Disabled by its own prop or by `Root disabled`. */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `CheckboxGroup.Parent`.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport interface CheckboxGroupParentProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"type\"\n | \"name\"\n | \"value\"\n | \"checked\"\n | \"defaultChecked\"\n | \"defaultValue\"\n | \"form\"\n | \"required\"\n | \"autoComplete\"\n | \"aria-checked\"\n | \"onChange\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * The Item values this Parent controls (usually every Item of the group). Its checked and\n * mixed states are derived from them; its click checks or unchecks all of them. Values with\n * no Item are still added to / removed from the group's value.\n *\n * Values whose Items are disabled (their own `disabled` prop) are left alone: the click does\n * not change them and the derivation ignores them, so the Parent shows checked when every\n * enabled Item is. When every value has only disabled Items, the Parent acts on all of them\n * (disable the Parent to make it inert). Before hydration the server-rendered state counts\n * disabled Items too; it settles when the Items hydrate.\n */\n values: string[];\n /**\n * Native `disabled`: unfocusable, never dispatches.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Forwarded to the Parent's `<ViewTransition default>`. Default: no boundary. Fires only on the\n * commit that settles the action (or rolls it back), never on the optimistic flip; animate the\n * flip itself with CSS on `:checked` / `:indeterminate`.\n *\n * Static: setting or unsetting it remounts the element. Any value, `\"none\"` included, makes a\n * mount or `<Activity>` reveal inside a transition start a document view transition (a ~250 ms\n * page cross-fade that the next transition waits for).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxGroupParentState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxGroupParentState>;\n /** Replace the rendered element. Must keep an `<input>`; the library sets `type=\"checkbox\"`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, CheckboxGroupParentState>;\n}\n\n/** `checked` / `indeterminate` of a Parent over `values` against `set` (design 6.1). */\nfunction derive(values: readonly string[], set: ReadonlySet<string>) {\n let inSet = 0;\n for (const v of values) if (set.has(v)) inSet += 1;\n const checked = values.length > 0 && inSet === values.length;\n return { checked, indeterminate: inSet > 0 && !checked };\n}\n\n/**\n * The mixed-state \"select all\" checkbox of a group (WAI-ARIA APG \"Checkbox (Mixed-State)\"):\n * `<input type=\"checkbox\">` checked when every value in `values` is in the group's optimistic\n * set, mixed (`el.indeterminate`, `data-indeterminate`) when some are. A click checks every value\n * when mixed, unchecks every value when checked, and from unchecked restores the last partial\n * combination of its values the group committed (seeded at mount), else checks every value. Each\n * click is one dispatch through the Root's `valueChangeAction`. Never submitted (no `name`).\n * \"Its values\" are those whose Items are enabled: disabled Items are left alone (see `values`).\n *\n * Owned keys (conventions 1.2): `type`, `name` (removed), `value` (removed), `checked`,\n * `defaultChecked`, `indeterminate` (stripped; the property is set), `required` (removed), `form`\n * (removed), `autoComplete` (`\"off\"`), `disabled`, `aria-checked` (removed), `data-checked`, `data-indeterminate`,\n * `data-pending`, `data-disabled`. `onChange` is merged.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport function CheckboxGroupParent({\n values,\n disabled: disabledProp = false,\n transition,\n className,\n style,\n render,\n ...rest\n}: CheckboxGroupParentProps) {\n const ctx = useCheckboxGroupContext(\"CheckboxGroup.Parent\");\n // The values the Parent acts on: `values` minus disabled Items (design 6.2). A hydration\n // render uses every value, as the server did (it cannot know which Items are disabled), so\n // that the DOM `checked` it hydrates can be compared with the derivation for the\n // pre-hydration report below, also when this Parent hydrates after the Items registered.\n const hydrating = useHydratedMount();\n const { disabledItems } = ctx;\n const effective = useMemo(\n () => (hydrating ? values : enabledValues(values, disabledItems)),\n [hydrating, values, disabledItems],\n );\n const { checked, indeterminate } = derive(effective, ctx.optimistic);\n const pending =\n ctx.state.pending && values.some((v) => ctx.optimistic.has(v) !== ctx.committed.has(v));\n const disabled = ctx.state.disabled || disabledProp;\n\n // The APG restore memory: the last partial combination of `values` the group committed\n // (design 6.2). Committed, not optimistic, so a partial state that only ever rolled back is\n // never restored. The first run seeds it from the mount-time value.\n const memory = useRef<readonly string[] | null>(null);\n const { committed } = ctx;\n useLayoutEffect(() => {\n const inCommitted = effective.filter((v) => committed.has(v));\n if (inCommitted.length > 0 && inCommitted.length < effective.length) {\n memory.current = inCommitted;\n }\n }, [committed, effective]);\n\n const inputRef = useNativeChecked({\n type: \"checkbox\",\n component: \"CheckboxGroup.Parent\",\n checked,\n indeterminate,\n group: true,\n onItemMounted: (el) => {\n if (el !== null) {\n // A click before hydration flipped the box (design 8.1): report it as the Parent's\n // semantic before the Root reads the group (which leaves disabled Items alone). Firefox's\n // form-state restoration cannot cause this: the Parent renders `autocomplete=\"off\"`.\n if (el.checked !== checked) ctx.reportParent(values, el.checked);\n syncPresences(el, {\n \"data-checked\": checked,\n \"data-indeterminate\": indeterminate,\n \"data-pending\": pending,\n \"data-disabled\": disabled,\n });\n }\n ctx.onItemMounted(el);\n },\n defaultChecked:\n ctx.defaultValue === undefined ? undefined : derive(effective, ctx.defaultValue).checked,\n });\n\n // A form reset sets the Parent's DOM `checked` to its `defaultChecked`, which in controlled\n // mode is React's mount-time value and can be stale (its `values` changed, it mounted after the\n // Items with another value). The Parent re-renders only if the Root dispatches; otherwise put\n // the derivation back (the Root's own microtask, queued after this one, may still dispatch,\n // and the re-render re-applies `checked`).\n const node = useRef<HTMLInputElement | null>(null);\n const ref = useCallback(\n (el: HTMLInputElement) => {\n node.current = el;\n const cleanup = inputRef(el);\n return () => {\n node.current = null;\n if (typeof cleanup === \"function\") cleanup();\n };\n },\n [inputRef],\n );\n useFormReset(node, () => {\n const el = node.current;\n if (el !== null && el.checked !== checked) el.checked = checked;\n });\n\n /** The click cycle of design 6.2. */\n const cyclePatch = (): CheckboxGroupPatch => {\n if (checked) return { added: [], removed: [...effective] };\n if (indeterminate) {\n return { added: effective.filter((v) => !ctx.optimistic.has(v)), removed: [] };\n }\n const restore = memory.current?.filter((v) => effective.includes(v)) ?? [];\n return { added: restore.length > 0 ? restore : [...effective], removed: [] };\n };\n\n const state: CheckboxGroupParentState = { values, checked, indeterminate, pending, disabled };\n\n const element = useRender<ComponentPropsWithRef<\"input\">, CheckboxGroupParentState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n ref,\n props: rest,\n libraryProps: {\n type: \"checkbox\",\n // A Parent is not a value: it never posts and is never required.\n name: undefined,\n value: undefined,\n required: undefined,\n form: undefined,\n // Nothing to restore (it is not a value): without this, Firefox restores its `checked` on\n // reload and the mount read would take it for a click before hydration (design 8.1).\n autoComplete: \"off\",\n checked,\n defaultChecked: undefined,\n // Not a DOM attribute; the hook sets the property. Owned so that a `render` element's own\n // `indeterminate` prop (which react-dom would warn about) is stripped.\n ...{ indeterminate: undefined },\n \"aria-checked\": undefined,\n disabled: disabledProp,\n \"data-checked\": dataAttr(checked),\n \"data-indeterminate\": dataAttr(indeterminate),\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n onChange: (event: ChangeEvent<HTMLInputElement>) => {\n if (disabled) return;\n const nativeEvent = event.nativeEvent;\n guardCheckableChange(\n nativeEvent,\n () => ctx.apply(cyclePatch(), nativeEvent),\n \"CheckboxGroup.Parent\",\n );\n },\n },\n });\n\n return useTransitionBoundary(\"CheckboxGroup.Parent\", transition, element);\n}\n\nCheckboxGroupParent.displayName = \"CheckboxGroupParent\";\n"],"mappings":";;;;;;;;;;;;AA6FA,SAAS,OAAO,QAA2B,KAA0B;CACnE,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,IAAI,CAAC,GAAG,SAAS;CACjD,MAAM,UAAU,OAAO,SAAS,KAAK,UAAU,OAAO;CACtD,OAAO;EAAE;EAAS,eAAe,QAAQ,KAAK,CAAC;CAAQ;AACzD;;;;;;;;;;;;;;;;;AAkBA,SAAgB,oBAAoB,EAClC,QACA,UAAU,eAAe,OACz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box-group/checkbox-group-parent.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\nimport type { ChangeEvent, ComponentPropsWithRef, CSSProperties, ViewTransitionClass } from \"react\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useHydratedMount } from \"../internal/use-hydrated-mount.js\";\nimport { guardCheckableChange, useNativeChecked } from \"../internal/form/use-native-checked.js\";\nimport { useFormReset } from \"../internal/form/use-form-reset.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { enabledValues, useCheckboxGroupContext } from \"./checkbox-group-context.js\";\nimport type { CheckboxGroupPatch } from \"./checkbox-group-context.js\";\nimport { syncPresences } from \"../internal/form/sync-presence.js\";\n\n/**\n * State of `CheckboxGroup.Parent`, passed to the function forms of `className`, `style` and\n * `render`.\n */\nexport interface CheckboxGroupParentState {\n /** The Parent's `values` prop: the Items it checks and unchecks. */\n readonly values: readonly string[];\n /** Every value in `values` is optimistically checked (`false` when `values` is empty). */\n readonly checked: boolean;\n /**\n * Some but not all of `values` are optimistically checked. Never true together with\n * `checked`. Not suspended while pending (it is derived from optimistic state).\n */\n readonly indeterminate: boolean;\n /** The Root is pending and at least one of `values` differs between optimistic and committed. */\n readonly pending: boolean;\n /** Disabled by its own prop or by `Root disabled`. */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `CheckboxGroup.Parent`.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport interface CheckboxGroupParentProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"type\"\n | \"name\"\n | \"value\"\n | \"checked\"\n | \"defaultChecked\"\n | \"defaultValue\"\n | \"form\"\n | \"required\"\n | \"autoComplete\"\n | \"aria-checked\"\n | \"onChange\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * The Item values this Parent controls (usually every Item of the group). Its checked and\n * mixed states are derived from them; its click checks or unchecks all of them. Values with\n * no Item are still added to / removed from the group's value.\n *\n * Values whose Items are disabled (their own `disabled` prop) are left alone: the click does\n * not change them and the derivation ignores them, so the Parent shows checked when every\n * enabled Item is. When every value has only disabled Items, the Parent acts on all of them\n * (disable the Parent to make it inert). Before hydration the server-rendered state counts\n * disabled Items too; it settles when the Items hydrate.\n */\n values: string[];\n /**\n * Native `disabled`: unfocusable, never dispatches.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Forwarded to the Parent's `<ViewTransition default>`. Default: no boundary. Fires only on the\n * commit that settles the action (or rolls it back), never on the optimistic flip; animate the\n * flip itself with CSS on `:checked` / `:indeterminate`.\n *\n * Static: setting or unsetting it remounts the element. Any value, `\"none\"` included, makes a\n * mount or `<Activity>` reveal inside a transition start a document view transition (a ~250 ms\n * page cross-fade that the next transition waits for).\n */\n transition?: ViewTransitionClass;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxGroupParentState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxGroupParentState>;\n /** Replace the rendered element. Must keep an `<input>`; the library sets `type=\"checkbox\"`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, CheckboxGroupParentState>;\n}\n\n/** `checked` / `indeterminate` of a Parent over `values` against `set` (design 6.1). */\nfunction derive(values: readonly string[], set: ReadonlySet<string>) {\n let inSet = 0;\n for (const v of values) if (set.has(v)) inSet += 1;\n const checked = values.length > 0 && inSet === values.length;\n return { checked, indeterminate: inSet > 0 && !checked };\n}\n\n/**\n * The mixed-state \"select all\" checkbox of a group (WAI-ARIA APG \"Checkbox (Mixed-State)\"):\n * `<input type=\"checkbox\">` checked when every value in `values` is in the group's optimistic\n * set, mixed (`el.indeterminate`, `data-indeterminate`) when some are. A click checks every value\n * when mixed, unchecks every value when checked, and from unchecked restores the last partial\n * combination of its values the group committed (seeded at mount), else checks every value. Each\n * click is one dispatch through the Root's `valueChangeAction`. Never submitted (no `name`).\n * \"Its values\" are those whose Items are enabled: disabled Items are left alone (see `values`).\n *\n * Owned keys (conventions 1.2): `type`, `name` (removed), `value` (removed), `checked`,\n * `defaultChecked`, `indeterminate` (stripped; the property is set), `required` (removed), `form`\n * (removed), `autoComplete` (`\"off\"`), `disabled`, `aria-checked` (removed), `data-checked`, `data-indeterminate`,\n * `data-pending`, `data-disabled`. `onChange` is merged.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport function CheckboxGroupParent({\n values,\n disabled: disabledProp = false,\n transition,\n className,\n style,\n render,\n ...rest\n}: CheckboxGroupParentProps) {\n const ctx = useCheckboxGroupContext(\"CheckboxGroup.Parent\");\n // The values the Parent acts on: `values` minus disabled Items (design 6.2). A hydration\n // render uses every value, as the server did (it cannot know which Items are disabled), so\n // that the DOM `checked` it hydrates can be compared with the derivation for the\n // pre-hydration report below, also when this Parent hydrates after the Items registered.\n const hydrating = useHydratedMount();\n const { disabledItems } = ctx;\n const effective = useMemo(\n () => (hydrating ? values : enabledValues(values, disabledItems)),\n [hydrating, values, disabledItems],\n );\n const { checked, indeterminate } = derive(effective, ctx.optimistic);\n const pending =\n ctx.state.pending && values.some((v) => ctx.optimistic.has(v) !== ctx.committed.has(v));\n const disabled = ctx.state.disabled || disabledProp;\n\n // The APG restore memory: the last partial combination of `values` the group committed\n // (design 6.2). Committed, not optimistic, so a partial state that only ever rolled back is\n // never restored. The first run seeds it from the mount-time value.\n const memory = useRef<readonly string[] | null>(null);\n const { committed } = ctx;\n useLayoutEffect(() => {\n const inCommitted = effective.filter((v) => committed.has(v));\n if (inCommitted.length > 0 && inCommitted.length < effective.length) {\n memory.current = inCommitted;\n }\n }, [committed, effective]);\n\n const inputRef = useNativeChecked({\n type: \"checkbox\",\n component: \"CheckboxGroup.Parent\",\n checked,\n indeterminate,\n group: true,\n onItemMounted: (el) => {\n if (el !== null) {\n // A click before hydration flipped the box (design 8.1): report it as the Parent's\n // semantic before the Root reads the group (which leaves disabled Items alone). Firefox's\n // form-state restoration cannot cause this: the Parent renders `autocomplete=\"off\"`.\n if (el.checked !== checked) ctx.reportParent(values, el.checked);\n syncPresences(el, {\n \"data-checked\": checked,\n \"data-indeterminate\": indeterminate,\n \"data-pending\": pending,\n \"data-disabled\": disabled,\n });\n }\n ctx.onItemMounted(el);\n },\n defaultChecked:\n ctx.defaultValue === undefined ? undefined : derive(effective, ctx.defaultValue).checked,\n });\n\n // A form reset sets the Parent's DOM `checked` to its `defaultChecked`, which in controlled\n // mode is React's mount-time value and can be stale (its `values` changed, it mounted after the\n // Items with another value). The Parent re-renders only if the Root dispatches; otherwise put\n // the derivation back (the Root's own microtask, queued after this one, may still dispatch,\n // and the re-render re-applies `checked`).\n const node = useRef<HTMLInputElement | null>(null);\n const ref = useCallback(\n (el: HTMLInputElement) => {\n node.current = el;\n const cleanup = inputRef(el);\n return () => {\n node.current = null;\n if (typeof cleanup === \"function\") cleanup();\n };\n },\n [inputRef],\n );\n useFormReset(node, () => {\n const el = node.current;\n if (el !== null && el.checked !== checked) el.checked = checked;\n });\n\n /** The click cycle of design 6.2. */\n const cyclePatch = (): CheckboxGroupPatch => {\n if (checked) return { added: [], removed: [...effective] };\n if (indeterminate) {\n return { added: effective.filter((v) => !ctx.optimistic.has(v)), removed: [] };\n }\n const restore = memory.current?.filter((v) => effective.includes(v)) ?? [];\n return { added: restore.length > 0 ? restore : [...effective], removed: [] };\n };\n\n const state: CheckboxGroupParentState = { values, checked, indeterminate, pending, disabled };\n\n const element = useRender<ComponentPropsWithRef<\"input\">, CheckboxGroupParentState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n ref,\n props: rest,\n libraryProps: {\n type: \"checkbox\",\n // A Parent is not a value: it never posts and is never required.\n name: undefined,\n value: undefined,\n required: undefined,\n form: undefined,\n // Nothing to restore (it is not a value): without this, Firefox restores its `checked` on\n // reload and the mount read would take it for a click before hydration (design 8.1).\n autoComplete: \"off\",\n checked,\n defaultChecked: undefined,\n // Not a DOM attribute; the hook sets the property. Owned so that a `render` element's own\n // `indeterminate` prop (which react-dom would warn about) is stripped.\n ...{ indeterminate: undefined },\n \"aria-checked\": undefined,\n disabled: disabledProp,\n \"data-checked\": dataAttr(checked),\n \"data-indeterminate\": dataAttr(indeterminate),\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n onChange: (event: ChangeEvent<HTMLInputElement>) => {\n if (disabled) return;\n const nativeEvent = event.nativeEvent;\n guardCheckableChange(\n nativeEvent,\n () => ctx.apply(cyclePatch(), nativeEvent),\n \"CheckboxGroup.Parent\",\n );\n },\n },\n });\n\n return useTransitionBoundary(\"CheckboxGroup.Parent\", transition, element);\n}\n\nCheckboxGroupParent.displayName = \"CheckboxGroupParent\";\n"],"mappings":";;;;;;;;;;;;AA6FA,SAAS,OAAO,QAA2B,KAA0B;CACnE,IAAI,QAAQ;CACZ,KAAK,MAAM,KAAK,QAAQ,IAAI,IAAI,IAAI,CAAC,GAAG,SAAS;CACjD,MAAM,UAAU,OAAO,SAAS,KAAK,UAAU,OAAO;CACtD,OAAO;EAAE;EAAS,eAAe,QAAQ,KAAK,CAAC;CAAQ;AACzD;;;;;;;;;;;;;;;;;AAkBA,SAAgB,oBAAoB,EAClC,QACA,UAAU,eAAe,OACzB,YACA,WACA,OACA,QACA,GAAG,QACwB;CAC3B,MAAM,MAAM,wBAAwB,sBAAsB;CAK1D,MAAM,YAAY,iBAAiB;CACnC,MAAM,EAAE,kBAAkB;CAC1B,MAAM,YAAY,cACT,YAAY,SAAS,cAAc,QAAQ,aAAa,GAC/D;EAAC;EAAW;EAAQ;CAAa,CACnC;CACA,MAAM,EAAE,SAAS,kBAAkB,OAAO,WAAW,IAAI,UAAU;CACnE,MAAM,UACJ,IAAI,MAAM,WAAW,OAAO,MAAM,MAAM,IAAI,WAAW,IAAI,CAAC,MAAM,IAAI,UAAU,IAAI,CAAC,CAAC;CACxF,MAAM,WAAW,IAAI,MAAM,YAAY;CAKvC,MAAM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AC;EACzE,OAAO;GAAE,OAAO,QAAQ,SAAS,IAAI,UAAU,CAAC,GAAG,SAAS;GAAG,SAAS,CAAC;EAAE;CAC7E;CAIA,MAAM,UAAU,UAAoE;EAClF,gBAAgB;EAChB;EACA,OAAA;GALwC;GAAQ;GAAS;GAAe;GAAS;EAK7E;EACJ;EACA;EACA,UAAU,KAAA;EACV;EACA,OAAO;EACP,cAAc;GACZ,MAAM;GAEN,MAAM,KAAA;GACN,OAAO,KAAA;GACP,UAAU,KAAA;GACV,MAAM,KAAA;GAGN,cAAc;GACd;GACA,gBAAgB,KAAA;GAGX,eAAe,KAAA;GACpB,gBAAgB,KAAA;GAChB,UAAU;GACV,gBAAgB,SAAS,OAAO;GAChC,sBAAsB,SAAS,aAAa;GAC5C,gBAAgB,SAAS,OAAO;GAChC,iBAAiB,SAAS,QAAQ;GAClC,WAAW,UAAyC;IAClD,IAAI,UAAU;IACd,MAAM,cAAc,MAAM;IAC1B,qBACE,mBACM,IAAI,MAAM,WAAW,GAAG,WAAW,GACzC,sBACF;GACF;EACF;CACF,CAAC;CAED,OAAO,sBAAsB,wBAAwB,YAAY,OAAO;AAC1E;AAEA,oBAAoB,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox-group-root.d.mts","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"checkbox-group-root.d.mts","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"mappings":";;;;iBAiCiB,wCAAwC;;;;;;;WAO9C,QAAQ;;WAER;;WAEA;;;;;;iBAOM;;;;;;;;WAQN;;WAEA;;WAEA;;;;;;;iBAQM,+BAA+B,KAC9C;;;;;;;;;EAkBA;;;;;;;EAOA;;;;;;;;;;;;;;EAcA,oBAAoB,uBAAuB;;;;;;;EAO3C;;EAEA;;;;;;;;;;EAUA;;;;;;EAMA;;EAEA,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;;;;EAK9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,mCAAmC;;;;;;;;;;;;;;;;;;wBAqDzC,oBACd,OACA,cACA,mBACA,MAAM,UACN,MACA,UAAU,cACV,UAAU,cACV,WACA,OACA,UACA,WACG,QACF,yCAAsB,IAAA;yBAbT"}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { createActionDetails } from "../internal/action-details.mjs";
|
|
2
|
+
import { createActionDetails } from "../internal/action/action-details.mjs";
|
|
3
3
|
import { dataAttr } from "../internal/data-attr.mjs";
|
|
4
4
|
import { useRender } from "../internal/use-render.mjs";
|
|
5
5
|
import { transitionTypes } from "../internal/transition-types.mjs";
|
|
6
6
|
import { useLatest } from "../internal/use-latest.mjs";
|
|
7
|
-
import { intendedValue, useControllableAction } from "../internal/use-controllable-action.mjs";
|
|
7
|
+
import { intendedValue, useControllableAction } from "../internal/action/use-controllable-action.mjs";
|
|
8
8
|
import { EMPTY_SET, applyPatch, setsEqual, sortByOrder } from "../internal/value-set.mjs";
|
|
9
9
|
import { useItemOrder } from "../internal/use-item-order.mjs";
|
|
10
10
|
import { useValueSet } from "../internal/use-value-set.mjs";
|
|
11
|
-
import { useFieldValueChange } from "../internal/use-field-control.mjs";
|
|
12
|
-
import { useFieldsetGroup } from "../internal/use-fieldset-group.mjs";
|
|
13
|
-
import { useNativeGroupReconciliation } from "../internal/use-native-group-reconciliation.mjs";
|
|
11
|
+
import { useFieldValueChange } from "../internal/form/use-field-control.mjs";
|
|
12
|
+
import { useFieldsetGroup } from "../internal/form/use-fieldset-group.mjs";
|
|
13
|
+
import { useNativeGroupReconciliation } from "../internal/form/use-native-group-reconciliation.mjs";
|
|
14
14
|
import { CheckboxGroupContext, enabledValues } from "./checkbox-group-context.mjs";
|
|
15
15
|
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
16
16
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -96,7 +96,7 @@ function CheckboxGroupRoot({ value, defaultValue, valueChangeAction, name: nameP
|
|
|
96
96
|
...details.added.length > 0 ? ["fsui-checkbox-group-check"] : [],
|
|
97
97
|
...details.removed.length > 0 ? ["fsui-checkbox-group-uncheck"] : []
|
|
98
98
|
],
|
|
99
|
-
reducer: (prev,
|
|
99
|
+
reducer: (prev, _next, details) => applyPatch(prev, details),
|
|
100
100
|
warn: {
|
|
101
101
|
component: "CheckboxGroup.Root",
|
|
102
102
|
prop: "value"
|
|
@@ -105,15 +105,18 @@ function CheckboxGroupRoot({ value, defaultValue, valueChangeAction, name: nameP
|
|
|
105
105
|
const base = () => intendedValue(latestInFlight, optimistic);
|
|
106
106
|
/** The latest dispatch was a form reset (the absolute one, see `reducer`); for #151 below. */
|
|
107
107
|
const latestIsReset = useRef(false);
|
|
108
|
-
/**
|
|
109
|
-
|
|
108
|
+
/**
|
|
109
|
+
* Dispatches `patch` on top of `from`, with the details of design 3.1. `reset`: a form reset,
|
|
110
|
+
* dispatched whole (absolute, see `reducer`).
|
|
111
|
+
*/
|
|
112
|
+
const dispatchPatch = (from, patch, reason, event, reset = false) => {
|
|
110
113
|
const details = createActionDetails(event, {
|
|
111
114
|
reason,
|
|
112
115
|
added: sortByDocument(patch.added),
|
|
113
116
|
removed: sortByDocument(patch.removed)
|
|
114
117
|
});
|
|
115
|
-
latestIsReset.current =
|
|
116
|
-
dispatch(applyPatch(from, details), details);
|
|
118
|
+
latestIsReset.current = reset;
|
|
119
|
+
dispatch(applyPatch(from, details), details, { whole: reset });
|
|
117
120
|
};
|
|
118
121
|
/**
|
|
119
122
|
* The group as the DOM shows it (`checked`) or as a form reset leaves it (`defaultChecked`),
|
|
@@ -153,14 +156,14 @@ function CheckboxGroupRoot({ value, defaultValue, valueChangeAction, name: nameP
|
|
|
153
156
|
base,
|
|
154
157
|
equals: setsEqual,
|
|
155
158
|
dispatchEqualReset: () => value === void 0 && latestInFlight() !== null && !latestIsReset.current,
|
|
156
|
-
onPlatformChange: (next, event) => {
|
|
159
|
+
onPlatformChange: (next, event, path) => {
|
|
157
160
|
const from = base();
|
|
158
161
|
const added = [...next].filter((v) => !from.has(v));
|
|
159
162
|
const removed = [...from].filter((v) => !next.has(v));
|
|
160
163
|
dispatchPatch(from, {
|
|
161
164
|
added,
|
|
162
165
|
removed
|
|
163
|
-
}, "platform", event);
|
|
166
|
+
}, "platform", event, path === "reset");
|
|
164
167
|
}
|
|
165
168
|
});
|
|
166
169
|
useLayoutEffect(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox-group-root.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type {\n ActionDetails,\n ChangeAction,\n ChangeReason,\n RenderProp,\n StateValue,\n} from \"../internal/types.js\";\nimport { intendedValue, useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useFieldValueChange } from \"../internal/use-field-control.js\";\nimport { useFieldsetGroup } from \"../internal/use-fieldset-group.js\";\nimport { useItemOrder } from \"../internal/use-item-order.js\";\nimport type { ItemLayout } from \"../internal/use-item-order.js\";\nimport { useNativeGroupReconciliation } from \"../internal/use-native-group-reconciliation.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useValueSet } from \"../internal/use-value-set.js\";\nimport { applyPatch, EMPTY_SET, setsEqual, sortByOrder } from \"../internal/value-set.js\";\nimport type { ValueSet } from \"../internal/value-set.js\";\nimport { CheckboxGroupContext, enabledValues } from \"./checkbox-group-context.js\";\nimport type { CheckboxGroupContextValue, CheckboxGroupPatch } from \"./checkbox-group-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Details passed as the second argument of `valueChangeAction`. */\nexport interface CheckboxGroupValueChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user toggled an Item or a Parent (click, Space, label click; `event` is the\n * native `click`). `\"platform\"`: the browser changed the checked boxes itself: a form reset\n * (`event` is the `reset` event), or clicks before hydration / Firefox form-state restoration\n * found at mount (`event` is `undefined`).\n */\n readonly reason: ChangeReason;\n /** Values this dispatch checked, in document order of their Items (values with no Item last). */\n readonly added: readonly string[];\n /** Values this dispatch unchecked, same order. */\n readonly removed: readonly string[];\n}\n\n/**\n * State of `CheckboxGroup.Root`, `CheckboxGroup.Label`, passed to the function forms of\n * `className`, `style`, `children` and `render`.\n */\nexport interface CheckboxGroupRootState {\n /**\n * Optimistic checked values, in document order of the Items as of the Root's last render\n * (values with no Item last). Items reordered by a component that re-renders without the Root\n * keep the previous order here until the Root renders again; `next` and `details` of\n * `valueChangeAction` always read the current DOM order. The server render and the first client\n * render use the value's own order. Content rendered from it must not suspend.\n */\n readonly value: readonly string[];\n /** An action dispatched through this group is in flight. */\n readonly pending: boolean;\n /** The `disabled` prop (or the enclosing `Field.Root`'s). */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `CheckboxGroup.Root`.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport interface CheckboxGroupRootProps extends Omit<\n ComponentPropsWithRef<\"fieldset\">,\n | \"className\"\n | \"style\"\n | \"children\"\n | \"defaultValue\"\n | \"defaultChecked\"\n | \"name\"\n | \"disabled\"\n | \"form\"\n> {\n /**\n * Controlled checked values. `[]` checks nothing; `undefined` means uncontrolled. Order is not\n * significant and duplicates are ignored: the value is a set.\n *\n * A form reset returns each box to the `checked` it had when *that box* mounted (React sets\n * `defaultChecked` once, from the initial `checked`). The reset is offered to\n * `valueChangeAction` as a `\"platform\"` change; for a stable target use `defaultValue`.\n */\n value?: string[];\n /**\n * Initial values in uncontrolled mode. Also the values a form reset returns\n * to: the latest prop value is mirrored into the boxes' `defaultChecked`.\n *\n * @defaultValue `[]`\n */\n defaultValue?: string[];\n /**\n * Runs inside the Root's transition whenever the set of checked values changes. May be sync\n * or async (also a Server Function); rejections reach the nearest Error Boundary and roll the\n * change back.\n *\n * `next` is the whole set as a fresh array in document order of the Items; treat it as a set.\n * `details.added` / `details.removed` say what changed. When controlled and updating after\n * your own `await`, prefer a functional update keyed by `added` / `removed` over\n * `setValue(next)`: two overlapping actions completing out of order would otherwise land the\n * older whole set last. A `setState` placed after your own `await` is not a Transition update;\n * wrap it in `startTransition` (React limitation). `details.event.preventDefault()` is not a\n * veto; use controlled mode to veto a change.\n */\n valueChangeAction?: ChangeAction<string[], CheckboxGroupValueChangeDetails>;\n /**\n * The `name` shared by every Item (form data key: `formData.getAll(name)`). Pass a real name\n * when the group is inside a `<form>` you submit.\n *\n * @defaultValue a `useId()` value\n */\n name?: string;\n /** The `form` attribute, applied to the fieldset and to every Item. */\n form?: string;\n /**\n * \"At least one Item must be checked.\" Rendered as native `required` on every Item while no\n * enabled Item is checked, and on none once one is: values with no Item and checked disabled\n * Items (neither is submitted) do not satisfy it. Until the Items have mounted (server HTML,\n * before hydration) any checked value satisfies it. Not exposed on the fieldset (ARIA does not\n * allow `aria-required` on role `group`): say it in the `Label` or through `aria-describedby`.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * Renders `<fieldset disabled>`: every Item and Parent is disabled and unfocusable.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxGroupRootState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxGroupRootState>;\n /**\n * The Label, Parents and Items. The function form receives the optimistic value; must not\n * suspend.\n */\n children?: StateValue<ReactNode, CheckboxGroupRootState>;\n /** Replace the rendered element. Must keep a `<fieldset>`. */\n render?: RenderProp<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>;\n}\n\n/** Value → \"has an Item without its own `disabled`\", over the registered Items. */\ntype ItemRegistry = Map<object, { readonly value: string; readonly disabled: boolean }>;\n\nfunction summarize(registry: ItemRegistry): Map<string, boolean> {\n const items = new Map<string, boolean>();\n for (const { value, disabled } of registry.values()) {\n items.set(value, (items.get(value) ?? false) || !disabled);\n }\n return items;\n}\n\nfunction disabledOf(items: ReadonlyMap<string, boolean> | null): ValueSet {\n if (items === null) return EMPTY_SET;\n const disabled = new Set<string>();\n for (const [value, enabled] of items) if (!enabled) disabled.add(value);\n return disabled.size === 0 ? EMPTY_SET : disabled;\n}\n\nfunction mapsEqual(a: ReadonlyMap<string, boolean>, b: ReadonlyMap<string, boolean>): boolean {\n if (a.size !== b.size) return false;\n for (const [k, v] of a) if (b.get(k) !== v) return false;\n return true;\n}\n\nconst NO_ORDER: ItemLayout = { order: [] };\n\n/** The group's Items: checkboxes of this `name` in the fieldset (Parents have none). */\nfunction readItems(fieldset: HTMLFieldSetElement | null, name: string): HTMLInputElement[] {\n if (fieldset === null) return [];\n return [...fieldset.querySelectorAll<HTMLInputElement>('input[type=\"checkbox\"]')].filter(\n (box) => box.name === name,\n );\n}\n\n/**\n * `<fieldset>` that owns the group's state (a set of values), the transition, the shared `name`,\n * the form-reset listener, the mount reconciliation and the group-level `required`\n * (design/components/checkbox-group.md 14.3). Carries `data-pending` while `valueChangeAction`\n * is in flight. Its implicit role is `group`; no `role` is written.\n *\n * Owned keys (conventions 1.2): `disabled`, `form`, `data-pending`, `data-disabled`; inside a\n * `Field.Root` also `aria-labelledby` (→ `Field.Label`, token-merged), `aria-describedby`\n * (token-merged), `aria-invalid` and `data-invalid`, and `name` / `required` / `disabled` default\n * from the Field.\n *\n * Unlike RadioGroup, Items may hydrate after their Root (a Suspense boundary between them): a\n * click before an Item hydrated is reconciled when it does.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport function CheckboxGroupRoot({\n value,\n defaultValue,\n valueChangeAction,\n name: nameProp,\n form,\n required: requiredProp,\n disabled: disabledProp,\n className,\n style,\n children,\n render,\n ...rest\n}: CheckboxGroupRootProps) {\n // `required` is \"at least one\" (design section 7).\n const { field, name, required, disabled, fieldsetRef, rootRef } = useFieldsetGroup({\n component: \"CheckboxGroup.Root\",\n name: nameProp,\n disabled: disabledProp,\n required: requiredProp,\n });\n /** Parent reports waiting for the next mount read (design 8.1). */\n const parentReports = useRef<{ values: readonly string[]; checked: boolean }[]>([]);\n\n // Item registration (design 6.2, 7): each Item reports its value and own `disabled` from a\n // layout effect. The ref is current for the residual-path reads; the state, set only when the\n // summary changes, is what render uses. `null` until an Item registered, so the server render\n // and the hydration render (which cannot know) agree.\n const itemRegistry = useRef<ItemRegistry>(new Map());\n const [items, setItems] = useState<ReadonlyMap<string, boolean> | null>(null);\n const registerItem = useCallback((value: string, disabled: boolean) => {\n const publish = () => {\n const next = summarize(itemRegistry.current);\n setItems((prev) => (prev !== null && mapsEqual(prev, next) ? prev : next));\n };\n const token = {};\n itemRegistry.current.set(token, { value, disabled });\n publish();\n return () => {\n itemRegistry.current.delete(token);\n publish();\n };\n }, []);\n const disabledItems = useMemo(() => disabledOf(items), [items]);\n\n const controlledSet = useValueSet(value);\n const defaultSet = useValueSet(defaultValue);\n\n /** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */\n const sortByDocument = (values: Iterable<string>): string[] =>\n sortByOrder(\n values,\n readItems(fieldsetRef.current, name).map((item) => item.value),\n );\n\n const { optimistic, committed, pending, dispatch, latestInFlight } = useControllableAction<\n ValueSet,\n CheckboxGroupValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n valueChangeAction && ((next, details) => valueChangeAction(sortByDocument(next), details)),\n transitionTypes: (_next, _prev, details) => [\n ...transitionTypes(\"checkbox-group\"),\n ...(details.added.length > 0 ? [\"fsui-checkbox-group-check\"] : []),\n ...(details.removed.length > 0 ? [\"fsui-checkbox-group-uncheck\"] : []),\n ],\n // A patch, re-based on the committed set; it is also how the uncontrolled commit is folded\n // over the resolved dispatches (#150). A form reset (reason \"platform\" with the `reset`\n // event) is absolute: adopted whole, so a change rejected after it cannot survive the reset.\n reducer: (prev, next, details) =>\n details.reason === \"platform\" && details.event !== undefined\n ? next\n : applyPatch(prev, details),\n warn: { component: \"CheckboxGroup.Root\", prop: \"value\" },\n });\n // Deliberately no warning when neither `value` nor `defaultValue` is given: an empty group is\n // the HTML default (design 3.1).\n\n const base = (): ValueSet => intendedValue(latestInFlight, optimistic);\n\n /** The latest dispatch was a form reset (the absolute one, see `reducer`); for #151 below. */\n const latestIsReset = useRef(false);\n /** Dispatches `patch` on top of `from`, with the details of design 3.1. */\n const dispatchPatch = (\n from: ValueSet,\n patch: CheckboxGroupPatch,\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n const details = createActionDetails(event, {\n reason,\n added: sortByDocument(patch.added),\n removed: sortByDocument(patch.removed),\n });\n latestIsReset.current = reason === \"platform\" && event !== undefined;\n dispatch(applyPatch(from, details), details);\n };\n\n /**\n * The group as the DOM shows it (`checked`) or as a form reset leaves it (`defaultChecked`),\n * laid over `base()` so that values with no Item are kept (they have no DOM to read).\n */\n const readDom = (prop: \"checked\" | \"defaultChecked\"): Map<string, boolean> =>\n new Map(readItems(fieldsetRef.current, name).map((item) => [item.value, item[prop]]));\n const readGroup = (\n prop: \"checked\" | \"defaultChecked\",\n from: ValueSet,\n dom: ReadonlyMap<string, boolean> = readDom(prop),\n ): Set<string> => {\n const next = new Set(from);\n for (const [v, isChecked] of dom) {\n if (isChecked) next.add(v);\n else next.delete(v);\n }\n return next;\n };\n\n /**\n * The Root's own mount reconciliation ran: later member mounts are \"late\" (8.3). Set after the\n * adapter's mount effect; reset by the cleanup (StrictMode included).\n */\n const rootMounted = useRef(false);\n /**\n * Late mounts: the members' `checked` read in the first late member's mount layout effect. The\n * adapter reads the group in a microtask, but the Items' registration re-renders the group\n * right after the layout effects, and that re-render re-applies each Item's `checked`, erasing a\n * click made before the Item hydrated. Every member of the commit is in the DOM by then.\n */\n const lateSnapshot = useRef<Map<string, boolean> | null>(null);\n\n // The residual browser paths (design section 8): one dispatch per group, from here. Items and\n // Parents that mount after the Root report through `onItemMounted`.\n const { onItemMounted: onMemberMounted } = useNativeGroupReconciliation<ValueSet>({\n element: fieldsetRef,\n readCurrent: () => {\n const next = readGroup(\"checked\", base(), lateSnapshot.current ?? undefined);\n lateSnapshot.current = null;\n // A Parent clicked before hydration means what its click means: check / uncheck all of its\n // values whose Items are enabled (8.1, 6.2). Read from the registry ref: the Items of this\n // commit registered before this runs, and render has not caught up yet.\n const disabledNow = disabledOf(summarize(itemRegistry.current));\n for (const report of parentReports.current) {\n for (const v of enabledValues(report.values, disabledNow)) {\n if (report.checked) next.add(v);\n else next.delete(v);\n }\n }\n parentReports.current = [];\n return next;\n },\n // Uncontrolled: start from `defaultValue`, so values with no Item return to it too (they have\n // no `defaultChecked` to read). Controlled: from `base()`, as for the mount read; the parent\n // decides.\n readDefault: () =>\n readGroup(\"defaultChecked\", value === undefined ? (defaultSet ?? EMPTY_SET) : base()),\n base,\n equals: setsEqual,\n // #151: a reset is absolute in the uncontrolled replay (the `reducer` above), so while a\n // change is in flight it is dispatched even when its target equals the intended value;\n // otherwise an earlier change that rejects later would roll the group back past the reset.\n // Not when the latest dispatch is itself a reset: nothing after it could be rolled back, and\n // repeated resets stay one dispatch. Controlled: no replay, the parent decides.\n dispatchEqualReset: () =>\n value === undefined && latestInFlight() !== null && !latestIsReset.current,\n onPlatformChange: (next, event) => {\n const from = base();\n const added = [...next].filter((v) => !from.has(v));\n const removed = [...from].filter((v) => !next.has(v));\n dispatchPatch(from, { added, removed }, \"platform\", event);\n },\n });\n\n useLayoutEffect(() => {\n rootMounted.current = true;\n return () => {\n rootMounted.current = false;\n };\n }, []);\n const onItemMounted = (el: HTMLInputElement | null) => {\n const late = rootMounted.current;\n if (late && lateSnapshot.current === null) lateSnapshot.current = readDom(\"checked\");\n onMemberMounted(el);\n // A snapshot the adapter did not consume (it queues one read per commit, before this).\n if (late) {\n queueMicrotask(() => {\n lateSnapshot.current = null;\n });\n }\n };\n\n // The state's `value` is in document order (design 14.6: Item values are unique).\n const { renderedValue } = useItemOrder({\n optimistic,\n initial: NO_ORDER,\n read: () => ({ order: readItems(fieldsetRef.current, name).map((item) => item.value) }),\n duplicateMessage:\n isDev &&\n ((duplicate) =>\n `CheckboxGroup.Item: two Items share the value \"${duplicate}\" in one ` +\n `CheckboxGroup.Root. Item values must be unique; both boxes follow the same value.`),\n });\n\n const itemsRequired =\n required &&\n (items === null ? optimistic.size === 0 : ![...optimistic].some((v) => items.get(v) === true));\n // Inside a Field: the Items' `checked` and derived `required` are written by React after the\n // click's `change` (a Parent checks Items with no event of their own), so the Field re-reads\n // validity and `validate` after the commit (design/components/field-form.md 7.2).\n useFieldValueChange(`${[...optimistic].sort().join(\"\\u0000\")}|${String(itemsRequired)}`);\n\n // `aria-invalid` is not supported on role `group` (ARIA 1.2 made it widget-specific): inside a\n // Field it goes on every Item (a `checkbox`) instead; the fieldset keeps `data-invalid` and\n // `aria-describedby`, read when focus enters the group.\n const { \"aria-invalid\": fieldInvalid, ...groupAttributes } = field.attributes;\n\n // `renderedValue` is a fresh array on every render: keyed on its contents.\n const renderedKey = JSON.stringify(renderedValue);\n const state = useMemo<CheckboxGroupRootState>(\n () => ({ value: JSON.parse(renderedKey) as string[], pending, disabled }),\n [renderedKey, pending, disabled],\n );\n\n // The context's callbacks are stable (handlers and member effects only: they read the last\n // committed render), so the context changes only with the values below.\n const latest = useLatest({ optimistic, onItemMounted, sortByDocument, dispatchPatch });\n const callbacks = useMemo(\n () => ({\n onItemMounted: (el: HTMLInputElement | null) => latest.current.onItemMounted(el),\n reportParent: (values: readonly string[], checked: boolean) => {\n parentReports.current.push({ values, checked });\n },\n sortByDocument: (values: Iterable<string>) => latest.current.sortByDocument(values),\n toggle: (item: string, checked: boolean, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n // No-op rule against the optimistic set (conventions 2.3 item 8).\n if (optimistic.has(item) === checked) return;\n const patch = checked ? { added: [item], removed: [] } : { added: [], removed: [item] };\n dispatchPatch(optimistic, patch, \"activate\", event);\n },\n apply: (patch: CheckboxGroupPatch, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n const added = patch.added.filter((v) => !optimistic.has(v));\n const removed = patch.removed.filter((v) => optimistic.has(v));\n if (added.length === 0 && removed.length === 0) return;\n dispatchPatch(optimistic, { added, removed }, \"activate\", event);\n },\n }),\n [latest],\n );\n const contextDefault = value === undefined ? (defaultSet ?? EMPTY_SET) : undefined;\n const context = useMemo<CheckboxGroupContextValue>(\n () => ({\n name,\n form,\n fieldInvalid,\n required: itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n defaultValue: contextDefault,\n ...callbacks,\n }),\n [\n name,\n form,\n fieldInvalid,\n itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n contextDefault,\n callbacks,\n ],\n );\n\n const element = useRender<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>({\n defaultElement: \"fieldset\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n ...groupAttributes,\n disabled,\n form,\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n },\n ref: rootRef,\n });\n\n return <CheckboxGroupContext value={context}>{element}</CheckboxGroupContext>;\n}\n\nCheckboxGroupRoot.displayName = \"CheckboxGroupRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA2HvC,SAAS,UAAU,UAA8C;CAC/D,MAAM,wBAAQ,IAAI,IAAqB;CACvC,KAAK,MAAM,EAAE,OAAO,cAAc,SAAS,OAAO,GAChD,MAAM,IAAI,QAAQ,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC,QAAQ;CAE3D,OAAO;AACT;AAEA,SAAS,WAAW,OAAsD;CACxE,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,2BAAW,IAAI,IAAY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AE,OAAO,CAAC;IAAG,SAAS,CAAC,IAAI;GAAE,GACrD,YAAY,KAAK;EACpD;EACA,QAAQ,OAA2B,UAAiB;GAClD,MAAM,EAAE,YAAY,kBAAkB,OAAO;GAC7C,MAAM,QAAQ,MAAM,MAAM,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;GAC1D,MAAM,UAAU,MAAM,QAAQ,QAAQ,MAAM,WAAW,IAAI,CAAC,CAAC;GAC7D,IAAI,MAAM,WAAW,KAAK,QAAQ,WAAW,GAAG;GAChD,cAAc,YAAY;IAAE;IAAO;GAAQ,GAAG,YAAY,KAAK;EACjE;CACF,IACA,CAAC,MAAM,CACT;CACA,MAAM,iBAAiB,UAAU,KAAA,IAAa,cAAc,YAAa,KAAA;CACzE,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA,UAAU;EACV;EACA;EACA;EACA;EACA;EACA,cAAc;EACd,GAAG;CACL,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,UAAU,UAAqE;EACnF,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,GAAG;GACH;GACA;GACA,gBAAgB,SAAS,OAAO;GAChC,iBAAiB,SAAS,QAAQ;EACpC;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA8B,CAAA;AAC9E;AAEA,kBAAkB,cAAc"}
|
|
1
|
+
{"version":3,"file":"checkbox-group-root.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type {\n ActionDetails,\n ChangeAction,\n ChangeReason,\n RenderProp,\n StateValue,\n} from \"../internal/types.js\";\nimport {\n intendedValue,\n useControllableAction,\n} from \"../internal/action/use-controllable-action.js\";\nimport { useFieldValueChange } from \"../internal/form/use-field-control.js\";\nimport { useFieldsetGroup } from \"../internal/form/use-fieldset-group.js\";\nimport { useItemOrder } from \"../internal/use-item-order.js\";\nimport type { ItemLayout } from \"../internal/use-item-order.js\";\nimport { useNativeGroupReconciliation } from \"../internal/form/use-native-group-reconciliation.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useValueSet } from \"../internal/use-value-set.js\";\nimport { applyPatch, EMPTY_SET, setsEqual, sortByOrder } from \"../internal/value-set.js\";\nimport type { ValueSet } from \"../internal/value-set.js\";\nimport { CheckboxGroupContext, enabledValues } from \"./checkbox-group-context.js\";\nimport type { CheckboxGroupContextValue, CheckboxGroupPatch } from \"./checkbox-group-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Details passed as the second argument of `valueChangeAction`. */\nexport interface CheckboxGroupValueChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user toggled an Item or a Parent (click, Space, label click; `event` is the\n * native `click`). `\"platform\"`: the browser changed the checked boxes itself: a form reset\n * (`event` is the `reset` event), or clicks before hydration / Firefox form-state restoration\n * found at mount (`event` is `undefined`).\n */\n readonly reason: ChangeReason;\n /** Values this dispatch checked, in document order of their Items (values with no Item last). */\n readonly added: readonly string[];\n /** Values this dispatch unchecked, same order. */\n readonly removed: readonly string[];\n}\n\n/**\n * State of `CheckboxGroup.Root`, `CheckboxGroup.Label`, passed to the function forms of\n * `className`, `style`, `children` and `render`.\n */\nexport interface CheckboxGroupRootState {\n /**\n * Optimistic checked values, in document order of the Items as of the Root's last render\n * (values with no Item last). Items reordered by a component that re-renders without the Root\n * keep the previous order here until the Root renders again; `next` and `details` of\n * `valueChangeAction` always read the current DOM order. The server render and the first client\n * render use the value's own order. Content rendered from it must not suspend.\n */\n readonly value: readonly string[];\n /** An action dispatched through this group is in flight. */\n readonly pending: boolean;\n /** The `disabled` prop (or the enclosing `Field.Root`'s). */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `CheckboxGroup.Root`.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport interface CheckboxGroupRootProps extends Omit<\n ComponentPropsWithRef<\"fieldset\">,\n | \"className\"\n | \"style\"\n | \"children\"\n | \"defaultValue\"\n | \"defaultChecked\"\n | \"name\"\n | \"disabled\"\n | \"form\"\n> {\n /**\n * Controlled checked values. `[]` checks nothing; `undefined` means uncontrolled. Order is not\n * significant and duplicates are ignored: the value is a set.\n *\n * A form reset returns each box to the `checked` it had when *that box* mounted (React sets\n * `defaultChecked` once, from the initial `checked`). The reset is offered to\n * `valueChangeAction` as a `\"platform\"` change; for a stable target use `defaultValue`.\n */\n value?: string[];\n /**\n * Initial values in uncontrolled mode. Also the values a form reset returns\n * to: the latest prop value is mirrored into the boxes' `defaultChecked`.\n *\n * @defaultValue `[]`\n */\n defaultValue?: string[];\n /**\n * Runs inside the Root's transition whenever the set of checked values changes. May be sync\n * or async (also a Server Function); rejections reach the nearest Error Boundary and roll the\n * change back.\n *\n * `next` is the whole set as a fresh array in document order of the Items; treat it as a set.\n * `details.added` / `details.removed` say what changed. When controlled and updating after\n * your own `await`, prefer a functional update keyed by `added` / `removed` over\n * `setValue(next)`: two overlapping actions completing out of order would otherwise land the\n * older whole set last. A `setState` placed after your own `await` is not a Transition update;\n * wrap it in `startTransition` (React limitation). `details.event.preventDefault()` is not a\n * veto; use controlled mode to veto a change.\n */\n valueChangeAction?: ChangeAction<string[], CheckboxGroupValueChangeDetails>;\n /**\n * The `name` shared by every Item (form data key: `formData.getAll(name)`). Pass a real name\n * when the group is inside a `<form>` you submit.\n *\n * @defaultValue a `useId()` value\n */\n name?: string;\n /** The `form` attribute, applied to the fieldset and to every Item. */\n form?: string;\n /**\n * \"At least one Item must be checked.\" Rendered as native `required` on every Item while no\n * enabled Item is checked, and on none once one is: values with no Item and checked disabled\n * Items (neither is submitted) do not satisfy it. Until the Items have mounted (server HTML,\n * before hydration) any checked value satisfies it. Not exposed on the fieldset (ARIA does not\n * allow `aria-required` on role `group`): say it in the `Label` or through `aria-describedby`.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * Renders `<fieldset disabled>`: every Item and Parent is disabled and unfocusable.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, CheckboxGroupRootState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, CheckboxGroupRootState>;\n /**\n * The Label, Parents and Items. The function form receives the optimistic value; must not\n * suspend.\n */\n children?: StateValue<ReactNode, CheckboxGroupRootState>;\n /** Replace the rendered element. Must keep a `<fieldset>`. */\n render?: RenderProp<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>;\n}\n\n/** Value → \"has an Item without its own `disabled`\", over the registered Items. */\ntype ItemRegistry = Map<object, { readonly value: string; readonly disabled: boolean }>;\n\nfunction summarize(registry: ItemRegistry): Map<string, boolean> {\n const items = new Map<string, boolean>();\n for (const { value, disabled } of registry.values()) {\n items.set(value, (items.get(value) ?? false) || !disabled);\n }\n return items;\n}\n\nfunction disabledOf(items: ReadonlyMap<string, boolean> | null): ValueSet {\n if (items === null) return EMPTY_SET;\n const disabled = new Set<string>();\n for (const [value, enabled] of items) if (!enabled) disabled.add(value);\n return disabled.size === 0 ? EMPTY_SET : disabled;\n}\n\nfunction mapsEqual(a: ReadonlyMap<string, boolean>, b: ReadonlyMap<string, boolean>): boolean {\n if (a.size !== b.size) return false;\n for (const [k, v] of a) if (b.get(k) !== v) return false;\n return true;\n}\n\nconst NO_ORDER: ItemLayout = { order: [] };\n\n/** The group's Items: checkboxes of this `name` in the fieldset (Parents have none). */\nfunction readItems(fieldset: HTMLFieldSetElement | null, name: string): HTMLInputElement[] {\n if (fieldset === null) return [];\n return [...fieldset.querySelectorAll<HTMLInputElement>('input[type=\"checkbox\"]')].filter(\n (box) => box.name === name,\n );\n}\n\n/**\n * `<fieldset>` that owns the group's state (a set of values), the transition, the shared `name`,\n * the form-reset listener, the mount reconciliation and the group-level `required`\n * (design/components/checkbox-group.md 14.3). Carries `data-pending` while `valueChangeAction`\n * is in flight. Its implicit role is `group`; no `role` is written.\n *\n * Owned keys (conventions 1.2): `disabled`, `form`, `data-pending`, `data-disabled`; inside a\n * `Field.Root` also `aria-labelledby` (→ `Field.Label`, token-merged), `aria-describedby`\n * (token-merged), `aria-invalid` and `data-invalid`, and `name` / `required` / `disabled` default\n * from the Field.\n *\n * Unlike RadioGroup, Items may hydrate after their Root (a Suspense boundary between them): a\n * click before an Item hydrated is reconciled when it does.\n *\n * @see https://ui.funstack.work/components/checkbox-group\n */\nexport function CheckboxGroupRoot({\n value,\n defaultValue,\n valueChangeAction,\n name: nameProp,\n form,\n required: requiredProp,\n disabled: disabledProp,\n className,\n style,\n children,\n render,\n ...rest\n}: CheckboxGroupRootProps) {\n // `required` is \"at least one\" (design section 7).\n const { field, name, required, disabled, fieldsetRef, rootRef } = useFieldsetGroup({\n component: \"CheckboxGroup.Root\",\n name: nameProp,\n disabled: disabledProp,\n required: requiredProp,\n });\n /** Parent reports waiting for the next mount read (design 8.1). */\n const parentReports = useRef<{ values: readonly string[]; checked: boolean }[]>([]);\n\n // Item registration (design 6.2, 7): each Item reports its value and own `disabled` from a\n // layout effect. The ref is current for the residual-path reads; the state, set only when the\n // summary changes, is what render uses. `null` until an Item registered, so the server render\n // and the hydration render (which cannot know) agree.\n const itemRegistry = useRef<ItemRegistry>(new Map());\n const [items, setItems] = useState<ReadonlyMap<string, boolean> | null>(null);\n const registerItem = useCallback((value: string, disabled: boolean) => {\n const publish = () => {\n const next = summarize(itemRegistry.current);\n setItems((prev) => (prev !== null && mapsEqual(prev, next) ? prev : next));\n };\n const token = {};\n itemRegistry.current.set(token, { value, disabled });\n publish();\n return () => {\n itemRegistry.current.delete(token);\n publish();\n };\n }, []);\n const disabledItems = useMemo(() => disabledOf(items), [items]);\n\n const controlledSet = useValueSet(value);\n const defaultSet = useValueSet(defaultValue);\n\n /** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */\n const sortByDocument = (values: Iterable<string>): string[] =>\n sortByOrder(\n values,\n readItems(fieldsetRef.current, name).map((item) => item.value),\n );\n\n const { optimistic, committed, pending, dispatch, latestInFlight } = useControllableAction<\n ValueSet,\n CheckboxGroupValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n valueChangeAction && ((next, details) => valueChangeAction(sortByDocument(next), details)),\n transitionTypes: (_next, _prev, details) => [\n ...transitionTypes(\"checkbox-group\"),\n ...(details.added.length > 0 ? [\"fsui-checkbox-group-check\"] : []),\n ...(details.removed.length > 0 ? [\"fsui-checkbox-group-uncheck\"] : []),\n ],\n // A patch, re-based on the committed set; it is also how the uncontrolled commit is folded\n // over the resolved dispatches (#150). A form reset is absolute: `dispatchPatch` dispatches\n // it with `whole`, so it bypasses this reducer and a change rejected after it cannot survive\n // the reset.\n reducer: (prev, _next, details) => applyPatch(prev, details),\n warn: { component: \"CheckboxGroup.Root\", prop: \"value\" },\n });\n // Deliberately no warning when neither `value` nor `defaultValue` is given: an empty group is\n // the HTML default (design 3.1).\n\n const base = (): ValueSet => intendedValue(latestInFlight, optimistic);\n\n /** The latest dispatch was a form reset (the absolute one, see `reducer`); for #151 below. */\n const latestIsReset = useRef(false);\n /**\n * Dispatches `patch` on top of `from`, with the details of design 3.1. `reset`: a form reset,\n * dispatched whole (absolute, see `reducer`).\n */\n const dispatchPatch = (\n from: ValueSet,\n patch: CheckboxGroupPatch,\n reason: ChangeReason,\n event: Event | undefined,\n reset = false,\n ): void => {\n const details = createActionDetails(event, {\n reason,\n added: sortByDocument(patch.added),\n removed: sortByDocument(patch.removed),\n });\n latestIsReset.current = reset;\n dispatch(applyPatch(from, details), details, { whole: reset });\n };\n\n /**\n * The group as the DOM shows it (`checked`) or as a form reset leaves it (`defaultChecked`),\n * laid over `base()` so that values with no Item are kept (they have no DOM to read).\n */\n const readDom = (prop: \"checked\" | \"defaultChecked\"): Map<string, boolean> =>\n new Map(readItems(fieldsetRef.current, name).map((item) => [item.value, item[prop]]));\n const readGroup = (\n prop: \"checked\" | \"defaultChecked\",\n from: ValueSet,\n dom: ReadonlyMap<string, boolean> = readDom(prop),\n ): Set<string> => {\n const next = new Set(from);\n for (const [v, isChecked] of dom) {\n if (isChecked) next.add(v);\n else next.delete(v);\n }\n return next;\n };\n\n /**\n * The Root's own mount reconciliation ran: later member mounts are \"late\" (8.3). Set after the\n * adapter's mount effect; reset by the cleanup (StrictMode included).\n */\n const rootMounted = useRef(false);\n /**\n * Late mounts: the members' `checked` read in the first late member's mount layout effect. The\n * adapter reads the group in a microtask, but the Items' registration re-renders the group\n * right after the layout effects, and that re-render re-applies each Item's `checked`, erasing a\n * click made before the Item hydrated. Every member of the commit is in the DOM by then.\n */\n const lateSnapshot = useRef<Map<string, boolean> | null>(null);\n\n // The residual browser paths (design section 8): one dispatch per group, from here. Items and\n // Parents that mount after the Root report through `onItemMounted`.\n const { onItemMounted: onMemberMounted } = useNativeGroupReconciliation<ValueSet>({\n element: fieldsetRef,\n readCurrent: () => {\n const next = readGroup(\"checked\", base(), lateSnapshot.current ?? undefined);\n lateSnapshot.current = null;\n // A Parent clicked before hydration means what its click means: check / uncheck all of its\n // values whose Items are enabled (8.1, 6.2). Read from the registry ref: the Items of this\n // commit registered before this runs, and render has not caught up yet.\n const disabledNow = disabledOf(summarize(itemRegistry.current));\n for (const report of parentReports.current) {\n for (const v of enabledValues(report.values, disabledNow)) {\n if (report.checked) next.add(v);\n else next.delete(v);\n }\n }\n parentReports.current = [];\n return next;\n },\n // Uncontrolled: start from `defaultValue`, so values with no Item return to it too (they have\n // no `defaultChecked` to read). Controlled: from `base()`, as for the mount read; the parent\n // decides.\n readDefault: () =>\n readGroup(\"defaultChecked\", value === undefined ? (defaultSet ?? EMPTY_SET) : base()),\n base,\n equals: setsEqual,\n // #151: a reset is absolute in the uncontrolled replay (the `reducer` above), so while a\n // change is in flight it is dispatched even when its target equals the intended value;\n // otherwise an earlier change that rejects later would roll the group back past the reset.\n // Not when the latest dispatch is itself a reset: nothing after it could be rolled back, and\n // repeated resets stay one dispatch. Controlled: no replay, the parent decides.\n dispatchEqualReset: () =>\n value === undefined && latestInFlight() !== null && !latestIsReset.current,\n onPlatformChange: (next, event, path) => {\n const from = base();\n const added = [...next].filter((v) => !from.has(v));\n const removed = [...from].filter((v) => !next.has(v));\n dispatchPatch(from, { added, removed }, \"platform\", event, path === \"reset\");\n },\n });\n\n useLayoutEffect(() => {\n rootMounted.current = true;\n return () => {\n rootMounted.current = false;\n };\n }, []);\n const onItemMounted = (el: HTMLInputElement | null) => {\n const late = rootMounted.current;\n if (late && lateSnapshot.current === null) lateSnapshot.current = readDom(\"checked\");\n onMemberMounted(el);\n // A snapshot the adapter did not consume (it queues one read per commit, before this).\n if (late) {\n queueMicrotask(() => {\n lateSnapshot.current = null;\n });\n }\n };\n\n // The state's `value` is in document order (design 14.6: Item values are unique).\n const { renderedValue } = useItemOrder({\n optimistic,\n initial: NO_ORDER,\n read: () => ({ order: readItems(fieldsetRef.current, name).map((item) => item.value) }),\n duplicateMessage:\n isDev &&\n ((duplicate) =>\n `CheckboxGroup.Item: two Items share the value \"${duplicate}\" in one ` +\n `CheckboxGroup.Root. Item values must be unique; both boxes follow the same value.`),\n });\n\n const itemsRequired =\n required &&\n (items === null ? optimistic.size === 0 : ![...optimistic].some((v) => items.get(v) === true));\n // Inside a Field: the Items' `checked` and derived `required` are written by React after the\n // click's `change` (a Parent checks Items with no event of their own), so the Field re-reads\n // validity and `validate` after the commit (design/components/field-form.md 7.2).\n useFieldValueChange(`${[...optimistic].sort().join(\"\\u0000\")}|${String(itemsRequired)}`);\n\n // `aria-invalid` is not supported on role `group` (ARIA 1.2 made it widget-specific): inside a\n // Field it goes on every Item (a `checkbox`) instead; the fieldset keeps `data-invalid` and\n // `aria-describedby`, read when focus enters the group.\n const { \"aria-invalid\": fieldInvalid, ...groupAttributes } = field.attributes;\n\n // `renderedValue` is a fresh array on every render: keyed on its contents.\n const renderedKey = JSON.stringify(renderedValue);\n const state = useMemo<CheckboxGroupRootState>(\n () => ({ value: JSON.parse(renderedKey) as string[], pending, disabled }),\n [renderedKey, pending, disabled],\n );\n\n // The context's callbacks are stable (handlers and member effects only: they read the last\n // committed render), so the context changes only with the values below.\n const latest = useLatest({ optimistic, onItemMounted, sortByDocument, dispatchPatch });\n const callbacks = useMemo(\n () => ({\n onItemMounted: (el: HTMLInputElement | null) => latest.current.onItemMounted(el),\n reportParent: (values: readonly string[], checked: boolean) => {\n parentReports.current.push({ values, checked });\n },\n sortByDocument: (values: Iterable<string>) => latest.current.sortByDocument(values),\n toggle: (item: string, checked: boolean, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n // No-op rule against the optimistic set (conventions 2.3 item 8).\n if (optimistic.has(item) === checked) return;\n const patch = checked ? { added: [item], removed: [] } : { added: [], removed: [item] };\n dispatchPatch(optimistic, patch, \"activate\", event);\n },\n apply: (patch: CheckboxGroupPatch, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n const added = patch.added.filter((v) => !optimistic.has(v));\n const removed = patch.removed.filter((v) => optimistic.has(v));\n if (added.length === 0 && removed.length === 0) return;\n dispatchPatch(optimistic, { added, removed }, \"activate\", event);\n },\n }),\n [latest],\n );\n const contextDefault = value === undefined ? (defaultSet ?? EMPTY_SET) : undefined;\n const context = useMemo<CheckboxGroupContextValue>(\n () => ({\n name,\n form,\n fieldInvalid,\n required: itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n defaultValue: contextDefault,\n ...callbacks,\n }),\n [\n name,\n form,\n fieldInvalid,\n itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n contextDefault,\n callbacks,\n ],\n );\n\n const element = useRender<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>({\n defaultElement: \"fieldset\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n ...groupAttributes,\n disabled,\n form,\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n },\n ref: rootRef,\n });\n\n return <CheckboxGroupContext value={context}>{element}</CheckboxGroupContext>;\n}\n\nCheckboxGroupRoot.displayName = \"CheckboxGroupRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;;AA8BA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA2HvC,SAAS,UAAU,UAA8C;CAC/D,MAAM,wBAAQ,IAAI,IAAqB;CACvC,KAAK,MAAM,EAAE,OAAO,cAAc,SAAS,OAAO,GAChD,MAAM,IAAI,QAAQ,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC,QAAQ;CAE3D,OAAO;AACT;AAEA,SAAS,WAAW,OAAsD;CACxE,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,IAAI,CAAC,SAAS,SAAS,IAAI,KAAK;CACtE,OAAO,SAAS,SAAS,IAAI,YAAY;AAC3C;AAEA,SAAS,UAAU,GAAiC,GAA0C;CAC5F,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAC9B,KAAK,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI,EAAE,IAAI,CAAC,MAAM,GAAG,OAAO;CACnD,OAAO;AACT;AAEA,MAAM,WAAuB,EAAE,OAAO,CAAC,EAAE;;AAGzC,SAAS,UAAU,UAAsC,MAAkC;CACzF,IAAI,aAAa,MAAM,OAAO,CAAC;CAC/B,OAAO,CAAC,GAAG,SAAS,iBAAmC,0BAAwB,CAAC,CAAC,CAAC,QAC/E,QAAQ,IAAI,SAAS,IACxB;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,kBAAkB,EAChC,OACA,cACA,mBACA,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A;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,UAAU,UAAqE;EACnF,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,GAAG;GACH;GACA;GACA,gBAAgB,SAAS,OAAO;GAChC,iBAAiB,SAAS,QAAQ;EACpC;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA8B,CAAA;AAC9E;AAEA,kBAAkB,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-context.mjs","names":[],"sources":["../../src/combobox/combobox-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { RefObject } from \"react\";\nimport type { PopoverRootValue } from \"../internal/use-overlay-root.js\";\n\n/** What a mounted `Combobox.Option` tells its Root (design 2, \"mounted options, labels\"). */\nexport interface ComboboxOptionEntry {\n readonly element: HTMLElement;\n /** The `label` prop; `undefined`: the element's trimmed `textContent` at the moment of use. */\n readonly label: string | undefined;\n readonly disabled: boolean;\n}\n\n/** One Combobox: what its Root provides to every part (design 14, `combobox-context.ts`). */\nexport interface ComboboxContextValue {\n /** The shared popover machinery (`
|
|
1
|
+
{"version":3,"file":"combobox-context.mjs","names":[],"sources":["../../src/combobox/combobox-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { RefObject } from \"react\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\n\n/** What a mounted `Combobox.Option` tells its Root (design 2, \"mounted options, labels\"). */\nexport interface ComboboxOptionEntry {\n readonly element: HTMLElement;\n /** The `label` prop; `undefined`: the element's trimmed `textContent` at the moment of use. */\n readonly label: string | undefined;\n readonly disabled: boolean;\n}\n\n/** One Combobox: what its Root provides to every part (design 14, `combobox-context.ts`). */\nexport interface ComboboxContextValue {\n /** The shared popover machinery (`usePopoverRoot`, library mode). */\n readonly popover: PopoverRootValue;\n readonly ids: {\n readonly input: string;\n readonly label: string;\n readonly list: string;\n /** `${root}-option-`: an Option's id is this plus `encodeURIComponent(value)`. */\n readonly optionPrefix: string;\n };\n /** Optimistic selection. */\n readonly value: string | null;\n /** The `valueChangeAction` transition is in flight. */\n readonly valuePending: boolean;\n /** `valuePending` or the open transition is in flight (the Root's `pending`). */\n readonly pending: boolean;\n /** The urgent text. */\n readonly inputValue: string;\n /** `useDeferredValue(inputValue)`: what the mounted results are for. */\n readonly query: string;\n readonly stale: boolean;\n /** The option `aria-activedescendant` points at (urgent virtual focus), or `null`. */\n readonly activeValue: string | null;\n /** No option is mounted and the results are settled (`Empty`, `data-empty`). */\n readonly empty: boolean;\n /** A `Combobox.Status` is mounted inside the List (a Suspense fallback): results are loading. */\n readonly loading: boolean;\n /** A `Combobox.Label` is mounted (the List's `aria-labelledby` names it only then). */\n readonly hasLabel: boolean;\n /** The enclosing `Field.Label`'s id: names the List when no `Combobox.Label` is mounted. */\n readonly fieldLabelId: string | undefined;\n readonly disabled: boolean;\n readonly inputRef: RefObject<HTMLInputElement | null>;\n readonly listRef: RefObject<HTMLElement | null>;\n /** Registers a mounted Option; returns the unregistration. */\n readonly registerOption: (value: string, entry: ComboboxOptionEntry) => () => void;\n /** Registers a mounted `Combobox.Status`; while one is mounted the results count as loading. */\n readonly registerStatus: () => () => void;\n /** Registers a mounted `Combobox.Label`; returns the unregistration. */\n readonly registerLabel: () => () => void;\n /** Make `value` the active option (urgent; never dispatches). */\n readonly setActive: (value: string | null) => void;\n /** Accept an option (design 5.2): urgent text write, dispatch, close when it settles. */\n readonly accept: (value: string, event: Event) => void;\n /** `Combobox.Clear` (design 3.3). */\n readonly clear: (event: Event) => void;\n /** The `change` of the Input: urgent text write and an open request (design 2.2, 5.1). */\n readonly typed: (text: string, event: Event) => void;\n /** Keyboard model of design section 8, run by the Input's `onKeyDown`. */\n readonly keyDown: (event: KeyboardEvent) => boolean;\n /** Focus arrived in the Input: track presses until a leave is decided. */\n readonly focusIn: (event: FocusEvent) => void;\n /** Focus left the Input (design 5.4): close at once, then revert or commit free text. */\n readonly focusOut: (event: FocusEvent) => void;\n /** A pointer click in the Input (`openOnClick`). */\n readonly inputClick: (event: MouseEvent) => void;\n /** A press on the Input: captures the pointer to the shown Popup (design 5.4). */\n readonly inputPointerDown: (event: PointerEvent) => void;\n}\n\nexport const ComboboxContext = createContext<ComboboxContextValue | null>(null);\n\nexport function useComboboxContext(part: string): ComboboxContextValue {\n const context = use(ComboboxContext);\n if (context === null) {\n throw new Error(`${part} must be rendered inside a Combobox.Root.`);\n }\n return context;\n}\n\n/** Provided by `Combobox.Popup` (a List outside a Popup warns). */\nexport const ComboboxPopupContext = createContext<boolean>(false);\n\n/** Provided by `Combobox.List` (an Option outside a List warns). */\nexport const ComboboxListContext = createContext<boolean>(false);\n\n/** `Combobox.Group`: the id its `Combobox.GroupLabel` renders. */\nexport const ComboboxGroupContext = createContext<string | null>(null);\n\n/** The id fragment of an option value: stable across result sets, no whitespace (design 3.5). */\nexport function optionId(prefix: string, value: string): string {\n return `${prefix}${encodeURIComponent(value)}`;\n}\n"],"mappings":";;;AA0EA,MAAa,kBAAkB,cAA2C,IAAI;AAE9E,SAAgB,mBAAmB,MAAoC;CACrE,MAAM,UAAU,IAAI,eAAe;CACnC,IAAI,YAAY,MACd,MAAM,IAAI,MAAM,GAAG,KAAK,0CAA0C;CAEpE,OAAO;AACT;;AAGA,MAAa,uBAAuB,cAAuB,KAAK;;AAGhE,MAAa,sBAAsB,cAAuB,KAAK;;AAG/D,MAAa,uBAAuB,cAA6B,IAAI;;AAGrE,SAAgB,SAAS,QAAgB,OAAuB;CAC9D,OAAO,GAAG,SAAS,mBAAmB,KAAK;AAC7C"}
|
|
@@ -3,8 +3,8 @@ import { dataAttr } from "../internal/data-attr.mjs";
|
|
|
3
3
|
import { useRender } from "../internal/use-render.mjs";
|
|
4
4
|
import { useElementCheck } from "../internal/use-element-check.mjs";
|
|
5
5
|
import { useMergedRefs } from "../internal/use-merged-refs.mjs";
|
|
6
|
-
import { useFieldControl } from "../internal/use-field-control.mjs";
|
|
7
|
-
import { registerTrigger } from "../internal/trigger-ref.mjs";
|
|
6
|
+
import { useFieldControl } from "../internal/form/use-field-control.mjs";
|
|
7
|
+
import { registerTrigger } from "../internal/overlay/trigger-ref.mjs";
|
|
8
8
|
import { optionId, useComboboxContext } from "./combobox-context.mjs";
|
|
9
9
|
import { isValidElement, useCallback } from "react";
|
|
10
10
|
//#region src/combobox/combobox-input.tsx
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-input.mjs","names":[],"sources":["../../src/combobox/combobox-input.tsx"],"sourcesContent":["\"use client\";\nimport { isValidElement, useCallback } from \"react\";\nimport type {\n ChangeEvent,\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n PointerEvent,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { registerTrigger } from \"../internal/trigger-ref.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useFieldControl } from \"../internal/use-field-control.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { optionId, useComboboxContext } from \"./combobox-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** State of `Combobox.Input`, passed to the function forms of `className`, `style` and `render`. */\nexport interface ComboboxInputState {\n /** Optimistic selection. */\n readonly value: string | null;\n /** The urgent text. */\n readonly inputValue: string;\n /** Optimistic open state. */\n readonly open: boolean;\n /** The Root is pending (a selection or an open in flight). */\n readonly pending: boolean;\n /** The results shown are for an older text. */\n readonly stale: boolean;\n /** The Root's `disabled` (or the Field's). */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `Combobox.Input`.\n *\n * @see https://ui.funstack.work/components/combobox\n */\nexport interface ComboboxInputProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"value\"\n | \"defaultValue\"\n | \"onChange\"\n | \"onInput\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onClick\"\n | \"onPointerDown\"\n | \"role\"\n | \"aria-autocomplete\"\n | \"aria-expanded\"\n | \"aria-controls\"\n | \"aria-activedescendant\"\n | \"autoComplete\"\n | \"disabled\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Native `required`: empty text is `valueMissing`. */\n required?: boolean;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, ComboboxInputState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, ComboboxInputState>;\n /** Must render an `<input>` of type `text` or `search`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, ComboboxInputState>;\n}\n\n/**\n * The text field: `<input role=\"combobox\" aria-autocomplete=\"list\" aria-expanded aria-controls\n * aria-activedescendant autocomplete=\"off\">`. DOM focus stays here while the active option moves\n * virtually (design 7.1). Its text is the Root's urgent `inputValue`; typing opens the listbox.\n *\n * Owned keys (conventions 1.2): `id`, `type`, `role`, `value`, `autoComplete`,\n * `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged), `aria-activedescendant`,\n * `disabled`, `onChange`, `onKeyDown`, `onFocus` and `onBlur` (focus arriving starts the press\n * watch that decides a focus loss), `onClick`, `onPointerDown` (a primary-button press while the\n * listbox is shown captures the pointer to the Popup, so it is no light dismiss), `data-open`,\n * `data-pending`, `data-selected`, `data-stale`, `data-disabled`; inside a `Field.Root` (whose\n * control id it takes) also `required` (own or the Field's), `aria-describedby` (token-merged),\n * `aria-invalid` and `data-invalid`. `onFocusCapture` passes through.\n *\n * @see https://ui.funstack.work/components/combobox\n */\nexport function ComboboxInput({ className, style, render, ...rest }: ComboboxInputProps) {\n const ctx = useComboboxContext(\"Combobox.Input\");\n const { popover, ids, inputRef } = ctx;\n const { triggerRef } = popover;\n\n const state: ComboboxInputState = {\n value: ctx.value,\n inputValue: ctx.inputValue,\n open: popover.optimistic,\n pending: ctx.pending,\n stale: ctx.stale,\n disabled: ctx.disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) => {\n const type = element.tagName === \"INPUT\" ? (element as HTMLInputElement).type : \"\";\n return type !== \"text\" && type !== \"search\"\n ? `Combobox.Input: rendered <${element.tagName.toLowerCase()}` +\n `${type === \"\" ? \"\" : ` type=\"${type}\"`}>. Render an <input> of type \"text\" or ` +\n '\"search\": `role=\"combobox\"`, `aria-activedescendant` and the caret keys depend on it.'\n : null;\n }),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n inputRef.current = element as HTMLInputElement;\n // The popover's \"trigger\" is the input: `showPopover({ source: input })` anchors the\n // listbox to it and stacks a nested listbox under its popover (design 5.1). It does not\n // exempt presses on the input from light dismiss; `onPointerDown` does that.\n const unregister = registerTrigger(triggerRef, element, \"Combobox.Input\");\n return () => {\n if (inputRef.current === element) inputRef.current = null;\n unregister();\n };\n },\n [checkElement, inputRef, triggerRef],\n );\n\n // Inside a Field.Root (design/components/field-form.md 7.2) the Input is the Field's control:\n // the Root already took the Field's id for it; `required` and the ARIA wiring land here.\n const field = useFieldControl({\n labelable: true,\n required: rest.required,\n disabled: ctx.disabled,\n id: rest.id,\n component: \"Combobox.Input\",\n });\n const fieldRef = field.ref;\n const mergedRef = useMergedRefs<HTMLElement>(ref, fieldRef);\n\n const searchType = isValidElement<{ type?: unknown }>(render) && render.props.type === \"search\";\n\n const libraryProps: ComponentPropsWithRef<\"input\"> & DataAttributes = {\n ...field.attributes,\n ...(field.inField && { required: field.required }),\n id: ids.input,\n type: searchType ? \"search\" : \"text\",\n role: \"combobox\",\n value: ctx.inputValue,\n autoComplete: \"off\",\n \"aria-autocomplete\": \"list\",\n // Shown (the listbox is in the top layer); `data-open` is the optimistic one.\n \"aria-expanded\": popover.shown,\n \"aria-controls\": ids.list,\n \"aria-activedescendant\":\n ctx.activeValue === null ? undefined : optionId(ids.optionPrefix, ctx.activeValue),\n disabled: ctx.disabled,\n onChange: (event: ChangeEvent<HTMLInputElement>) => {\n ctx.typed(event.currentTarget.value, event.nativeEvent);\n },\n onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {\n ctx.keyDown(event.nativeEvent);\n },\n onFocus: (event: FocusEvent<HTMLInputElement>) => {\n ctx.focusIn(event.nativeEvent);\n },\n onBlur: (event: FocusEvent<HTMLInputElement>) => {\n ctx.focusOut(event.nativeEvent);\n },\n onClick: (event: MouseEvent<HTMLInputElement>) => {\n ctx.inputClick(event.nativeEvent);\n },\n onPointerDown: (event: PointerEvent<HTMLInputElement>) => {\n ctx.inputPointerDown(event.nativeEvent);\n },\n \"data-open\": dataAttr(popover.optimistic),\n \"data-pending\": dataAttr(state.pending),\n \"data-selected\": dataAttr(ctx.value !== null),\n \"data-stale\": dataAttr(ctx.stale),\n \"data-disabled\": dataAttr(ctx.disabled),\n };\n\n return useRender<ComponentPropsWithRef<\"input\">, ComboboxInputState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n props: rest,\n libraryProps,\n ref: mergedRef,\n });\n}\n\nComboboxInput.displayName = \"ComboboxInput\";\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;;;AAuEvC,SAAgB,cAAc,EAAE,WAAW,OAAO,QAAQ,GAAG,QAA4B;CACvF,MAAM,MAAM,mBAAmB,gBAAgB;CAC/C,MAAM,EAAE,SAAS,KAAK,aAAa;CACnC,MAAM,EAAE,eAAe;CAEvB,MAAM,QAA4B;EAChC,OAAO,IAAI;EACX,YAAY,IAAI;EAChB,MAAM,QAAQ;EACd,SAAS,IAAI;EACb,OAAO,IAAI;EACX,UAAU,IAAI;CAChB;CAEA,MAAM,eAAe,gBACnB,WACI,YAAY;EACZ,MAAM,OAAO,QAAQ,YAAY,UAAW,QAA6B,OAAO;EAChF,OAAO,SAAS,UAA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aAAa,SAAS,QAAQ,UAAU;EACxC,gBAAgB,SAAS,MAAM,OAAO;EACtC,iBAAiB,SAAS,IAAI,UAAU,IAAI;EAC5C,cAAc,SAAS,IAAI,KAAK;EAChC,iBAAiB,SAAS,IAAI,QAAQ;CACxC;CAEA,OAAO,UAA8D;EACnE,gBAAgB;EAChB;EACA;EACA;EACA;EACA,UAAU,KAAA;EACV,OAAO;EACP;EACA,KAAK;CACP,CAAC;AACH;AAEA,cAAc,cAAc"}
|
|
1
|
+
{"version":3,"file":"combobox-input.mjs","names":[],"sources":["../../src/combobox/combobox-input.tsx"],"sourcesContent":["\"use client\";\nimport { isValidElement, useCallback } from \"react\";\nimport type {\n ChangeEvent,\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n PointerEvent,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { registerTrigger } from \"../internal/overlay/trigger-ref.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useFieldControl } from \"../internal/form/use-field-control.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { optionId, useComboboxContext } from \"./combobox-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** State of `Combobox.Input`, passed to the function forms of `className`, `style` and `render`. */\nexport interface ComboboxInputState {\n /** Optimistic selection. */\n readonly value: string | null;\n /** The urgent text. */\n readonly inputValue: string;\n /** Optimistic open state. */\n readonly open: boolean;\n /** The Root is pending (a selection or an open in flight). */\n readonly pending: boolean;\n /** The results shown are for an older text. */\n readonly stale: boolean;\n /** The Root's `disabled` (or the Field's). */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `Combobox.Input`.\n *\n * @see https://ui.funstack.work/components/combobox\n */\nexport interface ComboboxInputProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"value\"\n | \"defaultValue\"\n | \"onChange\"\n | \"onInput\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onClick\"\n | \"onPointerDown\"\n | \"role\"\n | \"aria-autocomplete\"\n | \"aria-expanded\"\n | \"aria-controls\"\n | \"aria-activedescendant\"\n | \"autoComplete\"\n | \"disabled\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Native `required`: empty text is `valueMissing`. */\n required?: boolean;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, ComboboxInputState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, ComboboxInputState>;\n /** Must render an `<input>` of type `text` or `search`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, ComboboxInputState>;\n}\n\n/**\n * The text field: `<input role=\"combobox\" aria-autocomplete=\"list\" aria-expanded aria-controls\n * aria-activedescendant autocomplete=\"off\">`. DOM focus stays here while the active option moves\n * virtually (design 7.1). Its text is the Root's urgent `inputValue`; typing opens the listbox.\n *\n * Owned keys (conventions 1.2): `id`, `type`, `role`, `value`, `autoComplete`,\n * `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged), `aria-activedescendant`,\n * `disabled`, `onChange`, `onKeyDown`, `onFocus` and `onBlur` (focus arriving starts the press\n * watch that decides a focus loss), `onClick`, `onPointerDown` (a primary-button press while the\n * listbox is shown captures the pointer to the Popup, so it is no light dismiss), `data-open`,\n * `data-pending`, `data-selected`, `data-stale`, `data-disabled`; inside a `Field.Root` (whose\n * control id it takes) also `required` (own or the Field's), `aria-describedby` (token-merged),\n * `aria-invalid` and `data-invalid`. `onFocusCapture` passes through.\n *\n * @see https://ui.funstack.work/components/combobox\n */\nexport function ComboboxInput({ className, style, render, ...rest }: ComboboxInputProps) {\n const ctx = useComboboxContext(\"Combobox.Input\");\n const { popover, ids, inputRef } = ctx;\n const { triggerRef } = popover;\n\n const state: ComboboxInputState = {\n value: ctx.value,\n inputValue: ctx.inputValue,\n open: popover.optimistic,\n pending: ctx.pending,\n stale: ctx.stale,\n disabled: ctx.disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) => {\n const type = element.tagName === \"INPUT\" ? (element as HTMLInputElement).type : \"\";\n return type !== \"text\" && type !== \"search\"\n ? `Combobox.Input: rendered <${element.tagName.toLowerCase()}` +\n `${type === \"\" ? \"\" : ` type=\"${type}\"`}>. Render an <input> of type \"text\" or ` +\n '\"search\": `role=\"combobox\"`, `aria-activedescendant` and the caret keys depend on it.'\n : null;\n }),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n inputRef.current = element as HTMLInputElement;\n // The popover's \"trigger\" is the input: `showPopover({ source: input })` anchors the\n // listbox to it and stacks a nested listbox under its popover (design 5.1). It does not\n // exempt presses on the input from light dismiss; `onPointerDown` does that.\n const unregister = registerTrigger(triggerRef, element, \"Combobox.Input\");\n return () => {\n if (inputRef.current === element) inputRef.current = null;\n unregister();\n };\n },\n [checkElement, inputRef, triggerRef],\n );\n\n // Inside a Field.Root (design/components/field-form.md 7.2) the Input is the Field's control:\n // the Root already took the Field's id for it; `required` and the ARIA wiring land here.\n const field = useFieldControl({\n labelable: true,\n required: rest.required,\n disabled: ctx.disabled,\n id: rest.id,\n component: \"Combobox.Input\",\n });\n const fieldRef = field.ref;\n const mergedRef = useMergedRefs<HTMLElement>(ref, fieldRef);\n\n const searchType = isValidElement<{ type?: unknown }>(render) && render.props.type === \"search\";\n\n const libraryProps: ComponentPropsWithRef<\"input\"> & DataAttributes = {\n ...field.attributes,\n ...(field.inField && { required: field.required }),\n id: ids.input,\n type: searchType ? \"search\" : \"text\",\n role: \"combobox\",\n value: ctx.inputValue,\n autoComplete: \"off\",\n \"aria-autocomplete\": \"list\",\n // Shown (the listbox is in the top layer); `data-open` is the optimistic one.\n \"aria-expanded\": popover.shown,\n \"aria-controls\": ids.list,\n \"aria-activedescendant\":\n ctx.activeValue === null ? undefined : optionId(ids.optionPrefix, ctx.activeValue),\n disabled: ctx.disabled,\n onChange: (event: ChangeEvent<HTMLInputElement>) => {\n ctx.typed(event.currentTarget.value, event.nativeEvent);\n },\n onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {\n ctx.keyDown(event.nativeEvent);\n },\n onFocus: (event: FocusEvent<HTMLInputElement>) => {\n ctx.focusIn(event.nativeEvent);\n },\n onBlur: (event: FocusEvent<HTMLInputElement>) => {\n ctx.focusOut(event.nativeEvent);\n },\n onClick: (event: MouseEvent<HTMLInputElement>) => {\n ctx.inputClick(event.nativeEvent);\n },\n onPointerDown: (event: PointerEvent<HTMLInputElement>) => {\n ctx.inputPointerDown(event.nativeEvent);\n },\n \"data-open\": dataAttr(popover.optimistic),\n \"data-pending\": dataAttr(state.pending),\n \"data-selected\": dataAttr(ctx.value !== null),\n \"data-stale\": dataAttr(ctx.stale),\n \"data-disabled\": dataAttr(ctx.disabled),\n };\n\n return useRender<ComponentPropsWithRef<\"input\">, ComboboxInputState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n props: rest,\n libraryProps,\n ref: mergedRef,\n });\n}\n\nComboboxInput.displayName = \"ComboboxInput\";\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;;;AAuEvC,SAAgB,cAAc,EAAE,WAAW,OAAO,QAAQ,GAAG,QAA4B;CACvF,MAAM,MAAM,mBAAmB,gBAAgB;CAC/C,MAAM,EAAE,SAAS,KAAK,aAAa;CACnC,MAAM,EAAE,eAAe;CAEvB,MAAM,QAA4B;EAChC,OAAO,IAAI;EACX,YAAY,IAAI;EAChB,MAAM,QAAQ;EACd,SAAS,IAAI;EACb,OAAO,IAAI;EACX,UAAU,IAAI;CAChB;CAEA,MAAM,eAAe,gBACnB,WACI,YAAY;EACZ,MAAM,OAAO,QAAQ,YAAY,UAAW,QAA6B,OAAO;EAChF,OAAO,SAAS,UAAU,SAAS,WAC/B,6BAA6B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U;EACxC,gBAAgB,SAAS,MAAM,OAAO;EACtC,iBAAiB,SAAS,IAAI,UAAU,IAAI;EAC5C,cAAc,SAAS,IAAI,KAAK;EAChC,iBAAiB,SAAS,IAAI,QAAQ;CACxC;CAEA,OAAO,UAA8D;EACnE,gBAAgB;EAChB;EACA;EACA;EACA;EACA,UAAU,KAAA;EACV,OAAO;EACP;EACA,KAAK;CACP,CAAC;AACH;AAEA,cAAc,cAAc"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
3
|
+
import { flushSync } from "react-dom";
|
|
4
|
+
//#region src/combobox/combobox-keyboard.ts
|
|
5
|
+
/**
|
|
6
|
+
* The keyboard model of the Combobox Input (design/components/combobox.md 8), the counterpart of
|
|
7
|
+
* `menu/use-menu-keyboard.ts`. A plain factory, not a hook (it calls none): the Root calls it on
|
|
8
|
+
* every render. Returns the Input's `keydown` handler, which tells whether it handled the key.
|
|
9
|
+
*/
|
|
10
|
+
function createComboboxKeyDown({ disabled, loop, allowCustomValue, popover, options, active, accept, commitText }) {
|
|
11
|
+
const { registry, orderedOptions } = options;
|
|
12
|
+
const { activeRef, setActive, pendingEdgeRef } = active;
|
|
13
|
+
const move = (direction) => {
|
|
14
|
+
const enabled = orderedOptions().filter((option) => !option.disabled);
|
|
15
|
+
if (enabled.length === 0) return;
|
|
16
|
+
const last = enabled.length - 1;
|
|
17
|
+
const index = enabled.findIndex((option) => option.value === activeRef.current);
|
|
18
|
+
let next;
|
|
19
|
+
if (direction === 1) next = index < 0 ? 0 : index >= last ? loop ? 0 : last : index + 1;
|
|
20
|
+
else next = index < 0 ? last : index <= 0 ? loop ? last : 0 : index - 1;
|
|
21
|
+
const target = enabled[next];
|
|
22
|
+
setActive(target.value);
|
|
23
|
+
if (typeof target.element.scrollIntoView === "function") target.element.scrollIntoView({ block: "nearest" });
|
|
24
|
+
};
|
|
25
|
+
const activeEnabled = () => {
|
|
26
|
+
const current = activeRef.current;
|
|
27
|
+
if (current === null) return null;
|
|
28
|
+
const entry = registry.get(current);
|
|
29
|
+
return entry !== void 0 && !entry.disabled ? current : null;
|
|
30
|
+
};
|
|
31
|
+
return (event) => {
|
|
32
|
+
if (disabled || event.ctrlKey || event.metaKey) return false;
|
|
33
|
+
if (event.isComposing || event.keyCode === 229) return false;
|
|
34
|
+
const isOpen = isPopoverOpen(popover.popupRef.current);
|
|
35
|
+
switch (event.key) {
|
|
36
|
+
case "ArrowDown":
|
|
37
|
+
event.preventDefault();
|
|
38
|
+
if (event.altKey) {
|
|
39
|
+
if (!isOpen) popover.requestOpen(event, "activate");
|
|
40
|
+
} else if (!isOpen) {
|
|
41
|
+
pendingEdgeRef.current = "first";
|
|
42
|
+
popover.requestOpen(event, "activate");
|
|
43
|
+
} else move(1);
|
|
44
|
+
return true;
|
|
45
|
+
case "ArrowUp":
|
|
46
|
+
event.preventDefault();
|
|
47
|
+
if (event.altKey) {
|
|
48
|
+
if (isOpen) {
|
|
49
|
+
const current = activeEnabled();
|
|
50
|
+
if (current !== null) accept(current, event);
|
|
51
|
+
else popover.requestClose(event, "activate");
|
|
52
|
+
}
|
|
53
|
+
} else if (!isOpen) {
|
|
54
|
+
pendingEdgeRef.current = "last";
|
|
55
|
+
popover.requestOpen(event, "activate");
|
|
56
|
+
} else move(-1);
|
|
57
|
+
return true;
|
|
58
|
+
case "Enter":
|
|
59
|
+
if (isOpen) {
|
|
60
|
+
event.preventDefault();
|
|
61
|
+
const current = activeEnabled();
|
|
62
|
+
if (current !== null) accept(current, event);
|
|
63
|
+
else if (allowCustomValue && !commitText(event, true)) popover.requestClose(event, "activate");
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
if (allowCustomValue) flushSync(() => commitText(event, false));
|
|
67
|
+
return false;
|
|
68
|
+
case "Home":
|
|
69
|
+
case "End":
|
|
70
|
+
case "ArrowLeft":
|
|
71
|
+
case "ArrowRight":
|
|
72
|
+
if (activeRef.current !== null) setActive(null);
|
|
73
|
+
return false;
|
|
74
|
+
default: return false;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
export { createComboboxKeyDown };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=combobox-keyboard.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"combobox-keyboard.mjs","names":[],"sources":["../../src/combobox/combobox-keyboard.ts"],"sourcesContent":["\"use client\";\nimport { flushSync } from \"react-dom\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport type { ActiveOption } from \"./use-active-option.js\";\nimport type { OptionRegistry } from \"./use-option-registry.js\";\n\nexport interface ComboboxKeyboardOptions {\n /** The Root's `disabled`, `loop` and `allowCustomValue`. */\n readonly disabled: boolean;\n readonly loop: boolean;\n readonly allowCustomValue: boolean;\n readonly popover: Pick<PopoverRootValue, \"popupRef\" | \"requestOpen\" | \"requestClose\">;\n readonly options: Pick<OptionRegistry, \"registry\" | \"orderedOptions\">;\n readonly active: Pick<ActiveOption, \"activeRef\" | \"setActive\" | \"pendingEdgeRef\">;\n /** Accepts an option (design 5.2). */\n readonly accept: (optionValue: string, event: Event) => void;\n /** Free text as the value (design 5.3). Returns whether it dispatched. */\n readonly commitText: (event: Event, close: boolean) => boolean;\n}\n\n/**\n * The keyboard model of the Combobox Input (design/components/combobox.md 8), the counterpart of\n * `menu/use-menu-keyboard.ts`. A plain factory, not a hook (it calls none): the Root calls it on\n * every render. Returns the Input's `keydown` handler, which tells whether it handled the key.\n */\nexport function createComboboxKeyDown({\n disabled,\n loop,\n allowCustomValue,\n popover,\n options,\n active,\n accept,\n commitText,\n}: ComboboxKeyboardOptions): (event: KeyboardEvent) => boolean {\n const { registry, orderedOptions } = options;\n const { activeRef, setActive, pendingEdgeRef } = active;\n\n const move = (direction: 1 | -1): void => {\n const enabled = orderedOptions().filter((option) => !option.disabled);\n if (enabled.length === 0) return;\n const last = enabled.length - 1;\n const index = enabled.findIndex((option) => option.value === activeRef.current);\n let next: number;\n if (direction === 1) next = index < 0 ? 0 : index >= last ? (loop ? 0 : last) : index + 1;\n else next = index < 0 ? last : index <= 0 ? (loop ? last : 0) : index - 1;\n const target = enabled[next]!;\n setActive(target.value);\n if (typeof target.element.scrollIntoView === \"function\") {\n target.element.scrollIntoView({ block: \"nearest\" });\n }\n };\n\n const activeEnabled = (): string | null => {\n const current = activeRef.current;\n if (current === null) return null;\n const entry = registry.get(current);\n return entry !== undefined && !entry.disabled ? current : null;\n };\n\n return (event: KeyboardEvent): boolean => {\n if (disabled || event.ctrlKey || event.metaKey) return false;\n // IME: the key belongs to the composition (Enter commits it, arrows pick a candidate).\n if (event.isComposing || event.keyCode === 229) return false;\n // What the user sees, not what is intended: right after Escape the platform has hidden the\n // popup but its `toggle` (and the fact it reports) is still queued, and an open that\n // is still committing shows nothing yet. Enter must submit and arrows must open in both.\n const isOpen = isPopoverOpen(popover.popupRef.current);\n switch (event.key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (event.altKey) {\n if (!isOpen) popover.requestOpen(event, \"activate\");\n } else if (!isOpen) {\n pendingEdgeRef.current = \"first\";\n popover.requestOpen(event, \"activate\");\n } else {\n move(1);\n }\n return true;\n case \"ArrowUp\":\n event.preventDefault();\n if (event.altKey) {\n if (isOpen) {\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else popover.requestClose(event, \"activate\");\n }\n } else if (!isOpen) {\n pendingEdgeRef.current = \"last\";\n popover.requestOpen(event, \"activate\");\n } else {\n move(-1);\n }\n return true;\n case \"Enter\": {\n if (isOpen) {\n // An open listbox means the user is choosing: never submit from here.\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) accept(current, event);\n else if (allowCustomValue && !commitText(event, true)) {\n popover.requestClose(event, \"activate\");\n }\n return true;\n }\n // Closed: not prevented, so a form still submits. The key's default action (implicit\n // submission) must see the optimistic hidden value: Firefox submits before React's\n // scheduled flush of the optimistic render, so it is flushed here (design 5.3).\n if (allowCustomValue) flushSync(() => commitText(event, false));\n return false;\n }\n case \"Home\":\n case \"End\":\n case \"ArrowLeft\":\n case \"ArrowRight\":\n // APG: the caret keys move visual focus to the input (not prevented: the caret moves).\n if (activeRef.current !== null) setActive(null);\n return false;\n default:\n return false;\n }\n };\n}\n"],"mappings":";;;;;;;;;AA0BA,SAAgB,sBAAsB,EACpC,UACA,MACA,kBACA,SACA,SACA,QACA,QACA,cAC6D;CAC7D,MAAM,EAAE,UAAU,mBAAmB;CACrC,MAAM,EAAE,WAAW,WAAW,mBAAmB;CAEjD,MAAM,QAAQ,cAA4B;EACxC,MAAM,UAAU,eAAe,CAAC,CAAC,QAAQ,WAAW,CAAC,OAAO,QAAQ;EACpE,IAAI,QAAQ,WAAW,GAAG;EAC1B,MAAM,OAAO,QAAQ,SAAS;EAC9B,MAAM,QAAQ,QAAQ,WAAW,WAAW,OAAO,UAAU,UAAU,OAAO;EAC9E,IAAI;EACJ,IAAI,cAAc,GAAG,OAAO,QAAQ,IAAI,IAAI,SAAS,OAAQ,OAAO,IAAI,OAAQ,QAAQ;OACnF,OAAO,QAAQ,IAAI,OAAO,SAAS,IAAK,OAAO,OAAO,IAAK,QAAQ;EACxE,MAAM,SAAS,QAAQ;EACvB,UAAU,OAAO,KAAK;EACtB,IAAI,OAAO,OAAO,QAAQ,mBAAmB,YAC3C,OAAO,QAAQ,eAAe,EAAE,OAAO,UAAU,CAAC;CAEtD;CAEA,MAAM,sBAAqC;EACzC,MAAM,UAAU,UAAU;EAC1B,IAAI,YAAY,MAAM,OAAO;EAC7B,MAAM,QAAQ,SAAS,IAAI,OAAO;EAClC,OAAO,UAAU,KAAA,KAAa,CAAC,MAAM,WAAW,UAAU;CAC5D;CAEA,QAAQ,UAAkC;EACxC,IAAI,YAAY,MAAM,WAAW,MAAM,SAAS,OAAO;EAEvD,IAAI,MAAM,eAAe,MAAM,Y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