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

Commit

Permalink
Prevent QuantitySelector stealing focus on page load (#9487)
Browse files Browse the repository at this point in the history
  • Loading branch information
Aljullu authored May 18, 2023
1 parent a5d9d5c commit bffce23
Showing 1 changed file with 6 additions and 1 deletion.
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

0 comments on commit bffce23

Please sign in to comment.