Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Prevent QuantitySelector stealing focus on page load #9487

Merged
merged 1 commit into from
May 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion assets/js/base/components/quantity-selector/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { speak } from '@wordpress/a11y';
import classNames from 'classnames';
import { useCallback, useLayoutEffect, useRef } from '@wordpress/element';
import { DOWN, UP } from '@wordpress/keycodes';
import { usePrevious } from '@woocommerce/base-hooks';
import { useDebouncedCallback } from 'use-debounce';

/**
Expand Down Expand Up @@ -74,6 +75,8 @@ const QuantitySelector = ( {
const canDecrease = ! disabled && quantity - step >= minimum;
const canIncrease =
! disabled && ( ! hasMaximum || quantity + step <= maximum );
const previousCanDecrease = usePrevious( canDecrease );
const previousCanIncrease = usePrevious( canIncrease );

// When the increase or decrease buttons get disabled, the focus
// gets moved to the `<body>` element. This was causing weird
Expand All @@ -95,20 +98,22 @@ const QuantitySelector = ( {

const currentDocument = inputRef.current.ownerDocument;
if (
previousCanDecrease &&
! canDecrease &&
( currentDocument.activeElement === decreaseButtonRef.current ||
currentDocument.activeElement === currentDocument.body )
) {
inputRef.current.focus();
}
if (
previousCanIncrease &&
! canIncrease &&
( currentDocument.activeElement === increaseButtonRef.current ||
currentDocument.activeElement === currentDocument.body )
) {
inputRef.current.focus();
}
}, [ canDecrease, canIncrease ] );
}, [ previousCanDecrease, previousCanIncrease, canDecrease, canIncrease ] );

/**
* The goal of this function is to normalize what was inserted,
Expand Down