All files / app/features/publicTrips PublicTripCard.tsx

90% Statements 72/80
67.92% Branches 36/53
75% Functions 18/24
92.85% Lines 65/70

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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481                        5x 5x 5x 5x 5x                   5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x                   159x           25x             159x                         159x                               5x           5x             5x             159x                     213x                     5x 800x 159x                         148x               159x 159x 159x 159x 112x 56x     159x 159x 159x     159x 159x 159x 159x 159x   159x 5x 5x   159x   159x 159x 159x 159x   159x                 159x 159x                               1x                   1x             25x       1x             1x                   1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
import {
  HourglassEmptyOutlined,
  PlaceOutlined,
  WavingHandOutlined,
} from "@mui/icons-material";
import {
  Box,
  Card,
  CardContent,
  Chip,
  styled,
  Typography,
} from "@mui/material";
import Avatar from "components/Avatar";
import Button from "components/Button";
import ConfirmationDialogWrapper from "components/ConfirmationDialogWrapper";
import EllipsisMenu, { EllipsisMenuItem } from "components/EllipsisMenu";
import {
  CalendarIcon,
  CheckCircleIcon,
  CouchIcon,
  EditIcon,
  ExpandLessIcon,
  ExpandMoreIcon,
  ReopenIcon,
  VisibilityIcon,
} from "components/Icons";
import ProfileIncompleteDialog from "components/ProfileIncompleteDialog/ProfileIncompleteDialog";
import StyledLink from "components/StyledLink";
import { useAuthContext } from "features/auth/AuthProvider";
import useAccountInfo from "features/auth/useAccountInfo";
import FlagButton from "features/FlagButton";
import { useTranslation } from "i18n";
import { PUBLIC_TRIPS } from "i18n/namespaces";
import { PublicTripStatus } from "proto/public_trips_pb";
import { useCallback, useState } from "react";
import { routeToCommunity, routeToUser } from "routes";
import { localizeDateTimeRange } from "utils/date";
import dayjs from "utils/dayjs";
import { useIsNativeEmbed } from "utils/nativeLink";
 
import PublicTripDialog from "./PublicTripDialog";
import { PublicTrip, useUpdatePublicTrip } from "./useListPublicTrips";
 
interface PublicTripCardProps {
  trip: PublicTrip;
  // When true, renders the owner's view: hides Offer-to-host / View profile /
  // Flag, shows Edit / Close actions and a status chip for closed trips.
  ownerView?: boolean;
  id?: string;
}
 
const StyledCard = styled(Card)(({ theme }) => ({
  border: `1px solid var(--mui-palette-grey-300)`,
  borderRadius: theme.spacing(1),
  position: "relative",
}));
 
const OwnerMenuContainer = styled("div")(({ theme }) => ({
  position: "absolute",
  top: theme.spacing(0.5),
  right: theme.spacing(0.5),
  zIndex: 1,
}));
 
const StyledCardContent = styled(CardContent)(({ theme }) => ({
  display: "flex",
  gap: theme.spacing(2),
  padding: theme.spacing(2.5),
  "&:last-child": {
    paddingBottom: theme.spacing(2.5),
  },
  [theme.breakpoints.down("sm")]: {
    flexDirection: "column",
    gap: theme.spacing(1.5),
  },
}));
 
const UserSection = styled("div")(({ theme }) => ({
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  gap: theme.spacing(0.5),
  width: theme.spacing(14),
  minWidth: theme.spacing(14),
  [theme.breakpoints.down("sm")]: {
    flexDirection: "row",
    width: "auto",
    minWidth: "auto",
    gap: theme.spacing(1.5),
    paddingRight: theme.spacing(5),
  },
}));
 
const UserName = styled(Typography)({
  maxWidth: "100%",
  textAlign: "left",
  overflowWrap: "break-word",
});
 
const UserDetails = styled(Typography)({
  color: "var(--mui-palette-text-secondary)",
  textAlign: "left",
  maxWidth: "100%",
  overflowWrap: "break-word",
});
 
const ContentSection = styled("div")({
  display: "flex",
  flexDirection: "column",
  flex: 1,
  minWidth: 0,
});
 
const MetaRow = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  gap: theme.spacing(2),
  marginBottom: theme.spacing(1),
  flexWrap: "wrap",
  [theme.breakpoints.down("sm")]: {
    gap: theme.spacing(1),
  },
}));
 
const MetaItem = styled("div")(({ theme }) => ({
  display: "flex",
  alignItems: "center",
  gap: theme.spacing(0.5),
  color: "var(--mui-palette-text-secondary)",
  fontSize: "0.875rem",
  "& svg": {
    fontSize: "1rem",
  },
}));
 
const Description = styled(Typography, {
  shouldForwardProp: (prop) => prop !== "expanded",
})<{ expanded: boolean }>(({ expanded, theme }) => ({
  ...(!expanded && {
    display: "-webkit-box",
    WebkitLineClamp: 3,
    WebkitBoxOrient: "vertical" as const,
    overflow: "hidden",
    textOverflow: "ellipsis",
    [theme.breakpoints.down("sm")]: {
      WebkitLineClamp: 2,
    },
  }),
}));
 
export default function PublicTripCard({
  trip,
  ownerView = false,
  id,
}: PublicTripCardProps) {
  const {
    t,
    i18n: { language: locale },
  } = useTranslation([PUBLIC_TRIPS]);
  const [expanded, setExpanded] = useState(false);
  const [isOverflowing, setIsOverflowing] = useState(false);
  const descriptionRef = useCallback((node: HTMLElement | null) => {
    if (node) {
      setIsOverflowing(node.scrollHeight > node.clientHeight);
    }
  }, []);
  const [showIncompleteDialog, setShowIncompleteDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [menuAnchorEl, setMenuAnchorEl] = useState<HTMLButtonElement | null>(
    null,
  );
  const { data: accountInfo } = useAccountInfo();
  const { authState } = useAuthContext();
  const isNativeEmbed = useIsNativeEmbed();
  const { mutate: updateTrip } = useUpdatePublicTrip();
  const isOwnTrip = trip.user?.userId === authState.userId;
 
  const handleMenuOpen = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    setMenuAnchorEl(event.currentTarget);
  };
  const handleMenuClose = () => setMenuAnchorEl(null);
 
  const isClosed = trip.status === PublicTripStatus.PUBLIC_TRIP_STATUS_CLOSED;
  const isPast = dayjs(trip.toDate).isBefore(dayjs().startOf("day"));
  const isDimmed = isClosed || isPast;
  const showOwnMarker = isOwnTrip && !ownerView;
 
  const handleOfferToHost = () => {
    if (!accountInfo?.profileComplete) {
      setShowIncompleteDialog(true);
    } else {
      // TODO: create host request with public_trip_id linked
    }
  };
 
  // The backend always populates user, but the proto type is optional.
  const { user } = trip;
  Iif (!user) return null;
 
  return (
    <>
      {showIncompleteDialog && (
        <ProfileIncompleteDialog
          open
          onClose={() => setShowIncompleteDialog(false)}
          attempted_action="send_request"
        />
      )}
      {ownerView && (
        <PublicTripDialog
          mode="edit"
          trip={trip}
          open={showEditDialog}
          onClose={() => setShowEditDialog(false)}
        />
      )}
      <StyledCard id={id} elevation={0} sx={{ opacity: isDimmed ? 0.65 : 1 }}>
        {ownerView && (
          <ConfirmationDialogWrapper
            title={t("publicTrips:close_dialog_title")}
            message={t("publicTrips:close_dialog_message")}
            confirmButtonLabel={t("publicTrips:close_dialog_confirm")}
            onConfirm={() =>
              updateTrip({
                tripId: trip.tripId,
                status: PublicTripStatus.PUBLIC_TRIP_STATUS_CLOSED,
              })
            }
          >
            {(setConfirmOpen) => {
              const menuItems: EllipsisMenuItem[] = [
                {
                  icon: EditIcon,
                  label: t("publicTrips:edit"),
                  onClick: () => setShowEditDialog(true),
                },
                ...(!isClosed
                  ? [
                      {
                        icon: CheckCircleIcon,
                        label: t("publicTrips:close"),
                        onClick: () => setConfirmOpen(true),
                      },
                    ]
                  : []),
                ...(isClosed && !isPast
                  ? [
                      {
                        icon: ReopenIcon,
                        label: t("publicTrips:reopen"),
                        onClick: () =>
                          updateTrip({
                            tripId: trip.tripId,
                            status:
                              PublicTripStatus.PUBLIC_TRIP_STATUS_SEARCHING_FOR_HOST,
                          }),
                      },
                    ]
                  : []),
              ];
              return (
                <OwnerMenuContainer>
                  <EllipsisMenu
                    idName={`public-trip-${trip.tripId}`}
                    isMenuOpen={!!menuAnchorEl}
                    menuAnchorEl={menuAnchorEl}
                    onMenuOpen={handleMenuOpen}
                    onMenuClose={handleMenuClose}
                    items={menuItems}
                  />
                </OwnerMenuContainer>
              );
            }}
          </ConfirmationDialogWrapper>
        )}
        <StyledCardContent>
          <UserSection>
            <Box
              sx={{
                position: "relative",
                width: "3rem",
                height: "3rem",
                flexShrink: 0,
              }}
            >
              <Avatar user={user} isProfileLink />
              {showOwnMarker && (
                <Box
                  sx={{
                    position: "absolute",
                    inset: 0,
                    borderRadius: "50%",
                    bgcolor: "rgba(0,0,0,0.55)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    pointerEvents: "none",
                    zIndex: 1,
                  }}
                >
                  <Typography
                    sx={{
                      color: "white",
                      fontWeight: 700,
                      fontSize: "0.65rem",
                      letterSpacing: "0.08em",
                    }}
                  >
                    {t("publicTrips:you_overlay")}
                  </Typography>
                </Box>
              )}
            </Box>
            <StyledLink href={routeToUser(user.username)}>
              <UserName variant="h3">{user.name}</UserName>
            </StyledLink>
            <UserDetails variant="body2">
              {user.age}
              {user.gender ? `, ${user.gender}` : ""}
            </UserDetails>
            <UserDetails variant="body2">
              {t("publicTrips:references", {
                count: user.numReferences,
              })}
            </UserDetails>
          </UserSection>
 
          <ContentSection>
            <MetaRow>
              <MetaItem>
                <CalendarIcon />
                {localizeDateTimeRange(
                  new Date(trip.fromDate + "T00:00:00"),
                  new Date(trip.toDate + "T00:00:00"),
                  {
                    locale,
                    includeTime: false,
                    abbreviate: true,
                  },
                )}
              </MetaItem>
              {trip.communityName && (
                <MetaItem>
                  <PlaceOutlined sx={{ fontSize: "1rem" }} />
                  <StyledLink
                    href={routeToCommunity(
                      trip.communityId,
                      trip.communitySlug,
                    )}
                  >
                    {trip.communityName}
                  </StyledLink>
                </MetaItem>
              )}
              {trip.sameGenderOnly && (
                <MetaItem>
                  <VisibilityIcon />
                  {t("publicTrips:same_gender_only_indicator")}
                </MetaItem>
              )}
            </MetaRow>
            <Description
              variant="body1"
              ref={descriptionRef}
              expanded={expanded}
              onClick={
                isOverflowing || expanded
                  ? () => setExpanded((e) => !e)
                  : undefined
              }
              sx={{ cursor: isOverflowing || expanded ? "pointer" : "default" }}
            >
              {trip.description}
            </Description>
            {(isOverflowing || expanded) && (
              <Typography
                variant="body2"
                onClick={() => setExpanded((e) => !e)}
                sx={{
                  cursor: "pointer",
                  color: "var(--mui-palette-primary-main)",
                  display: "flex",
                  alignItems: "center",
                  gap: 0.25,
                  mt: 0.5,
                }}
              >
                {expanded
                  ? t("publicTrips:show_less")
                  : t("publicTrips:show_more")}
                {expanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
              </Typography>
            )}
            {!showOwnMarker && (
              <Box
                sx={{
                  mt: 1.5,
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 1,
                }}
              >
                {ownerView ? (
                  <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                    {isClosed ? (
                      <Chip
                        label={t("publicTrips:status_closed")}
                        size="small"
                      />
                    ) : isPast ? (
                      <Chip label={t("publicTrips:status_past")} size="small" />
                    ) : (
                      <Chip
                        label={t("publicTrips:status_active")}
                        size="small"
                        color="primary"
                        variant="outlined"
                      />
                    )}
                    {trip.offersCount !== undefined && (
                      <Box
                        component="span"
                        sx={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: "3px",
                          fontSize: "0.8125rem",
                          fontWeight: 700,
                          color:
                            trip.offersCount > 0
                              ? "var(--mui-palette-primary-main)"
                              : "var(--mui-palette-text-secondary)",
                        }}
                      >
                        {trip.offersCount > 0 ? (
                          <WavingHandOutlined sx={{ fontSize: "1rem" }} />
                        ) : (
                          <HourglassEmptyOutlined sx={{ fontSize: "1rem" }} />
                        )}
                        {trip.offersCount > 0
                          ? t("publicTrips:offers_count", {
                              count: trip.offersCount,
                            })
                          : t("publicTrips:no_offers")}
                      </Box>
                    )}
                  </Box>
                ) : (
                  <>
                    <StyledLink
                      href={routeToUser(user.username)}
                      target={isNativeEmbed ? undefined : "_blank"}
                    >
                      {t("publicTrips:view_profile")}
                    </StyledLink>
                    <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
                      <FlagButton
                        contentRef={`public_trip/${trip.tripId}`}
                        authorUser={user.userId}
                      />
                      <Button
                        startIcon={<CouchIcon />}
                        onClick={handleOfferToHost}
                      >
                        {t("publicTrips:offer_to_host")}
                      </Button>
                    </Box>
                  </>
                )}
              </Box>
            )}
          </ContentSection>
        </StyledCardContent>
      </StyledCard>
    </>
  );
}