Skip to main content

cranpose_ui/
localization.rs

1//! Reactive localization that composes with existing text and string-taking APIs.
2//!
3//! ```
4//! #[cranpose_ui::composable]
5//! fn Greeting() {
6//!     let text = cranpose_ui::tr!("Hello, {name}!", name = "Ana");
7//!     assert!(text.as_str().contains("Ana"));
8//! }
9//! cranpose_ui::run_test_composition(Greeting);
10//! ```
11//!
12//! Missing arguments are compile errors:
13//!
14//! ```compile_fail
15//! #[cranpose_ui::composable]
16//! fn Greeting() {
17//!     let _ = cranpose_ui::tr!("Hello, {name}!");
18//! }
19//! ```
20//!
21//! Extra arguments are compile errors:
22//!
23//! ```compile_fail
24//! #[cranpose_ui::composable]
25//! fn Save() {
26//!     let _ = cranpose_ui::tr!("Save", unused = 42);
27//! }
28//! ```
29//!
30//! `tr!` outside a composable is a compile error. A task callback or a
31//! helper that runs outside composition uses `message!`:
32//!
33//! ```compile_fail,E0425
34//! fn greeting() {
35//!     let _ = cranpose_ui::tr!("Hello");
36//! }
37//! ```
38
39use std::cell::RefCell;
40
41use cranpose_core::{
42    CompositionLocal, CompositionLocalProvider, compositionLocalOf, remember, rememberKeyed,
43};
44pub use cranpose_localization::{
45    Argument, Catalog, DeferredMessage, FluentValue, Language, LanguagePreference,
46    LanguagePreferenceStore, Locale, Localization, LocalizationError, Message, PreviewMode,
47    Resource, SourceCatalog, Translator,
48};
49
50/// A formatted translation with shared text storage and owned-string conversions.
51pub type LocalizedText = crate::text::SharedText;
52
53#[cfg(feature = "localization-formatting")]
54pub use cranpose_localization::{FormatError, LocaleFormatters};
55
56/// Translations for Cranpose controls, also usable by native services and test tools.
57/// UI providers add this fallback automatically; applications can override its namespaces.
58pub use crate::ui_strings::catalog as framework_catalog;
59
60/// Locale-aware data formatters retained for the current language provider.
61/// A language change replaces these formatters without changing stored application data.
62#[cfg(feature = "localization-formatting")]
63#[track_caller]
64pub fn local_formatters() -> Result<std::rc::Rc<LocaleFormatters>, FormatError> {
65    if let Some(translator) = local_translator().current() {
66        return translator.formatters();
67    }
68    rememberKeyed((), |()| {
69        LocaleFormatters::new(&Locale::parse("en").expect("source locale")).map(std::rc::Rc::new)
70    })
71}
72
73/// Displays a message captured by `message!` using the current provider.
74/// A language change updates the text even when the request remains in application state.
75#[track_caller]
76pub fn localized_message(message: &DeferredMessage) -> LocalizedText {
77    let translator = local_translator().current();
78    rememberKeyed((message.clone(), translator), |(message, translator)| {
79        LocalizedText::from(message.format(translator.as_ref()).unwrap_or_else(|error| {
80            log::error!("{error}");
81            message.fallback_text()
82        }))
83    })
84}
85
86/// The translator installed by the nearest [`ProvideLocalization`].
87/// `None` uses each message's inline source-language catalog.
88pub fn local_translator() -> CompositionLocal<Option<Translator>> {
89    crate::thread_state::with_environment(|locals| {
90        locals
91            .translator
92            .get_or_init(|| compositionLocalOf(|| None))
93            .clone()
94    })
95}
96
97/// Installs a catalog and language for this subtree, including its reading direction.
98/// Change the supplied locale state to update text and accessibility descriptions.
99/// Nested layout-direction providers can override the direction for individual controls.
100#[expect(non_snake_case, reason = "names follow Compose's casing")]
101#[track_caller]
102pub fn ProvideLocalization(catalog: &Catalog, locale: Locale, content: impl FnOnce()) {
103    let translator = rememberKeyed((catalog.clone(), locale), |(catalog, locale)| {
104        catalog
105            .clone()
106            .with_fallback(&crate::ui_strings::catalog())
107            .translator(locale.clone())
108    });
109    provide(translator, content);
110}
111
112/// Installs a prepared translator, including one negotiated from several preferred languages.
113#[expect(non_snake_case, reason = "names follow Compose's casing")]
114#[track_caller]
115pub fn ProvideTranslator(translator: Translator, content: impl FnOnce()) {
116    let translator = rememberKeyed(translator, |translator| {
117        translator.with_fallback(&crate::ui_strings::catalog())
118    });
119    provide(translator, content);
120}
121
122#[track_caller]
123fn provide(translator: Translator, content: impl FnOnce()) {
124    let direction = if translator.locale().is_rtl() {
125        crate::LayoutDirection::Rtl
126    } else {
127        crate::LayoutDirection::Ltr
128    };
129    let locales = rememberKeyed(translator.locale().clone(), |locale| {
130        crate::text::LocaleList::new(vec![locale.to_string()])
131    });
132    CompositionLocalProvider(
133        [
134            local_translator().provides(Some(translator)),
135            crate::local_layout_direction().provides(direction),
136            text_locales().provides(Some(locales)),
137        ],
138        content,
139    );
140}
141
142fn text_locales() -> CompositionLocal<Option<crate::text::LocaleList>> {
143    crate::thread_state::with_environment(|locals| {
144        locals
145            .text_locales
146            .get_or_init(|| compositionLocalOf(|| None))
147            .clone()
148    })
149}
150
151pub(crate) fn apply_text_locale(mut style: crate::text::TextStyle) -> crate::text::TextStyle {
152    if style.span_style.locale_list.is_none() {
153        style.span_style.locale_list = text_locales().current();
154    }
155    style
156}
157
158// The styles `apply_shared_text_locale` made last: each by the shared style
159// it was made from and the locales it took, so a screen that composes
160// texts in a few styles again copies none of them.
161pub(crate) type LocalizedTextStyles = crate::text::recent_values::RecentValues<
162    (
163        std::sync::Arc<crate::text::TextStyle>,
164        crate::text::LocaleList,
165        std::sync::Arc<crate::text::TextStyle>,
166    ),
167    16,
168>;
169
170// `apply_text_locale` for a shared style: the same one when it names its
171// locales or the composition has none, else the shared style with the
172// composition's locales.
173pub(crate) fn apply_shared_text_locale(
174    style: std::sync::Arc<crate::text::TextStyle>,
175) -> std::sync::Arc<crate::text::TextStyle> {
176    if style.span_style.locale_list.is_some() {
177        return style;
178    }
179    let Some(locales) = text_locales().current() else {
180        return style;
181    };
182    crate::thread_state::with(|state| {
183        let mut localized = state.localized_text_styles.borrow_mut();
184        if let Some((_, _, made)) = localized
185            .find(|(from, made_in, _)| std::sync::Arc::ptr_eq(from, &style) && *made_in == locales)
186        {
187            return std::sync::Arc::clone(made);
188        }
189        let mut made = crate::text::TextStyle::clone(&style);
190        made.span_style.locale_list = Some(locales.clone());
191        let made = crate::text_modifier_node::shared_text_style(&made);
192        std::sync::Arc::clone(&localized.keep((style, locales, made)).2)
193    })
194}
195
196struct CachedTranslation {
197    translator: Option<Translator>,
198    message: &'static Message,
199    arguments: Vec<Argument<'static>>,
200    text: LocalizedText,
201}
202
203/// Resolves a static message at this composition position. Prefer [`crate::tr!`].
204/// Unchanged arguments, catalog, and language reuse the previous formatted text.
205#[track_caller]
206pub fn localized<const N: usize>(
207    message: &'static Message,
208    mut arguments: [Argument<'_>; N],
209) -> LocalizedText {
210    localized_impl(message, &mut arguments)
211}
212
213#[track_caller]
214fn localized_impl(message: &'static Message, arguments: &mut [Argument<'_>]) -> LocalizedText {
215    let translator = local_translator().current();
216    let slot = remember(|| RefCell::new(None::<CachedTranslation>));
217    slot.with(|slot| {
218        let mut cached = slot.borrow_mut();
219        if let Some(value) = &*cached
220            && value.translator == translator
221            && std::ptr::eq(value.message, message)
222            && value.arguments.as_slice() == &*arguments
223        {
224            return value.text.clone();
225        }
226        let formatted = match &translator {
227            Some(translator) => translator.format(message, arguments),
228            None => message.format_source(arguments),
229        };
230        let text = LocalizedText::from(formatted.unwrap_or_else(|error| {
231            log::error!("{error}");
232            message.fallback_text(arguments)
233        }));
234        if let Some(value) = &mut *cached {
235            value.translator = translator;
236            value.message = message;
237            value.text = text.clone();
238            for (index, argument) in arguments.iter_mut().enumerate() {
239                match value.arguments.get_mut(index) {
240                    Some(previous) => previous.update_from(argument),
241                    None => value.arguments.push(argument.take_owned()),
242                }
243            }
244            value.arguments.truncate(arguments.len());
245        } else {
246            *cached = Some(CachedTranslation {
247                translator,
248                message,
249                arguments: arguments.iter_mut().map(Argument::take_owned).collect(),
250                text: text.clone(),
251            });
252        }
253        text
254    })
255}