l10n

package
v0.4.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package l10n is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package l10n provides localization for NSGo games: versioned YAML and JSON string tables with BCP-47 locale fallback, plain and locale-aware styled interpolation, and CLDR pluralization; locale-aware number, integer, percent, compact, list, and duration formatting and BCP-47 language display names; 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, golang.org/x/text for CLDR number formatting, and go.yaml.in/yaml/v3 for YAML string tables and asset manifests.

Index

Examples

Constants

View Source
const AssetManifestVersion = 1

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

View Source
const CLDRVersion = "48.2"

CLDRVersion is the Unicode CLDR release used to generate the cardinal integer plural rules.

View Source
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.

View Source
const SchemaURL = "https://nsgo.games/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.

View Source
const StringTableVersion = 1

StringTableVersion is the YAML string table schema version this package reads and writes.

Variables

This section is empty.

Functions

func BidiLevels

func BidiLevels(line string, baseDir Direction) []uint8

BidiLevels returns the resolved embedding level of each rune of one line of logical-order text under baseDir, by the same rules VisualOrder uses: even levels run left to right and odd levels right to left, and white space at the end of the line takes the base level (rule L1). A caller that shapes runs of text itself (rich text drawn through the platform, for example) splits the line where the level changes and puts the runs in visual order with ReorderLevels. The result has one entry per rune of line; line must not contain '\n'.

func DisplayStyle

func DisplayStyle(style string) string

DisplayStyle returns "plain" when style is empty, otherwise style.

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 ExportCSV

func ExportCSV(w io.Writer, locales []string, rows map[string]map[string]string) error

ExportCSV writes a key/locale table: a header row "key" followed by locales in the given order, then one row per key in sorted order. A locale a key has no text for is written as an empty cell.

func ExportPO

func ExportPO(w io.Writer, source, target *StringTable, opts POOptions) error

ExportPO writes target (paired with source for msgid source strings; source may be nil to fall back to target's own strings) as a deterministic GNU gettext .po file.

Each entry uses msgctxt for the message key and msgid for the source text. CLDR plural entries emit msgid_plural and msgstr[0..n-1] ordered by PluralCategories(target.Locale), with a matching Plural-Forms header. When target's CLDR integer categories omit "zero" (or "other" for rules such as ru/pl) and either table supplies that form, a companion singular entry tagged with "#. nsgo-plural-form: <cat>" preserves it losslessly across round trips. Output contains no timestamps so round trips are byte-stable.

func ExportPOT

func ExportPOT(w io.Writer, source *StringTable, extraKeys []string, opts POOptions) error

ExportPOT writes a deterministic GNU gettext .pot template containing every key from source (which may be nil) plus any additional keys in extraKeys (for example keys extracted from Go source, scenes, screens, cutscenes, and data tables).

func ExportTablesCSV

func ExportTablesCSV(w io.Writer, tables []*StringTable, opts CSVOptions) error

ExportTablesCSV writes one or more StringTables as a deterministic CSV file.

When no table contains plural keys, the header is "key,context,<locales...>". When any table contains plural keys, the header is "key,plural,context,<locales...>", with an empty plural cell for plain strings and one row per non-empty CLDR plural category (zero, one, two, few, many, other) for plural keys. Locales are written in the order of tables, keys are sorted lexicographically, and cells starting with spreadsheet formula characters are neutralized unless opts.DisableFormulaGuard is set.

func FormatCompact

func FormatCompact(locale string, v float64, opts ...NumberOption) string

FormatCompact formats v using CLDR 48.2 short compact decimal notation (such as "12K" in en, "1.2万" in ja/zh-Hans, "1,2\u00a0Mio." in de, or "1.2\u00a0लाख" in hi). Locales or magnitudes without a CLDR compact rule (such as thousands in de, or unlisted locales) fall back to plain locale grouping via FormatNumber.

func FormatDuration

func FormatDuration(locale string, d time.Duration, opts ...NumberOption) string

FormatDuration formats d as whole days, hours, minutes, and seconds using locale's CLDR short/narrow duration units and numbering system, truncating sub-second fractions (for example "1m 35s" in en, "1分35秒" in ja). Zero components are omitted unless the whole-second duration is 0 (which formats as 0 seconds). A negative duration is written with a single leading minus sign.

func FormatInteger

func FormatInteger(locale string, v int64, opts ...NumberOption) string

FormatInteger formats v with locale's CLDR integer grouping and numbering system. Pass LatinDigits() to keep ASCII digits 0-9.

func FormatList

func FormatList(locale string, items []string) string

FormatList joins items using locale's CLDR conjunction ("and") list pattern (for example "A, B, and C" in en, "A, B und C" in de, "A、B、C" in ja).

func FormatListOr

func FormatListOr(locale string, items []string) string

FormatListOr joins items using locale's CLDR disjunction ("or") list pattern (for example "A, B, or C" in en, "A, B oder C" in de).

func FormatNumber

func FormatNumber(locale string, v float64, opts ...NumberOption) string

FormatNumber formats v according to locale's CLDR decimal grouping, decimal separator, and default numbering system (via golang.org/x/text/number). Pass Decimals(n) to fix the number of fractional digits and LatinDigits() to keep ASCII digits 0-9. Non-finite values format as "NaN", "∞", and "-∞".

func FormatPercent

func FormatPercent(locale string, v float64, opts ...NumberOption) string

FormatPercent formats a unit fraction v (for example 0.35 for 35%) according to locale's CLDR percent pattern, percent sign, spacing, and numbering system. Pass Decimals(n) to fix fractional digits and LatinDigits() to keep ASCII digits.

func ImportCSV

func ImportCSV(r io.Reader) ([]string, map[string]map[string]string, error)

ImportCSV reads a table ExportCSV wrote and returns its locales in column order and its rows by key. A header that does not start with "key", a locale column that is not a canonical BCP-47 tag or appears twice, a row with the wrong number of columns, an empty key and a key on more than one row are refused.

func LanguageName

func LanguageName(tag string) string

LanguageName returns the native (self) display name of a BCP-47 locale tag from Unicode CLDR 48.2 (for example "日本語" for "ja", "Deutsch" for "de", "简体中文" for "zh-Hans", "العربية" for "ar", "हिन्दी" for "hi"). Unknown or empty tags are returned as their trimmed/normalized input.

func LanguageNameIn

func LanguageNameIn(tag, displayLocale string) string

LanguageNameIn returns the display name of tag written in displayLocale from Unicode CLDR 48.2 (for example LanguageNameIn("ja", "en") == "Japanese", LanguageNameIn("en", "ja") == "英語"). If displayLocale or tag has no entry in the CLDR table, it falls back to LanguageName(tag).

func LayoutAlignment

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

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

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 PseudoLocale

func PseudoLocale(text string) string

PseudoLocale returns text with its Latin vowels replaced by accented capitals and the result wrapped in brackets, for spotting hard-coded strings, missing glyphs and clipped text in UI review. Placeholders ({name}, {name, style[, option]}), key references ({@key}), inline plural/select syntax and selectors, #, and the escaped braces {{ and }} are preserved so the result still evaluates with Catalog.Format, while literal text inside plural and select branches is pseudolocalized.

func ReadingOrder

func ReadingOrder(count int, rtl bool) []int

ReadingOrder returns the indices 0 to count-1 in visual reading order, reversed when rtl is true, for laying out or focusing a row of items; mirror each item's position with MirrorX. It returns nil when count is not positive.

func ReorderLevels

func ReorderLevels(levels []uint8) []int

ReorderLevels returns the indices of items with the given embedding levels in visual order from left to right, by rule L2 of the bidirectional algorithm: from the highest level down to the lowest odd level, every maximal sequence at that level or higher is reversed. The items may be runes or runs of uniform level; levels usually comes from BidiLevels. It returns nil for no items.

func StripPlaceholders

func StripPlaceholders(tmpl string) string

StripPlaceholders removes {name}, styled placeholders, {@key} references, and inline plural/select markup from tmpl while keeping visible literal text from every branch and unescaping doubled braces ("{{" -> "{", "}}" -> "}"). Malformed templates with unclosed braces fall back to keeping unclosed braces literally.

func TemplateLocale

func TemplateLocale(tag string, available []string) string

TemplateLocale resolves a device language tag to a catalog locale with deterministic fallback.

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 ValidateLocale

func ValidateLocale(locale string) error

ValidateLocale reports whether locale is a non-empty canonical BCP-47 locale tag (matching NormalizeLocale, with ASCII alphanumeric subtags of length 1 to 8).

func ValidatePlaceholders

func ValidatePlaceholders(source, translated string) error

ValidatePlaceholders reports an error unless translated matches source's placeholders. For plain/styled templates without inline plural or select branches, translated must use the exact same placeholders as source, each as many times. For templates with inline plural or select choices, translated must use the same set of placeholder names and select branch keys (allowing different branch counts across locales). Doubled braces ("{{", "}}") are literal braces, as in Catalog.Format.

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, non-empty PluralForms entries, valid message template syntax (placeholders, styles, inline plural/select branches with required "other", and {@key} references), and acyclic {@key} references.

func ValidateTablePlaceholders

func ValidateTablePlaceholders(source, target *StringTable) error

ValidateTablePlaceholders verifies that every translated string and plural form in target preserves the placeholders, select branch keys, and placeholder styles of source, and does not change a key between plain string and plural form. Errors name both the target locale and message key.

func ValidateTemplate

func ValidateTemplate(tmpl string) error

ValidateTemplate parses tmpl strictly as a localization message template and returns a *TemplateError with its 1-based rune column if tmpl is malformed.

func VisualOrder

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.

func VisualRuneOrder

func VisualRuneOrder(line string, baseDir Direction) []int

VisualRuneOrder returns, for one line of logical-order text, the logical rune index drawn at each visual position from left to right under baseDir, using the same bidirectional rules as VisualOrder. The result has one entry per rune of line; a caller that lays out its own glyphs (rich text, for example) uses it to place them without losing which logical rune each one came from. VisualOrder(line, baseDir) equals the runes of line taken in this order, except that paired brackets at right-to-left levels are mirrored. line must not contain '\n'.

Types

type Arg

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

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

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 and WatchLocale whenever one or more asset groups are affected by a locale switch. The returned function removes the callback.

func (*AssetCatalog) Read

func (c *AssetCatalog) Read(fsys fs.FS, name, locale string) ([]byte, ResolvedAsset, error)

Read resolves a logical asset and reads its selected variant from fsys. The returned metadata identifies the locale fallback that was used.

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

func (c *AssetCatalog) ResolvePath(name string) (string, bool)

ResolvePath resolves logical asset name for the catalog's current active locale (falling back along the BCP-47 chain to BaseLocale) and returns its concrete path. It satisfies assets.LocaleCatalog directly.

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 (and any registered OnReload listeners) 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 CSVImportResult

type CSVImportResult struct {
	// Locales lists the locale columns in the order they appeared in the CSV header.
	Locales []string
	// Tables maps each normalized BCP-47 locale tag in Locales to its StringTable.
	Tables map[string]*StringTable
	// Context maps message keys to non-empty translator notes read from the
	// optional "context" column.
	Context map[string]string
}

CSVImportResult holds the string tables and optional translator notes decoded by ImportTablesCSV.

func ImportTablesCSV

func ImportTablesCSV(r io.Reader, opts CSVOptions) (*CSVImportResult, error)

ImportTablesCSV reads a CSV file produced by ExportTablesCSV (or a hand-authored CSV with header "key,[plural,][context,]<locales...>") into per-locale StringTables.

Unknown or non-canonical locale columns, duplicate locales, wrong column counts, invalid keys, invalid CLDR plural categories, duplicate (key, plural) rows, keys mixed as both plain string and plural, and invalid message templates are refused.

type CSVOptions

type CSVOptions struct {
	// Context maps message keys to optional translator notes written in the
	// "context" CSV column on export.
	Context map[string]string
	// DisableFormulaGuard disables spreadsheet formula injection neutralization
	// on CSV cells starting with '=', '+', '-', '@', '\t', or '\r'. By default
	// (false), ExportTablesCSV prepends a single quote (') to cells matching
	// ^'*[=+\-@\t\r] and ImportTablesCSV strips one leading quote from cells
	// matching ^'+[=+\-@\t\r], which is bijective and lossless across round trips.
	DisableFormulaGuard bool
}

CSVOptions configures ExportTablesCSV and ImportTablesCSV.

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

func NewCatalog(fallbackLocale string) *Catalog

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 or introduces a cyclic {@key} reference.

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

func (c *Catalog) FallbackLocale() string

FallbackLocale returns the normalized fallback locale configured on c.

func (*Catalog) Format

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

Format resolves key for locale along the BCP-47 fallback chain and evaluates its message template with args. Templates support plain {name} placeholders, locale-aware styled placeholders ({name, style[, option]}), inline CLDR plurals ({n, plural, =0 {...} one {# ...} other {...}}), select choices ({g, select, female {...} male {...} other {...}}), arbitrary nesting, and same-locale key references ({@other.key}).

When key resolves to a plural-forms entry and args supplies an integer "count" parameter, Format selects the matching CLDR plural form; otherwise it uses Other (or One if Other is empty). If key is not found in any locale in the chain, key itself is returned.

func (*Catalog) Has

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

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

func (*Catalog) LoadJSON

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.

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

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 (*Catalog) Locales

func (c *Catalog) Locales() []string

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

func (*Catalog) MarshalYAML

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 (*Catalog) Plural

func (c *Catalog) Plural(locale, key string, count int, args ...Arg) string

Plural resolves key for locale, selects the plural form matching integer count under the matched locale's CLDR cardinal plural rules (CLDRVersion), and evaluates the template with args (including inline plural/select choices and {@key} references).

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

func (c *Catalog) Set(locale, key, value string)

Set stores a localized string for locale and key.

func (*Catalog) SetLatinDigits

func (c *Catalog) SetLatinDigits(enabled bool)

SetLatinDigits configures whether styled placeholders in T and Plural (number, integer, percent, compact, duration) default to ASCII Latin digits (0-9) instead of the locale's native numbering system (such as Arabic-Indic digits in "ar"). Individual placeholders can still specify the "latin" option.

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.

func (*Catalog) T

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

T resolves key for locale along the BCP-47 fallback chain and formats its template using args. It calls Format.

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

func (*Catalog) UseLatinDigits

func (c *Catalog) UseLatinDigits() bool

UseLatinDigits reports whether c formats styled numeric placeholders with ASCII Latin digits by default.

type Direction

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

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

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.

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

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 (Direction) IsRTL

func (d Direction) IsRTL() bool

IsRTL reports whether d is DirRTL.

func (Direction) String

func (d Direction) String() string

String returns "ltr" or "rtl".

type FontRun

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

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

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

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

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

func (fs *FontSet[F]) ForScript(script Script) F

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

func (*FontSet[F]) ForText

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 (*FontSet[F]) RunsForText

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 (*FontSet[F]) SetLocale

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 (*FontSet[F]) SetScript

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

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

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

func NewLocalizer(cx *core.Scope, cat *Catalog) *Localizer

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

func (*Localizer) Catalog

func (l *Localizer) Catalog() *Catalog

Catalog returns the underlying Catalog.

func (*Localizer) Direction

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 (*Localizer) Format

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

Format resolves key for the active locale and evaluates its message template with args. Reading Format inside a reactive computation subscribes it to locale changes.

func (*Localizer) Locale

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 (*Localizer) Plural

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 (*Localizer) RTL

func (l *Localizer) RTL() bool

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

func (*Localizer) SetLocale

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 (*Localizer) T

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 (*Localizer) Visual

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

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

type MessageMismatch

type MessageMismatch struct {
	Kind        MessageMismatchKind
	Key         string
	IsPlural    bool
	BaseLocale  string
	Locale      string
	Placeholder string
	SelectKey   string
}

MessageMismatch reports one placeholder or select-key difference between Locale and BaseLocale for a message key.

func CheckMessages

func CheckMessages(tables ...*StringTable) []MessageMismatch

CheckMessages compares every locale's placeholders and select branch keys against the base locale ("en" when present, otherwise the first locale in sorted order) across all string and plural keys defined in both locales.

Results are sorted deterministically by Locale, Key, IsPlural, Kind, Placeholder, and SelectKey.

type MessageMismatchKind

type MessageMismatchKind string

MessageMismatchKind classifies a cross-locale placeholder or select-key mismatch reported by CheckMessages.

const (
	// MismatchMissingPlaceholder reports a placeholder present in BaseLocale
	// that is missing from Locale.
	MismatchMissingPlaceholder MessageMismatchKind = "missing_placeholder"
	// MismatchExtraPlaceholder reports a placeholder present in Locale that is
	// absent from BaseLocale.
	MismatchExtraPlaceholder MessageMismatchKind = "extra_placeholder"
	// MismatchMissingSelectKey reports a select branch key present in BaseLocale
	// that is missing from Locale.
	MismatchMissingSelectKey MessageMismatchKind = "missing_select_key"
	// MismatchExtraSelectKey reports a select branch key present in Locale that
	// is absent from BaseLocale.
	MismatchExtraSelectKey MessageMismatchKind = "extra_select_key"
)

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 NumberOption

type NumberOption func(*numberConfig)

NumberOption configures FormatNumber, FormatInteger, FormatPercent, FormatCompact, and FormatDuration.

func Decimals

func Decimals(n int) NumberOption

Decimals fixes the exact number of fractional digits emitted by FormatNumber, FormatPercent, and FormatCompact. Negative values are clamped to 0.

func LatinDigits

func LatinDigits() NumberOption

LatinDigits formats numbers with ASCII Latin digits (0-9) instead of the locale's default numbering system (for example Arabic-Indic digits in "ar").

type POImportResult

type POImportResult struct {
	// Locale is the normalized BCP-47 locale tag resolved from the locale parameter
	// or the PO file's Language header.
	Locale string
	// Table holds every non-empty, non-fuzzy translated string and plural entry.
	Table *StringTable
	// Comments maps message keys to translator notes ("#." / "# ") found in the PO file.
	Comments map[string]string
	// Fuzzy lists sorted message keys marked with "#, fuzzy" in the PO file; fuzzy
	// translations are not merged into Table so unreviewed guesses are never imported silently.
	Fuzzy []string
}

POImportResult holds the decoded StringTable and metadata from ImportPO.

func ImportPO

func ImportPO(r io.Reader, locale string) (*POImportResult, error)

ImportPO parses a GNU gettext .po file strictly and decodes its translated entries into a StringTable for locale.

If locale is empty, the locale is read and normalized from the PO header's "Language:" field. If locale is non-empty, it must be a canonical BCP-47 tag and must agree with any non-empty "Language:" header in the file. Malformed escape sequences, unknown keywords, out-of-range msgstr[n] indices, duplicate keys or forms, and invalid message templates are refused. Entries marked "#, fuzzy" are recorded in POImportResult.Fuzzy and omitted from Table.

type POOptions

type POOptions struct {
	// Project is written to the Project-Id-Version header (defaults to "nsgo-game").
	Project string
	// Comments maps message keys to translator notes emitted as "#." extracted comments.
	Comments map[string]string
	// References maps message keys to source locations ("file:line") emitted as "#:" comments.
	References map[string][]string
	// PluralKeys optionally marks extra keys passed to ExportPOT as plural entries when
	// they do not exist in the source StringTable yet.
	PluralKeys map[string]bool
}

POOptions configures ExportPO and ExportPOT.

type Placeholder

type Placeholder struct {
	Name   string
	Style  string
	Option string
}

Placeholder describes one interpolation token in a localization template: plain "{name}" (Style == "") or styled "{name, style}" / "{name, style, option}".

func ParsePlaceholders

func ParsePlaceholders(tmpl string) ([]Placeholder, error)

ParsePlaceholders parses tmpl as a message template and returns every plain ({name}) and styled ({name, style[, option]}) placeholder found in tmpl, including placeholders nested inside inline plural and select branches.

func (Placeholder) Canonical

func (p Placeholder) Canonical() string

Canonical returns the normalized placeholder expression without surrounding braces (for example "score", "gold, number", or "off, percent, 0").

type PlaceholderStyleMismatch

type PlaceholderStyleMismatch struct {
	Key            string
	Placeholder    string
	BaseLocale     string
	BaseStyle      string
	Locale         string
	Style          string
	IsPlural       bool
	PluralCategory PluralCategory
}

PlaceholderStyleMismatch reports a placeholder whose style (plain "" vs "number", "integer", "percent", "compact", "list", or "duration") differs between locales for the same message key.

func CheckPlaceholderStyles

func CheckPlaceholderStyles(tables ...*StringTable) []PlaceholderStyleMismatch

CheckPlaceholderStyles compares placeholder styles for every string and plural key across tables and returns every mismatch where the same placeholder name uses a different style in another locale (or across forms of the same plural key). Style options such as "latin" or decimal counts are not treated as style mismatches. Results are sorted deterministically by Locale, Key, IsPlural, PluralCategory, and Placeholder.

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.

func (PluralForms) EachForm

func (p PluralForms) EachForm(fn func(cat PluralCategory, tmpl string))

EachForm calls fn for each non-empty plural form template in p in canonical CLDR category order (zero, one, two, few, many, other).

type RefIssue

type RefIssue struct {
	Kind     RefIssueKind
	Locale   string
	Key      string
	IsPlural bool
	Target   string   // referenced key for RefIssueMissingTarget
	Cycle    []string // cycle path for RefIssueCycle (e.g. ["a", "b", "a"])
}

RefIssue reports a broken or cyclic {@key} reference found across string tables.

func CheckMessageRefs

func CheckMessageRefs(tables ...*StringTable) []RefIssue

CheckMessageRefs audits {@key} references across tables, reporting missing reference targets (not present in the locale or its fallback chain to base) and reference cycles (including across multiple files in the same locale).

type RefIssueKind

type RefIssueKind string

RefIssueKind classifies a {@key} message reference problem reported by CheckMessageRefs.

const (
	// RefIssueMissingTarget reports a {@key} reference whose target key does not
	// exist in the locale or any locale along its fallback chain.
	RefIssueMissingTarget RefIssueKind = "missing_target"
	// RefIssueCycle reports a cycle among {@key} references (including cycles
	// spanning multiple string-table files or fallback locales).
	RefIssueCycle RefIssueKind = "cycle"
)

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.

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

func DetectScript

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

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

func RuneScript(r rune) Script

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

func (Script) String

func (s Script) String() string

String returns the human-readable name of s.

type ScriptRun

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

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

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.gold") to localized message templates. Templates support {name}, {name, style[, option]} (number, integer, percent, compact, list, duration), inline {n, plural, ... other {...}} with #, {g, select, ... other {...}}, nesting, and {@other.key} references.
	Strings map[string]string `yaml:"strings,omitempty"`
	// Plurals maps message keys to CLDR plural form templates (zero, one, two, few, many, other). Each form supports the same placeholder, inline plural/select, nesting, and {@key} reference syntax as strings.
	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://nsgo.games/schemas/l10n.v1.json
version: 1
locale: en
strings:
  hud.gold: "Gold: {gold, number}"
  hud.score: "Score: {score}"
  menu.play: Play
plurals:
  coins:
    zero: No coins
    one: "{count} coin"
    other: "{count} coins"

Templates support plain {name} placeholders (Go default formatting), locale-aware styled placeholders {name, style} or {name, style, option} (where style is number, integer, percent, compact, list, or duration), inline CLDR plurals {n, plural, [offset:N] =0 {...} one {# ...} other {...}} (where # formats the plural count), select choices {g, select, female {...} male {...} other {...}}, arbitrary nesting of plural and select, and same-locale key references {@other.key} (cycles refused). Numeric styles accept an optional decimal digit count (0-15) and/or "latin" to keep ASCII digits; integer and duration accept "latin"; list accepts "and" or "or". Escaped braces at top level use {{ and }}.

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 MergeStringTable

func MergeStringTable(existing, incoming *StringTable) (*StringTable, error)

MergeStringTable merges incoming's non-empty string and plural entries on top of a clone of existing (which may be nil) and validates the resulting table. Entries absent from incoming are preserved from existing, and empty plural categories in incoming do not erase existing forms.

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.

func (*StringTable) CollectChars

func (t *StringTable) CollectChars() string

CollectChars returns the sorted, deduplicated non-control characters used by every string and plural form in t after stripping {placeholders}.

type TemplateError

type TemplateError struct {
	Column  int
	Message string
}

TemplateError reports a syntax error in a localization message template at a 1-based rune Column within the template string.

func (*TemplateError) Error

func (e *TemplateError) Error() string

Error returns the formatted template error including its 1-based column when known.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL