mirror of
https://gitlab.com/PronounsPage/PronounsPage.git
synced 2025-09-27 23:13:01 -04:00

the #shared alias used by Nuxt cannot be easily disabled and to prevent breackage with jiti, we make use of it
80 lines
2.8 KiB
TypeScript
80 lines
2.8 KiB
TypeScript
import { DateTime, Settings } from 'luxon';
|
|
|
|
import buildLocaleList from '#shared/buildLocaleList.ts';
|
|
import type { Pronoun } from '#shared/classes.ts';
|
|
import { buildDict } from '#shared/helpers.ts';
|
|
import { Translator } from '#shared/translator.ts';
|
|
import { loadConfig, loadTranslations } from '~/src/data.ts';
|
|
import baseTranslations from '~~/locale/_base/translations.suml';
|
|
|
|
declare module '#app' {
|
|
interface NuxtApp {
|
|
$t<T extends string | string[] = string>
|
|
(key: string, params?: Record<string, string | number>, warn?: boolean): NoInfer<T>;
|
|
}
|
|
}
|
|
|
|
declare module 'vue' {
|
|
interface ComponentCustomProperties {
|
|
$t<T extends string | string[] = string>
|
|
(key: string, params?: Record<string, string | number>, warn?: boolean): NoInfer<T>;
|
|
}
|
|
}
|
|
|
|
export default defineNuxtPlugin({
|
|
enforce: 'pre',
|
|
async setup() {
|
|
const [config, translations] = await Promise.all([loadConfig(), loadTranslations()]);
|
|
|
|
const translator = new Translator(translations, baseTranslations, config);
|
|
const t = (key: string, params = {}, warn = false): string => translator.translate(key, params, warn);
|
|
const te = (key: string, fallback = false): boolean => {
|
|
if (translator.has(key)) {
|
|
return true;
|
|
}
|
|
if (fallback && translator.hasFallback(key)) {
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
const translateForPronoun = (str: string, pronoun: Pronoun | null): string => {
|
|
let translation = translator.translate(`flags.${str.replace(/ /g, '_').replace(/'/g, '*')}`, {}, false) || str;
|
|
if (pronoun) {
|
|
translation = pronoun.format(translation);
|
|
}
|
|
return translation;
|
|
};
|
|
|
|
const locales = buildDict(function* () {
|
|
const locales = buildLocaleList(config.locale);
|
|
if (config.locale !== '_') {
|
|
yield [config.locale, locales[config.locale]];
|
|
}
|
|
for (const [locale, localeDescription] of Object.entries(locales)) {
|
|
if (locale !== config.locale) {
|
|
yield [locale, localeDescription];
|
|
}
|
|
}
|
|
});
|
|
|
|
try {
|
|
Settings.defaultLocale = config.intlLocale || config.locale;
|
|
DateTime.now().toFormat('y-MM-dd HH:mm'); // test if locale is supported by luxon
|
|
} catch {
|
|
Settings.defaultLocale = 'en';
|
|
}
|
|
|
|
return {
|
|
provide: {
|
|
// identifier must be different to config because it is already reserved for Nuxt runtime config
|
|
localeConfig: config,
|
|
translator,
|
|
t,
|
|
te,
|
|
translateForPronoun,
|
|
locales,
|
|
},
|
|
};
|
|
},
|
|
});
|