@ozen-ui/kit
Version:
React component library
76 lines (75 loc) • 3.5 kB
JavaScript
import { useEffect } from 'react';
import { getNextIndex } from '../../../../utils/getNextIndex';
import { getPrevIndex } from '../../../../utils/getPrevIndex';
import { isKey } from '../../../../utils/isKey';
import { isKeys } from '../../../../utils/isKeys';
import { lastSelectedValue, getOptionIndex } from '../../utils';
export var useDataListBaseControls = function (_a) {
var active = _a.active, valueControl = _a.valueControl, optionsStore = _a.optionsStore;
var findOption = function (value) {
var _a, _b;
if (value === null) {
return null;
}
var lastId = lastSelectedValue(value !== null && value !== void 0 ? value : null);
return ((_b = (_a = optionsStore.options.current.find(function (option) { return option.id === lastId; })) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : null);
};
useEffect(function () {
var _a, _b;
if (!active) {
return;
}
optionsStore.setFocused(findOption(optionsStore.focused.current));
optionsStore.setCurrentOption(valueControl.value
? findOption(lastSelectedValue(valueControl.value))
: (_b = (_a = optionsStore.options.current[0]) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : null);
}, [active]);
// Сброс
useEffect(function () {
if (!active) {
return undefined;
}
return function () {
optionsStore.setFocused(null);
optionsStore.setCurrentOption(null);
};
}, [active]);
var onKeyDown = function (event) {
var _a, _b, _c;
if (!active || !isKeys(event, ['Enter', 'ArrowUp', 'ArrowDown'])) {
return;
}
var currentOption = (_a = optionsStore.focused.current) !== null && _a !== void 0 ? _a : optionsStore.currentOption.current;
if (isKey(event, 'Enter')) {
// Не обрабатываем ввод в пустом списке
if (!optionsStore.options.current.length) {
return;
}
if (!currentOption) {
return;
}
var optionFullInfo = optionsStore.getOptionFullInfo(currentOption);
if (!optionFullInfo || optionFullInfo.disabled) {
return;
}
event.preventDefault();
optionsStore.setFocused(optionFullInfo.id);
optionsStore.setCurrentOption(optionFullInfo.id);
valueControl.setValue(event, optionFullInfo.id);
}
if (isKeys(event, ['ArrowUp', 'ArrowDown'])) {
event.preventDefault();
var availableOptions = optionsStore.availableOptions.current;
var currentIndex = currentOption
? getOptionIndex(availableOptions, currentOption)
: null;
var isArrowUp = isKey(event, 'ArrowUp');
var newIndex = isArrowUp
? getPrevIndex(currentIndex !== null && currentIndex !== void 0 ? currentIndex : 0, availableOptions.length)
: getNextIndex(currentIndex !== null && currentIndex !== void 0 ? currentIndex : -1, availableOptions.length);
var newItem = (_c = (_b = availableOptions[newIndex]) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : null;
optionsStore.setFocused(newItem);
}
};
return { onKeyDown: onKeyDown };
};