website/src/i18n/utils.ts

33 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-03-28 18:30:52 +01:00
import { defaultLocale, getLocale } from 'astro-i18n-aut';
2024-03-26 16:36:18 +01:00
import { ui, defaultLang, showDefaultLang } from './ui';
2024-04-03 18:07:54 +02:00
export function useTranslatedPath(url: URL) {
const locale = getLocale(url);
2024-03-28 18:30:52 +01:00
return function translatePath(path: string, l: string = locale) {
2024-03-26 16:36:18 +01:00
return !showDefaultLang && l === defaultLang ? path : `/${l}${path}`.replace(/\/$/g, '');
}
}
2024-04-03 18:07:54 +02:00
export function useTranslations(url: URL) {
const lang = getLocale(url);
2024-03-26 16:36:18 +01:00
return function t(key: keyof typeof ui[typeof defaultLang]) {
return ui[lang as keyof typeof ui][key] || ui[defaultLang][key];
}
}
export function parseSlug(id: string) {
const splitPath = id.split('/');
const split = splitPath.pop()?.split('.');
const lang = split?.length === 2 ? defaultLocale : split?.[1];
return [splitPath.join("/"), lang]
}
2024-04-03 18:07:54 +02:00
export function filterCollection<T extends { id: string, data: { date: Date } }>(collection: T[], locale: string): T[] {
2024-03-26 16:36:18 +01:00
return collection.filter(post => {
const [_, lang] = parseSlug(post?.id);
return lang === locale;
2024-04-03 14:27:48 +02:00
}).sort((a, b) => {
2024-04-03 18:07:54 +02:00
return (a?.data?.date > b?.data?.date) ? -1 : 1;
2024-03-26 16:36:18 +01:00
});
}