All files / app/features/communities/events EventPage.tsx

90.62% Statements 58/64
90% Branches 36/40
64.28% Functions 9/14
90.47% Lines 57/63

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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366                1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x 10x               24x                                                                                                                                                                                             13x 13x   13x         1x             24x 24x 24x           24x           24x   2x             1x       1x     1x         24x   24x   24x   24x       24x 19x         24x       24x 1x     23x                                                       1x                                                                                                                                                               2x                                                                          
import {
  Card,
  Chip,
  CircularProgress,
  darken,
  Link as MuiLink,
  Theme,
  Typography,
} from "@material-ui/core";
import { eventImagePlaceholderUrl } from "appConstants";
import Alert from "components/Alert";
import Button from "components/Button";
import HeaderButton from "components/HeaderButton";
import HtmlMeta from "components/HtmlMeta";
import { BackIcon, CalendarIcon } from "components/Icons";
import Markdown from "components/Markdown";
import Snackbar from "components/Snackbar";
import NotFoundPage from "features/NotFoundPage";
import { eventAttendeesBaseKey, eventKey } from "features/queryKeys";
import { Timestamp } from "google-protobuf/google/protobuf/timestamp_pb";
import { RpcError } from "grpc-web";
import { useTranslation } from "i18n";
import { COMMUNITIES } from "i18n/namespaces";
import Link from "next/link";
import { useRouter } from "next/router";
import { AttendanceState, Event } from "proto/events_pb";
import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "react-query";
import { routeToEditEvent, routeToEvent } from "routes";
import { service } from "service";
import { timestamp2Date } from "utils/date";
import dayjs from "utils/dayjs";
import makeStyles from "utils/makeStyles";
 
import CommentTree from "../discussions/CommentTree";
import AttendanceMenu from "./AttendanceMenu";
import CancelEventDialog from "./CancelEventDialog";
import EventAttendees from "./EventAttendees";
import EventOrganizers from "./EventOrganizers";
import { useEvent } from "./hooks";
import InviteCommunityDialog from "./InviteCommunityDialog";
 
export const useEventPageStyles = makeStyles<Theme, { eventImageSrc: string }>(
  (theme) => ({
    eventCoverPhoto: {
      height: 100,
      [theme.breakpoints.up("md")]: {
        height: 200,
      },
      width: "100%",
      objectFit: ({ eventImageSrc }) =>
        eventImageSrc === eventImagePlaceholderUrl ? "contain" : "cover",
      marginBlockStart: theme.spacing(2),
    },
    header: {
      alignItems: "center",
      gap: theme.spacing(2, 2),
      display: "grid",
      gridTemplateAreas: `
      "backButton eventTitle eventTitle"
      "eventTime eventTime eventTime"
      "actionButtons actionButtons ."
    `,
      gridAutoFlow: "column",
      gridTemplateColumns: "3.125rem 1fr auto",
      marginBlockEnd: theme.spacing(4),
      marginBlockStart: theme.spacing(2),
      [theme.breakpoints.up("sm")]: {
        gridTemplateAreas: `
      "backButton eventTitle actionButtons"
      ". eventTime eventTime"
    `,
      },
    },
    backButton: {
      gridArea: "backButton",
      width: "3.125rem",
      height: "3.125rem",
    },
    eventTitle: {
      gridArea: "eventTitle",
    },
    onlineInfoContainer: {
      display: "grid",
      columnGap: theme.spacing(2),
      gridAutoFlow: "column",
      gridTemplateColumns: "max-content max-content",
    },
    actionButtons: {
      display: "grid",
      gridAutoFlow: "column",
      columnGap: theme.spacing(1),
      gridArea: "actionButtons",
      justifySelf: "start",
    },
    cancelButton: {
      flexShrink: 0,
      "&:hover": {
        backgroundColor: darken(theme.palette.error.main, 0.1),
      },
      backgroundColor: theme.palette.error.main,
    },
    cancelledChip: {
      backgroundColor: theme.palette.error.main,
      color: theme.palette.common.white,
      fontWeight: "bold",
    },
    eventTypeText: {
      color: theme.palette.grey[600],
    },
    eventTimeContainer: {
      alignItems: "center",
      gridArea: "eventTime",
      display: "grid",
      columnGap: theme.spacing(1),
      gridTemplateColumns: "3.75rem auto",
      [theme.breakpoints.up("md")]: {
        gridTemplateColumns: "3.75rem 30%",
      },
    },
    calendarIcon: {
      marginInlineStart: theme.spacing(-0.5),
      height: "3.75rem",
      width: "3.75rem",
    },
    eventDetailsContainer: {
      display: "grid",
      rowGap: theme.spacing(3),
      marginBlockEnd: theme.spacing(5),
    },
    cardSection: {
      padding: theme.spacing(2),
      "& + &": {
        marginBlockStart: theme.spacing(3),
      },
    },
    discussionContainer: {
      marginBlockEnd: theme.spacing(5),
    },
  })
);
 
function getEventTimeString(
  startTime: Timestamp.AsObject,
  endTime: Timestamp.AsObject
) {
  const start = dayjs(timestamp2Date(startTime));
  const end = dayjs(timestamp2Date(endTime));
 
  return `${start.format("LLLL")} to ${end.format(
    end.isSame(start, "day") ? "LT" : "LLLL"
  )}`;
}
 
export default function EventPage({
  eventId,
  eventSlug,
}: {
  eventId: number;
  eventSlug: string;
}) {
  const { t } = useTranslation([COMMUNITIES]);
  const router = useRouter();
  const queryClient = useQueryClient();
  const {
    data: event,
    error: eventError,
    isLoading,
    isValidEventId,
  } = useEvent({ eventId });
 
  const {
    isLoading: isSetEventAttendanceLoading,
    error: setEventAttendanceError,
    mutate: setEventAttendance,
  } = useMutation<Event.AsObject, RpcError, AttendanceState>(
    (newEventAttendance: AttendanceState) => {
      return service.events.setEventAttendance({
        attendanceState: newEventAttendance,
        eventId,
      });
    },
    {
      onSuccess(updatedEvent) {
        queryClient.setQueryData<Event.AsObject>(
          eventKey(eventId),
          updatedEvent
        );
        queryClient.invalidateQueries(eventKey(eventId), {
          refetchActive: false,
        });
        queryClient.invalidateQueries([eventAttendeesBaseKey, eventId]);
      },
    }
  );
 
  const [cancelDialogIsOpen, setCancelDialogIsOpen] = useState(false);
  const [showInviteCommunitySuccess, setShowInviteCommunitySuccess] =
    useState(false);
  const [inviteCommunityDialogIsOpen, setInviteCommunityDialogIsOpen] =
    useState(false);
 
  const isPastEvent = event?.endTime
    ? dayjs().isAfter(timestamp2Date(event.endTime))
    : false;
 
  useEffect(() => {
    Iif (event?.slug && event.slug !== eventSlug) {
      router.replace(routeToEvent(event.eventId, event.slug));
    }
  }, [event, eventSlug, router]);
 
  const classes = useEventPageStyles({
    eventImageSrc: event?.photoUrl || eventImagePlaceholderUrl,
  });
 
  if (!isValidEventId) {
    return <NotFoundPage />;
  }
 
  return (
    <>
      <HtmlMeta title={event?.title} />
      {(eventError || setEventAttendanceError) && (
        <Alert severity="error">
          {eventError?.message || setEventAttendanceError?.message || ""}
        </Alert>
      )}
 
      {showInviteCommunitySuccess && (
        <Snackbar severity="success">
          {t("communities:invite_community_dialog.toast_success")}
        </Snackbar>
      )}
 
      {isLoading ? (
        <CircularProgress />
      ) : (
        event && (
          <>
            <img
              className={classes.eventCoverPhoto}
              src={event.photoUrl || eventImagePlaceholderUrl}
              alt=""
            />
            <div className={classes.header}>
              <HeaderButton
                className={classes.backButton}
                onClick={() => router.back()}
                aria-label={t("communities:previous_page")}
              >
                <BackIcon />
              </HeaderButton>
              <div className={classes.eventTitle}>
                <Typography variant="h1">{event.title}</Typography>
                {event.onlineInformation ? (
                  <div className={classes.onlineInfoContainer}>
                    <Typography
                      className={classes.eventTypeText}
                      variant="body1"
                    >
                      {t("communities:virtual_event")}
                    </Typography>
                    <MuiLink href={event.onlineInformation.link}>
                      {t("communities:event_link")}
                    </MuiLink>
                  </div>
                ) : (
                  <Typography className={classes.eventTypeText} variant="body1">
                    {event.offlineInformation?.address}
                  </Typography>
                )}
                {event.isCancelled && (
                  <Chip
                    classes={{ root: classes.cancelledChip }}
                    label={t("communities:cancelled")}
                  />
                )}
              </div>
              <div className={classes.actionButtons}>
                {event.canEdit ? (
                  <>
                    <Link
                      href={routeToEditEvent(event.eventId, event.slug)}
                      passHref
                    >
                      <Button
                        component="a"
                        variant="outlined"
                        disabled={event.isCancelled || isPastEvent}
                      >
                        {t("communities:edit_event")}
                      </Button>
                    </Link>
                    <Button
                      onClick={() => setCancelDialogIsOpen(true)}
                      variant="contained"
                      color="primary"
                      classes={{ containedPrimary: classes.cancelButton }}
                      disabled={event.isCancelled || isPastEvent}
                    >
                      {t("communities:cancel_event")}
                    </Button>
                    <CancelEventDialog
                      open={cancelDialogIsOpen}
                      onClose={() => setCancelDialogIsOpen(false)}
                      eventId={eventId}
                    />
                    <Button
                      onClick={() => setInviteCommunityDialogIsOpen(true)}
                      variant="contained"
                      color="secondary"
                      disabled={event.isCancelled || isPastEvent}
                    >
                      {t("communities:invite_community_dialog_buttons.open")}
                    </Button>
                    <InviteCommunityDialog
                      afterSuccess={() => setShowInviteCommunitySuccess(true)}
                      open={inviteCommunityDialogIsOpen}
                      onClose={() => setInviteCommunityDialogIsOpen(false)}
                      eventId={eventId}
                    />
                  </>
                ) : null}
 
                <AttendanceMenu
                  loading={isSetEventAttendanceLoading}
                  onChangeAttendanceState={(attendanceState) =>
                    setEventAttendance(attendanceState)
                  }
                  attendanceState={event.attendanceState}
                  id="event-page-attendance"
                  disabled={event.isCancelled || isPastEvent}
                />
              </div>
 
              <div className={classes.eventTimeContainer}>
                <CalendarIcon className={classes.calendarIcon} />
                <Typography variant="body1">
                  {getEventTimeString(event.startTime!, event.endTime!)}
                </Typography>
              </div>
            </div>
            <div className={classes.eventDetailsContainer}>
              <Card className={classes.cardSection}>
                <Typography variant="h2">
                  {t("communities:details_subheading_colon")}
                </Typography>
                <Markdown source={event.content} topHeaderLevel={3} />
              </Card>
              <EventOrganizers eventId={event.eventId} />
              <EventAttendees eventId={event.eventId} />
            </div>
            <div className={classes.discussionContainer}>
              <Typography variant="h2">
                {t("communities:event_discussion")}
              </Typography>
              <CommentTree threadId={event.thread!.threadId} />
            </div>
          </>
        )
      )}
    </>
  );
}