Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

6.0 KB
Raw Blame
import { FallbackLngObjList } from "i18next";
import { useTranslation } from "react-i18next";
import i18n, { locales, TLocale } from "@/i18n";
import enTranslation from "@/locales/en.json";

const LOCALE_STORAGE_KEY = "memos-locale";
const LOCALE_DIRECTION_CHANGE_EVENT = "memos:locale-direction-change";

export type LocaleDirection = "ltr" | "rtl";

export const getLocaleDirection = (): LocaleDirection =>
  typeof document !== "undefined" && document.documentElement.dir === "rtl" ? "rtl" : "ltr";

export const subscribeToLocaleDirection = (listener: () => void): (() => void) => {
  if (typeof window === "undefined") return () => {};
  window.addEventListener(LOCALE_DIRECTION_CHANGE_EVENT, listener);
  return () => window.removeEventListener(LOCALE_DIRECTION_CHANGE_EVENT, listener);
};

export const applyDocumentLocale = (locale: string): LocaleDirection => {
  const direction = i18n.dir(locale);
  if (typeof document === "undefined") return direction;

  const previousDirection = document.documentElement.getAttribute("dir");
  document.documentElement.lang = locale;
  document.documentElement.dir = direction;
  if (previousDirection !== direction && typeof window !== "undefined") {
    window.dispatchEvent(new Event(LOCALE_DIRECTION_CHANGE_EVENT));
  }
  return direction;
};

const getStoredLocale = (): Locale | null => {
  try {
    const stored = localStorage.getItem(LOCALE_STORAGE_KEY);
    return stored && locales.includes(stored) ? (stored as Locale) : null;
  } catch {
    return null;
  }
};

const setStoredLocale = (locale: Locale): void => {
  try {
    localStorage.setItem(LOCALE_STORAGE_KEY, locale);
  } catch {
    // localStorage might not be available
  }
};

export const findNearestMatchedLanguage = (language: string): Locale => {
  if (locales.includes(language as TLocale)) {
    return language as Locale;
  }

  const i18nFallbacks = Object.entries(i18n.store.options.fallbackLng as FallbackLngObjList);
  for (const [main, fallbacks] of i18nFallbacks) {
    if (language === main) {
      return fallbacks[0] as Locale;
    }
  }

  const shortCode = language.substring(0, 2);
  if (locales.includes(shortCode as TLocale)) {
    return shortCode as Locale;
  }

  // Try to match "xx-YY" to existing translation for "xx-ZZ" as a last resort
  // If some match is undesired, it can be overridden in src/i18n.ts `fallbacks` option
  for (const existing of locales) {
    if (shortCode == existing.substring(0, 2)) {
      return existing as Locale;
    }
  }

  // should be "en", so the selector is not empty if there isn't a translation for current user's language
  return (i18n.store.options.fallbackLng as FallbackLngObjList).default[0] as Locale;
};

type NestedKeyOf<T, K = keyof T> = K extends keyof T & (string | number)
  ? `${K}` | (T[K] extends object ? `${K}.${NestedKeyOf<T[K]>}` : never)
  : never;

// Represents the keys of nested translation objects.
export type Translations = NestedKeyOf<typeof enTranslation>;

// Represents a typed translation function.
type TypedT = (key: Translations, params?: Record<string, unknown>) => string;

export const useTranslate = (): TypedT => {
  const { t } = useTranslation<Translations>();
  return t;
};

export const isValidLocale = (locale: string | undefined | null): boolean => {
  if (!locale) return false;
  return locales.includes(locale);
};

// Gets the locale to use with proper priority:
// 1. User setting (if logged in and has preference)
// 2. localStorage (from previous session)
// 3. Browser language preference
export const getLocaleWithFallback = (userLocale?: string): Locale => {
  // Priority 1: User setting (if logged in and valid)
  if (userLocale && isValidLocale(userLocale)) {
    return userLocale as Locale;
  }

  // Priority 2: localStorage
  const stored = getStoredLocale();
  if (stored) {
    return stored;
  }

  // Priority 3: Browser language
  return findNearestMatchedLanguage(navigator.language);
};

// Applies and persists a locale setting
export const loadLocale = (locale: string): Locale => {
  const validLocale = isValidLocale(locale) ? (locale as Locale) : findNearestMatchedLanguage(navigator.language);
  setStoredLocale(validLocale);
  applyDocumentLocale(validLocale);
  i18n.changeLanguage(validLocale);
  return validLocale;
};

/**
 * Applies locale early during initial page load to prevent language flash.
 * Uses only localStorage and browser language (no user settings yet).
 */
export const applyLocaleEarly = (): void => {
  const stored = getStoredLocale();
  const locale = stored ?? findNearestMatchedLanguage(navigator.language);
  loadLocale(locale);
};

// Get the display name for a locale in its native language
export const getLocaleDisplayName = (locale: string): string => {
  try {
    const displayName = new Intl.DisplayNames([locale], { type: "language" }).of(locale);
    if (displayName) {
      return displayName.charAt(0).toUpperCase() + displayName.slice(1);
    }
  } catch {
    // Intl.DisplayNames might not be available or might fail for some locales
  }
  return locale;
};

export const normalizeLocaleSearchText = (value: string): string => {
  return value
    .normalize("NFD")
    .replace(/\p{Diacritic}/gu, "")
    .toLowerCase();
};

const getLocaleDisplayNameForLanguage = (locale: string, displayLanguage: string): string => {
  try {
    return new Intl.DisplayNames([displayLanguage], { type: "language" }).of(locale) ?? locale;
  } catch {
    return locale;
  }
};

export const getLocaleSearchLabels = (locale: string, uiLocale: string): string[] => {
  return Array.from(
    new Set([
      locale,
      getLocaleDisplayNameForLanguage(locale, locale),
      getLocaleDisplayNameForLanguage(locale, "en"),
      getLocaleDisplayNameForLanguage(locale, uiLocale),
    ]),
  );
};

export const localeMatchesSearch = (locale: string, query: string, uiLocale: string): boolean => {
  const normalizedQuery = normalizeLocaleSearchText(query.trim());
  if (!normalizedQuery) return true;

  return getLocaleSearchLabels(locale, uiLocale).some((label) => normalizeLocaleSearchText(label).includes(normalizedQuery));
};