Expand description
Typed Fluent messages for Bevy, built on
fluent-typed.
The optional fluent_typed_codegen
dependency generates typed accessors in build.rs. Load translations through
Bevy’s asset system or explicitly embed them.
§Setup
Add these dependencies to Cargo.toml:
[dependencies]
bevy = "0.20"
bevy_fluent_typed = { version = "0.5.0", features = ["codegen"] }
[build-dependencies]
bevy_fluent_typed = { version = "0.5.0", default-features = false, features = ["build"] }The normal dependency provides the plugin; the build dependency generates the
accessors. Configure the translation paths in the same Cargo.toml:
[package.metadata.localization]
catalog = "assets/localizations/localization.toml"Create build.rs beside Cargo.toml:
fn main() -> std::process::ExitCode {
bevy_fluent_typed::build()
}§Add the translations
Create these two files under the application’s standard Bevy assets directory:
assets/localizations/localization.toml
assets/localizations/translations/en/presentation/hud.ftlassets/localizations/localization.toml defines the manifest:
source-language = "en"
default-language = "en"
translations-directory = "translations"assets/localizations/translations/en/presentation/hud.ftl contains a message:
title = ReadyThis generates texts::presentation::Hud with a typed msg_title() accessor.
Add matching files under another language directory when you need another locale.
§Run a complete application
Replace src/main.rs with the following three blocks, in order.
First, import Bevy and the localization plugin, then declare the
module generated by build.rs:
use bevy::{asset::AssetPlugin, prelude::*};
use bevy_fluent_typed::LocalizationPlugin;
bevy_fluent_typed::translations!(mod texts);Next, register the plugin after Bevy’s DefaultPlugins:
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(AssetPlugin {
file_path: ".".into(),
..default()
}))
.add_plugins(LocalizationPlugin::<texts::Translations>::new(texts::manifest()))
.add_systems(Startup, show_title)
.run();
}Finally, read the generated resource:
fn show_title(hud: Res<texts::presentation::Hud>) {
println!("{}", hud.msg_title());
}Run cargo run. A Bevy window opens and the terminal prints Ready once the
translations are loaded. Close the window to exit. This uses Bevy’s normal
window setup and platform prerequisites.
For a console-only program, see the headless recipe.
texts::manifest() supplies the manifest contract from your build configuration.
It loads no translations and embeds no FTL. This application sets Bevy’s source
root to Bevy’s base directory (the package directory under cargo run) so
assets/localizations/localization.toml is resolved as written. The build path does not configure AssetServer automatically.
For another source layout, pass a LocalizationManifest with its runtime origin.
On Bevy 0.19/0.20, the default Lazy mode loads scopes used by inserted
Localized bindings and ordinary Res<Scope> systems. Startup defaults to
Deferred: show_title waits for the HUD, runs once and releases its temporary
demand. Independent startup steps run while it waits; frame updates keep loading
assets. Optional load/unload calls retain extra scopes independently.
After adding matching Spanish translations and rebuilding, use
localization.set_locale(texts::Locale::Es) to change language. The plugin
keeps the active resources and text until the requested language is ready, then
switches automatically. A failed target leaves the active language usable.
See the loading guide for automatic module lifetime and optional manual loading.
§Explicit embedding
To use the same application without shipping FTL files, replace its plugin constructor with:
LocalizationPlugin::<texts::Translations>::new(texts::embed_manifest!())Keep AssetPlugin installed. The generated macro includes FTL bytes only where
it is invoked; generation alone does not embed them. This form includes every
known language’s raw FTL. Needed scopes of the selected language are parsed
during plugin updates, so readiness checks still apply. Static source bytes stay in the executable for
its lifetime; no compressor or decompressor is involved.
The macro accepts only an empty invocation or a block of constants. For the constant-declaration recipe, use the same 0.5.0 dependency in both Cargo sections. Declare an embedded source for just the HUD:
texts::embed_manifest! {
pub const HUD = presentation::Hud;
}Pass HUD directly to LocalizationPlugin::<texts::Translations>::new(HUD).
Inserted HUD bindings and native resource systems request it automatically on
Bevy 0.19/0.20; no load call is needed.
HUD has type LocalizationManifest and contains this leaf’s bytes across known
languages. Select Presentation for that group’s descendants, or Translations
for the whole tree. These are paths relative to the generated tree, without
texts::; imported aliases and generic parameters are not selectors. Ordinary
catalog aliases remain usable for constructors and resources such as Res<Interface>.
Unselected payloads are absent even in debug builds without optimization, LTO
or linker dead-code removal. The macro is crate-local even when texts is public;
a private localization module can export the manifest constant and its catalog types.
§Supported engines
| Normal-dependency feature | Bevy release family |
|---|---|
bevy-0-20 (default) | 0.20.0 and compatible patches |
bevy-0-19 | 0.19.0 and compatible patches |
bevy-0-18 | 0.18.0 and compatible patches |
bevy-0-17 | 0.17.0 and compatible patches |
bevy-0-16 | 0.16.1 and compatible patches |
Rust minimum: 1.97.1. Select exactly one backend. For an older backend, disable defaults on the normal
runtime dependency, enable that backend plus codegen, and select the same
version family for bevy. Leave the build-dependency unchanged. Do not use
runtime/workspace --all-features. Examples that send exit or update notifications
use Bevy 0.20 message APIs;
Bevy 0.16 uses EventWriter/send instead of MessageWriter/write.
Bevy 0.19 and 0.20 discover native resource consumers, provide startup strategies,
and enforce immutable generated resources in ECS. Bevy 0.16–0.18 use
registration helpers
for automatic demand and resource readiness. They retain native one-shot startup; their read-only catalog
API does not have the ECS immutability guarantee. watch is an
optional normal-dependency feature for filesystem change notifications.
§Advanced integrations
Use custom Bevy asset sources for on-demand access to application-owned storage. Keep generated accessors when supplying already-loaded bytes; the plugin retains those buffers. See without code generation for a minimal runtime and a handwritten provider.
§Further reading
- Loading guide: automatic module lifetime, manual modes and headless applications.
- BSN and text spans: use the same binding on scene text and child spans.
- Loading progress: optional native progress subtrees and module details.
- Custom bindings: custom components, semantic labels and provider cache policies.
- Performance: skipped work, cache tradeoffs and measured costs.
- Migration Guide: choose the upgrade path from your current version.
- Changelog.
§Choose what stays loaded
A module is one FTL file. A scope is a generated leaf, a folder containing
leaves, or the whole Translations tree. Loading a scope requests all its leaves.
| Need | Plugin/controller mode | Requests |
|---|---|---|
| Load only modules used by text or resource systems | Lazy (default) | Bindings on every backend; native resource readers on 0.19/0.20, helper-registered readers on 0.16–0.18 |
| Keep the whole selected language ready, including direct world polling | Full | All modules automatically |
| Manage loading explicitly, including hybrid lifetimes | Manual | Explicit load and unload |
Use LocalizationPlugin::<texts::Translations>::new(texts::manifest()) for the
usual automatic path. With no consumers, manual pins or leases, no FTL modules
are read or parsed.
A scope requests complete FTL leaves, not individual messages. Creating an
unattached Msg or binding, inspecting the world, or navigating a controller
view is passive. Lazy also supports optional manual pins; Full has no
load or unload methods.
§Registration conflicts
Install one LocalizationPlugin per root catalog type. Every plugin claims its
complete root schema, including leaves absent from its source. Repeating that
root is a configuration error even with disjoint embedded subsets, different
languages, source kinds or loading modes. Branches are represented by their FTL
leaf paths; only schema structure participates in this check.
Ordinary app.add_plugins(plugin) checks this during plugin setup. A conflict
panics with the root catalog name, sorted leaf paths, both concrete plugin types
and the locations where the plugin values were constructed. The second provider’s
localization resources and systems are not installed. The check does not read
translation files, invoke loaders or compare FTL contents.
To handle the typed error before calling Bevy registration:
use bevy_fluent_typed::{LocalizationPlugin, LocalizationRegistrationError};
fn install_localization(app: &mut App) -> Result<(), LocalizationRegistrationError> {
let plugin = LocalizationPlugin::<texts::Translations>::new(texts::manifest());
plugin.validate_registration(app)?;
app.add_plugins(plugin);
Ok(())
}This preliminary check does not reserve the catalog; add_plugins checks again.
The error exposes the catalog’s TypeId and readable name, its leaf paths, both
plugin types and constructor locations. Distinct root Rust types remain independent
namespaces, even when their leaf paths match. Declare translations! once for a
shared catalog and import or re-export that module: separate declarations create
separate types rather than a shared provider.
§Automatic module lifetime
Insert a binding and let the plugin manage its scope:
commands.spawn((
Text::default(),
Localized::<Text, texts::presentation::Hud>::new(|hud| hud.msg_title()),
));In Lazy, every inserted Localized<Text, Scope> requests and retains its scope.
Removing the last binding releases that demand. Other bindings, native resource
consumers on 0.19/0.20 and helper-registered consumers on 0.16–0.18 keep
overlapping scopes loaded. No explicit screen-entry or screen-exit loading calls
are needed for bound text.
On Bevy 0.19/0.20, register ordinary Res<Scope> consumers with
app.add_systems. The plugin discovers their catalog reads when Bevy initializes
the schedule and waits for readiness. Recurring systems retain ownership while
their system state exists, including when run_if is false; a condition controls
execution, not module lifetime. Remove the owning schedule or use entity-bound
text for lifetime that follows a screen’s entities. Catalog reads in run conditions
also establish demand.
With default Deferred startup, each startup consumer releases temporary demand after it finishes and deferred commands apply. Inserted bindings take over their own demand before unneeded modules are released. A one-time read does not keep the catalog loaded afterward. Older backends use explicit registration helpers for automatic demand and readiness of direct readers.
Standalone messages and World::get_resource inspection neither request nor
retain a module. For an application that polls the complete language directly,
select LocalizationPlugin::<texts::Translations, Full>::new(manifest) and use
the matching Localization<texts::Translations, Full> controller type.
After the last consumer, manual pin and lease disappear, the plugin releases parsed
snapshots and strong asset handles at synchronization. Bevy may retire assets
on later updates. Application-owned clones may keep parsed data alive; embedded
static bytes and buffers passed to from_bytes have their own source lifetime.
§Optional manual retention
Most text and resource consumers need no additional calls. To preload a scope or keep it available independently of consumers, use the same Lazy controller:
// In a system with ResMut<Localization<texts::Translations>>:
localization.load::<texts::presentation::Hud>();
// When that extra retention is no longer needed:
localization.unload::<texts::presentation::Hud>();load creates an idempotent manual pin per scope type. Two loads followed by one
unload remove that pin; automatic consumers and other overlapping pins still
retain their leaves. unload cannot evict a scope used by a binding or localized
system or held lease. Pins persist across language changes. hold::<Scope>()
adds independent owners in Lazy or Manual when needed; see the manual ownership
recipe. Explicit Manual uses these manual APIs without
automatic consumers; Full always requests the complete language.
The following examples add a pause screen and Spanish. Keep the quickstart’s manifest and English HUD; add these files:
assets/localizations/translations/en/screens/pause.ftl:
title = Pausedassets/localizations/translations/es/presentation/hud.ftl:
title = Listoassets/localizations/translations/es/screens/pause.ftl:
title = En pausaAll languages have the same module/message contract. Rebuild to generate the
new texts::screens::Pause type and texts::Locale::Es variant.
§Manual loading
Use this advanced recipe only when the application owns explicit requests.
Keep the quickstart’s imports, translations! declaration and show_title.
Unlike Lazy, Manual does not let bindings or native resource consumers request modules.
Add the Manual controller types:
use bevy_fluent_typed::{Manual, Localization};
type AppLocalization = Localization<texts::Translations, Manual>;Replace main with this version:
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(bevy::asset::AssetPlugin {
file_path: ".".into(),
..default()
}))
.add_plugins(LocalizationPlugin::<texts::Translations, Manual>::new(texts::manifest()))
.add_systems(Startup, (request_hud, show_title).chain())
.run();
}Add the explicit HUD request:
fn request_hud(mut localization: ResMut<AppLocalization>) {
localization.load::<texts::presentation::Hud>();
}This requests the HUD and prints Ready once it arrives. The pause module is
not requested, read or parsed. The request stays active until you unload it.
LocalizationPlugin::<texts::Translations>::new_manual(texts::manifest()) returns
the same plugin type. All three modes use the same Res<texts::presentation::Hud>.
With a file-backed manifest, load::<Scope>() starts the requested Bevy asset
loads at synchronization. The AssetLoader reads and parses each module during
that load, then the plugin publishes its typed resource. All modes use
Bevy’s asynchronous loading; Manual lets the application choose which scopes to
request and retain. No additional parsing is deferred until accessor use.
Use the same 0.5.0 facade in both normal and build dependencies for this recipe.
Then embed only the HUD by declaring its source next to translations!:
texts::embed_manifest! {
const HUD = presentation::Hud;
}Pass HUD in place of texts::manifest() and keep the request.
Embedding selects raw bytes in the binary; Manual requests select what gets parsed.
Use const ALL = Translations; and pass ALL to include the pause screen too.
The existing expression form texts::embed_manifest!() also includes the whole tree.
§Export an embedded source from a private module
The source constant has type LocalizationManifest. Export it alongside ordinary
catalog aliases; the generated module can stay private:
mod localization {
bevy_fluent_typed::translations!(mod texts);
pub use texts::presentation::Hud as Interface;
pub use texts::Translations;
texts::embed_manifest! {
pub const HUD = presentation::Hud;
}
}Consumers use the exported types and constant directly:
use localization::{HUD, Interface, Translations};
// During plugin setup:
app.add_plugins(LocalizationPlugin::<Translations>::new(HUD));Insert Localized<Text, Interface> or register a Res<Interface> consumer with
add_systems on Bevy 0.19/0.20; Lazy requests its scope without manual calls.
Interface names the catalog resource; HUD describes its embedded source.
The macro’s selectors always use the original relative schema names. Multiple
constants, visibility and per-declaration #[cfg(...)] attributes are supported.
A constant includes bytes but does not parse a Fluent catalog. Source bytes stay
static after their last consumer disappears; parsed catalogs follow the usual resource lifetime.
§Load and release a screen
In the same Manual application, call these systems when the pause screen opens and
closes. For example, register them in your state’s OnEnter and OnExit
schedules; do not register both unconditionally in Update:
fn open_pause(mut localization: ResMut<AppLocalization>) {
localization.load::<texts::screens::Pause>();
}
fn close_pause(mut localization: ResMut<AppLocalization>) {
localization.unload::<texts::screens::Pause>();
}Keep the HUD’s request while the game uses it. This gives hybrid loading. Release
that request with unload::<texts::presentation::Hud>() when its owner exits too.
Requests are idempotent per scope type, not reference-counted calls. Two
load::<Hud>() calls followed by one unload::<Hud>() release that request.
Independent parent/child requests do overlap:
localization.load::<texts::Presentation>();
localization.load::<texts::presentation::Hud>();
localization.unload::<texts::Presentation>(); // The explicit Hud request remains.
localization.unload::<texts::presentation::Hud>(); // Now it can be released.For independent owners or preloading, Lazy and Manual both support a
ModuleLease<Scope> returned by hold. This Manual example keeps screen entry/exit
under application control:
use bevy_fluent_typed::ModuleLease;
fn open_pause(mut commands: Commands, mut localization: ResMut<AppLocalization>) {
let lease: ModuleLease<texts::screens::Pause> =
localization.hold::<texts::screens::Pause>();
commands.spawn(lease); // Despawning this owner releases its demand.
}Continue consuming ready translations through native Res<Scope> and ordinary
system registration below. Each hold creates an independent owner, including
repeated holds of the same scope; overlapping groups and leaves share loading.
Dropping a token on any thread releases only its owner’s demand at the next
publication boundary. Explicit load requests survive token drops, and unload
releases only the explicit request, leaving automatic consumers and other leases
active. Dropping before the first publication starts
no I/O. Tokens retain demand across language changes and do not keep a removed
controller alive. They cannot be cloned; an application may share one token
through Arc, releasing it when the last clone drops. Lazy bindings and
native required-resource systems on Bevy 0.19/0.20 own scopes automatically; they do not need
application-held lease tokens. Explicit Manual remains manual. Failed attempts
retry through set_locale, load or ReloadCatalogs; acquiring another lease
does not retry a failed attempt.
load::<texts::Translations>() requests the whole tree. It removes the memory
benefit of partial loading while that request remains active. Subdivide very
large translations into useful FTL files: a leaf is parsed and retained as a
whole, not one message at a time.
After the last automatic consumer, explicit request or lease is released, the plugin drops its scope snapshots and strong asset handles at synchronization. Bevy may retire assets over later updates. Application-owned clones can keep data alive, and explicitly embedded static bytes always remain in the executable. There is no language cache or implicit fallback.
§Read resources and handle readiness
On Bevy 0.19/0.20, use ordinary system registration and native Res<Scope>:
fn update_hud(hud: Res<texts::presentation::Hud>) {
println!("{}", hud.msg_title());
}
app.add_systems(Update, update_hud);The plugin discovers registered catalog reads from Bevy’s scheduler metadata,
including aliases, nested parameters, derived SystemParams and ParamSet.
Each system waits for its own catalogs without blocking the frame. A parent
waits for all descendants; a HUD leaf does not wait for its siblings. During a
locale switch, consumers keep using active resources until the target publishes.
In Lazy, recurring consumers retain scopes even when their run_if is false.
Manual still requires explicit pins or leases; Full keeps the whole language loaded.
Missing non-catalog resources and application errors retain native Bevy behavior.
Apply normal Bevy configuration directly; original function ordering remains valid:
app.add_systems(Update, update_hud.run_if(screen_is_open));
app.add_systems(Update, (update_title, update_buttons).chain());Install localization plugins before a schedule’s first initialization. New systems
added later are discovered on subsequent App updates. Register custom schedules
before an App::update discovers them and before their first manual execution;
direct World::run_schedule before App discovery bypasses this setup. Systems
initialized before discovery retain their previous behavior. OnEnter and other
one-shot custom schedules do not retry readiness waits: load ahead of time or
move the consumer to a recurring loading/ready phase. Broad &World inspection
is passive and does not request every catalog.
For an observer that must run while a catalog is absent, Bevy 0.19/0.20 provides
Option<PassiveCatalog<Scope>>: it returns None without requesting, retaining or
waiting for a module. A plain Option<Res<Scope>> has the same scheduler metadata
as required Res and is conservatively treated as a consumer. This distinction
applies to automatic discovery, including run conditions.
PassiveCatalog accepts only FluentScope types; after matching Some(scope),
its Deref exposes the catalog methods directly.
§Startup strategies
Default Deferred preserves startup phases and declared dependencies:
app.add_systems(Startup, (setup_hud, finish_setup).chain());
fn setup_hud(mut commands: Commands, hud: Res<texts::presentation::Hud>) {
commands.spawn(Text::new(hud.msg_title()));
}Independent steps execute once. Catalog consumers wait; steps ordered after them
wait too. PostStartup follows completed Startup. A completed or normally
condition-skipped step does not rerun. Temporary demand is released after deferred
commands apply, including when the function returns an error. Use Localized
for text that must follow later language changes.
Frame schedules keep running while startup waits so Bevy can load assets.
Guard ordinary frame systems that require application resources created by
unfinished startup steps. Only catalog readiness is deferred automatically.
Put asset-source/bootstrap setup before consumers: a PreStartup catalog consumer
cannot wait for a loader that the application starts only in a later startup phase.
Failed loads remain observable through status and wait until explicitly retried.
Startup policy belongs to the whole App and is configured through
LocalizationStartupPlugin. Localization source plugins inherit that policy.
Select Native to preserve ordinary one-shot startup:
use bevy_fluent_typed::{LocalizationStartupPlugin, StartupStrategy};
app.add_plugins(LocalizationStartupPlugin::new(StartupStrategy::Native));Native preserves ordinary one-shot startup and native missing-resource validation. Startup catalog reads do not request or wait automatically in this policy; use already-ready catalogs or create bindings without reading one. Recurring consumers and inserted bindings remain automatic in Lazy.
Register the startup plugin before or after LocalizationPlugin, before the
first App update. If absent, LocalizationPlugin adds an implicit Deferred
fallback. An explicit startup plugin added later selects the policy without
installing a second coordinator or executing startup twice.
Alternatively, Barrier waits for the selected set’s combined catalog requirements:
#[derive(SystemSet, Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct AppStartup;
app.add_plugins(LocalizationStartupPlugin::barrier(AppStartup));
app.add_systems(Startup, (setup_hud, setup_buttons).in_set(AppStartup));Startup outside the set may proceed while its catalogs load, subject to ordinary
ordering. Use LocalizationStartupPlugin::barrier to select the set; passing
StartupStrategy::Barrier to LocalizationStartupPlugin::new is rejected.
Loading mode and startup strategy are independent: a Manual barrier still needs
application-owned requests.
All roots share the explicit choice regardless of registration order. Without an explicit choice, the App uses Deferred. Matching explicit startup plugins are accepted; contradictory choices and changes after startup begins are rejected.
§Older Bevy backends
Bevy 0.16–0.18 provide LocalizationAppExt, localized and
IntoLocalizedSystems exclusively for those backends. Their implementation and
exports are not compiled on 0.19/0.20 or in build-only configurations.
use bevy_fluent_typed::{LocalizationAppExt, localized};
app.add_localized_systems(Update, update_hud);
app.add_systems(Update, localized(update_buttons).run_if(screen_is_open));
app.add_localized_startup_systems(setup_hud);In Lazy, each helper-registered direct required Res<Scope> requests and retains
its scope. A recurring consumer retains demand while its system state exists,
even with a false application condition. Each tuple member waits independently.
Plain Option<Res<Scope>> remains passive. Aliases of a direct required resource
work; derived SystemParams, nested tuples and ParamSet are not inspected.
Expose each required catalog as a direct parameter when using these helpers.
Install the localization plugin before initializing the schedule.
The one-time helper runs each function once in Update after its catalogs are ready. It does not defer native Startup phases or preserve ordering references to the original function. Combine dependent setup steps into one function or own their initialization state explicitly. Completion releases the helper’s demand; inserted text bindings take over before unused modules are released. Manual still needs explicit requests; Full keeps the selected language loaded.
Ordinary add_systems does not gain resource discovery on these older backends.
For application-owned loading through Full, pins or leases, native
resource_exists::<Scope> remains available as a readiness condition. Native
Startup, OnEnter and custom one-shot schedules do not retry skipped consumers.
Localized owns its scope automatically in Lazy on every backend. Startup
strategies and PassiveCatalog remain exclusive to Bevy 0.19/0.20.
Localization::new(locale) and Default create a controller, not a ready catalog.
Use status::<Scope>() to distinguish Unloaded, Loading, Ready and
Failed(error). A separate observer can report load errors while required systems
wait. An invalid same-language reload preserves the last good value, so its
consumers can run while the latest attempt has status Failed. Send
ReloadCatalogs to retry requested leaves. Repeating load::<Scope>() in Lazy
or Manual also retries failed active and prepared leaves while keeping its manual
pin. Repeating set_locale retries failures in that requested language without
pinning scopes or reloading already-ready active leaves.
§Observe loading progress
One root progress plugin provides native views for the entire registered tree:
use bevy_fluent_typed::LocalizationProgressPlugin;
app.add_plugins(LocalizationProgressPlugin::<texts::Translations>::new());This includes LocalizationProgress<texts::presentation::Hud> automatically;
no separate HUD registration is needed. To observe only a group’s subtree instead,
use LocalizationProgressPlugin::<texts::Presentation>::new(). It includes
that group and its registered descendants, excluding ancestors and siblings.
A leaf plugin observes only that leaf. Consumer plugins may register overlapping
subtrees in separate calls; repeats are idempotent and share one provider dispatcher.
During App setup, either order relative to the owning LocalizationPlugin works.
Lazy/Full/Manual is inferred from that base plugin; no Cargo progress feature is required.
Selected scopes get native resources before Startup once the base plugin is
installed. Registration snapshots any active/prepared state already present
during setup; compose these plugins before the App is finished. Read a typed view
from an existing UI system, or gate a dedicated observer on visible changes:
use bevy::ecs::schedule::common_conditions::resource_changed;
use bevy_fluent_typed::LocalizationProgress;
fn loading_ui(progress: Res<LocalizationProgress<texts::presentation::Hud>>) {
let active = progress.active();
println!("{}: {}/{} ready", active.locale, active.ready, active.total);
if let Some(target) = progress.preparation() {
println!("target {}: {}/{} ready", target.locale, target.ready, target.total);
}
}
app.add_systems(
PostUpdate,
loading_ui
.run_if(resource_changed::<LocalizationProgress<texts::presentation::Hud>>)
.after(bevy_fluent_typed::LocalizationSystems::Progress),
);Without a progress plugin, there is no native progress resource, no recurring
tracker and no tracking identity or revision updates. Ordinary loading and
status continue normally. The progress plugin creates neither logging nor a loading UI;
presentation belongs to the application. active() covers ordinary initial loading,
set_locale and same-language reloads. preparation() is present during an
automatic language switch or explicit prepare_locale, until cancellation or
publication. Preparing the active locale mirrors
its active data without additional I/O.
The root view counts the current demand union: Lazy includes automatic consumers,
manual pins and leases; Manual includes manual pins and leases; Full counts the
whole root. Group and
leaf views count their fixed, deduplicated schema paths, including unrequested
leaves. Overlapping owners do not inflate the total. Progress plugins and resource
reads create no loading requests or leases and do not retain parsed catalogs.
Each LoadingProgress<Locale> contains locale, total, ready,
loading, failed, unloaded and available. The four attempt counts sum to
total; available separately counts usable last-good snapshots, including
during a loading or failed reload. These are module counts, not downloaded bytes
or a percentage of elapsed work.
active() and preparation() counters describe the observed scope, but
preparation_status() is provider-wide because locale commit applies to the
whole provider’s demand. A ready HUD does not mean other requested leaves are
ready; conversely, an unrequested observed scope can remain unloaded while the
provider reports PreparationStatus::Ready. Check that provider-wide status
before asking the live controller to commit_locale. Scoped ready == total is
insufficient; retries or asset-handle retirement can also prevent a commit.
set_locale switches automatically when the provider is ready; explicit
prepare_locale leaves publication to the application through commit_locale.
Reading a snapshot never initiates a commit. Manual preparation failures appear
through PreparationStatus::Failed without precommit Rejected notifications;
automatic target failures emit Rejected for that target. Active translations
remain usable throughout preparation.
The tracker runs after PreUpdate publication and after PostUpdate text refresh,
in LocalizationSystems::Progress. Read fresh snapshots in Update, or order a
PostUpdate observer after that progress boundary as shown above. Use
resource_changed to update a loading UI only when visible progress changes;
settled frames preserve its change tick. Several transitions between observations
may coalesce: this is the latest snapshot, not a history of messages. Use
CatalogUpdateReader when you need accepted/rejected load notifications.
For passive counts of another scope, localization.progress::<Scope>() and
ModuleStore::progress::<Scope>() include all unique schema leaves of that scope,
including unrequested leaves. localization.preparation_progress::<Scope>()
returns target counts when preparation exists. These on-demand queries create
no demand, enable no recurring tracking and require no optional feature.
See the generated progress example for a bounded headless runner, explicit prepare/commit and a change-gated observer.
§Optional module details
Enable the default-off diagnostics feature only when you need individual
module paths, attempt errors or snapshot availability:
bevy_fluent_typed = { version = "0.5.0", features = ["codegen", "diagnostics"] }Keep the build dependency unchanged. During explicit inspection:
let modules = localization.diagnostics::<texts::presentation::Hud>();
let target_modules = localization.preparation_diagnostics::<texts::presentation::Hud>();diagnostics::<Scope>() is also available on ModuleStore. Each call collects
sorted ModuleDiagnostic values with path, status and usable, including
unrequested schema leaves; target inspection returns None without preparation.
The queries neither request nor retain parsed catalogs. Detailed lists and their
error copies are collected only when requested, never by the registered progress
publisher, even with the feature enabled. Counter scans borrow attempt states.
Typed PreparationStatus::Failed still retains the first target failure for commit
readiness. The diagnostics feature does not activate native tracking; use
LocalizationProgressPlugin<Scope> when a native view is needed. Counters and typed
preparation readiness require no optional feature. Details add no dependencies
and start no logging.
§Navigate from the root or a parent
The controller’s views work with a partially loaded tree:
fn inspect(localization: Res<AppLocalization>) {
let presentation = localization.modules().presentation();
if let Ok(hud) = presentation.hud() {
println!("{}", hud.msg_title());
}
}Group methods return another view. Leaf methods return Result<&Leaf, ModuleError> with the locale, logical module path and loading status. Views do
not load anything. A leaf borrow belongs to the controller’s store, so a chained
call such as localization.modules().presentation().hud() is also valid.
With a complete scope resource, ordinary accessors return direct references:
fn inspect_complete(presentation: Res<texts::Presentation>) {
let hud = presentation.hud();
println!("{}", hud.msg_title());
}Register that system with app.add_systems(Update, inspect_complete) on Bevy 0.19/0.20.
localization.catalog() returns Option<&texts::Translations>; it is normally
None in an application that intentionally leaves some modules unloaded.
§Bind text without keeping an old translation
A Localized<Text, Scope> component stores a closure. The plugin renders it using
the current resource and updates the selected target when the language, module
or message changes. Select Text, Text2d or TextSpan explicitly:
use bevy_fluent_typed::Localized;
fn spawn_title(mut commands: Commands) {
commands.spawn((
Text::default(),
Localized::<Text, texts::presentation::Hud>::new(|hud| hud.msg_title()),
));
}Register spawn_title in Startup; it is safe to create a binding before its
module loads. In Lazy, insertion requests the HUD and removal releases that
binding’s demand. Your application owns the usual Bevy UI/camera/font setup.
Missing or unloaded resources clear bound text, and it
refreshes when the resource becomes available. Bind to the smallest scope the
message uses: a Localized<Text, Translations> would wait for the entire tree.
Bindings can be cloned and used in native Bevy 0.19/0.20 scenes; see the
BSN recipe for the syntax of each backend and child text spans.
Use Localized<TextSpan, Scope> for spans and Localized<Text2d, Scope> for world
labels. Supply the target component alongside its binding; Default is not
required and no target is created automatically. If the target is missing when
the deferred add callback runs, the binding is removed with a warning. Supplied
components keep their settings. See target bindings.
A span binding owns its scope just like a root binding in Lazy. Its parent
Text/Text2d, hierarchy and styles belong to the application; refreshing a
span does not insert a root Text. All three targets keep their active-language
content while a new locale loads or fails validation.
For stored notices, use Msg<Scope> and render only when its scope is ready.
A stored message does not establish demand until inserted as a Localized
binding; render it in a native required-resource system on Bevy 0.19/0.20 when needed:
use bevy_fluent_typed::Msg;
let message = Msg::new(|hud: &texts::presentation::Hud| hud.msg_title());
// Or: Msg::<texts::presentation::Hud>::new(|hud| hud.msg_title())
if let Ok(hud) = localization.modules().presentation().hud() {
let text = message.render(hud);
}Capture owned message arguments, not a translated string or an old module
snapshot. Replace the binding when captured values change. Editable text drafts
should use separate components: localization replaces bound text. Number
formatting stays application-owned; see the ICU4X example.
The complete Msg update rules
separate formatter invalidation, cached target repair and application-owned snapshots.
The provider defaults to CachePolicy::Rendered. Use
.with_cache_policy(CachePolicy::None) to retain tracking metadata without an
additional formatted-output cache; see cache policies
for native repair, custom-adapter costs and paired accessibility handling.
§Change language and reload files
For the quickstart’s locales, use the matching default controller alias:
use bevy_fluent_typed::Localization;
type AppLocalization = Localization<texts::Translations>;Then select Spanish:
fn select_spanish(mut localization: ResMut<AppLocalization>) {
localization.set_locale(texts::Locale::Es);
}Call it from your language-selection action. The plugin loads and validates the
currently needed scopes in Spanish while locale(), native resources, controller
views and bound text keep using the active language. When all target leaves are
ready, it automatically publishes them together at the next PreUpdate
LocalizationSystems::Publish boundary. Text refreshes in PostUpdate. No separate
commit_locale() call is needed. Consumers added or removed during acquisition
update the target demand as well.
prepared_locale() reports the pending target; preparation_status() reports
Preparing, Ready, Failed(error) or Idle. A failed target leaves the active
language usable and emits CatalogUpdate::Rejected with the target locale. It
is not retried every frame. Repeat set_locale(target), retry a failed requested
scope with load::<Scope>(), or send ReloadCatalogs after correcting the source.
The latest requested language wins; selecting the active language cancels a
pending target and retries only failed active leaves, without adding manual pins
or reloading ready leaves. Repeating a pending target does not duplicate loads.
For a different initial language, insert AppLocalization::new(texts::Locale::Es)
before installing the plugin. Selecting a locale before the first app update
also chooses only that initial language. Otherwise the manifest default is used.
No implicit fallback locale or retained locale cache is introduced.
§Advanced: prepare and choose the publication time
Use explicit preparation only when the application must decide when a validated target becomes active, for example at a transition boundary:
use bevy_fluent_typed::PreparationStatus;
localization.prepare_locale(texts::Locale::Es);
// In a later update, publish only when the application is also ready to switch:
if let PreparationStatus::Ready = localization.preparation_status() {
localization.commit_locale()?;
}prepare_locale takes over manual control, including for a target already
requested with set_locale: it stops automatic switching. Preparation follows
current automatic consumers, manual pins and leases in Lazy, pins and leases in
Manual, or the whole language in Full, using the existing source and checked parsers.
Target leaves do not replace active native resources or following bindings until
commit. Ready target scopes can already be read through for_locale; independent
fixed-language consumers can use that language while preparation is pending.
commit_locale() returns
CommitLocaleError::NotPrepared, Pending or Failed(ModuleError) until every
requested target leaf passes its latest attempt. A retained earlier good target
snapshot does not satisfy a failed retry. Success queues the coordinated swap
for the next PreUpdate Publish boundary; committed leaves emit Loaded.
Manual preparation failures remain available through preparation_status();
they do not emit Rejected. Automatic set_locale failures emit Rejected
for their target before switching.
Repeating prepare_locale keeps successful leaves and retries failures; a
different target replaces it. Changing the required leaf union, or explicitly
retrying leaves, revokes a queued manual commit. Poll readiness and commit again.
Publication rechecks source readiness. Automatic set_locale intent instead
continues through demand changes and explicit retries, and commits when ready.
cancel_preparation() cancels both manual preparation and pending automatic
switching, releasing target snapshots and tasks/handles that no independent
fixed-language consumer still needs. Fixed-language pins, leases and bindings
keep their own demand and ready snapshots. External I/O may finish later, but
canceled attempts cannot replace the active language. Preparing the
active locale is immediately ready and performs no additional I/O. An empty
Lazy/Manual demand also needs no module acquisition.
Preparation retains active and target parsed leaves until cancellation or commit.
Application-owned clones and source buffers retain their usual lifetime. File
sources use Bevy’s AssetReader and AssetLoader with private preparation assets
and per-attempt identities. A retry may wait asynchronously for obsolete handles
to retire; uncancelable readers or another owner retaining a handle may delay
readiness. Active consumers keep running. Source metadata must allow Bevy to
select the requested asset type; .meta files selecting another loader cause
preparation to fail. Remove that override or configure the source’s metadata
policy. Watching and ReloadCatalogs continue after commit. Preparation does not
snapshot a changing archive or order overlapping external reloads; keep the
source coherent, as described below.
To retry all requested FTL files on Bevy 0.17–0.20:
use bevy_fluent_typed::ReloadCatalogs;
fn reload(mut requests: MessageWriter<ReloadCatalogs<texts::Translations>>) {
requests.write(ReloadCatalogs::default());
}Register this on your reload action, not every frame. Bevy 0.16 uses EventWriter
and send. The request works without filesystem watching and can recover from
initially missing files. It does not reread TOML: the manifest remains the
contract you passed to the plugin.
To watch files automatically, enable the runtime’s watch feature on the normal
dependency and set AssetPlugin::watch_for_changes_override to Some(true).
The selected asset source must support watching. Compatible prose edits can load
without recompiling; changing the schema requires rebuilding the application.
For load diagnostics, use CatalogUpdateReader<texts::Translations> and iterate
.read(). CatalogUpdate::Loaded { locale, path } identifies an accepted module;
Rejected { locale, path, error } reports a failed attempt. In PreUpdate, order
the observer after LocalizationSystems::Publish. Error presentation belongs to
the application.
§Scheduling and reload guarantees
Publication runs in PreUpdate’s LocalizationSystems::Publish, then again in
PostUpdate before LocalizationSystems::Refresh, where text bindings refresh.
set_locale prepares the target while leaving the active controller locale and
resources usable. A ready target switches at PreUpdate Publish, then bindings
refresh in PostUpdate. Consumers that need the refreshed text in that frame
should run after LocalizationSystems::Refresh.
Checked leaves publish independently. A bad same-language reload keeps that
leaf’s last good value; valid siblings can still change. Ordinary same-language
reloads have no multi-file transaction. Locale replacement commits its currently
requested target leaves together after validation, automatically with set_locale
or at the application’s chosen time with prepare_locale/commit_locale.
Successful reloads publish fresh snapshots even if text is identical;
idle frames and unchanged siblings preserve resource identity and change ticks.
The plugin serializes its own reload requests per module and coalesces pending
retries. Watcher reloads and direct AssetServer::reload calls bypass that queue.
Bevy exposes no request generation before opening the reader or in a failure
event, so overlapping external reloads cannot always be ordered by request time.
If strict order matters, disable automatic watching and send ReloadCatalogs;
a custom reader must supply coherent data as well.
§Custom byte sources
For on-demand reading and unloading, use Lazy
with Bevy’s asset system, or manual loading. Custom asset sources let the
application supply transport, decompression and caching through an AssetReader.
from_bytes is for data the application has already obtained and intends to keep
in memory. The plugin retains all supplied buffers for later loads and language
changes. In Lazy, only parsing and resource creation wait for consumers;
removing consumers releases unneeded parsed resources, but retains input buffers.
Explicit Manual follows manual requests with the same buffer lifetime.
Keep codegen, build.rs and translations!. Generated accessors work with
these buffers too; only the plugin constructor changes. This path needs
MinimalPlugins or DefaultPlugins, without AssetPlugin.
For the guide’s two English modules, read both files and keep the default Lazy:
let hud = std::fs::read("assets/localizations/translations/en/presentation/hud.ftl")?;
let pause = std::fs::read("assets/localizations/translations/en/screens/pause.ftl")?;
let plugin = LocalizationPlugin::<texts::Translations>::from_bytes([
(texts::Locale::En, texts::presentation::Hud::PATH, hud),
(texts::Locale::En, texts::screens::Pause::PATH, pause),
])?;
app.add_plugins(plugin);Inserted bindings on every backend, native Res consumers on Bevy 0.19/0.20
and helper-registered readers on 0.16–0.18 request only the modules they need;
no explicit load call is needed. Supply Spanish buffers too if the application
will switch to Spanish.
from_bytes accepts (locale, leaf path, bytes) tuples, checks their keys
immediately, and validates FTL when a module is parsed. A missing buffer becomes
ModuleStatus::Failed when requested. The provider’s default locale is selected
initially, unless a Localization<C> resource was inserted before the plugin.
For a runnable complete example, see generated bytes:
cargo run --manifest-path examples/codegen/Cargo.toml --bin bytesFor asynchronous acquisition outside Bevy’s asset system, use from_loader.
The callback receives (locale, leaf path) and returns a result convertible
through Into<Vec<u8>>. A fresh Vec<u8> or String transfers its allocation;
a slice is copied once. Generated parsers pass the owned buffer into Fluent
without another full-source copy. Handwritten Module::new parsers receive
Vec<u8> and can transfer it to their own parser or borrow it locally.
from_bytes retains shared source bytes for reuse and supplies an owned copy
when parsing. Application captures and caches can also retain data. Loader
callbacks and parsers run on Bevy’s I/O task pool; futures must be nonblocking
and any required executor integration is owned by the application. Reload
notifications and explicit retries use the same callback. This path has no
AssetServer file watching; send ReloadCatalogs after source changes.
See LocalizationPlugin::from_loader for cancellation, scheduling and reload
guarantees.
§Without code generation
This is an advanced integration for applications supplying their own provider. Most applications should keep the generated API above, including when they provide their own bytes.
For Bevy 0.20, the minimal dependency is:
[dependencies]
bevy_fluent_typed = { version = "0.5.0", default-features = false, features = ["bevy-0-20"] }There is no build-dependency, build.rs, translations!, TOML manifest or
fluent_typed_codegen dependency in this configuration. Implement FluentCatalog
and FluentScope, register checked leaf parsers through Module::new, and pass
bytes with from_bytes or from_loader. The application owns the locale/module
schema, accessor API and validation. Bytes alone cannot create typed Rust methods.
The plugin still manages automatic consumers or explicit Full/Manual requests,
typed resources, readiness, bindings, language changes, retries and unloading.
Follow the complete handwritten example for these
implementations. Add manifest if that provider needs the existing manifest/file
constructors. manifest is enabled by default and by codegen; it uses the
generator package’s small runtime manifest API, without enabling generation.
See the feature table for host/target separation.
For advanced handwritten providers with groups, declare the immediate parent in each child descriptor:
ScopeRegistration::new::<Hud>().with_parent::<Presentation>()The parent must share the child’s FluentScope::Catalog. Descriptors without a
parent are direct children of the catalog root; root observation includes every
registered descriptor, including existing providers without parent metadata.
Generated Bevy providers emit these relationships automatically from their accessor
hierarchy. The one-file handwritten example needs no parent boilerplate.
§Headless application
For a console-only example, use MinimalPlugins, AssetPlugin and a repeating
runner. Build src/main.rs from these three blocks; the application prints
Ready and exits, or returns an error if the HUD cannot load.
The imports and generated module:
use bevy::{
app::{AppExit, ScheduleRunnerPlugin},
prelude::*,
};
use bevy_fluent_typed::{
Localization, LocalizationPlugin, ModuleStatus,
};
use std::{path::Path, time::Duration};
bevy_fluent_typed::translations!(mod texts);The console event loop and asset root:
fn main() -> AppExit {
let assets = Path::new(env!("CARGO_MANIFEST_DIR"));
App::new()
.add_plugins((
MinimalPlugins.set(ScheduleRunnerPlugin::run_loop(Duration::from_millis(16))),
AssetPlugin {
file_path: assets.to_string_lossy().into_owned(),
..default()
},
LocalizationPlugin::<texts::Translations>::new(texts::manifest()),
))
.add_systems(Startup, show_title)
.add_systems(Update, report_failure)
.run()
}The output and failure handling:
fn show_title(
hud: Res<texts::presentation::Hud>,
mut exit: MessageWriter<AppExit>,
) {
println!("{}", hud.msg_title());
exit.write(AppExit::Success);
}
fn report_failure(
localization: Res<Localization<texts::Translations>>,
mut exit: MessageWriter<AppExit>,
) {
if let ModuleStatus::Failed(error) = localization.status::<texts::presentation::Hud>() {
eprintln!("{error}");
exit.write(AppExit::error());
}
}The absolute asset root here makes this standalone console executable runnable from another working directory. A normal Bevy application uses its existing asset configuration and event loop, as in the quickstart.
§Migration from registry 0.1.3
Follow the migration guide to 0.5.0 for dependency updates, before/after initialization, readiness handling, optional Manual adoption and handwritten providers. The standard upgrade uses Lazy with inserted bindings and native resource systems; choose explicit Full to preserve eager loading or direct world polling.
§Compile-time mode boundaries
Lazy, Full and Manual implement the sealed LoadingMode trait. Explicit
requests and independent leases are available on Lazy and Manual. The compiler
rejects requests on Full and scopes
belonging to another root:
use bevy_fluent_typed::{FluentCatalog, Full, Localization};
fn request<C: FluentCatalog>(state: &mut Localization<C, Full>) {
state.load::<C>();
}use bevy_fluent_typed::{FluentCatalog, Full, Localization};
fn hold<C: FluentCatalog>(state: &mut Localization<C, Full>) {
let _lease = state.hold::<C>();
}use bevy_fluent_typed::{FluentCatalog, Full, Localization};
fn release<C: FluentCatalog>(state: &mut Localization<C, Full>) {
state.unload::<C>();
}use bevy_fluent_typed::{FluentCatalog, FluentScope, Manual, Localization};
fn wrong_root<C: FluentCatalog, S: FluentScope>(state: &mut Localization<C, Manual>) {
state.load::<S>(); // S::Catalog must be C.
}use bevy_fluent_typed::LoadingMode;
struct Other;
impl LoadingMode for Other { const FULL: bool = false; }§More recipes
- Custom sources: supply files through your own reader.
- Decimal and percentage arguments: reuse ICU4X formatters.
- Build API: explicit generation and feature selection.
§Custom components and semantic labels
See application-defined bindings
for Localized<Target, Scope> on custom components and their String fields.
Bindings retain scope demand by entity presence in Lazy, without registration
or a user refresh system. The same interface
updates immutable AccessibleLabel on Bevy 0.19/0.20 after UI accessibility producers.
§Custom asset sources
The quickstart uses texts::manifest() for the file-source contract prepared by
the build configuration. To keep the same schema with different runtime storage,
construct the contract explicitly as below. The generated helper retains the
build-time CATALOG_PATH; it does not infer a Bevy source root. In the explicit
contract below, the application supplies a Bevy asset address as the origin;
AssetPlugin owns the asset root. LocalizationManifest::from_file(path) instead
reads TOML through the native filesystem, so its origin is not automatically a
Bevy-relative address.
The manifest is a prepared contract, not a catalog or live TOML asset. Register
an application’s AssetReader before AssetPlugin, then preserve its named source
in the origin:
use bevy_fluent_typed::{LocalizationManifest, LocalizationPlugin};
let manifest = LocalizationManifest::parse(
texts::CATALOG_CONFIG,
"translations://localizations/localization.toml",
)?;
app.add_plugins(LocalizationPlugin::<texts::Translations>::new(manifest));For directory translations, a request for the quickstart’s English
presentation/hud.ftl reads exactly
translations://localizations/translations/en/presentation/hud.ftl through AssetServer.
The TOML need not exist in that source: parsing has already supplied the contract.
Runtime directory/origin may differ from build inputs. Source/default language
metadata must be compatible with the compiled schema. Paths are validated and
mapped exactly; nested logical paths are never inferred from suffixes.
The source owns transport, decompression, caching and change notifications. Archive support requires an appropriate reader; a source name is not a built-in format selector. Explicit ReloadCatalogs works without watching and only rereads demanded FTL. Keep a coherent source revision while loading several files: schema validation cannot recognize mixed but otherwise valid prose revisions. Same-language reloads publish leaves independently; locale switches publish the currently desired target leaves together after validation. This does not provide a source revision snapshot or implicit embedded rollback.
The memory-source example provides virtual files and tests missing data, rejected edits and recovery. It explicitly embeds sample bytes only to seed its demonstration reader. Downloading, signatures, installations and persistent rollback belong to the app.
The localization retry queue serializes its own requests, but cannot order
independent watcher/direct AssetServer reloads whose reader-opening futures finish
out of order. Bevy supplies no pre-loader request generation. Its
AssetLoadFailedEvent also has no generation, including failures inside
read_to_end. For strict order, disable watching and use ReloadCatalogs. See the
loading boundary.
§Injecting ICU formatters through Bevy resources
Number formatting is application work. Use dedicated ICU4X or ICU services for numbers, percentages, currencies and dates. Neither this runtime nor its generator adds an ICU dependency or a formatting feature.
The ICU example’s formatting module
creates reusable services per catalog locale and captures a shared map in
deferred bindings. The system receives it through Res; closures
select a formatter from the current catalog, preserving language changes without
rebuilding the UI. The complete runnable example
owns the implementation and tests existing Bevy UI/world text.
The example’s dependencies, in addition to the standard generated consumer setup:
[dependencies]
icu_decimal = { version = "2.3", features = ["alloc"] }
icu_experimental = "=0.6.0"
icu_locale_core = "2.3"
icu_provider = { version = "2.3", features = ["sync"] }
writeable = "0.6"PercentFormatter is experimental and pinned only in the example. Its input
is in percent units; the application converts a ratio such as 0.125 to 12.5
once before formatting. ICU supplies the percent symbol and its locale-specific
placement; Fluent receives the complete formatted String. DecimalFormatter and
the percentage formatter reuse the same configured decimal formatting data.
Scaling also shifts visible leading padding, so the example uses ICU Decimal’s
trim_start() after multiplying. In the pinned experimental version, the chosen
Arabic locale yields Arabic-Indic digits but ASCII % with bidi marks, not U+066A.
The example preserves and tests that output; consumers needing U+066A must assess
their ICU version/backend. No manual symbol substitution is implemented.
The generated texts module needs presentation/hud.ftl in EN/ES/RU/AR, with
these English source contracts:
# $value (String) - Locale-formatted damage.
damage = Damage: { $value }
# $value (String) - Complete localized percentage, including symbol and spacing.
chance = Chance: { $value }Call app.insert_resource(NumberFormats::try_new(GroupingStrategy::Auto)?)
once during setup and register spawn_labels in Startup, after configuring
Bevy and LocalizationPlugin. The example’s
main.rs
handles that wiring. Generated types and ICU dependencies belong to the example;
the library’s documentation links to its source rather than embedding it.
Locale switches rerender the existing bindings, selecting a prebuilt formatter;
they do not recreate services. A change to an arbitrary resource is not an
automatic refresh signal. Replacing NumberFormats leaves previously captured
Arcs intact: replace affected bindings when formatting policy or raw values
change. The example has a regression test for that lifecycle. Arbitrary input
scaling/rounding limits remain application policy; the demonstration inputs are
bounded. Arabic string tests do not verify visual RTL layout or font coverage.
§Typed messages in Bevy scenes
Native bsn! scenes accept typed Localized constructors on Bevy 0.19 and
0.20. Use the generated setup
and enable scenes on the application’s Bevy dependency:
[dependencies]
bevy = { version = "0.20", features = ["bevy_scene", "bevy_ui_widgets"] }
bevy_fluent_typed = { version = "0.5.0", features = ["codegen"] }
[build-dependencies]
bevy_fluent_typed = { version = "0.5.0", default-features = false, features = ["build"] }The localization library adds no scene dependency or separate scene feature.
Use the quickstart’s build.rs, manifest and generated texts module. Add
this message to its HUD file:
# $name (String) - Name supplied by the application.
hello = Hello, { $name }!Keep matching messages in every configured language. DefaultPlugins installs
Bevy’s scene plugin. Applications using MinimalPlugins also install
AssetPlugin and bevy::scene::ScenePlugin; the runnable example does this.
§Create a binding inside BSN
Import the usual component constructor and your catalog scope:
use bevy::prelude::*;
use bevy_fluent_typed::Localized;
use texts::presentation::Hud as Interface;Then create the binding directly beneath its text target:
fn spawn_greeting(mut commands: Commands) {
let name = String::from("Ada");
commands.spawn_scene(bsn! {
Text
Localized::<Text, Interface>::new(move |hud| hud.msg_hello(&name))
});
}Register it with .add_systems(Startup, spawn_greeting). The same block works
on 0.19 and 0.20.
The native FromTemplate implementation supplies Bevy’s scene template;
no template(...) callback or default localized message is needed. A scene
that omits its message constructor returns an error rather than an empty binding.
Scene construction needs no ready Res<Interface>. With default Lazy, inserting
the scene’s Localized<Text, Interface> component requests and retains its scope.
Removing the last binding releases its demand unless another consumer, manual
pin or lease still needs the module. Constructing a scene or cloning a binding before
insertion is passive. Explicit Full loads every module; explicit Manual still uses
application-owned load/unload calls.
§Reuse a message or binding
The same from constructor accepts a deferred Msg<Interface> or an existing
Localized<Text, Interface> on both backends. For a stored message:
use bevy_fluent_typed::Msg;
fn spawn_notice(mut commands: Commands) {
let message = Msg::<Interface>::new(|hud| hud.msg_hello("Ada"));
commands.spawn_scene(bsn! {
Text
Localized::<Text, _>::from(message)
});
}The scope is inferred from Msg<Interface>; BSN still needs explicit target
and scope parameters: ::<Text, _>.
When several entities need the same message, keeping a separate Msg and
cloning it can be convenient. You can construct each Localized where it is
attached. For a binding prepared before the macro, use
Localized::<Text, Interface>::from(binding).
Bevy 0.20 also accepts a component variable directly, such as Text binding;
on 0.19 use the typed constructor above. Message clones share their formatter
and owned arguments through Arc.
Each label follows the current catalog independently, including language changes
and translation reloads. In explicit Manual, unloading its scope clears its text until that scope
is ready again. Replace a binding when its captured arguments change.
For a fixed-language binding, configure with_locale before the macro on
Bevy 0.19 and pass the binding through Localized::from. Bevy 0.20 also permits
the chained modifier inside bsn!; see
several-language scenes.
§Localize a text span
Use Localized<TextSpan, Scope> on a TextSpan child of a Text or Text2d root:
TextSpan
Localized::<TextSpan, Interface>::new(|hud| hud.msg_hello("Ada"))The binding changes only that span’s content and does not insert a root Text
on the span entity. The application owns its parent Text/Text2d, fonts,
colors and hierarchy. In Lazy, the inserted span binding requests and retains
its scope until removed, exactly like a root text binding. Other consumers or
manual pins can keep that scope alive. Spans keep their active-language content
while a requested locale loads or fails validation. Keep each translated message complete;
do not assemble a sentence from separately translated fragments in Rust.
§Bevy 0.19 dependencies
Select the matching backend on the normal dependency; leave the build dependency as shown above. The scene constructors stay the same:
[dependencies]
bevy = { version = "0.19", features = ["bevy_scene", "bevy_ui_widgets"] }
bevy_fluent_typed = { version = "0.5.0", default-features = false, features = ["bevy-0-19", "codegen"] }§Buttons and caption slots
A button’s visible caption normally lives on a Text child. @button(...)
in Bevy 0.20 calls an application scene function; it is not a built-in text
initializer. Accept a deferred Msg and retain it on the actual targets:
use bevy::ui_widgets::Button;
use bevy_fluent_typed::{FluentScope, Localized, Msg};
fn button<S: FluentScope>(message: Msg<S>) -> impl Scene {
let accessible = message.clone();
bsn! {
Button
AccessibleLabel
Localized::<AccessibleLabel, S>::from(accessible)
Children [
Text
Localized::<Text, S>::from(message)
]
}
}The visible binding belongs to the child, while the semantic name belongs to its button root. Both use the same message and retain its scope independently. AccessibleLabel is available on Bevy 0.19/0.20; its binding updates the immutable component through Bevy hooks after UI accessibility producers. The runtime leaves the neighboring AccessibilityNode to Bevy; node-only changes are not independently repaired. No Text is added on the button root. The application supplies styling, interactions and focus.
Bevy 0.20 uses @ for scene function calls and -- between child entities:
let message = Msg::<Interface>::new(|hud| hud.msg_hello("Ada"));
let first = message.clone();
let second = message;
commands.spawn_scene(bsn! {
Node
Children [
#FirstButton
@button(first)
--
#SecondButton
@button(second)
]
});On Bevy 0.19, use button(message.clone()) without @, and separate child
entities with commas. Scene IDs such as #FirstButton are internal identifiers,
not translation keys.
A reusable widget can instead accept caption: impl Scene, keeping its
semantic name as a separate Msg<S>. Bevy 0.20 inserts that caption with
Children [ @caption ]; Bevy 0.19 uses Children [ ({caption}) ]. This slot can
contain text, an icon or a composed scene. Icon-only controls still need an
accessible name even when no visible Text is present.
Feathers uses FeathersButtonProps.caption: Box<dyn SceneList> on both versions.
With the application’s bevy_feathers feature enabled, supply a localized scene
rather than a resolved string:
use bevy::feathers::controls::FeathersButtonProps;
let caption_message = message.clone();
let props = FeathersButtonProps {
caption: Box::new(bsn_list! {
Text
Localized::<Text, Interface>::from(caption_message)
}),
..default()
};Attach AccessibleLabel and Localized::<AccessibleLabel, Interface>::from(message)
to the final button root as well. Feathers remains application-owned; the
localization crate adds no widget/Feathers dependency. String-taking helpers create a translated
snapshot if given a rendered String; keeping a Msg binding inside the
caption preserves language switching.
Feathers button source and native BSN migration.
For application-defined components, see
custom bindings.
Localized<Target, Scope> names the target first. Every target is a component;
Default is not required. Include it in the same scene entity as its binding.
An omitted target removes the binding with a warning; no component is created.
Later target removal after a successful attachment is respected.
A binding always needs its formatting closure or Msg.
The runnable BSN example includes typed button and caption-slot helpers and
checks EN/ES/RU visible/semantic labels and release after despawning.
§World labels and scene setup
Use Localized::<Text2d, Interface>::new(...) for a world label. Cameras, fonts,
shaping and layout remain normal Bevy application setup. Include Text2d beside
its binding, just as UI scenes include Text; no implicit target is created.
These recipes use compiled Rust scenes. They do not add a .bsn file loader or
serialize formatting closures. Translation reload keeps the generated schema
unchanged; changing messages or argument types requires rebuilding the application.
The headless BSN example contains a runnable file-backed application and tests for late loading, language changes, reload rejection/recovery, UI/world labels, unloading and missing messages on both backends.
§Application-defined localization bindings
Use Localized<Target, Scope> for every automatic binding: ordinary Bevy text,
application widgets and semantic labels. Targets implement Component; Default is optional.
The binding owns Msg; the target component stores its output. All targets use the same
provider, loading modes and entity-owned demand, without a user refresh system
or component registration.
Msg<Scope> is the deferred formatter type. Message<Scope> remains a deprecated
alias with the same constructors and binding conversions; use Msg in new code.
§Bind a custom component
Implement LocalizationTarget on your component. Add the normal source plugin
from the quickstart, then spawn the component with its binding:
use bevy::prelude::{Component, EntityWorldMut};
use bevy_fluent_typed::{LocalizationTarget, LocalizationUpdate, Localized};
use texts::presentation::Hud;
#[derive(Component)]
struct MyCaption {
text: String,
}
impl LocalizationTarget for MyCaption {
type Data = &'static mut Self;
type Filter = ();
fn apply(entity: &mut EntityWorldMut<'_>, update: &mut LocalizationUpdate<'_>) {
let Some(target) = entity.get_mut::<Self>() else {
return;
};
update.set_text(target.map_unchanged(|target| &mut target.text));
}
}
commands.spawn((
MyCaption { text: String::new() },
Localized::<MyCaption, Hud>::new(|hud| hud.msg_title()),
));Only Data/Filter and apply are required. This example uses the default sequential
writer; no registration, additional plugin or derive helper is needed. For direct
query writes and Idle skipping, override update and needs_update as shown by
Badge in the runnable example.
Implementing the trait alone does not opt entities into automatic updates.
Each entity needs its own Localized<Target, Scope> binding; native text uses
the same rule as application components.
Spawn the target and its binding together. When the deferred add callback runs,
a missing target removes the binding with one warning naming the entity, target
type and scope. No component is created automatically, even when it implements
Default. Rejected bindings do not retain their catalog or formatter captures.
Warnings use standard tracing/Bevy logging and do not require the diagnostics feature.
The check does not require a ready catalog and does not evaluate Data/Filter.
Applications also supply any neighboring components used by the adapter.
Supplied components keep their settings. Removing the target after a successful attachment does not recreate it, including after a language or Msg change. Reinserting the target resumes updates. Removing and adding the binding checks presence again; replacing its Msg does not. A rejected binding does not revive when a target appears later: attach a new binding alongside that target.
Compound and immutable components use this same trait. Components without
Default are supported; non-component field markers are not. Other hooks have defaults:
| Hook | Default and purpose |
|---|---|
needs_update(&data, &update) | Returns true. An optional pure predicate can skip Idle work and guide parallel scheduling. |
update(data, &mut update) | Returns UpdateResult::Deferred, requesting sequential apply. Override for direct query writes. |
apply(entity, &mut update) | Required writer. Read update.text() only when a translation is needed. |
matches(read_only_data, text) | Returns false. Optional confirmation of a deferred write after the whole batch and its hooks. |
PHASE | TargetUpdatePhase::BeforeLayout. |
UpdateResult::Done means handled, including an unchanged value or an intentional
wait. Deferred requests apply after query borrows end. Neither step forces a
message read. With CachePolicy::None, text() formats on demand and reuses that
value for the rest of the invocation and its deferred continuation. Rendered
retains prepared output instead. A context’s invalidation remains pending until
it is read. Returning false from needs_update postpones that work; if the catalog
changes while paused, resuming uses its latest value without intermediate writes.
update.is_changed() covers catalog/readiness, Msg identity and query reentry.
Combine it with update.component_changed(&component) for relevant Ref/Mut data.
This tracks application changes while excluding confirmed own writes. Ordinary
Bevy is_changed() remains available with its normal semantics. Deliberate
bypass_change_detection writes are outside the built-in tracking.
Compare before writing to preserve target ticks. For a String field, the shared
update.set_text(target.map_unchanged(|target| &mut target.text)) helper performs
that check, marks actual writes and can reuse buffers when a translation grows.
It leaves update.text() available for additional outputs. The built-in mutable text adapters and the Badge example use this same public helper.
matches receives the read-only view of the same Data/Filter query and must be
pure. Return true only when the relevant outputs equal the supplied text. The
engine checks after all deferred callbacks and their hooks, then acknowledges
its own writes. A skipped structural write stays pending even if its filter
returns before the next refresh; it is retried when eligible. The default is correct without confirmation, but can cause an
additional read on the next pass under None. Users do not implement a tracking
component, private cache or refresh system.
The scope snapshot is cloned before borrowing Data, including on modern Bevy’s
resource entities. Callback rows are disjoint and may run on compute workers;
do not depend on thread identity or entity order. Neither callback may change
its own binding; apply must not despawn the entity. An apply-only adapter queues
work every eligible refresh. Under None it formats every time it reads text.
§One Query and native filters
Data can contain several neighboring components. Filter accepts (), With,
Without, tuples and nested Or. For example, part of a paired adapter could be:
type Data = (
Option<Ref<'static, Caption>>,
Option<&'static mut SemanticNode>,
);
type Filter = (
With<Widget>,
Without<Editing>,
Or<(With<MenuItem>, With<OverlayItem>)>,
);Every item belongs to the binding’s entity. The engine uses one native query for
that adapter, composing its own Entity and Localized access with your Data.
Do not request the binding itself or whole-entity mutable access, which would
conflict with that access. Bevy validates query access normally. On Bevy 0.19/0.20,
Data must implement native SingleEntityQueryData to preserve disjoint rows;
older backends use their native QueryData. There are no auxiliary user Query
parameters or arbitrary SystemParam hook in this contract. Application systems
can compose relationships across entities; independent bindings can share Msg
clones when several targets need the same translation.
'static describes reference types in Data; the actual query items borrow the
running query, not the program’s entire lifetime. TargetItem names that actual
item consistently across all supported backends, including Bevy 0.16’s different
native QueryItem lifetime arity. This follows Bevy’s
QueryData model.
Required &mut Caption or Mut<Caption> excludes an entity without Caption,
so updates wait while the component is absent. Mut<'static, Caption> additionally
preserves a Ref in the query’s read-only view, including change detection.
Built-in targets and the Badge example use application-owned components and required
data without an Option.
Use optional data only when absence is part of your custom logic, such as an
optional neighbor; it does not itself create or retain anything.
Filter is an ArchetypeFilter: Changed/Added are not accepted, including
inside tuples or Or. A language or Msg can change without changing the target
first. Observe change ticks inside Data instead. Excluded entities keep their current
output; reentry after an excluded refresh catches up to the current translation.
A filtered-out binding still retains its catalog in Lazy. To release that demand,
remove its binding or despawn the entity.
§Supported targets
Implement LocalizationTarget directly on a component; no Default implementation
is required. Use one component type per independently bound value. Non-component
field markers and separate adapters for foreign component types are not supported.
Localized::<MyCaption, Hud>::from(message) accepts an existing Msg.
Its scope can also be inferred: Localized::<MyCaption, _>::from(message).
Replace the companion binding when the message or its captured arguments change.
A Msg stored elsewhere does not become a subscription: replacing that field
does not replace the companion, even if they originally shared a clone.
Built-in adapters are Text, Text2d and TextSpan, plus AccessibleLabel on
Bevy 0.19/0.20. Like application components, each must be supplied alongside its
binding. TextSpan still needs an application-owned text parent. A custom target
never receives an implicit UI Text from the library.
§Semantic labels and refresh ordering
let name = Msg::<Hud>::new(|hud| hud.msg_title());
commands.spawn((
AccessibleLabel::default(),
Localized::<AccessibleLabel, Hud>::from(name),
));This updates the same entity’s AccessibleLabel, including icon-only controls. Its immutable replacements run Bevy’s ordinary insertion hooks. Bevy owns AccessibilityNode and its required-component behavior: a normal AccessibleLabel insertion can create that node and update its name. The localization runtime does not independently query, repair or recreate the node. Node-only edits/removal do not invalidate Msg. Other UI producers may overwrite the node later, just as with an unbound AccessibleLabel; coordinate native producers or implement a custom paired adapter if your application needs a different policy. The application owns accessible roles, tree, focus and interaction.
Targets default to TargetUpdatePhase::BeforeLayout, in
LocalizationSystems::Refresh. AccessibleLabel uses AfterLayout, in
LocalizationAccessibilitySet, after UI accessibility producers
and before accessibility export. Custom adapters may select the
same phase through LocalizationTarget::PHASE. On Bevy 0.16–0.18 there is no
AccessibleLabel adapter; AfterLayout custom callbacks follow the localization
refresh, without a UI-producer/export ordering guarantee.
§Choose a provider’s cache policy
Configure the owning root provider once; its leaf and group bindings inherit the policy. Independent root providers can choose differently.
use bevy_fluent_typed::{CachePolicy, LocalizationPlugin};
app.add_plugins(
LocalizationPlugin::<texts::Translations>::new(HUD)
.with_cache_policy(CachePolicy::None),
);HUD is the generated embedded manifest from the quickstart. The same builder
works with files, from_bytes and from_loader, in Lazy, Full and Manual.
There is no per-binding override or runtime policy switch.
| Policy | Retained output | Repair and Idle behavior |
|---|---|---|
CachePolicy::Rendered (default) | An additional formatted String per binding, in the same ECS metadata for all targets. | Target repair reuses that output. Unchanged native text does not reformat. |
CachePolicy::None | No formatted output retained by the runtime; identity and invalidation metadata remain. | Built-in targets skip Idle and format for application edits or invalidation. Custom adapters format when they request update.text(). |
Rendered and built-in targets format after catalog/Msg changes and eligibility
reentry. An uncached custom adapter sees that invalidation through
update.is_changed() and requests text when it can handle it. Equal output
avoids native target writes. Disabling the result cache does not discard
the String owned by Text, a custom component or AccessibleLabel, nor the name
owned by AccessibilityNode; these are the target values. Deferred work can keep temporary output through its callback and confirmation;
None retains none of that output after the refresh.
A custom adapter can inspect query or entity data before asking for text. An intact caption can repair a companion from its own String without Fluent; the Caption/CaptionMirror example combines this with a structural pause filter. An apply-only adapter that always reads text formats every eligible refresh under None. Built-in and manual targets share the same optional post-batch confirmation for immutable/structural writes.
Cache policy does not change module loading, scope lifetime, readiness, locale
publication or Msg::render, which always invokes the formatter immediately.
Native text mutations through bypass_change_detection remain deliberately
untracked under both policies. The binding example
can run the same scenario with and without retained results.
§Loading and lifecycle
Creating or cloning an unattached binding/message is passive. Lazy retains
inserted companions, alongside other consumers, pins and leases. A target
component without a binding does not request a catalog. Full requests all modules; Manual still requires explicit
load calls. When a catalog is unavailable, adapters receive an empty string. Preparing a target locale keeps active values
until publication, including preparation failure.
Catalogs remain immutable snapshots. Capture owned arguments, not a translated string or catalog snapshot. Number formatting remains application-owned; use locale-aware ICU/ICU4X services inside the formatter. Changing captured external state does not automatically invalidate a Msg: replace it when inputs change.
Native BSN supports Localized::<Target, Scope>::new(...) and from(message)
on Bevy 0.19/0.20; missing formatter constructors fail during scene construction.
See button composition.
§Every Msg rendering and update path
A Msg stores Fn(&Scope) -> String. There are two entry points:
| Entry point | Who invokes the formatter and applies its result |
|---|---|
Localized<Target, Scope> | The runtime formats according to the provider’s cache policy and updates the target on the same entity. No target registration is needed. |
message.render(&scope) | The caller invokes the formatter immediately on every call, without this runtime cache, and decides where to put the String. |
The built-in targets are UI Text, world Text2d, child TextSpan, and
AccessibleLabel on Bevy 0.19/0.20. Custom targets may address an entire component
or a field. Text does not imply an AccessibleLabel, and a parent binding does
not propagate to text children: each target needs its own binding.
World spawning, Commands, later insertion, native BSN, Scene and SceneList
composition all use this same binding path. Localized scene templates and
Msg::new, Msg::literal, Localized::new, from and clone are
passive. Formatting starts after insertion and deferred commands, when a matching
provider enables that scope and its refresh job runs. Preexisting instances are
adopted during App setup without target registration.
§When the automatic formatter runs
The following table describes built-in targets under the default
CachePolicy::Rendered. All use the shared ECS state
and common engine.
Custom adapters additionally decide when their callbacks read text. An eligible
row needs its required target data; removed components receive no refresh.
A ready scope is required to call Msg; otherwise the supplied output is empty.
Caches are separate per World, binding type and entity, without deduplicating
owners of the same cloned Msg.
| Situation observed by refresh | Formatter invocation | Output behavior |
|---|---|---|
| First eligible target with a ready scope | Yes | Apply the translation. |
| Binding attached to a supplied target before its scope loads, or the first load fails | No | Eligible output is empty. |
| Target missing when the binding is first attached | No | Remove the binding with a warning; create no component or catalog demand. |
| Scope becomes ready after loading, retry or reacquisition | Yes | Publish the current translation. |
set_locale publishes a prepared language | Yes | Keep the active language until publication, then update. |
Manual commit_locale reaches publication | Yes | The call queues the commit; resource publication invalidates bindings. |
| Valid same-language reload publishes a fresh scope, including identical bytes | Yes | Equal output preserves target ticks. |
| A new Msg identity replaces the existing binding’s formatter | Yes, when ready | Recompute without running initialization again. |
| A cloned Msg is attached to another entity or target | Yes, when ready | That binding has independent metadata and output. |
| Existing binding is replaced by a clone of its current Msg | No, if inputs are unchanged | Reuse output without initialization. |
| Binding removed and added again | Yes, when eligible/ready | Check target presence again; reject a missing target with a warning. |
| Scope becomes unavailable | No | Clear eligible output; missing targets stay absent. |
| Existing target is edited through ordinary Bevy mutation | No additional formatting | Repair from cached output. |
| Target is removed while Localized remains | No | Respect removal; catalog and Msg changes do not revive it. |
| Target/query eligibility returns after an excluded refresh | Yes, when ready | Catch up to current inputs. |
Native output is edited through bypass_change_detection | No | Leave the untracked edit until another observed change or invalidation. |
| AccessibilityNode alone is edited or removed | No | Leave it to Bevy/application behavior; do not independently repair it. |
| No relevant input or target change | No | Skip work and preserve target ticks. |
Under None, eligible existing target edits and the invalidations above request a fresh translation. Missing targets still remain absent and do not format. Repeated text reads within update/apply reuse the invocation’s value. Shared post-batch verification excludes confirmed own writes from component_changed; external writes from later hooks remain detectable. An unavailable scope never calls Msg under either policy.
Scope changes are tracked at the selected scope’s granularity, not per Fluent key. Reloading another key in the same leaf still invalidates a Msg using that leaf; a group/root also follows changes to any required descendant. Missing published scope resources are restored from the retained snapshot, which marks them changed as well. Several changes before one refresh can coalesce; the formatter reads the state visible at that refresh.
prepare_locale, progress changes, loading attempts and rejected reloads do not
by themselves invoke a Msg. Active catalogs stay available during a pending,
failed or cancelled language switch and failed same-language reload. Independent
active-catalog edits or Msg replacements can still update text during that wait.
Selecting the already active locale does not reload ready leaves; it can retry
failed ones, whose later successful publication uses the normal rules above.
§Applying a cached result is separate work
The runtime checks active bindings in PostUpdate through one query composed from Data, Filter, Localized and shared ECS metadata. It uses the same callbacks for Text, Text2d, TextSpan, AccessibleLabel and user targets, without known-type dispatch or a private target protocol.
Small sets stay sequential. Large sets with an unchanged catalog inspect dirty work first; a few changes stay sequential, large updates use Bevy’s parallel query iterator, and all-Idle sets avoid task scheduling. Query size hints provide a scheduling estimate without a separate row-count traversal. This still reads binding metadata each frame; it is not zero-cost polling. String comparison before writes preserves equal-output ticks and reuses target buffer capacity.
needs_update is a pure optional predicate and may be checked during scheduling.
update receives its row once when selected. Done includes unchanged output or
waiting; Deferred queues sequential apply after borrows end. The lazy context
allows apply to use existing neighbor data without a forced Msg read. Membership
and Msg identity are rechecked before each structural callback. The same query’s
read-only view verifies opt-in matches only after the whole batch and hooks.
No user tracking component or second refresh system is required.
The initial presence check is separate from refresh and happens only on binding attachment. It preserves supplied settings and removes a binding whose target is absent, without creating tracking state. Removing a target later does not run the check again; removing Localized retires its metadata, while an existing target stays intact. Temporary query exclusion can retain cached storage and binding-owned catalog demand; reentry uses current inputs.
Parallel query work requires Bevy’s native multi_threaded feature; a multi-worker
pool alone does not enable it. Work completes before this refresh returns. There is no built-in frame
budget or automatic spreading across frames. Formatting and component updates
are only part of a language switch’s cost: Bevy must still process changed text
and layout. The runtime does not create a separate worker pool.
See the performance reference
for formatter counts, cache tradeoffs and measured refresh costs.
BeforeLayout targets run in LocalizationSystems::Refresh. AfterLayout targets
run in LocalizationAccessibilitySet; the AccessibleLabel adapter uses that
phase after UI accessibility producers on Bevy 0.19/0.20. Insertions or user
writes ordered after the relevant phase take effect on its next refresh.
Formatting does not run on an independent timer or directly on a file-watcher
thread. Files, embedded manifests, supplied bytes and asynchronous/custom asset
sources all enter the same scope publication and refresh path. ReloadCatalogs
requests a fresh read; changing a source buffer without a read/publication does
not invalidate a Msg. Source validation and successful publication remain
required for automatic source-driven updates.
Full, Lazy and Manual choose module loading and lifetime. All three still refresh existing bindings automatically when a scope is available. Manual means explicit module requests; application-owned text uses a plain String without a binding. Applications construct the targets and supply the deferred Msg explicitly.
§Cases that do not establish automatic ownership
A standalone Msg in a variable or a field of a resource, event or target component
has no automatic refresh. A Msg is not itself a Bevy component. Reading
Res<Scope> or calling a generated scope.msg_hello() returns application-owned
data; it does not attach a binding to any resulting String. A direct
message.render(&scope) is likewise a caller-owned snapshot. Running that call
in Update, Startup, an observer or another caller only changes when the caller
runs; each explicit call formats again.
Changes to other resources, captured Arc contents, numbers or formatter settings
are not inferred. Replace the Msg when these inputs change. A closure that
captures an already translated String keeps that snapshot, even when called
with a newer scope. Msg::literal intentionally returns fixed text, but in
an automatic binding it still needs a ready scope; without one the output is empty.
Removing a Localized companion stops its writes and leaves an existing target’s
last String in place. Removing only the target leaves Localized attached but does not recreate the
component. Its required query data is absent; reinsert the component to resume.
The binding still owns its catalog demand until removed.
Despawn removes the entity through Bevy. Remaining bindings, native consumers,
pins, leases or Full can keep catalogs loaded; an unattached Msg alone does not.
Use separate component types for independent bindings. Each bound component
should have one localization writer. An application marker such as UserOwned does not
change these rules; ownership follows the actual binding types.
§Hidden and disabled entities
Visibility, layout and styling do not pause these refresh queries. A hidden text still follows its scope. Bevy’s default query filters exclude Disabled entities; they receive no refresh while excluded. Returning after at least one excluded refresh causes a fresh formatting pass when a scope is available.
Localized hooks count the inserted binding even while Disabled, retaining
its Lazy demand. Reenabling resumes refresh; disabling is not an unload request.
Removing the binding or despawning releases its ownership. Merely hidden entities
continue both refresh and demand as usual.
§Runnable examples
The complete binding example keeps native targets and custom components in one focused package:
cargo run --locked --manifest-path examples/bindings/Cargo.toml| Task | Starting point |
|---|---|
| Configure the source | main.rs: ordinary source plugin and Startup system |
| Spawn native text, a button and custom components | widgets.rs: explicit targets, custom adapters, styling and hierarchy |
| Implement component adapters | targets.rs: Title, Badge and Caption |
| Change arguments, switch EN/ES/RU and release demand | scenario.rs: headless driver, separate from spawning |
| Compose Scene or SceneList captions | BSN buttons and composition recipes |
The executable runs without a window or font assets. The process test runs the automatic path under both cache policies, including query-filter reentry.
§Replace the previous text binding
LocalizedText has been removed. Use Localized<Text, Scope>,
Localized<Text2d, Scope> or Localized<TextSpan, Scope> according to the target.
The target type is explicit; the scope can be inferred with
Localized::<Text, _>::from(message). A binding does not inspect neighboring
components to guess its target, and it never inserts an AccessibleLabel unless
that target is bound explicitly.
§Explicit build-script API
For a complete Cargo.toml, files and application, follow the quickstart. This section explains the optional custom build entrypoints.
The build feature exposes build(), from_cargo(), generate() and
Settings and BuildError through the same crate used by the application. Its private build
module emits the Bevy provider; no separate bridge package is needed.
Discovery and the typed module tree come from
fluent_typed_codegen; message accessors
and Fluent resolution come from fluent-typed.
In build-dependencies, disable default features and enable only build.
This configuration compiles the generator, not Bevy or the localization runtime.
Normal dependencies enable a Bevy backend and codegen, not build. Use Cargo
resolver 2 or 3 so host and target features remain separate.
fn main() -> std::process::ExitCode {
bevy_fluent_typed::build()
}Generation and Cargo file/directory tracking run exclusively in this explicit
call. The application’s translations! macro only includes the prepared output
under OUT_DIR; macro expansion never runs the generator or writes files.
For custom diagnostics use from_cargo() and handle its error; for explicit
package/output paths use generate() with Settings. Do not ignore generation
failures or compile stale output after an error.
fn main() -> Result<(), bevy_fluent_typed::BuildError> {
bevy_fluent_typed::from_cargo()
}Both from_cargo() and generate() return the generator’s BuildError,
re-exported by this facade. Match BuildError::Io for the operation, filesystem
path and original I/O error; BuildError::Config preserves the typed configuration
cause and available filename. Module differences expose sorted missing/extra
paths, and upstream failures keep their original typed error. All variants print
readable diagnostics with Display and expose their original causes through
std::error::Error::source() where applicable.
Settings::from_manifest and CatalogConfig::parse return ConfigError;
LocalizationManifest wraps configuration failures in ManifestError::Config.
Use ConfigField, FieldError and PathError for matching invalid known fields
or paths; unknown configuration fields remain ignored. Runtime-only consumers
without manifest or codegen still have no generator dependency. Build-only
errors are available only with build; they do not enable an engine backend.
Cargo feature forwarding such as bevy_fluent_typed/bevy-0-17 can enable a feature
on both dependency kinds when they share a name. Select the backend directly in
the normal dependency’s features array, not through application feature
forwarding. Cargo also requires the same dependency name in both sections; if
renaming the crate, use that alias in both, as in the integration example.
The public facade is available since 0.1.1. Version 0.1.0 required a separate bridge build-dependency. Number formatting and plural-category preparation are application runtime work, not part of this build phase.
§Features
| Feature selection | Available API and dependencies |
|---|---|
| Defaults | Bevy 0.20 runtime and manifest support; runtime loading defaults to Lazy |
codegen on the normal dependency | translations!, generated resources and manifest helpers; enables manifest, not generation |
build alone, defaults disabled | Explicit generation in build.rs; generator build dependencies, no Bevy |
manifest with a backend | Manifest constructors and the generator’s runtime manifest API; no generation |
| One backend alone, defaults disabled | Byte sources and handwritten providers; no generator package, TOML or bridge |
watch | Bevy asset-source file watching; does not watch custom byte loaders |
diagnostics with a backend | Explicit per-module detail queries only; disabled by default, no additional dependencies |
Loading counters and passive per-scope progress queries are available with
every runtime backend, including the minimal byte-source configuration. Native
tracking is enabled with LocalizationProgressPlugin<Scope> through ordinary
app.add_plugins during setup; no Cargo progress feature exists. Without a
progress plugin, no native view or recurring tracker is installed. Scopes of one
provider share a dispatcher. Selecting the root includes all registered views;
a group includes its descendants, and a leaf selects itself. Generated providers
supply hierarchy metadata automatically. The diagnostics feature only enables
on-demand module details and does not activate tracking.
codegen and manifest are independent of how you obtain runtime bytes.
Generated providers currently include manifest helpers, so codegen enables
those types even when the application chooses from_bytes or from_loader.
Disabling only codegen leaves the default manifest feature enabled. Use
default-features = false and select a backend for the minimal handwritten path.
§Manifest configuration
[package.metadata.localization] contains only catalog, the TOML file path
relative to the consuming package’s Cargo.toml. Parent components (..) may
locate shared translation sources. The manifest selects source-language,
default-language and the optional translations-directory (default ".").
languages-directory is the legacy alias; do not specify both directory names.
Unknown fields in Cargo metadata and the TOML manifest are ignored; recognized
fields are validated. Languages are discovered from directories; keep their module/message contracts
in sync. Typed annotations belong to the source language.
The generated CATALOG_CONFIG contains the TOML contract, and CATALOG_PATH
is its package-relative build location. The generator does not select a Bevy
asset root or rewrite this path into an asset address. texts::manifest() keeps
that origin verbatim. The application must configure a source that resolves it,
or create a LocalizationManifest with a different runtime origin. For example,
with the standard Bevy assets root, use LocalizationManifest::parse( texts::CATALOG_CONFIG, "localizations/localization.toml").
No generated FTL payload is embedded unless the application
explicitly invokes embed_manifest!, including a declaration such as
texts::embed_manifest! { const HUD = presentation::Hud; }.
The Bevy facade re-exports the same LocalizationManifest type used by the
generator; declared constants require no additional import, adapter or conversion.
§Work on local checkouts
Local paths are for editing and testing the libraries together.
Replace the quickstart’s runtime/build entries and add a generator patch as
shown below. Keep its other dependencies, metadata, build.rs and source files.
Set both paths to your checkouts:
[dependencies]
bevy_fluent_typed = { path = "/absolute/path/to/bevy_fluent_typed", features = ["codegen"] }
[build-dependencies]
bevy_fluent_typed = { path = "/absolute/path/to/bevy_fluent_typed", default-features = false, features = ["build"] }
[patch.crates-io]
fluent_typed_codegen = { path = "/absolute/path/to/fluent_typed_codegen" }The runtime checkout contains the Bevy build adapter. Put the patch in the workspace root when the consumer belongs to a workspace. This is development wiring; normal applications use the registry dependencies in Setup.
The runtime requires generator 0.3.0 for its current generated contract. For local changes in both libraries, select the matching generator checkout; cloning the two repositories does not apply this override automatically.
For repeated example runs, add this to .cargo/config.toml at the runtime
repository root, preserving any existing settings:
[patch.crates-io]
fluent_typed_codegen = { path = "/absolute/path/to/fluent_typed_codegen" }This local configuration applies the override to the commands in the example READMEs. Keep it out of commits. If your enclosing workspace already supplies the matching patch, no additional configuration is needed.
For a single command, provide the same patch on the command line instead:
cargo run --manifest-path examples/codegen/Cargo.toml --config 'patch.crates-io.fluent_typed_codegen.path="/absolute/path/to/fluent_typed_codegen"'Re-exports§
pub use fluent_typed;
Macros§
- translations
- Declare a typed translation tree prepared by this crate’s build API.
Structs§
- Catalog
Config - Typed configuration failures shared by manifest parsing and host generation.
Contents of
localization.toml, separate from Cargo’s catalog path. - Full
- Load every module of the selected language.
- Lazy
- Default policy: load only scopes owned by inserted bindings and resource consumers.
- Loading
Progress - Latest attempts and usable snapshots across unique logical module paths.
- Locale
Access - Borrowed access to one compiled language; inspection never starts loading.
Use
Self::modulesfor explicit navigation, or access navigation methods directly throughDeref. The explicit path also avoids method-name conflicts. - Locale
Access Mut - Borrowed access to fixed-language requests; dropping it does not remove pins.
Use
Localization::for_localefor read-only navigation and status inspection. - Localization
- Controller for the selected locale and requested scopes.
- Localization
Accessibility Set - PostUpdate boundary for semantic targets, separate from the native text refresh.
On Bevy 0.19/0.20 it follows UI accessibility producers and precedes export.
Older backends order it after
LocalizationSystems::Refreshonly. - Localization
Manifest - A source contract for readable FTL; creating one never parses FTL.
- Localization
Plugin - Register loading and typed resources from a manifest or application-owned byte source.
- Localization
Progress - Native latest progress for one explicitly observed root, group or leaf.
- Localization
Progress Plugin - Observe a scope and all its descendants without requesting translations.
- Localization
Registration Error - Two localization plugins claim the same root catalog type.
- Localization
Startup Plugin - Configure startup coordination independently of localization source plugins.
- Localization
Update - The message value and invalidation signal for one adapter invocation.
- Localized
- Bind a deferred message to a Bevy text component or an application-defined target.
- Manual
- Load only explicitly requested scopes; persistent requests give hybrid loading.
- Module
- A checked leaf parser associated with a logical FTL path.
- Module
Diagnostic - Latest attempt and snapshot availability for one logical module.
- Module
Error - A typed scope is unavailable for the selected locale.
- Module
Lease - Independent ownership of a Manual localization scope.
- Module
Mismatch - Generator settings for explicit build frontends. Per-language difference from the complete source module inventory.
- Module
Store - Read-only access to ready scopes for typed navigation and provider assembly.
- Msg
- Cloneable deferred formatting for a leaf, group or complete catalog.
- Passive
Catalog - Borrow an available catalog without requesting or retaining its module.
- Reload
Catalogs - Retry all currently requested modules without exposing asset handles. Also retries requested target leaves during locale preparation.
- Scope
Registration - Type-erased registration for one root, group or leaf resource.
Provider integrations construct these with
new; applications use typed resources. - Settings
- Generator settings for explicit build frontends. A package-relative filesystem path locating the catalog configuration.
Enums§
- Build
Error - Generator settings for explicit build frontends. Configuration, catalog validation, generation or filesystem failure.
- Cache
Policy - Whether automatic bindings retain an additional copy of formatted text.
- Catalog
Update - The host application decides how to present successful/rejected acquisitions.
Automatic switching failures are reported before switching; successful target
leaves report
Loadedwhen their locale is committed. Manual preparation failures remain available throughLocalization::preparation_status. - Commit
Locale Error - A locale commit could not be scheduled.
- Config
Error - Typed configuration failures shared by manifest parsing and host generation. Invalid TOML, a recognized setting, or a configuration path.
- Config
Field - Typed configuration failures shared by manifest parsing and host generation. A localization setting or requested source address.
- Field
Error - Typed configuration failures shared by manifest parsing and host generation. Why a recognized field cannot be used as a string.
- IoOperation
- Generator settings for explicit build frontends. Filesystem operation that failed.
- Localization
Systems - Ordering boundaries for localization consumers.
- Manifest
Error - A manifest or requested module could not be obtained.
- Module
Status - Status of a module’s latest request for the selected locale.
- Name
Error - Generator settings for explicit build frontends. Why a source component cannot identify a Rust module or type.
- Name
Owner - Generator settings for explicit build frontends. The generated declaration owning a conflicting Rust name.
- Path
Error - Typed configuration failures shared by manifest parsing and host generation. Why a filesystem input path is invalid.
- Preparation
Status - Availability of the target locale, independent of active catalog readiness.
- Schema
Error - Generator settings for explicit build frontends. Fluent syntax, duplicate key or contract mismatch.
- Startup
Strategy - How native startup systems wait for their localization catalogs on Bevy 0.19/0.20.
- Syntax
Node - Generator settings for explicit build frontends. Opaque Rust syntax category rejected before source printing.
- Target
Update Phase - Choose when a target receives its translated value in PostUpdate.
- Update
Result - Whether an adapter finished through its query or needs exclusive entity access.
- Upstream
Shape Error - Generator settings for explicit build frontends. Unsupported structure in upstream generated source.
Traits§
- Fluent
Catalog - Root provider connecting compiled typed schemas to the Bevy runtime.
- Fluent
Scope - One generated root, directory group or independently loadable leaf.
- Loading
Mode - A loading policy supported by this runtime. Implementations are sealed.
- Localization
Target - Apply translated text through one native Bevy query and optional structural work.
Functions§
- build
- Explicit build-script generation and configuration, without an engine backend. Explicit build-script generation and configuration, without an engine backend. Explicit build-script generation and configuration, without an engine backend. Build-script entrypoint: discover catalogs and emit their Bevy adapter. On generation failure, prints diagnostics to stderr and returns a failure ExitCode without terminating the process. Return it from build.rs main so Cargo observes generation failures.
- from_
cargo - Explicit build-script generation and configuration, without an engine backend.
Explicit build-script generation and configuration, without an engine backend.
Explicit build-script generation and configuration, without an engine backend.
Generate from the consuming package’s Cargo metadata and OUT_DIR.
Reads
CARGO_MANIFEST_DIRandOUT_DIR, writes the plain and Bevy entrypoints, and emits Cargo rerun directives to stdout. - generate
- Explicit build-script generation and configuration, without an engine backend.
Explicit build-script generation and configuration, without an engine backend.
Explicit build-script generation and configuration, without an engine backend.
Generate with explicit package/output paths, without Cargo environment lookup.
Settings paths are relative to
package. Createsoutputand overwrites owned outputs, includingbevy_catalog.rs, leaving unrelated files untouched. Writes persistent staging files and Cargo rerun directives through the generator. Keep output in a tool-owned target directory; generation is not transactional, so discard its results after a failure.
Type Aliases§
- Catalog
Update Reader - Bevy system parameter for reading this provider’s reload notifications.
- Message
Deprecated - Deprecated name for
Msg; constructors and binding conversions are unchanged. - Target
Item - One item of an adapter’s native query, with the query’s actual borrow lifetimes.
- Target
Read Item - Read-only view of an adapter’s same query, used for deferred confirmation.