%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home/emergentqj/actioncivile/pre-auth/.8352c036a19b0051d0217d27d25e3f4a/static/js/components/
Upload File :
Create Path :
Current File : /home/emergentqj/actioncivile/pre-auth/.8352c036a19b0051d0217d27d25e3f4a/static/js/components/CountryDropdown.js

import React, {
  useCallback, useEffect, useRef, useState,
} from "react";
import {
  arrayOf, func, object, shape, string, bool,
} from "prop-types";
import { withTranslation, useTranslation } from "react-i18next";
import { withStyles } from "@material-ui/core/styles";
import { ArrowDropDown } from "@material-ui/icons";

import { trackMixpanelActions } from "utils";
import useOnClickOutside from "utils/useOnClickOutside";
import { getLanguageByCountry } from "utils/getLanguage";
import MIXPANEL_ACTIONS from "constants/mixpanel_actions";
import DropdownMenu from "components/DropdownMenu";

const styles = (theme) => ({
  wrapper: {
    position: "relative",
    minWidth: 0,
    minHeight: 0,
  },
  wrapperBorder: {
    border: "1px solid #C4C4C4",
    borderRadius: "4px",
    padding: "6px 14px",
  },
  flagWrapper: {
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    width: "100%",
    minWidth: 0,
    minHeight: 0,
    cursor: "pointer",
  },
  flag: {
    height: "15px",
    width: "20px",
    boxSizing: "content-box",
    borderRadius: "2px",
    border: "1px solid #aaa",
  },
  country: {
    width: "100%",
    display: "flex",
    alignItems: "center",
    minWidth: 0,
    minHeight: 0,
  },
  arrow: {
    color: theme.palette.text.secondary,
  },
  countryName: {
    paddingLeft: "8px",
    marginTop: 3,
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
    minWidth: 0,
    minHeight: 0,
    color: theme.palette.text.primary,
  },
  countryChoose: {
    marginTop: 3,
  },
});

const updateQueryString = (countryCode) => {
  const language = getLanguageByCountry(countryCode);

  if ("URLSearchParams" in window) {
    const searchParams = new URLSearchParams(window.location.search);

    searchParams.set("country", countryCode);
    searchParams.set("lang", language);

    const newRelativePathQuery = `${window.location.pathname}?${searchParams.toString()}`;
    window.history.pushState(null, "", newRelativePathQuery);
  }
};

function CountryDropdown({
  classes,
  countryCode,
  choosableCountries,
  setCountry,
  setLanguage,
  withBorder,
  fullWidthDropdown,
}) {
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [t] = useTranslation();
  const country = choosableCountries.find(({ code }) => code === countryCode);

  const changeCountry = useCallback((code, isUpdateQueryString) => {
    if (code === countryCode) return;

    if (isUpdateQueryString) {
      updateQueryString(code);
    }

    setCountry(code);
    setLanguage(code);
    setDropdownOpen(false);

    trackMixpanelActions(MIXPANEL_ACTIONS.LANGUAGE_SWITCHED, {
      category: "LanguageSwitch",
      channel: "DesktopWeb",
      eventType: "click",
      label: code,
    });
  }, [countryCode, setCountry, setLanguage]);

  useEffect(() => {
    const popStateListener = () => {
      const qsCountry = new URLSearchParams(window.location.search).get("country");
      const newCountry = choosableCountries.find(({ code }) => code === qsCountry);
      if (newCountry?.code) {
        changeCountry(newCountry.code);
      }
    };

    window.addEventListener("popstate", popStateListener);
  }, [changeCountry, choosableCountries]);

  const ref = useRef();
  useOnClickOutside(ref, () => setDropdownOpen(false));

  return (
    <div
      role="button"
      tabIndex={0}
      ref={ref}
      className={`${classes.wrapper}${withBorder ? ` ${classes.wrapperBorder}` : ""}`}
      onClick={() => setDropdownOpen(!dropdownOpen)}
      onKeyPress={(event) => {
        if (event.key === "Enter") {
          setDropdownOpen(!dropdownOpen);
        }
      }}
    >
      <div className={classes.flagWrapper}>
        <span className={classes.country}>
          {countryCode && (
            <img
              // eslint-disable-next-line import/no-dynamic-require, global-require
              src={require(`assets/images/flags/${countryCode.toLowerCase()}.svg`)}
              alt={country.name}
              className={classes.flag}
            />
          )}
          {country ? (
            <span className={classes.countryName}>{country.name[0]}</span>
          ) : (
            <span className={classes.countryChoose}>Choose country</span>
          )}
        </span>
        <ArrowDropDown
          className={classes.arrow}
          style={{
            transform: dropdownOpen ? "rotate(180deg)" : "",
          }}
        />
      </div>

      {dropdownOpen && (
        <DropdownMenu fullWidthDropdown={fullWidthDropdown} title={t("auth.login.selectAccountCountry")}>
          {choosableCountries.map(({ code, name }) => (
            <CountryDropdownButton
              key={code}
              classes={classes}
              name={name}
              code={code}
              countryCode={countryCode}
              changeCountry={() => changeCountry(code, true)}
            />
          ))}
        </DropdownMenu>
      )}
    </div>
  );
}

export function CountryDropdownButton({
  classes,
  name,
  code,
  countryCode,
  changeCountry,
}) {
  return (
    <li
      className={`${classes.dropdownItem} ${
        code === countryCode && classes.selectedItem
      }`}
    >
      <div
        role="button"
        tabIndex={0}
        onClick={() => {
          changeCountry();
        }}
        onKeyPress={(event) => {
          if (event.key === "Enter") {
            changeCountry();
          }
        }}
        className={classes.dropdownItemButton}
      >
        <img
          alt={name.join(" / ")}
          className={classes.dropdownItemImage}
          // eslint-disable-next-line import/no-dynamic-require, global-require
          src={require(`assets/images/flags/${code.toLowerCase()}.svg`)}
        />
        {name.join(" / ")}
      </div>
    </li>
  );
}

CountryDropdownButton.propTypes = {
  classes: object,
  code: string.isRequired,
  countryCode: string.isRequired,
  name: arrayOf(string).isRequired,
  changeCountry: func.isRequired,
};

CountryDropdownButton.defaultProps = {
  classes: styles,
};

CountryDropdown.propTypes = {
  countryCode: string,
  choosableCountries: arrayOf(
    shape({
      code: string.isRequired,
      name: arrayOf(string).isRequired,
    }),
  ).isRequired,
  classes: object.isRequired,
  setCountry: func.isRequired,
  setLanguage: func.isRequired,
  withBorder: bool,
  fullWidthDropdown: bool,
};

CountryDropdown.defaultProps = {
  countryCode: null,
  withBorder: false,
  fullWidthDropdown: false,
};

export default withTranslation()(withStyles(styles)(CountryDropdown));

Zerion Mini Shell 1.0