es_fluent_manager_embedded/lib.rs
1#![doc = include_str!("../README.md")]
2
3use arc_swap::ArcSwap;
4use es_fluent::set_shared_context;
5use es_fluent_manager_core::FluentManager;
6use std::sync::{Arc, OnceLock};
7use unic_langid::LanguageIdentifier;
8
9#[cfg(feature = "macros")]
10pub use es_fluent_manager_macros::define_embedded_i18n_module as define_i18n_module;
11
12static GENERIC_MANAGER: OnceLock<ArcSwap<FluentManager>> = OnceLock::new();
13
14/// Initializes the embedded singleton `FluentManager`.
15///
16/// This function discovers all embedded i18n modules linked into the binary,
17/// creates a `FluentManager` with them, and sets it as a global embedded singleton.
18/// It also registers this manager with the `es-fluent` crate's central context,
19/// allowing the `es_fluent::localize!` macro to work.
20///
21/// This function should be called once at the beginning of your application's
22/// lifecycle.
23///
24/// # Panics
25///
26/// This function will not panic if called more than once, but it will log a
27/// warning and have no effect after the first successful call.
28pub fn init() {
29 let manager = FluentManager::new_with_discovered_modules();
30 let manager_arc = Arc::new(manager);
31 if GENERIC_MANAGER
32 .set(ArcSwap::new(Arc::clone(&manager_arc)))
33 .is_ok()
34 {
35 set_shared_context(manager_arc);
36 } else {
37 tracing::warn!("Generic fluent manager already initialized.");
38 }
39}
40
41/// Selects the active language for the embedded singleton `FluentManager`.
42///
43/// After a language is selected, all subsequent calls to localization functions
44/// will use the bundles for this language.
45///
46/// # Errors
47///
48/// This function will log an error if the embedded singleton has not been initialized by
49/// calling `init()` first.
50pub fn select_language<L: Into<LanguageIdentifier>>(lang: L) {
51 if let Some(manager) = GENERIC_MANAGER.get() {
52 manager.load().select_language(&lang.into());
53 } else {
54 tracing::error!("Generic fluent manager not initialized. Call init() first.");
55 }
56}