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

react-safe-i18n

v1.2.0

Published

A typesafe [Internationalization](#more-information-on-internationalization) library that uses a base translation, as a fallback with a custom parser, to achieve full safety in the React UI.

Downloads

6

Readme

React Safe i18n

A typesafe Internationalization library that uses a base translation, as a fallback with a custom parser, to achieve full safety in the React UI.

Even when no translation data can be asynchonously aquired, so a connection to some kind of backend is not possibel, then the React UI can still render without having a bunch of undefined values.

Features

  • A default language can be set to allow changing the translation of the default language after deployment
  • Async Provider that can load translations from any asynchronous source
  • Detector that handles detecting and setting of the users selected language
    • can be configured with fallback methods
    • even allows the users selected language to be fetched from a network source using a custom Detector
    • common methods of detecting the users language available packaged with library
  • Safe Html parser and RendererComponent that can render React Elements from Translations or any string
  • fully typesafe formatting/templating (Syntax) in the translations thanks to typesafe-i18n
  • Formatter functions compatible with typesafe-i18n

Example

For a full example see this Sandbox or the projects development app here.

Roadmap

Translations are strings, so rendering React Components in them is currently not supported! Something similar to this will be implemented in the future.

  • [x] React element for setting the lang attribute on the html tag
  • [x] formatter user setting ...
  • [x] add more tests
  • [x] utility for React Components in Translations (React in Translation: recipe)
  • [ ] v2 - complete rethinking of language & translation loading process (see image)
    • [ ] restructure into Core and React to allow adding other frameworks in the future
    • [ ] React Component Render mode: wait(render after loading) or lazy(pop in of new translations)
    • [ ] provide errors to application for tracing or display
    • [ ] dynamic loading retry
  • [ ] Translation splitting (nested Translation build method creates context)
  • [ ] v3 - even more safety
  • check translations for use of templating and parameters to avoid showing translations with broken templates
  • make language code as parameter for formatters depend on language of the formatted translation, so that translations that were replaced by default or fallback use the language of that default/fallback to match the formatting
  • [ ] Data caching
  • local storage
  • how to check for changes?
    • invalidate after time
    • store time when cached and check if changes were made sinceand hooks
  • [ ] Html Parser: switch Attributes to list, add attribute merging callback (list to object, default uses last value)
  • [ ] Add more formatters & utilitys
  • [ ] Custom lang resolve algorithm (Detector)

Usage

Most of the configuration and Boilerplate can be contained in a single file.

Installation

npm install react-safe-i18n
pnpm add react-safe-i18n

Providers

Based on your use case either the Static or Async Provider should be sufficient enough to get you started.

Direction & Document language

It is recommended by The World Wide Web Consortium (W3C) to set the language using attributes on the root html tag. This can be easily acchieved by adding the LangHtmlComponent of this library in your root "main.tsx", "index.tsx" or other root component.

import { LangHtmlComponent } from 'react-safe-i18n';
import init from './i18n';
import { useLanguage } from './i18n';

(async () => {
  const I18nProvider = await init();

  ReactDOM.createRoot(document.getElementById('root')!).render(
    <React.StrictMode>
      <I18nProvider>
        {/* will change the documents html tag */}
        <LangHtmlComponent hook={useLanguage} />
        <App />
      </I18nProvider>
    </React.StrictMode>
  );
})();

Formatting/Templating Syntax

See typesafe-i18n's documentation for it's syntax, Here. Also the development App of this project and it's Formatters component for some examples on how to use the templating.

This is extendable by writing formatters

import {
  type BaseFormatters,
  date,
  replace,
  lowercase,
} from 'react-safe-i18n/formatters';

export function initFormatters(locale: string) {
  return {
    round: (value) => Math.round(value),
    weekday: date(locale, { weekday: 'long' }),
    myFormatter: locale === 'en' ? identity : ignore,
    noSpaces: replace(/\s/g, '-'),
    lower: lowercase,
  } satisfies BaseFormatters;
}

and providing them to the builder like this

const builder = new i18nBuilder(base_language, asyncProvider).addFormatterInit(
  initFormatters
)

All available formatters:

import {
  date,
  identity,
  ignore,
  lowercase,
  number,
  replace,
  time,
  uppercase,
} from 'react-safe-i18n/formatters';

Here's the Documentation for Custom Formatters and some more Example

Rendering React Elements

See here

More Information on Internationalization

Preload

Asynchronously loading translation data can (significantly) increase time until First Contentful Paint. For big translations, it is recommended to use HTML preload to speed up the page load.

<head>
  <!-- preload list of languages -->
  <link rel="preload" href="/rest/localization/languages" as="fetch" crossorigin="anonymous">
  <!-- preload default language (if needed) -->
  <link rel="preload" href="/rest/localization/translations?lang=en" as="fetch" crossorigin="anonymous">
</head>

Original Development

This is the Stackblitz Sandbox the development was started in. I tried to achieve my idea using zod but it did not work like I wanted it to, so I wrote the parse.