"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ScrollableItems = void 0; const tslib_1 = require("tslib"); const ink_1 = require("ink"); const react_1 = tslib_1.__importStar(require("react")); const useFocusRequest_1 = require("../hooks/useFocusRequest"); const useListInput_1 = require("../hooks/useListInput"); const ScrollableItems = ({ active = true, children = [], radius = 10, size = 1, loop = true, onFocusRequest, willReachEnd }) => { const getKey = (child) => { if (child.key === null) { throw new Error(`Expected all children to have a key`); } else { return child.key; } }; const keys = react_1.default.Children.map(children, child => getKey(child)); const initialKey = keys[0]; const [activeKey, setActiveKey] = (0, react_1.useState)(initialKey); const activeIndex = keys.indexOf(activeKey); (0, react_1.useEffect)(() => { // If the active key is missing from the // new keys, set it to the initalKey if (!keys.includes(activeKey)) { setActiveKey(initialKey); } }, [children]); (0, react_1.useEffect)(() => { if (willReachEnd && activeIndex >= keys.length - 2) { willReachEnd(); } }, [activeIndex]); (0, useFocusRequest_1.useFocusRequest)({ active: active && !!onFocusRequest, }, request => { onFocusRequest?.(request); }, [ onFocusRequest, ]); (0, useListInput_1.useListInput)(activeKey, keys, { active, minus: `up`, plus: `down`, set: setActiveKey, loop, }); let min = activeIndex - radius; let max = activeIndex + radius; if (max > keys.length) { min -= max - keys.length; max = keys.length; } if (min < 0) { max += -min; min = 0; } if (max >= keys.length) max = keys.length - 1; const rendered = []; for (let t = min; t <= max; ++t) { const key = keys[t]; const activeItem = active && key === activeKey; rendered.push(react_1.default.createElement(ink_1.Box, { key: key, height: size }, react_1.default.createElement(ink_1.Box, { marginLeft: 1, marginRight: 1 }, react_1.default.createElement(ink_1.Text, null, activeItem ? react_1.default.createElement(ink_1.Text, { color: `cyan`, bold: true }, `>`) : ` `)), react_1.default.createElement(ink_1.Box, null, react_1.default.cloneElement(children[t], { active: activeItem })))); } return react_1.default.createElement(ink_1.Box, { flexDirection: `column`, width: `100%` }, rendered); }; exports.ScrollableItems = ScrollableItems;