hooks#usePageVisibility TypeScript Examples

The following examples show how to use hooks#usePageVisibility. 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.tsx    From livepeer-com with MIT License 4 votes vote down vote up
StreamSessionsTable = ({
  streamId,
  streamName,
  mt = null,
}: {
  streamId: string;
  streamName: string;
  mt?: string | number;
}) => {
  const [streamsSessions, setStreamsSessions] = useState([]);
  const { user, getStreamSessions } = useApi();
  const [sessionsLoading, setSessionsLoading] = useState(false);
  useEffect(() => {
    getStreamSessions(streamId, undefined, 0)
      .then(([streams, nextCursor]) => {
        setStreamsSessions(streams);
      })
      .catch((err) => console.error(err)); // todo: surface this
  }, [streamId]);
  const isVisible = usePageVisibility();
  useEffect(() => {
    if (!isVisible) {
      return;
    }
    const interval = setInterval(() => {
      if (!sessionsLoading) {
        setSessionsLoading(true);
        getStreamSessions(streamId, undefined, 0)
          .then(([streams, nextCursor]) => {
            setStreamsSessions(streams);
          })
          .catch((err) => console.error(err)) // todo: surface this
          .finally(() => setSessionsLoading(false));
      }
    }, 10000);
    return () => clearInterval(interval);
  }, [streamId, isVisible]);

  const columns: any = useMemo(
    () => [
      {
        Header: "Created at",
        accessor: "created",
        Cell: DateCell,
        sortType: (...params: SortTypeArgs) =>
          dateSort("original.created.date", ...params),
      },
      {
        Header: "Session duration",
        accessor: "duration",
        Cell: DurationCell,
        sortType: (...params: SortTypeArgs) =>
          numberSort("original.duration.duration", ...params),
      },
      {
        Header: "Recording URL",
        accessor: "recordingUrl",
        Cell: RecordingUrlCell,
        disableSortBy: true,
      },
    ],
    []
  );

  const data: SessionsTableData[] = useMemo(() => {
    return streamsSessions.map((session) => {
      return {
        id: session.id,
        recordingUrl: {
          id: session.id,
          showMP4: true,
          profiles:
            session.recordingUrl &&
            session.recordingStatus === "ready" &&
            session.profiles?.length
              ? [{ name: "source" }, ...session.profiles]
              : undefined,
          children:
            session.recordingUrl && session.recordingStatus === "ready"
              ? session.recordingUrl
              : "n/a",
          href: session.recordingUrl ? session.recordingUrl : undefined,
          streamName,
          createdAt: session.createdAt,
        },
        duration: {
          duration: session.sourceSegmentsDuration || 0,
          status: session.recordingStatus,
        },
        created: { date: new Date(session.createdAt), fallback: <i>unseen</i> },
      };
    });
  }, [streamsSessions]);

  return streamsSessions.length ? (
    <Box sx={{ mb: "0.5em", mt: "2em" }}>
      <Box as="h4" sx={{ mb: "0.5em" }}>
        Stream Sessions
      </Box>
      <TableV2
        columns={columns}
        data={data}
        pageSize={50}
        rowSelection={null}
        initialSortBy={[{ id: "created", desc: true }]}
        showOverflow={true}
      />
    </Box>
  ) : null;
}
Example #2
Source File: index.tsx    From livepeer-com with MIT License 4 votes vote down vote up
StreamsTable = ({ userId, id }: { userId: string; id: string }) => {
  const [deleteModal, setDeleteModal] = useState(false);
  const [selectedStreams, setSelectedStreams] = useState([]);
  const [streams, setStreams] = useState([]);
  const { getStreams, deleteStream, deleteStreams, getBroadcasters } = useApi();

  useEffect(() => {
    async function init() {
      const [streams] = await getStreams(userId);
      setStreams(streams);
    }
    init();
  }, [userId, deleteModal]);

  const close = useCallback(() => {
    setDeleteModal(false);
  }, []);

  const isVisible = usePageVisibility();

  useEffect(() => {
    if (!isVisible) {
      return;
    }
    const interval = setInterval(async () => {
      const [streams] = await getStreams(userId);
      setStreams(streams);
    }, 5000);
    return () => clearInterval(interval);
  }, [userId, isVisible]);

  const columns: any = useMemo(
    () => [
      {
        Header: "Name",
        accessor: "name",
        Cell: TextCell,
        sortType: (...params: SortTypeArgs) =>
          stringSort("original.name.children", ...params),
      },
      {
        Header: "Details",
        accessor: "details",
        Cell: RenditionsDetailsCell,
        disableSortBy: true,
      },
      {
        Header: "Created",
        accessor: "created",
        Cell: DateCell,
        sortType: (...params: SortTypeArgs) =>
          dateSort("original.created.date", ...params),
      },
      {
        Header: "Last Active",
        accessor: "lastActive",
        Cell: DateCell,
        sortType: (...params: SortTypeArgs) =>
          dateSort("original.lastActive.date", ...params),
      },
      {
        Header: "Status",
        accessor: "status",
        disableSortBy: true,
      },
    ],
    []
  );

  const data: StreamsTableData[] = useMemo(() => {
    return streams.map((stream) => {
      return {
        id: stream.id,
        name: {
          id: stream.id,
          children: stream.name,
          tooltipChildren: stream.createdByTokenName ? (
            <>
              Created by token <b>{stream.createdByTokenName}</b>
            </>
          ) : null,
          href: `/app/stream/${stream.id}`,
        },
        details: { stream },
        created: { date: new Date(stream.createdAt), fallback: <i>unseen</i> },
        lastActive: {
          date: new Date(stream.lastSeen),
          fallback: <i>unseen</i>,
        },
        status: stream.isActive ? "Active" : "Idle",
      };
    });
  }, [streams]);

  const handleRowSelectionChange = useCallback(
    (rows: Row<StreamsTableData>[]) => {
      setSelectedStreams(
        rows.map((r) => streams.find((s) => s.id === r.original.id))
      );
    },
    [streams]
  );

  return (
    <Container sx={{ mb: 5 }} id={id}>
      {deleteModal && selectedStreams.length && (
        <DeleteStreamModal
          numStreamsToDelete={selectedStreams.length}
          streamName={selectedStreams[0].name}
          onClose={close}
          onDelete={() => {
            if (selectedStreams.length === 1) {
              deleteStream(selectedStreams[0].id).then(close);
            } else if (selectedStreams.length > 1) {
              deleteStreams(selectedStreams.map((s) => s.id)).then(close);
            }
          }}
        />
      )}
      <Flex sx={{ alignItems: "center", mb: 3 }}>
        <Box>
          <Link href="/app/stream/new-stream" passHref>
            <A variant="buttons.outlineSmall" sx={{ mr: 2 }}>
              Create
            </A>
          </Link>
          <Button
            variant="primarySmall"
            aria-label="Delete Stream button"
            disabled={!selectedStreams.length}
            onClick={() => selectedStreams.length && setDeleteModal(true)}>
            Delete
          </Button>
          <Box
            sx={{
              ml: "1.4em",
              display: ["none", "none", "none", "inline-block"],
            }}>
            <b>New beta feature</b>: Record your live streams. Send feedback to
            [email protected].
            <Box
              as="a"
              target="_blank"
              href="https://livepeer.com/blog/record-every-video-livestream-with-livepeer"
              sx={{
                display: "inline-block",
                ml: "0.2em",
                textDecoration: "none",
                color: "primary",
                cursor: "pointer",
                ":hover": { textDecoration: "underline" },
              }}>
              <b>Read more ⬈</b>
            </Box>
          </Box>
        </Box>
      </Flex>
      <TableV2
        columns={columns}
        data={data}
        rowSelection="all"
        onRowSelectionChange={handleRowSelectionChange}
        initialSortBy={[{ id: "created", desc: true }]}
      />
    </Container>
  );
}