trancorder
v1.0.4
Published
Trancorder is an intelligent translation package manager and tool for localisation automation.
Downloads
8
Maintainers
Readme
Trancorder
Quick references: Command line
What is Trancorder?
The Trancorder localisation module is a versatile and powerful tool for providing translations support in both client-side and server-side applications. It offers a range of features to make localisation simple and effective, whether you choose to build translations directly into your application or dynamically load them from a server.
One of the key benefits of the Trancorder module is its ability to handle variables within messages. This means you can create messages that include placeholders for dynamic content, such as user names or product names. You can then pass in the relevant variables at runtime to generate a fully customised message.
Another powerful feature of the Trancorder module is its support for message expressions. This allows you to create messages that contain conditional logic, based on the values of variables passed in at runtime. For example, you could use expressions to show different messages for different languages, or to handle different pluralisation rules.
The Trancorder module also provides a way to connect translations keys to enum values, which helps to ensure that all possible options are covered. This makes it easy to maintain a complete and accurate set of translations for your application.
Finally, the Trancorder module provides command line tools, such as the trancorder-cli
, to help with validating, generating, and updating your translations. This makes it easy to keep your translations up to date, and to ensure that your application is always providing the best possible user experience.
Installation and start!
You need the latest version of nodejs and then run:
npm install trancorder
Basic usage
"setup.ts" file
import { localTrancorder as tranc } from "trancorder";
import * as enUS from "./en-US.json";
import * as csCZ from "./cs-CZ.json";
const { t, setLanguage } = tranc({
languages: {
"en-US": enUS,
"cs-CZ": csCZ,
},
});
export { t, setLanguage };
"en-US.json" file
{
"Hello friend!": "Hello friend!",
"Hi, my name is {name}": "Hi, my name is {name}"
}
"cs-CZ.json" file
{
"Hello friend!": "Ahoj příteli!",
"Hi, my name is {name}": "Ahoj, moje jméno je {name}"
}
"example.ts" file
import { t } from "./setup.ts";
const greeting = t("Hello friend!");
API
Trancorder localisation module can be used in both a browser environment and a Node.js environment. In a browser environment, the Trancorder module can be loaded as a script and used directly in your application code. This makes it easy to provide translations support for client-side applications, such as web applications or mobile apps built using frameworks like React or Angular.
In a Node.js environment, the Trancorder module can be installed as a package and used in your server-side code. This makes it easy to provide translations support for server-side applications, such as APIs or backend services.
In both cases, the Trancorder module provides a consistent API that makes it easy to work with translations and handle variables or expressions within messages. Whether you are building a client-side application or a server-side service, the Trancorder module can help you provide a seamless and user-friendly experience for users who speak different languages.
Here is the documentation for each exported type and function:
Types
LocalTrancorderOptions
: An options object for a local Trancorder, there needs to be static map of languagesLanguageTranslations
provided.RemoteTrancorderOptions
: An options object for a remote Trancorder, there needs to be promise for used language provided. This promise receive current language and needs to returnLanguageTranslations
.Messages
: An interface that represents a collection of message keys and values for a Trancorder instance.TrancorderApi
: An interface that represents the methods available on a Trancorder instance.Replacer
: An interface that represents a single replacement operation to be performed by a Trancorder.LoggerMessage
: An interface that represents a log message for a Trancorder instance.Logger
: An interface that represents a logger for a Trancorder instance.LogMessageType
: An enum that represents the different types of log messages that can be emitted by a Trancorder instance.LanguageTranslations
: An interface that represents a collection of language translations for a Trancorder instance.LanguageTranslation
: An interface that represents a single language translation for a Trancorder instance.LanguageTranslationAlternative
: An interface that represents an alternative language translation for a Trancorder instance.LanguageTranslationFull
: An interface that represents the full set of language translations for a Trancorder instance.
Constants
THIS_MARKER
: A string constant that represents the value of thethis
keyword in replacement operations.ENUM_VALUE_MARKER
: A string constant that represents the value of an enum value in replacement operations.
Functions
localTrancorder(options: LocalTrancorderOptions): Messages & TrancorderApi
A function that creates a local Trancorder instance with the specified options, and returns an object that combines the Messages
and TrancorderApi
interfaces. Local trancorder is used for serving static list of languages thats needs to be provided through options object.
Example of usage
"setup.ts" file
import { localTrancorder as tranc } from "trancorder";
import * as enUS from "./locales/en-US.json";
import * as csCZ from "./locales/cs-CZ.json";
const { t, setLanguage } = tranc({
languages: {
"en-US": enUS,
"cs-CZ": csCZ,
},
});
export { t, setLanguage };
remoteTrancorder(options: RemoteTrancorderOptions): Messages & TrancorderApi
A function that creates a remote Trancorder instance with the specified options, and returns an object that combines the Messages
and TrancorderApi
interfaces. Remote trancorder is used for loading selected language on demand and needs promise object that receive a selected language and needs to return selected language object with translations.
Example of usage
"setup.ts" file
import { remoteTrancorder as tranc } from "trancorder";
const { t, setLanguage } = tranc({
fetch: async (language) => {
return await fetch(`/api/locales/${language}`).then((data) => data.json());
},
});
export { t, setLanguage };
calculateExpression(expression: string, replacers: Record<string, object>): CalculatedExpression
A function that takes an expression string and a record of replacers, and returns a CalculatedExpression
object that contains a boolean result and an array of errors.
Example of usage
"expression.ts" file
import { calculateExpression, calculateReplacers } from "trancorder";
const replacers = calculateReplacers({ users: { count: 10 } }, { ... });
const results = calculateExpression("{users.count} = 0", replacers.replacers);
calculateReplacers(values: object, options: CommonTrancorderOptions): CalculatedReplacers
A function that takes an object of values and a CommonTrancorderOptions
object, and returns a CalculatedReplacers
object that contains a list of Replacer
objects and a record of replacers
. Results of this method can be used in calculateExpression
.
Example of usage
"expression.ts" file
import { calculateExpression, calculateReplacers } from "trancorder";
const replacers = calculateReplacers({ users: { count: 10 } }, { ... });
const results = calculateExpression("{users.count} = 0", replacers.replacers);
Using the t
function for translation
The t
function is used to retrieve translations for a specific message key. Here's how you can use it:
Step 1: First, make sure you have initialized the Trancorder module with the appropriate configuration options. This will typically involve specifying the language translations to use, either by statically including them in your app or dynamically loading them from a server.
"setup.ts" file
import { localTrancorder as tranc } from "trancorder";
import * as enUS from "./en-US.json";
import * as csCZ from "./cs-CZ.json";
const { t, setLanguage } = tranc({
languages: {
"en-US": enUS,
"cs-CZ": csCZ,
},
});
//set default language here, but this is basically call after app start and loaded some
//settings from server
setLanguage("en-US");
export { t, setLanguage };
"en-US.json" file
{
"Hello friend!": "Hello friend!",
"Hi, my name is {name}": "Hi, my name is {name}"
}
"cs-CZ.json" file
{
"Hello friend!": "Ahoj příteli!",
"Hi, my name is {name}": "Ahoj, moje jméno je {name}"
}
Step 2: Once the Trancorder module is initialized, you can use the t
function to retrieve translations for a specific message key. For example, if you want to retrieve the translation for the message key "Hello friend!", you would call the t
function like this:
"example.ts" file
import { t } from "./setup.ts";
const greeting = t("Hello friend!");
The t
function will look up the translation for the "Hello friend!" message key in the current language translations, and return the translated message as a string. If no translation is found for the specified message key, the t
function will return the original message key as a fallback, in this case "Hello friend!".
Step 3: If your message includes variables or expressions, you can use the second parameter of the t
function to specify the values for those variables or expressions. For example, if your "Hi, my name is {name}" message includes a variable for the user's name, you could use the t
function like this:
"example.ts" file
import { t } from "./setup.ts";
const name = "John";
const greeting = t("Hi, my name is {name}", { name });
In this case, the t
function will replace any occurrences of the {name}
variable in the translated message with the value of the name variable you provided. This is also work for nested objects and arrays so calling can looks like this:
"example.ts" file
import { t } from "./setup.ts";
const user = { name: "John", surname: "Doe", cities: [{ city: "New York" }, { city: "London" }] };
const greeting = t(
"Hi, my name is {usern.name} {usern.surname} and im living in {user.cities[0].city}!",
{ user }
);
Trancorder pick variables from provided object and replace it in message. This is also work for dynamic objects, but in this case, Trancorder can not validate if keys are really used and inform about this in command line interface as a information message.
Step 4: In some cases its necessary to use different message for some defined enum in code. Or just use current enum value for using in message. Trancorder has solution for this and you could use the t
function like this:
"example.ts" file
import { t } from "./setup.ts";
const Enum = {
Variable: "variable",
String: "string",
};
//use enum value in message directly, this is not so common case
const message1 = t(Enum, "Current selected type is {this}.", { enumValue: "string" });
//use unique message for all enum values
const message2 = t(
Enum,
{
[Enum.Variable]: "This is a variable type.",
[Enum.String]: "This is a string type.",
},
{ enumValue: "string" }
);
Trancorder will select right message and replace "this" placeholder for current enum value. The second example has also advantage, that Trancorder client can validate enum value in case that you add or remove some options from enum definition.
Option of t
function
For every placeholder used in message, there can be specified special formatter. Formatters are defined globally in Trancorder settings, but these formatters can be override for special placeholders and make different formatting then default. You could use the t
function like this:
"example.ts" file
import { t } from "./setup.ts";
const user = { name: "John", surname: "Doe", cities: [{ city: "New York" }, { city: "London" }] };
const greeting = t(
"Hi, my name is {usern.name} {usern.surname} and im living in {user.cities[0].city}!",
{ user },
{
formats: {
"user.cities[0].city": (locale, value) => {
if (locale === "en-US") {
return value.toUpperCase();
}
return value.toLowerCase();
},
},
}
);
In this example, user.cities[0].city placeholder will have different formatting than is default and for "en-US" will be upper cased and for other languages will be lower cased.
How to define localisations?
A localization file is a file that contains translations for a specific language. It is used in software development to provide support for multiple languages in an application or website. Based on supported formats can be now only json, but there can be more format available in future,
These files consist of an object where the keys represent the original string or message in the application, and the values represent the translation of that string in a specific language. Developers use trancorder
package and this key to look up the correct translation of the message and render it in the correct language for the user. It can also used trancorder-cli
package to validate and create these localisations files.
For example, if you have an English website with a button that says "Submit", the localization file for French might contain a translation where the key is "Submit" and the value is "Soumettre". When the user switches the language of the website to French, the application will look up the key "Submit" in the French localization file and render the translated value "Soumettre" instead of "Submit" for the French speaking user.
Here's an example of how you could create a JSON localisation file:
"en-US.json" file
{
"Hello World!": {
"value": "Hello World!",
"description": "A greeting message",
"translate": true,
"maximumCharacters": 20,
"alternatives": {
"{formal} = true": "Greetings, world!",
"{informal} = true": "Hey, world!"
}
},
"Welcome to our app!": {
"value": "Welcome to our app!",
"description": "A message displayed to new users",
"translate": true,
"maximumCharacters": 25
},
"Error {code}: {message}": "Error {code}: {message}"
}
In this example, we have three translation keys: Hello World!
, Welcome to our app!
and Error {code}: {message}
.
The first two keys (Hello World
and Welcome to our app!
) are objects that contain additional information about the translation message. They both have a value
property, which contains the actual translation message. They also have an optional description
property, which provides context about the translation message, an optional translate
property, which indicates whether the message should be translated, an optional maximumCharacters
property, which sets the maximum length of the message, and an optional alternatives
property, which contains alternative messages based on certain conditions.
The description
property in the localization JSON file is used to provide additional information about the translation message that may help translators understand the context and meaning of the message. This property is not used in the client application and is typically not visible to the end-users. Instead, it is intended to provide context for translation companies or services that are responsible for translating the messages into different languages.
For example, if the message is "Space", the description property can provide information that the message refers to outer space and not to a physical space or a keyboard key. This can help translators to understand the context and ensure that the message is translated accurately.
The translate
property in the localisation JSON file is used to specify whether or not the translation of the message is required. When set to true
od missing (default), it indicates that the message should be translated, while when set to false
, it indicates that the message should not be translated.
This can be useful in cases where some messages should remain in their original language, such as technical terms or branding names. It can also be helpful in cases where translation is not necessary, such as messages that are already in a universally understood language, like English, or messages that are only used internally by the development team.
Overall, the
translate
property provides a way to control which messages should be translated and which should not, giving developers and translators more control over the localisation process.
The maximumCharacters
property in the localisation JSON file is used to specify the maximum number of characters that the translated message can have. This property is optional and can be used to ensure that the translated message fits within the layout of the application or to enforce constraints on the length of the message.
For example, if the maximum length of a label in a user interface is 20 characters, and the translation of the label in a specific language is longer than that, the translation may be truncated or cause layout problems. By specifying the maximum length of the translated message using the maximumCharacters property, the localisation module can ensure that the message is truncated or altered to fit the layout and prevent layout problems.
The alternatives
key in this JSON file is used to provide different translations of a message based on certain conditions. In the example provided, the message "Hello World!" has two alternative translations that will be used instead of the default message depending on the value of a variable.
The two alternatives are "Greetings, world!" and "Hey, world!", and they are conditioned on the value of the
formal
andinformal
variables respectively that needs to be provided by usingt
function.If the value of the
formal
variable istrue
, the message "Greetings, world!" will be used instead of "Hello World!". On the other hand, if the value of theinformal
variable istrue
, the message "Hey, world!" will be used instead of "Hello World!".The
alternatives
key can be used to provide translations for different scenarios, such as different genders, plural and singular forms, or different regions or dialects. It provides a flexible way to handle different translations without creating multiple keys for each variation. When thet
function is used to translate a message that has alternatives, it evaluates each condition in the order they are defined and returns the first alternative whose condition is true. In this case, if the "formal" variable is set to true, the translation "Greetings, world!" would be returned, otherwise, if "informal" is set to true, the translation "Hey, world!" would be returned.If none of the conditions are true, the default translation specified in the "value" field of the original message is returned.
Donate me
| QR | Paypal | | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | | |