altui 0.2.0

A state-driven TUI runtime built on top of altui-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
use altui_core::{backend::Backend, layout::Rect, Frame};
use crossterm::event::{Event, KeyCode};
use indexmap::IndexMap;

use crate::{context::ViewCtx, ctxstore::CtxStore, ids::WidgetId, views::View, AppHandler};

/// Frame-scoped view manager used by [`ViewLoop`](crate::ViewLoop).
///
/// `ViewFactory` stores the views for the current runtime instance and exposes
/// the helper methods used by the `views` and `event_handler` closures.
///
/// It is responsible for:
///
/// - storing views
/// - creating and owning their [`ViewCtx`](crate::ViewCtx) values
/// - exposing the current frame event
/// - exposing navigation helpers
/// - coordinating layout state with [`CtxStore`]
///
/// Views are inserted through the `views` closure passed to
/// [`ViewLoop::run`](crate::ViewLoop::run).
///
/// The insertion order strictly defines:
///
/// - context association
/// - area assignment order
/// - rendering order
///
/// That is why `views` and `areas` must stay in lockstep.
pub struct ViewFactory<'a, State> {
    pub(crate) views: IndexMap<usize, Box<dyn View<State = State> + 'a>>,
    pub(crate) contexts: CtxStore,
    pub(crate) widget_id: Option<usize>,
    pub(crate) event: Option<Event>,
    // First of all skip event on first iteration. Then on button click
    pub(crate) skip_event: bool,
    pub(crate) first_iteration: bool,
    pub(crate) click_time: u64,
    pub(crate) vscroll: bool,
    pub(crate) basic_navigation: bool,
    pub(crate) current_area: Rect,
}

impl<'a, State: AppHandler> ViewFactory<'a, State> {
    pub(crate) fn new() -> Self {
        Self {
            views: Default::default(),
            contexts: Default::default(),
            widget_id: None,
            event: Default::default(),
            skip_event: true,
            first_iteration: true,
            click_time: 150,
            vscroll: false,
            basic_navigation: false,
            current_area: Rect::default(),
        }
    }

    pub(crate) fn take_last_active(&mut self) -> Option<usize> {
        self.widget_id.take()
    }

    /// Returns the event currently being processed by the runtime.
    ///
    /// This is the primary way for the
    /// [`event_handler`](crate::ViewLoop::run) closure to inspect the input that
    /// triggered the current frame.
    ///
    /// The event is populated near the start of
    /// [`ViewLoop::run`](crate::ViewLoop::run). Depending on dispatch order, it
    /// may later be consumed by a hovered or active view through
    /// [`View::on_event`](crate::View::on_event), so `event_handler` is the
    /// place where app-level code should usually inspect it first.
    ///
    /// This method is also useful when you disable
    /// [`basic_navigation`](crate::ViewLoop::basic_navigation) and implement your
    /// own navigation policy by combining `event()` with the public navigation
    /// helpers on [`ViewFactory`].
    ///
    /// # Examples
    /// ```rust,ignore
    /// use crossterm::event::Event;
    ///
    /// fn event_handler<State>(view_factory: &altui::ViewFactory<'_, State>) {
    /// if let Some(event) = view_factory.event() {
    ///     match event {
    ///         Event::Key(key_event) => { /* handle key press */ },
    ///         Event::Mouse(mouse_event) => { /* handle mouse action */ },
    ///         _ => (),
    ///     }
    /// }
    /// }
    /// ```
    pub fn event(&self) -> Option<&Event> {
        self.event.as_ref()
    }

    /// Returns the current terminal area as a [`Rect`].
    ///
    /// This is an alias for [`Frame::size`] that provides the current render area
    /// during the draw cycle. The value represents the terminal dimensions available
    /// for rendering at the time before **the next** draw call.
    ///
    /// Use it in the `event_handler` closure of [`crate::ViewLoop::run`] method to determine
    /// available space for layout calculations
    pub fn area(&self) -> Rect {
        self.current_area
    }

    /// Inserts a non-interactive view.
    ///
    /// The inserted view gets [`ViewCtx::silent`](crate::ViewCtx::silent):
    ///
    /// - it participates in `logic` and rendering
    /// - it is not part of keyboard or mouse navigation
    /// - it never becomes hovered or active through built-in navigation
    ///
    /// Use this for static layers such as backgrounds, labels, or page content
    /// that should only react to shared application state.
    ///
    /// The order of inserted views determines the order of assigned rectangles.
    ///
    /// This is the common choice for passive content in examples such as
    /// `simple_pages`.
    ///
    /// WARNING! This method is experimental. It is not recommended to add or remove
    /// views while the app is running. This can break the order of views and rectangles.
    pub fn insert_view(&mut self, view: impl View<State = State> + 'static) -> WidgetId {
        let ctx = ViewCtx::silent();
        let id = ctx.get_widget_id();
        self.views.insert(ctx.get_id(), Box::new(view));
        self.contexts.push(ctx);
        id
    }

    /// Inserts a one-shot interactive view.
    ///
    /// The inserted view gets [`ViewCtx::button`](crate::ViewCtx::button):
    ///
    /// - it participates in navigation
    /// - it can become hovered
    /// - activation is transient and is automatically reset after one frame
    /// - `logic` is the usual place for the one-shot action
    ///
    /// This is the most convenient choice for menu buttons and toggles. It is
    /// used in `flex_buttons` and for page selectors in `simple_pages`.
    ///
    /// See:
    /// <https://altlinux.space/writers/altui/src/branch/main/examples/flex_buttons>
    ///
    /// The order of inserted views determines the order of assigned rectangles.
    ///
    /// WARNING! This method is experimental. It is not recommended to add or remove
    /// views while the app is running. This can break the order of views and rectangles.
    pub fn insert_button_view(&mut self, view: impl View<State = State> + 'static) -> WidgetId {
        let ctx = ViewCtx::button();
        let id = ctx.get_widget_id();
        self.views.insert(ctx.get_id(), Box::new(view));
        self.contexts.push_interactive(ctx);
        id
    }

    /// Inserts a selectable view.
    ///
    /// A selectable view participates in navigation and can receive
    /// [`View::on_event`](crate::View::on_event), but it does not keep exclusive
    /// control of the input stream the way an interactive view does.
    ///
    /// In practice:
    ///
    /// - it can become hovered and active
    /// - its active state is cleared before `logic` in the active dispatch path
    /// - built-in navigation can still continue around it on later frames
    /// - you can combine navigation with extra behavior in `on_event`
    ///
    /// Use this when a view should be part of the navigation graph and react to
    /// input, but should not behave like a modal editor.
    ///
    /// The order of inserted views determines the order of assigned rectangles.
    ///
    /// WARNING! This method is experimental. It is not recommended to add or remove
    /// views while the app is running. This can break the order of views and rectangles
    /// and cause the app to panic or behave incorrectly.
    pub fn insert_selectable_view(&mut self, view: impl View<State = State> + 'static) -> WidgetId {
        let ctx = ViewCtx::selectable();
        let id = ctx.get_widget_id();
        self.views.insert(ctx.get_id(), Box::new(view));
        self.contexts.push_interactive(ctx);
        id
    }

    /// Inserts an interactive view that can keep control while active.
    ///
    /// The inserted view gets [`ViewCtx::interactive`](crate::ViewCtx::interactive):
    ///
    /// - it participates in navigation
    /// - it can receive [`View::on_event`](crate::View::on_event)
    /// - once active, it keeps receiving the event stream until it leaves the
    ///   active state
    ///
    /// Use this for widgets that should temporarily own the input stream, such
    /// as modal content or editors. The `popup` example uses an interactive view
    /// so the popup can stay focused until it closes itself or the app resets it.
    ///
    /// See:
    /// <https://altlinux.space/writers/altui/src/branch/main/examples/popup>
    ///
    /// The order of inserted views determines the order of assigned rectangles.
    ///
    /// WARNING! This method is experimental. It is not recommended to add or remove
    /// views while the app is running. This can break the order of views and rectangles
    /// and cause the app to panic or behave incorrectly.
    pub fn insert_interactive_view(
        &mut self,
        view: impl View<State = State> + 'static,
    ) -> WidgetId {
        let ctx = ViewCtx::interactive();
        let id = ctx.get_widget_id();
        self.views.insert(ctx.get_id(), Box::new(view));
        self.contexts.push_interactive(ctx);
        id
    }

    /// Removes a view from `ViewFactory` by tag.
    ///
    /// Returns nothing if no matching tag is found.
    ///
    /// WARNING! This method is experimental. It is not recommended to add or remove
    /// views while the app is running. This can break the order of views and rectangles
    /// and cause the app to panic or behave incorrectly.
    pub fn try_remove_view_by_tag(&mut self, tag: &str) {
        if let Some(i) = self
            .contexts
            .contexts
            .iter()
            .position(|ctx| ctx.tags().iter().any(|t| **t == *tag))
        {
            if self.views.shift_remove(&i).is_none() {
                tracing::trace!("Failed to remove a View with tag: {tag}");
                return;
            }

            self.contexts.contexts.remove(i);
            self.contexts.interactive.retain(|idx| idx != &i);
        }
    }

    /// Sets the delay used when the runtime intentionally skips the next event
    /// after a mouse click.
    ///
    /// This delay is primarily used for button-style interactions. After a click,
    /// the runtime skips the next iteration's event handling and waits for the
    /// specified amount of time so that the same press is not immediately
    /// interpreted again.
    ///
    /// The default delay is **150 milliseconds**.
    ///
    /// You may increase or decrease this value depending on how responsive you
    /// want mouse interactions to feel. Setting the delay to `0` disables the
    /// waiting period entirely.
    pub fn set_click_time(&mut self, millis: u64) {
        self.click_time = millis;
    }

    /// Enables or disables vertical movement in the built-in navigation helper.
    ///
    /// This is the `ViewFactory` equivalent of
    /// [`ViewLoop::vscroll`](crate::ViewLoop::vscroll). It is mainly useful when
    /// reproducing built-in navigation manually inside `event_handler`.
    pub fn vscroll(&mut self, on: bool) {
        self.vscroll = on;
    }

    /// Sets the vertical navigation step for built-in or custom navigation.
    ///
    /// When vertical navigation is enabled, moving up or down changes the hover
    /// index by this step. A regular grid usually uses the number of items in a
    /// row.
    ///
    /// This is demonstrated in:
    /// <https://altlinux.space/writers/altui/src/branch/main/examples/simple_buttons_with_vscroll>
    pub fn set_vscroll(&mut self, step: usize) {
        self.contexts.set_vscroll(step);
    }

    /// Moves hover to the first interactive view.
    pub fn first(&mut self) {
        self.contexts.first();
    }

    /// Moves hover to the last interactive view.
    pub fn last(&mut self) {
        self.contexts.last();
    }

    /// Moves hover to the next interactive view.
    pub fn next(&mut self) {
        self.contexts.next();
    }

    /// Moves hover to the previous interactive view.
    pub fn prev(&mut self) {
        self.contexts.previous();
    }

    /// Sets hover to the interactive view under the given mouse coordinates.
    pub fn mouse_set_hover(&mut self, x: u16, y: u16) {
        self.contexts.mouse_set_hover(x, y);
    }

    /// Returns whether the current hover already contains the given coordinates.
    ///
    /// This is useful when reproducing the runtime mouse navigation manually.
    pub fn mouse_is_hovered(&mut self, x: u16, y: u16) {
        self.contexts.mouse_is_hovered(x, y);
    }

    /// Stores the widget id whose active action should be replayed on the next frame.
    ///
    /// This helper exists so custom navigation can mirror the runtime behavior
    /// around resetting active state without losing one pending action.
    pub fn set_last_active_action_for(&mut self, widget_id: Option<usize>) {
        self.widget_id = widget_id;
    }

    pub(crate) fn set_current_area(&mut self, area: Rect) {
        self.current_area = area;
    }

    pub(crate) fn navigation(&mut self, app: &mut State) {
        if let Some(event) = self.event.as_ref() {
            match event {
                Event::Key(key_event) => {
                    if app.hover().is_some() && app.active().is_none() {
                        match key_event.code {
                            KeyCode::Left | KeyCode::Char('h') | KeyCode::BackTab => {
                                self.contexts.previous()
                            }
                            KeyCode::Up | KeyCode::Char('k') if self.vscroll => self.contexts.up(),
                            KeyCode::Right | KeyCode::Char('l') | KeyCode::Tab => {
                                self.contexts.next()
                            }
                            KeyCode::Down | KeyCode::Char('j') if self.vscroll => {
                                self.contexts.down()
                            }
                            KeyCode::Enter | KeyCode::Char('i') | KeyCode::Char(' ') => {
                                app.set_active().unwrap()
                            }
                            KeyCode::Esc | KeyCode::Char('q') => {
                                let _ = app.reset_hover().unwrap();
                            }
                            _ => {}
                        }
                    // могут случится события, относящиеся к active, но без hover, которые должны иметь приоритет, если даже hover 0
                    } else if let Some(id) = app.active() {
                        if key_event.code == KeyCode::Esc {
                            self.set_last_active_action_for(Some(id));
                            app.reset_active();
                        }
                    } else if app.hover().is_none() {
                        match key_event.code {
                            KeyCode::Left | KeyCode::Char('h') | KeyCode::BackTab => {
                                self.contexts.last()
                            }
                            KeyCode::Right | KeyCode::Char('l') | KeyCode::Tab => {
                                self.contexts.first()
                            }
                            KeyCode::Up | KeyCode::Char('k') if self.vscroll => {
                                self.contexts.last()
                            }
                            KeyCode::Down | KeyCode::Char('j') if self.vscroll => {
                                self.contexts.first()
                            }
                            _ => {}
                        }
                    }
                }
                Event::Mouse(mouse_event) => {
                    match self
                        .contexts
                        .mouse_is_hovered(mouse_event.column, mouse_event.row)
                    {
                        false if mouse_event.kind.is_moved() => {
                            if let Err(e) = app.reset_hover() {
                                tracing::trace!("Failed to reset hover on mouse movement: {e}");
                            }
                            self.contexts
                                .mouse_set_hover(mouse_event.column, mouse_event.row)
                        }
                        true if mouse_event.kind.is_down() => {
                            if let Err(e) = app.set_active() {
                                tracing::trace!("Failed to set active widget: {e}");
                            }
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }
    }

    pub(crate) fn iteration<B: Backend>(&mut self, frame: &mut Frame<B>, app: &mut State) {
        for ((_, view), ctx) in self.views.iter_mut().zip(self.contexts.contexts.iter_mut()) {
            let active = ctx.is_active();

            if !(active && ctx.is_hover()) {
                view.logic(ctx, app);
            }

            if ctx.is_visible() {
                view.render(
                    ctx.get_area(),
                    &mut self.contexts.layout_cache,
                    frame.current_buffer_mut(),
                );
            }

            // Сбрасываем active после отрисовки, чтобы логика active отработала лишь раз
            if active && ctx.is_button() {
                self.skip_event = true;
                ctx.reset_active();
            }
        }
    }
}