@material-ui/icons#AttachFile JavaScript Examples

The following examples show how to use @material-ui/icons#AttachFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Chat.js    From Chathub with MIT License 4 votes vote down vote up
function Chat() {
  const [input, setInput] = useState("");
  const [seed, setSeed] = useState("");
  const { roomId } = useParams();
  const [roomName, setRoomName] = useState("");
  const [messages, setMessages] = useState([]);
  const [{ user }] = useStateValue();
  const chatBodyRef = useRef(null);
  const inputRef = useRef(null);
  const [showEmoji, setEMoji] = useState(false);

  const [open, setOpen] = useState(false);
  const [fileObjects, setFileObjects] = useState([]);

  const upload = () => {
    if (fileObjects == null) return;
    storage
      .ref(`/files/${fileObjects}`)
      .put(fileObjects)
      .on("state_changed", alert("success"), alert);
  };

  const dialogTitle = () => (
    <>
      <span>Upload file</span>
      <IconButton
        style={{ right: "12px", top: "8px", position: "absolute" }}
        onClick={() => setOpen(false)}
      >
        <CloseIcon />
      </IconButton>
    </>
  );

  useEffect(() => {
    if (roomId) {
      db.collection("rooms")
        .doc(roomId)
        .onSnapshot((snapshot) => setRoomName(snapshot.data().name));

      db.collection("rooms")
        .doc(roomId)
        .collection("messages")
        .orderBy("timestamp", "asc")
        .onSnapshot((snapshot) =>
          setMessages(snapshot.docs.map((doc) => doc.data()))
        );
    }
  }, [roomId]);

  useEffect(() => {
    setSeed(Math.floor(Math.random() * 5000));
  }, [roomId]);

  useEffect(() => {
    chatBodyRef.current.scrollTop = chatBodyRef.current.scrollHeight;
  });
  const toggleEMoji = () => {
    sEmoji();
  };
  const sEmoji = (e) => {
    setEMoji(!showEmoji);
  };
  const addEmoji = (e) => {
    sEmoji();
    let emoji = e.native;
    setInput(input + emoji);
  };
  const sendMessage = (e) => {
    e.preventDefault();
    db.collection("rooms").doc(roomId).collection("messages").add({
      message: input,
      name: user.displayName,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });

    setInput("");
  };

  const copyToClipBoard = (e) => {
    e.preventDefault();
    inputRef.current.select();
    document.execCommand("copy");
  };

  return (
    <div className="chat">
      <div className="chat__header">
        <Avatar src={`https://avatars.dicebear.com/api/human/${seed}.svg`} />
        <div className="chat__headerInfo">
          <h3 className="chat-room-name">{roomName}</h3>
          <p className="chat-room-last-seen">
            Last seen{" "}
            {new Date(
              messages[messages.length - 1]?.timestamp?.toDate()
            ).toUTCString()}
          </p>
        </div>
        <div className="chat__headerRight">
          <IconButton>
            <SearchOutlined />
          </IconButton>

          <IconButton onClick={() => setOpen(true)}>
            <AttachFile />
          </IconButton>
          <DropzoneDialogBase
            dialogTitle={dialogTitle()}
            acceptedFiles={[]}
            fileObjects={fileObjects}
            cancelButtonText={"cancel"}
            submitButtonText={"submit"}
            maxFileSize={5000000}
            open={open}
            onAdd={(newFileObjs) => {
              console.log("onAdd", newFileObjs);
              setFileObjects([].concat(fileObjects, newFileObjs));
            }}
            onDelete={(deleteFileObj) => {
              console.log("onDelete", deleteFileObj);
            }}
            onClose={() => setOpen(false)}
            onSave={() => {
              console.log("onSave", fileObjects);
              upload();
              setOpen(false);
            }}
            showPreviews={true}
            showFileNamesInPreview={true}
          />
          <IconButton>
            <MoreVert />
          </IconButton>
        </div>
      </div>
      <div className="chat__body" ref={chatBodyRef}>
        {messages.map((message) => (
          <p
            className={`chat__message ${
              message.name === user.displayName && "chat__receiver"
            }`}
          >
            <span className="chat__name">{message.name}</span>
            {message.message}
            {/*{fileObjects.length > 0 && (
              <div className="chat__name">
                {message.name}
                {fileObjects.length}
              </div>
            )}*/}
            <span className="chat__timestamp">
              {" "}
              {new Date(message.timestamp?.toDate()).toUTCString()}
            </span>
          </p>
        ))}
      </div>

      <div className="chat__footer">
        {showEmoji ? (
          <Picker onSelect={addEmoji} emojiTooltip={true} title="Chathub" />
        ) : null}
        <button
          type="button"
          style={{ cursor: "pointer", background: "none" }}
          className="toggle-emoji"
          onClick={toggleEMoji}
        >
          <InsertEmoticonIcon />
        </button>
        <form>
          <input
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            type="text"
            placeholder="Type a message"
          />
          <button type="submit" onClick={sendMessage}>
            {" "}
            Send a Message
          </button>
        </form>

        <Tooltip title="Copy">
          <AssignmentIcon onClick={copyToClipBoard} />
        </Tooltip>

        <MicIcon />
      </div>
    </div>
  );
}
Example #2
Source File: WebChatRoomHeaderView.js    From WhatsApp-Clone with MIT License 4 votes vote down vote up
WebChatRoomHeaderView = ({ item, isNewChat }) => {
  // console.log("isNewChat =>", isNewChat);
  const [userType, setUserType] = React.useState("");
  const [displayLastSeen, setDisplayLastSeen] = React.useState("");
  const [apiLastSeen, setApiLastSeen] = React.useState("");
  let styles = useStyles();

  let data = item.chat[0];

  useEffect(() => {
    populateUserType();
    listenUserLastSeen();
    getUserLastSeen();
  }, [item]);

  useEffect(() => {
    if (apiLastSeen != "") {
      calcLastSeen(apiLastSeen);
    }
  }, [apiLastSeen]);

  const populateUserType = () => {
    let userType = getUserType(item);
    setUserType(userType);
  };

  async function getUserLastSeen() {
    let userId = getLocalData(webConstants.USER_ID);
    // This to get id of the other user
    let id = data.userId === userId ? data.chatId : data.userId;
    let request = { id: id };
    let res = getLastSeenUser(request);
    res
      .then((lastSeen) => {
        if (lastSeen) {
          // console.log("User Last Seen ==> ", JSON.stringify(lastSeen));
          setApiLastSeen(lastSeen.data.lastSeen[0]);
        }
      })
      .catch((err) => {
        console.log("User Last Seen ==> ", err);
      });
  }

  function listenUserLastSeen() {
    socket.on(webConstants.LAST_SEEN, (status) => {
      // console.log("App Status == ", status);
      let newStatus = {
        userId: status.userId,
        userName: status.userName,
        status: status.status,
        lastSeen: status.lastSeen,
      };

      let id = getLocalData(webConstants.USER_ID);
      if (status.userId != id) {
        calcLastSeen(newStatus);
      } else {
        // setDisplayLastSeen("");
      }
    });
    sendPageLoadStatus();
  }

  async function calcLastSeen(lastSeen) {
    if (lastSeen) {
      if (lastSeen.userId === data.userId || lastSeen.userId === data.chatId) {
        let time =
          lastSeen.status === "Offline"
            ? `Last seen at ${getDateTimeInFormat(lastSeen.lastSeen)}`
            : lastSeen.status;
        setDisplayLastSeen(time);
      } else if (apiLastSeen != "") {
        let time = `Last seen at ${getDateTimeInFormat(apiLastSeen.lastSeen)}`;
        setDisplayLastSeen(time);
      }
    } else {
      // User last seen not available yet
      setApiLastSeen("");
      setDisplayLastSeen("");
    }
  }

  return (
    <div className={styles.parentView} elevation={webConstants.PAPER_ELEVATION}>
      <div
        style={{
          width: "5%",
          marginLeft: "1%",
          alignSelf: "center",
          marginTop: "0.2%",
        }}
      >
        <Avatar src={chatImage} className={styles.profileIcon} />

        {/* <chatImage width={40} height={40} style={styles.profileIcon} /> */}
      </div>
      <div
        style={{
          display: "flex",
          width: "76%",
          flexDirection: "column",
          marginLeft: "1%",
          alignSelf: "center",
        }}
      >
        <Typography className={styles.userName}>
          {userType == webConstants.FRIEND ? data.userName : data.chatName}
        </Typography>
        <Typography className={styles.userMessage}>
          {displayLastSeen}
        </Typography>
      </div>
      <div
        style={{
          width: "19%",
          display: "flex",
          flexDirection: "row",
          justifyContent: "space-evenly",
        }}
      >
        <Search className={styles.menuIcons} />
        <AttachFile className={styles.menuIcons} />
        <MoreVert className={styles.menuIcons} />
      </div>
    </div>
  );
}