index.js 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { useEffect, useState } from 'react';
  2. import { arrayMoveImmutable } from 'array-move';
  3. import { DropZone } from '../DropZone';
  4. import { SortableList } from './SortableList';
  5. import { SortableItem } from './SortableItem';
  6. import { Box, Button, IconButton, ImageList, ImageListItem, ImageListItemBar, Typography } from '@mui/material';
  7. import { MdClose } from 'react-icons/md';
  8. import { backendURL } from '../../../helpers';
  9. export const EntityEditor = ({ entity = { images: [] }, onSave, onFileDrop, uploadFiles, onImagesSave }) => {
  10. const [state, setState] = useState(entity);
  11. useEffect(() => {
  12. setState(entity);
  13. console.log(entity.images);
  14. }, [entity]);
  15. useEffect(() => {
  16. if (uploadFiles?.status === 'FULFILLED') {
  17. setState({ ...state, images: [...(state.images || []), ...uploadFiles?.payload] });
  18. }
  19. }, [uploadFiles]);
  20. useEffect(() => {
  21. onImagesSave && onImagesSave(state.images?.filter((img) => img?._id && img?.url));
  22. }, [state]);
  23. const onSortEnd = ({ oldIndex, newIndex }) => {
  24. console.log(arrayMoveImmutable(state.images, oldIndex, newIndex));
  25. setState({ ...state, images: arrayMoveImmutable(state.images, oldIndex, newIndex) });
  26. };
  27. const onItemRemove = (toRemoveId) => {
  28. setState({ ...state, images: [...state.images.filter((el) => el?._id !== toRemoveId)] });
  29. };
  30. return (
  31. <Box className="EntityEditor">
  32. <DropZone onFileDrop={(files) => onFileDrop(files)}>
  33. <Typography>Drop images here!</Typography>
  34. </DropZone>
  35. <SortableList pressDelay={200} onSortEnd={onSortEnd} axis="xy" className="SortableContainer">
  36. <ImageList sx={{ maxHeight: 800 }} cols={3} fullwidth>
  37. {state.images?.map(
  38. (image, index) =>
  39. !!image?._id &&
  40. !!image?.url && (
  41. <SortableItem key={`item-${image._id}`} index={index}>
  42. <ImageListItem key={image._id}>
  43. <ImageListItemBar
  44. sx={{
  45. background: 'rgba(0,0,0,0.1)',
  46. }}
  47. actionIcon={
  48. <IconButton onClick={() => onItemRemove(image._id)}>
  49. <MdClose />
  50. </IconButton>
  51. }
  52. />
  53. <Box
  54. component="img"
  55. className="DropZoneImage"
  56. src={`${image.url}`}
  57. loading="lazy"
  58. />
  59. </ImageListItem>
  60. </SortableItem>
  61. )
  62. )}
  63. </ImageList>
  64. </SortableList>
  65. {!!onSave && (
  66. <Button
  67. onClick={() => {
  68. onSave(entity._id, state.images);
  69. }}
  70. >
  71. Save
  72. </Button>
  73. )}
  74. </Box>
  75. );
  76. };