@funstack/ui 0.1.0-alpha.18 → 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 +30 -35
- package/dist/accordion/accordion-root.mjs.map +1 -1
- package/dist/accordion/accordion-trigger.mjs +1 -1
- package/dist/button/button.d.mts +11 -6
- package/dist/button/button.d.mts.map +1 -1
- package/dist/button/button.mjs +25 -14
- 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 +5 -5
- 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 -169
- 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/button.md +3 -3
- package/dist/docs/components/dialog.md +3 -3
- package/dist/docs/components/field.md +4 -3
- package/dist/docs/components/popover.md +3 -3
- package/dist/docs/components/toast.md +8 -5
- 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} +13 -28
- 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} +2 -2
- 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 -66
- 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":"field-root.mjs","names":[],"sources":["../../src/field/field-root.tsx"],"sourcesContent":["\"use client\";\nimport {\n use,\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode, RefObject } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { FieldContext, fieldDataAttributes, FormContext } from \"../internal/field-context.js\";\nimport type {\n FieldContextValue,\n FieldControlRegistration,\n FieldState,\n FormFieldRegistration,\n} from \"../internal/field-context.js\";\nimport { collectInvalid } from \"../internal/focus-first-invalid.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useFormOwnerEvent } from \"../internal/use-form-owner-event.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useServerErrorVisibility } from \"./use-server-error-visibility.js\";\nimport {\n focusTargetOf,\n normaliseErrorValue,\n snapshotValidity,\n supportsUserInvalid,\n VALID,\n validityElementOf,\n validityEquals,\n} from \"../internal/validity.js\";\nimport type { FieldErrorValue, FieldValidity, ValidatableElement } from \"../internal/validity.js\";\nimport { arraysEqual } from \"../internal/value-set.js\";\n\nexport type { FieldState } from \"../internal/field-context.js\";\nexport type { FieldValidity } from \"../internal/validity.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * A custom constraint: receives the field's submitted value (`formData.get(name)` as a string,\n * `\"\"` when absent) and the whole form's `FormData`. Return a message (or several) for an error,\n * `null` / `undefined` / `\"\"` for none.\n */\nexport type FieldValidate = (value: string, formData: FormData) => FieldErrorValue;\n\n/**\n * Props of `Field.Root`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FieldRootProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"className\" | \"style\" | \"children\"\n> {\n /** Form field name: the control's default `name`, the key in `Form.Root errors`, and the entry `validate` reads. */\n name?: string;\n /**\n * Disables the control (native `disabled`) and marks every part `data-disabled`.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Makes the control `required` (native) and marks every part `data-required`.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * A custom constraint, written into the control with `setCustomValidity`. Sync. Receives the\n * field's submitted value (`formData.get(name)` as a string, `\"\"` when absent) and the whole\n * form's `FormData`, so a cross-field rule can read the other field. Runs at mount, on every\n * `input` / `change` in the form (and a FUNSTACK control's value change), on blur, after a\n * reset, on a submission attempt, and in every commit in which this prop changed identity, so\n * a rule that reads outside state (a list that loads, a sibling value in React state) updates\n * on render. An inline function therefore re-runs on every render of the Field; wrap it in\n * `useCallback` to re-run only when its inputs change. Return a string\n * or strings for an error, `null` / `undefined` / `\"\"` for none. Shown when the platform's\n * `:user-invalid` heuristic says so, like a native constraint. Not serialisable: a Field with\n * `validate` is rendered from a client component.\n */\n validate?: FieldValidate;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, FieldState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FieldState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FieldState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, FieldState>;\n}\n\n/** The urgent mirror of browser-owned validity (design 2.4). */\ninterface Mirror {\n readonly userInvalid: boolean;\n readonly validity: FieldValidity;\n readonly messages: readonly string[];\n}\n\nconst NONE: readonly string[] = Object.freeze([]);\nconst INITIAL_MIRROR: Mirror = { userInvalid: false, validity: VALID, messages: NONE };\n\ninterface RefreshOptions {\n /** The user edited the control: the server message is dropped from the slot at once. */\n readonly dismiss?: boolean;\n /** After a form reset: the user-validity flag is clear again. */\n readonly reset?: boolean;\n}\n\nfunction mirrorEquals(a: Mirror, b: Mirror): boolean {\n return (\n a.userInvalid === b.userInvalid &&\n validityEquals(a.validity, b.validity) &&\n arraysEqual(a.messages, b.messages)\n );\n}\n\n/** `FormData` entries as comparable strings; a `File` counts as unchanged (design 3.2 item 2). */\nfunction entryStrings(entries: readonly FormDataEntryValue[]): string[] {\n return entries.map((entry) => (typeof entry === \"string\" ? entry : \"\\u0000file\"));\n}\n\n/**\n * The field: a `div` that owns the ids, the urgent validity mirror, the custom-validity slot\n * (`validate` and the server error), the control registration and the native listeners\n * (design/components/field-form.md 2, 14). `data-pending` is the enclosing form's submission\n * (`useFormStatus`), the one part that folds the form channel into its own state, because a\n * Field has no action of its own.\n *\n * Owned keys (conventions 1.2): `data-invalid`, `data-disabled`, `data-required`, `data-pending`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FieldRoot({\n name,\n disabled = false,\n required = false,\n validate,\n className,\n style,\n children,\n render,\n ...rest\n}: FieldRootProps) {\n const parent = use(FieldContext);\n const form = use(FormContext);\n useDevWarning(\n parent !== null,\n isDev &&\n \"Field.Root: nested inside another Field.Root. A control registers with the nearest Field \" +\n \"only; give each control its own, sibling Field.\",\n );\n useDevWarning(\n validate !== undefined && name === undefined,\n isDev &&\n \"Field.Root: `validate` without `name`. `validate` receives `formData.get(name)`, which is \" +\n 'always \"\" without a name.',\n );\n\n const id = useId();\n const ids = useMemo(\n () => ({\n control: `${id}-control`,\n label: `${id}-label`,\n description: `${id}-description`,\n error: `${id}-error`,\n }),\n [id],\n );\n\n const { pending: formPending } = useFormStatus();\n\n // --- Registration -------------------------------------------------------------------------\n\n const controlRef = useRef<FieldControlRegistration | null>(null);\n const [control, setControl] = useState<FieldControlRegistration | null>(null);\n const warnedTwoControls = useRef(false);\n const registerControl = useCallback((registration: FieldControlRegistration) => {\n const current = controlRef.current;\n if (current !== null && current.element !== registration.element) {\n if (isDev && !warnedTwoControls.current) {\n warnedTwoControls.current = true;\n console.error(\n \"Field.Root: two form controls registered in one Field. The first one is the \" +\n \"Field's control; give each control its own Field.Root.\",\n );\n }\n return () => {};\n }\n controlRef.current = registration;\n setControl(registration);\n return () => {\n if (controlRef.current !== registration) return;\n controlRef.current = null;\n setControl(null);\n };\n }, []);\n\n const errorCount = useRef(0);\n const registerError = useCallback(() => {\n errorCount.current += 1;\n if (isDev && errorCount.current === 2) {\n console.error(\n \"Field.Error: two Field.Error parts in one Field.Root. Render one; its function \" +\n \"`children` receives `validity` for per-constraint wording.\",\n );\n }\n return () => {\n errorCount.current -= 1;\n };\n }, []);\n\n // --- Server errors: shown, dismissed, re-armed, suppressed (design 3.4) -------------------\n\n const errors = form?.errors;\n const serverMessages = useMemo(\n () => normaliseErrorValue(name === undefined ? undefined : errors?.[name]),\n [errors, name],\n );\n const serverKey = serverMessages.join(\"\\n\");\n const { serverShown, dismiss, setSuppressNext } = useServerErrorVisibility(\n formPending,\n serverMessages,\n );\n\n // --- The mirror -----------------------------------------------------------------------------\n\n const [mirror, setMirror] = useState<Mirror>(INITIAL_MIRROR);\n /** The last mirror written: `refresh` compares against it, so an unchanged read renders nothing. */\n const mirrorRef = useRef<Mirror>(INITIAL_MIRROR);\n /** jsdom fallback for `:user-invalid` (design 2.2): `invalid` fired, cleared by a reset. */\n const attempted = useRef(false);\n /** The element the slot was last written on (a group's first member can change). */\n const slotElement = useRef<ValidatableElement | null>(null);\n\n const latest = useLatest({ name, validate, serverMessages, serverShown, formPending, form });\n\n /** Re-reads the slot and the mirror; returns the messages the Field shows for the control. */\n const refresh = useCallback(\n (options: RefreshOptions = {}): readonly string[] => {\n const registration = controlRef.current;\n if (registration === null) return NONE;\n // The element whose validity is real (field-form.md, `validityElement`) and the\n // element whose `:user-invalid` the user's interaction sets; the same for every control but\n // NumberField.\n const surface = validityElementOf(registration.element);\n const el = registration.validityElement?.() ?? surface;\n if (el === null) return NONE;\n const { name, validate, serverMessages, serverShown, formPending, form } = latest.current;\n\n const owner = el.form;\n const formData = owner === null ? new FormData() : new FormData(owner);\n const entry = name === undefined ? null : formData.get(name);\n const value = typeof entry === \"string\" ? entry : \"\";\n const custom = validate === undefined ? NONE : normaliseErrorValue(validate(value, formData));\n\n // The slot (design 2.1): the server message while shown, else `validate`'s.\n const showServer = serverShown && options.dismiss !== true;\n if (slotElement.current !== null && slotElement.current !== el) {\n slotElement.current.setCustomValidity(\"\");\n }\n slotElement.current = el;\n el.setCustomValidity(showServer ? serverMessages.join(\"\\n\") : custom.join(\"\\n\"));\n // Mirror onto the surface so its `:user-invalid` read below sees the new state (the control\n // writes the same derived value after each of its own writes).\n if (\n surface !== null &&\n surface !== el &&\n surface.validationMessage !== el.validationMessage\n ) {\n surface.setCustomValidity(el.validationMessage);\n }\n\n if (options.reset === true) attempted.current = false;\n const userInvalid = supportsUserInvalid()\n ? (surface ?? el).matches(\":user-invalid\")\n : attempted.current && !el.validity.valid;\n const validity = snapshotValidity(el.validity);\n const messages = validity.valid\n ? NONE\n : validity.customError && !showServer && custom.length > 0\n ? custom\n : el.validationMessage === \"\"\n ? NONE\n : [el.validationMessage];\n const next: Mirror = { userInvalid, validity, messages };\n // Only a change schedules a render (a `focusout` with nothing new causes none).\n if (!mirrorEquals(mirrorRef.current, next)) {\n mirrorRef.current = next;\n setMirror(next);\n }\n\n // Stale-value suppression (design 3.2 item 2): while the Form's own submission is in\n // flight, an error is about the value it sent; compare with what the field holds now.\n const submitted = formPending && name !== undefined ? (form?.submittedData() ?? null) : null;\n if (submitted !== null && name !== undefined) {\n setSuppressNext(\n !arraysEqual(entryStrings(formData.getAll(name)), entryStrings(submitted.getAll(name))),\n );\n }\n return showServer ? serverMessages : messages;\n },\n [latest, setSuppressNext],\n );\n\n // The slot follows the server error and `validate` (and is written once the control is known).\n // Keyed on `validate`'s identity (design 2.1): a rule reading outside state updates in the\n // commit that changed it. An inline function re-runs on every render (documented: `useCallback`\n // avoids it); the form's own values are covered by the listeners below.\n useLayoutEffect(() => {\n refresh();\n }, [refresh, control, serverShown, serverKey, validate]);\n\n // Clear the slot when the control goes away (it may be reused outside the Field).\n useLayoutEffect(\n () => () => {\n slotElement.current?.setCustomValidity(\"\");\n slotElement.current = null;\n },\n [],\n );\n\n // The control's own events (capture, so a group's members are seen on its fieldset).\n const element = control?.element ?? null;\n useLayoutEffect(() => {\n if (element === null) return;\n const onEdit = () => {\n dismiss();\n refresh({ dismiss: true });\n };\n const onBlur = () => refresh();\n const onInvalid = (event: Event) => {\n const target = event.target as ValidatableElement;\n // A submission attempt sets user validity before validating; `checkValidity()` and\n // `reportValidity()` do not (design 2.5). The fallback cannot tell them apart.\n const attempt = supportsUserInvalid() ? target.matches(\":user-invalid\") : true;\n if (!supportsUserInvalid()) attempted.current = true;\n if (attempt && errorCount.current > 0) {\n event.preventDefault();\n const messages = refresh();\n collectInvalid(focusTargetOf(element), messages.join(\" \"), target);\n return;\n }\n refresh();\n };\n element.addEventListener(\"input\", onEdit, true);\n element.addEventListener(\"change\", onEdit, true);\n element.addEventListener(\"focusout\", onBlur, true);\n element.addEventListener(\"invalid\", onInvalid, true);\n return () => {\n element.removeEventListener(\"input\", onEdit, true);\n element.removeEventListener(\"change\", onEdit, true);\n element.removeEventListener(\"focusout\", onBlur, true);\n element.removeEventListener(\"invalid\", onInvalid, true);\n };\n }, [element, refresh, dismiss]);\n\n // The form owner's events: another field's edit re-runs `validate` (cross-field rules); a reset\n // clears the user-validity flag, re-read when the controls hold their reset values.\n const ownerRef = useMemo<RefObject<Element | null>>(\n () => ({\n get current() {\n return controlRef.current?.element ?? null;\n },\n set current(_ignored) {},\n }),\n [],\n );\n const onOwnerEdit = (event: Event) => {\n const target = event.target;\n if (target instanceof Node && controlRef.current?.element.contains(target) === true) return;\n refresh();\n };\n useFormOwnerEvent(ownerRef, \"input\", onOwnerEdit);\n useFormOwnerEvent(ownerRef, \"change\", onOwnerEdit);\n // A new submission sends the current values: nothing differs from it yet (a queued second\n // submit arrives while the status stays pending, so the pending edge alone would miss it).\n useFormOwnerEvent(ownerRef, \"submit\", () => {\n setSuppressNext(false);\n });\n useFormOwnerEvent(ownerRef, \"reset\", (event) => {\n queueMicrotask(() => {\n if (event.defaultPrevented) return;\n refresh({ reset: true });\n });\n });\n\n // Registration with the Form, for the first-error focus after a settle (design 3.5) and the\n // refresh of the other Fields on a change no DOM event carried.\n const registerField = form?.registerField;\n const formRegistration = useRef<FormFieldRegistration | null>(null);\n useLayoutEffect(() => {\n if (registerField === undefined) return;\n const registration: FormFieldRegistration = {\n getFocusTarget: () => focusTargetOf(controlRef.current?.element ?? null),\n showsServerError: () => latest.current.serverShown,\n serverMessages: () => latest.current.serverMessages,\n refresh: () => {\n refresh();\n },\n };\n formRegistration.current = registration;\n const unregister = registerField(registration);\n return () => {\n unregister();\n if (formRegistration.current === registration) formRegistration.current = null;\n };\n }, [registerField, latest, refresh]);\n\n const notifyChange = useCallback(\n (edit: boolean) => {\n if (edit) dismiss();\n refresh(edit ? { dismiss: true } : {});\n latest.current.form?.refreshFields(formRegistration.current);\n },\n [refresh, latest, dismiss],\n );\n\n // Development: a Field around something that is not a form control (Toggle, Menu, ...).\n useEffect(() => {\n if (!isDev || controlRef.current !== null) return;\n console.error(\n \"Field.Root: no form control registered. Render a Field.Control or a FUNSTACK form \" +\n \"control (Checkbox, Switch, RadioGroup, CheckboxGroup, Select, Combobox, Slider, \" +\n \"NumberField) inside it.\",\n );\n }, []);\n\n const invalid = mirror.userInvalid || serverShown;\n const messages = serverShown ? serverMessages : mirror.userInvalid ? mirror.messages : NONE;\n const validity = mirror.validity;\n const stateDisabled = disabled || (control?.disabled ?? false);\n const stateRequired = required || (control?.required ?? false);\n // Memoised: the context value (and so every part) changes only with the state.\n const memoState = useMemo<FieldState>(\n () => ({\n invalid,\n messages,\n validity,\n disabled: stateDisabled,\n required: stateRequired,\n pending: formPending,\n }),\n [invalid, messages, validity, stateDisabled, stateRequired, formPending],\n );\n\n const labelable = control?.labelable ?? true;\n const context = useMemo<FieldContextValue>(\n () => ({\n ids,\n name,\n disabled,\n required,\n state: memoState,\n labelable,\n registerControl,\n registerError,\n notifyChange,\n }),\n [\n ids,\n name,\n disabled,\n required,\n memoState,\n labelable,\n registerControl,\n registerError,\n notifyChange,\n ],\n );\n\n const element$ = useRender<ComponentPropsWithRef<\"div\">, FieldState>({\n defaultElement: \"div\",\n render,\n state: memoState,\n className,\n style,\n children,\n props: rest,\n libraryProps: fieldDataAttributes(memoState),\n });\n\n return <FieldContext value={context}>{element$}</FieldContext>;\n}\n\nFieldRoot.displayName = \"FieldRoot\";\n"],"mappings":";;;;;;;;;;;;;;AA0CA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA+DvC,MAAM,OAA0B,OAAO,OAAO,CAAC,CAAC;AAChD,MAAM,iBAAyB;CAAE,aAAa;CAAO,UAAU;CAAO,UAAU;AAAK;AASrF,SAAS,aAAa,GAAW,GAAoB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AChB;EACA,OAAO;EACP;EACA;EACA;EACA,OAAO;EACP,cAAc,oBAAoB,SAAS;CAC7C,CAAC;CAED,OAAO,oBAAC,cAAD;EAAc,OAAO;EAAU,UAAA;CAAuB,CAAA;AAC/D;AAEA,UAAU,cAAc"}
|
|
1
|
+
{"version":3,"file":"field-root.mjs","names":[],"sources":["../../src/field/field-root.tsx"],"sourcesContent":["\"use client\";\nimport {\n use,\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode, RefObject } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { FieldContext, fieldDataAttributes, FormContext } from \"../internal/form/field-context.js\";\nimport type {\n FieldContextValue,\n FieldControlRegistration,\n FieldState,\n FormFieldRegistration,\n} from \"../internal/form/field-context.js\";\nimport { collectInvalid } from \"../internal/form/focus-first-invalid.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useFormOwnerEvent } from \"../internal/form/use-form-owner-event.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useServerErrorVisibility } from \"./use-server-error-visibility.js\";\nimport {\n focusTargetOf,\n normaliseErrorValue,\n snapshotValidity,\n supportsUserInvalid,\n VALID,\n validityElementOf,\n validityEquals,\n} from \"../internal/form/validity.js\";\nimport type {\n FieldErrorValue,\n FieldValidity,\n ValidatableElement,\n} from \"../internal/form/validity.js\";\nimport { arraysEqual } from \"../internal/value-set.js\";\n\nexport type { FieldState } from \"../internal/form/field-context.js\";\nexport type { FieldValidity } from \"../internal/form/validity.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * A custom constraint: receives the field's submitted value (`formData.get(name)` as a string,\n * `\"\"` when absent) and the whole form's `FormData`. Return a message (or several) for an error,\n * `null` / `undefined` / `\"\"` for none.\n */\nexport type FieldValidate = (value: string, formData: FormData) => FieldErrorValue;\n\n/**\n * Props of `Field.Root`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FieldRootProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"className\" | \"style\" | \"children\"\n> {\n /** Form field name: the control's default `name`, the key in `Form.Root errors`, and the entry `validate` reads. */\n name?: string;\n /**\n * Disables the control (native `disabled`) and marks every part `data-disabled`.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Makes the control `required` (native) and marks every part `data-required`.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * A custom constraint, written into the control with `setCustomValidity`. Sync. Receives the\n * field's submitted value (`formData.get(name)` as a string, `\"\"` when absent) and the whole\n * form's `FormData`, so a cross-field rule can read the other field. Runs at mount, on every\n * `input` / `change` in the form (and a FUNSTACK control's value change), on blur, after a\n * reset, on a submission attempt, and in every commit in which this prop changed identity, so\n * a rule that reads outside state (a list that loads, a sibling value in React state) updates\n * on render. An inline function therefore re-runs on every render of the Field; wrap it in\n * `useCallback` to re-run only when its inputs change. Return a string\n * or strings for an error, `null` / `undefined` / `\"\"` for none. Shown when the platform's\n * `:user-invalid` heuristic says so, like a native constraint. Not serialisable: a Field with\n * `validate` is rendered from a client component.\n */\n validate?: FieldValidate;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, FieldState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FieldState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FieldState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, FieldState>;\n}\n\n/** The urgent mirror of browser-owned validity (design 2.4). */\ninterface Mirror {\n readonly userInvalid: boolean;\n readonly validity: FieldValidity;\n readonly messages: readonly string[];\n}\n\nconst NONE: readonly string[] = Object.freeze([]);\nconst INITIAL_MIRROR: Mirror = { userInvalid: false, validity: VALID, messages: NONE };\n\ninterface RefreshOptions {\n /** The user edited the control: the server message is dropped from the slot at once. */\n readonly dismiss?: boolean;\n /** After a form reset: the user-validity flag is clear again. */\n readonly reset?: boolean;\n}\n\nfunction mirrorEquals(a: Mirror, b: Mirror): boolean {\n return (\n a.userInvalid === b.userInvalid &&\n validityEquals(a.validity, b.validity) &&\n arraysEqual(a.messages, b.messages)\n );\n}\n\n/** `FormData` entries as comparable strings; a `File` counts as unchanged (design 3.2 item 2). */\nfunction entryStrings(entries: readonly FormDataEntryValue[]): string[] {\n return entries.map((entry) => (typeof entry === \"string\" ? entry : \"\\u0000file\"));\n}\n\n/**\n * The field: a `div` that owns the ids, the urgent validity mirror, the custom-validity slot\n * (`validate` and the server error), the control registration and the native listeners\n * (design/components/field-form.md 2, 14). `data-pending` is the enclosing form's submission\n * (`useFormStatus`), the one part that folds the form channel into its own state, because a\n * Field has no action of its own.\n *\n * Owned keys (conventions 1.2): `data-invalid`, `data-disabled`, `data-required`, `data-pending`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FieldRoot({\n name,\n disabled = false,\n required = false,\n validate,\n className,\n style,\n children,\n render,\n ...rest\n}: FieldRootProps) {\n const parent = use(FieldContext);\n const form = use(FormContext);\n useDevWarning(\n parent !== null,\n isDev &&\n \"Field.Root: nested inside another Field.Root. A control registers with the nearest Field \" +\n \"only; give each control its own, sibling Field.\",\n );\n useDevWarning(\n validate !== undefined && name === undefined,\n isDev &&\n \"Field.Root: `validate` without `name`. `validate` receives `formData.get(name)`, which is \" +\n 'always \"\" without a name.',\n );\n\n const id = useId();\n const ids = useMemo(\n () => ({\n control: `${id}-control`,\n label: `${id}-label`,\n description: `${id}-description`,\n error: `${id}-error`,\n }),\n [id],\n );\n\n const { pending: formPending } = useFormStatus();\n\n // --- Registration -------------------------------------------------------------------------\n\n const controlRef = useRef<FieldControlRegistration | null>(null);\n const [control, setControl] = useState<FieldControlRegistration | null>(null);\n const warnedTwoControls = useRef(false);\n const registerControl = useCallback((registration: FieldControlRegistration) => {\n const current = controlRef.current;\n if (current !== null && current.element !== registration.element) {\n if (isDev && !warnedTwoControls.current) {\n warnedTwoControls.current = true;\n console.error(\n \"Field.Root: two form controls registered in one Field. The first one is the \" +\n \"Field's control; give each control its own Field.Root.\",\n );\n }\n return () => {};\n }\n controlRef.current = registration;\n setControl(registration);\n return () => {\n if (controlRef.current !== registration) return;\n controlRef.current = null;\n setControl(null);\n };\n }, []);\n\n const errorCount = useRef(0);\n const registerError = useCallback(() => {\n errorCount.current += 1;\n if (isDev && errorCount.current === 2) {\n console.error(\n \"Field.Error: two Field.Error parts in one Field.Root. Render one; its function \" +\n \"`children` receives `validity` for per-constraint wording.\",\n );\n }\n return () => {\n errorCount.current -= 1;\n };\n }, []);\n\n // --- Server errors: shown, dismissed, re-armed, suppressed (design 3.4) -------------------\n\n const errors = form?.errors;\n const serverMessages = useMemo(\n () => normaliseErrorValue(name === undefined ? undefined : errors?.[name]),\n [errors, name],\n );\n const serverKey = serverMessages.join(\"\\n\");\n const { serverShown, dismiss, setSuppressNext } = useServerErrorVisibility(\n formPending,\n serverMessages,\n );\n\n // --- The mirror -----------------------------------------------------------------------------\n\n const [mirror, setMirror] = useState<Mirror>(INITIAL_MIRROR);\n /** The last mirror written: `refresh` compares against it, so an unchanged read renders nothing. */\n const mirrorRef = useRef<Mirror>(INITIAL_MIRROR);\n /** jsdom fallback for `:user-invalid` (design 2.2): `invalid` fired, cleared by a reset. */\n const attempted = useRef(false);\n /** The element the slot was last written on (a group's first member can change). */\n const slotElement = useRef<ValidatableElement | null>(null);\n\n const latest = useLatest({ name, validate, serverMessages, serverShown, formPending, form });\n\n /** Re-reads the slot and the mirror; returns the messages the Field shows for the control. */\n const refresh = useCallback(\n (options: RefreshOptions = {}): readonly string[] => {\n const registration = controlRef.current;\n if (registration === null) return NONE;\n // The element whose validity is real (field-form.md, `validityElement`) and the\n // element whose `:user-invalid` the user's interaction sets; the same for every control but\n // NumberField.\n const surface = validityElementOf(registration.element);\n const el = registration.validityElement?.() ?? surface;\n if (el === null) return NONE;\n const { name, validate, serverMessages, serverShown, formPending, form } = latest.current;\n\n const owner = el.form;\n const formData = owner === null ? new FormData() : new FormData(owner);\n const entry = name === undefined ? null : formData.get(name);\n const value = typeof entry === \"string\" ? entry : \"\";\n const custom = validate === undefined ? NONE : normaliseErrorValue(validate(value, formData));\n\n // The slot (design 2.1): the server message while shown, else `validate`'s.\n const showServer = serverShown && options.dismiss !== true;\n if (slotElement.current !== null && slotElement.current !== el) {\n slotElement.current.setCustomValidity(\"\");\n }\n slotElement.current = el;\n el.setCustomValidity(showServer ? serverMessages.join(\"\\n\") : custom.join(\"\\n\"));\n // Mirror onto the surface so its `:user-invalid` read below sees the new state (the control\n // writes the same derived value after each of its own writes).\n if (\n surface !== null &&\n surface !== el &&\n surface.validationMessage !== el.validationMessage\n ) {\n surface.setCustomValidity(el.validationMessage);\n }\n\n if (options.reset === true) attempted.current = false;\n const userInvalid = supportsUserInvalid()\n ? (surface ?? el).matches(\":user-invalid\")\n : attempted.current && !el.validity.valid;\n const validity = snapshotValidity(el.validity);\n const messages = validity.valid\n ? NONE\n : validity.customError && !showServer && custom.length > 0\n ? custom\n : el.validationMessage === \"\"\n ? NONE\n : [el.validationMessage];\n const next: Mirror = { userInvalid, validity, messages };\n // Only a change schedules a render (a `focusout` with nothing new causes none).\n if (!mirrorEquals(mirrorRef.current, next)) {\n mirrorRef.current = next;\n setMirror(next);\n }\n\n // Stale-value suppression (design 3.2 item 2): while the Form's own submission is in\n // flight, an error is about the value it sent; compare with what the field holds now.\n const submitted = formPending && name !== undefined ? (form?.submittedData() ?? null) : null;\n if (submitted !== null && name !== undefined) {\n setSuppressNext(\n !arraysEqual(entryStrings(formData.getAll(name)), entryStrings(submitted.getAll(name))),\n );\n }\n return showServer ? serverMessages : messages;\n },\n [latest, setSuppressNext],\n );\n\n // The slot follows the server error and `validate` (and is written once the control is known).\n // Keyed on `validate`'s identity (design 2.1): a rule reading outside state updates in the\n // commit that changed it. An inline function re-runs on every render (documented: `useCallback`\n // avoids it); the form's own values are covered by the listeners below.\n useLayoutEffect(() => {\n refresh();\n }, [refresh, control, serverShown, serverKey, validate]);\n\n // Clear the slot when the control goes away (it may be reused outside the Field).\n useLayoutEffect(\n () => () => {\n slotElement.current?.setCustomValidity(\"\");\n slotElement.current = null;\n },\n [],\n );\n\n // The control's own events (capture, so a group's members are seen on its fieldset).\n const element = control?.element ?? null;\n useLayoutEffect(() => {\n if (element === null) return;\n const onEdit = () => {\n dismiss();\n refresh({ dismiss: true });\n };\n const onBlur = () => refresh();\n const onInvalid = (event: Event) => {\n const target = event.target as ValidatableElement;\n // A submission attempt sets user validity before validating; `checkValidity()` and\n // `reportValidity()` do not (design 2.5). The fallback cannot tell them apart.\n const attempt = supportsUserInvalid() ? target.matches(\":user-invalid\") : true;\n if (!supportsUserInvalid()) attempted.current = true;\n if (attempt && errorCount.current > 0) {\n event.preventDefault();\n const messages = refresh();\n collectInvalid(focusTargetOf(element), messages.join(\" \"), target);\n return;\n }\n refresh();\n };\n element.addEventListener(\"input\", onEdit, true);\n element.addEventListener(\"change\", onEdit, true);\n element.addEventListener(\"focusout\", onBlur, true);\n element.addEventListener(\"invalid\", onInvalid, true);\n return () => {\n element.removeEventListener(\"input\", onEdit, true);\n element.removeEventListener(\"change\", onEdit, true);\n element.removeEventListener(\"focusout\", onBlur, true);\n element.removeEventListener(\"invalid\", onInvalid, true);\n };\n }, [element, refresh, dismiss]);\n\n // The form owner's events: another field's edit re-runs `validate` (cross-field rules); a reset\n // clears the user-validity flag, re-read when the controls hold their reset values.\n const ownerRef = useMemo<RefObject<Element | null>>(\n () => ({\n get current() {\n return controlRef.current?.element ?? null;\n },\n set current(_ignored) {},\n }),\n [],\n );\n const onOwnerEdit = (event: Event) => {\n const target = event.target;\n if (target instanceof Node && controlRef.current?.element.contains(target) === true) return;\n refresh();\n };\n useFormOwnerEvent(ownerRef, \"input\", onOwnerEdit);\n useFormOwnerEvent(ownerRef, \"change\", onOwnerEdit);\n // A new submission sends the current values: nothing differs from it yet (a queued second\n // submit arrives while the status stays pending, so the pending edge alone would miss it).\n useFormOwnerEvent(ownerRef, \"submit\", () => {\n setSuppressNext(false);\n });\n useFormOwnerEvent(ownerRef, \"reset\", (event) => {\n queueMicrotask(() => {\n if (event.defaultPrevented) return;\n refresh({ reset: true });\n });\n });\n\n // Registration with the Form, for the first-error focus after a settle (design 3.5) and the\n // refresh of the other Fields on a change no DOM event carried.\n const registerField = form?.registerField;\n const formRegistration = useRef<FormFieldRegistration | null>(null);\n useLayoutEffect(() => {\n if (registerField === undefined) return;\n const registration: FormFieldRegistration = {\n getFocusTarget: () => focusTargetOf(controlRef.current?.element ?? null),\n showsServerError: () => latest.current.serverShown,\n serverMessages: () => latest.current.serverMessages,\n refresh: () => {\n refresh();\n },\n };\n formRegistration.current = registration;\n const unregister = registerField(registration);\n return () => {\n unregister();\n if (formRegistration.current === registration) formRegistration.current = null;\n };\n }, [registerField, latest, refresh]);\n\n const notifyChange = useCallback(\n (edit: boolean) => {\n if (edit) dismiss();\n refresh(edit ? { dismiss: true } : {});\n latest.current.form?.refreshFields(formRegistration.current);\n },\n [refresh, latest, dismiss],\n );\n\n // Development: a Field around something that is not a form control (Toggle, Menu, ...).\n useEffect(() => {\n if (!isDev || controlRef.current !== null) return;\n console.error(\n \"Field.Root: no form control registered. Render a Field.Control or a FUNSTACK form \" +\n \"control (Checkbox, Switch, RadioGroup, CheckboxGroup, Select, Combobox, Slider, \" +\n \"NumberField) inside it.\",\n );\n }, []);\n\n const invalid = mirror.userInvalid || serverShown;\n const messages = serverShown ? serverMessages : mirror.userInvalid ? mirror.messages : NONE;\n const validity = mirror.validity;\n const stateDisabled = disabled || (control?.disabled ?? false);\n const stateRequired = required || (control?.required ?? false);\n // Memoised: the context value (and so every part) changes only with the state.\n const memoState = useMemo<FieldState>(\n () => ({\n invalid,\n messages,\n validity,\n disabled: stateDisabled,\n required: stateRequired,\n pending: formPending,\n }),\n [invalid, messages, validity, stateDisabled, stateRequired, formPending],\n );\n\n const labelable = control?.labelable ?? true;\n const context = useMemo<FieldContextValue>(\n () => ({\n ids,\n name,\n disabled,\n required,\n state: memoState,\n labelable,\n registerControl,\n registerError,\n notifyChange,\n }),\n [\n ids,\n name,\n disabled,\n required,\n memoState,\n labelable,\n registerControl,\n registerError,\n notifyChange,\n ],\n );\n\n const element$ = useRender<ComponentPropsWithRef<\"div\">, FieldState>({\n defaultElement: \"div\",\n render,\n state: memoState,\n className,\n style,\n children,\n props: rest,\n libraryProps: fieldDataAttributes(memoState),\n });\n\n return <FieldContext value={context}>{element$}</FieldContext>;\n}\n\nFieldRoot.displayName = \"FieldRoot\";\n"],"mappings":";;;;;;;;;;;;;;AA8CA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA+DvC,MAAM,OAA0B,OAAO,OAAO,CAAC,CAAC;AAChD,MAAM,iBAAyB;CAAE,aAAa;CAAO,UAAU;CAAO,UAAU;AAAK;AASrF,SAAS,aAAa,GAAW,GAAoB;CACnD,OACE,EAAE,gBAAgB,EAAE,eACpB,eAAe,EAAE,UAAU,EAAE,QAAQ,KACrC,YAAY,EAAE,UAAU,EAAE,QAAQ;AAEtC;;AAGA,SAAS,aAAa,SAAkD;CACtE,OAAO,QAAQ,KAAK,UAAW,OAAO,UAAU,WAAW,QAAQ,QAAa;AAClF;;;;;;;;;;;;AAaA,SAAgB,UAAU,EACxB,MACA,WAAW,OACX,WAAW,OACX,UACA,WACA,OACA,UACA,QACA,GAAG,QACc;CACjB,MAAM,SAAS,IAAI,YAAY;CAC/B,MAAM,OAAO,IAAI,WAAW;CAC5B,cACE,WAAW,MACX,SACE,0IAEJ;CACA,cACE,aAAa,KAAA,KAAa,SAAS,KAAA,GACnC,SACE,uHAEJ;CAEA,MAAM,KAAK,MAAM;CACjB,MAAM,MAAM,eACH;EACL,SAAS,GAAG,GAAG;EACf,OAAO,GAAG,GAAG;EACb,aAAa,GAAG,GAAG;EACnB,OAAO,GAAG,GAAG;CACf,IACA,CAAC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;EACd,IAAI,CAAC,SAAS,WAAW,YAAY,MAAM;EAC3C,QAAQ,MACN,2LAGF;CACF,GAAG,CAAC,CAAC;CAEL,MAAM,UAAU,OAAO,eAAe;CACtC,MAAM,WAAW,cAAc,iBAAiB,OAAO,cAAc,OAAO,WAAW;CACvF,MAAM,WAAW,OAAO;CACxB,MAAM,gBAAgB,aAAa,SAAS,YAAY;CACxD,MAAM,gBAAgB,aAAa,SAAS,YAAY;CAExD,MAAM,YAAY,eACT;EACL;EACA;EACA;EACA,UAAU;EACV,UAAU;EACV,SAAS;CACX,IACA;EAAC;EAAS;EAAU;EAAU;EAAe;EAAe;CAAW,CACzE;CAEA,MAAM,YAAY,SAAS,aAAa;CACxC,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA;EACA,OAAO;EACP;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,WAAW,UAAoD;EACnE,gBAAgB;EAChB;EACA,OAAO;EACP;EACA;EACA;EACA,OAAO;EACP,cAAc,oBAAoB,SAAS;CAC7C,CAAC;CAED,OAAO,oBAAC,cAAD;EAAc,OAAO;EAAU,UAAA;CAAuB,CAAA;AAC/D;AAEA,UAAU,cAAc"}
|
package/dist/field/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { FieldValidity } from "../internal/validity.mjs";
|
|
2
|
-
import { FieldState } from "../internal/field-context.mjs";
|
|
1
|
+
import { FieldValidity } from "../internal/form/validity.mjs";
|
|
2
|
+
import { FieldState } from "../internal/form/field-context.mjs";
|
|
3
3
|
import { FieldControl, FieldControlProps } from "./field-control.mjs";
|
|
4
4
|
import { FieldDescription, FieldDescriptionProps } from "./field-description.mjs";
|
|
5
5
|
import { FieldError, FieldErrorProps } from "./field-error.mjs";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RenderProp, StateValue } from "../internal/types.mjs";
|
|
2
|
-
import { FieldErrorValue, FormErrors } from "../internal/validity.mjs";
|
|
2
|
+
import { FieldErrorValue, FormErrors } from "../internal/form/validity.mjs";
|
|
3
3
|
import { CSSProperties, ComponentPropsWithRef, ReactNode } from "react";
|
|
4
4
|
//#region src/form/form-root.d.ts
|
|
5
5
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-root.d.mts","names":[],"sources":["../../src/form/form-root.tsx"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"form-root.d.mts","names":[],"sources":["../../src/form/form-root.tsx"],"mappings":";;;;;;;;iBA0BiB;;WAEN;;;;;;;iBAQM,sBAAsB,KACrC;;;;;;;;EAUA,oBAAoB,UAAU;;;;;;;EAO9B,SAAS;;;;;;;;EAQT;;EAEA,SAAS;;EAET,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,+BAA+B;;;;;;;;;;;;;;;;;wBAwBrC,WACd,QACA,QACA,WACA,QACA,WACA,OACA,UACA,WACG,QACF,gCAAa,IAAA;yBAVA"}
|
package/dist/form/form-root.mjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { dataAttr } from "../internal/data-attr.mjs";
|
|
3
3
|
import { resolveStateValue } from "../internal/render-element.mjs";
|
|
4
|
+
import { reportDropped } from "../internal/action/report-dropped.mjs";
|
|
5
|
+
import { useConnected } from "../internal/action/use-connected.mjs";
|
|
4
6
|
import { useRender } from "../internal/use-render.mjs";
|
|
5
7
|
import { useLatest } from "../internal/use-latest.mjs";
|
|
6
8
|
import { sortByDocumentOrder } from "../internal/dom-order.mjs";
|
|
7
9
|
import { useElementCheck } from "../internal/use-element-check.mjs";
|
|
8
|
-
import { FormContext } from "../internal/field-context.mjs";
|
|
9
|
-
import { FormStatusWatcher } from "../internal/form-status-watcher.mjs";
|
|
10
|
-
import { hasAnyError } from "../internal/validity.mjs";
|
|
10
|
+
import { FormContext } from "../internal/form/field-context.mjs";
|
|
11
|
+
import { FormStatusWatcher } from "../internal/form/form-status-watcher.mjs";
|
|
12
|
+
import { hasAnyError } from "../internal/form/validity.mjs";
|
|
11
13
|
import { announce } from "../internal/announce.mjs";
|
|
12
14
|
import { useCallback, useMemo, useRef, useState, useTransition } from "react";
|
|
13
15
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
@@ -32,6 +34,8 @@ function FormRoot({ action, errors, autoReset = true, method, className, style,
|
|
|
32
34
|
const [isPending, startTransition] = useTransition();
|
|
33
35
|
const [statusPending, setStatusPending] = useState(false);
|
|
34
36
|
const pending = isPending || statusPending;
|
|
37
|
+
const latestRun = useRef(0);
|
|
38
|
+
const connected = useConnected();
|
|
35
39
|
const formRef = useRef(null);
|
|
36
40
|
const submission = useRef(null);
|
|
37
41
|
const fields = useRef(/* @__PURE__ */ new Set());
|
|
@@ -71,8 +75,14 @@ function FormRoot({ action, errors, autoReset = true, method, className, style,
|
|
|
71
75
|
intercepted: true,
|
|
72
76
|
formData
|
|
73
77
|
};
|
|
78
|
+
const id = ++latestRun.current;
|
|
74
79
|
startTransition(async () => {
|
|
75
|
-
|
|
80
|
+
try {
|
|
81
|
+
await action(formData);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (id === latestRun.current && connected.current) throw error;
|
|
84
|
+
reportDropped(error);
|
|
85
|
+
}
|
|
76
86
|
});
|
|
77
87
|
};
|
|
78
88
|
const registerField = useCallback((registration) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-root.mjs","names":[],"sources":["../../src/form/form-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useMemo, useRef, useState, useTransition } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, FormEvent, ReactNode } from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { sortByDocumentOrder } from \"../internal/dom-order.js\";\nimport { FormContext } from \"../internal/field-context.js\";\nimport type { FormContextValue, FormFieldRegistration } from \"../internal/field-context.js\";\nimport { announce } from \"../internal/announce.js\";\nimport { FormStatusWatcher } from \"../internal/form-status-watcher.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport { hasAnyError } from \"../internal/validity.js\";\nimport type { FormErrors } from \"../internal/validity.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport type { FieldErrorValue, FormErrors } from \"../internal/validity.js\";\n\n/**\n * State of `Form.Root`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface FormRootState {\n /** A submission is in flight: the Form's own transition, or the form's status (`useFormStatus`), including the Suspense wait of the result. */\n readonly pending: boolean;\n}\n\n/**\n * Props of `Form.Root`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FormRootProps extends Omit<\n ComponentPropsWithRef<\"form\">,\n \"onSubmit\" | \"method\" | \"action\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * React form action (`(formData) => unknown`: a Server Function, a `useActionState` dispatch,\n * or a client function), rendered on the form unwrapped so React's progressive enhancement is\n * kept, and run by the Form inside its own transition after hydration (no automatic reset; see\n * `autoReset`). A string is a navigating form. A submitter with its own `formAction` is left to\n * React (automatic reset applies to it).\n */\n action?: string | ((formData: FormData) => unknown);\n /**\n * Field errors keyed by field `name` (usually `state.errors` from `useActionState`). Each\n * `Field.Root` with that name shows its entry, writes it into the control's custom validity,\n * and clears it on the user's next edit; the next settled submission shows the new entries.\n * Errors present at mount are shown without moving focus.\n */\n errors?: FormErrors;\n /**\n * Reset the form (`form.reset()`) when a submission the Form ran settles with no non-empty\n * entry in `errors`. A submission that reports errors never resets, so the\n * user's input, `:user-invalid` and custom validity stay. `false`: never reset.\n *\n * @defaultValue `true`\n */\n autoReset?: boolean;\n /** Only with a string `action`. Owned otherwise (React's own with a function action). */\n method?: ComponentPropsWithRef<\"form\">[\"method\"];\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, FormRootState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FormRootState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FormRootState>;\n /** Must render a `<form>`. */\n render?: RenderProp<ComponentPropsWithRef<\"form\">, FormRootState>;\n}\n\ninterface Submission {\n /** The Form ran the action itself (`onSubmit` + its own transition). */\n readonly intercepted: boolean;\n readonly formData: FormData | null;\n}\n\n/**\n * A `<form>` that runs its function `action` itself after hydration (design/components/field-form.md\n * 3): `onSubmit` cancels the native submission, so react-dom neither runs the action nor schedules\n * its automatic reset, and the Form awaits `action(formData)` inside its own transition, which\n * still starts the form's status (`useFormStatus`). The action stays rendered unwrapped on the\n * element, so a Server Function posts before hydration.\n *\n * When a submission settles, the Form focuses the first Field that shows a server error (from\n * `errors`), or, when `errors` has no entry and `autoReset` is on, resets the form.\n *\n * Owned keys (conventions 1.2): `action`, `method` (except with a string `action`), `onSubmit`,\n * `data-pending`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FormRoot({\n action,\n errors,\n autoReset = true,\n method,\n className,\n style,\n children,\n render,\n ...rest\n}: FormRootProps) {\n const [isPending, startTransition] = useTransition();\n const [statusPending, setStatusPending] = useState(false);\n const pending = isPending || statusPending;\n\n const formRef = useRef<HTMLFormElement | null>(null);\n const submission = useRef<Submission | null>(null);\n const fields = useRef(new Set<FormFieldRegistration>());\n const latest = useLatest({ errors, autoReset });\n const isFunction = typeof action === \"function\";\n\n // A native capture listener sees every submission, React's path included (a submitter with its\n // own `formAction`), before React's `onSubmit` runs and marks it intercepted.\n const checkElement = useElementCheck<HTMLFormElement>(\n isDev &&\n ((form) =>\n form.tagName !== \"FORM\"\n ? `Form.Root: expected to render a <form> element but got <${form.tagName.toLowerCase()}>.`\n : null),\n );\n const libraryRef = useCallback(\n (form: HTMLFormElement) => {\n formRef.current = form;\n checkElement?.(form);\n const onSubmit = (event: Event) => {\n if (event.target !== form) return;\n submission.current = { intercepted: false, formData: null };\n };\n form.addEventListener(\"submit\", onSubmit, true);\n return () => {\n form.removeEventListener(\"submit\", onSubmit, true);\n if (formRef.current === form) formRef.current = null;\n };\n },\n [checkElement],\n );\n\n const onSubmit = (event: FormEvent<HTMLFormElement>) => {\n if (typeof action !== \"function\") return; // a navigating form: the browser's\n // A `render` element's own `onSubmit` (merged, it runs first) vetoed the submission\n // (conventions: a `preventDefault()` in the consumer's handler cancels the library's work).\n if (event.defaultPrevented) {\n submission.current = null;\n return;\n }\n const native = event.nativeEvent as SubmitEvent;\n const submitter = native.submitter;\n // A per-button action: React's own path (and its automatic reset).\n if (submitter?.hasAttribute(\"formaction\") === true) return;\n // react-dom now skips its action run and its reset, and still starts the form's status.\n event.preventDefault();\n const formData = new FormData(event.currentTarget, submitter);\n submission.current = { intercepted: true, formData };\n startTransition(async () => {\n await action(formData);\n });\n };\n\n const registerField = useCallback((registration: FormFieldRegistration) => {\n fields.current.add(registration);\n return () => {\n fields.current.delete(registration);\n };\n }, []);\n\n // The settle (design 3.2): the form's status went `true → false`. The Fields rendered the\n // result's errors in that commit; this effect runs after it.\n const onSettled = useCallback(() => {\n const settled = submission.current;\n submission.current = null;\n const form = formRef.current;\n if (form === null) return;\n const shown = [...fields.current]\n .filter((field) => field.showsServerError())\n .map((field) => ({ field, target: field.getFocusTarget() }))\n .filter(\n (entry): entry is { field: FormFieldRegistration; target: HTMLElement } =>\n entry.target !== null && entry.target.isConnected,\n );\n if (shown.length > 0) {\n const first = sortByDocumentOrder(shown, (entry) => entry.target)[0]!;\n // Focus already there (the user pressed Enter in that field): `focus()` does nothing and\n // nothing reads the new description, so the message is announced instead (design 5.3).\n if (first.target.ownerDocument.activeElement === first.target) {\n announce(first.target, first.field.serverMessages().join(\" \"));\n } else {\n first.target.focus();\n }\n return;\n }\n const { errors, autoReset } = latest.current;\n if (autoReset && settled?.intercepted === true && !hasAnyError(errors)) form.reset();\n }, [latest]);\n\n const submittedData = useCallback(() => {\n const current = submission.current;\n return current?.intercepted === true ? current.formData : null;\n }, []);\n\n const refreshFields = useCallback((source: FormFieldRegistration | null) => {\n for (const field of fields.current) if (field !== source) field.refresh();\n }, []);\n\n const context = useMemo<FormContextValue>(\n () => ({ errors, registerField, submittedData, refreshFields }),\n [errors, registerField, submittedData, refreshFields],\n );\n\n const state: FormRootState = { pending };\n\n const element = useRender<ComponentPropsWithRef<\"form\">, FormRootState>({\n defaultElement: \"form\",\n render,\n state,\n className,\n style,\n children: (s) => (\n <>\n {resolveStateValue(children, s)}\n {isFunction && (\n <FormStatusWatcher onPendingChange={setStatusPending} onSettled={onSettled} />\n )}\n </>\n ),\n props: rest,\n libraryProps: {\n method: typeof action === \"string\" ? method : undefined,\n // React's own type wants `void | Promise<void>`; the library's actions return `unknown`\n // (conventions 2.2) and React ignores the result.\n action: action as ComponentPropsWithRef<\"form\">[\"action\"],\n onSubmit: isFunction ? onSubmit : undefined,\n \"data-pending\": dataAttr(pending),\n },\n ref: libraryRef,\n });\n\n return <FormContext value={context}>{element}</FormContext>;\n}\n\nFormRoot.displayName = \"FormRoot\";\n"],"mappings":";;;;;;;;;;;;;;AAgBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;;AA8EvC,SAAgB,SAAS,EACvB,QACA,QACA,YAAY,MACZ,QACA,WACA,OACA,UACA,QACA,GAAG,QACa;CAChB,MAAM,CAAC,WAAW,mBAAmB,cAAc;CACnD,MAAM,CAAC,eAAe,oBAAoB,SAAS,KAAK;CACxD,MAAM,UAAU,aAAa;CAE7B,MAAM,UAAU,OAA+B,IAAI;CACnD,MAAM,aAAa,OAA0B,IAAI;CACjD,MAAM,SAAS,uBAAO,IAAI,IAA2B,CAAC;CACtD,MAAM,SAAS,UAAU;EAAE;EAAQ;CAAU,CAAC;CAC9C,MAAM,aAAa,OAAO,WAAW;CAIrC,MAAM,eAAe,gBACnB,WACI,SACA,KAAK,YAAY,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":3,"file":"form-root.mjs","names":[],"sources":["../../src/form/form-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useMemo, useRef, useState, useTransition } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, FormEvent, ReactNode } from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { sortByDocumentOrder } from \"../internal/dom-order.js\";\nimport { FormContext } from \"../internal/form/field-context.js\";\nimport type { FormContextValue, FormFieldRegistration } from \"../internal/form/field-context.js\";\nimport { announce } from \"../internal/announce.js\";\nimport { FormStatusWatcher } from \"../internal/form/form-status-watcher.js\";\nimport { reportDropped } from \"../internal/action/report-dropped.js\";\nimport { useConnected } from \"../internal/action/use-connected.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport { hasAnyError } from \"../internal/form/validity.js\";\nimport type { FormErrors } from \"../internal/form/validity.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport type { FieldErrorValue, FormErrors } from \"../internal/form/validity.js\";\n\n/**\n * State of `Form.Root`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface FormRootState {\n /** A submission is in flight: the Form's own transition, or the form's status (`useFormStatus`), including the Suspense wait of the result. */\n readonly pending: boolean;\n}\n\n/**\n * Props of `Form.Root`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FormRootProps extends Omit<\n ComponentPropsWithRef<\"form\">,\n \"onSubmit\" | \"method\" | \"action\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * React form action (`(formData) => unknown`: a Server Function, a `useActionState` dispatch,\n * or a client function), rendered on the form unwrapped so React's progressive enhancement is\n * kept, and run by the Form inside its own transition after hydration (no automatic reset; see\n * `autoReset`). A string is a navigating form. A submitter with its own `formAction` is left to\n * React (automatic reset applies to it).\n */\n action?: string | ((formData: FormData) => unknown);\n /**\n * Field errors keyed by field `name` (usually `state.errors` from `useActionState`). Each\n * `Field.Root` with that name shows its entry, writes it into the control's custom validity,\n * and clears it on the user's next edit; the next settled submission shows the new entries.\n * Errors present at mount are shown without moving focus.\n */\n errors?: FormErrors;\n /**\n * Reset the form (`form.reset()`) when a submission the Form ran settles with no non-empty\n * entry in `errors`. A submission that reports errors never resets, so the\n * user's input, `:user-invalid` and custom validity stay. `false`: never reset.\n *\n * @defaultValue `true`\n */\n autoReset?: boolean;\n /** Only with a string `action`. Owned otherwise (React's own with a function action). */\n method?: ComponentPropsWithRef<\"form\">[\"method\"];\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, FormRootState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FormRootState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FormRootState>;\n /** Must render a `<form>`. */\n render?: RenderProp<ComponentPropsWithRef<\"form\">, FormRootState>;\n}\n\ninterface Submission {\n /** The Form ran the action itself (`onSubmit` + its own transition). */\n readonly intercepted: boolean;\n readonly formData: FormData | null;\n}\n\n/**\n * A `<form>` that runs its function `action` itself after hydration (design/components/field-form.md\n * 3): `onSubmit` cancels the native submission, so react-dom neither runs the action nor schedules\n * its automatic reset, and the Form awaits `action(formData)` inside its own transition, which\n * still starts the form's status (`useFormStatus`). The action stays rendered unwrapped on the\n * element, so a Server Function posts before hydration.\n *\n * When a submission settles, the Form focuses the first Field that shows a server error (from\n * `errors`), or, when `errors` has no entry and `autoReset` is on, resets the form.\n *\n * Owned keys (conventions 1.2): `action`, `method` (except with a string `action`), `onSubmit`,\n * `data-pending`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FormRoot({\n action,\n errors,\n autoReset = true,\n method,\n className,\n style,\n children,\n render,\n ...rest\n}: FormRootProps) {\n const [isPending, startTransition] = useTransition();\n const [statusPending, setStatusPending] = useState(false);\n const pending = isPending || statusPending;\n // The newest submission the Form ran, and whether the Form is connected (use-connected.ts).\n const latestRun = useRef(0);\n const connected = useConnected();\n\n const formRef = useRef<HTMLFormElement | null>(null);\n const submission = useRef<Submission | null>(null);\n const fields = useRef(new Set<FormFieldRegistration>());\n const latest = useLatest({ errors, autoReset });\n const isFunction = typeof action === \"function\";\n\n // A native capture listener sees every submission, React's path included (a submitter with its\n // own `formAction`), before React's `onSubmit` runs and marks it intercepted.\n const checkElement = useElementCheck<HTMLFormElement>(\n isDev &&\n ((form) =>\n form.tagName !== \"FORM\"\n ? `Form.Root: expected to render a <form> element but got <${form.tagName.toLowerCase()}>.`\n : null),\n );\n const libraryRef = useCallback(\n (form: HTMLFormElement) => {\n formRef.current = form;\n checkElement?.(form);\n const onSubmit = (event: Event) => {\n if (event.target !== form) return;\n submission.current = { intercepted: false, formData: null };\n };\n form.addEventListener(\"submit\", onSubmit, true);\n return () => {\n form.removeEventListener(\"submit\", onSubmit, true);\n if (formRef.current === form) formRef.current = null;\n };\n },\n [checkElement],\n );\n\n const onSubmit = (event: FormEvent<HTMLFormElement>) => {\n if (typeof action !== \"function\") return; // a navigating form: the browser's\n // A `render` element's own `onSubmit` (merged, it runs first) vetoed the submission\n // (conventions: a `preventDefault()` in the consumer's handler cancels the library's work).\n if (event.defaultPrevented) {\n submission.current = null;\n return;\n }\n const native = event.nativeEvent as SubmitEvent;\n const submitter = native.submitter;\n // A per-button action: React's own path (and its automatic reset).\n if (submitter?.hasAttribute(\"formaction\") === true) return;\n // react-dom now skips its action run and its reset, and still starts the form's status.\n event.preventDefault();\n const formData = new FormData(event.currentTarget, submitter);\n submission.current = { intercepted: true, formData };\n const id = ++latestRun.current;\n startTransition(async () => {\n try {\n await action(formData);\n } catch (error) {\n // The latest submission's rejection takes React's route to the boundary while the Form\n // is there to render it; a superseded one's, or one after the Form unmounted or was\n // hidden, React would drop: reported instead (conventions 2.4, `useActionTrigger`).\n if (id === latestRun.current && connected.current) throw error;\n reportDropped(error);\n }\n });\n };\n\n const registerField = useCallback((registration: FormFieldRegistration) => {\n fields.current.add(registration);\n return () => {\n fields.current.delete(registration);\n };\n }, []);\n\n // The settle (design 3.2): the form's status went `true → false`. The Fields rendered the\n // result's errors in that commit; this effect runs after it.\n const onSettled = useCallback(() => {\n const settled = submission.current;\n submission.current = null;\n const form = formRef.current;\n if (form === null) return;\n const shown = [...fields.current]\n .filter((field) => field.showsServerError())\n .map((field) => ({ field, target: field.getFocusTarget() }))\n .filter(\n (entry): entry is { field: FormFieldRegistration; target: HTMLElement } =>\n entry.target !== null && entry.target.isConnected,\n );\n if (shown.length > 0) {\n const first = sortByDocumentOrder(shown, (entry) => entry.target)[0]!;\n // Focus already there (the user pressed Enter in that field): `focus()` does nothing and\n // nothing reads the new description, so the message is announced instead (design 5.3).\n if (first.target.ownerDocument.activeElement === first.target) {\n announce(first.target, first.field.serverMessages().join(\" \"));\n } else {\n first.target.focus();\n }\n return;\n }\n const { errors, autoReset } = latest.current;\n if (autoReset && settled?.intercepted === true && !hasAnyError(errors)) form.reset();\n }, [latest]);\n\n const submittedData = useCallback(() => {\n const current = submission.current;\n return current?.intercepted === true ? current.formData : null;\n }, []);\n\n const refreshFields = useCallback((source: FormFieldRegistration | null) => {\n for (const field of fields.current) if (field !== source) field.refresh();\n }, []);\n\n const context = useMemo<FormContextValue>(\n () => ({ errors, registerField, submittedData, refreshFields }),\n [errors, registerField, submittedData, refreshFields],\n );\n\n const state: FormRootState = { pending };\n\n const element = useRender<ComponentPropsWithRef<\"form\">, FormRootState>({\n defaultElement: \"form\",\n render,\n state,\n className,\n style,\n children: (s) => (\n <>\n {resolveStateValue(children, s)}\n {isFunction && (\n <FormStatusWatcher onPendingChange={setStatusPending} onSettled={onSettled} />\n )}\n </>\n ),\n props: rest,\n libraryProps: {\n method: typeof action === \"string\" ? method : undefined,\n // React's own type wants `void | Promise<void>`; the library's actions return `unknown`\n // (conventions 2.2) and React ignores the result.\n action: action as ComponentPropsWithRef<\"form\">[\"action\"],\n onSubmit: isFunction ? onSubmit : undefined,\n \"data-pending\": dataAttr(pending),\n },\n ref: libraryRef,\n });\n\n return <FormContext value={context}>{element}</FormContext>;\n}\n\nFormRoot.displayName = \"FormRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;;AA8EvC,SAAgB,SAAS,EACvB,QACA,QACA,YAAY,MACZ,QACA,WACA,OACA,UACA,QACA,GAAG,QACa;CAChB,MAAM,CAAC,WAAW,mBAAmB,cAAc;CACnD,MAAM,CAAC,eAAe,oBAAoB,SAAS,KAAK;CACxD,MAAM,UAAU,aAAa;CAE7B,MAAM,YAAY,OAAO,CAAC;CAC1B,MAAM,YAAY,aAAa;CAE/B,MAAM,UAAU,OAA+B,IAAI;CACnD,MAAM,aAAa,OAA0B,IAAI;CACjD,MAAM,SAAS,uBAAO,IAAI,IAA2B,CAAC;CACtD,MAAM,SAAS,UAAU;EAAE;EAAQ;CAAU,CAAC;CAC9C,MAAM,aAAa,OAAO,WAAW;CAIrC,MAAM,eAAe,gBACnB,WACI,SACA,KAAK,YAAY,SACb,2DAA2D,KAAK,QAAQ,YAAY,EAAE,MACtF,KACV;CACA,MAAM,aAAa,aAChB,SAA0B;EACzB,QAAQ,UAAU;EAClB,eAAe,IAAI;EACnB,MAAM,YAAY,UAAiB;GACjC,IAAI,MAAM,WAAW,MAAM;GAC3B,WAAW,UAAU;IAAE,aAAa;IAAO,UAAU;GAAK;EAC5D;EACA,KAAK,iBAAiB,UAAU,UAAU,IAAI;EAC9C,aAAa;GACX,KAAK,oBAAoB,UAAU,UAAU,IAAI;GACjD,IAAI,QAAQ,YAAY,MAAM,QAAQ,UAAU;EAClD;CACF,GACA,CAAC,YAAY,CACf;CAEA,MAAM,YAAY,UAAsC;EACtD,IAAI,OAAO,WAAW,YAAY;EAGlC,IAAI,MAAM,kBAAkB;GAC1B,WAAW,UAAU;GACrB;EACF;EAEA,MAAM,YADS,MAAM,YACI;EAEzB,IAAI,WAAW,aAAa,YAA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,WAAW;EAC3B,OAAO,SAAS,gBAAgB,OAAO,QAAQ,WAAW;CAC5D,GAAG,CAAC,CAAC;CAEL,MAAM,gBAAgB,aAAa,WAAyC;EAC1E,KAAK,MAAM,SAAS,OAAO,SAAS,IAAI,UAAU,QAAQ,MAAM,QAAQ;CAC1E,GAAG,CAAC,CAAC;CAEL,MAAM,UAAU,eACP;EAAE;EAAQ;EAAe;EAAe;CAAc,IAC7D;EAAC;EAAQ;EAAe;EAAe;CAAa,CACtD;CAIA,MAAM,UAAU,UAAwD;EACtE,gBAAgB;EAChB;EACA,OAAA,EAL6B,QAKzB;EACJ;EACA;EACA,WAAW,MACT,qBAAA,UAAA,EAAA,UAAA,CACG,kBAAkB,UAAU,CAAC,GAC7B,cACC,oBAAC,mBAAD;GAAmB,iBAAiB;GAA6B;EAAY,CAAA,CAE/E,EAAA,CAAA;EAEJ,OAAO;EACP,cAAc;GACZ,QAAQ,OAAO,WAAW,WAAW,SAAS,KAAA;GAGtC;GACR,UAAU,aAAa,WAAW,KAAA;GAClC,gBAAgB,SAAS,OAAO;EAClC;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,aAAD;EAAa,OAAO;EAAU,UAAA;CAAqB,CAAA;AAC5D;AAEA,SAAS,cAAc"}
|
|
@@ -18,8 +18,11 @@ export interface FormSubmitState {
|
|
|
18
18
|
*/
|
|
19
19
|
export interface FormSubmitProps extends Omit<ComponentPropsWithRef<"button">, "type" | "className" | "style" | "children"> {
|
|
20
20
|
/**
|
|
21
|
-
* Native `disabled
|
|
22
|
-
*
|
|
21
|
+
* Native `disabled` (owned; a `render` element cannot re-enable it) and `data-disabled`. Never
|
|
22
|
+
* set by the library (conventions 3.6). Native also with a component `render`, assumed to
|
|
23
|
+
* render a submit button: only native `disabled` stops a submitter before hydration. With a
|
|
24
|
+
* host element of another tag (`render={<a />}`), `aria-disabled="true"` instead and the click
|
|
25
|
+
* is cancelled.
|
|
23
26
|
*
|
|
24
27
|
* @defaultValue `false`
|
|
25
28
|
*/
|
|
@@ -39,7 +42,8 @@ export interface FormSubmitProps extends Omit<ComponentPropsWithRef<"button">, "
|
|
|
39
42
|
* (`Form.Root`, `Dialog.Form`, a plain `<form action>`). Never disabled while pending: block
|
|
40
43
|
* repeat clicks with CSS on `[data-pending]` if you need to.
|
|
41
44
|
*
|
|
42
|
-
* Owned keys (conventions 1.2): `type` (on a `<button>`), `disabled`, `
|
|
45
|
+
* Owned keys (conventions 1.2): `type` (on a `<button>`), `disabled`, `aria-disabled` (a host
|
|
46
|
+
* element other than `<button>` / `<input>`), `onClick` (while disabled), `data-pending`,
|
|
43
47
|
* `data-disabled`.
|
|
44
48
|
*
|
|
45
49
|
* @see https://ui.funstack.work/components/field
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-submit.d.mts","names":[],"sources":["../../src/form/form-submit.tsx"],"mappings":";;;;;;;iBAciB;;WAEN;;WAEA;;;;;;;iBAQM,wBAAwB,KACvC
|
|
1
|
+
{"version":3,"file":"form-submit.d.mts","names":[],"sources":["../../src/form/form-submit.tsx"],"mappings":";;;;;;;iBAciB;;WAEN;;WAEA;;;;;;;iBAQM,wBAAwB,KACvC;;;;;;;;;;EAYA;;EAEA,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,iCAAiC;;;;;;;;;;;;;;wBAevC,aACd,UACA,WACA,OACA,UACA,WACG,QACF,kBAAe;yBAPF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { dataAttr } from "../internal/data-attr.mjs";
|
|
3
|
-
import { rendersButton } from "../internal/render-element.mjs";
|
|
3
|
+
import { cancelClick, disabledButton, rendersButton } from "../internal/render-element.mjs";
|
|
4
4
|
import { useRender } from "../internal/use-render.mjs";
|
|
5
5
|
import { useElementCheck } from "../internal/use-element-check.mjs";
|
|
6
6
|
import { useFormStatus } from "react-dom";
|
|
@@ -12,7 +12,8 @@ const isDev = process.env.NODE_ENV !== "production";
|
|
|
12
12
|
* (`Form.Root`, `Dialog.Form`, a plain `<form action>`). Never disabled while pending: block
|
|
13
13
|
* repeat clicks with CSS on `[data-pending]` if you need to.
|
|
14
14
|
*
|
|
15
|
-
* Owned keys (conventions 1.2): `type` (on a `<button>`), `disabled`, `
|
|
15
|
+
* Owned keys (conventions 1.2): `type` (on a `<button>`), `disabled`, `aria-disabled` (a host
|
|
16
|
+
* element other than `<button>` / `<input>`), `onClick` (while disabled), `data-pending`,
|
|
16
17
|
* `data-disabled`.
|
|
17
18
|
*
|
|
18
19
|
* @see https://ui.funstack.work/components/field
|
|
@@ -22,20 +23,23 @@ function FormSubmit({ disabled = false, className, style, children, render, ...r
|
|
|
22
23
|
const ref = useElementCheck(isDev && ((el) => {
|
|
23
24
|
return el.tagName === "BUTTON" || el.tagName === "INPUT" && ["submit", "image"].includes(el.type) ? null : `Form.Submit: expected to render a <button> (or <input type="submit">) but got <${el.tagName.toLowerCase()}>. Only a submit button submits the form natively.`;
|
|
24
25
|
}));
|
|
26
|
+
const state = {
|
|
27
|
+
pending,
|
|
28
|
+
disabled
|
|
29
|
+
};
|
|
30
|
+
const disabledProps = disabledButton(render, disabled, { handlesClick: false }).props;
|
|
25
31
|
return useRender({
|
|
26
32
|
defaultElement: "button",
|
|
27
33
|
render,
|
|
28
|
-
state
|
|
29
|
-
pending,
|
|
30
|
-
disabled
|
|
31
|
-
},
|
|
34
|
+
state,
|
|
32
35
|
className,
|
|
33
36
|
style,
|
|
34
37
|
children,
|
|
35
38
|
props: rest,
|
|
36
39
|
libraryProps: {
|
|
37
40
|
...rendersButton(render) && { type: "submit" },
|
|
38
|
-
|
|
41
|
+
...disabledProps,
|
|
42
|
+
...disabled && { onClick: cancelClick },
|
|
39
43
|
"data-pending": dataAttr(pending),
|
|
40
44
|
"data-disabled": dataAttr(disabled)
|
|
41
45
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"form-submit.mjs","names":[],"sources":["../../src/form/form-submit.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { rendersButton, useRender } from \"../internal/use-render.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * State of `Form.Submit`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface FormSubmitState {\n /** The enclosing form's submission is in flight (`useFormStatus().pending`). */\n readonly pending: boolean;\n /** The `disabled` prop (never set by the library while pending). */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `Form.Submit`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FormSubmitProps extends Omit<\n ComponentPropsWithRef<\"button\">,\n \"type\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * Native `disabled
|
|
1
|
+
{"version":3,"file":"form-submit.mjs","names":[],"sources":["../../src/form/form-submit.tsx"],"sourcesContent":["\"use client\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { useFormStatus } from \"react-dom\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { cancelClick, disabledButton, rendersButton, useRender } from \"../internal/use-render.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * State of `Form.Submit`, passed to the function forms of `className`, `style`, `children` and\n * `render`.\n */\nexport interface FormSubmitState {\n /** The enclosing form's submission is in flight (`useFormStatus().pending`). */\n readonly pending: boolean;\n /** The `disabled` prop (never set by the library while pending). */\n readonly disabled: boolean;\n}\n\n/**\n * Props of `Form.Submit`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport interface FormSubmitProps extends Omit<\n ComponentPropsWithRef<\"button\">,\n \"type\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * Native `disabled` (owned; a `render` element cannot re-enable it) and `data-disabled`. Never\n * set by the library (conventions 3.6). Native also with a component `render`, assumed to\n * render a submit button: only native `disabled` stops a submitter before hydration. With a\n * host element of another tag (`render={<a />}`), `aria-disabled=\"true\"` instead and the click\n * is cancelled.\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, FormSubmitState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, FormSubmitState>;\n /** Content, or a function of the part's state. */\n children?: StateValue<ReactNode, FormSubmitState>;\n /** Replace the default `<button>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"button\">, FormSubmitState>;\n}\n\n/**\n * The form's submit button: `<button type=\"submit\">` with `data-pending` while the enclosing\n * form's submission is in flight (`useFormStatus`). Works in any React-rendered form\n * (`Form.Root`, `Dialog.Form`, a plain `<form action>`). Never disabled while pending: block\n * repeat clicks with CSS on `[data-pending]` if you need to.\n *\n * Owned keys (conventions 1.2): `type` (on a `<button>`), `disabled`, `aria-disabled` (a host\n * element other than `<button>` / `<input>`), `onClick` (while disabled), `data-pending`,\n * `data-disabled`.\n *\n * @see https://ui.funstack.work/components/field\n */\nexport function FormSubmit({\n disabled = false,\n className,\n style,\n children,\n render,\n ...rest\n}: FormSubmitProps) {\n const { pending } = useFormStatus();\n const ref = useElementCheck(\n isDev &&\n ((el) => {\n const submitter =\n el.tagName === \"BUTTON\" ||\n (el.tagName === \"INPUT\" && [\"submit\", \"image\"].includes((el as HTMLInputElement).type));\n return submitter\n ? null\n : `Form.Submit: expected to render a <button> (or <input type=\"submit\">) but got ` +\n `<${el.tagName.toLowerCase()}>. Only a submit button submits the form natively.`;\n }),\n );\n const state: FormSubmitState = { pending, disabled };\n // The browser submits (`handlesClick: false`): native `disabled` wherever the element may be a\n // submitter (no `render`, a host `<button>` or `<input>`, a component), the only thing that\n // stops it before hydration and blocks implicit submission; `aria-disabled` and the cancelled\n // click below on a host element of another tag (`<a>`, `<div>`; conventions 1.2).\n const disabledProps = disabledButton(render, disabled, { handlesClick: false }).props;\n return useRender<ComponentPropsWithRef<\"button\">, FormSubmitState>({\n defaultElement: \"button\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n ...(rendersButton(render) && { type: \"submit\" as const }),\n ...disabledProps,\n // Only while disabled: an enabled submitter's click is the browser's (and React's).\n ...(disabled && {\n // Cancelling the click cancels the submission and a link's navigation.\n onClick: cancelClick,\n }),\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n },\n ref,\n });\n}\n\nFormSubmit.displayName = \"FormSubmit\";\n"],"mappings":";;;;;;;AAQA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;AAsDvC,SAAgB,WAAW,EACzB,WAAW,OACX,WACA,OACA,UACA,QACA,GAAG,QACe;CAClB,MAAM,EAAE,YAAY,cAAc;CAClC,MAAM,MAAM,gBACV,WACI,OAAO;EAIP,OAFE,GAAG,YAAY,YACd,GAAG,YAAY,WAAW,CAAC,UAAU,OAAO,CAAC,CAAC,SAAU,GAAwB,IAAI,IAEnF,OACA,kFACM,GAAG,QAAQ,YAAY,EAAE;CACrC,EACJ;CACA,MAAM,QAAyB;EAAE;EAAS;CAAS;CAKnD,MAAM,gBAAgB,eAAe,QAAQ,UAAU,EAAE,cAAc,MAAM,CAAC,CAAC,CAAC;CAChF,OAAO,UAA4D;EACjE,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,GAAI,cAAc,MAAM,KAAK,EAAE,MAAM,SAAkB;GACvD,GAAG;GAEH,GAAI,YAAY,EAEd,SAAS,YACX;GACA,gBAAgB,SAAS,OAAO;GAChC,iBAAiB,SAAS,QAAQ;EACpC;EACA;CACF,CAAC;AACH;AAEA,WAAW,cAAc"}
|
package/dist/form/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { FieldErrorValue, FormErrors } from "../internal/validity.mjs";
|
|
1
|
+
import { FieldErrorValue, FormErrors } from "../internal/form/validity.mjs";
|
|
2
2
|
import { FormRoot, FormRootProps, FormRootState } from "./form-root.mjs";
|
|
3
3
|
import { FormSubmit, FormSubmitProps, FormSubmitState } from "./form-submit.mjs";
|
|
4
4
|
//#region src/form/index.d.ts
|
package/dist/index.d.mts
CHANGED
|
@@ -35,8 +35,8 @@ import { DialogOpenChangeDetails, DialogRootProps, DialogRootState } from "./dia
|
|
|
35
35
|
import { DialogTitleProps, DialogTitleState } from "./dialog/dialog-title.mjs";
|
|
36
36
|
import { DialogTriggerProps, DialogTriggerState } from "./dialog/dialog-trigger.mjs";
|
|
37
37
|
import { Dialog } from "./dialog/index.mjs";
|
|
38
|
-
import { FieldErrorValue, FieldValidity, FormErrors } from "./internal/validity.mjs";
|
|
39
|
-
import { FieldState } from "./internal/field-context.mjs";
|
|
38
|
+
import { FieldErrorValue, FieldValidity, FormErrors } from "./internal/form/validity.mjs";
|
|
39
|
+
import { FieldState } from "./internal/form/field-context.mjs";
|
|
40
40
|
import { FieldControlProps } from "./field/field-control.mjs";
|
|
41
41
|
import { FieldDescriptionProps } from "./field/field-description.mjs";
|
|
42
42
|
import { FieldErrorProps } from "./field/field-error.mjs";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"action-details.mjs","names":[],"sources":["../../../src/internal/action/action-details.ts"],"sourcesContent":["import type { ActionDetails } from \"../types.js\";\n\nfunction isDev(): boolean {\n return process.env.NODE_ENV !== \"production\";\n}\n\nfunction rejectEventWrite(): never {\n throw new TypeError(\n \"`details.event` is a read-only virtual property; it cannot be assigned or defined. \" +\n \"Keep the DOM event out of `details` so that it stays serialisable.\",\n );\n}\n\n/**\n * Builds the `details` argument of an action (conventions 2.2).\n *\n * `fields` is a plain, extensible object of serialisable component-specific fields. `event` is a\n * virtual, non-own property served by a Proxy: `details.event` and `\"event\" in details` work,\n * while `Object.keys`, spread, `JSON.stringify` and React's Server Function serialiser see only\n * the real fields. That is what lets a Server Function be passed directly as an action.\n *\n * Writing `event` (`details.event = x`, `Object.defineProperty(details, \"event\", ...)`) is\n * rejected so that an own, enumerable `event` can never appear: in development it throws a\n * `TypeError`; in production an assignment is ignored and a `defineProperty` is declined (which\n * makes `Object.defineProperty` throw and `Reflect.defineProperty` return `false`).\n *\n * No `\"use client\"` directive: this file uses no client-only API, so it is importable from\n * anywhere (conventions 7.1).\n */\nexport function createActionDetails<T extends object>(\n event: Event | undefined,\n fields: T,\n): T & ActionDetails {\n return new Proxy(fields, {\n get: (target, key, receiver) => (key === \"event\" ? event : Reflect.get(target, key, receiver)),\n has: (target, key) => key === \"event\" || Reflect.has(target, key),\n set: (target, key, value, receiver) => {\n if (key === \"event\") {\n if (isDev()) rejectEventWrite();\n return true;\n }\n return Reflect.set(target, key, value, receiver);\n },\n defineProperty: (target, key, descriptor) => {\n if (key === \"event\") {\n if (isDev()) rejectEventWrite();\n return false;\n }\n return Reflect.defineProperty(target, key, descriptor);\n },\n }) as T & ActionDetails;\n}\n"],"mappings":";AAEA,SAAS,QAAiB;CACxB,OAAO,QAAQ,IAAI,aAAa;AAClC;AAEA,SAAS,mBAA0B;CACjC,MAAM,IAAI,UACR,uJAEF;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,oBACd,OACA,QACmB;CACnB,OAAO,IAAI,MAAM,QAAQ;EACvB,MAAM,QAAQ,KAAK,aAAc,QAAQ,UAAU,QAAQ,QAAQ,IAAI,QAAQ,KAAK,QAAQ;EAC5F,MAAM,QAAQ,QAAQ,QAAQ,WAAW,QAAQ,IAAI,QAAQ,GAAG;EAChE,MAAM,QAAQ,KAAK,OAAO,aAAa;GACrC,IAAI,QAAQ,SAAS;IACnB,IAAI,MAAM,GAAG,iBAAiB;IAC9B,OAAO;GACT;GACA,OAAO,QAAQ,IAAI,QAAQ,KAAK,OAAO,QAAQ;EACjD;EACA,iBAAiB,QAAQ,KAAK,eAAe;GAC3C,IAAI,QAAQ,SAAS;IACnB,IAAI,MAAM,GAAG,iBAAiB;IAC9B,OAAO;GACT;GACA,OAAO,QAAQ,eAAe,QAAQ,KAAK,UAAU;EACvD;CACF,CAAC;AACH"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { reportDropped } from "./report-dropped.mjs";
|
|
2
|
+
//#region src/internal/action/call-urgent-handler.ts
|
|
2
3
|
/** Whether `value` is a thenable (a promise, or anything with a callable `then`). */
|
|
3
4
|
function isThenable(value) {
|
|
4
5
|
return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
|
|
@@ -12,8 +13,7 @@ function isThenable(value) {
|
|
|
12
13
|
* Used by `onOpenChange` (the overlay Roots), a toast's `onClose` and Combobox's
|
|
13
14
|
* `onInputValueChange`. A missing handler is a no-op.
|
|
14
15
|
*
|
|
15
|
-
* Directive-free: no client-only API (
|
|
16
|
-
* and repeats its two-line `reportError` fallback instead).
|
|
16
|
+
* Directive-free: no client-only API (`report-dropped.ts` is directive-free too).
|
|
17
17
|
*/
|
|
18
18
|
function callUrgentHandler(handler, ...args) {
|
|
19
19
|
if (handler === void 0) return;
|
|
@@ -21,15 +21,10 @@ function callUrgentHandler(handler, ...args) {
|
|
|
21
21
|
try {
|
|
22
22
|
result = handler(...args);
|
|
23
23
|
} catch (error) {
|
|
24
|
-
|
|
24
|
+
reportDropped(error);
|
|
25
25
|
return;
|
|
26
26
|
}
|
|
27
|
-
if (isThenable(result)) result.then(void 0,
|
|
28
|
-
}
|
|
29
|
-
/** `reportError`, or `console.error` where it does not exist (jsdom), as `reportDropped`. */
|
|
30
|
-
function report(error) {
|
|
31
|
-
if (typeof reportError === "function") reportError(error);
|
|
32
|
-
else console.error(error);
|
|
27
|
+
if (isThenable(result)) result.then(void 0, reportDropped);
|
|
33
28
|
}
|
|
34
29
|
//#endregion
|
|
35
30
|
export { callUrgentHandler };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"call-urgent-handler.mjs","names":[],"sources":["../../../src/internal/action/call-urgent-handler.ts"],"sourcesContent":["import { reportDropped } from \"./report-dropped.js\";\n\n/** Whether `value` is a thenable (a promise, or anything with a callable `then`). */\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Calls an `on*` handler under the rule every handler the library defines follows (conventions\n * 2.1, #148): synchronously, in the caller's event, not awaited and with no pending state. A\n * synchronous throw is caught and passed to `reportError`, so the library's own bookkeeping after\n * the call still runs; a returned thenable gets a rejection handler that passes the reason to\n * `reportError`. Nothing reaches an Error Boundary, and a returned promise is never a warning.\n * Used by `onOpenChange` (the overlay Roots), a toast's `onClose` and Combobox's\n * `onInputValueChange`. A missing handler is a no-op.\n *\n * Directive-free: no client-only API (`report-dropped.ts` is directive-free too).\n */\nexport function callUrgentHandler<Args extends readonly unknown[]>(\n handler: ((...args: Args) => unknown) | undefined,\n ...args: Args\n): void {\n if (handler === undefined) return;\n let result: unknown;\n try {\n result = handler(...args);\n } catch (error) {\n reportDropped(error);\n return;\n }\n if (isThenable(result)) result.then(undefined, reportDropped);\n}\n"],"mappings":";;;AAGA,SAAS,WAAW,OAA+C;CACjE,QACG,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;;;;AAaA,SAAgB,kBACd,SACA,GAAG,MACG;CACN,IAAI,YAAY,KAAA,GAAW;CAC3B,IAAI;CACJ,IAAI;EACF,SAAS,QAAQ,GAAG,IAAI;CAC1B,SAAS,OAAO;EACd,cAAc,KAAK;EACnB;CACF;CACA,IAAI,WAAW,MAAM,GAAG,OAAO,KAAK,KAAA,GAAW,aAAa;AAC9D"}
|
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { useLayoutEffect, useRef } from "react";
|
|
3
|
-
//#region src/internal/report-dropped.ts
|
|
1
|
+
//#region src/internal/action/report-dropped.ts
|
|
4
2
|
/**
|
|
5
3
|
* Reports an action rejection that React would drop (conventions 2.4), for `useControllableAction`
|
|
6
4
|
* and `useActionTrigger`. React routes a transition's rejection only by unwrapping the newest
|
|
@@ -17,29 +15,13 @@ import { useLayoutEffect, useRef } from "react";
|
|
|
17
15
|
* The library passes them to the global `reportError` instead, as React's standalone
|
|
18
16
|
* `startTransition` does with every rejection: a window `error` event, seen by monitoring tools
|
|
19
17
|
* and by test runners, while the UI stays up. `console.error` where there is no `reportError`.
|
|
18
|
+
* `callUrgentHandler` routes an `on*` handler's throw or rejection here too.
|
|
20
19
|
*/
|
|
21
20
|
function reportDropped(error) {
|
|
22
21
|
if (typeof reportError === "function") reportError(error);
|
|
23
22
|
else console.error(error);
|
|
24
23
|
}
|
|
25
|
-
/**
|
|
26
|
-
* Whether the calling component's effects are connected: `true` from its mount layout effect until
|
|
27
|
-
* that effect is cleaned up, which happens on unmount, when an `<Activity>` hides it (`keepMounted`
|
|
28
|
-
* included) and when a Suspense boundary above it re-suspends and shows its fallback. Read from
|
|
29
|
-
* action continuations only, to decide between rethrowing a latest rejection (React routes it to
|
|
30
|
-
* the boundary) and `reportDropped`.
|
|
31
|
-
*/
|
|
32
|
-
function useConnected() {
|
|
33
|
-
const connected = useRef(false);
|
|
34
|
-
useLayoutEffect(() => {
|
|
35
|
-
connected.current = true;
|
|
36
|
-
return () => {
|
|
37
|
-
connected.current = false;
|
|
38
|
-
};
|
|
39
|
-
}, []);
|
|
40
|
-
return connected;
|
|
41
|
-
}
|
|
42
24
|
//#endregion
|
|
43
|
-
export { reportDropped
|
|
25
|
+
export { reportDropped };
|
|
44
26
|
|
|
45
27
|
//# sourceMappingURL=report-dropped.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"report-dropped.mjs","names":[],"sources":["../../../src/internal/action/report-dropped.ts"],"sourcesContent":["// No directive: no client-only API, so directive-free modules (`call-urgent-handler.ts`) import\n// it too (conventions 7.1). `useConnected` lives in `use-connected.ts`.\n\n/**\n * Reports an action rejection that React would drop (conventions 2.4), for `useControllableAction`\n * and `useActionTrigger`. React routes a transition's rejection only by unwrapping the newest\n * thenable of a `useTransition` in a render of the component that owns it, so two rejections reach\n * no Error Boundary:\n *\n * - a **superseded** run's (a later run of the same hook replaced its thenable), and\n * - the **latest** run's once the owner is **gone**: unmounted, or hidden (a consumer's\n * `<Activity>`, the library's `keepMounted` overlays in `overlay-popup.tsx`, Toast's Suspense\n * guard, any Suspense boundary showing its fallback): no render reads it (#152). Hidden counts\n * as gone: the rejection is reported once and does not reach the boundary on re-show, where\n * React would deliver it (a deliberate deviation, conventions resolved question 43).\n *\n * The library passes them to the global `reportError` instead, as React's standalone\n * `startTransition` does with every rejection: a window `error` event, seen by monitoring tools\n * and by test runners, while the UI stays up. `console.error` where there is no `reportError`.\n * `callUrgentHandler` routes an `on*` handler's throw or rejection here too.\n */\nexport function reportDropped(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else console.error(error);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cAAc,OAAsB;CAClD,IAAI,OAAO,gBAAgB,YAAY,YAAY,KAAK;MACnD,QAAQ,MAAM,KAAK;AAC1B"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { reportDropped
|
|
2
|
+
import { reportDropped } from "./report-dropped.mjs";
|
|
3
|
+
import { useConnected } from "./use-connected.mjs";
|
|
3
4
|
import { useRef, useTransition } from "react";
|
|
4
|
-
//#region src/internal/use-action-trigger.ts
|
|
5
|
+
//#region src/internal/action/use-action-trigger.ts
|
|
5
6
|
/**
|
|
6
7
|
* The transition of a pure-trigger part: an `action` with no state of its own (`Button`,
|
|
7
8
|
* `Dialog.Close`, `Popover.Close`, `Menu.Item`, `Toast.Action`; conventions 3.4), and the steps
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-action-trigger.mjs","names":[],"sources":["../../../src/internal/action/use-action-trigger.ts"],"sourcesContent":["\"use client\";\nimport { useRef, useTransition } from \"react\";\nimport { reportDropped } from \"./report-dropped.js\";\nimport { useConnected } from \"./use-connected.js\";\n\nexport interface ActionTriggerOptions {\n /**\n * Open generation of the overlay a `then` belongs to: `then` is skipped when a newer open of\n * the overlay started after the run began.\n */\n readonly openGeneration?: (() => number) | undefined;\n /**\n * Ignore `run` while a run is in flight (conventions 2.5.1): `run` returns `false` and starts\n * nothing. In flight means the hook's synchronous in-flight counter is non-zero (it also sees\n * two activations in one task, before React re-rendered); the last render's `pending` is not\n * consulted, so a click in a settled-but-held commit window runs. Default `false`: runs\n * overlap, as with React's own `useTransition`. A pure trigger passes\n * `(whilePending ?? <its default>) === \"ignore\"`, read per render (#146), through\n * `usePureTrigger`.\n */\n readonly ignoreWhilePending?: boolean | undefined;\n}\n\nexport interface ActionTrigger {\n /** A run started through this hook is in flight (the part's own transition). */\n readonly pending: boolean;\n /**\n * Runs `work` inside the part's own transition and, once it resolves, `then` (still inside the\n * transition: a Close part's close, a menu item's close). With overlapping runs, `then` runs\n * once, when the last run in flight settles, and only if the latest run resolved: it is the\n * latest run's `then` (#146 review F1). A rejection skips `then` and reaches\n * the nearest Error Boundary above the part; a run that a later run superseded, or any run\n * once the part unmounted or was hidden by `<Activity>`, passes its rejection to `reportError`\n * instead (conventions 2.4). With\n * `openGeneration`, `then` is skipped when a newer open of the overlay started after the run\n * began. Returns `false` when the run was ignored (a run is in flight and `ignoreWhilePending`\n * is on), so the part can\n * `preventDefault()` the activation, and `true` otherwise.\n */\n readonly run: (work: () => unknown, then?: () => void) => boolean;\n}\n\n/**\n * The transition of a pure-trigger part: an `action` with no state of its own (`Button`,\n * `Dialog.Close`, `Popover.Close`, `Menu.Item`, `Toast.Action`; conventions 3.4), and the steps\n * of the continuous controls (`Slider`, `NumberField`). A second `run` while one is in flight is\n * ignored only with `ignoreWhilePending` (a part whose `whilePending` is `\"ignore\"`, conventions\n * 2.5.1).\n *\n * Without it (`whilePending=\"run\"`, the steps) runs overlap, and the hook handles superseded\n * rejections as `useControllableAction` does: React keeps only the newest\n * thenable per `useTransition`, so the rejection of a run that a later run superseded reaches no\n * boundary. The hook passes it to `reportError` (`reportDropped`); the latest run's rejection\n * is rethrown inside the transition and reaches the boundary. In both modes, a latest rejection\n * that arrives after the part unmounted or was hidden by `<Activity>` is reported too (#152):\n * React would route it only through a render of the part.\n */\nexport function useActionTrigger(options: ActionTriggerOptions = {}): ActionTrigger {\n const { openGeneration, ignoreWhilePending = false } = options;\n\n const [pending, startOwnTransition] = useTransition();\n const latest = useRef(0);\n // Runs whose work has not settled yet. Updated synchronously, so a second activation in the\n // same task (React's `pending` is still the stale render value) is seen (conventions 2.5).\n const inFlight = useRef(0);\n const connected = useConnected();\n // The latest run's continuation once it resolved, waiting for the other runs in flight to\n // settle. Cleared by every new run: only the latest run's outcome decides (#146 review F1).\n const resolvedThen = useRef<(() => void) | null>(null);\n\n // A run settled. When it was the last in flight, the latest run's continuation runs if that\n // run resolved; a rejected latest run (or a newer run since) left nothing to run.\n const settled = () => {\n inFlight.current--;\n if (inFlight.current > 0) return;\n const continuation = resolvedThen.current;\n resolvedThen.current = null;\n continuation?.();\n };\n\n const run = (work: () => unknown, then?: () => void): boolean => {\n // The own counter only, not the rendered `pending` (design/components/button.md 5.2): after\n // the work settled, a commit held by entanglement must not drop a new activation.\n if (ignoreWhilePending && inFlight.current > 0) return false;\n inFlight.current++;\n const id = ++latest.current;\n // The open this run belongs to (design/components/popover.md 3.4): if the\n // user dismisses and re-opens while the action runs, its close must not close the new open.\n const generation = openGeneration?.();\n resolvedThen.current = null;\n startOwnTransition(async () => {\n try {\n await work();\n } catch (error) {\n // The latest run's rejection takes React's own route to the boundary while the part is\n // there to render it; otherwise React would drop it, as it drops a superseded one (2.4).\n const rethrow = id === latest.current && connected.current;\n if (!rethrow) reportDropped(error);\n settled();\n if (rethrow) throw error;\n return;\n }\n if (id === latest.current && then !== undefined) {\n resolvedThen.current = () => {\n if (openGeneration !== undefined && openGeneration() !== generation) return;\n then();\n };\n }\n settled();\n });\n return true;\n };\n\n return { pending, run };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,iBAAiB,UAAgC,CAAC,GAAkB;CAClF,MAAM,EAAE,gBAAgB,qBAAqB,UAAU;CAEvD,MAAM,CAAC,SAAS,sBAAsB,cAAc;CACpD,MAAM,SAAS,OAAO,CAAC;CAGvB,MAAM,WAAW,OAAO,CAAC;CACzB,MAAM,YAAY,aAAa;CAG/B,MAAM,eAAe,OAA4B,IAAI;CAIrD,MAAM,gBAAgB;EACpB,SAAS;EACT,IAAI,SAAS,UAAU,GAAG;EAC1B,MAAM,eAAe,aAAa;EAClC,aAAa,UAAU;EACvB,eAAe;CACjB;CAEA,MAAM,OAAO,MAAqB,SAA+B;EAG/D,IAAI,sBAAsB,SAAS,UAAU,GAAG,OAAO;EACvD,SAAS;EACT,MAAM,KAAK,EAAE,OAAO;EAGpB,MAAM,aAAa,iBAAiB;EACpC,aAAa,UAAU;EACvB,mBAAmB,YAAY;GAC7B,IAAI;IACF,MAAM,KAAK;GACb,SAAS,OAAO;IAGd,MAAM,UAAU,OAAO,OAAO,WAAW,UAAU;IACnD,IAAI,CAAC,SAAS,cAAc,KAAK;IACjC,QAAQ;IACR,IAAI,SAAS,MAAM;IACnB;GACF;GACA,IAAI,OAAO,OAAO,WAAW,SAAS,KAAA,GACpC,aAAa,gBAAgB;IAC3B,IAAI,mBAAmB,KAAA,KAAa,eAAe,MAAM,YAAY;IACrE,KAAK;GACP;GAEF,QAAQ;EACV,CAAC;EACD,OAAO;CACT;CAEA,OAAO;EAAE;EAAS;CAAI;AACxB"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useLayoutEffect, useRef } from "react";
|
|
3
|
+
//#region src/internal/action/use-connected.ts
|
|
4
|
+
/**
|
|
5
|
+
* Whether the calling component's effects are connected: `true` from its mount layout effect until
|
|
6
|
+
* that effect is cleaned up, which happens on unmount, when an `<Activity>` hides it (`keepMounted`
|
|
7
|
+
* included) and when a Suspense boundary above it re-suspends and shows its fallback. Read from
|
|
8
|
+
* action continuations only, to decide between rethrowing a latest rejection (React routes it to
|
|
9
|
+
* the boundary) and `reportDropped`.
|
|
10
|
+
*/
|
|
11
|
+
function useConnected() {
|
|
12
|
+
const connected = useRef(false);
|
|
13
|
+
useLayoutEffect(() => {
|
|
14
|
+
connected.current = true;
|
|
15
|
+
return () => {
|
|
16
|
+
connected.current = false;
|
|
17
|
+
};
|
|
18
|
+
}, []);
|
|
19
|
+
return connected;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { useConnected };
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=use-connected.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-connected.mjs","names":[],"sources":["../../../src/internal/action/use-connected.ts"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect, useRef } from \"react\";\nimport type { RefObject } from \"react\";\n\n/**\n * Whether the calling component's effects are connected: `true` from its mount layout effect until\n * that effect is cleaned up, which happens on unmount, when an `<Activity>` hides it (`keepMounted`\n * included) and when a Suspense boundary above it re-suspends and shows its fallback. Read from\n * action continuations only, to decide between rethrowing a latest rejection (React routes it to\n * the boundary) and `reportDropped`.\n */\nexport function useConnected(): RefObject<boolean> {\n const connected = useRef(false);\n useLayoutEffect(() => {\n connected.current = true;\n return () => {\n connected.current = false;\n };\n }, []);\n return connected;\n}\n"],"mappings":";;;;;;;;;;AAWA,SAAgB,eAAmC;CACjD,MAAM,YAAY,OAAO,KAAK;CAC9B,sBAAsB;EACpB,UAAU,UAAU;EACpB,aAAa;GACX,UAAU,UAAU;EACtB;CACF,GAAG,CAAC,CAAC;CACL,OAAO;AACT"}
|