-
Notifications
You must be signed in to change notification settings - Fork 40
Create Plugin: i18n addition script #2320
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sunker
wants to merge
23
commits into
main
Choose a base branch
from
create-plugin/i18n-addition
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
85325a8
add core infrastructure for 'add' command
sunker ad64883
wip - add i18n script
sunker e9b463b
split script into multiple files and add parent directory
sunker 7fc88ea
update glob
sunker a1722f7
add docs
sunker 237e5f1
delete legacy files
sunker 232868a
use semver range
sunker e96c304
fix broken test
sunker 62cd988
add section about additions
sunker 3154eaa
change grafana dep
sunker 30dc8f5
check externals
sunker 2478267
exit early in case react 17 is used
sunker 00fd6b6
add success messages with next steps
sunker 01ccf59
improve readme
sunker c124f6a
add unit tests
sunker b7f800a
fix readme
sunker b098127
remove example script
sunker 86a6a59
fix broken test
sunker 5e09379
remove idempotent text
sunker 4d82d6e
simplify logic
sunker 07db27b
additiondebug
sunker e19da02
copilot pr feedback
sunker 3ba04f2
revert one suggestion
sunker File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
161 changes: 161 additions & 0 deletions
161
packages/create-plugin/src/codemods/additions/scripts/i18n/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| # I18n Addition | ||
|
|
||
| Adds internationalization (i18n) support to a Grafana plugin. | ||
|
|
||
| ## Usage | ||
|
|
||
| ```bash | ||
| npx @grafana/create-plugin add i18n --locales <locales> | ||
| ``` | ||
|
|
||
| ## Requirements | ||
|
|
||
| - **Grafana >= 11.0.0**: i18n is not supported for Grafana versions prior to 11.0.0. If your plugin's `grafanaDependency` is set to a version < 11.0.0, the script will automatically update it to `>=11.0.0` (it will not exit with an error). | ||
| - **React >= 18**: The `@grafana/i18n` package requires React 18 or higher. If your plugin uses React < 18, the script will exit with an error and prompt you to upgrade. | ||
|
|
||
| ## Required Flags | ||
|
|
||
| ### `--locales` | ||
|
|
||
| A comma-separated list of locale codes to support in your plugin. | ||
|
|
||
| **Format:** Locale codes must follow the `xx-XX` pattern (e.g., `en-US`, `es-ES`, `sv-SE`) | ||
|
|
||
| **Example:** | ||
|
|
||
| ```bash | ||
| npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE | ||
| ``` | ||
|
|
||
| ## What This Addition Does | ||
|
|
||
| **Important:** This script sets up the infrastructure and configuration needed for translations. After running this script, you'll need to: | ||
|
|
||
| 1. Mark up your code with translation functions (`t()` and `<Trans>`) | ||
| 2. Run `npm run i18n-extract` to extract translatable strings | ||
| 3. Fill in the locale JSON files with translated strings | ||
|
|
||
| This addition configures your plugin for internationalization by: | ||
|
|
||
| 1. **Updating `docker-compose.yaml`** - Adds the `localizationForPlugins` feature toggle to your local Grafana instance | ||
| 2. **Updating `src/plugin.json`** - Adds the `languages` array and updates `grafanaDependency` | ||
| 3. **Creating locale files** - Creates empty JSON files for each locale at `src/locales/{locale}/{pluginId}.json` | ||
| 4. **Adding dependencies** - Installs `@grafana/i18n` and optionally `semver` (for backward compatibility) | ||
| 5. **Updating ESLint config** - Adds i18n linting rules to catch untranslated strings | ||
| 6. **Initializing i18n in module.ts** - Adds `initPluginTranslations()` call to your plugin's entry point | ||
| 7. **Creating support files**: | ||
| - `i18next.config.ts` - Configuration for extracting translations | ||
| - `src/loadResources.ts` - (Only for Grafana < 12.1.0) Custom resource loader | ||
| 8. **Adding npm scripts** - Adds `i18n-extract` script to extract translations from your code | ||
|
|
||
| ## Backward Compatibility | ||
|
|
||
| **Note:** i18n is not supported for Grafana versions prior to 11.0.0. | ||
|
|
||
| The addition automatically detects your plugin's `grafanaDependency` version: | ||
|
|
||
| ### Grafana >= 12.1.0 | ||
|
|
||
| - Sets `grafanaDependency` to `>=12.1.0` | ||
| - Grafana handles loading translations automatically | ||
| - Simple initialization: `await initPluginTranslations(pluginJson.id)` | ||
| - No `loadResources.ts` file needed | ||
| - No `semver` dependency needed | ||
|
|
||
| ### Grafana 11.0.0 - 12.0.x | ||
|
|
||
| - Keeps or sets `grafanaDependency` to `>=11.0.0` | ||
| - Plugin handles loading translations | ||
| - Creates `src/loadResources.ts` for custom resource loading | ||
| - Adds runtime version check using `semver` | ||
| - Initialization with loaders: `await initPluginTranslations(pluginJson.id, loaders)` | ||
|
|
||
| ## Running Multiple Times | ||
|
|
||
| This addition can be run multiple times safely. It uses defensive programming to check if configurations already exist before adding them, preventing duplicates and overwrites: | ||
|
|
||
| ### Adding New Locales | ||
|
|
||
| You can run the command again with additional locales to add them: | ||
|
|
||
| ```bash | ||
| # First run | ||
| npx @grafana/create-plugin add i18n --locales en-US | ||
|
|
||
| # Later, add more locales | ||
| npx @grafana/create-plugin add i18n --locales en-US,es-ES,sv-SE | ||
| ``` | ||
|
|
||
| The addition will: | ||
|
|
||
| - Merge new locales into `plugin.json` without duplicates | ||
| - Create only the new locale files (won't overwrite existing ones) | ||
| - Skip updating files that already have i18n configured | ||
|
|
||
| ## Files Created | ||
|
|
||
| ``` | ||
| your-plugin/ | ||
| ├── docker-compose.yaml # Modified: adds localizationForPlugins toggle | ||
| ├── src/ | ||
| │ ├── plugin.json # Modified: adds languages array | ||
| │ ├── module.ts # Modified: adds i18n initialization | ||
| │ ├── loadResources.ts # Created: (Grafana 11.x only) resource loader | ||
| │ └── locales/ | ||
| │ ├── en-US/ | ||
| │ │ └── your-plugin-id.json # Created: empty translation file | ||
| │ ├── es-ES/ | ||
| │ │ └── your-plugin-id.json # Created: empty translation file | ||
| │ └── sv-SE/ | ||
| │ └── your-plugin-id.json # Created: empty translation file | ||
| ├── i18next.config.ts # Created: extraction config | ||
| ├── eslint.config.mjs # Modified: adds i18n linting rules | ||
| └── package.json # Modified: adds dependencies and scripts | ||
| ``` | ||
|
|
||
| ## Dependencies Added | ||
|
|
||
| **Always:** | ||
|
|
||
| - `@grafana/i18n` (v12.2.2) - i18n utilities and types | ||
| - `i18next-cli` (dev) - Translation extraction tool | ||
|
|
||
| **For Grafana 11.x only:** | ||
|
|
||
| - `semver` - Runtime version checking | ||
| - `@types/semver` (dev) - TypeScript types for semver | ||
|
|
||
| ## Next Steps | ||
|
|
||
| After running this addition: | ||
|
|
||
| 1. **Use in code**: Import and use the translation functions to mark up your code: | ||
|
|
||
| ```typescript | ||
| import { t, Trans } from '@grafana/i18n'; | ||
|
|
||
| // Use t() for simple strings | ||
| const title = t('components.myComponent.title', 'Default Title'); | ||
|
|
||
| // Use Trans for JSX | ||
| <Trans i18nKey="components.myComponent.description"> | ||
| This is a description | ||
| </Trans> | ||
| ``` | ||
|
|
||
| 2. **Extract translations**: Run `npm run i18n-extract` to scan your code for translatable strings | ||
| 3. **Add translations**: Fill in your locale JSON files with translated strings | ||
|
|
||
| ## Debug Output | ||
|
|
||
| Enable debug logging to see what the addition is doing: | ||
|
|
||
| ```bash | ||
| DEBUG=create-plugin:additions npx @grafana/create-plugin add i18n --locales en-US,es-ES | ||
| ``` | ||
|
|
||
| ## References | ||
|
|
||
| - [Grafana i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization) | ||
| - [Grafana 11.x i18n Documentation](https://grafana.com/developers/plugin-tools/how-to-guides/plugin-internationalization-grafana-11) | ||
| - [Available Languages](https://github.com/grafana/grafana/blob/main/packages/grafana-i18n/src/constants.ts) |
158 changes: 158 additions & 0 deletions
158
packages/create-plugin/src/codemods/additions/scripts/i18n/code-generation.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| import * as recast from 'recast'; | ||
| import * as babelParser from 'recast/parsers/babel-ts.js'; | ||
|
|
||
| import type { Context } from '../../../context.js'; | ||
| import { additionsDebug } from '../../../utils.js'; | ||
|
|
||
| const { builders } = recast.types; | ||
|
|
||
| export function addI18nInitialization(context: Context, needsBackwardCompatibility: boolean): void { | ||
| // Find module.ts or module.tsx | ||
| const moduleTsPath = context.doesFileExist('src/module.ts') | ||
| ? 'src/module.ts' | ||
| : context.doesFileExist('src/module.tsx') | ||
| ? 'src/module.tsx' | ||
| : null; | ||
|
|
||
| if (!moduleTsPath) { | ||
| additionsDebug('No module.ts or module.tsx found, skipping i18n initialization'); | ||
| return; | ||
| } | ||
|
|
||
| const moduleContent = context.getFile(moduleTsPath); | ||
| if (!moduleContent) { | ||
| return; | ||
| } | ||
|
|
||
| // Defensive: check if i18n is already initialized | ||
| if (moduleContent.includes('initPluginTranslations')) { | ||
| additionsDebug('i18n already initialized in module file'); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| const ast = recast.parse(moduleContent, { | ||
| parser: babelParser, | ||
| }); | ||
|
|
||
| const imports = []; | ||
|
|
||
| // Add necessary imports based on backward compatibility | ||
| imports.push( | ||
| builders.importDeclaration( | ||
| [builders.importSpecifier(builders.identifier('initPluginTranslations'))], | ||
| builders.literal('@grafana/i18n') | ||
| ) | ||
| ); | ||
|
|
||
| imports.push( | ||
| builders.importDeclaration( | ||
| [builders.importDefaultSpecifier(builders.identifier('pluginJson'))], | ||
| builders.literal('plugin.json') | ||
| ) | ||
| ); | ||
|
|
||
| if (needsBackwardCompatibility) { | ||
| imports.push( | ||
| builders.importDeclaration( | ||
| [builders.importSpecifier(builders.identifier('config'))], | ||
| builders.literal('@grafana/runtime') | ||
| ) | ||
| ); | ||
| imports.push( | ||
| builders.importDeclaration( | ||
| [builders.importDefaultSpecifier(builders.identifier('semver'))], | ||
| builders.literal('semver') | ||
| ) | ||
| ); | ||
| imports.push( | ||
| builders.importDeclaration( | ||
| [builders.importSpecifier(builders.identifier('loadResources'))], | ||
| builders.literal('./loadResources') | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| // Find the last import index (use consistent approach for both imports and initialization) | ||
| const lastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration'); | ||
|
|
||
| // Add imports after the last import statement | ||
| if (lastImportIndex !== -1) { | ||
| ast.program.body.splice(lastImportIndex + 1, 0, ...imports); | ||
| } else { | ||
| ast.program.body.unshift(...imports); | ||
| } | ||
|
|
||
| // Add i18n initialization code | ||
| const i18nInitCode = needsBackwardCompatibility | ||
| ? `// Before Grafana version 12.1.0 the plugin is responsible for loading translation resources | ||
| // In Grafana version 12.1.0 and later Grafana is responsible for loading translation resources | ||
| const loaders = semver.lt(config?.buildInfo?.version, '12.1.0') ? [loadResources] : []; | ||
|
|
||
| await initPluginTranslations(pluginJson.id, loaders);` | ||
| : `await initPluginTranslations(pluginJson.id);`; | ||
|
|
||
| // Parse the initialization code and insert it at the top level (after imports) | ||
| const initAst = recast.parse(i18nInitCode, { | ||
| parser: babelParser, | ||
| }); | ||
|
|
||
| // Find the last import index again (after adding new imports) | ||
| const finalLastImportIndex = ast.program.body.findLastIndex((node: any) => node.type === 'ImportDeclaration'); | ||
| if (finalLastImportIndex !== -1) { | ||
| ast.program.body.splice(finalLastImportIndex + 1, 0, ...initAst.program.body); | ||
| } else { | ||
| ast.program.body.unshift(...initAst.program.body); | ||
| } | ||
|
|
||
| const output = recast.print(ast, { | ||
| tabWidth: 2, | ||
| trailingComma: true, | ||
| lineTerminator: '\n', | ||
| }).code; | ||
|
|
||
| context.updateFile(moduleTsPath, output); | ||
| additionsDebug(`Updated ${moduleTsPath} with i18n initialization`); | ||
| } catch (error) { | ||
| additionsDebug('Error updating module file:', error); | ||
| } | ||
| } | ||
|
|
||
| export function createLoadResourcesFile(context: Context): void { | ||
| const loadResourcesPath = 'src/loadResources.ts'; | ||
|
|
||
| // Defensive: skip if already exists | ||
| if (context.doesFileExist(loadResourcesPath)) { | ||
| additionsDebug('loadResources.ts already exists, skipping'); | ||
| return; | ||
| } | ||
|
|
||
| const pluginJsonRaw = context.getFile('src/plugin.json'); | ||
| if (!pluginJsonRaw) { | ||
| additionsDebug('Cannot create loadResources.ts without plugin.json'); | ||
| return; | ||
| } | ||
|
|
||
| const loadResourcesContent = `import { LANGUAGES, ResourceLoader, Resources } from '@grafana/i18n'; | ||
| import pluginJson from 'plugin.json'; | ||
|
|
||
| const resources = LANGUAGES.reduce<Record<string, () => Promise<{ default: Resources }>>>((acc, lang) => { | ||
| acc[lang.code] = () => import(\`./locales/\${lang.code}/\${pluginJson.id}.json\`); | ||
| return acc; | ||
| }, {}); | ||
|
|
||
| export const loadResources: ResourceLoader = async (resolvedLanguage: string) => { | ||
| try { | ||
| const translation = await resources[resolvedLanguage](); | ||
| return translation.default; | ||
| } catch (error) { | ||
| // This makes sure that the plugin doesn't crash when the resolved language in Grafana isn't supported by the plugin | ||
| console.error(\`The plugin '\${pluginJson.id}' doesn't support the language '\${resolvedLanguage}'\`, error); | ||
| return {}; | ||
| } | ||
| }; | ||
| `; | ||
|
|
||
| context.addFile(loadResourcesPath, loadResourcesContent); | ||
| additionsDebug('Created src/loadResources.ts for backward compatibility'); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.