i18n.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. export const locales = ["en", "zh"] as const;
  2. export type Locale = (typeof locales)[number];
  3. export const isLocale = (value: string): value is Locale =>
  4. (locales as readonly string[]).includes(value);
  5. /** Chinese keeps the bare paths; English lives under /en. */
  6. export function localePath(lang: Locale, path: string) {
  7. if (lang === "zh") return path;
  8. return path === "/" ? "/en" : `/en${path}`;
  9. }
  10. /** The language a pathname is in. */
  11. export const localeOf = (pathname: string): Locale =>
  12. pathname === "/en" || pathname.startsWith("/en/") ? "en" : "zh";
  13. /** A pathname without its language prefix. */
  14. export function stripLocale(pathname: string) {
  15. if (pathname === "/en") return "/";
  16. return pathname.startsWith("/en/") ? pathname.slice(3) : pathname;
  17. }
  18. export const htmlLang = { en: "en", zh: "zh-CN" } as const;
  19. export const ogLocale = { en: "en_US", zh: "zh_CN" } as const;
  20. export const dateLocale = { en: "en-US", zh: "zh-CN" } as const;
  21. /** Canonical URL and hreflang alternates for a page that exists in both languages. */
  22. export const alternates = (lang: Locale, path: string) => ({
  23. canonical: localePath(lang, path),
  24. languages: {
  25. en: localePath("en", path),
  26. "zh-CN": path,
  27. "x-default": path,
  28. },
  29. });
  30. export const formatDate = (
  31. lang: Locale,
  32. date: Date | string | number,
  33. options: Intl.DateTimeFormatOptions,
  34. ) =>
  35. new Date(date).toLocaleDateString(dateLocale[lang], {
  36. timeZone: "UTC",
  37. ...options,
  38. });