UNPKG

@awsui/components-react

Version:

AWS UI is a collection of [React](https://reactjs.org/) components that help create intuitive, responsive, and accessible user experiences for web applications. It is developed by Amazon Web Services (AWS). This work is available under the terms of the [A

63 lines (62 loc) 2.75 kB
import { useMemo, useState, useCallback } from 'react'; export var createMoveHighlight = function (items, callback, isInteractive, withinRange) { var moveHighlight = function (direction, startIndex) { if (startIndex === void 0) { startIndex = 0; } var newIndex = startIndex; do { newIndex += direction; } while (withinRange(items, newIndex) && !isInteractive(items[newIndex])); if (withinRange(items, newIndex) && isInteractive(items[newIndex])) { callback(newIndex); } }; return moveHighlight; }; export var __withinRange = function (items, index) { return index >= 0 && index < items.length; }; export var useHighlightedOption = function (_a) { var options = _a.options, isInteractive = _a.isInteractive, scrollToIndex = _a.scrollToIndex, _b = _a.withinRange, withinRange = _b === void 0 ? __withinRange : _b; var _c = useState(-1), highlightedIndex = _c[0], setHighlightedIndex = _c[1]; var patchedSetHighlighted = useCallback(function (index) { scrollToIndex && scrollToIndex(index); setHighlightedIndex(index); }, [scrollToIndex, setHighlightedIndex]); var highlightedOption = useMemo(function () { if (!withinRange(options, highlightedIndex) || !isInteractive(options[highlightedIndex])) { return undefined; } return options[highlightedIndex]; }, [highlightedIndex, options, isInteractive, withinRange]); var __moveHighlight = useCallback(createMoveHighlight(options, patchedSetHighlighted, isInteractive, withinRange), [ options, patchedSetHighlighted, isInteractive ]); var moveHighlight = useCallback(function (direction, startIndex) { __moveHighlight(direction, startIndex !== null && startIndex !== void 0 ? startIndex : highlightedIndex); }, [highlightedIndex, __moveHighlight]); var resetHighlight = useCallback(function () { patchedSetHighlighted(-1); }, [patchedSetHighlighted]); var goHome = useCallback(function () { moveHighlight(1, -1); }, [moveHighlight]); var goEnd = useCallback(function () { moveHighlight(-1, options.length); }, [moveHighlight, options]); var highlightOption = useCallback(function (option) { var index = options.indexOf(option); patchedSetHighlighted(index); }, [options, patchedSetHighlighted]); return { highlightedOption: highlightedOption, moveHighlight: moveHighlight, resetHighlight: resetHighlight, setHighlightedIndex: patchedSetHighlighted, highlightedIndex: highlightedIndex, highlightOption: highlightOption, goHome: goHome, goEnd: goEnd }; };