All files / app/features/translate LanguagePickerSelect.tsx

95% Statements 57/60
73.68% Branches 28/38
86.66% Functions 13/15
95% Lines 57/60

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 3181x 1x                         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x           1x 111x 10x                               3x     10x 10x 10x 10x   10x 10x   10x   10x   10x   1x     10x 1x   1x 1x       1x     10x 1x   1x 1x     10x 66x           66x                                     10x     70x         90x         90x       20x 70x     10x       60x   60x                                                                                                         10x 6x                               6x                                                                 3x 1x                                                                                                                                          
import CheckIcon from "@mui/icons-material/Check";
import ExpandMoreOutlinedIcon from "@mui/icons-material/ExpandMoreOutlined";
import {
  Box,
  FormControl,
  ListItemIcon,
  ListItemText,
  MenuItem,
  Select,
  SelectChangeEvent,
  Stack,
  styled,
  Typography,
  useMediaQuery,
} from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import CatalanFlagIcon from "components/Icons/CatalanFlagIcon";
import Snackbar from "components/Snackbar";
import { useAuthContext } from "features/auth/AuthProvider";
import { useWeblateStats } from "features/weblate/useWeblateStats";
import { useTranslation } from "i18n";
import { LANGUAGE_MAP } from "i18n/constants";
import { GLOBAL } from "i18n/namespaces";
import { useRouter } from "next/router"; // we'll use this to reload the components w/ changed languages
import { useState } from "react";
import { translateRoute } from "routes";
import { service } from "service";
import { theme } from "theme";
 
import { ALMOST_DONE_CUTOFF, HIDDEN_CUTOFF } from "./constants";
 
interface StyledMuiSelectProps {
  displayMode?: "round" | "rect";
}
 
const StyledSelect = styled(Select, {
  shouldForwardProp: (prop) => prop !== "displayMode",
})<StyledMuiSelectProps>(({ theme, displayMode }) => ({
  borderRadius: displayMode === "round" ? 999 : theme.shape.borderRadius,
  "& .MuiSelect-icon": {
    color: theme.palette.text.primary,
    fontSize: "1.25rem",
    top: "50%",
    transform: "translateY(-50%)",
    right: 10,
  },
  height: 41.25,
}));
 
type LanguagePickerSelectProps = {
  displayMode?: "round" | "rect";
};
 
export default function LanguagePickerSelect({
  displayMode = "round",
}: LanguagePickerSelectProps) {
  const router = useRouter();
  const { asPath, locale, pathname } = router;
  const { authState } = useAuthContext();
  const isAuthenticated = authState.authenticated;
 
  const isMobile = useMediaQuery(theme.breakpoints.down("md"));
  const { t } = useTranslation([GLOBAL]);
 
  const { data: languages, isLoading, error } = useWeblateStats();
 
  const [isOpen, setIsOpen] = useState(false);
 
  const { mutate: changeLanguageMutation } = useMutation({
    mutationFn: (newLanguage: string) =>
      service.account.changeLanguage(newLanguage),
  });
 
  const handleChange = async (event: SelectChangeEvent<unknown>) => {
    const newLocale = event.target.value as string;
 
    if (isAuthenticated) {
      await changeLanguageMutation(newLocale);
    }
 
    // Push new route with updated locale, keep the current asPath for display
    router.push({ pathname }, asPath, { locale: newLocale });
  };
 
  const handleTranslationProgressClick = (e: React.MouseEvent) => {
    e.stopPropagation();
 
    setIsOpen(false);
    router.push(translateRoute);
  };
 
  const renderFlag = (flagCode: string, percent?: number) => {
    const commonStyles = {
      filter:
        percent && percent < ALMOST_DONE_CUTOFF ? "grayscale(100%)" : "none",
      opacity: percent && percent < ALMOST_DONE_CUTOFF ? 0.4 : 1,
    } as const;
 
    Iif (flagCode === "CAT") {
      return (
        <CatalanFlagIcon
          sx={{ width: 25, height: 18.75, ...commonStyles }}
          aria-label="Catalan flag"
        />
      );
    }
 
    return (
      <img
        alt={`${flagCode} flag`}
        src={`https://cdn.couchers.org/img/language-icons/${flagCode}.svg`}
        style={{ width: 25, ...commonStyles }}
      />
    );
  };
  // Languages with < 20% translated are hidden
  // Languages with < 80% translated are greyed out
  const availableLanguages = languages
    ?.filter(
      (language) =>
        LANGUAGE_MAP[language.code.replace("_", "-")] &&
        language.translated_percent > HIDDEN_CUTOFF,
    )
    // sort by translated percent with the >= 80 grouped at the top, then sorted alphabetically by code
    .sort((a, b) => {
      Iif (
        a.translated_percent >= ALMOST_DONE_CUTOFF &&
        b.translated_percent < ALMOST_DONE_CUTOFF
      )
        return -1;
      if (
        a.translated_percent < ALMOST_DONE_CUTOFF &&
        b.translated_percent >= ALMOST_DONE_CUTOFF
      )
        return 1;
      return a.code.localeCompare(b.code);
    });
 
  const menuItems: React.ReactNode[] | undefined = isLoading
    ? []
    : availableLanguages?.map((language) => {
        // language.code has underscore, we need to change to hyphen
        const languageCode = language.code.replace("_", "-");
 
        return (
          <MenuItem
            key={languageCode}
            value={languageCode}
            sx={{
              display: "flex",
              alignItems: "center",
              gap: theme.spacing(1),
              "& .Mui-selected": {
                backgroundColor: theme.palette.action.selected,
              },
              "& .Mui-selected:hover": {
                backgroundColor: theme.palette.action.hover,
              },
            }}
          >
            <Stack
              sx={{ width: "100%" }}
              direction="row"
              alignItems="center"
              justifyContent="space-between"
            >
              <Stack direction="row">
                <ListItemIcon>
                  {renderFlag(
                    LANGUAGE_MAP[languageCode].flagIconCode,
                    language.translated_percent,
                  )}
                </ListItemIcon>
                <ListItemText
                  sx={{
                    opacity:
                      language.translated_percent < ALMOST_DONE_CUTOFF
                        ? 0.4
                        : 1,
                    fontWeight: "bold",
                    display: "inline",
                  }}
                >
                  {languageCode.toUpperCase()}
                </ListItemText>
              </Stack>
              <div>
                {locale === languageCode && (
                  <CheckIcon fontSize="small" sx={{ color: "#00a69a" }} />
                )}
              </div>
            </Stack>
          </MenuItem>
        );
      });
 
  // renderValue function for what should be rendered after a selection is made
  const renderValue = (value: unknown) => {
    const selected = value as string;
    const selectedDisplay = (
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 1,
          pl: 1,
          color: "#666666",
          fontWeight: "bold",
        }}
      >
        {renderFlag(LANGUAGE_MAP[selected].flagIconCode)}
        {selected.toUpperCase()}
      </Box>
    );
    return selectedDisplay;
  };
 
  return (
    <>
      {error && (
        <Snackbar severity="error">
          {t("global:language_preference.error_loading_languages")}
        </Snackbar>
      )}
      <Box sx={{ minWidth: 40 }}>
        <FormControl
          variant="outlined"
          sx={{
            width:
              displayMode === "round"
                ? "fit-content"
                : !isMobile
                  ? "241px"
                  : "100%",
          }}
        >
          {displayMode === "round" ? (
            <StyledSelect
              id="language-select"
              value={isLoading ? "" : locale || ""}
              displayMode={displayMode}
              onChange={handleChange}
              // Use renderValue to display the selected language in collapsed state
              renderValue={renderValue}
              IconComponent={ExpandMoreOutlinedIcon}
              disabled={isLoading}
              open={isOpen}
              onOpen={() => setIsOpen(true)}
              onClose={() => setIsOpen(false)}
            >
              {menuItems}
              <Box
                key="translation-progress"
                onClick={handleTranslationProgressClick}
                sx={{
                  borderTop: `1px solid ${theme.palette.divider}`,
                  mt: 1,
                  pt: 1,
                  px: 2,
                  cursor: "pointer",
                  "&:hover": {
                    backgroundColor: "action.hover",
                  },
                }}
              >
                <Typography
                  color="primary"
                  sx={{ fontWeight: "bold" }}
                  onClick={handleTranslationProgressClick}
                >
                  {t("global:language_preference.translation_progress.title")}
                </Typography>
              </Box>
            </StyledSelect>
          ) : (
            <StyledSelect
              id="newLanguage"
              displayMode={displayMode}
              value={isLoading ? "" : locale}
              placeholder={t("global:language_preference.select_language")}
              fullWidth={isMobile}
              onChange={handleChange}
              disabled={isLoading}
              open={isOpen}
              onOpen={() => setIsOpen(true)}
              onClose={() => setIsOpen(false)}
            >
              {menuItems}
              <Box
                onClick={handleTranslationProgressClick}
                sx={{
                  borderTop: `1px solid ${theme.palette.divider}`,
                  mt: 1,
                  pt: 1,
                  px: 2,
                  py: 1,
                  cursor: "pointer",
                  "&:hover": {
                    backgroundColor: "action.hover",
                  },
                }}
              >
                <Typography
                  variant="body2"
                  color="primary"
                  onClick={handleTranslationProgressClick}
                >
                  {t("global:language_preference.translation_progress.title")}
                </Typography>
              </Box>
            </StyledSelect>
          )}
        </FormControl>
      </Box>
    </>
  );
}