import React from "react";
import { isFileDragEvent, isInputElement } from "./dom";

const dragEventsToPrevent: Array<keyof DocumentEventMap> = ["drop", "dragover"];

/**
 * Prevent files dragged and dropped onto the page from triggering the browser's
 * default behavior of navigating away and loading the dropped file.
 *
 * Example:
 *
 *   <PreventFileDropNavigateAway />
 *
 * This component has global effect, and can be rendered anywhere in in the
 * React tree. File form inputs are given special treatment to allow files to be
 * dropped onto the input.
 */
export class PreventFileDropNavigateAway extends React.Component {
  public componentDidMount() {
    for (const event of dragEventsToPrevent) {
      document!.addEventListener(event, preventFileDragEventDefault);
    }
  }

  public componentWillUnmount() {
    for (const event of dragEventsToPrevent) {
      document!.removeEventListener(event, preventFileDragEventDefault);
    }
  }

  public render() {
    return null;
  }
}

function preventFileDragEventDefault(e: Event): void {
  if (isFileDragEvent(e)) {
    const { target } = e;
    if (target !== null && (!isInputElement(target) || target.type !== "file")) {
      e.preventDefault();
    }
  }
}
