Storybook: how to update i18 locale depending on globals Storybook: how to update i18 locale depending on globals vue.js vue.js

Storybook: how to update i18 locale depending on globals


I'm more familiar with React, but I think something along these lines should work.

Solution

  • Listen to context.globals passed as the second parameter to the decorator.
  • Replace addDecorator with the exported decorators array.
  • Update this.storybookLocale tocontext.globals.storybookLocale.

Notes

  • Docs explain how to use a decorator for globals here.
  • I found this related article, but ultimately didn't gain much from it given that you already had the basic set up. They do go through some additional steps, but I'm not sure they're necessary in your case.

.storybook/preview.js

import Vue from "vue";import VueI18n from "vue-i18n";import store from "../src/store";import message from "./translations.json";Vue.use(VueI18n);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' },      ],    },  },};export const decorators = [  (story, context) => ({    template: "<story/>",    i18n: new VueI18n({      defaultLocale: 'en',      locale: 'en',      locales: [ 'en', 'ar' ],      messages: {        en: message.en,        ar: message.ar,      },    }),    props: {      storybookLocale: {        type: String,        default: 'en',      },    },    watch: {      storybookLocale: {        handler() {          this.$i18n.locale = context.globals.storybookLocale;          let dir = storybookLocale === 'ar' ? 'rtl' : 'ltr';          document.querySelector('html').setAttribute('dir', dir);        },        immediate: true,      },    },  })];