diff --git a/.xstate/date-picker.js b/.xstate/date-picker.js index 299d4d2fe4..b425c3fdf7 100644 --- a/.xstate/date-picker.js +++ b/.xstate/date-picker.js @@ -21,6 +21,7 @@ const fetchMachine = createMachine({ "isOpenControlled": false, "isOpenControlled": false, "isOpenControlled": false, + "shouldRestoreFocus && isInteractOutsideEvent": false, "shouldRestoreFocus": false, "isMonthView": false, "isYearView": false, @@ -167,6 +168,10 @@ const fetchMachine = createMachine({ exit: ["clearHoveredDate", "resetView"], on: { "CONTROLLED.CLOSE": [{ + cond: "shouldRestoreFocus && isInteractOutsideEvent", + target: "focused", + actions: ["focusTriggerElement"] + }, { cond: "shouldRestoreFocus", target: "focused", actions: ["focusInputElement"] @@ -387,6 +392,7 @@ const fetchMachine = createMachine({ "isYearView": ctx => ctx["isYearView"], "isMonthView": ctx => ctx["isMonthView"], "isOpenControlled": ctx => ctx["isOpenControlled"], + "shouldRestoreFocus && isInteractOutsideEvent": ctx => ctx["shouldRestoreFocus && isInteractOutsideEvent"], "shouldRestoreFocus": ctx => ctx["shouldRestoreFocus"], "isRangePicker && hasSelectedRange": ctx => ctx["isRangePicker && hasSelectedRange"], "isRangePicker && isSelectingEndDate && closeOnSelect && isOpenControlled": ctx => ctx["isRangePicker && isSelectingEndDate && closeOnSelect && isOpenControlled"], diff --git a/packages/machines/date-picker/src/date-picker.machine.ts b/packages/machines/date-picker/src/date-picker.machine.ts index d52971145e..1f98c856b4 100644 --- a/packages/machines/date-picker/src/date-picker.machine.ts +++ b/packages/machines/date-picker/src/date-picker.machine.ts @@ -232,6 +232,11 @@ export function machine(userContext: UserDefinedContext) { exit: ["clearHoveredDate", "resetView"], on: { "CONTROLLED.CLOSE": [ + { + guard: and("shouldRestoreFocus", "isInteractOutsideEvent"), + target: "focused", + actions: ["focusTriggerElement"], + }, { guard: "shouldRestoreFocus", target: "focused", @@ -524,6 +529,7 @@ export function machine(userContext: UserDefinedContext) { isSelectingEndDate: (ctx) => ctx.activeIndex === 1, closeOnSelect: (ctx) => !!ctx.closeOnSelect, isOpenControlled: (ctx) => !!ctx.__controlled, + isInteractOutsideEvent: (_ctx, evt) => evt.previousEvent?.type === "INTERACT_OUTSIDE", }, activities: { trackPositioning(ctx) { @@ -817,8 +823,8 @@ export function machine(userContext: UserDefinedContext) { invokeOnClose(ctx) { ctx.onOpenChange?.({ open: false }) }, - toggleVisibility(ctx, _evt, { send }) { - send({ type: ctx.open ? "CONTROLLED.OPEN" : "CONTROLLED.CLOSE" }) + toggleVisibility(ctx, evt, { send }) { + send({ type: ctx.open ? "CONTROLLED.OPEN" : "CONTROLLED.CLOSE", previousEvent: evt }) }, }, compareFns: {