All files / app/features/auth InviteCodesPage.tsx

91.89% Statements 34/37
70.83% Branches 17/24
92.3% Functions 12/13
91.89% Lines 34/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200                        1x 1x 1x   1x 1x   1x 1x 1x   1x   4x 11x 11x   11x             11x     6x         11x     1x       11x 1x   1x     11x 11x   11x 1x 1x 1x     1x                                     1x                       8x                                   7x 7x 7x                               1x                   1x                                                                                                                
import { ContentCopy } from "@mui/icons-material";
import {
  Alert,
  Box,
  Button,
  IconButton,
  List,
  ListItem,
  ListItemText,
  Skeleton,
  Tooltip,
  Typography,
} from "@mui/material";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import dayjs from "dayjs";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { GLOBAL } from "i18n/namespaces";
import { ListInviteCodesRes } from "proto/account_pb";
import React from "react";
import { inviteRoute } from "routes";
import { service } from "service";
 
import { inviteCodesKey } from "../queryKeys";
 
export default function InviteCodesPage() {
  const { t } = useTranslation(GLOBAL);
  const queryClient = useQueryClient();
 
  const { data, error, isLoading } = useQuery<
    ListInviteCodesRes.AsObject,
    RpcError,
    ListInviteCodesRes.AsObject
  >({
    queryKey: [inviteCodesKey],
    queryFn: service.account.listInviteCodes,
    select: (res) => ({
      ...res,
      inviteCodesList: [...(res.inviteCodesList ?? [])].sort(
        (a, b) => (b.created?.seconds ?? 0) - (a.created?.seconds ?? 0),
      ),
    }),
  });
 
  const { isPending: isCreatePending, mutate: createInviteCode } = useMutation({
    mutationFn: service.account.createInviteCode,
    onSuccess: () =>
      queryClient.invalidateQueries({ queryKey: [inviteCodesKey] }),
  });
 
  const { isPending: isDisablePending, mutate: disableInviteCode } =
    useMutation({
      mutationFn: (code: string) => service.account.disableInviteCode(code),
      onSuccess: () =>
        queryClient.invalidateQueries({ queryKey: [inviteCodesKey] }),
    });
 
  const [copiedCode, setCopiedCode] = React.useState<string | null>(null);
  const copiedTimerRef = React.useRef<number | null>(null);
 
  const copy = async (url: string, code: string) => {
    await navigator.clipboard.writeText(url);
    setCopiedCode(code);
    Iif (copiedTimerRef.current) {
      window.clearTimeout(copiedTimerRef.current);
    }
    copiedTimerRef.current = window.setTimeout(() => {
      setCopiedCode(null);
      copiedTimerRef.current = null;
    }, 1500);
  };
 
  return (
    <Box sx={{ width: "100%", maxWidth: 800, mx: "auto", mt: 6, px: 2 }}>
      <Typography variant="h2" gutterBottom sx={{ mb: 1 }}>
        {t("global:nav.invite_members")}
      </Typography>
 
      <Typography color="textSecondary" sx={{ mb: 3 }}>
        {t("invites.instructions")}
      </Typography>
 
      <Box sx={{ display: "flex", gap: 1, mb: 2 }}>
        <Button
          variant="contained"
          onClick={() => createInviteCode()}
          disabled={isCreatePending}
        >
          {t("global:create")}
        </Button>
      </Box>
 
      {error && <Alert severity="error">{error.message}</Alert>}
 
      {isLoading ? (
        <List>
          {[0, 1].map((i) => (
            <ListItem
              key={`sk-${i}`}
              divider
              secondaryAction={
                <Skeleton variant="circular" sx={{ width: 24, height: 24 }} />
              }
            >
              <ListItemText
                primary={<Skeleton variant="text" sx={{ width: "15%" }} />}
                secondary={<Skeleton variant="text" sx={{ width: "50%" }} />}
              />
            </ListItem>
          ))}
        </List>
      ) : (
        <List>
          {(data?.inviteCodesList ?? []).map((c) => {
            const origin =
              typeof window !== "undefined" ? window.location.origin : "";
            const shareUrl = `${origin}${inviteRoute}?code=${c.code}`;
            return (
              <ListItem
                key={c.code}
                divider
                sx={c.disabled ? { opacity: 0.6 } : undefined}
                secondaryAction={
                  <>
                    <Tooltip
                      open={copiedCode === c.code}
                      title={t("global:copied")}
                      placement="top"
                      arrow
                    >
                      <IconButton
                        edge="end"
                        aria-label={t("global:copy")}
                        onClick={() => copy(shareUrl, c.code)}
                        disabled={!!c.disabled}
                      >
                        <ContentCopy />
                      </IconButton>
                    </Tooltip>
                    {!c.disabled && (
                      <Button
                        size="small"
                        sx={{ ml: 1 }}
                        onClick={() => disableInviteCode(c.code)}
                        disabled={isDisablePending}
                      >
                        {t("global:disable")}
                      </Button>
                    )}
                  </>
                }
              >
                <ListItemText
                  primary={
                    <span data-testid="invite-code-link">{shareUrl}</span>
                  }
                  sx={c.disabled ? { color: "text.disabled" } : undefined}
                  secondary={
                    <>
                      {c.created?.seconds && (
                        <>
                          {t("global:created")}:{" "}
                          {dayjs(new Date(c.created.seconds * 1000)).format(
                            "YYYY-MM-DD HH:mm",
                          )}
                        </>
                      )}
                      {c.disabled?.seconds && (
                        <>
                          {" • "}
                          {t("global:disabled")}:{" "}
                          {dayjs(new Date(c.disabled.seconds * 1000)).format(
                            "YYYY-MM-DD HH:mm",
                          )}
                        </>
                      )}
                      {typeof c.uses === "number" && (
                        <>
                          {" • "}
                          {t("global:uses")}: {c.uses}{" "}
                          {t("invites.uses_suffix")}
                        </>
                      )}
                    </>
                  }
                />
              </ListItem>
            );
          })}
          {!(data?.inviteCodesList?.length ?? 0) && (
            <Typography color="textSecondary">
              {t("global:no_invite_codes")}
            </Typography>
          )}
        </List>
      )}
    </Box>
  );
}