nicecode-v2/packages/meta/lib/_util/hooks/useMultipleSelect.js

57 lines
2.2 KiB
JavaScript

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/_util/hooks/useMultipleSelect.ts
var useMultipleSelect_exports = {};
__export(useMultipleSelect_exports, {
default: () => useMultipleSelect
});
module.exports = __toCommonJS(useMultipleSelect_exports);
var import_react = require("react");
function useMultipleSelect(getKey) {
const [prevSelectedIndex, setPrevSelectedIndex] = (0, import_react.useState)(null);
const multipleSelect = (0, import_react.useCallback)(
(currentSelectedIndex, data, selectedKeys) => {
const configPrevSelectedIndex = prevSelectedIndex ?? currentSelectedIndex;
const startIndex = Math.min(configPrevSelectedIndex || 0, currentSelectedIndex);
const endIndex = Math.max(configPrevSelectedIndex || 0, currentSelectedIndex);
const rangeKeys = data.slice(startIndex, endIndex + 1).map((item) => getKey(item));
const shouldSelected = rangeKeys.some((rangeKey) => !selectedKeys.has(rangeKey));
const changedKeys = [];
rangeKeys.forEach((item) => {
if (shouldSelected) {
if (!selectedKeys.has(item)) {
changedKeys.push(item);
}
selectedKeys.add(item);
} else {
selectedKeys.delete(item);
changedKeys.push(item);
}
});
setPrevSelectedIndex(shouldSelected ? endIndex : null);
return changedKeys;
},
[prevSelectedIndex]
);
const updatePrevSelectedIndex = (val) => {
setPrevSelectedIndex(val);
};
return [multipleSelect, updatePrevSelectedIndex];
}