"use client";
import { usePathname } from "next/navigation";
import * as React from "react";
import { LOCALES, localeCookie, type Locale } from "@/src/domain/locale";
import { switchPath } from "@/src/domain/routes";
import { DecodeText } from "./bits/DecodeText";
import { useContent, useLocale } from "./ContentProvider";
import {
getIdleState,
getSwitchState,
startSwitch,
subscribe,
} from "./locale-switch-store";
const EASE = "cubic-bezier(0.23, 1, 0.32, 1)";
/**
* LanguageSwitch: the two languages side by side, with a marker that slides to
* the chosen one. Choosing a language closes the bit curtain (see BitCurtain),
* swaps the page behind it and keeps the reading position. The choice is stored
* in a cookie so that the language detection does not undo it.
*
* The options are plain links to the other language's address, so the switch
* also works without JavaScript and for search engines.
*/
export const LanguageSwitch: React.FC<{
/** `pill` for the header, `text` for the footer. */
variant?: "pill" | "text";
}> = ({ variant = "pill" }) => {
const locale = useLocale();
const { nav } = useContent();
const pathname = usePathname();
const state = React.useSyncExternalStore(
subscribe,
getSwitchState,
getIdleState,
);
// The marker moves as soon as a language is chosen, before the page follows.
const shown = state.phase === "idle" ? locale : state.target;
const choose = (target: Locale) => (event: React.MouseEvent) => {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
return;
}
event.preventDefault();
if (target === locale) return;
document.cookie = localeCookie(target);
startSwitch(locale, target, switchPath(pathname, target));
};
if (variant === "text") {
return (
);
}
return (
);
};