Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat[ATLAS-113]: add locale apis in core module #62

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4e7148c
add getDefaultLocaleForAllCountries api
RgnDunes Feb 1, 2024
48874da
add UT for getDefaultLocaleForAllCountries
RgnDunes Feb 1, 2024
3d58ed1
Create silver-zoos-raise.md
RgnDunes Feb 1, 2024
3d48295
migrate locale module to core module
RgnDunes Feb 1, 2024
ead0f79
update README
RgnDunes Feb 1, 2024
104c66e
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Feb 5, 2024
a30e0e5
add other locale based functions in code module
RgnDunes Feb 5, 2024
2312772
Update silver-zoos-raise.md
RgnDunes Feb 5, 2024
7205835
update README with locale apis docs
RgnDunes Feb 5, 2024
ca7d9cb
reformat README
RgnDunes Feb 5, 2024
0cab1b6
add dynamic import in getAllLocales
RgnDunes Feb 8, 2024
bcb138c
add dynamic import in getDefaultLocaleForAllCountries
RgnDunes Feb 8, 2024
27b22fa
resolve review comments
RgnDunes Feb 8, 2024
20a7dd1
resolve review comments
RgnDunes Feb 8, 2024
cd440e6
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Feb 8, 2024
dd4b0e8
update readme with locale apis desc
RgnDunes Feb 8, 2024
bf164a9
update readme formatting
RgnDunes Feb 8, 2024
b179d1d
[fix]: fix failing UT
RgnDunes Feb 13, 2024
f05b86b
[fix]: Failing UT plus exception messages
RgnDunes Feb 27, 2024
b58aaef
Merge branch 'master' into ATLAS-113-add-getDefaultLocales
RgnDunes Feb 27, 2024
f761fa0
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Feb 27, 2024
1ef3bae
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Feb 29, 2024
956022f
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Mar 12, 2024
4dc6c49
fix failing UT
RgnDunes Mar 12, 2024
e2907ce
fix failing UT
RgnDunes Mar 12, 2024
b875d5a
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Mar 13, 2024
37a8ff9
Merge remote-tracking branch 'origin/master' into ATLAS-113-add-getDe…
RgnDunes Mar 13, 2024
b17d19f
[chore]: back merge master
RgnDunes Apr 1, 2024
b5e1eb1
Merge branch 'master' into ATLAS-113-add-getDefaultLocales
RgnDunes Apr 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/silver-zoos-raise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@razorpay/i18nify-js': minor
---

[feat]: add locale based apis in core module
129 changes: 119 additions & 10 deletions packages/i18nify-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,32 @@ Go on, code conqueror, the adventure awaits!

Welcome to the command center for your i18n experience! This module serves as the control hub, housing the essential functions to manage your i18n settings seamlessly. This module offers a trio of functions to handle all your i18n needs. Whether it's checking the current state, customizing settings, or starting afresh, this module has got you covered in managing your i18n world! 🚀

#### Functions
#### setState(newState)

**setState(newState: Partial `<I18nState>`):** Customize and update your i18n state with ease! Whether you're changing locales or tweaking directions, this function is your ticket to tailor your i18n experience precisely how you want it! 🎨
Customize and update your i18n state with ease! Whether you're changing locales or tweaking directions, this function is your ticket to tailor your i18n experience precisely how you want it! 🎨

```
import { setState } from "@razorpay/i18nify-js/core";
##### Examples
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can include 1 more API.. getLocale which detects locale from browser and returns it. This can be a sync utility.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We already have this utility in .internal. Reusing that.


```javascript
import { setState } from '@razorpay/i18nify-js/core';

// Set a new locale
setState({ locale: 'en-US' });
```

**getState():** Peek into the current i18n state - the active locale, direction, and country settings - at any time, giving you a snapshot of your i18n setup! 📸
#### getState()

```
Peek into the current i18n state – the active locale, direction, and country settings – at any time, giving you a snapshot of your i18n setup! 📸

##### Examples

```javascript
import { getState } from '@razorpay/i18nify-js/core';

// Get the current state
const currentState = getState();
console.log(currentState);
/*
/*
{
locale: 'en-US',
direction: '',
Expand All @@ -55,15 +61,118 @@ console.log(currentState);
*/
```

**resetState():** Made a mess? No worries! Hit the reset button with this function. It's the ultimate undo for your i18n adjustments, whisking your settings back to their pristine defaults. Fresh start, anyone? 🆕
#### resetState()

```
import { resetState } from "@razorpay/i18nify-js/core";
Made a mess? No worries! Hit the reset button with this function. It's the ultimate undo for your i18n adjustments, whisking your settings back to their pristine defaults. Fresh start, anyone? 🆕

##### Examples

```javascript
import { resetState } from '@razorpay/i18nify-js/core';

// Reset everything!
resetState();
```

#### getAllLocales()

The `getAllLocales` function 🌐🔍 is your comprehensive guide to the linguistic landscape of the world. Acting as a detailed atlas, it provides a panoramic view of the diverse locales across all countries, from the bustling cities of Japan to the tranquil countryside of France. This function is a treasure trove for anyone engaged in localization, cultural exploration, or linguistic curiosity, offering a passport to embark on a global journey through languages and dialects.

By invoking `getAllLocales`, you gain access to an extensive map detailing the array of locales for each country. It’s like unlocking a global directory, where every entry points to a unique cultural and linguistic setting 🗺️📖. This functionality enables developers and content creators to tailor experiences that resonate on a personal level with users worldwide, fostering inclusivity and understanding across borders.

##### Examples

```javascript
// Retrieve all locales for every country
const allLocales = getAllLocales();
console.log(allLocales); // Outputs a comprehensive list: { AE: ['ar_AE', 'en_AE'], AL: ['sq_AL'], ... }

// Exploring locales for United Arab Emirates
console.log(allLocales.AE); // Outputs ['ar_AE', 'en_AE']

// Checking out the locales for Albania
console.log(allLocales.AL); // Outputs ['sq_AL']
```

Utilizing `getAllLocales` in your projects opens up a world of possibilities, allowing you to navigate through the rich and varied linguistic landscape of our planet 🌍💡. It serves not just as a tool for technical implementation, but as a bridge connecting the myriad cultures and languages that enrich our global village.

#### getDefaultLocaleByCountry(countryCode)

The `getDefaultLocaleByCountry` function 🌍🔧 is an essential utility designed for applications requiring localization precision. It maps a given ISO country code to its corresponding default locale, facilitating a culturally accurate and linguistically tailored user experience. This function serves as a crucial component in internationalizing applications, ensuring that content is presented in the most appropriate language and format based on the user's geographic location.

By accepting a country code as its single argument, this function delivers the default locale, embodying the primary language or dialect spoken within that territory 🗣️🌐. This enables developers to automatically adjust the language settings of their application or website, promoting accessibility and enhancing user engagement across diverse cultural contexts.

##### Examples

```javascript
// Retrieving the default locale for Germany
const germanyLocale = getDefaultLocaleByCountry('DE');
console.log(germanyLocale); // Outputs 'de-DE'

// Retrieving the default locale for Brazil
const brazilLocale = getDefaultLocaleByCountry('BR');
console.log(brazilLocale); // Outputs 'pt-BR'
```

Incorporating `getDefaultLocaleByCountry` into your development process empowers you to craft applications that not only function globally 🌎💼 but also communicate effectively and respectfully with users worldwide 🗣️❤️, acknowledging and adapting to the rich tapestry of global cultures and languages.

#### getLocalesByCountry(countryCode)

🧭 Locale Explorer. Set sail on a linguistic expedition with getLocalesByCountry! This function is your compass, pointing to all the locales a country embraces. Whether you're tailoring content for the cosmopolitan cities of Canada or the traditional towns of Tanzania, this function ensures you have the full list of linguistic lanes to traverse. It's not just a function; it's your passport to personalization and precision. 🛤️✨

##### Examples

```javascript
// Retrieve locales for Canada
const canadaLocales = getLocalesByCountry('CA');
console.log(canadaLocales); // ['en_CA', 'fr_CA', ...]

// Retrieve locales for Tanzania
const tanzaniaLocales = getLocalesByCountry('TZ');
console.log(tanzaniaLocales); // ['sw_TZ', 'en_TZ']
```

With getLocalesByCountry, your application doesn't just speak languages; it speaks cultures. Navigate the nuances of localization and give your users a home feeling, no matter where they are. 🌍🔍

#### getDefaultLocales()

🌐 This powerhouse function is like the United Nations of locales, bringing together a world of country codes and their corresponding default locales. It's simple: call it, and you get an object packed with every country code linked to its default locale. From 'IN' to 'MY', and beyond, gearing up your app to go global has never been easier! 🌍✨

##### Examples

```javascript
// Retrieve default locales for all countries
const locales = getDefaultLocales();
console.log(locales); // { IN: 'en-IN', MY: 'ms-MY', ... }

// Accessing the default locale for India
console.log(locales.IN); // 'en-IN'

// Accessing the default locale for Malaysia
console.log(locales.MY); // 'ms-MY'
```

With this module, localizing your application is straightforward and efficient. It's like having a world map of languages and cultures right at your fingertips. Dive in and give your users the local touch they deserve! 🌐✨

#### getLocale()

The `getLocale` function 🌍🔧 is a sleek and intelligent utility crafted to seamlessly identify and retrieve the user's current locale setting. Whether your application is scaling the digital heights of global markets or fine-tuning the nuances of local user experiences, `getLocale` serves as your navigator through the intricate web of regional language settings. This function is invaluable for developers aiming to create applications that adapt dynamically to the user's linguistic and cultural environment, offering a personalized touch right from the start.

##### Example

```javascript
// Dynamically retrieve the user's current locale
const userLocale = getLocale();
console.log(userLocale); // Outputs the detected locale, e.g., 'en-US' for a user in the United States

// Example in a non-browser or unsupported environment
// The output defaults to 'en-IN', ensuring broad compatibility
const defaultLocale = getLocale();
console.log(defaultLocale); // Outputs 'en-IN'
```

Employing `getLocale` in your development toolkit opens doors to a world where applications are not just globally aware but also culturally connected. It ensures that every user interaction is informed by linguistic precision and cultural empathy, paving the way for truly globalized digital experiences. 🌐💼

### Module 01: Currency

This module's your go-to guru for everything currency/number-related. 🤑 It's all about formatting, validations, and handy tricks to make dealing with money/numbers a breeze. Here are the cool APIs and utilities this Currency Module gives you to play with! 🚀💸
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import getAllLocales from '../getAllLocales';

// Mock the COUNTRY_TO_ALL_LOCALES data
jest.mock('../data/countryToAllLocales', () => ({
COUNTRY_TO_ALL_LOCALES: {
US: ['en-US', 'es-US'],
GB: ['en-GB', 'cy-GB'],
CA: ['en-CA', 'fr-CA'],
},
}));

describe('core - getAllLocales', () => {
it('should return all countries with their respective locales', async () => {
const expected = {
US: ['en-US', 'es-US'],
GB: ['en-GB', 'cy-GB'],
CA: ['en-CA', 'fr-CA'],
// Expected data matching the mock
};

const result = await getAllLocales();

// Verify the result matches the expected object
expect(result).toEqual(expected);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import getDefaultLocaleByCountry from '../getDefaultLocaleByCountry';

jest.mock('../data/countryToAllLocales.ts', () => ({
COUNTRY_TO_ALL_LOCALES: {
AE: ['ar-AE', 'en-AE'],
US: ['en-US', 'es-US', 'haw-US'],
IN: ['en-IN', 'hi-IN'],
// ... more countries here
},
}));

describe('core - getDefaultLocaleByCountry', () => {
it('returns the default locale for a valid country code', async () => {
await expect(getDefaultLocaleByCountry('AE')).resolves.toBe('ar-AE');
await expect(getDefaultLocaleByCountry('US')).resolves.toBe('en-US');
await expect(getDefaultLocaleByCountry('IN')).resolves.toBe('en-IN');
});

it('throws an error for an invalid country code', async () => {
await expect(getDefaultLocaleByCountry('XX' as any)).rejects.toThrow(
'Invalid countryCode: XX',
);
});

it('returns the only locale for countries with a single locale', async () => {
jest.mock('../data/countryToAllLocales', () => ({
COUNTRY_TO_ALL_LOCALES: {
IN: ['en-IN'], // Mocked to only have one locale
},
}));
await expect(getDefaultLocaleByCountry('IN')).resolves.toBe('en-IN');
});

it('always returns the first locale for countries with multiple locales', async () => {
await expect(getDefaultLocaleByCountry('US')).resolves.toBe('en-US');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import getDefaultLocaleForAllCountries from '../getDefaultLocaleForAllCountries';

// Mock the COUNTRY_TO_ALL_LOCALES data
jest.mock('../data/countryToAllLocales', () => ({
COUNTRY_TO_ALL_LOCALES: {
AE: ['ar-AE', 'en-AE'],
US: ['en-US', 'es-US'],
IN: ['hi-IN', 'en-IN'],
},
}));

describe('locales - getDefaultLocaleForAllCountries', () => {
it('should return a map of countries to their default locales', async () => {
const expected = {
AE: 'ar-AE',
US: 'en-US',
IN: 'hi-IN',
// Expected default locales for mock countries
};

const result = await getDefaultLocaleForAllCountries();

// Verify the result matches the expected object
expect(result).toEqual(expected);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import getLocalesByCountry from '../getLocalesByCountry';

// Mock the COUNTRY_TO_ALL_LOCALES data for consistent testing
jest.mock('../data/countryToAllLocales', () => ({
COUNTRY_TO_ALL_LOCALES: {
US: ['en-US', 'es-US'],
GB: ['en-GB', 'cy-GB'],
},
}));

describe('core - getLocalesByCountry', () => {
it('returns all locales for a valid country code', () => {
expect(getLocalesByCountry('US')).toEqual(['en-US', 'es-US']);
expect(getLocalesByCountry('GB')).toEqual(['en-GB', 'cy-GB']);
});

it('throws an error for an invalid country code', () => {
const invalidCountryCode = 'XX'; // 'XX' is not a valid country code
// @ts-expect-error The function `getLocalesByCountry` is expected to have a mismatched type here so as to test the exception.
expect(() => getLocalesByCountry(invalidCountryCode)).toThrow(
`Invalid countryCode: ${invalidCountryCode}`,
);
});
});