Repository navigation
Milestone
Description
Feature Request
Instead of using browser.i18n.getMessage directly, include a custom i18n API that can be used in it's place.
It should:
- Read localizations from
<srcDir>/locales/[country-code].(json|json5|yaml|yml) - Generate correctly formatted
.output/[target]/_locales/[country-code]/messages.jsonfiles - Support plural forms
- Support interpolation
Basically, for message files that look like this:
# locales/en.yml
simple: Hello world!
manifestStyle:
message: This is the translated text
description: This is a description to give translators more context (it's never translated)
namedInterpolation: Hello $name1$, my name is $name2$
arrayInterpolation: Hello $1, my name is $2
some:
nested:
translation: You can nest translations inside deep objects
escapeTheDollarSign: You owe me $$100
pluralForm:
0: Zero items
1: 1 item
n: $count$ itemsWould be translated to look like this:
// .output/_locales/en.json
{
"simple": {
"message": "Hello world!"
},
"manifestStyle": {
"message": "This is the translated text",
"description": "This is a description to give translators more context (it's never translated)"
},
"namedInterpolation": {
"message": "Hello $name1$, my name is $name2$",
"placeholders": {
"name1": {
"content": "$1"
},
"name2": {
"content": "$2"
}
}
},
"arrayInterpolation": {
"message": "Hello $1, my name is $2"
},
"some_nested_translation": {
"message": "You can nest translations inside deep objects"
},
"escapeTheDollarSign": {
"message": "You owe me $$100"
},
"pluralForm": {
"message": "Zero items | 1 item | $count$ items",
"placeholders": {
"count": {
"content": "$1"
}
}
}
}The API would look something like this:
// Auto-imported from:
// import { createI18n } from 'wxt/i18n';
const i18n = createI18n();
i18n.t("simple"); // Hello world!
i18n.t("manifestStyle"); // This is the translated text
i18n.t("namedInterpolation", { name1: "John", name2: "Joe" }) // Hello John, my name is Joe
i18n.t("arrayInterpolation", ["John", "Joe"]) // Hello John, my name is Joe
i18n.t("some.nested.translation"); // You can nest translations inside deep objects
i18n.t("escapeTheDollarSign"); // You owe me $100
i18n.t("pluralForm", { count: 0 }); // Zero items
i18n.t("pluralForm", { count: 1 }); // 1 item
i18n.t("pluralForm", { count: 4 }); // 4 itemsAcceptance Criteria
- Currently, we generate types for
browser.i18n.getMessageto make sure the keys passed in are type-safe. Let's keep this logic, but how it is generated will be different.
wxt/src/core/utils/building/generate-wxt-dir.ts
Lines 96 to 98 in ab6a34a
async function writeI18nDeclarationFile( config: InternalConfig, ): Promise<string> { - Not everyone will be happy with the name "locales" for the new directory. We'll use that as a default, but let's add
localesDirto the config to allow customization - After copying public assets, we'll need to read in all files in
<srcDir>/<localesDir>/*, transform them, and output them to.output/[target]/_locales/[country-code]/messages.json. Public assets are copied here:
const publicAssets = await copyPublicDirectory(config); -
i18n.t- Plural form support
- Use a special named placeholder,
count, to detect keys that are plural
- Use a special named placeholder,
- Interpolation
- Escape
$correctly
- Plural form support
What are the alternatives?
See #217 for a discussion of alternative methods.
Additional context
Created based on #217 (comment)
Metadata
Metadata
Assignees
Labels
No labels
Activity
nnx0r commentedon Jan 6, 2024
I love the idea.
Perhaps these two can come as improvement in the future:
I dislike the
$syntax for interpolation. Can't we use{xxx}curly braces as placeholder with variable name inside?ongnxco commentedon Jan 7, 2024
Hi, may I ask about the code snippet within the file: entrypoints/popup/App.vue?
Even though the code still returns the expected result, in Visual Studio Code, it consistently shows a red underline under 'browser.' I am curious to know what the issue is with Visual Studio Code.
aklinker1 commentedon Jan 7, 2024
@ongnxco you may have to restart the typescript server after running
pnpm i. Thewxt preparecommand generates a.wxt/types/imports.d.tsfile, which, when included in the Typescript project, will define the type for thebrowservariable.I don't know specifically why your VSCode might not respect the file generated in the
.wxtdirectory.aklinker1 commentedon Jan 7, 2024
@dvlden plural forms can come later, but interpolation is a part of the existing
browser.i18n.getMessage, so to replace that API effectively, we'll need to include interpolation in the initial release.As for
$name$vs{name}... I agree. I think curly braces are better too lol. But my current thinking is that:$s adds a little complexity.But I could be convinced otherwise lol. I really don't like the built-in APIs and formats, but need to leverage them to avoid inflating the final bundle size.
Maybe I make a cleaner placeholder syntax a future enhancement?Edit: No, I only want to support a single method and I don't want to make breaking changes to this in the futurennx0r commentedon Jan 7, 2024
Oh so
$is already built in with browser.i18n? I did not know that it existed at all.I think making a tiny custom wrapper to support curly braces is well worth it. The output then can contain $'s...
I guess it's more unnecessary work, but considering that WXT is opinionated, I think it should be built in for cleaner syntax.
Regarding migration, perhaps the invers cli, that they can run, that would take all
public/_locales/lang-code/messages.jsonand transform/parse them toassets/locales/lang-code.json?I can try to tackle this outside of WXT, to see how simple it could be achieved?
aklinker1 commentedon Jan 7, 2024
@dvlden Sure, if you want to take a crack at, I'll leave it to you!
nnx0r commentedon Jan 8, 2024
After some investigation and playing, I thought that it'd be nice if in this opinionated approach, we drop
descriptionproperty, when it exists and transform it in the comment instead.In this case,
jsongoes out the way as it does not support comments natively (or I am outdated) and we can instead allow onlyjson5andyml/yamlcause they do have syntax for comments.So instead of transforming this:
{ "manifestStyle": { "message": "This is the translated text", "description": "This is a description to give translators more context (it's never translated)" } }Into the exact same output, we can do this:
Keeping it readable and avoid nesting... However, after further reading, I realised that browser also supports
placeholdersproperty. So perhaps instead of this:{ "manifestStyle": { "message": "This is the translated text with {somevar} here", "placeholders": { "somevar": { "content": "dynamic content placeholder" } } } }We do this instead?
I'm just trying to minimize nesting that native api implementation does. With lots of
messageproperties and optionaldescriptionandplaceholder. For those, like me, that only usemessageit makes it a nightmare to look at, with its constant repetition.So for my use-case, I think I can build custom script for now that I can use internally to have clean locale files that would be ran before
dev/buildscripts, to create appropriate_localedirs and files.I will play a bit more to see if I can get comments and placeholders to work the way I'd want it and give you a link to a repo, as I am trying it randomly with Node, outside of WXT for simplicity.
aklinker1 commentedon Jan 8, 2024
The main reason I allowed the original manifest style is so people can migrate to WXT easily, without changing anything. I'd rather we continue allowing that style.
If an object has 3 or less keys, and all the keys belong to
["message", "description", "placeholders"], we know that object is a standard chrome extension object, and can just copy it over without any transformation.There are obviously edge cases here with "reserved" key names, but I'm not too concerned because the typescript support will basically tell them if something's wrong.
I'd also prefer we auto-detect placeholders, so we don't have to define them at all in the source translation files, and generate them in the output JSON files.
Actually, I don't even think we need to define the placeholders key for them to work in chrome extensions?Edit: We are required to define them, so we should just generate them when found in the message.If someone wants to define placeholder information, they should use the original style. I don't think your array style is very readable, someone new to the framework would not recognize what the second object is for.
aklinker1 commentedon Jan 8, 2024
I've updated the issue's description with valid JSON that we need to transform the file into. Some things that changed:
namedInterpolationsome.nested.translationwithsome_nested_translation, since you can't use.in keysaklinker1 commentedon Jan 8, 2024
Here's a basic example that includes the JSON from above. i18n-example.zip
I don't know why I thought the
browser.i18nAPI included support for named parameters, it doesn't. So if we want to support named parameters, we'll need to do it ourselves... So I think{}might make sense.nnx0r commentedon Jan 8, 2024
Oh yea, looks like "named parameter" is only for placeholder use-case. I am not sure how is one being used, if there are multiple placeholders? Shouldn't it accept an K/V object to know where to place each dynamic value?
aklinker1 commentedon Jan 8, 2024
My understanding is that named placeholders are just inserted into the message where stated. The placeholders don't have to include interpolated parameters, they can be constant strings. Google provides a reason for this:
So maybe we can't support named substitutions like
{ name: "John" }. We're forced to use arrays like["John"]if we use thebrowser.i18n.getMessagefunction under the hook.A couple work-arounds I can think of:
[name: string]instead of just[string]Record<string, string>to an array passed intobrowser.i18n.getMessage. That would require the mapping be bundled with each entrypoint though...So I would say we go with option 1. Add types for substitutions and use named tuples instead of anonymous tuples.
2 remaining items
aklinker1 commentedon Jan 8, 2024
OK, so you're just considering the translation between the two file types.
That's fine, but I'm also considering writing a better API than
browser.runtime.getMessagethat is used at runtime. Which is what my previous 2 comments were about.IE: How would we implement this?
yunsii commentedon Jan 9, 2024
It seems UI framework agnostic? I want to know how to change locale if I use it in React?
aklinker1 commentedon Jan 9, 2024
@yunsii The built-in localization APIs provided to chrome extensions do not provide a way to change the current language. Since WXT's wrapper will use those APIs internally, the API discussed here will not support changing languages either.
If you're using react, you can use a library like
react-i18nextfor your UIs. I've provided a similar example of usingvue-i18nalong side the built-in APIs. You can refer to it as a reference to get started with React, it's very similar:https://github.com/wxt-dev/wxt-examples/tree/main/examples/vue-i18n#readme
I'd recommend reading this one as well to get a better understanding of how to use the built-in APIs.
https://github.com/wxt-dev/wxt-examples/tree/main/examples/vanilla-i18n#readme
yunsii commentedon Jan 9, 2024
Got it, thanks very much.
aklinker1 commentedon Jan 13, 2024
@dvlden I wanted to use this in one of my extensions, so I implemented this last night. See #343.
nnx0r commentedon Jan 13, 2024
That's actually great... Can you make an alpha release, so I can test it within my extension?
aklinker1 commentedon Jan 14, 2024
@dvlden will do 👍
nnx0r commentedon Jan 18, 2024
Will unassign myself as you already got it. It's not what I wanted, but it's still cool and useful.