Skip to content

Commit

Permalink
Make browser localization more powerful and automatic
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed Jul 27, 2024
1 parent b838ca1 commit fb1d3ef
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 13 deletions.
6 changes: 6 additions & 0 deletions .changeset/four-clocks-love.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@quilted/browser': patch
'@quilted/preact-localize': patch
---

Make browser localization more powerful and automatic
12 changes: 5 additions & 7 deletions packages/browser/source/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ export class Browser implements BrowserDetails {
readonly bodyAttributes = new BrowserElementAttributes(document.body);
readonly cookies = new BrowserCookies();
readonly serializations = new BrowserSerializations();
readonly locale = new BrowserLocale();
readonly locale: BrowserDetails['locale'];
readonly request = new Request(window.___location.href);

constructor({locale = navigator.language}: {locale?: string} = {}) {
this.locale = {value: locale};
}
}

export class BrowserCookies implements Cookies {
Expand Down Expand Up @@ -218,12 +222,6 @@ function getSerializedFromNode<T = unknown>(node: Element): T | undefined {
}
}

export class BrowserLocale {
get value() {
return navigator.language;
}
}

function setAttributes(
element: Element,
attributes: Record<string, any> | ReadonlySignal<Record<string, any>>,
Expand Down
19 changes: 13 additions & 6 deletions packages/preact-localize/source/Localization.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,11 @@ export function Localization({
direction: explicitDirection,
children,
}: RenderableProps<LocalizationProps>) {
const browserDetails = useBrowserDetails({optional: explicitLocale == null});
const locale = explicitLocale ?? browserDetails?.locale.value;

if (locale == null) {
throw new Error(`Could not determine locale`);
}
const browserDetails = useBrowserDetails({optional: true});
const locale =
explicitLocale ??
browserDetails?.locale.value ??
getLocaleFromEnvironment();

const formatting = useMemo(() => createLocalizedFormatting(locale), [locale]);
const direction =
Expand All @@ -52,3 +51,11 @@ export function Localization({
</LocaleContext.Provider>
);
}

function getLocaleFromEnvironment() {
if (typeof navigator === 'undefined') {
throw new Error(`Could not determine the locale automatically`);
}

return navigator.language;
}

0 comments on commit fb1d3ef

Please sign in to comment.