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

translation-manager-react

v1.3.1

Published

An React wrapper of translationManager

Downloads

37

Readme

translationManager-react

An React wrapper of translationManager

demo

Setup:

  1. npm i translation-manager && npm i translation-manager-react

  2. Create a folder /translations in your project (or copy translationsExample from this repo)

  3. Under this /translations folder create this tree:

    • /translations
      • /languages
        • /english
          • codes.json
          • ...any other json file
        • /french
          • codes.json
          • ...any other json file
        • ...any other language

    2.1 The files codes.json contains all the language codes used to target this language, example for english ["en","EN","en-us","en-US"]

    2.2 Next to the codes.json file you can create any other json file (with the name you want), these files will contain the translations: example:

    {
       "ADD": {
           "value": "add"
       },
       "CATEGORY": {
           "value": "category",
           "plural": "categories"
       },
       "<textCode>": {
           "value": "text",
           "<special>": "textSpecial"
       }
    }
    • you have an json-schema here

    • <special>: is any variant of your original text (plural, interrogative, ...)

  4. execute this command build-translations <path to your translations folder>, to create languageCodes.json, textCodes.json, translations.json. These three files are the compilation of the previous files.

  5. In your project, create a file initTranslations.js:

    const {TranslationManager} = require("translation-manager");
    const languageCodes        = require("translations/languageCodes");
    const translations         = require("translations/translations");
    
    TranslationManager.initData( languageCodes, translations );
    TranslationManager.setAppLanguage( "en" );
    // check Error
    if ( process.env.ENVIRONMENT !== "prod" )
        TranslationManager.verifyJson({ redundantCheck: false });

    IMPORTANT: Import initTranslations.js in first, in the entrance file of your app. So that TranslationManager.initData always takes place before usage of TranslationManager

  6. Finish, you can use TranslationManager:

    // todo
  7. Add shortcuts to the commands in your package.json scripts

    {
        "scripts": {
            "build-translations": "build-translations ./translations",
            "watch-translation": "watch-translations ./translations",
            "clean-translation": "clean-translations ./translations english true true"
        }
    }

Notes

TranslationManager.getText

TranslationManager.getText does not actually return a string, it returns an instance of the TranslationText class. TranslationText is an extends of String. But you can use it like a string, all the methods of the string class are available, you can Jsonify, concat, split, trim...

However:

  • typeof return "object"
  • if you print it, in the console, it display all the object
  • to avoid memory link, if you no longer need a text, think to do monTexte.destroy()

insertValues

You can insert values in your text, translationManager use lodash template. In your text in json file, add ${<keyName>}. When you make getText, specify insertValue option, example:

{
    "AN_ERROR_OCCURRED": {
        "value": "an error occurred: ${errorMessage}"
    }
}
const err = new Error("foobar");
TranslationManager.getText(textCode.AN_ERROR_OCCURRED, {insertValues: {errorMessage: err.message}});

html

You can use html tag in your text. If you use Text component, and set the props html to true. An parser will convert your string in react node.

render

To change languages dynamically, the components that own the text must be re-render, for this, you can simply subscribe your component to TranslatioNmanager.onLanguageUpdate(). But you can, more simply, use the Text component, or the hooks of this API.

API

[component] Text

props:
Text.propTypes = {
    className:     PropTypes.string,
    textCode:      PropTypes.string, // the wanted textCode, you can find them by import the builded file: "textCodes.json"
    language:      PropTypes.string, // to force the language
    insertValues:  PropTypes.object, // an object to insert values in your text
    option:        PropTypes.oneOf( ["capitalize","capitalizeWord","capitalizeSentence","uppercase","lowercase"]), // to transform your text
    special:       PropTypes.string, // if you want a special translation example: "plural", "interogation", ...
    ExtraContent:  PropTypes.oneOfType([PropTypes.function, PropTypes.element, PropTypes.string, PropTypes.number]), // a component which will be rendered after the text
    plural:        PropTypes.bool, // to override the props special and set this to "plural"
    interrogation: PropTypes.bool, // to override the props special and set this to "interrogation"
    html:         PropTypes.bool, // if the text must be parsed

    capitalize:         PropTypes.bool, // quick props to override props option
    capitalizeWord:     PropTypes.bool, // quick props to override props option
    capitalizeSentence: PropTypes.bool, // quick props to override props option
    uppercase:          PropTypes.bool, // quick props to override props option
    lowercase:          PropTypes.bool, // quick props to override props option
};
properties:
   Text.options = ["capitalize","capitalizeWord","capitalizeSentence","uppercase","lowercase"]
example:
import React from "react";
import { Text } from "translation-manager-react";
import textCodes from "./translations/textCodes";

const DynamicNiceText = () => {
    return (
        <div>
            <Text textCode={textCodes.CATEGORY}/>
        </div>
    );
};
Notes

The Text Component wrap your text in a span, and add an data-textcode to this element. To simplify your debugging, and when you add a new language

[hooks] useTranslationManager

An hooks for use TranslationManager. This hooks subscribe your component to the language update event.

example:
import React from "react";
import { useTranslationManager } from "translation-manager-react";
import textCodes from "./translations/textCodes";

const WithHooksTranslationManager = () => {
    const TranslationManager = useTranslationManager();
    return (
        <div>
            {TranslationManager.getText( textCodes.CATEGORY )}
        </div>
    );
};

[hooks] useTextCode

This hook allows you to recover the text directly. It is the lightest solution, and avoid too many re-render when the language change.

params:
  • textCode: [String] the wanted textCode
  • options: [Object]
    • options.special: ["value"] {string} the special value from the textCode to use
    • options.option: {string} an constant string (TranslationManager.textOptions=[capitalize,capitalizeWord,capitalizeSentence,uppercase,lowercase])
    • options.language: [appLanguage] {string} to force language
    • options.insertValues: {Object} an object of insert value {key: value}, in the translation text, you have to add ${}
  • forceString: [bool] (default true) if you want an TranslationText or an string, keep true if you want't a light solution
example:
import React from "react";
import { useTextCode } from "translation-manager-react";
import textCodes from "./translations/textCodes";

const WithHooksTextCode = () => {
    const textCode = textCodes.CATEGORY;
    const options = {special: "plural"};
    const forceString = true;
    const text = useTextCode( textCode, options, forceString );
    return (
        <div>
            {text}
        </div>
    );
};

Commands

build-translations

To build the translations files: languageCodes.json, textCodes.json, translations.json

$ build-translations <path_to_your_translations_folder>

clean-translations

To clean your translations files (rearrange textCodes, sort them alphabetically and can transform their case)

$ clean-translations <path_to_your_translations_folder> <base_folder_name> <organizeOtherLanguageLikeBase> <minimizeValueCase>
  • path_to_your_translations_folder: path to the translation folder
  • base_folder_name: the name of the language folder on which all cleaning will be based. textCodes of other languages will be stored in the same way as the selected language. Default is "english"
  • organizeOtherLanguageLikeBase: if you want to store textCode in the same way as the base language.
  • minimizeValueCase: if you want to transform all value in lowerCase
example:
$ clean-translations ./translations english true true

watch-translations

To watch the change in folder translations, with this command effective, any changement in translations files, trigger build-translations

$ watch-translations <path_to_your_translations_folder>

TranslationManager API

here

Authors

License

This project is licensed under the MIT - see the LICENSE file for details