wip: Extract country list generation into utility
This commit is contained in:
parent
46f31de837
commit
e7ada4b47d
2 changed files with 52 additions and 37 deletions
50
frontend/src/utils/countries.ts
Normal file
50
frontend/src/utils/countries.ts
Normal file
|
@ -0,0 +1,50 @@
|
|||
import iso3166 from "iso-3166-1";
|
||||
|
||||
/**
|
||||
* While the iso-3166-1 library does provide a country interface, said interface is not exported.
|
||||
* We re-define it to make it usable for our purposes.
|
||||
*/
|
||||
export type Country = ReturnType<typeof iso3166.all>[number];
|
||||
|
||||
// Define interface for divider/header items
|
||||
export interface CountryDivider {
|
||||
divider: boolean;
|
||||
header: string;
|
||||
}
|
||||
|
||||
// Define a type that can be either a Country or a Divider
|
||||
export type CountryListItemType = Country | CountryDivider;
|
||||
|
||||
// Get all countries from iso3166
|
||||
export const allCountries = iso3166.all() as Country[];
|
||||
|
||||
// Get user's locale from browser (module-scoped)
|
||||
export const userLocale = navigator.language || navigator.languages?.[0] || 'en-US';
|
||||
export const userCountryCode = userLocale.split('-')[1]?.toUpperCase() || '';
|
||||
|
||||
// Find user's country based on browser locale (module-scoped)
|
||||
export const userCountry = allCountries.find(c => c.alpha2 === userCountryCode);
|
||||
|
||||
/**
|
||||
* Prepares a list of countries with the user's country at the top (if available)
|
||||
* @returns An array of countries and dividers for use in selection components
|
||||
*/
|
||||
export function getAvailableCountries(): CountryListItemType[] {
|
||||
|
||||
// Create the country list
|
||||
const countries: CountryListItemType[] = [];
|
||||
|
||||
// Add user's country at the top if found
|
||||
if (userCountry) {
|
||||
countries.push(userCountry);
|
||||
countries.push({ divider: true, header: 'All Countries' });
|
||||
|
||||
// Add all countries except the user's country to avoid duplicates
|
||||
countries.push(...allCountries.filter(c => c.alpha2 !== userCountryCode));
|
||||
} else {
|
||||
// Add all countries if user's country not found
|
||||
countries.push(...allCountries);
|
||||
}
|
||||
|
||||
return countries;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue