All files / app/components/Navigation DarkModeToggle.tsx

94.44% Statements 17/18
54.54% Branches 6/11
66.66% Functions 2/3
94.44% Lines 17/18

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  1x 1x 1x 1x 1x   4x 8x 8x 8x   8x 4x       8x 4x       4x 4x   4x       4x                                                    
import { DarkModeOutlined, LightModeOutlined } from "@mui/icons-material";
import { IconButton, Tooltip } from "@mui/material";
import { useColorScheme } from "@mui/material/styles";
import { GLOBAL } from "i18n/namespaces";
import { useTranslation } from "next-i18next";
import { useEffect, useState } from "react";
 
export default function DarkModeToggle() {
  const { t } = useTranslation(GLOBAL);
  const { mode, systemMode, setMode } = useColorScheme();
  const [mounted, setMounted] = useState(false);
 
  useEffect(() => {
    setMounted(true);
  }, []);
 
  // Avoid hydration mismatch
  if (!mounted || !mode) {
    return null;
  }
 
  // Determine the actual displayed mode (resolving "system" to the actual mode)
  const resolvedMode = mode === "system" ? systemMode : mode;
  const isDark = resolvedMode === "dark";
 
  const handleToggle = () => {
    setMode(isDark ? "light" : "dark");
  };
 
  const tooltipText = isDark
    ? t("nav.switch_to_light_mode")
    : t("nav.switch_to_dark_mode");
 
  return (
    <Tooltip title={tooltipText}>
      <IconButton
        onClick={handleToggle}
        aria-label={tooltipText}
        sx={{
          padding: 0.5,
          margin: 0,
          color: "var(--mui-palette-text-primary)",
          "&:hover": {
            backgroundColor: "transparent",
            "& .MuiSvgIcon-root": {
              color: "var(--mui-palette-primary-main)",
            },
          },
        }}
      >
        {isDark ? <LightModeOutlined /> : <DarkModeOutlined />}
      </IconButton>
    </Tooltip>
  );
}