diff options
author | GeoSot <geo.sotis@gmail.com> | 2021-05-19 01:23:52 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-05-19 01:23:52 +0300 |
commit | df72a21fa89a4885bb666f4a3bc0a9e757b870c2 (patch) | |
tree | d80c2614184e53f73de9364ac46dbeef9f61aa08 /js/src/util | |
parent | 372890b67b28238c98ec4d5ffcdb777c9939e87c (diff) |
Add `getNextActiveElement` helper function to utils, replacing custom implementation through components (#33608)
Diffstat (limited to 'js/src/util')
-rw-r--r-- | js/src/util/index.js | 29 |
1 files changed, 29 insertions, 0 deletions
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, |