jointrashposs/server/plugins/i18nRedirector.ts

42 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-09-29 13:30:27 +02:00
import { useRuntimeConfig } from '#imports';
import { withTrailingSlash } from 'ufo';
import type { LocaleObject } from '@nuxtjs/i18n/dist/runtime/composables';
2023-09-29 13:30:27 +02:00
export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('render:html', (html, { event }) => {
2023-11-03 07:09:50 +01:00
if (event.path.includes("_nuxt") || event.path.match(/\d{3}\.html/) || event.path.match(/^\/ns/)) {
2023-09-29 17:08:56 +02:00
return;
}
const runtimeConfig = useRuntimeConfig();
const locales = runtimeConfig.public.locales as LocaleObject[];
if (!event.path.match(new RegExp(`^/(${locales.map((l) => l.code).join('|')})/`))) {
const links = locales.map((l) => {
const url = withTrailingSlash(`/${l.code}${event.path.replace(/\.html$/g, '/')}`);
return `<a href="${url}">${l.name}</a>`;
});
2023-09-29 13:30:27 +02:00
html.htmlAttrs = [];
const remainingList: string[] = [];
html.head.forEach((v) => {
remainingList.push(...(v.match(/<!--(.|\n)*(?<=-->)/gm) ?? []));
2023-12-23 18:13:23 +01:00
remainingList.push(...(v.match(/<link\s+rel="(og|alternate|canonical|me)[^>]+>/gm) ?? []));
2023-09-29 13:30:27 +02:00
remainingList.push(...(v.match(/<meta[^>]+>/gm) ?? []));
remainingList.push(...(v.match(/<script type="application\/ld\+json">.*(?<=<\/script>)/gm) ?? []));
});
2023-10-28 16:24:50 +02:00
remainingList.push('');
2023-09-29 13:30:27 +02:00
html.head = remainingList.map((v) => v + '\n');
//@ts-ignore
html.head.push('<script type="text/javascript">const s = ' + JSON.stringify(locales.map((l) => l.code)) + '; const d = new URLSearchParams(document.cookie); if (d.get(\'i18n_redirected\')) { location.replace(\'/\' + d.get(\'i18n_redirected\') + location.pathname + location.search); } else if (s.includes(navigator.language.split("-")[0])) { location.replace(\'/\' + navigator.language.split("-")[0] + location.pathname + location.search); } else { location.replace(\'/ja\' + location.pathname + location.search); }</script>\n');
html.body = [
'\n<noscript>Please enable Javascript to see this page properly.</noscript>\n',
`<noscript>${links.join(', ')}</noscript>\n`,
];
2023-09-29 13:30:27 +02:00
html.bodyAppend = [];
html.bodyPrepend = [];
}
});
});