react-virtualized#CellMeasurer JavaScript Examples

The following examples show how to use react-virtualized#CellMeasurer. 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: index.js    From AED-Map with MIT License 4 votes vote down vote up
ItemList = ({
  isLoading,
  defibrillators,
  activeDef,
  fetchDefItems,
  filter,
  totalCount,
  page,
  search,
  setMapCenterCoords,
  setMapZoomParam
}) => {
  const classes = useStyles();
  const noData = !isLoading && !defibrillators.length;
  const showMessage =
    (isLoading && !defibrillators.length) || noData;
  const showHorizontalLoader =
    isLoading && !!defibrillators.length;
  let message;

  switch (true) {
    case isLoading:
      message = 'Завантаження...';
      break;
    case noData:
      message = 'Даних не знайдено...';
      break;
    default:
      message = '';
  }

  const cache = new CellMeasurerCache({
    fixedWidth: true,
    defaultHeight: 100
  });

  const handleScroll = event => {
    const { scrollHeight, scrollTop, clientHeight } = event;

    if (
      totalCount >= page &&
      scrollHeight - Math.ceil(scrollTop) <= clientHeight
    ) {
      fetchDefItems({ page, ...filter, ...search });
    }
  };

  // eslint-disable-next-line react/prop-types
  const rowRenderer = ({ key, index, style, parent }) => {
    return (
      <CellMeasurer //  dynamically calculates the height of every item
        key={key}
        cache={cache}
        parent={parent}
        columnIndex={0}
        rowIndex={index}
      >
        <DefItem
          styleParam={style}
          defItemInfo={defibrillators[index]}
        />
      </CellMeasurer>
    );
  };

  useEffect(() => {
    if (!defibrillators.length) {
      fetchDefItems();
    }
    return () => {
      defsCancelToken.cancel();
    };
    // eslint-disable-next-line
  }, []);

  useEffect(() => {
    if (activeDef) {
      const [lng, lat] = activeDef.location.coordinates;
      setMapCenterCoords({
        lng,
        lat
      });
      setMapZoomParam(BASE_ZOOM_VALUE);
    }
    // eslint-disable-next-line
  }, [activeDef]);

  return (
    <div className={classes.listOuterStyle}>
      <AutoSizer>
        {({ width, height }) => {
          //  AutoSizer expands list to width and height of parent automatically
          return (
            <List
              onScroll={handleScroll}
              className={classes.listStyle}
              width={width}
              height={height}
              deferredMeasurementCache={cache}
              rowCount={defibrillators.length}
              rowHeight={cache.rowHeight}
              rowRenderer={rowRenderer}
              overscanRowCount={10}
            />
          );
        }}
      </AutoSizer>
      {showMessage && <InfoMessage>{message}</InfoMessage>}
      {showHorizontalLoader && <HorizontalLoader />}
    </div>
  );
}
Example #2
Source File: WebChatListView.js    From WhatsApp-Clone with MIT License 4 votes vote down vote up
WebChatListView = ({ onItemClick, userChatList }) => {
  var [state, dispatch] = useReducer(chatListReducer, initialChatListState);

  var { chatList, chatItem, refresh, userId } = state;

  useEffect(() => {
    listenSocket();
  }, []);

  useEffect(() => {
    if (refresh) {
      getLatestChats();
    }
  }, [refresh]);

  useEffect(() => {
    // console.log("Chat List Changed == ", JSON.stringify(chatList));
    if (chatItem != "") {
      renderChats();
    }
  }, [chatItem]);

  function getUserId() {
    const userId = getLocalData(webConstants.USER_ID);
    dispatch({ type: webConstants.USER_ID, payload: userId });
    return userId;
  }

  const getLatestChats = () => {
    getUserId();
    getChatList()
      .then((res) => {
        // console.log("LIST RESPONSE => " + JSON.stringify(res.data.data));
        if (res.status === 200) {
          userChatList(res.data.data);
          dispatch({ type: CHAT_LIST, payload: res.data.data });
        }
        dispatch({ type: REFRESH, payload: false });
      })
      .catch((error) => {
        console.log("ERROR ", error);
      });
  };

  async function renderChats() {
    let chatArray = chatList;
    console.log("Message CHAT Received => ", JSON.stringify(chatItem));

    var isMatch = false;
    if (chatArray.length > 0) {
      for (let i = 0; i < chatArray.length; i++) {
        const element = chatArray[i];
        if (chatItem && element.roomId === chatItem.roomId) {
          // Increment unread count
          chatItem = await calcUnreadCount(chatItem, element.chatUnreadCount);

          // Since chat item received is an object to convert it to array and they re initialise
          // if (chatItem.chat.length <= 0) {
          chatItem.chat = [chatItem.chat];
          // }
          console.log("Selected Chat Received => ", JSON.stringify(chatItem));
          chatArray[i] = chatItem;
          isMatch = true;
          break;
        }
      }

      if (!isMatch && chatItem.chatUnreadCount.type != 'reset') {
        // Increment unread count
        chatItem = await calcUnreadCount(chatItem, 0);

        // Since chat item received is an object to convert it to array and they re initialise
        // if (chatItem.chat.length <= 0) {
        chatItem.chat = [chatItem.chat];
        // }
        console.log("Selected Chat Received => ", JSON.stringify(chatItem));
        chatArray.push(chatItem);
      }

      console.log("Message CHAT AFTER Received => ", JSON.stringify(chatItem));

      dispatch({ type: CHAT_LIST, payload: chatArray });
      console.log(
        `FINAL CHAT ARRAY ${refresh} => `,
        "JSON.stringify(chatArray)"
      );
    } else {
      // For new chat
      if (chatItem.chatUnreadCount.type === "add") {
        dispatch({ type: REFRESH, payload: true });
      }
    }
  }

  function listenSocket() {
    // socket.removeListener(webConstants.CHAT_LIST);
    socket.on(webConstants.CHAT_LIST, (chatItem) => {
      dispatch({ type: CHAT_ITEM, payload: chatItem });
    });
  }

  function calcUnreadCount(chatItem, originalCount) {
    // const userId = getLocalData(webConstants.USER_ID);
    if (chatItem.chatUnreadCount.userId != userId) {
      if (chatItem.chatUnreadCount.type === "reset") {
        chatItem.chatUnreadCount = 0;
      } else if (chatItem.chatUnreadCount.type === "add") {
        chatItem.chatUnreadCount = originalCount ? originalCount + 1 : 1;
      } else {
        chatItem.chatUnreadCount = 0;
      }
    } else if (chatItem.chatUnreadCount.type === "reset") {
      chatItem.chatUnreadCount = 0;
    } else {
      chatItem.chatUnreadCount = originalCount;
    }
    return chatItem;
  }

  return (
    <div
      style={{
        flex: 1,
        width: "100%",
        borderRadius: 0,
        backgroundColor: WHITE,
      }}
    >
      {chatList.length === 0 && (
        <EmptyComponent message={"No chats, contacts or messages found"} />
      )}

      <List
        style={{
          height: "100%",
          width: "100%",
          outline: "none",
        }}
        rowCount={chatList.length}
        height={window.innerHeight}
        width={window.innerWidth - window.innerWidth / 3.2}
        rowHeight={cache.rowHeight}
        rowRenderer={({ index, parent, key, style }) => (
          <CellMeasurer
            key={key}
            cache={cache}
            parent={parent}
            columnIndex={0}
            rowIndex={index}
          >
            <WebChatListItem
              item={chatList[index]}
              position={index}
              onItemClick={onItemClick}
            />
          </CellMeasurer>
        )}
        overscanRowCount={0}
        data={refresh}
      />

      {/* {chatList.map(function(item, i) {
        return (
          <WebChatListItem item={item} position={i} onItemClick={onItemClick} />
        );
      })} */}
      {/* <Button className={classes.btnView}>
        <img src={CHAT} className={classes.thumbView} />
      </Button> */}
    </div>
  );
}
Example #3
Source File: WebChatRoomView.js    From WhatsApp-Clone with MIT License 4 votes vote down vote up
ChatRoomView = ({ chatItem, isNewChat }) => {
  const [chatRoomList, setChatRoomList] = useState([]);
  const [userId, setUserId] = useState("");
  const [refresh, setRefresh] = useState(false);
  const [roomId, setRoomId] = useState("");
  const [height, setHeight] = useState(80);
  const [message, setMessage] = useState("");
  const flatList = useRef();
  const inputRef = useRef();

  const cache = new CellMeasurerCache({
    fixedWidth: true,
    defaultHeight: 80,
  });

  // This side effect is for refreshing socket data
  useEffect(() => {
    if (message != "") {
      renderChats();
    }
  }, [message]);

  // This side effect is for refreshing various chat users
  useEffect(() => {
    if (chatItem != "") {
      fetchChatRoomMessages();
      // setRefresh(!refresh);
    }
  }, [chatItem]);

  // This side effect is for geting userid first
  useEffect(() => {
    getUser();
    listenSocket([]);
  }, [refresh]);

  // When user id is retrived this side effect is invoked
  useEffect(() => {
    fetchChatRoomMessages();
  }, [userId]);

  function fetchChatRoomMessages() {
    let req = {
      roomId: chatItem.roomId,
      userId: userId,
    };
    getChatRoom(req)
      .then((res) => {
        // console.log('RESPONSE => ' + JSON.stringify(res.data));
        if (res.status === 200 && res.data && res.data.data.length > 0) {
          var chatArray = res.data.data[0].chat;
          // chatArray.reverse(); // In case of web reverse is not required
          setChatRoomList(chatArray);
        } else {
          setChatRoomList([]);
        }
      })
      .catch((error) => {
        console.log("ERROR ", error);
        setChatRoomList([]);
      });
  }

  function getUser() {
    const userId = getLocalData(webConstants.USER_ID);
    setUserId(userId);
  }

  function listenSocket() {
    socket.removeListener(webConstants.CHAT_ROOM);
    socket.on(webConstants.CHAT_ROOM, (message) => {
      console.log("Message ROOM Received => ", JSON.stringify(message));
      setMessage(message);
    });
  }

  function renderChats() {
    // If message received invloves user then only add to list else ignore
    if (message.userId === userId || message.chatId === userId) {
      setRefresh(true);
      if (!chatRoomList) {
        chatRoomList = [];
      }
      setVirtualData(chatRoomList, message);
      setTimeout(() => {
        setRefresh(false);
      }, 1000);
    }
  }

  function setVirtualData(chatArray, message) {
    // chatArray.reverse();
    message != "" && chatArray.push(message.chat);
    // message != "" && chatArray.reverse();
    setChatRoomList(chatArray);
    flatList.current.forceUpdate();

    // flatList.current.scrollToRow(chatArray.length);
    // flatList.current.measureAllRows()
    setTimeout(() => {
      flatList.current.measureAllRows();
      flatList.current.scrollToRow(chatArray.length);
    }, 1500);
  }

  const onSendMessage = (text) => {
    if (text != "") {
      // var chatId = chatItem.chatId;
      // if (isNewChat) {
      //   chatId = chatItem.chatId;
      // } else {

      // const userType = getUserTypeChatRoom(chatItem, userId);
      // const mChatId =
      //   userType === webConstants.OWNER ? chatItem.chatId : chatItem.userId;
      // const mUserId =
      //   userType === webConstants.OWNER ? chatItem.userId : chatItem.chatId;

      // isNewChat = chatRoomList.length === 0 ? true : false;

      // const chatRequest = {
      //   isNewChat: isNewChat,
      //   roomId: chatItem.roomId,
      //   userId: chatItem.userId,
      //   chatId: chatItem.chatId,
      //   chat: {
      //     userId: mUserId,
      //     userName: chatItem.chat[0].userName,
      //     chatId: mChatId,
      //     chatName: chatItem.chat[0].chatName,
      //     chatMessage: text,
      //     chatNumber: chatItem.chat[0].chatNumber,
      //     chatImage: chatItem.chat[0].chatImage,
      //     chatTime: moment().format(),
      //     chatDelivery: 0,
      //     chatUnreadCount: 0
      //   }
      // };

      // console.log('CHAT chatItem => ', JSON.stringify(chatItem));
      // console.log('CHAT MESSAGE => ', JSON.stringify(chatRequest));

      isNewChat = chatRoomList.length === 0 ? true : false;
      let chatRequest = getChatRoomChatModel(chatItem, isNewChat, userId, text);

      socket.emit(webConstants.CHAT_ROOM, chatRequest);

      chatRequest.chatUnreadCount = {
        userId: userId,
        type: "add",
        count: 1,
      };

      if (chatRequest.roomId === "") {
        chatRequest.roomId = roomId;
      }

      const res = isNewChat
        ? createChatRoom(chatRequest)
        : updateChatRoom(chatRequest);
      res
        .then((res) => {
          console.log("CHAT ROOM RESPONSE=> ", JSON.stringify(res));
          chatRequest.roomId = res.data.id;
          setRoomId(chatRequest.roomId);

          // chatRequest.chat.chatUnreadCount = chatRequest.chat.chatUnreadCount + 1;
          // chatRequest.chatUnreadCount = {
          //   userId : userId,
          //   type: "add",
          //   count: 1
          // };
          socket.emit(webConstants.CHAT_LIST, chatRequest);
        })
        .catch((err) => {
          console.log("CHAT ROOM ERROR => ", JSON.stringify(err));
        });
    }
  };

  function modifyRowHeight(event) {
    if (event.target.value != "") {
      setHeight(inputRef.current.clientHeight);
      if (chatRoomList.length > 0) {
        setTimeout(() => {
          flatList.current.measureAllRows();
        }, 1500);
        flatList.current.scrollToRow(chatRoomList.length);
      }
    } else {
      setTimeout(() => {
        setHeight(inputRef.current.clientHeight);
        flatList.current.measureAllRows();
        flatList.current.scrollToRow(chatRoomList.length);
      }, 200);
    }
  }

  const rowRenderer = ({ index, parent, key, style, isScrolling }) => {
    var item = chatRoomList[index];
    let userType = getUserTypeChatRoom(item, userId);
    if (userType === webConstants.OWNER) {
      // if (isScrolling) {
      //   return null;
      // }

      return (
        <CellMeasurer
          key={key}
          cache={cache}
          parent={parent}
          columnIndex={0}
          rowIndex={index}
        >
          <ChatRoomRightItem item={item} styleList={style} />
        </CellMeasurer>
      );
    } else {
      return (
        <CellMeasurer
          key={key}
          cache={cache}
          parent={parent}
          columnIndex={0}
          rowIndex={index}
        >
          <ChatRoomLeftItem item={item} styleList={style} />
        </CellMeasurer>
      );
    }
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        width: "100%",
        background: "url(" + WhatsapBG + ")",
        height: "92%",
      }}
    >
      <div
        style={{
          backgroundColor: "#E4DDD6",
          height: "100%",
          zIndex: "100",
          opacity: "0.95",
        }}
      />

      {/* <div
        style={{
          background: "url(" + WhatsapBG + ")",
          width: "100%",
          height: "90%"
        }}
      > */}
      <div
        style={{
          position: "absolute",
          zIndex: "1000",
          height: "92%",
          width: "70%",
        }}
      >
        <List
          ref={flatList}
          style={{
            height: "100%",
            width: "100%",
            outline: "none",
            paddingBottom: height === "" ? 80 : height,
            paddingTop: 10,
          }}
          rowCount={chatRoomList.length}
          height={window.innerHeight - 120}
          width={window.innerWidth - window.innerWidth / 3.2}
          rowHeight={cache.rowHeight}
          deferredMeasurementCache={cache}
          rowRenderer={rowRenderer}
          scrollToAlignment={"end"}
          data={refresh}
        />
      </div>

      <div
        ref={inputRef}
        style={{
          position: "fixed",
          zIndex: "2000",
          width: "70%",
          marginBottom: 0,
          resize: "vertical",
          bottom: 0,
          maxHeight: 160,
          minHeight: 60,
          overflow: "hidden",
        }}
      >
        <ChatTextInput
          onSendMessage={(text) => onSendMessage(text)}
          onTyping={(event) => {
            modifyRowHeight(event);
          }}
        />
      </div>
    </div>
  );

  function renderRow(item) {
    let userType = getUserTypeChatRoom(item, userId);
    if (userType === webConstants.OWNER) {
      return <ChatRoomRightItem item={item} />;
    } else {
      return <ChatRoomLeftItem item={item} />;
    }
  }
}
Example #4
Source File: WebContactsView.js    From WhatsApp-Clone with MIT License 4 votes vote down vote up
WebContactsView = ({ onChatCloseClick, onItemClick }) => {
  const [contacts, setContacts] = useState([]);

  useEffect(() => {
    getRegisteredUsers();
  }, []);

  const getRegisteredUsers = () => {
    getLoggedInUserList()
      .then(async (res) => {
        console.log("User List Response => ", res.data);
        if (res.data.success) {
          var userList = res.data.data;
          var ownerID = await getLocalData(webConstants.USER_ID);

          for (let index = 0; index < userList.length; index++) {
            const user = userList[index];
            if (user.userId === ownerID) {
              userList.splice(index, 1);
            }
          }
          setContacts(userList);
        }
      })
      .catch((err) => {
        console.log("User List Error => ", err);
      });
  };

  return (
    <div style={styles.parent}>
      <ContactsHeaderView
        item={contacts ? contacts.length : 0}
        onChatCloseClick={onChatCloseClick}
      />
      <div style={styles.parent} >
        {contacts.length <= 0 && <EmptyComponent message={"No User Found"} />}

        {contacts.length > 0 && (
          <List
            style={{
              outline: "none",
              height: window.innerHeight - 120,
            }}
            rowCount={contacts.length}
            height={window.innerHeight}
            width={window.innerWidth}
            rowHeight={cache.rowHeight}
            rowRenderer={({ index, parent, key, style }) => (
              <CellMeasurer
                key={key}
                cache={cache}
                parent={parent}
                columnIndex={0}
                rowIndex={index}
              >
                <ContactsItem
                  item={contacts[index]}
                  onItemClick={onItemClick}
                />
              </CellMeasurer>
            )}
            overscanRowCount={0}
            // data={refresh}
          />
        )}
      </div>

      {/* <FlatList
        // contentContainerStyle={DEFAULT_STYLES.container}
        data={contacts}
        keyExtractor={(item, index) => index.toString()}
        ItemSeparatorComponent={() => {
          return <Divider />;
        }}
        renderItem={({ item }) => {
          return <ContactsItem item={item} navigation={navigation} />;
        }}
      /> */}
    </div>
  );
}
Example #5
Source File: WebStatusView.js    From WhatsApp-Clone with MIT License 4 votes vote down vote up
WebStatusView = ({ onCancelClick }) => {
  var [state, dispatch] = useReducer(statusReducer, statusState);

  var { statusData, masterStatusList, selectedStatus } = state;
  const [refresh, setRefresh] = useState(false);

  useEffect(() => {
    getUserStatusFromAPI(dispatch);
    listenSocket();
  }, []);

  useEffect(() => {
    console.log("masterStatusList : ", masterStatusList.length);
    setRefresh(!refresh);
  }, [masterStatusList, selectedStatus]);

  function toggleStatusView() {
    setRefresh(!refresh);
    getUserStatusFromAPI(dispatch);
    dispatch({ type: SELECTED_STATUS, payload: "" });
  }

  function listenSocket() {
    // socket.removeListener(webConstants.CHAT_LIST);
    socket.on(webConstants.USER_STATUS, async (statusModel) => {
      const id = getLocalData(webConstants.USER_ID);
      if (statusModel.userId != id) {
        console.log("STATUS RECEIVED");
        getUserStatusFromAPI(dispatch);
      }
    });
  }

  return (
    <div style={styles.parent}>
      <div style={styles.statusView}>
        <div style={styles.statusDivView}>
          <WebMyStatusView statusData={statusData} isUser dispatch={dispatch} isBorder={false} />
          <List
            style={{
              // height: window.innerHeight,
              // width: window.innerWidth,
              // paddingTop: "4%",
              outline: "none",
            }}
            // rowCount={40}
            rowCount={masterStatusList.length}
            height={window.innerHeight - 102}
            width={window.innerWidth / 3.5}
            rowHeight={statusCache.rowHeight}
            rowRenderer={({ index, parent, key, style }) => (
              <CellMeasurer
                key={key}
                cache={statusCache}
                parent={parent}
                columnIndex={0}
                rowIndex={index}
              >
                {getStatusView({
                  index,
                  parent,
                  key,
                  style,
                  masterStatusList,
                  dispatch,
                })}
              </CellMeasurer>
            )}
            overscanRowCount={3}
            data={refresh}
          />
        </div>
      </div>

      {(!selectedStatus || selectedStatus === "") && (
        <div style={styles.statusDetailView}>
          {!statusData && (
            <WebStatusEmptyComponent
              message={"Click on a contact to view their status updates"}
              onCancelClick={onCancelClick}
            />
          )}
          {statusData && (
            <WebZoneStatusComponent
              statusData={statusData}
              onCancelClick={onCancelClick}
              dispatch={dispatch}
            />
          )}
        </div>
      )}

      <Animated
        animationIn="fadeIn"
        animationOut="fadeOut"
        animationInDuration={600}
        animationOutDuration={1000}
        isVisible={selectedStatus && selectedStatus != ""}
        animateOnMount={selectedStatus && selectedStatus != ""}
        style={{
          width: "100%",
          position: "absolute",
          height: "100%",
          zIndex: 500000,
        }}
      >
        {selectedStatus && selectedStatus != "" && (
          <div style={styles.statusDetailProgres}>
            <WebStatusProgressView
              statusData={selectedStatus ? selectedStatus : statusData}
              isUser={false}
              dispatch={dispatch}
              toggleStatusView={toggleStatusView}
            />
          </div>
        )}
      </Animated>
    </div>
  );
}