vizia_core/localization/mod.rs
1//! Provides types for adapting an application to a particular language or regional peculiarities.
2//!
3//! # Language Translation
4//!
5//! Vizia provides the ability to dynamically translate text using [fluent](https://projectfluent.org/). Fluent provides a syntax for describing how text should be translated into different languages.
6//! The [fluent syntax guide](https://projectfluent.org/fluent/guide/) contains more information on the fluent syntax.
7//!
8//! ## Adding Fluent Files
9//! Before text can be translated, one or more fluent files must be added to an application with the corresponding locale:
10//! ```ignore
11//! # use vizia_core::prelude::*;
12//! # let mut cx = &mut Context::default();
13//! // Adds a fluent file to the application resource manager.
14//! // This file is then used for translations to the corresponding locale.
15//! cx.load_translation(
16//! langid!("en-US"),
17//! include_str!("resources/en-US/translation.ftl").to_owned(),
18//! );
19//!
20//! ```
21//!
22//! ## Setting the Locale
23//! The application will use the system locale by default, however an environment event can be used to set a custom locale.
24//! If no exact translation exists for the specified locale, vizia will negotiate the best available match and then fall back
25//! per message to the default translation bundle when needed.
26//! ```ignore
27//! # use vizia_core::prelude::*;
28//! # let mut cx = &mut Context::default();
29//! // Sets the current locale to en-US, regardless of the system locale
30//! cx.emit(EnvironmentEvent::SetLocale(langid!("en-US")));
31//! ```
32//!
33//! ## Diagnostics
34//! Missing keys, missing attributes, and Fluent formatting issues are reported through the standard
35//! [`log`](https://docs.rs/log) backend at `warn` level.
36//! Configure your logger (for example with `env_logger`, `tracing-log`, or `fern`) to surface these messages.
37//!
38//! ## Basic Translation
39//! Use the [`Localized`] type to specify a translation key to be used with fluent files. The key is then used to look up the corresponding translation.
40//! ```ignore
41//! # use vizia_core::prelude::*;
42//! # let mut cx = &mut Context::default();
43//! Label::new(cx, Localized::new("hello-world"));
44//! ```
45//! The markup in the loaded fluent (.ftl) files defines the translations for a particular key. The translation used depends on the application locale, which can be queried from [`Environment`].
46//! ```ftl
47//! // en-US/hello.ftl
48//! hello-world = Hello, world!
49//! ```
50//! ```ftl
51//! // fr/hello.ftl
52//! hello-world = Bonjour, monde!
53//! ```
54//!
55//! ## Variables
56//! Data from the application can be inserted into translated text using a [placeable](https://projectfluent.org/fluent/guide/variables.html).
57//! The variable is enclosed in curly braces and prefixed with a `$` symbol.
58//! ```ftl
59//! welcome = Welcome, { $user }!
60//! ```
61//! The [`Localized`] type provides the `arg(...)` method for referencing a variable. It accepts either a plain value
62//! or a signal, binding the fluent variable to application data and updating when that data changes.
63//! ```ignore
64//! # use vizia_core::prelude::*;
65//! # let mut cx = &mut Context::default();
66//! Label::new(cx, Localized::new("welcome").arg("user", "Jane"));
67//! ```
68//!
69//! ```ignore
70//! # use vizia_core::prelude::*;
71//! # let mut cx = &mut Context::default();
72//! #
73//! let user = Signal::new("Jane".to_string());
74//!
75//! Label::new(cx, Localized::new("welcome").arg("user", user));
76//! ```
77//!
78//! ## Attributes
79//! Messages can have named attributes that provide alternative translations. These are useful for UI elements that need multiple text values.
80//! Attributes must be preceded by a main message value:
81//! ```ftl
82//! file-dialog = File Dialog
83//! .title = Save File
84//! .save-button = Save
85//! ```
86//! To reference an attribute, use the `.attribute()` method:
87//! ```ignore
88//! # use vizia_core::prelude::*;
89//! # let mut cx = &mut Context::default();
90//! Label::new(cx, Localized::new("file-dialog").attribute("title"));
91//! ```
92//!
93//! ## Terms
94//! Terms are special variables prefixed with a hyphen that can be referenced in other messages. They're automatically
95//! available in all translations and are commonly used for product names or branding.
96//! ```ftl
97//! -brand = Vizia
98//! welcome = Welcome to { -brand }!
99//! ```
100//! Terms are automatically resolved when formatting, so no special configuration is needed when using them in messages.
101//!
102//! ## Message References
103//! Messages can reference other messages to maintain consistency and reduce duplication:
104//! ```ftl
105//! menu-save = Save
106//! help-menu-save = Click { menu-save } to save the file.
107//! ```
108//! Message references are automatically resolved by the localization system and work seamlessly with the [`Localized`] type.
109//! This is useful for keeping certain translations consistent across the interface and making maintenance easier.
110//!
111//! ## Selectors and Plurals
112//! Fluent selectors let you choose translations based on a variable value:
113//! ```ftl
114//! role-label = { $role ->
115//! [admin] You are signed in as an administrator.
116//! *[user] You are signed in as a user.
117//! }
118//! cart-summary = { $count ->
119//! [one] You have one item in your cart.
120//! *[other] You have { $count } items in your cart.
121//! }
122//! ```
123//! In Rust, pass the selector values with `arg(...)`:
124//! ```ignore
125//! # use vizia_core::prelude::*;
126//! # let mut cx = &mut Context::default();
127//! Label::new(cx, Localized::new("role-label").arg("role", "admin"));
128//! Label::new(cx, Localized::new("cart-summary").arg("count", 3));
129//! ```
130//!
131//! ## Number Formatting
132//! Numbers can be formatted in FTL with the built-in `NUMBER` function:
133//! ```ftl
134//! price = Your total is { NUMBER($amount) }
135//! ```
136//! In Rust, pass numbers directly as arguments (`NUMBER` also accepts a numeric string, and shows
137//! `NUMBER()` for a string that isn't a number):
138//! ```ignore
139//! # use vizia_core::prelude::*;
140//! # let mut cx = &mut Context::default();
141//! Label::new(cx, Localized::new("price").arg("amount", 99.99));
142//! ```
143//!
144//! For more control, use the helper functions to specify decimal places:
145//! ```ignore
146//! # use vizia_core::prelude::*;
147//! # let mut cx = &mut Context::default();
148//! Label::new(cx, Localized::new("price").arg("amount", number_with_fraction(99.99, 2)));
149//! ```
150//! Or for percentages:
151//! ```ignore
152//! # use vizia_core::prelude::*;
153//! # let mut cx = &mut Context::default();
154//! Label::new(cx, Localized::new("completion").arg("percent", percentage(0.75, 1)));
155//! ```
156//!
157//! Currency symbols and symbol placement are best handled in translations today.
158//! Pre-format the numeric portion in Rust or upstream and let each locale decide where the symbol belongs:
159//! ```ftl
160//! # en-US
161//! price-currency = Price: ${ $amount }
162//!
163//! # fr
164//! price-currency = Prix : { $amount } €
165//! ```
166//! ```ignore
167//! # use vizia_core::prelude::*;
168//! # let mut cx = &mut Context::default();
169//! Label::new(cx, Localized::new("price-currency").arg("amount", "99.99"));
170//! ```
171//!
172//! ## Date Formatting
173//! Dates can be formatted with locale-specific rules using the built-in `DATETIME` function in FTL.
174//! Pass [`jiff`] datetime values directly to `arg()` - the conversion to milliseconds is handled automatically:
175//! ```ignore
176//! # use vizia_core::prelude::*;
177//! # use jiff::Timestamp;
178//! # let mut cx = &mut Context::default();
179//! let now = Timestamp::now();
180//! Label::new(cx, Localized::new("event-date").arg("date", now));
181//! ```
182//!
183//! Both instants and civil datetimes are supported:
184//! - Instants like [`jiff::Timestamp`] or [`jiff::ZonedDateTime`] work directly; a `ZonedDateTime` is formatted as
185//! the instant it denotes, in UTC, whatever its time zone
186//! - Civil datetimes like [`jiff::civil::DateTime`] have no time zone and are automatically assumed to be in UTC
187//!
188//! For custom formatting, pre-format the date in Rust and pass the string to a message that uses it directly
189//! (`DATETIME` only formats a timestamp or a number of milliseconds, and shows `DATETIME()` for anything else):
190//! ```ftl
191//! event-date-text = Event date: { $date }
192//! ```
193//! ```ignore
194//! # use vizia_core::prelude::*;
195//! # let mut cx = &mut Context::default();
196//! let formatted_date = "April 13, 2026".to_string();
197//! Label::new(cx, Localized::new("event-date-text").arg("date", formatted_date));
198//! ```
199use crate::context::LocalizationContext;
200use crate::prelude::*;
201use crate::resource::LocalizationIssue;
202use fluent_bundle::FluentArgs;
203use fluent_bundle::FluentValue;
204use fluent_bundle::types::{FluentNumber, FluentNumberOptions};
205use hashbrown::HashMap;
206use jiff::civil;
207use jiff::tz::TimeZone;
208use jiff::{Timestamp, ZonedDateTime};
209use std::marker::PhantomData;
210use std::rc::Rc;
211use std::sync::Arc;
212
213/// Helper function for formatting a number with decimal places for localized display.
214///
215/// # Example
216/// ```ignore
217/// # use vizia_core::prelude::*;
218/// # let mut cx = &mut Context::default();
219/// Label::new(cx, Localized::new("price").arg("amount", number_with_fraction(99.99, 2)));
220/// ```
221pub fn number_with_fraction(value: f64, fraction_digits: usize) -> FluentNumber {
222 FluentNumber::new(
223 value,
224 FluentNumberOptions {
225 minimum_fraction_digits: Some(fraction_digits),
226 maximum_fraction_digits: Some(fraction_digits),
227 ..Default::default()
228 },
229 )
230}
231
232impl Res<FluentNumber> for FluentNumber {
233 fn get_value(&self, _: &impl DataContext) -> Self {
234 self.clone()
235 }
236}
237
238/// Helper function for formatting a number as a percentage for localized display.
239///
240/// # Example
241/// ```ignore
242/// # use vizia_core::prelude::*;
243/// # let mut cx = &mut Context::default();
244/// Label::new(cx, Localized::new("completion").arg("percent", percentage(0.75, 1)));
245/// ```
246pub fn percentage(value: f64, fraction_digits: usize) -> FluentNumber {
247 FluentNumber::new(
248 value * 100.0,
249 FluentNumberOptions {
250 minimum_fraction_digits: Some(fraction_digits),
251 maximum_fraction_digits: Some(fraction_digits),
252 ..Default::default()
253 },
254 )
255}
256
257/// Converts an instant to whole milliseconds since the Unix epoch, rounding toward negative infinity.
258fn timestamp_millis(timestamp: Timestamp) -> i64 {
259 timestamp.as_nanosecond().div_euclid(1_000_000) as i64
260}
261
262/// Wrapper for a jiff [`Timestamp`] that automatically converts to Fluent's expected millisecond format.
263///
264/// While this wrapper can be used, [`Timestamp`] and [`ZonedDateTime`] implement `Res` directly,
265/// so you can pass them to `arg()` without wrapping. A [`ZonedDateTime`] is converted to the instant it denotes,
266/// so its time zone does not affect the formatted value.
267///
268/// # Example
269/// ```ignore
270/// # use vizia_core::prelude::*;
271/// # use jiff::Timestamp;
272/// # let mut cx = &mut Context::default();
273/// let now = Timestamp::now();
274/// // Timestamps work directly with arg()
275/// Label::new(cx, Localized::new("event-date").arg("date", now));
276/// ```
277#[derive(Clone, Copy, Debug, PartialEq)]
278pub struct FluentDateTime(pub Timestamp);
279
280impl From<FluentDateTime> for FluentValue<'static> {
281 fn from(val: FluentDateTime) -> Self {
282 timestamp_millis(val.0).into()
283 }
284}
285
286impl Res<FluentDateTime> for FluentDateTime {
287 fn get_value(&self, _: &impl DataContext) -> Self {
288 *self
289 }
290}
291
292impl Res<FluentDateTime> for Timestamp {
293 fn get_value(&self, _: &impl DataContext) -> FluentDateTime {
294 FluentDateTime(*self)
295 }
296}
297
298impl Res<FluentDateTime> for ZonedDateTime {
299 fn get_value(&self, _: &impl DataContext) -> FluentDateTime {
300 FluentDateTime(self.timestamp())
301 }
302}
303
304/// Wrapper for a jiff civil [`DateTime`](civil::DateTime) that automatically converts to Fluent's expected
305/// millisecond format.
306///
307/// While this wrapper can be used, [`civil::DateTime`] implements `Res` directly,
308/// so you can pass it to `arg()` without wrapping. Note: assumes UTC timezone for the conversion.
309/// A civil datetime too close to the edge of the supported range to be placed in UTC converts to
310/// a Fluent error value.
311///
312/// # Example
313/// ```ignore
314/// # use vizia_core::prelude::*;
315/// # use jiff::{Timestamp, tz::TimeZone};
316/// # let mut cx = &mut Context::default();
317/// let now = Timestamp::now().to_zoned_datetime(TimeZone::UTC).datetime();
318/// // Civil datetimes work directly with arg() (assumes UTC)
319/// Label::new(cx, Localized::new("event-date").arg("date", now));
320/// ```
321#[derive(Clone, Copy, Debug, PartialEq)]
322pub struct FluentCivilDateTime(pub civil::DateTime);
323
324impl From<FluentCivilDateTime> for FluentValue<'static> {
325 fn from(val: FluentCivilDateTime) -> Self {
326 match TimeZone::UTC.to_timestamp(val.0) {
327 Ok(timestamp) => timestamp_millis(timestamp).into(),
328 Err(_) => FluentValue::Error,
329 }
330 }
331}
332
333impl Res<FluentCivilDateTime> for FluentCivilDateTime {
334 fn get_value(&self, _: &impl DataContext) -> Self {
335 *self
336 }
337}
338
339impl Res<FluentCivilDateTime> for civil::DateTime {
340 fn get_value(&self, _: &impl DataContext) -> FluentCivilDateTime {
341 FluentCivilDateTime(*self)
342 }
343}
344
345pub(crate) trait FluentStore {
346 fn get_val(&self, cx: &LocalizationContext) -> FluentValue<'static>;
347 fn make_clone(&self) -> Box<dyn FluentStore>;
348 fn bind(&self, cx: &mut Context, closure: Box<dyn Fn(&mut Context)>);
349}
350
351#[derive(Clone)]
352pub(crate) struct ResState<R, T> {
353 res: R,
354 _marker: PhantomData<T>,
355}
356
357impl<R, T> FluentStore for ResState<R, T>
358where
359 R: 'static + Clone + Res<T>,
360 T: 'static + Clone + Into<FluentValue<'static>>,
361{
362 fn get_val(&self, cx: &LocalizationContext) -> FluentValue<'static> {
363 self.res.get_value(cx).into()
364 }
365
366 fn make_clone(&self) -> Box<dyn FluentStore> {
367 Box::new(self.clone())
368 }
369
370 fn bind(&self, cx: &mut Context, closure: Box<dyn Fn(&mut Context)>) {
371 self.res.clone().set_or_bind(cx, move |cx, _| closure(cx));
372 }
373}
374
375/// A type which formats a localized message with any number of named arguments.
376pub struct Localized {
377 key: String,
378 attribute: Option<String>,
379 args: HashMap<String, Box<dyn FluentStore>>,
380 map: Rc<dyn Fn(&str) -> String + 'static>,
381}
382
383impl PartialEq for Localized {
384 fn eq(&self, other: &Self) -> bool {
385 self.key == other.key && self.attribute == other.attribute
386 }
387}
388
389impl Clone for Localized {
390 fn clone(&self) -> Self {
391 Self {
392 key: self.key.clone(),
393 attribute: self.attribute.clone(),
394 args: self.args.iter().map(|(k, v)| (k.clone(), v.make_clone())).collect(),
395 map: self.map.clone(),
396 }
397 }
398}
399
400impl Localized {
401 fn resolve_text(&self, cx: &LocalizationContext) -> String {
402 let requested_locale = cx.environment().locale.get();
403 let args = self.get_args(cx);
404 let mut saw_message = false;
405
406 for locale in cx.resource_manager.translation_locales(&requested_locale) {
407 let bundle = cx.resource_manager.current_translation(&locale);
408 let Some(message) = bundle.get_message(&self.key) else {
409 continue;
410 };
411 saw_message = true;
412
413 let value = if let Some(attr_name) = &self.attribute {
414 if let Some(attr) = message.get_attribute(attr_name) {
415 attr.value()
416 } else {
417 continue;
418 }
419 } else if let Some(value) = message.value() {
420 value
421 } else {
422 continue;
423 };
424
425 let mut err = vec![];
426 let res = bundle.format_pattern(value, Some(&args), &mut err);
427
428 if !err.is_empty() {
429 cx.resource_manager.report_localization_issue(LocalizationIssue::FormatError {
430 key: self.key.clone(),
431 locale: locale.to_string(),
432 details: format!("{:?}", err),
433 });
434 }
435
436 return (self.map)(&res);
437 }
438
439 if let Some(attr_name) = &self.attribute {
440 if saw_message {
441 cx.resource_manager.report_localization_issue(
442 LocalizationIssue::MissingAttribute {
443 key: self.key.clone(),
444 attribute: attr_name.clone(),
445 requested_locale: requested_locale.to_string(),
446 },
447 );
448 } else {
449 cx.resource_manager.report_localization_issue(LocalizationIssue::MissingMessage {
450 key: self.key.clone(),
451 requested_locale: requested_locale.to_string(),
452 });
453 }
454 (self.map)(&format!("{}.{}", self.key, attr_name))
455 } else {
456 cx.resource_manager.report_localization_issue(LocalizationIssue::MissingMessage {
457 key: self.key.clone(),
458 requested_locale: requested_locale.to_string(),
459 });
460 (self.map)(&self.key)
461 }
462 }
463
464 fn get_args(&self, cx: &LocalizationContext) -> FluentArgs {
465 let mut res = FluentArgs::new();
466 for (name, arg) in &self.args {
467 res.set(name.to_owned(), arg.get_val(cx));
468 }
469 res
470 }
471
472 /// Creates a new Localized type with a given key.
473 ///
474 /// The given key is used to retrieve a translation from a fluent bundle resource.
475 ///
476 /// # Example
477 /// ```no_run
478 /// # use vizia_core::prelude::*;
479 ///
480 /// # use vizia_winit::application::Application;
481 /// Application::new(|cx|{
482 /// Label::new(cx, Localized::new("key"));
483 /// })
484 /// .run();
485 pub fn new(key: &str) -> Self {
486 Self {
487 key: key.to_owned(),
488 attribute: None,
489 args: HashMap::new(),
490 map: Rc::new(|s| s.to_string()),
491 }
492 }
493
494 /// Sets a mapping function to apply to the translated text.
495 pub fn map(mut self, mapping: impl Fn(&str) -> String + 'static) -> Self {
496 self.map = Rc::new(mapping);
497
498 self
499 }
500
501 /// Selects a message attribute to translate instead of the message value.
502 ///
503 /// Messages can contain multiple attributes that define alternative translations.
504 /// This method allows you to select a specific attribute by name.
505 ///
506 /// # Example
507 /// ```no_run
508 /// # use vizia_core::prelude::*;
509 /// # use vizia_winit::application::Application;
510 /// Application::new(|cx|{
511 /// // Resolves the "title" attribute of the "dialog" message
512 /// Label::new(cx, Localized::new("dialog").attribute("title"));
513 /// })
514 /// .run();
515 pub fn attribute(mut self, attr_name: &str) -> Self {
516 self.attribute = Some(attr_name.to_owned());
517 self
518 }
519 ///
520 /// Takes a key name and a resource for the argument value.
521 ///
522 /// This accepts both plain values and reactive resources.
523 ///
524 /// # Example
525 /// ```no_run
526 /// # use vizia_core::prelude::*;
527 ///
528 /// # use vizia_winit::application::Application;
529 /// #
530 /// # struct AppData {
531 /// # value: i32,
532 /// # }
533 /// # impl Model for AppData {}
534 /// Application::new(|cx|{
535 ///
536 /// AppData {
537 /// value: 5,
538 /// }.build(cx);
539 ///
540 /// Label::new(cx, Localized::new("key").arg("value", AppData::value));
541 /// })
542 /// .run();
543 pub fn arg<R, T>(mut self, key: &str, res: R) -> Self
544 where
545 R: 'static + Clone + Res<T>,
546 T: 'static + Clone + Into<FluentValue<'static>>,
547 {
548 self.args.insert(key.to_owned(), Box::new(ResState { res, _marker: PhantomData }));
549 self
550 }
551}
552
553impl Res<String> for Localized {
554 fn get_value(&self, cx: &impl DataContext) -> String {
555 let cx = cx.localization_context().expect("Failed to get context");
556 self.resolve_text(&cx)
557 }
558
559 fn set_or_bind<F>(self, cx: &mut Context, closure: F)
560 where
561 F: 'static + Fn(&mut Context, Localized),
562 {
563 let current = cx.current();
564 let self2 = self.clone();
565 let closure = Arc::new(closure);
566 cx.with_current(current, |cx| {
567 let stores = self2.args.values().map(|x| x.make_clone()).collect::<Vec<_>>();
568 bind_recursive(cx, &stores, move |cx| {
569 let locale = cx.environment().locale;
570 let self3 = self2.clone();
571 let closure = closure.clone();
572 locale.set_or_bind(cx, move |cx, _| {
573 closure(cx, self3.clone());
574 });
575 });
576 });
577 }
578}
579
580fn bind_recursive<F>(cx: &mut Context, stores: &[Box<dyn FluentStore>], closure: F)
581where
582 F: 'static + Clone + Fn(&mut Context),
583{
584 if let Some((store, rest)) = stores.split_last() {
585 let rest = rest.iter().map(|x| x.make_clone()).collect::<Vec<_>>();
586 store.bind(
587 cx,
588 Box::new(move |cx| {
589 bind_recursive(cx, &rest, closure.clone());
590 }),
591 );
592 } else {
593 closure(cx);
594 }
595}
596
597impl<T: ToString> ToStringLocalized for T {
598 fn to_string_local(&self, _cx: &impl DataContext) -> String {
599 self.to_string()
600 }
601}
602
603/// A trait for converting from [Localized] to a `String` via a translation using fluent.
604pub trait ToStringLocalized {
605 /// Method for converting the current type to a `String` via a translation using fluent.
606 fn to_string_local(&self, cx: &impl DataContext) -> String;
607}
608
609impl ToStringLocalized for Localized {
610 fn to_string_local(&self, cx: &impl DataContext) -> String {
611 let cx = cx.localization_context().expect("Failed to get context");
612 self.resolve_text(&cx)
613 }
614}
615
616#[cfg(test)]
617mod tests {
618 use super::*;
619 use jiff::ToSpan;
620
621 #[test]
622 fn timestamp_converts_to_epoch_milliseconds() {
623 let timestamp = Timestamp::from_millisecond(1_700_000_000_123).unwrap();
624 let value: FluentValue<'static> = FluentDateTime(timestamp).into();
625 assert_eq!(value, FluentValue::from(1_700_000_000_123_i64));
626 }
627
628 #[test]
629 fn zoned_converts_to_the_same_instant_as_utc() {
630 let timestamp = Timestamp::from_millisecond(1_700_000_000_123).unwrap();
631 let zoned = timestamp.to_zoned_datetime(TimeZone::fixed(jiff::tz::offset(5)));
632 let value: FluentValue<'static> = zoned.get_value(&Context::default()).into();
633 assert_eq!(value, FluentValue::from(1_700_000_000_123_i64));
634 }
635
636 #[test]
637 fn timestamp_milliseconds_round_toward_negative_infinity() {
638 let timestamp = Timestamp::from_nanosecond(-1_000_500).unwrap();
639 let value: FluentValue<'static> = FluentDateTime(timestamp).into();
640 assert_eq!(value, FluentValue::from(-2_i64));
641 }
642
643 #[test]
644 fn civil_datetime_is_treated_as_utc() {
645 let datetime = civil::date(2023, 11, 14).at(22, 13, 20, 456_000_000);
646 let value: FluentValue<'static> = FluentCivilDateTime(datetime).into();
647 assert_eq!(value, FluentValue::from(1_700_000_000_456_i64));
648 }
649
650 #[test]
651 fn civil_datetime_outside_the_utc_range_is_a_fluent_error() {
652 let value: FluentValue<'static> = FluentCivilDateTime(civil::DateTime::MIN).into();
653 assert!(matches!(value, FluentValue::Error));
654 let value: FluentValue<'static> = FluentCivilDateTime(civil::DateTime::MAX).into();
655 assert!(matches!(value, FluentValue::Error));
656 }
657
658 #[test]
659 fn civil_datetime_is_accepted_up_to_the_timestamp_bounds() {
660 let convert = |datetime| -> FluentValue<'static> { FluentCivilDateTime(datetime).into() };
661
662 let latest = civil::date(9999, 12, 30).at(22, 0, 0, 0);
663 assert_eq!(convert(latest), FluentValue::from(253_402_207_200_000_i64));
664 assert!(matches!(convert(latest.saturating_add(1.second())), FluentValue::Error));
665
666 let earliest = civil::date(-9999, 1, 2).at(1, 59, 59, 0);
667 assert_eq!(convert(earliest), FluentValue::from(-377_705_023_201_000_i64));
668 assert!(matches!(convert(earliest.saturating_sub(1.second())), FluentValue::Error));
669 }
670
671 #[test]
672 fn missing_message_falls_back_to_key() {
673 let cx = Context::default();
674 cx.data::<Environment>().locale.set("en-US".parse().unwrap());
675
676 let text = Localized::new("missing-key").to_string_local(&cx);
677
678 assert_eq!(text, "missing-key");
679 }
680
681 #[test]
682 fn missing_attribute_falls_back_to_key_attribute() {
683 let mut cx = Context::default();
684 cx.data::<Environment>().locale.set("en-US".parse().unwrap());
685 cx.load_translation("en-US".parse().unwrap(), "dialog = File Dialog".to_string()).unwrap();
686
687 let text = Localized::new("dialog").attribute("title").to_string_local(&cx);
688
689 assert_eq!(text, "dialog.title");
690 }
691
692 #[test]
693 fn format_error_returns_partial_resolved_text() {
694 let mut cx = Context::default();
695 cx.data::<Environment>().locale.set("en-US".parse().unwrap());
696 cx.load_translation("en-US".parse().unwrap(), "welcome = Welcome, { $name }!".to_string())
697 .unwrap();
698
699 let text = Localized::new("welcome").to_string_local(&cx);
700 assert!(text.contains("Welcome"));
701 assert!(text.contains("$name"));
702 }
703
704 #[test]
705 fn falls_back_to_default_bundle_per_key() {
706 let mut cx = Context::default();
707 cx.data::<Environment>().locale.set("fr".parse().unwrap());
708
709 // Ensure the requested locale exists but does not contain the requested key.
710 cx.load_translation("fr".parse().unwrap(), "bonjour = Bonjour".to_string()).unwrap();
711
712 // Provide the requested key only in the default bundle.
713 cx.load_translation(
714 LanguageIdentifier::default(),
715 "greeting = Hello from default".to_string(),
716 )
717 .unwrap();
718
719 let text = Localized::new("greeting").to_string_local(&cx);
720
721 assert_eq!(text, "Hello from default");
722 }
723
724 #[test]
725 fn falls_back_to_default_bundle_for_attribute_when_message_exists_in_requested_locale() {
726 let mut cx = Context::default();
727 cx.data::<Environment>().locale.set("fr".parse().unwrap());
728
729 // Requested locale has the message but not the attribute.
730 cx.load_translation("fr".parse().unwrap(), "dialog = Dialogue".to_string()).unwrap();
731
732 // Default locale provides the missing attribute.
733 cx.load_translation(
734 LanguageIdentifier::default(),
735 "dialog = Dialog\n .title = Default Title".to_string(),
736 )
737 .unwrap();
738
739 let text = Localized::new("dialog").attribute("title").to_string_local(&cx);
740
741 assert_eq!(text, "Default Title");
742 }
743}