@etsoo/materialui
Version:
TypeScript Material-UI Implementation
72 lines (71 loc) • 3.1 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React from "react";
import { DataTypes } from "@etsoo/shared";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import List from "@mui/material/List";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemText from "@mui/material/ListItemText";
/**
* Item list component
* @param props Properties
*/
export function ItemList(props) {
// properties destructure
const { buttonLabel, className, color = "primary", keepClick = false, items, idField = "id", labelField = "label", minWidth, icon, onClose, selectedValue, size = "medium", title, variant = "outlined" } = props;
// Get label
const getLabel = (item) => {
if (typeof labelField === "function") {
return labelField(item);
}
else {
return DataTypes.convert(item[labelField], "string") ?? "";
}
};
// Dialog open or not state
const [open, setOpen] = React.useState(false);
// Default state
const defaultItem = items.find((item) => item[idField] === selectedValue);
// Current item
const [currentItem, setCurrentItem] = React.useState(defaultItem);
// Click handler
const clickHandler = () => {
if (items.length < 1 ||
(items.length === 1 && !keepClick && defaultItem != null)) {
return;
}
// Open the dialog
setOpen(true);
};
// Close handler
const closeHandler = () => {
if (!open)
return;
// Close the dialog
setOpen(false);
// Emit close event
if (onClose) {
onClose(currentItem, false);
}
};
// Close item handler
const closeItemHandler = (item) => {
if (!keepClick) {
// Update the current item
setCurrentItem(item);
}
// Close the dialog
setOpen(false);
// Emit close event
if (onClose) {
onClose(item, true);
}
};
return (_jsxs(_Fragment, { children: [_jsx(Button, { className: className, variant: variant, startIcon: icon, color: color, size: size, onClick: clickHandler, children: buttonLabel ?? (currentItem ? getLabel(currentItem) : undefined) }), _jsxs(Dialog, { "aria-labelledby": "dialog-title", open: open, onClose: closeHandler, children: [title && _jsx(DialogTitle, { id: "dialog-title", children: title }), _jsx(DialogContent, { sx: { minWidth }, children: _jsx(List, { children: items.map((item) => {
const id = item[idField];
return (_jsx(ListItemButton, { disabled: id === (currentItem ? currentItem[idField] : undefined) &&
!keepClick, onClick: () => closeItemHandler(item), children: _jsx(ListItemText, { children: getLabel(item) }) }, id));
}) }) })] })] }));
}