Thursday 15 July 2021

Storybook: how to update i18 locale depending on globals

I try to migrate from @storybook/addon-knobs to @storybook/addon-controls and I've got an issue.

I have a knob that I use to update i18n locale.
It also switch from rtl to ltr.
It works flawlessly:

import { select } from '@storybook/addon-knobs'
import Vue from "vue";

// import vue plugins
import VueI18n from "vue-i18n";

// import language file
const message = require("./translations.json");

// i18n and store
Vue.use(VueI18n);

import store from "../src/store";
addDecorator(() => ({
  template: "<story/>",
  i18n: new VueI18n({
    defaultLocale: 'en',
    locale: 'en',
    locales: [ 'en', 'ar' ],
    messages: {
      en: message.en,
      ar: message.ar,
    },
  }),
  // add a props to toggle language
  props: {
    storybookLocale: {
      type: String,
      default: select('I18n locale', ['en', 'ar'], 'en'),
    },
  },
  watch: {
    // add a watcher to toggle language
    storybookLocale: {
      handler() {
        this.$i18n.locale = this.storybookLocale;
        let dir = this.storybookLocale === 'ar' ? 'rtl' : 'ltr';
        document.querySelector('html').setAttribute('dir', dir);
      },
      immediate: true,
    },
  },
}));

Now, when I try to use @storybook/addon-controls, I fail to understand how to do it.

I've read Storybook documentation and was able to remove my knob to add a new select in the toolbar.

export const globalTypes = {
  storybookLocale: {
    name: 'storybookLocale',
    description: 'Internationalization locale',
    defaultValue: 'en',
    toolbar: {
      icon: 'globe',
      items: [
        { value: 'en', right: 'πŸ‡ΊπŸ‡Έ', title: 'English' },
        { value: 'ar', right: 'πŸ‡¦πŸ‡ͺ', title: 'Arabic' },
      ],
    },
  },
};

I don't know how to watch for this global change to update my i18n and the language direction.
In the doc, the global is consumed within a story, but I want it to be global.

Any help would be appreciated.



from Storybook: how to update i18 locale depending on globals

No comments:

Post a Comment