@etsoo/materialui
Version:
TypeScript Material-UI Implementation
56 lines (55 loc) • 2.33 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import Checkbox from "@mui/material/Checkbox";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import React from "react";
function GetListItemLabel(data, label) {
if (label == null)
return undefined;
if (typeof label === "function") {
return label(data);
}
else {
return data[label];
}
}
/**
* List multipler component
* @param props Props
* @returns Component
*/
export function ListMultipler(props) {
// Destruct
const { data, idField, primaryLabel, secondaryLabel, listItemProps, listItemTextProps, name, onCheckItems, ...rest } = props;
// Refs
const initialized = React.useRef(false);
React.useEffect(() => {
initialized.current = true;
}, []);
// State
const [checked, setChecked] = React.useState([]);
const ids = React.useMemo(() => {
const ids = checked.map((u) => u[idField]);
if (onCheckItems && initialized.current) {
onCheckItems(checked, ids);
}
return ids;
}, [checked]);
function handleToggle(id) {
if (ids.includes(id)) {
setChecked((prev) => prev.filter((u) => u[idField] !== id));
}
else {
const item = data.find((u) => u[idField] === id);
if (item) {
setChecked((prev) => [...prev, item]);
}
}
}
const inputType = typeof ids[0] === "string" ? "text" : "number";
// Layout
return (_jsxs(List, { ...rest, children: [name && (_jsx("input", { type: inputType, style: { display: "none" }, name: name, value: ids.join(","), readOnly: true })), data.map((u) => (_jsx(ListItem, { ...listItemProps, children: _jsxs(ListItemButton, { dense: true, onClick: () => handleToggle(u[idField]), children: [_jsx(ListItemIcon, { children: _jsx(Checkbox, { edge: "start", disableRipple: true, checked: ids.includes(u[idField]) }) }), _jsx(ListItemText, { primary: GetListItemLabel(u, primaryLabel), secondary: GetListItemLabel(u, secondaryLabel), ...listItemTextProps })] }) }, `${u[idField]}`)))] }));
}