i18n

package
v4.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 12 Imported by: 0

README

GWC | I18n Library

GoWebComponents (GWC)

High-Level Overview

The i18n library provides translation primitives and locale-aware text helpers for GWC apps.

Public APIs

github.com/monstercameron/GoWebComponents/i18n (package i18n)
  • Functions: BundleFromSSRBootstrap, DefaultLocale, Direction, DirectionForLocale, FallbackLocale, FormatDate, FormatNumber, Get, Locale, Locales, NewBundle, NormalizeLocale, PrefixPath, Provider, Register, RegisterNamespace, ResolvePath, Set, SetLocale, SupportedLocales, T, ToSSRBootstrap, Translate, UseI18n, UseLocale
  • Types: Arguments, Bundle, BundleOptions, Catalog, DateOptions, DateStyle, Direction, LocaleOptions, LocaleState, Message, MissingHandler, NamespaceCatalog, NumberOptions, PluralCategory, ProviderProps, ResolvedPath, RouteOptions, Runtime, SSRBootstrapOptions
  • Variables: none
  • Constants: DateStyleLong, DateStyleMedium, DateStyleShort, DirectionAuto, DirectionLTR, DirectionRTL, PluralFew, PluralMany, PluralOne, PluralOther, PluralTwo, PluralZero

Subfiles And Purpose

  • doc.go - Package-level Go documentation
  • helpers_more_test.go - Tests for helpers_more behavior
  • i18n.go - Core implementation for i18n
  • i18n_additional_test.go - Tests for i18n_additional behavior
  • i18n_benchmark_test.go - Tests for i18n_benchmark behavior
  • i18n_test.go - Tests for i18n behavior
  • locale_native.go - Native (non-WASM) implementation for locale
  • locale_wasm.go - WebAssembly-specific implementation for locale
  • runtime_core_test.go - Tests for runtime_core behavior

File Map

i18n/
|-- doc.go
|-- helpers_more_test.go
|-- i18n.go
|-- i18n_additional_test.go
|-- i18n_benchmark_test.go
|-- i18n_test.go
|-- locale_native.go
|-- locale_wasm.go
\-- runtime_core_test.go

Documentation

Overview

Package i18n provides locale state, message catalogs, interpolation, pluralization, locale-aware formatting helpers, and SSR bootstrap helpers for GoWebComponents applications.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatDate

func FormatDate(parseLocale string, parseValue time.Time, parseOptions ...DateOptions) string

FormatDate formats value as a locale-aware date string.

func FormatList

func FormatList(parseLocale string, parseItems []string) string

FormatList joins parseItems into a locale-aware list string using the appropriate conjunction for parseLocale (e.g. "a, b, and c" for en).

Example

ExampleFormatList joins items with the locale's list conjunction.

package main

import (
	"fmt"

	"github.com/monstercameron/GoWebComponents/v4/i18n"
)

func main() {
	fmt.Println(i18n.FormatList("en", []string{"alpha", "beta", "gamma"}))
}
Output:
alpha, beta, and gamma

func FormatNumber

func FormatNumber(parseLocale string, parseValue float64, parseOptions ...NumberOptions) string

FormatNumber formats value as a locale-aware number string.

func FormatRelativeTime

func FormatRelativeTime(parseLocale string, parseValue time.Time, parseBase time.Time) string

FormatRelativeTime formats parseValue relative to parseBase as a human-readable string in the language of parseLocale (e.g. "3 days ago", "in 2 hours").

Example

ExampleFormatRelativeTime formats a timestamp relative to a base time.

package main

import (
	"fmt"
	"time"

	"github.com/monstercameron/GoWebComponents/v4/i18n"
)

func main() {
	parseBase := time.Date(2026, 6, 11, 12, 0, 0, 0, time.UTC)
	parsePast := parseBase.Add(-3 * 24 * time.Hour)
	fmt.Println(i18n.FormatRelativeTime("en", parsePast, parseBase))
	fmt.Println(i18n.FormatRelativeTime("fr", parsePast, parseBase))
}
Output:
3 days ago
il y a 3 jours

func NormalizeLocale

func NormalizeLocale(parseRaw string) string

NormalizeLocale parses and canonicalizes a BCP 47 locale tag.

func PrefixPath

func PrefixPath(parseLocale string, parsePath string, parseOptions RouteOptions) string

PrefixPath prepends the locale prefix to path according to the route options.

func Provider

func Provider(parseProps ProviderProps) ui.Node

Provider renders an i18n runtime context provider around its children.

Types

type Arguments

type Arguments map[string]any

type Bundle

type Bundle struct {
	// contains filtered or unexported fields
}

func BundleFromSSRBootstrap

func BundleFromSSRBootstrap(parsePayload ui.SSRI18nBootstrap) *Bundle

BundleFromSSRBootstrap reconstructs a Bundle from an SSR bootstrap payload.

func NewBundle

func NewBundle(parseOptions ...BundleOptions) *Bundle

NewBundle creates a new i18n Bundle with the given options.

func (*Bundle) DefaultLocale

func (parseB *Bundle) DefaultLocale() string

func (*Bundle) FallbackLocale

func (parseB *Bundle) FallbackLocale() string

func (*Bundle) Locales

func (parseB *Bundle) Locales() []string

func (*Bundle) Register

func (parseB *Bundle) Register(parseLocale string, parseCatalog Catalog)

func (*Bundle) RegisterNamespace

func (parseB *Bundle) RegisterNamespace(parseLocale string, parseNamespace string, parseEntries NamespaceCatalog)

func (*Bundle) ToSSRBootstrap

func (parseB *Bundle) ToSSRBootstrap(parseOptions SSRBootstrapOptions) ui.SSRI18nBootstrap

func (*Bundle) Translate

func (parseB *Bundle) Translate(parseLocale string, parseNamespace string, parseKey string, parseArgs Arguments, parseFallbackLocale string) string

type BundleOptions

type BundleOptions struct {
	DefaultLocale  string
	FallbackLocale string
	OnMissing      MissingHandler
}

type Catalog

type Catalog map[string]NamespaceCatalog

type DateOptions

type DateOptions struct {
	Style    DateStyle
	Location *time.Location
}

type DateStyle

type DateStyle string
const (
	DateStyleShort  DateStyle = "short"
	DateStyleMedium DateStyle = "medium"
	DateStyleLong   DateStyle = "long"
)

type Direction

type Direction string
const (
	DirectionLTR  Direction = "ltr"
	DirectionRTL  Direction = "rtl"
	DirectionAuto Direction = "auto"
)

func DirectionForLocale

func DirectionForLocale(parseLocale string) Direction

DirectionForLocale returns DirectionRTL for right-to-left locales, otherwise DirectionLTR.

type LazyBundle

type LazyBundle struct {
	// contains filtered or unexported fields
}

LazyBundle wraps a Bundle with on-demand locale loading: a locale's catalog is fetched and registered the first time it is needed, not all up front. The application supplies the transport (the LocaleLoader); LazyBundle owns the load-once orchestration — dedup + register — so a locale is never registered twice and concurrent callers share one registration. This is the "lazy locale loading" path: ship only the active locale's strings on first paint and pull other locales when the user actually switches.

func NewLazyBundle

func NewLazyBundle(parseBundle *Bundle, parseLoad LocaleLoader) *LazyBundle

NewLazyBundle wraps bundle with the given on-demand loader. Any locales already registered on bundle (e.g. the initial/SSR locale) are treated as pre-loaded and never re-fetched.

func (*LazyBundle) Bundle

func (parseL *LazyBundle) Bundle() *Bundle

Bundle returns the underlying Bundle for Provider wiring, Translate, formatting, etc.

func (*LazyBundle) EnsureLocale

func (parseL *LazyBundle) EnsureLocale(parseLocale string) error

EnsureLocale loads and registers a locale's catalog if not already present, exactly once. Call it before switching to a locale (e.g. in a route guard or before Runtime.SetLocale) so the strings are present when the UI renders. It is idempotent and concurrency-safe; an already-loaded locale, a nil loader, or a nil bundle is a no-op returning nil. A loader error is returned and the locale stays unloaded so a later call can retry.

func (*LazyBundle) Loaded

func (parseL *LazyBundle) Loaded(parseLocale string) bool

Loaded reports whether a locale's catalog has been loaded and registered.

type LocaleLoader

type LocaleLoader func(parseLocale string) (Catalog, error)

LocaleLoader loads the full Catalog for one locale on demand — e.g. fetching a locale JSON bundle in the browser (via interop.ImportModule or fetch) or reading an embedded file on the server. It is called at most once per locale by LazyBundle.

type LocaleOptions

type LocaleOptions struct {
	InitialLocale    string
	SupportedLocales []string
	FallbackLocale   string
	PersistenceKey   string
	DetectBrowser    bool
	OnChange         func(string)
}

type LocaleState

type LocaleState struct {
	// contains filtered or unexported fields
}

func UseLocale

func UseLocale(parseLocaleOptions LocaleOptions) LocaleState

UseLocale creates a non-reactive LocaleState using the given options.

func (LocaleState) Direction

func (parseS LocaleState) Direction() Direction

func (LocaleState) FallbackLocale

func (parseS LocaleState) FallbackLocale() string

func (LocaleState) Get

func (parseS LocaleState) Get() string

func (LocaleState) Set

func (parseS LocaleState) Set(parseLocale string)

func (LocaleState) SupportedLocales

func (parseS LocaleState) SupportedLocales() []string

type Message

type Message struct {
	Text      string
	PluralArg string
	Plural    map[PluralCategory]string
	SelectArg string
	Select    map[string]string
	Default   string
}

type MissingHandler

type MissingHandler func(locale string, namespace string, key string) string

type Namespace

type Namespace struct {
	// contains filtered or unexported fields
}

Namespace binds a Runtime to a single namespace so its translations are looked up by key alone. It removes the per-call footgun of T(namespace, key, …) where swapping or forgetting the positional namespace silently misses; the namespace is fixed once at the NS() call site.

func (Namespace) Name

func (parseN Namespace) Name() string

Name returns the bound namespace.

func (Namespace) T

func (parseN Namespace) T(parseKey string, parseArgs ...Arguments) string

T translates key within the bound namespace, with the same args/fallback semantics as Runtime.T.

type NamespaceCatalog

type NamespaceCatalog map[string]Message

type NumberOptions

type NumberOptions struct {
	MaximumFractionDigits int
}

type PluralCategory

type PluralCategory string
const (
	PluralZero  PluralCategory = "zero"
	PluralOne   PluralCategory = "one"
	PluralTwo   PluralCategory = "two"
	PluralFew   PluralCategory = "few"
	PluralMany  PluralCategory = "many"
	PluralOther PluralCategory = "other"
)

type ProviderProps

type ProviderProps struct {
	Locale         LocaleState
	CurrentLocale  string
	FallbackLocale string
	Bundle         *Bundle
	Child          ui.Node
	Children       []ui.Node
}

type ResolvedPath

type ResolvedPath struct {
	Locale        string
	BasePath      string
	LocalizedPath string
	PrefixPresent bool
}

func ResolvePath

func ResolvePath(parsePath string, parseOptions RouteOptions) ResolvedPath

ResolvePath extracts the locale prefix from path and returns routing metadata.

type RouteOptions

type RouteOptions struct {
	SupportedLocales  []string
	DefaultLocale     string
	OmitDefaultPrefix bool
}

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

func UseI18n

func UseI18n() Runtime

UseI18n returns the i18n Runtime from the nearest Provider ancestor.

func (Runtime) Direction

func (parseR Runtime) Direction() Direction

func (Runtime) FormatDate

func (parseR Runtime) FormatDate(parseValue time.Time, parseOptions ...DateOptions) string

func (Runtime) FormatNumber

func (parseR Runtime) FormatNumber(parseValue float64, parseOptions ...NumberOptions) string

func (Runtime) Locale

func (parseR Runtime) Locale() string

func (Runtime) NS

func (parseR Runtime) NS(parseNamespace string) Namespace

NS returns a Namespace handle bound to namespace, so a component that translates many keys in the same namespace writes t := r.NS("checkout"); t.T("title"); t.T("total", args) instead of repeating the namespace (and risking a typo) at every call.

func (Runtime) PrefixPath

func (parseR Runtime) PrefixPath(parsePath string, parseOptions ...RouteOptions) string

func (Runtime) SetLocale

func (parseR Runtime) SetLocale(parseLocale string)

func (Runtime) T

func (parseR Runtime) T(parseNamespace string, parseKey string, parseArgs ...Arguments) string

type SSRBootstrapOptions

type SSRBootstrapOptions struct {
	Locale            string
	FallbackLocale    string
	Direction         Direction
	IncludeLocales    []string
	IncludeNamespaces []string
}

Directories

Path Synopsis
Package extract provides build-time i18n message extraction and locale completeness checking for the GoWebComponents i18n framework.
Package extract provides build-time i18n message extraction and locale completeness checking for the GoWebComponents i18n framework.

Jump to

Keyboard shortcuts

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