ImageField.jsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import React from "react";
  2. import { useTranslation } from "react-i18next";
  3. import styled from "styled-components";
  4. import { MediaLibraryButton, media2Url } from "./";
  5. import backgroundGrid from "../../images/background-grid.png";
  6. const StyledImageField = styled.div`
  7. & .typeSelect {
  8. padding: 0.5em;
  9. }
  10. & .imgContainer {
  11. margin: 0 1em;
  12. position: relative;
  13. display: flex;
  14. justify-content: center;
  15. align-items: center;
  16. flex-direction: column;
  17. gap: 0.5em;
  18. }
  19. `;
  20. const Thumbnail = styled.img`
  21. max-height: 100px;
  22. display: block;
  23. background-image: url(${backgroundGrid});
  24. `;
  25. const ImageField = ({ value, onChange }) => {
  26. const { t } = useTranslation();
  27. let type, content;
  28. // Manage compat with old version
  29. if (typeof value === "object") {
  30. type = value.type;
  31. content = value.content;
  32. } else {
  33. if (value) {
  34. type = "external";
  35. content = value;
  36. } else {
  37. type = "empty";
  38. content = null;
  39. }
  40. }
  41. const handleInputChange = (e) => {
  42. onChange({ type, content: e.target.value });
  43. };
  44. const handleTypeChange = (e) => {
  45. onChange({ type: e.target.value, content: "" });
  46. };
  47. const handleMediaSelect = (key) => {
  48. onChange({ type: "local", content: key });
  49. };
  50. const url = media2Url(value);
  51. return (
  52. <StyledImageField>
  53. <form className="typeSelect">
  54. <label>
  55. <input
  56. type="radio"
  57. value="empty"
  58. onChange={handleTypeChange}
  59. checked={type === "empty"}
  60. />
  61. {t("No image")}
  62. </label>
  63. <label>
  64. <input
  65. type="radio"
  66. value="local"
  67. onChange={handleTypeChange}
  68. checked={type === "local"}
  69. />
  70. {t("Library")}
  71. </label>
  72. <label>
  73. <input
  74. type="radio"
  75. value="external"
  76. checked={type === "external"}
  77. onChange={handleTypeChange}
  78. />
  79. {t("External")}
  80. </label>
  81. </form>
  82. <div className="imgContainer" onClick={(e) => e.preventDefault()}>
  83. {type !== "empty" && content && <Thumbnail src={url} />}
  84. {type === "external" && (
  85. <input
  86. value={content}
  87. placeholder={t("Enter an image url...")}
  88. onChange={handleInputChange}
  89. />
  90. )}
  91. {type === "local" && (
  92. <MediaLibraryButton
  93. onSelect={handleMediaSelect}
  94. label={content ? t("Change image") : t("Select image")}
  95. />
  96. )}
  97. </div>
  98. </StyledImageField>
  99. );
  100. };
  101. export default ImageField;