Documentation
¶
Overview ¶
Package l10n provides localization for NSGo games: versioned YAML and JSON string tables with BCP-47 locale fallback, interpolation, and CLDR pluralization; per-language asset resolution, fs.FS discovery, versioned YAML asset manifests, runtime locale switching, and missing-variant auditing; Unicode script detection and per-script/per-locale font selection; and right-to-left text reordering and HUD layout mirroring.
It builds on NSGo's public core package, the Go standard library, and go.yaml.in/yaml/v3 for YAML string tables and asset manifests.
Index ¶
- Constants
- func EncodeAssetManifest(m *AssetManifest) ([]byte, error)
- func EncodeYAML(t *StringTable) ([]byte, error)
- func LayoutAlignment(align string, dir Direction) string
- func MirrorX(x, width, containerWidth float32, dir Direction) float32
- func NormalizeLocale(tag string) string
- func ValidateAssetManifest(m *AssetManifest) error
- func ValidateStringTable(t *StringTable) error
- func VisualOrder(s string, baseDir Direction) string
- type Arg
- type AssetCatalog
- func (c *AssetCatalog) AffectedAssets(oldLocale, newLocale string) []string
- func (c *AssetCatalog) AffectedGroups(oldLocale, newLocale string) []string
- func (c *AssetCatalog) ApplyAssetManifest(m *AssetManifest) error
- func (c *AssetCatalog) AssetManifest() *AssetManifest
- func (c *AssetCatalog) BaseLocale() string
- func (c *AssetCatalog) CheckMissing(locales ...string) []MissingReport
- func (c *AssetCatalog) CheckMissingGroup(group string, locales ...string) []MissingReport
- func (c *AssetCatalog) Discover(fsys fs.FS) error
- func (c *AssetCatalog) GroupAssets(group string) []string
- func (c *AssetCatalog) Groups() []string
- func (c *AssetCatalog) LoadAssetManifestYAML(data []byte) error
- func (c *AssetCatalog) Locale() string
- func (c *AssetCatalog) Locales() []string
- func (c *AssetCatalog) MarshalAssetManifestYAML() ([]byte, error)
- func (c *AssetCatalog) Names() []string
- func (c *AssetCatalog) OnReload(fn func(groups []string, locale string)) (stop func())
- func (c *AssetCatalog) Register(name, locale, assetPath string)
- func (c *AssetCatalog) RegisterGroup(group string, names ...string)
- func (c *AssetCatalog) RegisterMap(name string, variants map[string]string)
- func (c *AssetCatalog) Resolve(name, locale string) (ResolvedAsset, bool)
- func (c *AssetCatalog) ResolveGroup(group, locale string) []ResolvedAsset
- func (c *AssetCatalog) SetLocale(locale string) []string
- func (c *AssetCatalog) WatchLocale(cx *core.Scope, localeSignal *core.Signal[string], ...) (stop func())
- type AssetManifest
- type Catalog
- func (c *Catalog) ApplyStringTable(t *StringTable) error
- func (c *Catalog) CheckPlurals(locales ...string) []UnusedPluralForm
- func (c *Catalog) FallbackLocale() string
- func (c *Catalog) Has(locale, key string) bool
- func (c *Catalog) LoadJSON(locale string, data []byte) error
- func (c *Catalog) LoadYAML(data []byte) error
- func (c *Catalog) Locales() []string
- func (c *Catalog) MarshalYAML(locale string) ([]byte, error)
- func (c *Catalog) Plural(locale, key string, count int, args ...Arg) string
- func (c *Catalog) Set(locale, key, value string)
- func (c *Catalog) SetPlural(locale, key string, forms PluralForms)
- func (c *Catalog) StringTable(locale string) (*StringTable, bool)
- func (c *Catalog) T(locale, key string, args ...Arg) string
- type Direction
- type FontRun
- type FontSet
- func (fs *FontSet[F]) Default() F
- func (fs *FontSet[F]) ForLocale(locale string) F
- func (fs *FontSet[F]) ForScript(script Script) F
- func (fs *FontSet[F]) ForText(locale, text string) F
- func (fs *FontSet[F]) RunsForText(locale, text string) []FontRun[F]
- func (fs *FontSet[F]) SetLocale(locale string, font F)
- func (fs *FontSet[F]) SetScript(script Script, font F)
- type Localizer
- func (l *Localizer) Catalog() *Catalog
- func (l *Localizer) Direction() Direction
- func (l *Localizer) Locale() string
- func (l *Localizer) Plural(key string, count int, args ...Arg) string
- func (l *Localizer) RTL() bool
- func (l *Localizer) SetLocale(locale string)
- func (l *Localizer) T(key string, args ...Arg) string
- func (l *Localizer) Visual(s string) string
- type MissingReport
- type PluralCategory
- type PluralForms
- type ResolvedAsset
- type Script
- type ScriptRun
- type StringTable
- type UnusedPluralForm
Examples ¶
Constants ¶
const AssetManifestVersion = 1
AssetManifestVersion is the asset manifest schema version this package reads and writes.
const CLDRVersion = "48.2"
CLDRVersion is the Unicode CLDR release used to generate the cardinal integer plural rules.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL
SchemaComment is the first line EncodeYAML writes: a YAML comment pointing a YAML language server at SchemaURL. ParseYAML ignores it like any other comment.
const SchemaURL = "https://game.nsgo.dev/schemas/l10n.v1.json"
SchemaURL is where the JSON Schema of version 1 YAML string tables is published. EncodeYAML names it in a yaml-language-server comment on the first line so editors and AI tools validate and complete string table files as they are written.
const StringTableVersion = 1
StringTableVersion is the YAML string table schema version this package reads and writes.
Variables ¶
This section is empty.
Functions ¶
func EncodeAssetManifest ¶
func EncodeAssetManifest(m *AssetManifest) ([]byte, error)
EncodeAssetManifest validates m and writes it as deterministic 2-space YAML: fields in schema order, map keys sorted, and group members sorted.
func EncodeYAML ¶
func EncodeYAML(t *StringTable) ([]byte, error)
EncodeYAML validates t and writes it as deterministic 2-space YAML prefixed with SchemaComment: fields in schema order (version, locale, strings, plurals), map keys sorted lexicographically, and CLDR plural categories in canonical order (zero, one, two, few, many, other).
func LayoutAlignment ¶
LayoutAlignment adapts a horizontal alignment string ("left", "right", "start", "end", "center", "justify") for dir.
In DirLTR, "start" maps to "left" and "end" maps to "right". In DirRTL, "left" and "start" map to "right", while "right" and "end" map to "left". "center", "justify", and unrecognized values are preserved.
func MirrorX ¶
MirrorX mirrors a horizontal HUD or dialogue element position x (with element width inside a container of containerWidth) when dir is DirRTL. In DirLTR, x is returned unchanged.
func NormalizeLocale ¶
NormalizeLocale canonicalizes a BCP-47 locale tag: underscores become hyphens, the primary language subtag is lowercased, 4-letter script subtags are Title-cased (e.g. "Hans"), and 2-letter region subtags are UPPERCASED (e.g. "US").
func ValidateAssetManifest ¶
func ValidateAssetManifest(m *AssetManifest) error
ValidateAssetManifest checks m against the version 1 schema: the version, a normalized base locale, clean asset names with at least one variant each, normalized variant locales with non-empty paths that carry no surrounding spaces, and non-empty group names whose members are clean and unique.
func ValidateStringTable ¶
func ValidateStringTable(t *StringTable) error
ValidateStringTable checks t against the version 1 string table schema: version == StringTableVersion, canonical BCP-47 locale, valid non-empty keys with no overlap between Strings and Plurals, and non-empty PluralForms entries.
func VisualOrder ¶
VisualOrder converts logical-order text s into visual left-to-right drawing order for baseDir, suitable for canvas/bitmap text renderers that draw glyphs left-to-right.
Each line separated by '\n' is reordered independently. Embedded LTR words and numbers inside RTL lines remain left-to-right, combining marks stay attached to their base characters, and paired brackets ((), [], {}, <>, «», ‹›) are mirrored inside RTL runs.
Types ¶
type Arg ¶
Arg is a named placeholder argument passed to Catalog.T, Catalog.Plural, Localizer.T, or Localizer.Plural.
type AssetCatalog ¶
type AssetCatalog struct {
// contains filtered or unexported fields
}
AssetCatalog maps logical asset names (such as "voice/intro.wav" or "ui/title_banner.png") to per-locale asset paths, resolves lookups along the BCP-47 fallback chain, tracks named asset groups for selective runtime reloads on language switch, and audits missing locale variants.
Example ¶
An AssetCatalog maps a logical asset name to its file for the current language, falling back to the base locale's file.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/l10n"
)
func main() {
assets := l10n.NewAssetCatalog("en")
assets.RegisterMap("voice/intro.wav", map[string]string{
"en": "voice/en/intro.wav",
"ja": "voice/ja/intro.wav",
})
assets.Register("ui/banner.png", "en", "ui/en/banner.png")
assets.RegisterGroup("title", "voice/intro.wav", "ui/banner.png")
for _, r := range assets.ResolveGroup("title", "ja") {
fmt.Println(r.LogicalName, r.Path, r.IsFallback)
}
for _, m := range assets.CheckMissing("ja") {
fmt.Println("missing:", m.Locale, m.Missing)
}
}
Output: ui/banner.png ui/en/banner.png true voice/intro.wav voice/ja/intro.wav false missing: ja [ui/banner.png]
func DiscoverFS ¶
func DiscoverFS(fsys fs.FS, baseLocale string) (*AssetCatalog, error)
DiscoverFS walks fsys and builds an AssetCatalog using baseLocale as the fallback locale for unlocalized files and BCP-47 fallback chains.
Recognized layouts:
- Directory layout: "locales/<locale>/<name>" (or "<prefix>/locales/<locale>/<name>")
- Dot suffix layout: "<name>.<locale>.<ext>" (for example "ui/title_banner.ja.png")
- Underscore suffix layout: "<name>_<locale>.<ext>" (for example "voice/intro_zh-Hans.wav" or "voice/intro_zh_Hans.wav")
- Unlocalized files (such as "sfx/click.wav"): registered under baseLocale when baseLocale is non-empty and no explicit baseLocale variant exists for that name.
func NewAssetCatalog ¶
func NewAssetCatalog(baseLocale string) *AssetCatalog
NewAssetCatalog creates a new AssetCatalog whose fallback locale is baseLocale (for example "en" or "en-US").
func (*AssetCatalog) AffectedAssets ¶
func (c *AssetCatalog) AffectedAssets(oldLocale, newLocale string) []string
AffectedAssets returns a sorted list of logical asset names whose resolved path or resolved locale changes when switching from oldLocale to newLocale.
func (*AssetCatalog) AffectedGroups ¶
func (c *AssetCatalog) AffectedGroups(oldLocale, newLocale string) []string
AffectedGroups returns a sorted list of registered group names that contain at least one asset whose resolved variant changes when switching from oldLocale to newLocale.
func (*AssetCatalog) ApplyAssetManifest ¶
func (c *AssetCatalog) ApplyAssetManifest(m *AssetManifest) error
ApplyAssetManifest validates m and merges it into c: a non-empty BaseLocale replaces c's base locale, every variant is registered (replacing an existing path for the same asset and locale), and group members are added to their groups.
func (*AssetCatalog) AssetManifest ¶
func (c *AssetCatalog) AssetManifest() *AssetManifest
AssetManifest returns a snapshot of c as a manifest: its base locale, every registered variant, and every group with its members sorted. The result shares no maps or slices with c.
func (*AssetCatalog) BaseLocale ¶
func (c *AssetCatalog) BaseLocale() string
BaseLocale returns the normalized base/fallback locale configured on c.
func (*AssetCatalog) CheckMissing ¶
func (c *AssetCatalog) CheckMissing(locales ...string) []MissingReport
CheckMissing audits direct-variant asset coverage for locales in deterministic sorted order.
If no locales are provided, all locales currently registered in c are audited. Each MissingReport lists the sorted logical asset names that lack a direct variant for that locale (and would therefore require fallback or fail to resolve).
func (*AssetCatalog) CheckMissingGroup ¶
func (c *AssetCatalog) CheckMissingGroup(group string, locales ...string) []MissingReport
CheckMissingGroup audits direct-variant asset coverage for the logical assets registered in group across locales in deterministic sorted order.
func (*AssetCatalog) Discover ¶
func (c *AssetCatalog) Discover(fsys fs.FS) error
Discover walks fsys and registers all discovered asset variants into c. Explicit locale matches ("locales/<locale>/<name>", "<name>.<locale>.<ext>", "<name>_<locale>.<ext>") take precedence over unlocalized default files.
func (*AssetCatalog) GroupAssets ¶
func (c *AssetCatalog) GroupAssets(group string) []string
GroupAssets returns a sorted list of logical asset names registered in group.
func (*AssetCatalog) Groups ¶
func (c *AssetCatalog) Groups() []string
Groups returns a sorted list of all asset group names registered in c.
func (*AssetCatalog) LoadAssetManifestYAML ¶
func (c *AssetCatalog) LoadAssetManifestYAML(data []byte) error
LoadAssetManifestYAML parses a YAML asset manifest with ParseAssetManifest and merges it into c with ApplyAssetManifest. Nothing is merged when the manifest is invalid.
func (*AssetCatalog) Locale ¶
func (c *AssetCatalog) Locale() string
Locale returns the currently active locale tracked by c, falling back to BaseLocale if no active locale has been set.
func (*AssetCatalog) Locales ¶
func (c *AssetCatalog) Locales() []string
Locales returns a sorted list of all locales that have at least one asset variant registered in c.
func (*AssetCatalog) MarshalAssetManifestYAML ¶
func (c *AssetCatalog) MarshalAssetManifestYAML() ([]byte, error)
MarshalAssetManifestYAML writes c's AssetManifest snapshot with EncodeAssetManifest.
func (*AssetCatalog) Names ¶
func (c *AssetCatalog) Names() []string
Names returns a sorted list of all logical asset names registered in c.
func (*AssetCatalog) OnReload ¶
func (c *AssetCatalog) OnReload(fn func(groups []string, locale string)) (stop func())
OnReload registers a callback invoked by SetLocale whenever one or more asset groups are affected by a locale switch. The returned function removes the callback.
func (*AssetCatalog) Register ¶
func (c *AssetCatalog) Register(name, locale, assetPath string)
Register registers a localized variant path for logical asset name and locale. It ignores an empty or invalid name, a locale that is empty or not BCP-47 syntax, and an empty path.
func (*AssetCatalog) RegisterGroup ¶
func (c *AssetCatalog) RegisterGroup(group string, names ...string)
RegisterGroup associates logical asset names with group so AffectedGroups, SetLocale, and WatchLocale can determine which asset groups require reloading on a locale switch. Calling RegisterGroup multiple times for the same group merges names.
func (*AssetCatalog) RegisterMap ¶
func (c *AssetCatalog) RegisterMap(name string, variants map[string]string)
RegisterMap registers multiple locale variants (locale -> path) for logical asset name.
func (*AssetCatalog) Resolve ¶
func (c *AssetCatalog) Resolve(name, locale string) (ResolvedAsset, bool)
Resolve looks up logical asset name for locale along the BCP-47 fallback chain (for example "zh-Hans-CN" -> "zh-Hans" -> "zh" -> BaseLocale).
IsFallback is true whenever the resolved locale differs from the normalized requested locale. Returns (ResolvedAsset{}, false) if no variant exists in the fallback chain.
func (*AssetCatalog) ResolveGroup ¶
func (c *AssetCatalog) ResolveGroup(group, locale string) []ResolvedAsset
ResolveGroup resolves every asset registered in group for locale, returning the resolved assets in deterministic sorted order by LogicalName.
func (*AssetCatalog) SetLocale ¶
func (c *AssetCatalog) SetLocale(locale string) []string
SetLocale switches the catalog's active locale at runtime, computes the affected asset groups between the previous locale and locale, notifies any OnReload listeners if at least one group is affected, and returns the sorted list of affected groups.
func (*AssetCatalog) WatchLocale ¶
func (c *AssetCatalog) WatchLocale( cx *core.Scope, localeSignal *core.Signal[string], reloadFn func(groups []string, locale string), ) (stop func())
WatchLocale subscribes to locale changes on localeSignal inside cx and invokes reloadFn with ONLY the affected asset groups whenever the active locale changes.
If localeSignal is nil, WatchLocale follows cx.Env().Locale(). The initial locale is recorded without triggering a reload; reloadFn is called only when a subsequent locale change alters at least one asset in a registered group. Calling the returned stop function cancels the subscription.
type AssetManifest ¶
type AssetManifest struct {
// Version is the schema version; it must equal AssetManifestVersion.
Version int `yaml:"version"`
// BaseLocale is the optional fallback locale, written in normalized BCP-47 form (for example "en" or "zh-Hans").
BaseLocale string `yaml:"base_locale,omitempty"`
// Assets maps a logical asset name (a clean slash-separated path such as "voice/intro.wav") to its variants, each a normalized locale mapped to a non-empty asset path.
Assets map[string]map[string]string `yaml:"assets,omitempty"`
// Groups maps a group name to the logical asset names it reloads on a locale switch. Members are clean asset names without duplicates; a group may name assets that the manifest itself does not list.
Groups map[string][]string `yaml:"groups,omitempty"`
}
AssetManifest is the versioned YAML document that maps logical asset names to per-locale paths and names asset groups. A manifest looks like this:
version: 1
base_locale: en
assets:
voice/intro.wav:
en: locales/en/voice/intro.wav
ja: locales/ja/voice/intro.wav
groups:
voice:
- voice/intro.wav
ParseAssetManifest decodes it strictly and EncodeAssetManifest writes it back in canonical form, so a manifest that EncodeAssetManifest wrote survives a load and save unchanged.
func ParseAssetManifest ¶
func ParseAssetManifest(data []byte) (*AssetManifest, error)
ParseAssetManifest decodes and validates a YAML asset manifest. Unknown fields, duplicate keys, trailing YAML documents, a missing or unsupported version, and names or locales that are not in canonical form are refused.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog stores localized string tables keyed by BCP-47 locale tag and message key, resolving lookups along the BCP-47 fallback chain to a fallback locale.
Example ¶
A Catalog looks up a message for a locale, falling back along the locale's parents to the fallback locale, and fills in named parameters.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/l10n"
)
func main() {
cat := l10n.NewCatalog("en")
cat.Set("en", "hud.score", "Score: {score}")
cat.Set("en", "menu.start", "Start")
cat.Set("fr", "hud.score", "Score : {score}")
cat.SetPlural("en", "hud.lives", l10n.PluralForms{One: "{count} life left", Other: "{count} lives left"})
fmt.Println(cat.T("fr-CA", "hud.score", l10n.Param("score", 42)))
fmt.Println(cat.T("fr-CA", "menu.start"))
fmt.Println(cat.Plural("en", "hud.lives", 1))
fmt.Println(cat.Plural("en", "hud.lives", 3))
}
Output: Score : 42 Start 1 life left 3 lives left
func NewCatalog ¶
NewCatalog creates a new localization catalog whose fallback locale is fallbackLocale (for example "en" or "en-US").
func (*Catalog) ApplyStringTable ¶
func (c *Catalog) ApplyStringTable(t *StringTable) error
ApplyStringTable validates t and merges its string and plural entries into c under t.Locale. Nothing is merged when t is invalid.
func (*Catalog) CheckPlurals ¶
func (c *Catalog) CheckPlurals(locales ...string) []UnusedPluralForm
CheckPlurals audits plural entries in c across locales (or all locales in c when none are given) and returns every form whose CLDR category is never selected for integer counts in that locale, sorted by locale, key, and canonical CLDR category order.
func (*Catalog) FallbackLocale ¶
FallbackLocale returns the normalized fallback locale configured on c.
func (*Catalog) Has ¶
Has reports whether key resolves in locale or anywhere along its fallback chain.
func (*Catalog) LoadJSON ¶
LoadJSON parses a JSON string table and merges its entries into locale.
Supported JSON shapes:
- Flat keys: {"title": "Quest", "hud.score": "Score: {score}"}
- Nested objects: {"menu": {"play": "Play"}} -> key "menu.play"
- Plural objects: {"coins": {"zero": "No coins", "one": "{count} coin", "other": "{count} coins"}}
Nested objects may contain plural objects at any depth. Calling LoadJSON multiple times for the same locale merges new keys into the existing table.
Errors about data are *loaderr.Error values that give the line and key of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
Example ¶
LoadJSON reads a locale's strings from a JSON table.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/l10n"
)
func main() {
cat := l10n.NewCatalog("en")
err := cat.LoadJSON("ja", []byte(`{"menu.start": "スタート", "menu.quit": "終了"}`))
fmt.Println(err, cat.T("ja", "menu.quit"), cat.Has("ja", "menu.options"))
}
Output: <nil> 終了 false
func (*Catalog) LoadYAML ¶
LoadYAML parses a versioned YAML string table with ParseYAML and merges its entries into the table's locale. Nothing is merged when data is invalid.
Errors about data are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
func (*Catalog) MarshalYAML ¶
MarshalYAML encodes locale's entries in c with EncodeYAML. It returns an error when locale has no entries in c or is not a valid BCP-47 tag.
func (*Catalog) Plural ¶
Plural resolves key for locale, selects the plural form matching integer count under the matched locale's CLDR cardinal plural rules (CLDRVersion), and interpolates named placeholders.
When count is 0 and the matched entry provides a non-empty Zero form, Zero is always selected regardless of whether the locale has a CLDR zero category. Otherwise PluralCategoryFor(matchedLocale, count) chooses the category, and any omitted category falls back to Other (or One if Other is empty).
The "{count}" placeholder is automatically populated with count unless args explicitly provides a Param("count", ...). If key is not found, key itself is returned.
func (*Catalog) SetPlural ¶
func (c *Catalog) SetPlural(locale, key string, forms PluralForms)
SetPlural stores plural form templates for locale and key.
func (*Catalog) StringTable ¶
func (c *Catalog) StringTable(locale string) (*StringTable, bool)
StringTable returns a snapshot of locale's entries in c as a StringTable, and reports whether locale exists in c. The result shares no maps with c.
type Direction ¶
type Direction uint8
Direction specifies horizontal text and layout reading direction.
func EnvDirection ¶
EnvDirection returns the active layout direction for cx, honoring cx.Env().RTL() and falling back to LocaleDirection(cx.Env().Locale()). Reading EnvDirection inside a reactive computation subscribes to environment RTL and locale changes.
func LocaleDirection ¶
LocaleDirection returns the default writing direction for a BCP-47 locale tag. Explicit script subtags (such as "ar-Latn" vs "az-Arab") take precedence over the primary language subtag.
Example ¶
LocaleDirection and DetectScript tell a layout which way text runs and which font it needs.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/l10n"
)
func main() {
for _, tag := range []string{"en_US", "ar", "he-IL", "zh-hant-tw"} {
fmt.Println(l10n.NormalizeLocale(tag), l10n.LocaleDirection(tag), l10n.LocaleScript(tag))
}
fmt.Println(l10n.DetectScript("こんにちは"), l10n.DetectScript("Привет"))
}
Output: en-US ltr Latin ar rtl Arabic he-IL rtl Hebrew zh-Hant-TW ltr CJK Japanese Cyrillic
func TextDirection ¶
TextDirection determines the base direction of s from its first strong directional character (UAX #9 rules P2/P3). If s contains no strong directional characters, DirLTR is returned.
type FontSet ¶
type FontSet[F any] struct { // contains filtered or unexported fields }
FontSet maps Unicode scripts and BCP-47 locales to fonts of any type F, so the same selector works with platform fonts (core.Font) as well as bitmap or atlas fonts (such as *text.Font).
Example ¶
A FontSet chooses a font by script or locale, and splits mixed text into runs that each use one font.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/l10n"
)
func main() {
fonts := l10n.NewFontSet("Latin Sans")
fonts.SetScript(l10n.ScriptCJK, "CJK Sans")
fonts.SetLocale("ja", "Japanese Sans")
fmt.Println(fonts.ForLocale("ja-JP"))
for _, run := range fonts.RunsForText("en", "Level 3 第三关") {
fmt.Printf("%q %s\n", run.Text, run.Font)
}
}
Output: Japanese Sans "Level 3 " Latin Sans "第三关" CJK Sans
func NewFontSet ¶
NewFontSet creates a FontSet with defaultFont as its fallback font.
func (*FontSet[F]) Default ¶
func (fs *FontSet[F]) Default() F
Default returns the fallback font configured on fs.
func (*FontSet[F]) ForLocale ¶
ForLocale selects the best font for locale by walking its BCP-47 fallback chain in registered locale fonts, then falling back to the font registered for LocaleScript(locale), and finally the default font.
func (*FontSet[F]) ForScript ¶
ForScript returns the font registered for script, or the default font if none is set.
func (*FontSet[F]) ForText ¶
ForText selects the best font for rendering text in locale.
If text's dominant script matches locale's script, locale-specific overrides (such as "zh-Hant" vs "zh-Hans") take precedence over generic script fonts. Otherwise the font registered for text's detected script is selected.
func (*FontSet[F]) RunsForText ¶
RunsForText segments text by script and attaches the resolved font for each run, enabling mixed-script rendering (for example Latin + CJK or Arabic).
type Localizer ¶
type Localizer struct {
// contains filtered or unexported fields
}
Localizer is a reactive localization view bound to a core.Scope.
By default it follows cx.Env().Locale() (and cx.Env().RTL()), so UI and HUD bindings that call Locale, Direction, T, or Plural re-evaluate automatically whenever the environment locale changes. Calling SetLocale sets an explicit override signal; calling SetLocale("") returns to following the environment.
func NewLocalizer ¶
NewLocalizer creates a reactive Localizer owned by cx backed by cat.
func (*Localizer) Direction ¶
Direction returns the active layout direction (DirLTR or DirRTL).
When a manual locale override is active, it returns LocaleDirection of that locale. Otherwise it honors cx.Env().RTL() and falls back to LocaleDirection(l.Locale()). Reading Direction inside a reactive computation subscribes to locale and RTL environment changes.
func (*Localizer) Locale ¶
Locale returns the active BCP-47 locale tag. When read inside a reactive computation, it subscribes to both manual SetLocale overrides and cx.Env().Locale() changes.
func (*Localizer) Plural ¶
Plural resolves a pluralized key for the active locale and count. Reading Plural inside a reactive computation subscribes it to locale changes.
func (*Localizer) SetLocale ¶
SetLocale overrides the active locale with a BCP-47 tag (such as "ja" or "zh-Hans"). Pass an empty string to clear the override and follow cx.Env().Locale() again.
type MissingReport ¶
type MissingReport struct {
Locale string
TotalAssets int
Present int
Missing []string
Coverage float64
}
MissingReport summarizes direct-variant localization coverage for a single locale across a set of logical assets.
func (MissingReport) Complete ¶
func (r MissingReport) Complete() bool
Complete reports whether every audited asset has a direct variant for Locale.
type PluralCategory ¶
type PluralCategory uint8
PluralCategory is one of the six Unicode CLDR cardinal plural categories.
const ( // PluralOther is the default fallback CLDR plural category. PluralOther PluralCategory = iota // PluralZero is the CLDR zero plural category. PluralZero // PluralOne is the CLDR one plural category. PluralOne // PluralTwo is the CLDR two plural category. PluralTwo // PluralFew is the CLDR few plural category. PluralFew // PluralMany is the CLDR many plural category. PluralMany )
func PluralCategories ¶
func PluralCategories(locale string) []PluralCategory
PluralCategories returns the CLDR cardinal plural categories reachable by integer counts for locale, in canonical CLDR order (zero, one, two, few, many, other).
func PluralCategoryFor ¶
func PluralCategoryFor(locale string, count int) PluralCategory
PluralCategoryFor returns the Unicode CLDR cardinal plural category for integer count in locale (using CLDRVersion rules with decimal operands v = w = f = t = c = e = 0).
Negative counts are evaluated using their absolute value, per CLDR TR35. Locales are matched along their normalized BCP-47 subtag chain (for example "pt-PT" uses European Portuguese rules, "pt-BR" falls back to "pt", and "cs-CZ" falls back to "cs"). Unlisted locales fall back to CLDR root (PluralOther).
func UnusedPluralForms ¶
func UnusedPluralForms(locale string, forms PluralForms) []PluralCategory
UnusedPluralForms returns the plural categories set on forms that are never selected by Plural for integer counts in locale, in canonical CLDR order.
PluralZero is never reported because Plural always honors an explicit zero form when count == 0 for every locale. PluralOther is never reported because Other is the universal fallback template.
func (PluralCategory) String ¶
func (c PluralCategory) String() string
String returns the canonical CLDR category name ("zero", "one", "two", "few", "many", or "other").
type PluralForms ¶
type PluralForms struct {
// Zero is the template used when count is 0 (if non-empty, for any locale) or matches the CLDR zero category.
Zero string `yaml:"zero,omitempty"`
// One is the template used for the CLDR one plural category.
One string `yaml:"one,omitempty"`
// Two is the template used for the CLDR two plural category.
Two string `yaml:"two,omitempty"`
// Few is the template used for the CLDR few plural category.
Few string `yaml:"few,omitempty"`
// Many is the template used for the CLDR many plural category.
Many string `yaml:"many,omitempty"`
// Other is the default fallback template for pluralization.
Other string `yaml:"other,omitempty"`
}
PluralForms holds localized message templates keyed by CLDR cardinal plural category. Any unset category falls back to Other (or One if Other is empty). When count is 0 and Zero is non-empty, Plural always selects Zero regardless of locale.
type ResolvedAsset ¶
type ResolvedAsset struct {
LogicalName string
RequestedLocale string
ResolvedLocale string
Path string
IsFallback bool
}
ResolvedAsset describes the concrete localized asset path selected for a logical asset name and requested BCP-47 locale.
type Script ¶
type Script uint8
Script identifies a Unicode writing script for font selection and text segmentation.
func DetectScript ¶
DetectScript returns the dominant non-Common Script present in s, or ScriptCommon if s contains only neutral characters (digits, spaces, punctuation) or is empty.
When Japanese Kana (Hiragana/Katakana) appears alongside CJK ideographs (Kanji), ScriptJapanese takes precedence; similarly ScriptKorean takes precedence when Hangul appears alongside Hanja.
func LocaleScript ¶
LocaleScript returns the primary writing Script associated with a BCP-47 locale tag (respecting explicit script subtags such as "sr-Latn" or "zh-Hans" before falling back to the primary language subtag).
func RuneScript ¶
RuneScript classifies a single Unicode rune into its Script. Spaces, digits, punctuation, and symbols return ScriptCommon.
type ScriptRun ¶
ScriptRun is a contiguous slice of text sharing a resolved Script. Start and End are byte offsets into the original string.
func SegmentByScript ¶
SegmentByScript splits mixed-script text (such as "Score: 100 得分") into contiguous ScriptRuns.
Neutral ScriptCommon characters (spaces, digits, punctuation) attach to the preceding strong script, or to the first strong script when they appear at the start of the string. A string containing only ScriptCommon characters returns a single ScriptCommon run; an empty string returns nil.
type StringTable ¶
type StringTable struct {
// Version is the schema version; it must equal StringTableVersion (1).
Version int `yaml:"version" schema:"required"`
// Locale is the normalized BCP-47 locale tag this table translates (for example "en" or "zh-Hans").
Locale string `yaml:"locale" schema:"required,minLength=1"`
// Strings maps message keys (such as "menu.play" or "hud.score") to localized string templates.
Strings map[string]string `yaml:"strings,omitempty"`
// Plurals maps message keys to CLDR plural form templates (zero, one, two, few, many, other).
Plurals map[string]PluralForms `yaml:"plurals,omitempty"`
}
StringTable is a versioned YAML localization string table for one locale. A file looks like this:
# yaml-language-server: $schema=https://game.nsgo.dev/schemas/l10n.v1.json
version: 1
locale: en
strings:
hud.score: "Score: {score}"
menu.play: Play
plurals:
coins:
zero: No coins
one: "{count} coin"
other: "{count} coins"
ParseYAML decodes it strictly and EncodeYAML writes it back in canonical form with sorted keys, so a table EncodeYAML wrote survives a load and save byte for byte.
func ParseYAML ¶
func ParseYAML(data []byte) (*StringTable, error)
ParseYAML decodes and validates a versioned YAML string table. Unknown fields, invalid CLDR plural categories, duplicate keys, trailing YAML documents, YAML anchors/aliases/merge keys, null values, a missing or unsupported version, non-canonical locales, empty keys, keys defined in both strings and plurals, and empty plural entries are refused.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
type UnusedPluralForm ¶
type UnusedPluralForm struct {
Locale string
Key string
Category PluralCategory
}
UnusedPluralForm identifies a plural form supplied in a localization table whose CLDR category is never selected by Plural for integer counts in Locale.
func CheckStringTablePlurals ¶
func CheckStringTablePlurals(t *StringTable) []UnusedPluralForm
CheckStringTablePlurals audits plural entries in t and returns every form whose CLDR category is never selected for integer counts in t.Locale, sorted by key and canonical CLDR category order.