Skip to content

Commit

Permalink
Add checkboxes to multi-select options
Browse files Browse the repository at this point in the history
  • Loading branch information
acelaya committed Aug 19, 2024
1 parent 6b4177e commit 9ee0aa2
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions src/components/input/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ function SelectOption<T>({
disabled = false,
classes,
}: SelectOptionProps<T>) {
const checkboxRef = useRef<HTMLElement | null>(null);
const selectContext = useContext(SelectContext);
if (!selectContext) {
throw new Error(
Expand All @@ -77,13 +78,20 @@ function SelectOption<T>({
!disabled &&
((multiple && currentValue.includes(value)) || currentValue === value);

const selectOrToggle = useCallback(() => {
// In single-select, just set current value
const selectOneValue = useCallback(() => {
if (!multiple) {
selectValue(value);
return;
}

selectValue(multiple ? [value] : []);
}, [multiple, selectValue, value]);
const toggleValue = useCallback(() => {
// This will never be invoked in single-select
if (!multiple) {
return;
}

// In multi-select, clear selection for nullish values
if (!value) {
selectValue([]);
Expand Down Expand Up @@ -112,15 +120,17 @@ function SelectOption<T>({
},
classes,
)}
onClick={() => {
if (!disabled) {
selectOrToggle();
onClick={e => {
// Do not invoke callback if clicked element is the checkbox, as it has
// its own event handler.
if (!disabled && e.target !== checkboxRef.current) {
selectOneValue();
}
}}
onKeyPress={e => {
if (!disabled && ['Enter', 'Space'].includes(e.code)) {
e.preventDefault();
selectOrToggle();
selectOneValue();
}
}}
role="option"
Expand Down Expand Up @@ -154,11 +164,13 @@ function SelectOption<T>({
<div
className={classnames('scale-125', {
'text-grey-6': selected,
'text-grey-3': !selected,
'text-grey-3 hover:text-grey-6': !selected,
})}
>
<Checkbox
checked={selected}
onChange={toggleValue}
elementRef={checkboxRef}
checkedIcon={CheckboxCheckedFilledIcon}
/>
</div>
Expand Down

0 comments on commit 9ee0aa2

Please sign in to comment.