Source: pages-sections/Foodhealth-sections/LocalStorageInput.js

import React, { useState } from "react";
import Button from "/components/CustomButtons/Button.js";

/**
 * The `LocalStorageInput` function is a React component that allows users to browse and select images
 * from their local storage.
 * @returns The `LocalStorageInput` component is being returned. It is a functional component that
 * allows users to browse and select an image from their local storage. The component contains a button
 * labeled "Browse Locally" that triggers the `handleBrowseClick` function when clicked. This function
 * opens a file input dialog for the user to select an image file. Once an image is selected, it is
 * displayed and passed to
 */
export function LocalStorageInput({ onImageSelect }) {
  const [picture, setPicture] = useState(null);

  return (
    <div>
      <div
        style={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <Button color="info" onClick={handleBrowseClick}>
          Browse Locally
        </Button>
      </div>
    </div>
  );
}
/**
 * The `browseLocalStorage` function allows users to select an image file from their local storage
 * and returns a Promise that resolves with the image data in base64 format.
 * @returns A Promise is being returned from the `browseLocalStorage` function.
 */
export const browseLocalStorage = () => {
  return new Promise((resolve, reject) => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";

    input.onchange = (event) => {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (event) => {
        const picture = event.target.result;
        resolve(picture);
      };
      reader.onerror = (event) => {
        reject(new Error("Failed to read the file"));
      };
      reader.readAsDataURL(file);
    };

    input.click();
  });
};
/**
 * The `handleBrowseClick` function asynchronously retrieves a picture from local storage, sets the
 * picture, and calls the `onImageSelect` function with the selected picture.
 */
export const handleBrowseClick = async () => {
  try {
    const picture = await browseLocalStorage();
    setPicture(picture);
    onImageSelect(picture);
  } catch (error) {
    console.error(error);
  }
};
/**
 * The `handleDiscardClick` function sets the `picture` state to null.
 */
export const handleDiscardClick = () => {
  setPicture(null);
};