From df72a21fa89a4885bb666f4a3bc0a9e757b870c2 Mon Sep 17 00:00:00 2001 From: GeoSot Date: Wed, 19 May 2021 01:23:52 +0300 Subject: Add `getNextActiveElement` helper function to utils, replacing custom implementation through components (#33608) --- js/src/util/index.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) (limited to 'js/src/util') diff --git a/js/src/util/index.js b/js/src/util/index.js index 9441d0a44a..6b38a05e94 100644 --- a/js/src/util/index.js +++ b/js/src/util/index.js @@ -261,6 +261,34 @@ const execute = callback => { } } +/** + * Return the previous/next element of a list. + * + * @param {array} list The list of elements + * @param activeElement The active element + * @param shouldGetNext Choose to get next or previous element + * @param isCycleAllowed + * @return {Element|elem} The proper element + */ +const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => { + let index = list.indexOf(activeElement) + + // if the element does not exist in the list initialize it as the first element + if (index === -1) { + return list[0] + } + + const listLength = list.length + + index += shouldGetNext ? 1 : -1 + + if (isCycleAllowed) { + index = (index + listLength) % listLength + } + + return list[Math.max(0, Math.min(index, listLength - 1))] +} + export { getElement, getUID, @@ -275,6 +303,7 @@ export { isDisabled, findShadowRoot, noop, + getNextActiveElement, reflow, getjQuery, onDOMContentLoaded, -- cgit v1.2.3