aetna-core 0.2.0

Aetna — backend-agnostic UI library core
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Tabs — a segmented row of triggers that drives a tab-panel
//! selection. Mirrors the shadcn / Radix Tabs primitive (which itself
//! reflects the WAI-ARIA `role="tablist"` / `role="tab"` pattern), so
//! LLM authors trained on web UI find the same shape here.
//!
//! The app owns the active tab value as a field of its choice
//! (`String`, an enum implementing [`std::fmt::Display`], …); the widget is a
//! pure visual + identity carrier — exactly the same controlled
//! pattern used by [`crate::widgets::select`] and
//! [`crate::widgets::slider`].
//!
//! # Shape
//!
//! ```ignore
//! use aetna_core::prelude::*;
//!
//! struct Settings { tab: String }
//!
//! impl App for Settings {
//!     fn build(&self) -> El {
//!         column([
//!             tabs_list("settings", &self.tab, [
//!                 ("account", "Account"),
//!                 ("appearance", "Appearance"),
//!                 ("advanced", "Advanced"),
//!             ]),
//!             match self.tab.as_str() {
//!                 "account" => account_panel(),
//!                 "appearance" => appearance_panel(),
//!                 "advanced" => advanced_panel(),
//!                 _ => spacer(),
//!             },
//!         ])
//!     }
//!
//!     fn on_event(&mut self, event: UiEvent) {
//!         tabs::apply_event(&mut self.tab, &event, "settings", |s| {
//!             Some(s.to_string())
//!         });
//!     }
//! }
//! ```
//!
//! There is intentionally no `tab_panel` / `tabs_content` wrapper:
//! Rust's `match` is more idiomatic than a sibling element that hides
//! itself when not active, and shadcn's `<TabsContent>` adds no visual
//! beyond a plain block.
//!
//! # Routed keys
//!
//! - `{key}:tab:{value}` — `Click` on a trigger; the app sets the
//!   active tab. Use [`tab_option_key`] to format and parse.
//!
//! # Dogfood note
//!
//! Composes only the public widget-kit surface — `Kind::Custom` for
//! the inspector tag, `.focusable()` + `.paint_overflow()` for the
//! focus ring, the existing `.current()` / `.ghost()` style modifiers
//! for active-vs-inactive treatment. An app crate can fork this file
//! and produce an equivalent widget against the same public API. See
//! `widget_kit.md`.

use std::panic::Location;

use crate::anim::Timing;
use crate::event::{UiEvent, UiEventKind};
use crate::style::StyleProfile;
use crate::tokens;
use crate::tree::*;

/// What a routed [`UiEvent`] means for a controlled tabs row keyed
/// `key`.
///
/// Returned by [`classify_event`]; [`apply_event`] is the convenience
/// wrapper that folds the action straight into the app's value field.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TabsAction<'a> {
    /// A trigger was clicked or activated. The string is the raw value
    /// token from the trigger's option key — apps convert it back to
    /// their value type (`&str` → `String`, `s.parse::<u32>()`, an
    /// enum lookup, …).
    Select(&'a str),
}

/// Classify a routed [`UiEvent`] against a controlled tabs row keyed
/// `key`. Returns `None` for events that aren't for this row.
///
/// Only `Click` / `Activate` event kinds qualify — pointer-move,
/// hover, and other non-activating events return `None` even when
/// they target a trigger. That means an app can call
/// [`classify_event`] unconditionally inside its event handler
/// without filtering on `event.kind` first.
///
/// The returned [`TabsAction::Select`] borrows from the event's routed
/// key, so apps that want to keep the value beyond the match arm
/// should `.to_string()` or `.parse()` it inline.
pub fn classify_event<'a>(event: &'a UiEvent, key: &str) -> Option<TabsAction<'a>> {
    if !matches!(event.kind, UiEventKind::Click | UiEventKind::Activate) {
        return None;
    }
    let routed = event.route()?;
    let rest = routed.strip_prefix(key)?.strip_prefix(':')?;
    let value = rest.strip_prefix("tab:")?;
    Some(TabsAction::Select(value))
}

/// Fold a routed [`UiEvent`] into the app's tab-value field for a
/// controlled tabs row keyed `key`. Returns `true` if the event was a
/// tabs event for this `key` (so the caller can short-circuit further
/// dispatch), `false` otherwise.
///
/// `parse` converts the raw value token back to the app's value type.
/// Returning `None` from `parse` ignores the click silently (useful
/// when the tab list and the value type can drift — e.g. a stale event
/// arriving after the underlying data changed).
///
/// ```ignore
/// use aetna_core::prelude::*;
///
/// struct Settings { tab: String }
///
/// impl App for Settings {
///     fn on_event(&mut self, event: UiEvent) {
///         tabs::apply_event(&mut self.tab, &event, "settings", |s| {
///             Some(s.to_string())
///         });
///     }
///     // ...
/// }
/// ```
pub fn apply_event<V>(
    value: &mut V,
    event: &UiEvent,
    key: &str,
    parse: impl FnOnce(&str) -> Option<V>,
) -> bool {
    let Some(TabsAction::Select(raw)) = classify_event(event, key) else {
        return false;
    };
    if let Some(v) = parse(raw) {
        *value = v;
    }
    true
}

/// Format the routed key emitted when a trigger is clicked. Apps that
/// match against the `:tab:` suffix can use this helper to produce the
/// same string the widget produces, but the convention is also stable
/// enough to format inline.
pub fn tab_option_key(key: &str, value: &impl std::fmt::Display) -> String {
    format!("{key}:tab:{value}")
}

/// The trigger surface for a single tab inside a [`tabs_list`]. Apps
/// usually let `tabs_list` build these from `(value, label)` pairs;
/// reach for `tab_trigger` directly when composing the row by hand
/// (e.g. mixing in icons, dividers, or different per-tab widths).
///
/// `list_key` is the parent tabs row's key — the routed key on the
/// trigger is `{list_key}:tab:{value}` (see [`tab_option_key`]).
/// `selected` styles the trigger as the active tab (raised surface
/// and semibold text, via the stock `.current()` modifier); inactive
/// triggers render with the `.ghost()` treatment.
#[track_caller]
pub fn tab_trigger(
    list_key: &str,
    value: impl std::fmt::Display,
    label: impl Into<String>,
    selected: bool,
) -> El {
    let routed_key = tab_option_key(list_key, &value);
    let base = El::new(Kind::Custom("tab_trigger"))
        .at_loc(Location::caller())
        .style_profile(StyleProfile::Surface)
        .focusable()
        .paint_overflow(Sides::all(tokens::FOCUS_RING_WIDTH))
        .key(routed_key)
        .text(label)
        .text_align(TextAlign::Center)
        .text_role(TextRole::Label)
        .radius(tokens::RADIUS_SM)
        .width(Size::Fill(1.0))
        .height(Size::Fixed(28.0))
        .padding(Sides::xy(tokens::SPACE_MD, 0.0));
    // `.current()` / `.ghost()` set fill, stroke, and text_color —
    // adding `.animate(SPRING_QUICK)` after them eases all three
    // between rebuilds, so switching tabs cross-fades the active
    // surface instead of snapping.
    let styled = if selected {
        base.current()
    } else {
        base.ghost()
    };
    styled.animate(Timing::SPRING_QUICK)
}

/// A segmented-control row of tab triggers. Visually a muted pill
/// containing one [`tab_trigger`] per option; the active trigger
/// surfaces above the muted base.
///
/// `current` is the currently-selected value — formatted via
/// [`std::fmt::Display`] and compared (also as a `Display` string)
/// against each option's `value` to pick the active trigger.
/// `options` is an iterable of `(value, label)` pairs.
///
/// The row's own key is `key`; per-trigger routed keys are
/// `{key}:tab:{value}`. Apps fold those back into their value field
/// with [`apply_event`].
#[track_caller]
pub fn tabs_list<I, V, L>(
    key: impl Into<String>,
    current: &impl std::fmt::Display,
    options: I,
) -> El
where
    I: IntoIterator<Item = (V, L)>,
    V: std::fmt::Display,
    L: Into<String>,
{
    let key = key.into();
    let current_str = current.to_string();
    let triggers: Vec<El> = options
        .into_iter()
        .map(|(value, label)| {
            let selected = value.to_string() == current_str;
            tab_trigger(&key, value, label, selected)
        })
        .collect();
    El::new(Kind::Custom("tabs_list"))
        .at_loc(Location::caller())
        .key(key)
        .axis(Axis::Row)
        .gap(tokens::SPACE_XS)
        .align(Align::Stretch)
        .children(triggers)
        .fill(tokens::BG_MUTED)
        .stroke(tokens::BORDER)
        .radius(tokens::RADIUS_MD)
        .padding(Sides::all(tokens::SPACE_XS))
        .width(Size::Fill(1.0))
        .height(Size::Hug)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{KeyModifiers, UiTarget};

    fn click_event(key: &str) -> UiEvent {
        UiEvent {
            kind: UiEventKind::Click,
            key: Some(key.to_string()),
            target: None,
            pointer: None,
            key_press: None,
            text: None,
            modifiers: KeyModifiers::default(),
        }
    }

    #[test]
    fn tab_option_key_matches_widget_format() {
        // Apps decoding routed events should use the same helper to
        // avoid format drift.
        assert_eq!(
            tab_option_key("settings", &"account"),
            "settings:tab:account"
        );
        assert_eq!(tab_option_key("dashboard:7", &42u32), "dashboard:7:tab:42");
    }

    #[test]
    fn tab_trigger_routes_via_tab_option_key() {
        let inactive = tab_trigger("settings", "account", "Account", false);
        assert_eq!(inactive.key.as_deref(), Some("settings:tab:account"));
        // Trigger opts into focus + ring overhead so keyboard users
        // can tab through the row like any other interactive surface.
        assert!(inactive.focusable);
        // Inactive triggers carry the ghost treatment: no fill, no
        // stroke. The .ghost() modifier wipes both.
        assert!(inactive.fill.is_none());
        assert!(inactive.stroke.is_none());

        let active = tab_trigger("settings", "account", "Account", true);
        // Active triggers carry the .current() treatment: BG_RAISED
        // fill, BORDER stroke, and Selected/Current surface role for
        // theme dispatch.
        assert_eq!(active.fill, Some(tokens::BG_RAISED));
        assert_eq!(active.surface_role, SurfaceRole::Current);
    }

    #[test]
    fn tabs_list_marks_only_the_current_value_active() {
        let list = tabs_list(
            "settings",
            &"appearance",
            [
                ("account", "Account"),
                ("appearance", "Appearance"),
                ("advanced", "Advanced"),
            ],
        );
        assert_eq!(list.key.as_deref(), Some("settings"));
        assert_eq!(list.children.len(), 3);

        let [account, appearance, advanced] =
            [&list.children[0], &list.children[1], &list.children[2]];
        // Per-trigger routed keys.
        assert_eq!(account.key.as_deref(), Some("settings:tab:account"));
        assert_eq!(appearance.key.as_deref(), Some("settings:tab:appearance"));
        assert_eq!(advanced.key.as_deref(), Some("settings:tab:advanced"));

        // Only the trigger whose value matches `current` carries the
        // active-tab surface role.
        assert_ne!(account.surface_role, SurfaceRole::Current);
        assert_eq!(appearance.surface_role, SurfaceRole::Current);
        assert_ne!(advanced.surface_role, SurfaceRole::Current);
    }

    #[test]
    fn tabs_list_compares_via_display_so_typed_values_work() {
        // Mirrors the select_option_key Display contract: an `enum` or
        // `u32` value can drive the comparison as long as it formats
        // the same way as the option-list values.
        let list = tabs_list(
            "page",
            &7u32,
            [(0u32, "Zero"), (7u32, "Seven"), (42u32, "Forty-two")],
        );
        let [zero, seven, fortytwo] = [&list.children[0], &list.children[1], &list.children[2]];
        assert_ne!(zero.surface_role, SurfaceRole::Current);
        assert_eq!(seven.surface_role, SurfaceRole::Current);
        assert_ne!(fortytwo.surface_role, SurfaceRole::Current);
    }

    #[test]
    fn classify_event_selects_only_on_matching_route() {
        assert_eq!(
            classify_event(&click_event("settings:tab:account"), "settings"),
            Some(TabsAction::Select("account")),
        );
        // Compound keys (e.g. a per-card tabs row) work the same way
        // — the helper compares against the full row key.
        assert_eq!(
            classify_event(&click_event("dashboard:7:tab:42"), "dashboard:7"),
            Some(TabsAction::Select("42")),
        );

        // Non-matching keys fall through.
        assert_eq!(
            classify_event(&click_event("settings"), "settings"),
            None,
            "the row's own key isn't itself a tab target",
        );
        assert_eq!(
            classify_event(&click_event("other:tab:account"), "settings"),
            None,
        );
        // Even when a key shares a prefix with the tabs key, the
        // separator-after-prefix check rejects events that aren't this
        // row's own children.
        assert_eq!(
            classify_event(&click_event("settings-other:tab:x"), "settings"),
            None,
        );
        // Malformed suffix isn't a Select.
        assert_eq!(
            classify_event(&click_event("settings:option:x"), "settings"),
            None,
        );
    }

    #[test]
    fn classify_event_ignores_non_activating_kinds() {
        // Pointer-down / drag / hotkey events that target the same
        // trigger key shouldn't switch tabs — only Click and Activate
        // qualify.
        let mut ev = click_event("settings:tab:account");
        ev.kind = UiEventKind::PointerDown;
        assert_eq!(classify_event(&ev, "settings"), None);
        ev.kind = UiEventKind::Drag;
        assert_eq!(classify_event(&ev, "settings"), None);
        ev.kind = UiEventKind::Activate;
        assert_eq!(
            classify_event(&ev, "settings"),
            Some(TabsAction::Select("account")),
            "keyboard activation should select like a click",
        );
    }

    #[test]
    fn apply_event_folds_actions_into_value() {
        let mut tab = String::from("account");
        // Click on a trigger replaces the value.
        assert!(apply_event(
            &mut tab,
            &click_event("settings:tab:advanced"),
            "settings",
            |s| Some(s.to_string()),
        ));
        assert_eq!(tab, "advanced");

        // Non-tabs event returns false; state unchanged.
        assert!(!apply_event(
            &mut tab,
            &click_event("save"),
            "settings",
            |s| Some(s.to_string()),
        ));
        assert_eq!(tab, "advanced");
    }

    #[test]
    fn apply_event_silently_ignores_unparseable_values() {
        // A typed-value tabs row (e.g. u32 tab indices) should leave
        // state alone when a stale string can't be parsed back, rather
        // than panic.
        let mut tab: u32 = 1;
        assert!(apply_event(
            &mut tab,
            &click_event("page:tab:not-a-number"),
            "page",
            |s| s.parse::<u32>().ok(),
        ));
        assert_eq!(tab, 1, "value preserved when parse returns None");
    }

    #[test]
    fn tab_trigger_animates_so_selection_changes_ease() {
        // Without `.animate()` on the trigger, `.current()` →
        // `.ghost()` (and back) snaps fill/text_color on every
        // rebuild, which reads as a hard cut between tabs.
        assert!(
            tab_trigger("settings", "account", "Account", true)
                .animate
                .is_some()
        );
        assert!(
            tab_trigger("settings", "account", "Account", false)
                .animate
                .is_some()
        );
    }

    #[test]
    fn tabs_list_paints_a_segmented_pill_around_the_triggers() {
        // The row carries the muted pill background, so the active
        // trigger's raised surface visually nests inside it.
        let list = tabs_list(
            "settings",
            &"account",
            [("account", "Account"), ("settings", "Settings")],
        );
        assert_eq!(list.fill, Some(tokens::BG_MUTED));
        assert_eq!(list.radius, tokens::RADIUS_MD);
        // Row axis with a small gap so triggers are visually distinct.
        assert_eq!(list.axis, Axis::Row);
        // The list itself is not focusable — only its triggers are.
        // (Otherwise Tab would land on the row before the first tab.)
        assert!(!list.focusable);
    }

    #[test]
    fn target_for_event_can_be_routed_through_apply_event() {
        // Smoke test that a click event whose route comes from a real
        // UiTarget (mirroring what runtime delivers) is matched.
        let ev = UiEvent {
            kind: UiEventKind::Click,
            key: Some("settings:tab:advanced".into()),
            target: Some(UiTarget {
                key: "settings:tab:advanced".into(),
                node_id: "/settings/2".into(),
                rect: Rect::new(0.0, 0.0, 60.0, 28.0),
            }),
            pointer: None,
            key_press: None,
            text: None,
            modifiers: KeyModifiers::default(),
        };
        let mut tab = String::from("account");
        assert!(apply_event(&mut tab, &ev, "settings", |s| Some(
            s.to_string()
        )));
        assert_eq!(tab, "advanced");
    }
}