ashlar-ui 0.2.0

ashlar UI components: theme tokens, controls, layout, docking, icons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Every word ashlar's components show, in one [`UiLabels`] installed on the context (like the
//! theme tokens). Components use the installed labels unless the app passes its own to that
//! component (`Toasts::labels`, `Form::labels`, `DiffView::labels`, …), which always win.
//!
//! The defaults are English. [`UiLabels::from_i18n`] builds them from an [`I18n`] that has the
//! built-in catalogs ([`add_catalogs`]: English and German), so an app switches every built-in
//! string with its own locale and can override any `ui.*` key in its own catalogs:
//!
//! ```
//! use ashlar_i18n::I18n;
//! use ashlar_ui::labels::{self, UiLabels};
//!
//! let mut i18n = I18n::new("en");
//! labels::add_catalogs(&mut i18n);
//! i18n.set_locale("de");
//! let ctx = egui::Context::default();
//! labels::install(&ctx, UiLabels::from_i18n(&i18n));
//! assert_eq!(labels::current(&ctx).toast.dismiss, "Schließen");
//! ```

use std::sync::{Arc, OnceLock};

use ashlar_i18n::I18n;

use crate::chat::ChatLabels;
use crate::commands::keymap_editor::KeymapLabels;
use crate::diff_view::DiffLabels;
use crate::form::FormLabels;
use crate::markdown::MarkdownLabels;
use crate::sidebar::SidebarLabels;
use crate::toasts::ToastLabels;

/// The built-in catalogs (`ui.*` keys), as `(locale, json)`.
pub const CATALOGS: &[(&str, &str)] = &[("en", include_str!("../i18n/en.json")), ("de", include_str!("../i18n/de.json"))];

/// Accessible names of the tab strip's buttons.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TabLabels {
    pub overflow: String,
    pub close: String,
}

impl Default for TabLabels {
    fn default() -> Self {
        TabLabels { overflow: "More tabs".into(), close: "Close tab".into() }
    }
}

/// The print settings panel's words, owned; [`PrintLabels::as_labels`] lends them to
/// [`crate::printing::State::show`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PrintLabels {
    pub printer: String,
    pub select_printer: String,
    pub refresh: String,
    pub copies: String,
    pub printer_default: String,
    pub duplex: String,
    pub one_sided: String,
    pub long_edge: String,
    pub short_edge: String,
    pub grayscale: String,
}

impl Default for PrintLabels {
    fn default() -> Self {
        PrintLabels {
            printer: "Printer".into(),
            select_printer: "Select a printer".into(),
            refresh: "Refresh".into(),
            copies: "Copies".into(),
            printer_default: "Printer default".into(),
            duplex: "Two-sided".into(),
            one_sided: "One-sided".into(),
            long_edge: "Long edge".into(),
            short_edge: "Short edge".into(),
            grayscale: "Grayscale".into(),
        }
    }
}

impl PrintLabels {
    pub fn as_labels(&self) -> crate::printing::Labels<'_> {
        crate::printing::Labels {
            printer: &self.printer,
            select_printer: &self.select_printer,
            refresh: &self.refresh,
            copies: &self.copies,
            printer_default: &self.printer_default,
            duplex: &self.duplex,
            one_sided: &self.one_sided,
            long_edge: &self.long_edge,
            short_edge: &self.short_edge,
            grayscale: &self.grayscale,
        }
    }
}

/// Every built-in component string.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct UiLabels {
    pub toast: ToastLabels,
    pub form: FormLabels,
    pub chat: ChatLabels,
    pub diff: DiffLabels,
    pub keymap: KeymapLabels,
    pub tabs: TabLabels,
    pub print: PrintLabels,
    pub search: SearchLabels,
    pub markdown: MarkdownLabels,
    pub controls: ControlLabels,
    pub sidebar: SidebarLabels,
}

/// Words of the everyday [`controls`](crate::controls) that do not take one from the caller.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ControlLabels {
    /// The accessible name of [`Skeleton`](crate::controls::Skeleton) rows.
    pub loading: String,
}

impl Default for ControlLabels {
    fn default() -> Self {
        ControlLabels { loading: "Loading".into() }
    }
}

/// The search field's and the command palette's words.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SearchLabels {
    /// The search field's name for screen readers (the placeholder is only a hint).
    pub field: String,
    pub clear: String,
    /// The command palette's input name.
    pub palette: String,
}

impl Default for SearchLabels {
    fn default() -> Self {
        SearchLabels { field: "Search".into(), clear: "Clear search".into(), palette: "Command palette".into() }
    }
}

/// Every key [`UiLabels::from_i18n`] reads; each must be in the English catalog (tested).
pub const KEYS: &[&str] = &[
    "ui.toast.dismiss",
    "ui.toast.more",
    "ui.form.no_match",
    "ui.form.no_match_body",
    "ui.form.reset",
    "ui.form.required",
    "ui.chat.transcript",
    "ui.chat.jump_to_latest",
    "ui.chat.user",
    "ui.chat.assistant",
    "ui.chat.system",
    "ui.chat.tool",
    "ui.chat.streaming",
    "ui.chat.approve",
    "ui.chat.deny",
    "ui.chat.show_details",
    "ui.chat.hide_details",
    "ui.chat.pending",
    "ui.chat.running",
    "ui.chat.succeeded",
    "ui.chat.failed",
    "ui.chat.needs_approval",
    "ui.chat.approved",
    "ui.chat.denied",
    "ui.chat.suggestions",
    "ui.chat.composer",
    "ui.diff.expand",
    "ui.diff.hidden",
    "ui.diff.binary",
    "ui.diff.added",
    "ui.diff.removed",
    "ui.keymap.search",
    "ui.keymap.command",
    "ui.keymap.shortcut",
    "ui.keymap.recording",
    "ui.keymap.unbound",
    "ui.keymap.reset",
    "ui.keymap.clear",
    "ui.keymap.conflicts_with",
    "ui.keymap.table",
    "ui.keymap.actions",
    "ui.search.field",
    "ui.search.clear",
    "ui.search.palette",
    "ui.tabs.overflow",
    "ui.tabs.close",
    "ui.print.printer",
    "ui.print.select_printer",
    "ui.print.refresh",
    "ui.print.copies",
    "ui.print.printer_default",
    "ui.print.duplex",
    "ui.print.one_sided",
    "ui.print.long_edge",
    "ui.print.short_edge",
    "ui.print.grayscale",
    "ui.markdown.copy",
    "ui.markdown.copied",
    "ui.markdown.code",
    "ui.markdown.more_rows",
    "ui.controls.loading",
    "ui.sidebar.rename",
    "ui.sidebar.items",
];

/// Adds the built-in catalogs to `i18n` (add the app's own catalogs after, to override keys).
pub fn add_catalogs(i18n: &mut I18n) {
    for (locale, json) in CATALOGS {
        i18n.add(locale, *json);
    }
}

impl UiLabels {
    /// The labels in `i18n`'s current locale. Keys `i18n` lacks keep their English default, so
    /// this works without [`add_catalogs`] too.
    pub fn from_i18n(i18n: &I18n) -> Self {
        let mut l = UiLabels::default();
        let set = |field: &mut String, key: &str| {
            if let Some(text) = i18n.get(key) {
                text.clone_into(field);
            }
        };
        let t = &mut l.toast;
        set(&mut t.dismiss, "ui.toast.dismiss");
        set(&mut t.more, "ui.toast.more");
        let f = &mut l.form;
        set(&mut f.no_match, "ui.form.no_match");
        set(&mut f.no_match_body, "ui.form.no_match_body");
        set(&mut f.reset, "ui.form.reset");
        set(&mut f.required, "ui.form.required");
        let c = &mut l.chat;
        for (field, key) in [
            (&mut c.transcript, "ui.chat.transcript"),
            (&mut c.jump_to_latest, "ui.chat.jump_to_latest"),
            (&mut c.user, "ui.chat.user"),
            (&mut c.assistant, "ui.chat.assistant"),
            (&mut c.system, "ui.chat.system"),
            (&mut c.tool, "ui.chat.tool"),
            (&mut c.streaming, "ui.chat.streaming"),
            (&mut c.approve, "ui.chat.approve"),
            (&mut c.deny, "ui.chat.deny"),
            (&mut c.show_details, "ui.chat.show_details"),
            (&mut c.hide_details, "ui.chat.hide_details"),
            (&mut c.pending, "ui.chat.pending"),
            (&mut c.running, "ui.chat.running"),
            (&mut c.succeeded, "ui.chat.succeeded"),
            (&mut c.failed, "ui.chat.failed"),
            (&mut c.needs_approval, "ui.chat.needs_approval"),
            (&mut c.approved, "ui.chat.approved"),
            (&mut c.denied, "ui.chat.denied"),
            (&mut c.suggestions, "ui.chat.suggestions"),
            (&mut c.composer, "ui.chat.composer"),
        ] {
            set(field, key);
        }
        let d = &mut l.diff;
        set(&mut d.expand, "ui.diff.expand");
        set(&mut d.hidden, "ui.diff.hidden");
        set(&mut d.binary, "ui.diff.binary");
        set(&mut d.added, "ui.diff.added");
        set(&mut d.removed, "ui.diff.removed");
        let k = &mut l.keymap;
        for (field, key) in [
            (&mut k.search, "ui.keymap.search"),
            (&mut k.command, "ui.keymap.command"),
            (&mut k.shortcut, "ui.keymap.shortcut"),
            (&mut k.recording, "ui.keymap.recording"),
            (&mut k.unbound, "ui.keymap.unbound"),
            (&mut k.reset, "ui.keymap.reset"),
            (&mut k.clear, "ui.keymap.clear"),
            (&mut k.conflicts_with, "ui.keymap.conflicts_with"),
            (&mut k.table, "ui.keymap.table"),
            (&mut k.actions, "ui.keymap.actions"),
        ] {
            set(field, key);
        }
        set(&mut l.search.field, "ui.search.field");
        set(&mut l.search.clear, "ui.search.clear");
        set(&mut l.search.palette, "ui.search.palette");
        set(&mut l.tabs.overflow, "ui.tabs.overflow");
        set(&mut l.tabs.close, "ui.tabs.close");
        let p = &mut l.print;
        for (field, key) in [
            (&mut p.printer, "ui.print.printer"),
            (&mut p.select_printer, "ui.print.select_printer"),
            (&mut p.refresh, "ui.print.refresh"),
            (&mut p.copies, "ui.print.copies"),
            (&mut p.printer_default, "ui.print.printer_default"),
            (&mut p.duplex, "ui.print.duplex"),
            (&mut p.one_sided, "ui.print.one_sided"),
            (&mut p.long_edge, "ui.print.long_edge"),
            (&mut p.short_edge, "ui.print.short_edge"),
            (&mut p.grayscale, "ui.print.grayscale"),
        ] {
            set(field, key);
        }
        let m = &mut l.markdown;
        for (field, key) in [
            (&mut m.copy, "ui.markdown.copy"),
            (&mut m.copied, "ui.markdown.copied"),
            (&mut m.code, "ui.markdown.code"),
            (&mut m.more_rows, "ui.markdown.more_rows"),
        ] {
            if let Some(text) = i18n.get(key) {
                *field = text.to_owned().into();
            }
        }
        set(&mut l.controls.loading, "ui.controls.loading");
        set(&mut l.sidebar.rename, "ui.sidebar.rename");
        set(&mut l.sidebar.items, "ui.sidebar.items");
        l
    }
}

fn id() -> egui::Id {
    egui::Id::new("ashlar_ui::labels")
}

/// Installs `labels` for every component on `ctx` (until replaced).
pub fn install(ctx: &egui::Context, labels: UiLabels) {
    ctx.data_mut(|d| d.insert_temp(id(), Arc::new(labels)));
    crate::wake::wake(ctx, crate::wake::Reason::SETTINGS);
}

/// The installed labels, or the English defaults. Cheap: an `Arc` clone.
pub fn current(ctx: &egui::Context) -> Arc<UiLabels> {
    ctx.data(|d| d.get_temp::<Arc<UiLabels>>(id())).unwrap_or_else(|| english().clone())
}

/// Count-dependent texts every component may show; each must be in the English catalog (tested).
/// They hold `{n}` and may have CLDR plural forms (`ui.toast.more.one`, `….few`, `….other`).
pub const PLURAL_KEYS: &[&str] = &["ui.toast.more", "ui.keymap.shared"];

/// Count-dependent texts with a locale's plural rules ([`PLURAL_KEYS`]). Installed next to the
/// [`UiLabels`] (they are kept apart so the label structs gain no fields); the default holds
/// nothing, and components then fill `{n}` into their [`UiLabels`] template.
#[derive(Clone, Default)]
pub struct Plurals {
    i18n: Option<Arc<I18n>>,
}

impl std::fmt::Debug for Plurals {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Plurals").field("locale", &self.i18n.as_ref().map(|i| i.locale().to_string())).finish()
    }
}

impl Plurals {
    /// The plural texts of `i18n`'s current locale.
    pub fn from_i18n(i18n: &I18n) -> Self {
        Plurals { i18n: Some(Arc::new(i18n.clone())) }
    }

    /// `key`'s text for `n` (by the locale's plural category, `{n}` filled with the locale's
    /// digits), or `None` when there is no catalog text for `key`.
    pub fn text(&self, key: &str, n: usize) -> Option<String> {
        let i18n = self.i18n.as_ref()?;
        let other = format!("{key}.other");
        if i18n.get(key).is_none() && i18n.get(&other).is_none() {
            return None;
        }
        let n = i64::try_from(n).unwrap_or(i64::MAX);
        let shown = i18n.integer(n);
        Some(i18n.plural(key, n, &[("n", &shown)]))
    }
}

fn plurals_id() -> egui::Id {
    egui::Id::new("ashlar_ui::labels::plurals")
}

/// Installs `plurals` for every component on `ctx` (until replaced).
pub fn install_plurals(ctx: &egui::Context, plurals: Plurals) {
    ctx.data_mut(|d| d.insert_temp(plurals_id(), plurals));
    crate::wake::wake(ctx, crate::wake::Reason::SETTINGS);
}

/// Installs the labels and the plural texts of `i18n`'s current locale (call again after
/// switching locale).
pub fn install_i18n(ctx: &egui::Context, i18n: &I18n) {
    install(ctx, UiLabels::from_i18n(i18n));
    install_plurals(ctx, Plurals::from_i18n(i18n));
}

/// The installed plural texts (empty unless installed).
pub fn plurals(ctx: &egui::Context) -> Plurals {
    ctx.data(|d| d.get_temp::<Plurals>(plurals_id())).unwrap_or_default()
}

/// The text for `n` of `key`: the installed plural form, else `template` with `{n}` filled.
pub fn count_text(ctx: &egui::Context, key: &str, n: usize, template: &str) -> String {
    plurals(ctx).text(key, n).unwrap_or_else(|| template.replace("{n}", &n.to_string()))
}

/// The English defaults, shared.
pub fn english() -> &'static Arc<UiLabels> {
    static ENGLISH: OnceLock<Arc<UiLabels>> = OnceLock::new();
    ENGLISH.get_or_init(|| Arc::new(UiLabels::default()))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn i18n() -> I18n {
        let mut i18n = I18n::new("en");
        add_catalogs(&mut i18n);
        i18n
    }

    #[test]
    fn catalogs_are_complete_and_match_the_defaults() {
        let i18n = i18n();
        assert_eq!(i18n.check(), vec![]);
        assert_eq!(i18n.missing_source_keys(KEYS), Vec::<&str>::new());
        // the English catalog and the Default impls say the same thing
        assert_eq!(UiLabels::from_i18n(&i18n), UiLabels::default());
    }

    #[test]
    fn plural_keys_are_in_every_catalog_and_follow_the_locale() {
        let mut i18n = i18n();
        assert_eq!(i18n.missing_source_keys(PLURAL_KEYS), Vec::<&str>::new());
        i18n.add("en", r#"{"ui.toast.more.one": "+{n} more toast", "ui.toast.more.other": "+{n} more toasts"}"#);
        let ctx = egui::Context::default();
        assert_eq!(count_text(&ctx, "ui.toast.more", 1, "+{n} more"), "+1 more", "nothing installed: the template");
        install_i18n(&ctx, &i18n);
        assert_eq!(count_text(&ctx, "ui.toast.more", 1, "x"), "+1 more toast");
        assert_eq!(count_text(&ctx, "ui.toast.more", 1200, "x"), "+1,200 more toasts");
        i18n.set_locale("de");
        install_i18n(&ctx, &i18n);
        assert_eq!(count_text(&ctx, "ui.keymap.shared", 3, "x"), "3 Befehle teilen sich ein Tastenkürzel");
        assert_eq!(plurals(&ctx).text("no.such.key", 2), None);
    }

    #[test]
    fn switching_locale_switches_labels() {
        let mut i18n = i18n();
        i18n.set_locale("de-DE");
        let de = UiLabels::from_i18n(&i18n);
        assert_eq!(de.toast.dismiss, "Schließen");
        assert_eq!(de.tabs.close, "Tab schließen");
        i18n.set_locale("ja");
        assert_eq!(UiLabels::from_i18n(&i18n), UiLabels::default());
    }

    #[test]
    fn current_falls_back_to_english() {
        let ctx = egui::Context::default();
        assert_eq!(current(&ctx).toast.dismiss, "Dismiss");
        let mut l = UiLabels::default();
        l.toast.dismiss = "Close".into();
        install(&ctx, l);
        assert_eq!(current(&ctx).toast.dismiss, "Close");
    }
}