Chonky icon indicating copy to clipboard operation
Chonky copied to clipboard

I want to create a confirmation popup when deleting files and folders. How can I do that?

Open Ryanstemkoski1 opened this issue 2 years ago • 1 comments

I want to create a confirmation popup when deleting files and folders. How can I do that?

Ryanstemkoski1 avatar Apr 01 '22 17:04 Ryanstemkoski1

I did this by adding a component to the file action handler that listens for a custom event, and displays a dialog. The component returns a promise and if resolved with true, it proceeds with the desired action. If resolved with false, it just skips the deletion. You can use it like this:

  const ok = await dispatchConfirmationDialogEvent({
            message: "Are sure you want to delete this?",
          });
          if (ok) delete(data);
        } else {
          return;
        }

And this is its implementation:

import { useState, useEffect } from "react";
import { Dialog, DialogActions, DialogContent } from "@mui/material";
import IconButton from "@mui/material/IconButton";
import CloseIcon from "@mui/icons-material/Close";
import CheckMark from "@mui/icons-material/Check";
interface SnackbarMessage {
  message: string;
}

export function dispatchConfirmationDialogEvent({ message }: SnackbarMessage) {
  return new Promise((resolve, reject) => {
    window.dispatchEvent(
      new CustomEvent("Confirmation-Dialog", {
        detail: { message, resolve },
      })
    );
  });
}

export function ConfirmationListener() {
  const [open, setOpen] = useState(false);
  const [msg, setMsg] = useState("");
  const [res, setRes] = useState("") as any;

  useEffect(() => {
    const _cb = (e: CustomEvent) => {
      const { message, resolve }: any = e.detail;
      setMsg(message);
      setOpen(true);
      setRes(() => resolve);
    };

    window.addEventListener("Confirmation-Dialog", _cb as EventListener);
    return () => {
      window.removeEventListener(
        "PM-Confirmation-Dialog",
        _cb as EventListener
      );
    };
  }, []);

  return (
    <Dialog open={open} sx={{ minWidth: 800 }}>
      <DialogContent>{msg}</DialogContent>

      <DialogActions>
        <IconButton
          color="primary"
          onClick={() => {
            setOpen(false);
            if (res) res(false);
          }}
        >
          <CloseIcon />
        </IconButton>
        <IconButton
          color="primary"
          onClick={() => {
            setOpen(false);
            if (res) res(true);
          }}
        >
          <CheckMark />
        </IconButton>
      </DialogActions>
    </Dialog>
  );
}

ptourlas avatar May 17 '22 09:05 ptourlas