Try to show holiday names using the browser's preferred language(s).

The date-holidays library has translations for many holidays, so we can
usually show a useful translation to the user, rather than all holidays
appearing in the language of the selected country.

However, they only support two-character language codes, and don't have
any sort of fallback, e.g. using an available `en` translation if we
pass in `en-GB`. So we just truncate all languages to two characters.
This commit is contained in:
Christopher Orr
2024-11-15 10:07:38 +01:00
parent cca813b3e9
commit 7ac4e085eb

View File

@@ -30,7 +30,11 @@ const formatDate = (date: Date): string => date.toLocaleDateString('en-US', { mo
// Get holidays for a specific year and country // Get holidays for a specific year and country
export function getHolidaysForYear(countryCode: string, year: number, stateCode?: string): { date: Date; name: string }[] { export function getHolidaysForYear(countryCode: string, year: number, stateCode?: string): { date: Date; name: string }[] {
const hd = stateCode ? new Holidays(countryCode, stateCode) : new Holidays(countryCode); // The date-holidays lib has translations for many holidays, but defaults to using the language of the country.
// We can pass in the browser's preferred languages (though the lib doesn't fall back, e.g. from `de-AT` to `de`)
const languages = navigator.languages.map(lang => lang.split('-')[0]);
const opts = { languages }
const hd = stateCode ? new Holidays(countryCode, stateCode, opts) : new Holidays(countryCode, opts);
return hd.getHolidays(year) return hd.getHolidays(year)
.filter(holiday => holiday.type === 'public') .filter(holiday => holiday.type === 'public')
.map(holiday => ({ .map(holiday => ({