Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/components/MapView/MapView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ function MapView({
const [userLocation] = useOnyx(ONYXKEYS.USER_LOCATION);
const navigation = useNavigation();
const {isOffline} = useNetwork();
const {translate} = useLocalize();
const {translate, preferredLocale} = useLocalize();
const styles = useThemeStyles();
const theme = useTheme();
const expensifyIcons = useMemoizedLazyExpensifyIcons(['Crosshair', 'MapCurrentLocation']);
Expand Down Expand Up @@ -261,11 +261,18 @@ function MapView({
const initCenterCoordinate = useMemo(() => (interactive ? centerCoordinate : undefined), [interactive, centerCoordinate]);
const initBounds = useMemo(() => (interactive ? undefined : waypointsBounds), [interactive, waypointsBounds]);

// Localize the map labels to the user's preferred app locale so they match the rest of the app.
const localizeLabels = useMemo<{locale: string} | undefined>(() => {
const language = utils.getNativeMapboxLanguage(preferredLocale);
return language ? {locale: language} : undefined;
}, [preferredLocale]);

return !isOffline && isAccessTokenReady && !!defaultSettings ? (
<View style={[style, !interactive ? styles.pointerEventsNone : {}]}>
<Mapbox.MapView
style={{flex: 1}}
styleURL={styleURL}
localizeLabels={localizeLabels}
onMapIdle={setMapIdle}
onCameraChanged={onCameraChanged}
onTouchStart={() => setUserInteractedWithMap(true)}
Expand Down
29 changes: 28 additions & 1 deletion src/components/MapView/MapViewImpl.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,10 @@ function MapViewImpl({
const hasAlternateDirection = !!alternateDirection?.coordinates?.length;

const [userLocation] = useOnyx(ONYXKEYS.USER_LOCATION);
const [countryByIp] = useOnyx(ONYXKEYS.COUNTRY);

const {isOffline} = useNetwork();
const {translate} = useLocalize();
const {translate, preferredLocale} = useLocalize();

const theme = useTheme();
const styles = useThemeStyles();
Expand Down Expand Up @@ -212,6 +213,32 @@ function MapViewImpl({
};
}, [mapRef]);

// cspell:ignore styledata
// Keep the map labels in the user's preferred app locale and its disputed borders drawn from the user's
// own worldview, reapplying whenever the map, the locale or the country changes.
useEffect(() => {
if (!mapRef) {
return;
}

const map = mapRef.getMap();
const applyLocalization = () => {
map.setLanguage(utils.getMapboxLanguage(preferredLocale));
map.setWorldview(utils.getMapboxWorldview(countryByIp));
};

if (map.isStyleLoaded()) {
applyLocalization();
return;
}

// The style must be loaded before labels and borders can be localized, so defer until it is ready.
map.once('styledata', applyLocalization);
return () => {
map.off('styledata', applyLocalization);
};
}, [mapRef, preferredLocale, countryByIp]);

// Tracks the wrapper size so the map mounts when it appears and unmounts when it collapses.
// Re-runs when the wrapper can come into existence, i.e. once the map is no longer pending.
useEffect(() => {
Expand Down
56 changes: 56 additions & 0 deletions src/components/MapView/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,58 @@
import {LOCALES} from '@src/CONST/LOCALES';
import type {Locale} from '@src/CONST/LOCALES';

import type {AlternateDirection, Coordinate} from './MapViewTypes';

/** App locales whose value isn't already the BCP-47 code Mapbox expects for label localization. */
const LOCALE_TO_MAPBOX_LANGUAGE: Partial<Record<Locale, string>> = {
[LOCALES.PT_BR]: 'pt',
[LOCALES.ZH_HANS]: 'zh-Hans',
};

/**
* Languages the native Mapbox Maps SDKs can localize labels to, i.e. the Mapbox Streets v8 `name_*` fields.
* Unlike mapbox-gl on web, the native SDKs reject any other language: iOS throws and Android logs a warning on every map load.
*/
const NATIVE_MAPBOX_SUPPORTED_LANGUAGES = new Set(['ar', 'en', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ja', 'ko', 'vi', 'zh-Hans', 'zh-Hant']);

/**
* Maps an app locale to the BCP-47 language code Mapbox uses to localize map labels.
* Most app locales are already valid Mapbox codes, so only a couple need remapping.
* On web, unsupported codes fall back to each label's local language on the Mapbox side.
*/
function getMapboxLanguage(locale: Locale | undefined): string | undefined {
if (!locale) {
return undefined;
}
return LOCALE_TO_MAPBOX_LANGUAGE[locale] ?? locale;
}

/**
* Maps an app locale to the language the native Mapbox SDKs localize labels to, or undefined when they can't.
* Leaving the language unset keeps the style's default labels instead of raising a native error.
*/
function getNativeMapboxLanguage(locale: Locale | undefined): string | undefined {
const language = getMapboxLanguage(locale);
return language && NATIVE_MAPBOX_SUPPORTED_LANGUAGES.has(language) ? language : undefined;
}

/** A worldview is an ISO 3166-1 alpha-2 country code, so anything that isn't two letters can't be one. */
const ISO_ALPHA_2_COUNTRY = /^[A-Z]{2}$/;

/**
* Maps the user's country to the Mapbox worldview used to draw disputed borders.
* Mapbox only defines a worldview for the handful of countries that dispute borders and falls back to the
* style's default for every other country code, so the country is passed straight through rather than
* matched against a list that would go stale as Mapbox adds worldviews. Anything that isn't a country code
* is dropped, because Mapbox raises an error for codes it can't parse.
*/
function getMapboxWorldview(country: string | undefined): string | undefined {
if (!country || !ISO_ALPHA_2_COUNTRY.test(country)) {
return undefined;
}
return country;
}

/** A geographic point as a plain longitude/latitude pair. Mapbox's `LngLat` became a class in mapbox-gl 3.x, but these helpers only read `.lng`/`.lat`, so a literal shape is all that's needed. */
type LngLatLiteral = {lng: number; lat: number};

Expand Down Expand Up @@ -249,4 +302,7 @@ export default {
isSingleSegmentRoute,
convertSegmentedRouteToSingleSegmentRoute,
getCoordinatesFromAllDirections,
getMapboxLanguage,
getNativeMapboxLanguage,
getMapboxWorldview,
};
86 changes: 86 additions & 0 deletions tests/unit/MapViewUtilsTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,90 @@ describe('MapView utils', () => {
expect(utils.isSingleSegmentRoute([])).toBe(true);
});
});

describe('getMapboxLanguage', () => {
it('passes locales that are already valid Mapbox codes through unchanged', () => {
// Given app locales whose values are already BCP-47 codes that Mapbox can localize labels to

// When each locale is mapped to the language the map labels are rendered in
const languages = [utils.getMapboxLanguage('en'), utils.getMapboxLanguage('es'), utils.getMapboxLanguage('fr'), utils.getMapboxLanguage('de')];

// Then every locale is passed through as is, because Mapbox already understands it and the labels should match the app's language
expect(languages).toEqual(['en', 'es', 'fr', 'de']);
});

it('remaps locales whose value differs from the Mapbox code', () => {
// Given app locales whose values are not the codes Mapbox expects, so Mapbox would not recognize them as is

// When each locale is mapped to the language the map labels are rendered in
const languages = [utils.getMapboxLanguage('pt-BR'), utils.getMapboxLanguage('zh-hans')];

// Then each locale is converted to the matching Mapbox code, so the labels are still shown in the user's language
expect(languages).toEqual(['pt', 'zh-Hans']);
});

it('returns undefined when there is no locale', () => {
// Given a user whose preferred locale has not loaded yet

// When the missing locale is mapped to a Mapbox language
const language = utils.getMapboxLanguage(undefined);

// Then no language is returned, so the map keeps its default labels instead of being set to an invalid language
expect(language).toBeUndefined();
});
});

describe('getNativeMapboxLanguage', () => {
it('returns the Mapbox language for locales the native SDKs can localize labels to', () => {
// Given app locales whose Mapbox language is one of the Mapbox Streets languages the native SDKs support

// When each locale is mapped to the language the native map labels are rendered in
const languages = [utils.getNativeMapboxLanguage('en'), utils.getNativeMapboxLanguage('ja'), utils.getNativeMapboxLanguage('pt-BR'), utils.getNativeMapboxLanguage('zh-hans')];

// Then the same language as on web is returned, so the native labels match the app's language
expect(languages).toEqual(['en', 'ja', 'pt', 'zh-Hans']);
});

it('returns undefined for locales the native SDKs reject', () => {
// Given app locales whose language the native Mapbox SDKs don't support, which makes iOS throw and Android log a warning

// When each locale is mapped to the language the native map labels are rendered in
const languages = [utils.getNativeMapboxLanguage('nl'), utils.getNativeMapboxLanguage('pl'), utils.getNativeMapboxLanguage('el')];

// Then no language is returned, so the native map keeps its default labels without raising an error
expect(languages).toEqual([undefined, undefined, undefined]);
});
});

describe('getMapboxWorldview', () => {
it('passes country codes Mapbox defines a worldview for through unchanged', () => {
// Given countries that Mapbox draws disputed borders for from their own point of view

// When each country is mapped to the worldview the map's borders are drawn from
const worldviews = [utils.getMapboxWorldview('US'), utils.getMapboxWorldview('CN'), utils.getMapboxWorldview('IN'), utils.getMapboxWorldview('JP')];

// Then every country is passed through as is, so users see the borders as their own country recognizes them
expect(worldviews).toEqual(['US', 'CN', 'IN', 'JP']);
});

it('passes countries without a dedicated worldview through so Mapbox falls back to the style default', () => {
// Given countries that Mapbox has no dedicated worldview for

// When each country is mapped to the worldview the map's borders are drawn from
const worldviews = [utils.getMapboxWorldview('DE'), utils.getMapboxWorldview('AU')];

// Then the countries are still passed through, because Mapbox falls back to the style's default worldview and a hardcoded list of supported countries would go stale
expect(worldviews).toEqual(['DE', 'AU']);
});

it('drops anything that is not a country code, which Mapbox would reject', () => {
// Given values that are not two-letter uppercase country codes, such as a missing country or a three-letter code

// When each value is mapped to the worldview the map's borders are drawn from
const worldviews = [utils.getMapboxWorldview(undefined), utils.getMapboxWorldview(''), utils.getMapboxWorldview('USA'), utils.getMapboxWorldview('us')];

// Then no worldview is returned for any of them, because Mapbox raises an error for codes it can't parse
expect(worldviews).toEqual([undefined, undefined, undefined, undefined]);
});
});
});
Loading