fix issues

This commit is contained in:
Red Adaya 2024-12-18 13:48:12 +08:00
parent 11c8723b37
commit d9b5f4f78b

View File

@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import React, { useState } from "react"; import React, { useState } from "react";
import "./MultiSelect.scss"; import "./multiselect.scss";
type Option = { type Option = {
label: string; label: string;
@ -11,7 +11,7 @@ type Option = {
type MultiSelectProps = { type MultiSelectProps = {
options: Option[]; options: Option[];
selectedValues?: string[]; // Pre-selected options selectedValues?: string[];
onChange: (values: string[]) => void; onChange: (values: string[]) => void;
}; };
@ -19,26 +19,43 @@ const MultiSelect: React.FC<MultiSelectProps> = ({ options, selectedValues = [],
const [selected, setSelected] = useState<string[]>(selectedValues); const [selected, setSelected] = useState<string[]>(selectedValues);
const handleToggle = (value: string) => { const handleToggle = (value: string) => {
const newSelected = selected.includes(value) setSelected((prevSelected) => {
? selected.filter((v) => v !== value) // Remove if already selected const newSelected = prevSelected.includes(value)
: [...selected, value]; // Add if not selected ? prevSelected.filter((v) => v !== value) // Remove if already selected
: [...prevSelected, value]; // Add if not selected
setSelected(newSelected);
onChange(newSelected); onChange(newSelected);
return newSelected;
});
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>, value: string) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
handleToggle(value);
}
}; };
return ( return (
<div className="multi-select"> <div className="multi-select" role="listbox" aria-multiselectable="true" aria-label="Multi-select list">
{options.map((option) => ( {options.map((option) => {
const isSelected = selected.includes(option.value);
return (
<div <div
key={option.value} key={option.value}
className={`option ${selected.includes(option.value) ? "selected" : ""}`} role="option"
aria-selected={isSelected}
className={`option ${isSelected ? "selected" : ""}`}
tabIndex={0}
onClick={() => handleToggle(option.value)} onClick={() => handleToggle(option.value)}
onKeyDown={(e) => handleKeyDown(e, option.value)}
> >
{option.label} {option.label}
{selected.includes(option.value) && <i className="fa fa-solid fa-check" />} {isSelected && <i className="fa fa-solid fa-check" aria-hidden="true" />}
</div> </div>
))} );
})}
</div> </div>
); );
}; };