npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@procore/globalization-toolkit

v3.4.1

Published

i18n formatting library

Downloads

4,233

Maintainers

swati.jadhavswati.jadhavtejeshwartejeshwarmohitsharma97mohitsharma97andreszorrilla-procoreandreszorrilla-procoremagdyyxxmagdyyxxcharan_procorecharan_procorealy-el-kerdanyaly-el-kerdanys_kudryks_kudrykadarsh.gautamadarsh.gautamvishal-procorevishal-procorekalyani.gosavikalyani.gosaviamit.gurav-contractoramit.gurav-contractorworldofsatyakiworldofsatyakikuldeepsingh4556kuldeepsingh4556karina.mendez-contractorkarina.mendez-contractorbikash.sahoobikash.sahoorowan.ibrahimrowan.ibrahimvinayakaprabhuvinayakaprabhusaurasumprocoresaurasumprocoreconner-procoreconner-procorechaitra-m-15chaitra-m-15vsobol-cvsobol-cabhishekkumar123abhishekkumar123jasaswinijasaswinialeh.haurylenia-contractoraleh.haurylenia-contractorkellikearnskellikearnsviktoriia_azarovskaviktoriia_azarovskafabriciobdfabriciobdyoussefameryoussefamerbrockpcorbrockpcorkani-procorekani-procoreantonyayoubantonyayoubashish.sharma2024ashish.sharma2024glidenorglidenordaniel-pierre-procoredaniel-pierre-procoreamitk030amitk030mathenes_procoremathenes_procorevinoth.kuppusamyvinoth.kuppusamymariia.solodovnikmariia.solodovniksflang-procoresflang-procorecassianomatos-procorecassianomatos-procorealan.facchini-contractoralan.facchini-contractorzayterzayterbohdan-horai-procorebohdan-horai-procorenigeld-procorenigeld-procoresamad.viranisamad.viranifernandocamilottifernandocamilotticonnie-feng-procoreconnie-feng-procoreroger-procoreroger-procoreganesh.raghupathyganesh.raghupathyyzhou2024yzhou2024alyelashram_procorealyelashram_procoremelch-procoremelch-procorepeterknifpeterknifmoaz-ashrafmoaz-ashrafattachiattachia.elbadaweia.elbadaweihyogmanhyogmandmitri_wmdmitri_wmstephanie.breretonstephanie.breretonprocore-oss-userprocore-oss-userstevenkang3stevenkang3max.helmetagmax.helmetagcodyrobertsprocorecodyrobertsprocoremiguel.garcia-procoremiguel.garcia-procoreatoaimaatoaimamustafa-abdelrahmanmustafa-abdelrahmanelewando-procoreelewando-procoreahmed.ghorabahmed.ghorablnspatz914lnspatz914richard.bunnrichard.bunnomar.wagdyomar.wagdymona.khairbekmona.khairbekmbartlett413mbartlett413cody_schindler_procorecody_schindler_procoreyoasyo25yoasyo25ritchleeritchleeandersontr15andersontr15steven.hinklesteven.hinklejamie-dugan-procorejamie-dugan-procorehgouhierprocorehgouhierprocoredenzylbalramdenzylbalramsarah.freitassarah.freitasalan.bresanialan.bresaniamyprocoreamyprocoreyoyis3000yoyis3000elijah.procoreelijah.procoremike-arndt-procoremike-arndt-procorejnhoang1jnhoang1pam-whisenhuntpam-whisenhuntshradha.khardshradha.kharddavid-christensen-procoredavid-christensen-procorejavio-procorejavio-procorechance.eakin.procorechance.eakin.procoregideon-procoregideon-procoreihor.diachenko_procoreihor.diachenko_procorejustinmwattsjustinmwattstedyangtedyangjyang-procorejyang-procorepwhisenhunt-procorepwhisenhunt-procorefairchildfairchildrodayna.ehabrodayna.ehabneil1023neil1023scottsternscottsternbrian.smith1brian.smith1g2mitchellg2mitchelldlameter-procoredlameter-procorekylepietzkylepietzabhijit-procoreabhijit-procorelhuang325lhuang325jake-pitkinjake-pitkinerikthoresonerikthoresonsimona.iancusimona.iancudecha-sansondecha-sansonaberkowitzaberkowitzasamayasamaymustafa-u-abdelrahmanmustafa-u-abdelrahmanrajatmenhdirattarajatmenhdirattajacksonleach-procorejacksonleach-procorepmfrawleypmfrawleyphunguyen-pcorphunguyen-pcortatsiana.cliftontatsiana.cliftondeiabdeiabsrichaitanya.peddintisrichaitanya.peddintikenny.foisykenny.foisymatheusprocorematheusprocorejgreene_procorejgreene_procorehectorthielehectorthieleetokarevetokarevdaniel.ferreira-contractordaniel.ferreira-contractordmccraw-procoredmccraw-procorecyrille.baicyrille.baigreg.sparksgreg.sparksfabiomelo513fabiomelo513phil.custerphil.custerbbreyel921bbreyel921amir-iskanderamir-iskanderneil.mckeemanneil.mckeemannickprocorenickprocorelzhou888lzhou888davidshuredavidshurestevenliprocorestevenliprocoreramysaid2ramysaid2refaiepcnrefaiepcnjgentesjgentesfaraz.haniffaraz.hanifmostafaeltazymostafaeltazyagamaleldinagamaleldinandrew.isaacandrew.isaacsaranahal2saranahal2rodrigo.dejuanarodrigo.dejuanakellen.stewartkellen.stewartbill-wagnerbill-wagnerezrasimeloffezrasimeloffjeffgiaquintojeffgiaquintogturkadzegturkadzesean.spearman.procoresean.spearman.procorekylemartinez-procorekylemartinez-procoreroobo-romeskiroobo-romeskiandres-mendez-procoreandres-mendez-procoregaurav.sharma.procoregaurav.sharma.procoretracy.ottotracy.ottosarah.herediasarah.herediavictorbendeck-pcvictorbendeck-pccbathgatecbathgatedavidkangprodavidkangprokyle.liukyle.liuamin.jaipuriamin.jaipurigrafffffffgrafffffffmishaelowoyemimishaelowoyemievan.cerwonka.procoreevan.cerwonka.procoreilya.dryha-contractorilya.dryha-contractorvaromirvaromiryogevfine1yogevfine1timofeeetimofeeematt.harris0223matt.harris0223winson.chuwinson.chuandersonbispoprocoreandersonbispoprocorescorgiat-procorescorgiat-procoreladavargaladavargaprocore_halzyprocore_halzyenyagaenyagawillpankonienwillpankoniensateesh-kadiyala-procoresateesh-kadiyala-procorechris.berberchris.berbertxin1txin1epalinprocoreepalinprocoremehrdad-panahandehmehrdad-panahandehtyler.wasden.procoretyler.wasden.procorejeremy.lundjeremy.lunddineshkumar.jayakdineshkumar.jayakryanfuentesprocoreryanfuentesprocorestajicsstajicsbrocktillotsonprocorebrocktillotsonprocorekyle.williamskyle.williamsdtorres-procoredtorres-procorenoor.alinoor.aliari-procoreari-procorealanprocorealanprocorejl4everjl4everjames.lawsonjames.lawsonajaykumar-procoreajaykumar-procoredennis.heckmandennis.heckmanlalovar-procorelalovar-procorejames.clearyjames.clearychadryderchadryderdevin.cunningham.procoredevin.cunningham.procoreabhijit.patwardhanabhijit.patwardhanlydiaharalydiaharasherylnapigkitsherylnapigkitchangprocorechangprocoreapcarroll_procoreapcarroll_procoreandy.mayerandy.mayerbob.laskowskibob.laskowskivinaya-procorevinaya-procorekahliholmeskahliholmesandrew.wheelerandrew.wheelerleandro-procleandro-procyadhu.prakashyadhu.prakashjason-kayejason-kayejesse.olsenjesse.olsenpatrick.lardinpatrick.lardinbrad.uranibrad.uraniallenanle.procoreallenanle.procorebrookyboy009brookyboy009uddhavjoglekaruddhavjoglekardancingshelldancingshellrysmithprocorerysmithprocorerobbiegprocorerobbiegprocorejadamsssjadamsssjeremy.bouzigardjeremy.bouzigardtimdohertytimdohertyb.bookoutb.bookoutjalyngjalynghtaelhtaeldev-account-admindev-account-adminsseanwangsseanwangbhargavrndbhargavrndfarismmkfarismmkdannyporrellodannyporrellodanny.oudanny.oumessanjahmessanjaheyvettesoueyvettesoujgee67jgee67cagmzcagmzmariah_delaneymariah_delaneylukenispellukenispelkimhin267kimhin267juliana.hernandezjuliana.hernandezjudy-lu-pcjudy-lu-pcprocore-it-supportprocore-it-supportandrewburke-pcandrewburke-pcjkleintechjkleintechrachel.arkebauerrachel.arkebauerprocore-npm-botprocore-npm-botjames.dabbs-procorejames.dabbs-procorelaurenbrandsteinprocorelaurenbrandsteinprocorescottbieser-procorescottbieser-procorezach.mckenzie.procorezach.mckenzie.procoreshayonj_procoreshayonj_procoreheplayskeysheplayskeysmike.southmike.souththomasoboylethomasoboyledischordedischordederek-carter-procorederek-carter-procoredlgasserdlgassercfprocorecfprocoreevan.waitsevan.waitsjeremy-marcusjeremy-marcusjmejia-fsljmejia-fslersgonzaloersgonzalostephan-procorestephan-procorealeclarsenprocorealeclarsenprocoreyihai.zweifelyihai.zweifeljay-rajanjay-rajanjacky-leijacky-leipeter.jinpeter.jin

Keywords

Readme

globalization-toolkit

i18n formatting library

Maintainer CircleCI NPM

Before implementing the Globalization Toolkit (GTK), please review the Globalization Toolkit Adoption Diagram to determine the best implementation strategy for you. Continue reading for instructions on direct usage of the GTK.

Engineering Documentation

The engineering documentation contains technical documentation for the GTK repo. It details classes, types, interfaces, and features. Continue reading for install and usage instructions. Further reading on the GTK:

Install

NPM

$ npm i --save @procore/globalization-toolkit

YARN

$ yarn add @procore/globalization-toolkit

Usage

The GTK has 3 available classes: NumberFormatter, DateTimeFormatter, CurrencyFormatter. The structure of the GTK Library allows for instantiation of a formatting class with defined options. The instantiated class gives access to related functions. In addition, the GTK makes the class functions available as stand-alone functions. Below are examples of GTK usage with class formatter and with stand-alone functions.

Sanitizing Locales

The GTK supports industry standard locale codes, which means some locales used in the Procore app will not work with the GTK or may not work as expected. For example, the GTK does NOT support Procore Custom Locales. When implementing the GTK, please sanitize the locale to follow industry standard of <language>-<region> like en-US.

Suggested sanitizations: | User Locale | Locale Passed to GTK | Reason | |-|-|-| | en-international | en-GB | Custom locales are not supported | | en-owner | en-US | Custom locales are not supported | | en-owner-beta | en-US | Custom locales are not supported | | en-specialty-contractor | en-US | Custom locales are not supported | | en | en-US | en will work as expected, but prefer <language>-<region> format | | es | es-419 | es is used for Latin America in the monolith but will format numbers like es-ES in the GTK if the region is not specified |

NumberFormatter Class

The GTK NumberFormatter class has the ability to format numbers for a given locale. The NumberFormatter class is instantiated with NumberOptions and has 4 available functions:

  • formatNumber(value: number),
  • formatNumberToParts(value: number),
  • parseNumber(value: string), and
  • getNumberSeparators(locale: string).

The NumberOptions are summarized below:

  • locale: string
  • maximumFractionDigits?: number
  • minimumFractionDigits?: number
  • percent?: 'standard', 'decimal'

Below code blocks display usage of the NumberFormatter class and available functions.

formatNumber() & formatNumberToParts()

import { NumberFormatter } from '@procore/globalization-toolkit';

const value = 1234;
const numberOptions = { locale: "en-US", minimumFractionDigits: 3 };
const formatter = new NumberFormatter(numberOptions);

console.log(formatter.formatNumber(value)) // expected output: '1,234.000'

console.log(formatter.formatNumberToParts(value))
    /**
     *  expected output is an array of objects representing the parts of the formatted number:
     * [
     *  { type: "integer",   value: "1",    },
     *  { type: "group",     value: ",",    },
     *  { type: "integer",   value: "234",  },
     *  { type: "decimal",   value: ".",    },
     *  { type: "fraction",  value: "000",  },
     * ];
    */

parseNumber()

import { NumberFormatter } from '@procore/globalization-toolkit';

const value = "123 456 789,12";
const numberOptions = { locale: "fr-FR" };
const formatter = new NumberFormatter(numberOptions);

console.log(formatter.parseNumber(value)); // expected output: '123456789.12'

console.log(formatter.parseNumber("Abcd")); // expected output: NaN

getSeparators()

import { NumberFormatter } from '@procore/globalization-toolkit';

const germanNumberOptions = { locale: "de-DE" };
const germanFormatter = new NumberFormatter(germanNumberOptions);

console.log(germanFormatter.getSeparators()); // expected output: { decimal: ",", group: "." }

const usNumberOptions = { locale: 'en-US' };
const formatter = new NumberFormatter(usNumberOptions);

console.log(formatter.getSeparators()); // expected output: { decimal: ".", group: "," }

NumberFormatter Functions

The functions used on the NumberFormatter class are also available as stand alone functions. Read more information about each function in the GTK Documentation.

The example below shows usage of the stand alone function: formatNumber().

import { formatNumber } from '@procore/globalization-toolkit';

const value = 1234;
const numberOptions = { locale: "en-US", minimumFractionDigits: 3 };

console.log(formatNumber(value, numberOptions)) // expected output: '1,234.000'

CurrencyFormatter class

The GTK CurrencyFormatter class has the ability to format a number with given options. The CurrencyFormatter class is instantiated with CurrencyOptions. The CurrencyFormatter has 5 available functions:

  • formatCurrency(value: number),
  • formatCurrencyToParts(value: number)
  • parseCurrency(value: string)
  • getCurrencySeparators()
  • getSupportedCurrencies()

The CurrencyOptions are summarized below:

  • currencyIsoCode: string (acceptable ISO codes)
  • locale: string
  • currencySign?: 'accounting', 'standard'
  • currencyDisplay?: 'code', 'name', 'narrowSymbol', 'symbol'
  • maximumFractionDigits?: number
  • minimumFractionDigits?: number

Below code blocks display usage of the CurrencyFormatter class and available functions.

formatCurrency(value: number)

const value = 1234;
const currencyOptions = { locale: "en-US", currencyIsoCode: "USD" };
const formatter = new CurrencyFormatter(currencyOptions);

console.log(formatter.formatCurrency(value)) // expected outcome: '$1,234.00'

Usage with currencyDisplay option

import { CurrencyFormatter } from '@procore/globalization-toolkit';

const value = 1234.567;
const currencyOptions: CurrencyOptions = {
    locale: "de-DE",
    currencyIsoCode: "USD",
    currencyDisplay: "name",
    };
const formatter = new CurrencyFormatter(currencyOptions);

console.log(formatter.formatCurrency(value)); // expected outcome: '1.234,57 US-Dollar'

Usage with minimumFractionDigits and currencyDisplay

const value = 1234.567;
const currencyOptions = {
    locale: "ja-JP",
    minimumFractionDigits: 2,
    currencyIsoCode: "JPY",
};
const formatter = new CurrencyFormatter(currencyOptions);

console.log(formatter.formatCurrency(value)); // expected outcome: '¥1,234.57'

formatCurrencyToParts()

import { CurrencyFormatter } from '@procore/globalization-toolkit';

const value = -1234.56;
const currencyOptions: CurrencyOptions = {
    locale: "en-US",
    currencyIsoCode: "CAD",
    currencySign: "accounting",
};
const formatter = new CurrencyFormatter(currencyOptions);
console.log(formatter.formatCurrencyToParts(value));
    /** expected output:
     * [
     *   { type: "literal", value: "(", },
     *   { type: "currency", value: "CA$", },
     *   { type: "integer", value: "1", },
     *   { type: "group", value: ",", },
     *   { type: "integer", value: "234", },
     *   { type: "decimal", value: ".", },
     *   { type: "fraction", value: "56", },
     *   { type: "literal", value: ")", },
     * ]
     **/

parseCurrency(value: string)

const value = "(1 234 567,56 €)";
const currencyOptions: CurrencyOptions = {
    locale: "fr-FR",
    currencyIsoCode: "EUR",
    currencySign: "accounting",
};
const formatter = new CurrencyFormatter(currencyOptions);

console.log(formatter.parseCurrency(value)); // expected outcome: -1234567.56

getCurrencySeparators

const currencyOptions = { locale: "de-DE", currencyIsoCode: "EUR" };
const formatter = new CurrencyFormatter(currencyOptions);

console.log(formatter.getCurrencySeparators()) // expected outcome: { decimal: ",", group: "." }

getSupportedCurrencies

const currencyOptions = { locale: "es-MX", currencyIsoCode: MXN" }
const formatter = new CurrencyFormatter(currencyOption)

console.log(formatter.getSupportedCurrencies())
    /** expected outcome
     * [
     *   "AED",
     *   "AFN",
     *   "ALL",
     *   ...
     *   ...
     *   "ZWL"
     * ]
    */

CurrencyFormatter Functions

The functions used on the CurrencyFormatter class are also available as stand alone functions. Read more information about each function in the GTK Documentation.

The example below shows usage of the stand alone function: formatCurrency(value, options).

import { formatCurrency, getCurrencySeparators } from '@procore/globalization-toolkit';

const value = 1234;
const currencyOptions = { locale: 'en-US', currencyIsoCode: 'USD' };

console.log(formatCurrency(value, currencyOptions)) // expected output: '$1,234.00'

console.log(getCurrencySeparators(currencyOptions)) // expected output: { decimal: ".", group: "," }

DateTimeFormatter

The GTK DateTimeFormatter class has the ability to format date and time for the correct timezone. The DateTimeFormatter class is instantiated with DateTimeOptions. The DateTimeFormatter has 3 available functions:

  • formatDateTime(value: Date),
  • formatDateTimeToParts(value: Date), and
  • getStartDayOfTheWeek()

The DateTimeOptions can be used in two ways, but the two options cannot be combined. This follows the pattern of Intl.DateTimeFormat.

  1. Style Options:
    • timeStyle: 'short', 'medium', 'long', 'full'
    • dateStyle: 'short', 'medium', 'long', 'full'
  2. Component Options
    • weekday: 'long', 'short', 'narrow'
    • year: 'numeric', '2-digit'
    • month: numeric', '2-digit', 'long', 'short', 'narrow'
    • day: 'numeric', '2-digit'
    • hour: 'numeric', '2-digit'
    • minute: 'numeric', '2-digit'
    • second: 'numeric', '2-digit'

Below code blocks display usage of the DateTimeFormatter class and available functions. formatDateTime(value: Date) SIMPLE OPTIONS

import { DateTimeFormatter } from '@procore/globalization-toolkit';

const value = new Date(1445419756738);
const dateTimeOptions = {
    locale: 'en-US',
    timeZone: 'UTC',
    dateStyle: 'full',
    timeStyle: 'long',
};
const formatter = new DateTimeFormatter(dateTimeOptions);

console.log(formatter.formatDateTime(value))
// expected output: Wednesday, October 21, 2015 at 9:29:16 AM UTC

COMPLEX OPTIONS

const value = new Date(Date.UTC(1885, 8, 1, 12, 0, 16, 738));
const dateTimeOptions = {
    locale: 'en-US',
    timeZone: 'UTC',
    weekday: 'long',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
};
const formatter = new DateTimeFormatter(dateTimeOptions);

console.log(formatter.formatDateTime(value))
// expected output: "Tuesday, 09/01/1885, 12:00:16 PM";

formatDateTimeToParts(value: Date)

const value = new Date(Date.UTC(1955, 10, 5, 6, 0, 16, 738));
const dateTimeOptions = {
    locale: "en-GB",
    timeZone: "UTC",
    dateStyle: DateStyle.FULL,
    timeStyle: TimeStyle.SHORT,
};
const formatter = new DateTimeFormatter(dateTimeOptions);

console.log(formatter.formatDateTime(value))
    /**   expected output:
     *   [ { type: "weekday", value: "Saturday", },
     *     { type: "literal", value: ", ", },
     *     { type: "day", value: "5", },
     *     { type: "literal", value: " ", },
     *     { type: "month", value: "November", },
     *     { type: "literal", value: " ", },
     *     { type: "year", value: "1955", },
     *     { type: "literal", value: " at ",},
     *     { type: "hour", value: "06",},
     *     { type: "literal", value: ":",},
     *     { type: "minute", value: "00",}, ];
     **/

[formatDateTimeToLocalISOString(value: Date)] This function returns a local ISO 8601 string. This method was designed only for internal purposes. Must not be used to display dates in the Procore UI.

const value = new Date(Date.UTC(1955, 10, 5, 6, 0, 16, 738));
const dateTimeOptions = {
    locale: "en-GB",
    timeZone: "UTC",
    dateStyle: DateStyle.FULL,
    timeStyle: TimeStyle.SHORT,
};
const formatter = new DateTimeFormatter(dateTimeOptions);

console.log(formatter.formatDateTimeToLocalISOString(value))
// expected output: "1955-11-05";

getStartDayOfTheWeek() This function returns an index value representing the start day of the week on the locale's calendar { Sunday: 0, Monday: 1 ...etc }

const dateTimeOptions = { locale: 'en-US' };
const formatter = new DateTimeFormatter(dateTimeOptions);

console.log(formatter.startDayOfTheWeek()); // expected output: 0

DateTimeFormatter Functions

The functions used on the DateTimeFormatter class are also available as stand alone functions. Read more information about each function in the GTK Documentation.

The example below shows usage of the stand alone function: formatDateTime().

import { formatDateTime } from '@procore/globalization-toolkit';

const value = new Date(Date.UTC(1955, 10, 5, 6, 0, 16, 738));
const dateTimeOptions = { locale: "en-US", timeZone: "UTC" };

console.log(formatDateTime(value, dateTimeOptions)) // expected output: 11/5/1955

FormatRelativeTime

The formatRelativeTime function allows you to format a time difference as a localized, human-readable string, based on the provided locale and relative time options. This is useful for displaying time differences like "2 hours ago" or "in 3 days" in a format that is appropriate for the user's language and region.

The example below shows usage of the stand alone function : formatRelativeTime().

import { formatRelativeTime} from '@procore/globalization-toolkit';

import formatRelativeTime from
const result1 = formatRelativeTime('en-US', { value: 1, unit: 'hour' });
// Output: "in 1 hour"

const result2 = formatRelativeTime('es-ES', { value: -1, unit: 'hour' });
// Output: "hace 1 hora"

const result3 = formatRelativeTime('en-GB', { value: new Date(Date.now() - 3600 * 1000) });
// Output: "1 hour ago"

GetOverrideLocale Function

The getOverrideLocale function returns a mapped locale based on predefined settings. If the environment locale isn't directly supported, it provides a fallback from the predefined mappings.

Note: This override locale is meant for translation and should not be used directly with GTK formatting functions. For formatting, refer to the Sanitizing Locales section.

Usage

Here is an example of how to use the getOverrideLocale function:

import { getOverrideLocale } from '@procore/globalization-toolkit';

// Example 1: Known supported locale
const locale1 = getOverrideLocale('ja-JP');
console.log(locale1); // Output: ja-JP

// Example 2: Fallback locale
const locale2 = getOverrideLocale('en-AE');
console.log(locale2); // Output: en-GB

// Example 3: Unknown locale
const locale3 = getOverrideLocale('unknown');
console.log(locale3); // Output: en

getFallbackLocaleList Function

The getFallbackLocaleList function returns a list of locales which should have translation files loaded in the client, including fallbacks when available in addition to the English source. If the environment locale is not supported directly, it overrides the locale according to predefined mappings.

Important This method should be only used by clients that don't support custom locales.

The example below shows usage of the standalone function: getFallbackLocaleList().

import { getFallbackLocaleList } from '@procore/globalization-toolkit';

// Example 1: Known supported locale
const locale1 = getFallbackLocaleList('ja-JP');
console.log(locale1); // Output: ['ja-JP', 'en']

// Example 2: Known supported locale with fallback available
const locale2 = getOverrideLocale('es-ES');
console.log(locale2); // Output: ['es-ES', 'es', 'en']

// Example 3: Unsupported locale
const locale3 = getOverrideLocale('en-AE');
console.log(locale3); // Output: ['en-GB', 'en']

// Example 4: Unknown/Custom locale (eg. en-owner)
const locale4 = getOverrideLocale('unknown');
console.log(locale4); // Output: ['en']

getTranslationsFromLocale Function

The getTranslationsFromLocale function is a utility designed to load and merge translations for a given locale and its fallback locales. It is part of the @procore/globalization-toolkit and provides a robust way to handle multiple languages in your application.

import { getTranslationsFromLocale } from "@procore/globalization-toolkit"

// Example locale loader function
async function loadLocale(lang: string): Promise<{ default: Translations }> {
  return import(`../locales/${lang}.json`)
}

// Example usage of getTranslationsFromLocale
const envLocale = "en"
const translations = await getTranslationsFromLocale(envLocale, loadLocale)

Polyfills

The GTK implementation relies heavily on Intl functionality. This is generally well-supported by browsers, but depending on the browser versions you intend to support and GTK features you plan to use, it may require polyfills. In particular, consumers have seen issues with Safari versions <14.1. If you intend to support older browser versions, we recommend using the Format.JS polyfills, of which NumberFormat, PluralRules, Locale, GetCanonicalLocales, and supportedValuesOf are the ones relevant to GTK. Please reach out if you have questions.


Developing

Install dependencies:

$ npm install

Prepare project:

$ npm run prepare

Compile Typescript:

$ npm run build

(Delete build npm run clean)

Testing

$ npm run test

If adding a new supported export (or removing one in a breaking change), update the snapshot test output and commit the change.

$ npm run test -- -u

To check formatting run npm run lint:check and npm run format:check.

To check dependencies run

$ npm run depcheck

Documentation

We auto-generate documentation on what the Globalization Toolkit offers by utilizing Typedoc. Once you generate the updated documentation, you can navigate it locally by opening 'docs/index.html'.

To generate updated documentation run:

$ npm run typedoc

Versioning and Publishing

We use changesets to manage releases, and encourage you to include a changeset with each commit or pull request.

To create a changeset run npm run changeset and follow the prompt instructions.

To publish a release with changes:

  • Create new branch (e.g., git checkout -b chore/release).
  • Run npm run changeset version to create a release containing all changes. This command will update the version of GTK, as well update the CHANGELOG.md file.
  • Commit the changes (e.g., git commit -m "chore: release").
  • Create a pull request. git push -u origin HEAD, and then create pull request in the web UI.
  • Once the pull request is merged to main the updated packages will be published to npm once the CI pipeline is completed.

License

The package is available under the Procore Developers License

About Procore

Procore - building the software that builds the world.

Learn more about the #1 most widely used construction management software at procore.com