GitHub快速开始

API 参考取自源码中的 Go 文档注释,以英文书写。

package l10n

import "github.com/nsgo-dev/game/pkg/l10n"

概述

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.

索引

常量

const AssetManifestVersion = 1

AssetManifestVersion is the asset manifest schema version this package reads and writes.

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.

函数

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(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(align string, dir Direction) string

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(x, width, containerWidth float32, dir Direction) float32

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(tag string) string

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(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(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(s string, baseDir Direction) string

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.

类型

type Arg struct {
	Name  string
	Value any
}

Arg is a named placeholder argument passed to Catalog.T, Catalog.Plural, Localizer.T, or Localizer.Plural.

func Param(name string, value any) Arg

Param creates a named placeholder argument for string interpolation (e.g. Param("score", 42) substitutes "{score}").

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.

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(baseLocale string) *AssetCatalog

NewAssetCatalog creates a new AssetCatalog whose fallback locale is baseLocale (for example "en" or "en-US").

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 (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 (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 (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 (c *AssetCatalog) BaseLocale() string

BaseLocale returns the normalized base/fallback locale configured on c.

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 (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 (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 (c *AssetCatalog) GroupAssets(group string) []string

GroupAssets returns a sorted list of logical asset names registered in group.

func (c *AssetCatalog) Groups() []string

Groups returns a sorted list of all asset group names registered in c.

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 (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 (c *AssetCatalog) Locales() []string

Locales returns a sorted list of all locales that have at least one asset variant registered in c.

func (c *AssetCatalog) MarshalAssetManifestYAML() ([]byte, error)

MarshalAssetManifestYAML writes c's AssetManifest snapshot with EncodeAssetManifest.

func (c *AssetCatalog) Names() []string

Names returns a sorted list of all logical asset names registered in c.

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 (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 (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 (c *AssetCatalog) RegisterMap(name string, variants map[string]string)

RegisterMap registers multiple locale variants (locale -> path) for logical asset name.

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 (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 (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 (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 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(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 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.

func NewCatalog(fallbackLocale string) *Catalog

NewCatalog creates a new localization catalog whose fallback locale is fallbackLocale (for example "en" or "en-US").

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 (c *Catalog) FallbackLocale() string

FallbackLocale returns the normalized fallback locale configured on c.

func (c *Catalog) Has(locale, key string) bool

Has reports whether key resolves in locale or anywhere along its fallback chain.

func (c *Catalog) LoadJSON(locale string, data []byte) error

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.

func (c *Catalog) LoadYAML(data []byte) error

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 (c *Catalog) Locales() []string

Locales returns a sorted list of all locales that have entries in c.

func (c *Catalog) MarshalYAML(locale string) ([]byte, error)

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 (c *Catalog) Plural(locale, key string, count int, args ...Arg) string

Plural resolves key for locale, selects the plural form matching count for the matched locale's plural rules, and interpolates named placeholders.

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 (c *Catalog) Set(locale, key, value string)

Set stores a localized string for locale and key.

func (c *Catalog) SetPlural(locale, key string, forms PluralForms)

SetPlural stores plural form templates for locale and key.

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.

func (c *Catalog) T(locale, key string, args ...Arg) string

T resolves key for locale along the BCP-47 fallback chain and interpolates any named placeholders ({name}) using args.

If key is not found in any locale in the chain, key itself is returned.

type Direction uint8

Direction specifies horizontal text and layout reading direction.

const (
	// DirLTR is left-to-right direction (Latin, CJK, Cyrillic, etc.).
	DirLTR Direction = iota
	// DirRTL is right-to-left direction (Arabic, Hebrew, Persian, Urdu, etc.).
	DirRTL
)
func EnvDirection(cx *core.Scope) Direction

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(locale string) Direction

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.

func TextDirection(s string) Direction

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.

func (d Direction) IsRTL() bool

IsRTL reports whether d is DirRTL.

func (d Direction) String() string

String returns "ltr" or "rtl".

type FontRun[F any] struct {
	Text   string
	Script Script
	Font   F
	Start  int
	End    int
}

FontRun pairs a segmented text run with its resolved Script and font.

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).

func NewFontSet[F any](defaultFont F) *FontSet[F]

NewFontSet creates a FontSet with defaultFont as its fallback font.

func (fs *FontSet[F]) Default() F

Default returns the fallback font configured on fs.

func (fs *FontSet[F]) ForLocale(locale string) F

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 (fs *FontSet[F]) ForScript(script Script) F

ForScript returns the font registered for script, or the default font if none is set.

func (fs *FontSet[F]) ForText(locale, text string) F

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 (fs *FontSet[F]) RunsForText(locale, text string) []FontRun[F]

RunsForText segments text by script and attaches the resolved font for each run, enabling mixed-script rendering (for example Latin + CJK or Arabic).

func (fs *FontSet[F]) SetLocale(locale string, font F)

SetLocale registers font for a BCP-47 locale tag (for example "zh-Hans" vs "zh-Hant" vs "ja" to pick region-specific Han glyph forms).

func (fs *FontSet[F]) SetScript(script Script, font F)

SetScript registers font for a Unicode script (for example ScriptCJK or ScriptArabic).

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(cx *core.Scope, cat *Catalog) *Localizer

NewLocalizer creates a reactive Localizer owned by cx backed by cat.

func (l *Localizer) Catalog() *Catalog

Catalog returns the underlying Catalog.

func (l *Localizer) Direction() 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 (l *Localizer) Locale() string

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 (l *Localizer) Plural(key string, count int, args ...Arg) string

Plural resolves a pluralized key for the active locale and count. Reading Plural inside a reactive computation subscribes it to locale changes.

func (l *Localizer) RTL() bool

RTL reports whether the active layout direction is right-to-left.

func (l *Localizer) SetLocale(locale string)

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.

func (l *Localizer) T(key string, args ...Arg) string

T resolves key for the active locale and interpolates args. Reading T inside a reactive computation subscribes it to locale changes.

func (l *Localizer) Visual(s string) string

Visual reorders s into visual left-to-right drawing order for the active Direction.

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 (r MissingReport) Complete() bool

Complete reports whether every audited asset has a direct variant for Locale.

type PluralForms struct {
	// Zero is the template used when count is 0 (if provided) 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 plural category. Any unset category falls back to Other (or One if Other is empty).

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 uint8

Script identifies a Unicode writing script for font selection and text segmentation.

const (
	ScriptCommon Script = iota
	ScriptLatin
	ScriptCJK
	ScriptJapanese
	ScriptKorean
	ScriptArabic
	ScriptHebrew
	ScriptCyrillic
	ScriptGreek
	ScriptThai
	ScriptDevanagari
)
func DetectScript(s string) Script

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(locale string) Script

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(r rune) Script

RuneScript classifies a single Unicode rune into its Script. Spaces, digits, punctuation, and symbols return ScriptCommon.

func (s Script) String() string

String returns the human-readable name of s.

type ScriptRun struct {
	Text   string
	Script Script
	Start  int
	End    int
}

ScriptRun is a contiguous slice of text sharing a resolved Script. Start and End are byte offsets into the original string.

func SegmentByScript(s string) []ScriptRun

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 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(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.