Skip to content

Commit

Permalink
feat(MultiSelect): add select all
Browse files Browse the repository at this point in the history
  • Loading branch information
yohanngab committed Oct 30, 2024
1 parent 58e2c5b commit 1a34de2
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions ui/src/Components/MultiSelect/MultiSelect.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable no-undef */

import Checkbox from "@codegouvfr/react-dsfr/Checkbox";
import Input from "@codegouvfr/react-dsfr/Input";
import { Checkbox } from "@codegouvfr/react-dsfr/Checkbox";
import { Input } from "@codegouvfr/react-dsfr/Input";
import { useEffect, useRef, useState } from "react";

import { isPlural } from "../../campagnes/utils";
Expand All @@ -11,7 +11,7 @@ const MultiSelect = ({ options, name, placeholder = "", label, selected, setSele
const [isOpen, setIsOpen] = useState(false);
const [values, setValues] = useState(selected || []);
const [search, setSearch] = useState("");

const [isAllSelected, setIsAllSelected] = useState(false);
const dropdownRef = useRef(null);

const displayedValues = values
Expand All @@ -31,14 +31,27 @@ const MultiSelect = ({ options, name, placeholder = "", label, selected, setSele
}
setValues(updatedValues);
setSelected(updatedValues);
setIsAllSelected(updatedValues.length === options.length);
};

useEffect(() => {
if (!values?.length && selected?.length) {
setValues(selected);
}
setIsAllSelected(selected?.length === options?.length);
}, [selected]);

const handleSelectAll = (e) => {
if (e.target.checked) {
setValues(options.map((option) => option.value));
setSelected(options.map((option) => option.value));
setIsAllSelected(true);
} else {
setValues([]);
setIsAllSelected(false);
}
};

useEffect(() => {
const handleClickOutside = (event) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
Expand Down Expand Up @@ -98,6 +111,19 @@ const MultiSelect = ({ options, name, placeholder = "", label, selected, setSele
</InputContainer>
{isOpen && (
<MenuContainer>
<Checkbox
options={[
{
label: isAllSelected ? "Tout désélectionner" : "Tout sélectionner",
nativeInputProps: {
name: `multiselect-${name}-select-all`,
checked: isAllSelected,
onChange: handleSelectAll,
},
},
]}
small
/>
{(search && formattedSearchedOptions.length) || (!search && formattedOptions.length) ? (
<Checkbox options={search ? formattedSearchedOptions : formattedOptions} small />
) : (
Expand Down

0 comments on commit 1a34de2

Please sign in to comment.