69 lines
2 KiB
TypeScript
69 lines
2 KiB
TypeScript
// * Packages
|
|
import { usePage } from "@inertiajs/react";
|
|
import { ReactNode } from "react";
|
|
// * Other
|
|
import { AppEnv } from "@/back/types/global";
|
|
import { TranslationField } from "@/back/types/i18n";
|
|
import useTrans from "@/hooks/use-translations";
|
|
|
|
/**
|
|
* Resolves the best translation value for the current locale.
|
|
*
|
|
* Priority:
|
|
* 1. Value for the current app locale
|
|
* 2. First non-empty available translation (fallback)
|
|
*
|
|
* @param value - Translation field containing localized values
|
|
* @return An object with the resolved value and optional fallback locale,
|
|
* or null if no translation is available
|
|
*/
|
|
function useGetTranslationValue(
|
|
value?: TranslationField,
|
|
): { value: string; locale?: string } | null {
|
|
const { appEnv } = usePage().props as unknown as {
|
|
appEnv: AppEnv;
|
|
};
|
|
if (!value) return null;
|
|
|
|
const local = value[appEnv.locale];
|
|
if (local) return { value: local };
|
|
|
|
const fallback = Object.entries(value).find(([, v]) => v?.trim());
|
|
if (!fallback) return null;
|
|
|
|
return { value: fallback[1], locale: fallback[0] };
|
|
}
|
|
|
|
/**
|
|
* Renders a table cell displaying a translated value.
|
|
*
|
|
* - Displays the value directly if it matches the current locale
|
|
* - Displays "locale: value" when a fallback translation is used
|
|
* - Displays a "not known" message when no translation is available
|
|
*
|
|
* @param value - Translation field containing localized values
|
|
* @return A ReactNode ready to be rendered inside a table cell
|
|
*/
|
|
export default function RenderTranslationCell({
|
|
value,
|
|
}: {
|
|
value?: TranslationField;
|
|
}): ReactNode {
|
|
const result = useGetTranslationValue(value);
|
|
const notKnown = useTrans("back.table_not_known");
|
|
|
|
if (!result) {
|
|
return <p className="text-muted-foreground italic m-0">{notKnown}</p>;
|
|
}
|
|
|
|
if (!result.locale) {
|
|
return result.value;
|
|
}
|
|
|
|
return (
|
|
<span className="italic text-xs">
|
|
<span className="text-muted-foreground mr-1">{result.locale}:</span>
|
|
{result.value}
|
|
</span>
|
|
);
|
|
}
|