From 4076758831660f252b844e05570deedce1d28462 Mon Sep 17 00:00:00 2001 From: Joe Carstairs <65492573+Sycamost@users.noreply.github.com> Date: Wed, 27 Dec 2023 13:00:45 +0000 Subject: Pulls out getLocaleFromDocument() --- src/lib/getLocaleFromDocument.ts | 22 ++++++++++++++++++++++ src/pages/[locale]/sign-up/index.astro | 4 ++-- src/pages/[locale]/sign-up/success.astro | 4 ++-- 3 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 src/lib/getLocaleFromDocument.ts (limited to 'src') diff --git a/src/lib/getLocaleFromDocument.ts b/src/lib/getLocaleFromDocument.ts new file mode 100644 index 0000000..83a27ac --- /dev/null +++ b/src/lib/getLocaleFromDocument.ts @@ -0,0 +1,22 @@ +import locales from '$i18n/locales'; +import type Locale from '$types/Locale'; + +/** + * Gets the locale from the provided document. + * + * Assuming the document is generated using a layout inherited from Layout, the + * locale should be set in the `lang` attribute of the element. + * + * @returns {Locale} + */ +export function getLocaleFromDocumentOrThrow(d: Document) { + const locale = d.getElementsByTagName('html')[0].lang as Locale; + if (!locales.includes(locale)) { + throw new Error(` + Tried to find a supported locale in the lang attribute of the HTML + element, but none was found. Found: "${locale}". + `); + } + + return locale; +} diff --git a/src/pages/[locale]/sign-up/index.astro b/src/pages/[locale]/sign-up/index.astro index 4f56f3c..5c6c056 100644 --- a/src/pages/[locale]/sign-up/index.astro +++ b/src/pages/[locale]/sign-up/index.astro @@ -31,17 +31,17 @@ const t = translate(locale);