EditItemButton.jsx 2.2 KB

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