useMultipleSelect.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = useMultipleSelect;
  6. var _react = require("react");
  7. /**
  8. * @title multipleSelect hooks
  9. * @description multipleSelect by hold down shift key
  10. */
  11. function useMultipleSelect(getKey) {
  12. const [prevSelectedIndex, setPrevSelectedIndex] = (0, _react.useState)(null);
  13. const multipleSelect = (0, _react.useCallback)((currentSelectedIndex, data, selectedKeys) => {
  14. const configPrevSelectedIndex = prevSelectedIndex !== null && prevSelectedIndex !== void 0 ? prevSelectedIndex : currentSelectedIndex;
  15. // add/delete the selected range
  16. const startIndex = Math.min(configPrevSelectedIndex || 0, currentSelectedIndex);
  17. const endIndex = Math.max(configPrevSelectedIndex || 0, currentSelectedIndex);
  18. const rangeKeys = data.slice(startIndex, endIndex + 1).map(item => getKey(item));
  19. const shouldSelected = rangeKeys.some(rangeKey => !selectedKeys.has(rangeKey));
  20. const changedKeys = [];
  21. rangeKeys.forEach(item => {
  22. if (shouldSelected) {
  23. if (!selectedKeys.has(item)) {
  24. changedKeys.push(item);
  25. }
  26. selectedKeys.add(item);
  27. } else {
  28. selectedKeys.delete(item);
  29. changedKeys.push(item);
  30. }
  31. });
  32. setPrevSelectedIndex(shouldSelected ? endIndex : null);
  33. return changedKeys;
  34. }, [prevSelectedIndex]);
  35. const updatePrevSelectedIndex = val => {
  36. setPrevSelectedIndex(val);
  37. };
  38. return [multipleSelect, updatePrevSelectedIndex];
  39. }