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

language-observer

v0.0.1-alpha.1

Published

The LanguageObserver class provides a simple way to manage internationalization in your web application. It automates the process of applying translations and simplifies support for multiple languages.

Downloads

22

Readme

npm GitHub package version NPM Downloads

1kB gzipped

Demo

Install

$ yarn add language-observer

Import

import LanguageObserver from 'language-observer';

Usage

const languageObserver = new LanguageObserver();

languageObserver.init({ lang: 'ru' });

translations.js

window.translations = window.translations || {};

window.translations['ru'] = {
  app: {
    title: {
      main: "Приложение",
      settings: "Настройки",
    },
    menu: {
      profile: "Профиль",
    },
  },
  buttons: {
    save: "Сохранить",
  },
};

window.translations['en'] = {
  app: {
    title: {
      main: "Application",
      settings: "Settings",
    },
    menu: {
      profile: "Profile",
    },
  },
  buttons: {
    save: "Save",
  },
};

window.translations['es'] = {
  app: {
    title: {
      main: "Aplicación",
      settings: "Configuraciones",
    },
    menu: {
      profile: "Perfil",
    },
  },
  buttons: {
    save: "Guardar",
  },
};

Switching

document.querySelector('#change-lang-to-es')?.addEventListener('click', () => {
  languageObserver.loadLanguage('es');
});

HTML example

<p data-i18n="title.welcome"></p>

<img data-i18n-attr='{"alt": "image.altText"}' src="image.jpg" alt="Default Alt Text">

Options

| Option | Type | Default | Description | |:------:|:--------:|:-------:|:--------------------------------------------------------------------------------------------------------------------------------| | lang | string | 'ru' | (Optional) The language code to initialize with. If not provided, the language is detected from the <body> element's class. |

Methods

| Method | Parameters | Returns | Description | |:--------------------------------------------------|:----------------------------------------------:|:---------:|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | init(options?) | options: { lang?: string } | void | Initializes the observer. If a lang is provided in options, it loads and applies that language's translations. | | loadLanguage(lang) | lang: string | Promise | Loads and applies translations for the specified language. If translations are not found, falls back to the default language and logs a warning. | | applyTranslations() | none | Promise | Applies the current translations to all elements with data-i18n and data-i18n-attr attributes on the page. Useful for updating translations after dynamic content changes. | | updateTranslations() | none | void | Manually updates translations on the page. Call this method after adding new translations to window.translations to apply them without changing the language or reloading the page. | | loadTranslations(lang, loader) | lang: string loader: (lang) => Promise | Promise | Asynchronously loads translations for the specified language using the provided loader function, then applies them if the language matches the current language. | | getNestedTranslation(obj, path) (static method) | obj: object path: string | any | Retrieves a nested translation value from an object using a dot-separated key path. Returns undefined if the key does not exist. |

Example of using methods

Using the loadTranslations method

async function fetchTranslations(lang) {
  const response = await fetch(`/locales/${lang}.json`);

  return response.json();
}

languageObserver.loadTranslations('fr', fetchTranslations);

Using the getNestedTranslation method

const nestedValue = LanguageObserver.getNestedTranslation(
  window.translations['en'], 
  'app.menu.profile'
);

console.log(nestedValue);

License

language-observer is released under MIT license