react-virtualized#CellMeasurerCache JavaScript Examples

The following examples show how to use react-virtualized#CellMeasurerCache. 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: WebChatListView.js    From WhatsApp-Clone with MIT License 5 votes vote down vote up
cache = new CellMeasurerCache({
  fixedWidth: true,
  defaultHeight: 60,
})
Example #2
Source File: WebContactsView.js    From WhatsApp-Clone with MIT License 5 votes vote down vote up
cache = new CellMeasurerCache({
  fixedWidth: true,
  defaultHeight: 80,
})
Example #3
Source File: WebStatusViewAction.js    From WhatsApp-Clone with MIT License 5 votes vote down vote up
statusCache = new CellMeasurerCache({
  fixedWidth: true,
  fixedHeight: true,
  defaultHeight: 65,
})
Example #4
Source File: LogTable.js    From binary-bot with MIT License 4 votes vote down vote up
Logtable = () => {
    const [id, setId] = React.useState(0);
    const [rows, setRows] = React.useState([]);
    const [widths, setWidths] = React.useState({
        timestamp: 0.25,
        message: 0.75,
    });

    const total_width = 1150;
    const min_height = 550;
    const cache = new CellMeasurerCache({
        defaultHeight: 35,
    });

    const columns = [
        { label: translate('Timestamp'), dataKey: 'timestamp' },
        { label: translate('Message'), dataKey: 'message' },
    ];

    React.useEffect(() => {
        globalObserver.register('log.export', exportLogs);
        globalObserver.register('bot.notify', notify);
        return () => {
            globalObserver.unregister('log.export', exportLogs);
            globalObserver.unregister('bot.notify', notify);
        };
    }, [rows]);

    const exportLogs = () => {
        const json2csvParser = new Parser({
            fields: ['timestamp', 'message'],
        });
        const data = json2csvParser.parse(rows);

        saveAs({ data, filename: 'logs.csv', type: 'text/csv;charset=utf-8' });
    };

    const notify = log => {
        if (!log) return;
        const { id: updated_id, rows: updated_rows } = appendRow(log, { id, rows }, true);
        setId(updated_id);
        setRows(updated_rows);
    };

    const headerRenderer = ({ dataKey, label }) => {
        const index = columns.findIndex(col => col.dataKey === dataKey);
        const is_last_column = index + 1 === columns.length;

        return (
            <React.Fragment key={dataKey}>
                <div className="ReactVirtualized__Table__headerTruncatedText">{label}</div>
                {!is_last_column && (
                    <Draggable
                        axis="x"
                        defaultClassName="DragHandle"
                        defaultClassNameDragging="DragHandleActive"
                        onDrag={(e, { deltaX }) =>
                            resizeRow({
                                dataKey,
                                deltaX,
                            })
                        }
                        position={{ x: 0 }}
                        zIndex={999}
                    >
                        <span className="DragHandleIcon log-table" />
                    </Draggable>
                )}
            </React.Fragment>
        );
    };

    const resizeRow = ({ deltaX }) => {
        const prev_widths = { ...widths };
        const percent_delta = deltaX / total_width;

        setWidths({
            message: prev_widths.message - percent_delta,
            timestamp: prev_widths.timestamp + percent_delta,
        });
    };

    const rowRenderer = ({ rowData, columns: cols, className, key }) => (
        <div className={`${className} ${rowData.type}`} key={key}>
            {cols?.map(({ props, key: inner_key }) => (
                <div style={props.style} className={props.className} role={props.role} key={inner_key}>
                    {props.title}
                </div>
            ))}
        </div>
    );

    return (
        <span id="logPanel" className="draggable-dialog" title={translate("Log")}>
            <div id="logTable" className="logTable-scroll">
                <div className="content-row">
                    <div>
                        <div className="content-row-table">
                            <div style={{ height: min_height }}>
                                <Table
                                    width={760}
                                    height={min_height}
                                    headerHeight={35}
                                    rowHeight={35}
                                    rowCount={rows.length}
                                    rowGetter={({ index }) => rows[index]}
                                    headerStyle={{
                                        fontSize: 11,
                                        textTransform: 'capitalize',
                                    }}
                                    rowRenderer={rowRenderer}
                                    deferredMeasurementCache={cache}
                                >
                                    {columns.map(({ label, dataKey }, index) => (
                                        <Column
                                            key={index}
                                            headerRenderer={headerRenderer}
                                            width={widths[dataKey] * total_width}
                                            label={label}
                                            dataKey={dataKey}
                                        />
                                    ))}
                                </Table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </span>
    );
}
Example #5
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 #6
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} />;
    }
  }
}