|
| 1 | +/* |
| 2 | + * Copyright 2025 New Vector Ltd. |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial |
| 5 | + * Please see LICENSE files in the repository root for full details. |
| 6 | + */ |
| 7 | + |
| 8 | +import { Addon, types, useGlobals } from "storybook/manager-api"; |
| 9 | +import { WithTooltip, IconButton, TooltipLinkList } from "storybook/internal/components"; |
| 10 | +import React, { useEffect } from "react"; |
| 11 | +import { GlobeIcon } from "@storybook/icons"; |
| 12 | + |
| 13 | +/** |
| 14 | + * Returns the title of a language in the user's locale. |
| 15 | + */ |
| 16 | +function languageTitle(language: string): string { |
| 17 | + return new Intl.DisplayNames([language], { type: "language", style: "short" }).of(language) || language; |
| 18 | +} |
| 19 | + |
| 20 | +export const languageAddon: Addon = { |
| 21 | + title: "Language Selector", |
| 22 | + type: types.TOOL, |
| 23 | + render: ({ active }) => { |
| 24 | + const [globals, updateGlobals] = useGlobals(); |
| 25 | + const selectedLanguage = globals.language || "en"; |
| 26 | + |
| 27 | + const [languages, setLanguages] = React.useState<string[]>([]); |
| 28 | + useEffect(() => { |
| 29 | + const loadLanguages = async () => { |
| 30 | + // We can't import `shared/i18n.tsx` directly here. |
| 31 | + // The storybook addon doesn't seem to benefit the webpack config of storybook and we can't resolve the alias in i18n.tsx. |
| 32 | + const json = await import("../webapp/i18n/languages.json"); |
| 33 | + const languages = Object.keys(json).filter((lang) => lang !== "default"); |
| 34 | + setLanguages(languages); |
| 35 | + }; |
| 36 | + |
| 37 | + loadLanguages(); |
| 38 | + }, []); |
| 39 | + |
| 40 | + return ( |
| 41 | + <WithTooltip |
| 42 | + placement="top" |
| 43 | + trigger="click" |
| 44 | + closeOnOutsideClick |
| 45 | + tooltip={({ onHide }) => { |
| 46 | + return ( |
| 47 | + <TooltipLinkList |
| 48 | + links={languages.map((language) => ({ |
| 49 | + id: language, |
| 50 | + title: languageTitle(language), |
| 51 | + active: selectedLanguage === language, |
| 52 | + onClick: async () => { |
| 53 | + // Update the global state with the selected language |
| 54 | + updateGlobals({ language }); |
| 55 | + onHide(); |
| 56 | + }, |
| 57 | + }))} |
| 58 | + /> |
| 59 | + ); |
| 60 | + }} |
| 61 | + > |
| 62 | + <IconButton title="Language"> |
| 63 | + <GlobeIcon /> |
| 64 | + {languageTitle(selectedLanguage)} |
| 65 | + </IconButton> |
| 66 | + </WithTooltip> |
| 67 | + ); |
| 68 | + }, |
| 69 | +}; |
0 commit comments