Skip to content

Commit

Permalink
improve browser language detection and set nl-be fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
elpoelma committed Jan 22, 2024
1 parent d67bf52 commit 1302825
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/nasty-bottles-pump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"frontend-gelinkt-notuleren": minor
---

Improve browser language detection and set a fallback of `nl-BE`
8 changes: 8 additions & 0 deletions app/routes/application.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Route from '@ember/routing/route';
import { service } from '@ember/service';
import ENV from 'frontend-gelinkt-notuleren/config/environment';
import { decentLocaleMatch } from '../utils/intl';

const featureFlagRegex = /^feature\[(.+)\]$/;

Expand All @@ -9,8 +10,15 @@ export default class ApplicationRoute extends Route {
@service features;
@service session;
@service plausible;
@service intl;

async beforeModel(transition) {
const userLocales = decentLocaleMatch(
navigator.languages,
this.intl.locales,
'nl-BE',
);
this.intl.setLocale(userLocales);
this.updateFeatureFlags(transition.to.queryParams);
await this.startAnalytics();
await this.session.setup();
Expand Down
34 changes: 34 additions & 0 deletions app/utils/intl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Helper function to help pick supported locales for ember-intl.
* Returns exact matches first, then language matches, then the default.
**/
export function decentLocaleMatch(
userLocales,
supportedLocales,
defaultLocale,
) {
// Ember-intl lowercases locales so we can make comparisons easier by doing the same
const userLocs = userLocales.map((locale) => locale.toLowerCase());
const supportedLocs = supportedLocales.map((locale) => locale.toLowerCase());

// First find exact matches. Use a set to avoid duplicates while preserving insert order.
const matches = new Set(
userLocs.filter((locale) => supportedLocs.includes(locale)),
);

// Then look for locales that just match based on language,
// e.g. match en or en-US if looking for en-GB
const languageMap = {};
supportedLocs.forEach((locale) => {
const lang = locale.split('-')[0];
languageMap[lang] = [...(languageMap[lang] || []), locale];
});
userLocs.forEach((locale) => {
const looseMatches = languageMap[locale.split('-')[0]] ?? [];
looseMatches.forEach((match) => matches.add(match));
});

// Add the default so we always have something
matches.add(defaultLocale.toLowerCase());
return [...matches];
}

0 comments on commit 1302825

Please sign in to comment.