Private
Public Access
1
0
Files

74 lines
2.4 KiB
JavaScript

'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "useSelection", {
enumerable: true,
get: function() {
return useSelection;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _reactutilities = require("@fluentui/react-utilities");
const useSelection = (props)=>{
const { defaultSelectedOptions, multiselect, onOptionSelect } = props;
const [selectedOptions, setSelectedOptions] = (0, _reactutilities.useControllableState)({
state: props.selectedOptions,
defaultState: defaultSelectedOptions,
initialState: []
});
const selectOption = _react.useCallback((event, option)=>{
// if the option is disabled, do nothing
if (option.disabled) {
return;
}
// for single-select, always return the selected option
let newSelection = [
option.value
];
// toggle selected state of the option for multiselect
if (multiselect) {
const selectedIndex = selectedOptions.findIndex((o)=>o === option.value);
if (selectedIndex > -1) {
// deselect option
newSelection = [
...selectedOptions.slice(0, selectedIndex),
...selectedOptions.slice(selectedIndex + 1)
];
} else {
// select option
newSelection = [
...selectedOptions,
option.value
];
}
}
setSelectedOptions(newSelection);
onOptionSelect === null || onOptionSelect === void 0 ? void 0 : onOptionSelect(event, {
optionValue: option.value,
optionText: option.text,
selectedOptions: newSelection
});
}, [
onOptionSelect,
multiselect,
selectedOptions,
setSelectedOptions
]);
const clearSelection = (event)=>{
setSelectedOptions([]);
onOptionSelect === null || onOptionSelect === void 0 ? void 0 : onOptionSelect(event, {
optionValue: undefined,
optionText: undefined,
selectedOptions: []
});
};
return {
clearSelection,
selectOption,
selectedOptions
};
};