EditItemButton.jsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import React from "react";
  2. import styled from "styled-components";
  3. import { useTranslation } from "react-i18next";
  4. import SidePanel from "../../ui/SidePanel";
  5. import ItemFormFactory from "./ItemFormFactory";
  6. import { useItemActions, useSelectedItems, useItems } from "react-sync-board";
  7. const CardContent = styled.div.attrs(() => ({ className: "content" }))`
  8. display: flex;
  9. flex-direction: column;
  10. padding: 0.5em;
  11. `;
  12. const EditItemButton = ({ showEdit, setShowEdit }) => {
  13. const { t } = useTranslation();
  14. const items = useItems();
  15. const selectedItems = useSelectedItems();
  16. const { batchUpdateItems } = useItemActions();
  17. const currentItems = React.useMemo(
  18. () => items.filter(({ id }) => selectedItems.includes(id)),
  19. [items, selectedItems]
  20. );
  21. const onSubmitHandler = React.useCallback(
  22. (formValues) => {
  23. batchUpdateItems(selectedItems, (item) => {
  24. if (formValues.item) {
  25. // Merge subitem for generator
  26. return {
  27. ...item,
  28. ...formValues,
  29. item: { ...item.item, ...formValues.item },
  30. };
  31. } else {
  32. return { ...item, ...formValues };
  33. }
  34. });
  35. },
  36. [batchUpdateItems, selectedItems]
  37. );
  38. let title = "";
  39. if (selectedItems.length === 1) {
  40. title = t("Edit item");
  41. }
  42. if (selectedItems.length > 1) {
  43. title = t("Edit all items");
  44. }
  45. return (
  46. <>
  47. <button
  48. className="button clear icon-only"
  49. onClick={() => setShowEdit((prev) => !prev)}
  50. title={t("Edit")}
  51. >
  52. {!showEdit && (
  53. <img
  54. src="https://icongr.am/feather/edit.svg?size=32&color=ffffff"
  55. alt={t("Edit")}
  56. />
  57. )}
  58. {showEdit && (
  59. <img
  60. src="https://icongr.am/feather/edit.svg?size=32&color=db5034"
  61. alt={t("Edit")}
  62. />
  63. )}
  64. </button>
  65. <SidePanel
  66. key={selectedItems[0]}
  67. open={showEdit}
  68. onClose={() => {
  69. setShowEdit(false);
  70. }}
  71. title={title}
  72. width="25%"
  73. >
  74. <CardContent>
  75. <ItemFormFactory onUpdate={onSubmitHandler} items={currentItems} />
  76. </CardContent>
  77. </SidePanel>
  78. </>
  79. );
  80. };
  81. export default EditItemButton;