i18n_next/text.rs
1//! `Text` (DESIGN 4.3): a lazy translation, resolved each time it is shown, the way
2//! `resolveText` of `@i18n-micro/core` resolves the props of `<i18n-t>`; `parts` / `fold`
3//! follow `foldTemplate`. `Key` (4.4) is a `const` key that resolves through scope and the
4//! global instance.
5//!
6//! Resolution writes straight into the caller's writer: the template is read inside the
7//! snapshot (no copy), parameters go through a stack buffer, so `Display` into a reused
8//! buffer allocates nothing and `to_string` allocates once (a sizing pass first).
9
10use crate::args::{Arg, Args, Count, Hit, Small, escape_html};
11use crate::catalog::{Entry, Msg, hole_ranges, is_js_space};
12use crate::i18n::{I18n, View};
13use crate::scope::{self, Code};
14use std::borrow::Cow;
15use std::fmt;
16use std::sync::Arc;
17
18/// The custom plural rule of [`Text::plural_rule`].
19type Rule = Arc<dyn Fn(&PluralCtx<'_>) -> Option<String> + Send + Sync>;
20
21/// A translation shown later: the Rust counterpart of `<i18n-t>`.
22///
23/// Built by [`I18n::text`], [`View::text`] or the [`t!`](crate::t!) macro, with options that
24/// mirror the component's props. Nothing is looked up until it is shown: every `Display`
25/// resolves it again, so a `Text` kept in UI state follows `set_locale` and the
26/// [`scope`](crate::scope()) it is shown in. `'static + Send + Sync + Clone`.
27///
28/// ```
29/// use i18n_next::I18n;
30///
31/// let i18n = I18n::builder()
32/// .messages("en", None, r#"{"hi": "Hi, {name}!", "apples": "no apples | one apple | {count} apples"}"#)
33/// .messages("de", None, r#"{"hi": "Hallo, {name}!"}"#)
34/// .build()?;
35/// let hi = i18n.text("hi").arg("name", "Ann");
36/// assert_eq!(hi.to_string(), "Hi, Ann!");
37/// i18n.set_locale("de")?;
38/// assert_eq!(hi, "Hallo, Ann!"); // the same value, the new locale
39/// assert_eq!(i18n.text("apples").count(5).locale("en"), "5 apples");
40/// assert_eq!(i18n.text("nope").or("Default").to_string(), "Default");
41/// assert_eq!(i18n.text("nope").resolve(), None); // a miss without a default
42/// # Ok::<(), i18n_next::Error>(())
43/// ```
44///
45/// Resolution, as `resolveText`:
46/// - the key's text in the locale and page (explicit on the `Text`, else the nearest
47/// scope's, else the active locale and the root), interpolated with the arguments;
48/// - with [`count`](Text::count): the plural form `tc` picks, with `{count}`;
49/// - with [`number`](Text::number): `{number}` is the number formatted in the text's locale
50/// (`tn`), never escaped; the plural form and a custom rule are then not used (JS: the
51/// `number` prop wins over `plural`); [`date`](Text::date) (`{date}`, `td`) and
52/// [`relative`](Text::relative) (`{relativeDate}`, `tdr`) the same, one of the three
53/// at a time, in that order of precedence;
54/// - a miss calls `missing` and shows the [`or`](Text::or) default, else the key (both
55/// interpolated); a subtree shows the key;
56/// - [`html`](Text::html): text arguments are escaped (numbers and booleans are not), the
57/// translation is trusted, a key standing in for it is escaped;
58/// - [`hide_if_empty`](Text::hide_if_empty): blank text resolves to `None` and displays
59/// as the default (or nothing), as `<i18n-t>` renders it;
60/// - a `Text` argument without its own locale or page resolves in the outer one's (and on
61/// its instance, when it has none); under `html` it is escaped unless it is `html`
62/// itself; `missing` is called once per display, for the outer and the inner alike;
63/// - nesting stops at 64 levels: a deeper `Text` argument is dropped, so its
64/// placeholder shows as written (showing, cloning and dropping never recurse deeper).
65///
66/// `Display` honours width, fill and precision (`{:>8}`, `{:.2}`), building the string
67/// first; without them it writes straight into the formatter.
68#[derive(Clone)]
69pub struct Text {
70 key: Cow<'static, str>,
71 i18n: Option<I18n>,
72 locale: Option<Code>,
73 page: Option<Code>,
74 args: Args<'static>,
75 count: Option<Count>,
76 /// `{number}` / `{date}` / `{relativeDate}` (JS `number` / `date` / `relativeDate`
77 /// props): the value and the named format.
78 #[cfg(feature = "format")]
79 number: Option<Shown>,
80 default: Option<Cow<'static, str>>,
81 rule: Option<Rule>,
82 html: bool,
83 hide: bool,
84 /// Levels of `Text` arguments below this one (0: none), at most `MAX_NESTING`.
85 pub(crate) depth: u8,
86 /// [`Text::emit`], reached through this pointer from `Args` (a `Text` argument of
87 /// `t_with`): an app that never builds a `Text` does not link its resolution (~8 KB of
88 /// `.wasm`).
89 shown: fn(&Text, &mut dyn fmt::Write) -> fmt::Result,
90}
91
92/// The value a `Text` formats into its placeholder (JS `formatParams`).
93#[cfg(feature = "format")]
94#[derive(Debug, Clone, PartialEq)]
95enum Shown {
96 Number(crate::Number, Option<Cow<'static, str>>),
97 /// A date or a relative date: its formatter is reached through the value, so a `Text`
98 /// that never shows one links none of the date code (or the zones of `tz`).
99 When(crate::DateArg<'static>),
100}
101
102#[cfg(feature = "format")]
103impl Shown {
104 /// JS checks `number`, then `date`, then `relativeDate`: the first one set wins.
105 fn rank(&self) -> u8 {
106 match self {
107 Shown::Number(..) => 0,
108 Shown::When(d) => 1 + u8::from(d.is_relative()),
109 }
110 }
111}
112
113/// What a custom plural rule ([`Text::plural_rule`]) gets: JS `customPluralRule(key,
114/// count, params, locale, getter)`.
115#[derive(Debug)]
116#[non_exhaustive]
117pub struct PluralCtx<'a> {
118 /// The key of the `Text`.
119 pub key: &'a str,
120 /// The count, as JS `Number(plural)` holds it.
121 pub count: f64,
122 /// The locale the `Text` resolves in.
123 pub locale: &'a str,
124 text: &'a Text,
125 i18n: &'a I18n,
126 view: Option<&'a str>,
127 page: Option<&'a str>,
128 /// A comparison or a quiet frame: a miss is not reported.
129 quiet: bool,
130}
131
132impl PluralCtx<'_> {
133 /// The raw text of `key` in the same locale and page (JS `getter(key)`): not
134 /// interpolated; a miss calls `missing` and gives the `Text`'s default, else the key
135 /// (escaped under `html`).
136 #[must_use]
137 pub fn get(&self, key: &str) -> String {
138 if key.is_empty() {
139 return String::new();
140 }
141 let found = self
142 .i18n
143 .inner
144 .read(|s| match s.lookup(self.view, self.page, key) {
145 Some(e) => Ok(e.text().map(String::from)),
146 None => Err(s.locale.clone()),
147 });
148 match found {
149 Ok(Some(t)) => t,
150 Ok(None) => key_text(key, self.text.html),
151 Err(active) => {
152 if !self.quiet && !scope::quiet() {
153 self.i18n
154 .report(Some(self.view.unwrap_or(&active)), self.page, key);
155 }
156 match self.text.default_text() {
157 Some(d) => d.to_owned(),
158 None => key_text(key, self.text.html),
159 }
160 }
161 }
162 }
163}
164
165/// One piece of [`Text::parts`]: text (parameters filled in), or a placeholder no
166/// argument fills, for the caller to render.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub enum Part<'a> {
169 /// Text to show as is.
170 Text(Cow<'a, str>),
171 /// A `{name}` placeholder without an argument: a slot.
172 Slot(Cow<'a, str>),
173}
174
175/// A `const` translation key ([`key!`](crate::key)): `Display` resolves it through the
176/// nearest scope or the global instance, like `t!(key)`.
177///
178/// ```
179/// use i18n_next::{I18n, Key, key, scope};
180///
181/// const QUIT: Key = key!("menu.quit");
182/// let i18n = I18n::builder().messages("en", None, r#"{"menu": {"quit": "Quit {app}"}}"#).build()?;
183/// scope().instance(i18n).run(|| {
184/// assert_eq!(QUIT.args().arg("app", "Demo").to_string(), "Quit Demo");
185/// assert_eq!(format!("{QUIT}"), "Quit {app}");
186/// });
187/// # Ok::<(), i18n_next::Error>(())
188/// ```
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
190pub struct Key(&'static str);
191
192impl Key {
193 /// A key; `const`, allocates nothing.
194 #[must_use]
195 pub const fn new(key: &'static str) -> Key {
196 Key(key)
197 }
198
199 /// A [`Text`] of this key, to add arguments and options to.
200 #[must_use]
201 pub fn args(self) -> Text {
202 Text::new(Cow::Borrowed(self.0), None)
203 }
204}
205
206impl fmt::Display for Key {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 self.args().fmt(f)
209 }
210}
211
212/// Levels of nested `Text` arguments kept (see [`Text`]): enough for any real message, few
213/// enough that showing one never overflows a 1 MiB stack.
214pub(crate) const MAX_NESTING: u8 = 64;
215
216/// The text of a template, read inside the snapshot: placeholders found at load (a range
217/// of the raw text and its holes), found now (a default, the key), or none.
218#[derive(Clone, Copy)]
219enum Tpl<'s> {
220 Holes {
221 raw: &'s str,
222 start: usize,
223 end: usize,
224 holes: &'s [(u32, u32)],
225 },
226 Scan(&'s str),
227 Literal(&'s str),
228}
229
230enum Piece<'s> {
231 Lit(&'s str),
232 Hole(&'s str),
233}
234
235impl<'s> Tpl<'s> {
236 /// The literal runs and placeholders in order (a hole is `raw[s..e]` between braces).
237 fn pieces(self, f: &mut dyn FnMut(Piece<'_>) -> fmt::Result) -> fmt::Result {
238 match self {
239 Tpl::Literal(s) => f(Piece::Lit(s)),
240 Tpl::Scan(raw) => walk(raw, 0, raw.len(), hole_ranges(raw), f),
241 Tpl::Holes {
242 raw,
243 start,
244 end,
245 holes,
246 } => walk(
247 raw,
248 start,
249 end,
250 holes.iter().map(|&(s, e)| (s as usize, e as usize)),
251 f,
252 ),
253 }
254 }
255
256 /// Writes the template with each placeholder an argument fills replaced (JS
257 /// `interpolate`); the others stay as written.
258 fn write(self, out: &mut dyn fmt::Write, p: Params<'_>) -> fmt::Result {
259 self.pieces(&mut |piece| match piece {
260 Piece::Lit(s) => out.write_str(s),
261 Piece::Hole(name) => {
262 if !p.put(name, out)? {
263 out.write_char('{')?;
264 out.write_str(name)?;
265 out.write_char('}')?;
266 }
267 Ok(())
268 }
269 })
270 }
271
272 /// Whether the interpolated text is blank (JS `!text.trim()`): stops at the first
273 /// character that is not JS whitespace.
274 fn blank(self, p: Params<'_>) -> Result<bool, fmt::Error> {
275 let mut probe = NonBlank(false);
276 let p = Params { quiet: true, ..p };
277 match self.write(&mut probe, p) {
278 Err(_) if probe.0 => Ok(false),
279 Err(e) => Err(e),
280 Ok(()) => Ok(true),
281 }
282 }
283
284 /// Bytes [`Tpl::write`] produces, a nested `Text` counted as nothing.
285 fn measure(self, p: Params<'_>) -> usize {
286 let mut len = Len(0);
287 let p = Params { measure: true, ..p };
288 let _ = self.write(&mut len, p);
289 len.0
290 }
291}
292
293fn walk(
294 raw: &str,
295 start: usize,
296 end: usize,
297 holes: impl Iterator<Item = (usize, usize)>,
298 f: &mut dyn FnMut(Piece<'_>) -> fmt::Result,
299) -> fmt::Result {
300 let mut at = start;
301 for (s, e) in holes {
302 // A hole of the whole string outside the form's trimmed range is not the form's.
303 if s <= start || e >= end {
304 continue;
305 }
306 let Some(name) = raw.get(s..e) else {
307 continue;
308 };
309 f(Piece::Lit(raw.get(at..s - 1).unwrap_or("")))?;
310 f(Piece::Hole(name))?;
311 at = e + 1;
312 }
313 f(Piece::Lit(raw.get(at..end).unwrap_or("")))
314}
315
316/// Where placeholder values come from: the arguments (JS `params`, or `{ ...params }` when
317/// spread: a list then has no `{length}`), `{count}` on top for a plural.
318#[derive(Clone, Copy)]
319struct Params<'x> {
320 args: &'x Args<'static>,
321 count: Option<Count>,
322 spread: bool,
323 html: bool,
324 /// Sizing pass: a nested `Text` writes nothing.
325 measure: bool,
326 /// `{number}` / `{date}` / `{relativeDate}`, resolved in the snapshot.
327 #[cfg(feature = "format")]
328 number: Option<Fill<'x>>,
329 /// Blank check or comparison: a nested `Text` reports no miss.
330 quiet: bool,
331 /// What a nested `Text` inherits.
332 outer: &'x Outer<'x>,
333}
334
335/// A `{number}`, `{date}` or `{relativeDate}` ready to write.
336#[cfg(feature = "format")]
337#[derive(Clone, Copy)]
338enum Fill<'x> {
339 Number {
340 value: crate::Number,
341 options: &'x crate::format::NumberOptions,
342 loc: &'static crate::format::Loc,
343 },
344 When(&'x crate::DateArg<'static>),
345}
346
347#[cfg(feature = "format")]
348impl Fill<'_> {
349 fn name(&self) -> &'static str {
350 match self {
351 Fill::Number { .. } => "number",
352 Fill::When(d) if d.is_relative() => "relativeDate",
353 Fill::When(_) => "date",
354 }
355 }
356
357 /// Writes the value; a date in the outer `Text`'s instance and locale.
358 fn write(&self, outer: &Outer<'_>, out: &mut dyn fmt::Write) -> fmt::Result {
359 match *self {
360 Fill::Number {
361 value,
362 options,
363 loc,
364 } => crate::format::write(value, options, loc, out),
365 Fill::When(d) => d.write_in(outer.i18n, outer.locale.map(Code::as_str), out),
366 }
367 }
368}
369
370/// The instance, locale and page the outer `Text` resolves in.
371struct Outer<'x> {
372 i18n: Option<&'x I18n>,
373 locale: Option<&'x Code>,
374 page: Option<&'x Code>,
375}
376
377impl Params<'_> {
378 fn put(&self, name: &str, out: &mut dyn fmt::Write) -> Result<bool, fmt::Error> {
379 #[cfg(feature = "format")]
380 if let Some(n) = &self.number
381 && name == n.name()
382 {
383 n.write(self.outer, out)?;
384 return Ok(true);
385 }
386 if let Some(c) = self.count
387 && name == "count"
388 {
389 let mut b = Small::new();
390 c.write(&mut b);
391 out.write_str(b.as_str())?;
392 return Ok(true);
393 }
394 let value = if self.spread {
395 self.args.spread(name)
396 } else {
397 self.args.find(name)
398 };
399 let v = match value {
400 Some(Hit::Arg(v)) => v,
401 Some(Hit::Len(n)) => return Arg::Int(n).emit(out, false).map(|()| true),
402 None => return Ok(false),
403 };
404 match v {
405 Arg::Text(_) if self.measure => Ok(true),
406 Arg::Text(_) => self.nested(v, out).map(|()| true),
407 #[cfg(feature = "format")]
408 Arg::Number { value, format } => {
409 let o = self.outer;
410 crate::format::api::write_in(
411 o.i18n,
412 o.locale.map(Code::as_str),
413 *value,
414 format.as_deref(),
415 out,
416 )
417 .map(|()| true)
418 }
419 #[cfg(feature = "format")]
420 Arg::Date(d) => {
421 let o = self.outer;
422 d.write_in(o.i18n, o.locale.map(Code::as_str), out)
423 .map(|()| true)
424 }
425 v => v.emit(out, self.html).map(|()| true),
426 }
427 }
428}
429
430impl Params<'_> {
431 /// A nested `Text`, written in a frame of the outer one's instance, locale and page.
432 /// Out of line: `put` stays small enough to inline into every hole.
433 #[inline(never)]
434 fn nested(&self, v: &Arg<'_>, out: &mut dyn fmt::Write) -> fmt::Result {
435 let o = self.outer;
436 scope::nest(o.i18n, o.locale, o.page, self.quiet, || {
437 v.emit(out, self.html)
438 })
439 }
440}
441
442/// Fails at the first character that is not JS whitespace.
443struct NonBlank(bool);
444
445impl fmt::Write for NonBlank {
446 fn write_str(&mut self, s: &str) -> fmt::Result {
447 if s.chars().all(is_js_space) {
448 Ok(())
449 } else {
450 self.0 = true;
451 Err(fmt::Error)
452 }
453 }
454}
455
456struct Len(usize);
457
458impl fmt::Write for Len {
459 fn write_str(&mut self, s: &str) -> fmt::Result {
460 self.0 += s.len();
461 Ok(())
462 }
463}
464
465/// Compares what is written with a string, without building it.
466struct Same<'a> {
467 rest: &'a str,
468 ok: bool,
469}
470
471impl fmt::Write for Same<'_> {
472 fn write_str(&mut self, s: &str) -> fmt::Result {
473 match self.rest.strip_prefix(s) {
474 Some(rest) => self.rest = rest,
475 None => self.ok = false,
476 }
477 if self.ok { Ok(()) } else { Err(fmt::Error) }
478 }
479}
480
481/// The placeholder value of `shown` in the snapshot, in `locale` (the active one when
482/// `None`); a named format nowhere to be found warns and formats with the defaults.
483#[cfg(feature = "format")]
484fn fill<'x>(s: &'x crate::i18n::Snapshot, locale: Option<&str>, shown: &'x Shown) -> Fill<'x> {
485 let loc = locale.map_or(s.number, |c| s.number_of(c));
486 let code = locale.unwrap_or(&s.locale);
487 match shown {
488 Shown::Number(value, name) => {
489 let options = name.as_deref().and_then(|n| s.meta.named_number(code, n));
490 if options.is_none()
491 && let Some(n) = name
492 {
493 crate::trace::missing_format("number", n, code);
494 }
495 Fill::Number {
496 value: *value,
497 options: options.unwrap_or(&crate::format::NumberOptions::DEFAULT),
498 loc,
499 }
500 }
501 Shown::When(d) => Fill::When(d),
502 }
503}
504
505/// JS `keyText`: the key standing in for a translation, escaped under `html`.
506fn key_text(key: &str, html: bool) -> String {
507 let mut out = String::new();
508 if html {
509 let _ = escape_html(&mut out, key);
510 } else {
511 out.push_str(key);
512 }
513 out
514}
515
516fn needs_escape(s: &str) -> bool {
517 s.bytes()
518 .any(|b| matches!(b, b'&' | b'<' | b'>' | b'"' | b'\''))
519}
520
521impl Text {
522 pub(crate) fn new(key: Cow<'static, str>, i18n: Option<I18n>) -> Text {
523 Text {
524 key,
525 i18n,
526 locale: None,
527 page: None,
528 args: Args::new(),
529 count: None,
530 #[cfg(feature = "format")]
531 number: None,
532 default: None,
533 rule: None,
534 html: false,
535 hide: false,
536 depth: 0,
537 shown: Text::emit,
538 }
539 }
540
541 /// The displayed text through [`Text::shown`] (see there).
542 pub(crate) fn show(&self, out: &mut dyn fmt::Write) -> fmt::Result {
543 (self.shown)(self, out)
544 }
545
546 /// Adds the value of `{name}` (JS `params[name]`): text, a number, a boolean, another
547 /// `Text`. Up to four arguments are stored inline, without allocating.
548 #[must_use]
549 pub fn arg(
550 mut self,
551 name: impl Into<Cow<'static, str>>,
552 value: impl Into<Arg<'static>>,
553 ) -> Self {
554 let value = value.into();
555 if let Arg::Text(t) = &value {
556 if t.depth >= MAX_NESTING {
557 return self;
558 }
559 self.depth = self.depth.max(t.depth + 1);
560 }
561 self.args.push_named(name.into(), value);
562 self
563 }
564
565 /// Adds positional values `{0}`, `{1}`… and `{length}` (a JS array as `params`).
566 #[must_use]
567 pub fn args<I>(mut self, items: I) -> Self
568 where
569 I: IntoIterator,
570 I::Item: Into<Arg<'static>>,
571 {
572 let mut depth = self.depth;
573 self.args
574 .extend_list(items.into_iter().map(Into::into).inspect(|a| {
575 if let Arg::Text(t) = a
576 && t.depth < MAX_NESTING
577 {
578 depth = depth.max(t.depth + 1);
579 }
580 }));
581 self.depth = depth;
582 self
583 }
584
585 /// Picks the plural form for `n` and fills `{count}` (JS `plural`), as `tc` does.
586 #[must_use]
587 pub fn count(mut self, n: impl Into<Count>) -> Self {
588 self.count = Some(n.into());
589 self
590 }
591
592 /// Fills `{number}` with `n` formatted in the text's locale with the default options
593 /// (JS `<i18n-t :number>`, `tn(number)`); not escaped under [`html`](Text::html). Set,
594 /// it replaces the plural form: [`count`](Text::count) and a custom rule are not used.
595 /// Feature `format`.
596 ///
597 /// ```
598 /// use i18n_next::I18n;
599 ///
600 /// let i18n = I18n::builder()
601 /// .messages("en", None, r#"{"total": "Total: {number}"}"#)
602 /// .messages("de", None, r#"{"total": "Summe: {number}"}"#)
603 /// .build()?;
604 /// assert_eq!(i18n.text("total").number(1234.5), "Total: 1,234.5");
605 /// assert_eq!(i18n.text("total").number(1234.5).locale("de"), "Summe: 1.234,5");
606 /// # Ok::<(), i18n_next::Error>(())
607 /// ```
608 #[cfg(feature = "format")]
609 #[must_use]
610 pub fn number(self, n: impl Into<crate::Number>) -> Self {
611 self.set_shown(Shown::Number(n.into(), None))
612 }
613
614 /// Sets what the text formats, unless a stronger one is set (JS: `number`, then `date`,
615 /// then `relativeDate`).
616 #[cfg(feature = "format")]
617 fn set_shown(mut self, s: Shown) -> Self {
618 if self
619 .number
620 .as_ref()
621 .is_none_or(|old| old.rank() >= s.rank())
622 {
623 self.number = Some(s);
624 }
625 self
626 }
627
628 /// [`Text::number`] with the named format `name` of the text's locale
629 /// ([`I18n::tn_as`]); a missing name warns and formats with the defaults.
630 #[cfg(feature = "format")]
631 #[must_use]
632 pub fn number_as(
633 self,
634 n: impl Into<crate::Number>,
635 name: impl Into<Cow<'static, str>>,
636 ) -> Self {
637 self.set_shown(Shown::Number(n.into(), Some(name.into())))
638 }
639
640 /// Fills `{date}` with `t` formatted in the text's locale with the default options (JS
641 /// `<i18n-t :date>`, `td(date)`); like [`number`](Text::number) it replaces the plural
642 /// form, and a number set as well wins (JS checks `number` first). Feature `format`.
643 ///
644 /// ```
645 /// use i18n_next::I18n;
646 ///
647 /// let i18n = I18n::builder()
648 /// .time_zone("UTC")
649 /// .messages("en", None, r#"{"due": "Due {date}"}"#)
650 /// .messages("de", None, r#"{"due": "Fällig am {date}"}"#)
651 /// .build()?;
652 /// assert_eq!(i18n.text("due").date(1_704_428_640_000i64), "Due 1/5/2024");
653 /// assert_eq!(i18n.text("due").date(1_704_428_640_000i64).locale("de"), "Fällig am 5.1.2024");
654 /// # Ok::<(), i18n_next::Error>(())
655 /// ```
656 #[cfg(feature = "format")]
657 #[must_use]
658 pub fn date(self, t: impl Into<crate::Timestamp>) -> Self {
659 self.set_shown(Shown::When(crate::DateArg::date(t.into(), None)))
660 }
661
662 /// [`Text::date`] with the named date format `name` of the text's locale
663 /// ([`I18n::td_as`]); a missing name warns and formats with the defaults.
664 #[cfg(feature = "format")]
665 #[must_use]
666 pub fn date_as(
667 self,
668 t: impl Into<crate::Timestamp>,
669 name: impl Into<Cow<'static, str>>,
670 ) -> Self {
671 self.set_shown(Shown::When(crate::DateArg::date(
672 t.into(),
673 Some(name.into()),
674 )))
675 }
676
677 /// Fills `{relativeDate}` with `t` relative to the instance's clock (JS `<i18n-t
678 /// :relative-date>`, `tdr(date)`): `3 days ago`. A number or date set as well wins.
679 /// Feature `format`.
680 ///
681 /// ```
682 /// use i18n_next::I18n;
683 ///
684 /// let now = 1_704_428_640_000i64;
685 /// let i18n = I18n::builder()
686 /// .clock(move || now)
687 /// .messages("en", None, r#"{"seen": "Seen {relativeDate}"}"#)
688 /// .build()?;
689 /// assert_eq!(i18n.text("seen").relative(now - 120_000), "Seen 2 minutes ago");
690 /// # Ok::<(), i18n_next::Error>(())
691 /// ```
692 #[cfg(feature = "format")]
693 #[must_use]
694 pub fn relative(self, t: impl Into<crate::Timestamp>) -> Self {
695 self.set_shown(Shown::When(crate::DateArg::relative(t.into())))
696 }
697
698 /// The text shown on a miss (JS `defaultValue`), interpolated; empty counts as none.
699 #[must_use]
700 pub fn or(mut self, default: impl Into<Cow<'static, str>>) -> Self {
701 self.default = Some(default.into());
702 self
703 }
704
705 /// Blank text resolves to `None` and displays as the default, or nothing (JS
706 /// `hideIfEmpty`).
707 #[must_use]
708 pub fn hide_if_empty(mut self) -> Self {
709 self.hide = true;
710 self
711 }
712
713 /// Replaces the plural rule (JS `customPluralRule`): with a [`count`](Text::count), the
714 /// rule's answer is the text as is (not interpolated); `None` is empty.
715 ///
716 /// ```
717 /// use i18n_next::I18n;
718 ///
719 /// let i18n = I18n::builder().messages("en", None, r#"{"cats": "cat|cats"}"#).build()?;
720 /// let cats = i18n.text("cats").count(3).plural_rule(|c| {
721 /// let forms = c.get(c.key);
722 /// let mut it = forms.split('|');
723 /// let form = if c.count == 1.0 { it.next() } else { it.nth(1) };
724 /// form.map(|f| format!("{} {f}", c.count))
725 /// });
726 /// assert_eq!(cats.to_string(), "3 cats");
727 /// # Ok::<(), i18n_next::Error>(())
728 /// ```
729 #[must_use]
730 pub fn plural_rule(
731 mut self,
732 rule: impl Fn(&PluralCtx<'_>) -> Option<String> + Send + Sync + 'static,
733 ) -> Self {
734 self.rule = Some(Arc::new(rule));
735 self
736 }
737
738 /// Reads this page (its layer, then the root), over any scope's page.
739 #[must_use]
740 pub fn page(mut self, name: impl Into<Cow<'static, str>>) -> Self {
741 self.page = Some(Code::from(name.into()));
742 self
743 }
744
745 /// Resolves in this locale (as [`I18n::with_locale`]), over any scope's locale.
746 #[must_use]
747 pub fn locale(mut self, code: impl Into<Cow<'static, str>>) -> Self {
748 self.locale = Some(Code::from(code.into()));
749 self
750 }
751
752 /// The result goes into markup (JS `html`): text arguments are escaped, the
753 /// translation is not; a key standing in for a missing translation is.
754 #[must_use]
755 pub fn html(mut self) -> Self {
756 self.html = true;
757 self
758 }
759
760 /// The text, `None` when the key is missing (or a subtree) and there is no default,
761 /// or when [`hide_if_empty`](Text::hide_if_empty) hides it. One allocation.
762 #[must_use]
763 pub fn resolve(&self) -> Option<String> {
764 let (out, keyed, hidden) = self.sized();
765 (!keyed && !hidden).then_some(out)
766 }
767
768 /// The displayed text in one allocation: what `Display` writes, sized first.
769 #[allow(clippy::inherent_to_string_shadow_display)] // same text, exact capacity
770 #[must_use]
771 pub fn to_string(&self) -> String {
772 let (out, _, hidden) = self.sized();
773 if hidden {
774 return self.default_text().map(str::to_owned).unwrap_or_default();
775 }
776 out
777 }
778
779 /// Appends the displayed text to `out` (what `Display` writes), allocating nothing.
780 ///
781 /// # Errors
782 /// Only what `out` returns.
783 pub fn write_to(&self, out: &mut impl fmt::Write) -> fmt::Result {
784 self.emit(out)
785 }
786
787 /// Whether `hide_if_empty` hides the text (callers check `self.hide` first). When it
788 /// does and there are `Text` arguments, they are written once more to nowhere: the
789 /// blank check is quiet, so this is where their misses are reported (once).
790 fn hidden(&self, tpl: Tpl<'_>, p: Params<'_>) -> Result<bool, fmt::Error> {
791 if !tpl.blank(p)? {
792 return Ok(false);
793 }
794 if self.depth > 0 {
795 let _ = tpl.write(&mut Len(0), p);
796 }
797 Ok(true)
798 }
799
800 /// The template in pieces for rich text: runs of text (arguments filled in) and
801 /// [`Part::Slot`]s for placeholders no argument fills.
802 ///
803 /// ```
804 /// use i18n_next::{I18n, Part};
805 ///
806 /// let i18n = I18n::builder().messages("en", None, r#"{"terms": "I accept the {link}, {who}"}"#).build()?;
807 /// let parts: Vec<Part> = i18n.text("terms").arg("who", "Ann").parts().collect();
808 /// assert_eq!(parts, [Part::Text("I accept the ".into()), Part::Slot("link".into()), Part::Text(", Ann".into())]);
809 /// # Ok::<(), i18n_next::Error>(())
810 /// ```
811 pub fn parts(&self) -> impl Iterator<Item = Part<'static>> + use<> {
812 self.split(None).into_iter()
813 }
814
815 /// Folds the template into your own nodes (JS `foldTemplate`): a placeholder with a
816 /// slot becomes the slot's node; else its argument, else the placeholder as written,
817 /// joins the surrounding text, which `text` turns into a node. Empty runs are skipped.
818 ///
819 /// ```
820 /// use i18n_next::I18n;
821 ///
822 /// let i18n = I18n::builder().messages("en", None, r#"{"terms": "I accept the {link}."}"#).build()?;
823 /// let nodes = i18n.text("terms").fold(|t| format!("<{t}>"), &[("link", &|| "[terms]".to_owned())]);
824 /// assert_eq!(nodes, ["<I accept the >", "[terms]", "<.>"]);
825 /// # Ok::<(), i18n_next::Error>(())
826 /// ```
827 pub fn fold<T>(
828 &self,
829 mut text: impl FnMut(&str) -> T,
830 slots: &[(&str, &dyn Fn() -> T)],
831 ) -> Vec<T> {
832 let names: Vec<&str> = slots.iter().map(|(n, _)| *n).collect();
833 self.split(Some(&names))
834 .into_iter()
835 .filter_map(|part| match part {
836 Part::Text(s) => Some(text(&s)),
837 Part::Slot(name) => slots.iter().find(|(n, _)| *n == name).map(|(_, f)| f()),
838 })
839 .collect()
840 }
841
842 /// Text runs and slots: with `slots`, a placeholder is a slot only when named there
843 /// (and wins over an argument); with `None` (`parts`), when no argument fills it.
844 fn split(&self, slots: Option<&[&str]>) -> Vec<Part<'static>> {
845 let mut parts = Vec::new();
846 let mut buf = String::new();
847 let mut hidden = false;
848 let _ = self.with_tpl(false, &mut |tpl, p| {
849 if self.hide && self.hidden(tpl, p)? {
850 hidden = true;
851 return Ok(());
852 }
853 tpl.pieces(&mut |piece| {
854 match piece {
855 Piece::Lit(s) => buf.push_str(s),
856 Piece::Hole(name) => {
857 let slot = if let Some(slots) = slots
858 && slots.contains(&name)
859 {
860 true
861 } else if slots.is_none() {
862 !p.put(name, &mut buf)?
863 } else {
864 if !p.put(name, &mut buf)? {
865 buf.push('{');
866 buf.push_str(name);
867 buf.push('}');
868 }
869 false
870 };
871 if slot {
872 if !buf.is_empty() {
873 parts.push(Part::Text(Cow::Owned(std::mem::take(&mut buf))));
874 }
875 parts.push(Part::Slot(Cow::Owned(name.to_owned())));
876 }
877 }
878 }
879 Ok(())
880 })
881 });
882 if hidden {
883 parts.clear();
884 buf = self.default_text().map(str::to_owned).unwrap_or_default();
885 }
886 if !buf.is_empty() {
887 parts.push(Part::Text(Cow::Owned(buf)));
888 }
889 parts
890 }
891
892 /// The default when it counts (JS `defaultValue ||`).
893 fn default_text(&self) -> Option<&str> {
894 self.default.as_deref().filter(|d| !d.is_empty())
895 }
896
897 /// `Display`: the text, or the default when hidden.
898 pub(crate) fn emit(&self, out: &mut dyn fmt::Write) -> fmt::Result {
899 self.emit_as(out, false)
900 }
901
902 /// [`Text::emit`]; `quiet`: a comparison, no miss is reported.
903 fn emit_as(&self, out: &mut dyn fmt::Write, quiet: bool) -> fmt::Result {
904 let mut hidden = false;
905 self.with_tpl(quiet, &mut |tpl, p| {
906 if self.hide && self.hidden(tpl, p)? {
907 hidden = true;
908 return Ok(());
909 }
910 tpl.write(out, p)
911 })?;
912 match self.default_text() {
913 Some(d) if hidden => out.write_str(d),
914 _ => Ok(()),
915 }
916 }
917
918 /// The text in one exactly sized `String` (a nested `Text` may grow it), whether the key
919 /// stood in for it, whether it is hidden.
920 fn sized(&self) -> (String, bool, bool) {
921 let mut out = String::new();
922 let mut hidden = false;
923 let keyed = self.with_tpl(false, &mut |tpl, p| {
924 if self.hide && self.hidden(tpl, p)? {
925 hidden = true;
926 return Ok(());
927 }
928 out.reserve_exact(tpl.measure(p));
929 tpl.write(&mut out, p)
930 });
931 (out, keyed.unwrap_or(false), hidden)
932 }
933
934 /// Structural equality (an [`Arg`] holding a `Text`).
935 pub(crate) fn same(&self, other: &Text) -> bool {
936 let rule = match (&self.rule, &other.rule) {
937 (Some(a), Some(b)) => Arc::ptr_eq(a, b),
938 (a, b) => a.is_none() && b.is_none(),
939 };
940 let i18n = match (&self.i18n, &other.i18n) {
941 (Some(a), Some(b)) => Arc::ptr_eq(&a.inner, &b.inner),
942 (a, b) => a.is_none() && b.is_none(),
943 };
944 self.key == other.key
945 && i18n
946 && rule
947 && self.locale == other.locale
948 && self.page == other.page
949 && self.args.same(&other.args)
950 && self.count == other.count
951 && self.same_number(other)
952 && self.default == other.default
953 && self.html == other.html
954 && self.hide == other.hide
955 }
956
957 #[cfg(feature = "format")]
958 fn same_number(&self, other: &Text) -> bool {
959 self.number == other.number
960 }
961
962 #[cfg(not(feature = "format"))]
963 fn same_number(&self, _: &Text) -> bool {
964 true
965 }
966
967 /// The count, unless a number replaces the plural form (JS: `number` wins over `plural`).
968 fn plural_count(&self) -> Option<Count> {
969 #[cfg(feature = "format")]
970 if self.number.is_some() {
971 return None;
972 }
973 self.count
974 }
975
976 /// Whether this `Text` is `html` (a nested one is then not escaped again).
977 pub(crate) fn is_html(&self) -> bool {
978 self.html
979 }
980
981 /// Resolves the template and hands it to `f` once, inside the catalog snapshot; then
982 /// reports a miss (also when `f` failed), unless `quiet` or inside a quiet frame.
983 /// `Ok(true)`: the key stands in for the text.
984 fn with_tpl(
985 &self,
986 quiet: bool,
987 f: &mut dyn FnMut(Tpl<'_>, Params<'_>) -> fmt::Result,
988 ) -> Result<bool, fmt::Error> {
989 let (scoped, scope_locale, scope_page, quiet_frame) = scope::current(
990 self.i18n.is_none(),
991 self.locale.is_none(),
992 self.page.is_none(),
993 );
994 let locale_code = self.locale.as_ref().or(scope_locale.as_ref());
995 let page_code = self.page.as_ref().or(scope_page.as_ref());
996 let locale = locale_code.map(Code::as_str);
997 let page = page_code.map(Code::as_str);
998 let key = &*self.key;
999 let global: Option<&I18n> = scope::global_instance();
1000 let instance = self.i18n.as_ref().or(scoped.as_ref()).or(global);
1001 let outer = Outer {
1002 i18n: instance,
1003 locale: locale_code,
1004 page: page_code,
1005 };
1006 let plain = Params {
1007 args: &self.args,
1008 count: None,
1009 // `escapeParams` builds an object: a list loses `{length}`.
1010 // `{ ...params, number }` is a spread too
1011 spread: self.html || self.plural_count() != self.count,
1012 html: self.html,
1013 measure: false,
1014 #[cfg(feature = "format")]
1015 number: None,
1016 quiet,
1017 outer: &outer,
1018 };
1019 let count = self.plural_count();
1020 let params = match count {
1021 Some(c) => Params {
1022 count: Some(c),
1023 spread: true,
1024 ..plain
1025 },
1026 None => plain,
1027 };
1028 let Some(i18n) = instance else {
1029 scope::uninstalled(key);
1030 return self
1031 .fallback(f, params)
1032 .map(|keyed| keyed && !key.is_empty());
1033 };
1034 if let (Some(count), Some(rule)) = (count, &self.rule) {
1035 let active = locale.is_none().then(|| i18n.locale());
1036 let ctx = PluralCtx {
1037 key,
1038 count: count.as_f64(),
1039 locale: locale.or(active.as_deref()).unwrap_or(""),
1040 text: self,
1041 i18n,
1042 view: locale,
1043 page,
1044 quiet,
1045 };
1046 let answer = rule(&ctx).unwrap_or_default();
1047 return f(Tpl::Literal(&answer), params).map(|()| false);
1048 }
1049 if key.is_empty() {
1050 // JS `t('')` is `''`, never a miss.
1051 return f(Tpl::Literal(""), params).map(|()| false);
1052 }
1053 let mut miss = None;
1054 let mut keyed = false;
1055 let read = i18n.inner.read(|s| {
1056 #[cfg(feature = "format")]
1057 let params = match &self.number {
1058 Some(shown) => Params {
1059 number: Some(fill(s, locale, shown)),
1060 ..params
1061 },
1062 None => params,
1063 };
1064 let found = s.lookup(locale, page, key);
1065 if let Some(count) = count {
1066 let plural = match locale {
1067 None => s.plural,
1068 Some(code) => s.plural_of(code),
1069 };
1070 match found {
1071 Some(Entry::Msg(Msg::Text(t))) => {
1072 let (start, end) = t.single_range();
1073 return f(
1074 Tpl::Holes {
1075 raw: t.raw,
1076 start,
1077 end,
1078 holes: t.hole_slice(),
1079 },
1080 params,
1081 );
1082 }
1083 Some(Entry::Msg(Msg::Plural(p))) => {
1084 return match p.form(count, plural) {
1085 Some((start, end, holes)) => f(
1086 Tpl::Holes {
1087 raw: p.text.raw,
1088 start,
1089 end,
1090 holes,
1091 },
1092 params,
1093 ),
1094 None => f(Tpl::Literal(""), params),
1095 };
1096 }
1097 // a number is its own one form; a boolean or a subtree has none
1098 Some(Entry::Value(v)) if !matches!(&**v, "true" | "false") => {
1099 return f(Tpl::Literal(v), params);
1100 }
1101 Some(_) => {}
1102 None => miss = Some(s.locale.clone()),
1103 }
1104 } else {
1105 match found {
1106 Some(Entry::Msg(Msg::Text(t))) => {
1107 return f(
1108 Tpl::Holes {
1109 raw: t.raw,
1110 start: 0,
1111 end: t.raw.len(),
1112 holes: t.hole_slice(),
1113 },
1114 params,
1115 );
1116 }
1117 Some(Entry::Msg(Msg::Plural(p))) => {
1118 let t = &p.text;
1119 return f(
1120 Tpl::Holes {
1121 raw: t.raw,
1122 start: 0,
1123 end: t.raw.len(),
1124 holes: t.hole_slice(),
1125 },
1126 params,
1127 );
1128 }
1129 Some(Entry::Value(v)) => return f(Tpl::Literal(v), params),
1130 // JS shows `String(subtree)`; Rust the key, as `t` does
1131 Some(Entry::Node) => {
1132 keyed = true;
1133 return self.key_tpl(f, params);
1134 }
1135 None => miss = Some(s.locale.clone()),
1136 }
1137 }
1138 keyed = self.fallback(f, params)?;
1139 Ok(())
1140 });
1141 if let Some(active) = miss
1142 && !quiet
1143 && !quiet_frame
1144 {
1145 i18n.report(Some(locale.unwrap_or(&active)), page, key);
1146 }
1147 read.map(|()| keyed)
1148 }
1149
1150 /// The default, else the key (escaped under `html`), as the template; `Ok(true)` when
1151 /// it is the key.
1152 fn fallback(
1153 &self,
1154 f: &mut dyn FnMut(Tpl<'_>, Params<'_>) -> fmt::Result,
1155 params: Params<'_>,
1156 ) -> Result<bool, fmt::Error> {
1157 if let Some(d) = self.default_text() {
1158 return f(Tpl::Scan(d), params).map(|()| false);
1159 }
1160 self.key_tpl(f, params).map(|()| true)
1161 }
1162
1163 /// The key (escaped under `html`) as the template (JS `keyText`).
1164 fn key_tpl(
1165 &self,
1166 f: &mut dyn FnMut(Tpl<'_>, Params<'_>) -> fmt::Result,
1167 params: Params<'_>,
1168 ) -> fmt::Result {
1169 let key = &*self.key;
1170 if self.html && needs_escape(key) {
1171 f(Tpl::Scan(&key_text(key, true)), params)
1172 } else {
1173 f(Tpl::Scan(key), params)
1174 }
1175 }
1176}
1177
1178impl fmt::Display for Text {
1179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180 if f.width().is_some() || f.precision().is_some() {
1181 return f.pad(&self.to_string());
1182 }
1183 self.emit(f)
1184 }
1185}
1186
1187impl fmt::Debug for Text {
1188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1189 let mut d = f.debug_struct("Text");
1190 d.field("key", &self.key);
1191 if self.i18n.is_some() {
1192 d.field("instance", &"explicit");
1193 }
1194 if let Some(l) = &self.locale {
1195 d.field("locale", &l.as_str());
1196 }
1197 if let Some(p) = &self.page {
1198 d.field("page", &p.as_str());
1199 }
1200 if !self.args.is_empty() {
1201 d.field("args", &self.args);
1202 }
1203 if let Some(c) = &self.count {
1204 d.field("count", c);
1205 }
1206 #[cfg(feature = "format")]
1207 if let Some(n) = &self.number {
1208 match n {
1209 Shown::Number(v, name) => d.field("number", &(v, name)),
1210 Shown::When(v) => d.field("date", v),
1211 };
1212 }
1213 if let Some(o) = &self.default {
1214 d.field("or", o);
1215 }
1216 if self.rule.is_some() {
1217 d.field("plural_rule", &"custom");
1218 }
1219 if self.html {
1220 d.field("html", &true);
1221 }
1222 if self.hide {
1223 d.field("hide_if_empty", &true);
1224 }
1225 d.finish()
1226 }
1227}
1228
1229/// Compares the displayed text, without building it.
1230impl PartialEq<&str> for Text {
1231 fn eq(&self, other: &&str) -> bool {
1232 let mut same = Same {
1233 rest: other,
1234 ok: true,
1235 };
1236 let _ = self.emit_as(&mut same, true);
1237 same.ok && same.rest.is_empty()
1238 }
1239}
1240
1241impl PartialEq<str> for Text {
1242 fn eq(&self, other: &str) -> bool {
1243 *self == other
1244 }
1245}
1246
1247impl PartialEq<Text> for &str {
1248 fn eq(&self, other: &Text) -> bool {
1249 other == self
1250 }
1251}
1252
1253/// The displayed text as a string (`collect_str`): a command or handler returning a
1254/// `Text` sends the translation.
1255#[cfg(feature = "serde")]
1256impl serde::Serialize for Text {
1257 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1258 s.collect_str(self)
1259 }
1260}
1261
1262impl I18n {
1263 /// A [`Text`] of `key` on this instance (the active locale, the root), resolved when
1264 /// shown; a scope's locale and page apply unless the `Text` sets its own.
1265 #[must_use]
1266 pub fn text(&self, key: impl Into<Cow<'static, str>>) -> Text {
1267 Text::new(key.into(), Some(self.clone()))
1268 }
1269}
1270
1271impl View {
1272 /// A [`Text`] of `key` in this view's locale and page.
1273 #[must_use]
1274 pub fn text(&self, key: impl Into<Cow<'static, str>>) -> Text {
1275 let mut t = Text::new(key.into(), Some(self.i18n.clone()));
1276 t.locale = self.locale.clone().map(Code::Shared);
1277 t.page = self.page.clone().map(Code::Shared);
1278 t
1279 }
1280}