gitv-tui 0.4.2

A terminal-based GitHub client built with Rust and Ratatui.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
pub mod components;
pub mod issue_data;
pub mod layout;
pub mod macros;
pub mod theme;
pub mod utils;
pub mod widgets;

#[cfg(test)]
pub(crate) mod testing;

use crate::{
    app::GITHUB_CLIENT,
    bookmarks::{Bookmarks, read_bookmarks},
    define_cid_map,
    errors::{AppError, Result},
    ui::components::{
        Component, DumbComponent,
        help::HelpElementKind,
        issue_conversation::IssueConversation,
        issue_convo_preview::IssueConvoPreview,
        issue_create::IssueCreate,
        issue_detail::IssuePreview,
        issue_list::{IssueList, MainScreen},
        label_list::LabelList,
        search_bar::TextSearch,
        status_bar::StatusBar,
        title_bar::TitleBar,
    },
};
use ratatui_toaster::{ToastBuilder, ToastEngine, ToastEngineBuilder, ToastMessage};

use crossterm::{
    event::{
        DisableBracketedPaste, EnableBracketedPaste, EventStream, KeyEvent,
        KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    },
    execute,
};
use futures::{StreamExt, future::FutureExt};
use octocrab::{
    Page,
    models::{Label, issues::Issue, reactions::ReactionContent},
};
use rat_widget::{
    event::{HandleEvent, Outcome, Regular},
    focus::{Focus, FocusBuilder, FocusFlag},
};
use ratatui::{
    crossterm,
    prelude::*,
    widgets::{Block, Clear, Padding, Paragraph, WidgetRef, Wrap},
};
use std::{
    collections::HashMap,
    fmt::Display,
    io::stdout,
    sync::{Arc, OnceLock, RwLock},
    time::{self},
};
use tachyonfx::{EffectManager, Interpolation, fx};
use termprofile::{DetectorSettings, TermProfile};
use tokio::{select, sync::mpsc::Sender};
use tokio_util::sync::CancellationToken;
use tracing::{error, info, instrument, trace};

use anyhow::anyhow;

use crate::ui::components::{
    issue_conversation::{CommentView, IssueConversationSeed, TimelineEventView},
    issue_detail::{IssuePreviewSeed, PrSummary},
};
use crate::ui::issue_data::{IssueId, UiIssuePool};

const TICK_RATE: std::time::Duration = std::time::Duration::from_millis(60);
pub static COLOR_PROFILE: OnceLock<TermProfile> = OnceLock::new();
pub static CIDMAP: OnceLock<HashMap<u8, usize>> = OnceLock::new();
const HELP_TEXT: &[HelpElementKind] = &[
    crate::help_text!("Global Help"),
    crate::help_text!(""),
    crate::help_keybind!("1", "focus Search Bar"),
    crate::help_keybind!("2", "focus Issue List"),
    crate::help_keybind!("3", "focus Issue Conversation"),
    crate::help_keybind!("4", "focus Label List"),
    crate::help_keybind!("5", "focus Issue Create"),
    crate::help_keybind!("q / Ctrl+C", "quit the application"),
    crate::help_keybind!("? / Ctrl+H", "toggle help menu"),
    crate::help_text!(""),
    crate::help_text!(
        "Navigate with the focus keys above. Components may have additional controls."
    ),
];

pub async fn run(
    AppState {
        repo,
        owner,
        current_user,
    }: AppState,
) -> Result<(), AppError> {
    if COLOR_PROFILE.get().is_none() {
        COLOR_PROFILE
            .set(TermProfile::detect(&stdout(), DetectorSettings::default()))
            .map_err(|_| AppError::ErrorSettingGlobal("color profile"))?;
    }
    let mut terminal = ratatui::init();
    setup_more_panic_hooks();
    let (action_tx, action_rx) = tokio::sync::mpsc::channel(100);
    let mut app = App::new(
        action_tx,
        action_rx,
        AppState::new(repo, owner, current_user),
    )
    .await?;
    let run_result = app.run(&mut terminal).await;
    ratatui::restore();
    finish_teardown()?;
    run_result
}

struct App {
    action_tx: tokio::sync::mpsc::Sender<Action>,
    action_rx: tokio::sync::mpsc::Receiver<Action>,
    toast_engine: Option<ToastEngine<Action>>,
    focus: Option<Focus>,
    cancel_action: CancellationToken,
    components: Vec<Box<dyn Component>>,
    dumb_components: Vec<Box<dyn DumbComponent>>,
    help: Option<&'static [HelpElementKind]>,
    in_help: bool,
    in_editor: bool,
    last_frame: time::Instant,
    current_screen: MainScreen,
    last_focused: Option<FocusFlag>,
    last_event_error: Option<String>,
    effects_manager: EffectManager<()>,
    bookmarks: Arc<RwLock<Bookmarks>>,
}

#[derive(Debug, Default, Clone)]
pub struct AppState {
    repo: String,
    owner: String,
    current_user: String,
}

impl AppState {
    pub fn new(repo: String, owner: String, current_user: String) -> Self {
        Self {
            repo,
            owner,
            current_user,
        }
    }
}

fn focus(state: &mut App) -> Result<&mut Focus, AppError> {
    focus_noret(state);
    state
        .focus
        .as_mut()
        .ok_or_else(|| AppError::Other(anyhow!("focus state was not initialized")))
}

fn focus_noret(state: &mut App) {
    let mut f = FocusBuilder::new(state.focus.take());
    for component in state.components.iter() {
        if component.should_render() {
            f.widget(component.as_ref());
        }
    }
    state.focus = Some(f.build());
}

impl App {
    fn capture_error(&mut self, err: impl Display) {
        let message = err.to_string();
        error!(error = %message, "captured ui error");
        self.last_event_error = Some(message);
    }

    pub async fn new(
        action_tx: Sender<Action>,
        action_rx: tokio::sync::mpsc::Receiver<Action>,
        state: AppState,
    ) -> Result<Self, AppError> {
        let mut text_search = TextSearch::new(state.clone());
        let status_bar = StatusBar::new(state.clone());
        let mut label_list = LabelList::new(state.clone());
        let issue_preview = IssuePreview::new(state.clone());
        let issue_pool = Arc::new(RwLock::new(UiIssuePool::default()));
        let mut issue_conversation = IssueConversation::new(state.clone(), issue_pool.clone());
        let mut issue_create = IssueCreate::new(state.clone(), issue_pool.clone());
        let mut issue_convo_preview = IssueConvoPreview::new(issue_pool.clone());
        let bookmarks = Arc::new(RwLock::new(read_bookmarks()));
        let issue_handler = GITHUB_CLIENT
            .get()
            .ok_or_else(|| AppError::Other(anyhow!("github client is not initialized")))?
            .inner()
            .issues(state.owner.clone(), state.repo.clone());
        let mut issue_list = IssueList::new(
            issue_handler,
            state.owner.clone(),
            state.repo.clone(),
            action_tx.clone(),
            bookmarks.clone(),
            issue_pool.clone(),
        )
        .await;

        let comps = define_cid_map!(
             2 -> issue_list,
             3 -> issue_conversation,
             5 -> issue_create,
             4 -> label_list,
             6 -> issue_convo_preview,
             1 -> text_search, // this needs to be the last one
        )?;
        let effects_manager = EffectManager::default();

        Ok(Self {
            focus: None,
            toast_engine: None,
            in_help: false,
            last_frame: time::Instant::now(),
            in_editor: false,
            current_screen: MainScreen::default(),
            help: None,
            action_tx,
            effects_manager,
            action_rx,
            bookmarks,
            last_focused: None,
            last_event_error: None,
            cancel_action: Default::default(),
            components: comps,
            dumb_components: vec![
                Box::new(status_bar),
                Box::new(issue_preview),
                Box::new(TitleBar),
            ],
        })
    }
    pub async fn run(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<impl std::io::Write>>,
    ) -> Result<(), AppError> {
        let ctok = self.cancel_action.clone();
        let action_tx = self.action_tx.clone();
        for component in self.components.iter_mut() {
            component.register_action_tx(action_tx.clone());
        }

        if let Err(err) = setup_terminal() {
            self.capture_error(err);
        }

        tokio::spawn(async move {
            let mut tick_interval = tokio::time::interval(TICK_RATE);
            let mut event_stream = EventStream::new();

            loop {
                let event = select! {
                    _ = ctok.cancelled() => break,
                    _ = tick_interval.tick() => Action::Tick,
                    kevent = event_stream.next().fuse() => {
                        match kevent {
                            Some(Ok(kevent)) => Action::AppEvent(kevent),
                            Some(Err(..)) => Action::None,
                            None => break,
                        }
                    }
                };
                if action_tx.send(event).await.is_err() {
                    break;
                }
            }
            Ok::<(), AppError>(())
        });
        focus_noret(self);
        if let Some(ref mut focus) = self.focus {
            if let Some(last) = self.components.last() {
                focus.focus(&**last);
            } else {
                self.capture_error(anyhow!("no components available to focus"));
            }
        }
        let ctok = self.cancel_action.clone();
        let builder = ToastEngineBuilder::new(Rect::default()).action_tx(self.action_tx.clone());
        self.toast_engine = Some(builder.build());
        loop {
            let action = self.action_rx.recv().await;
            let mut should_draw_error_popup = false;
            let mut full_redraw = false;
            if let Some(ref action) = action {
                if let Action::EditorModeChanged(enabled) = action {
                    self.in_editor = *enabled;
                    if *enabled {
                        continue;
                    }
                    full_redraw = true;
                }
                if self.in_editor && matches!(action, Action::Tick | Action::AppEvent(_)) {
                    continue;
                }
                for component in self.components.iter_mut() {
                    if let Err(err) = component.handle_event(action.clone()).await {
                        let message = err.to_string();
                        error!(error = %message, "captured ui error");
                        self.last_event_error = Some(message);
                        should_draw_error_popup = true;
                    }
                    if component.gained_focus() && self.last_focused != Some(component.focus()) {
                        self.last_focused = Some(component.focus());
                        component.set_global_help();
                    }
                }
                for component in self.dumb_components.iter_mut() {
                    if let Err(err) = component.handle_event(action.clone()).await {
                        let message = err.to_string();
                        error!(error = %message, "captured ui error");
                        self.last_event_error = Some(message);
                        should_draw_error_popup = true;
                    }
                }
            }
            let should_draw = match &action {
                Some(Action::Tick) => self.has_animated_components(),
                Some(Action::None) => false,
                Some(Action::Quit) | None => false,
                _ => true,
            };
            match action {
                Some(Action::Tick) => {}
                Some(Action::ToastAction(ref toast_action)) => match toast_action {
                    ToastMessage::Show {
                        message,
                        toast_type,
                        position,
                    } => {
                        if let Some(ref mut toast_engine) = self.toast_engine {
                            toast_engine.show_toast(
                                ToastBuilder::new(message.clone().into())
                                    .toast_type(*toast_type)
                                    .position(*position),
                            );

                            let fx = fx::slide_in(
                                tachyonfx::Motion::RightToLeft,
                                0,
                                0,
                                Color::from(*toast_type),
                                (420, Interpolation::Linear),
                            )
                            .with_area(toast_engine.toast_area());
                            self.effects_manager.add_effect(fx);
                        }
                    }
                    ToastMessage::Hide => {
                        if let Some(ref mut toast_engine) = self.toast_engine {
                            toast_engine.hide_toast();
                            let fx = fx::slide_in(
                                tachyonfx::Motion::LeftToRight,
                                0,
                                0,
                                Color::Reset,
                                (420, Interpolation::Linear),
                            )
                            .with_area(toast_engine.toast_area());
                            self.effects_manager.add_effect(fx);
                        }
                    }
                },
                Some(Action::ForceFocusChange) => match focus(self) {
                    Ok(focus) => {
                        let r = focus.next_force();
                        trace!(outcome = ?r, "Focus");
                    }
                    Err(err) => {
                        self.capture_error(err);
                        should_draw_error_popup = true;
                    }
                },
                Some(Action::ForceFocusChangeRev) => match focus(self) {
                    Ok(focus) => {
                        let r = focus.prev_force();
                        trace!(outcome = ?r, "Focus");
                    }
                    Err(err) => {
                        self.capture_error(err);
                        should_draw_error_popup = true;
                    }
                },
                Some(Action::AppEvent(ref event)) => {
                    info!(?event, "Received app event");
                    if let Err(err) = self.handle_event(event).await {
                        self.capture_error(err);
                        should_draw_error_popup = true;
                    }
                }
                Some(Action::SetHelp(help)) => {
                    self.help = Some(help);
                }
                Some(Action::EditorModeChanged(enabled)) => {
                    self.in_editor = enabled;
                }
                Some(Action::ChangeIssueScreen(screen)) => {
                    self.current_screen = screen;
                    focus_noret(self);
                }
                Some(Action::Quit) | None => {
                    ctok.cancel();
                }
                _ => {}
            }
            if !self.in_editor
                && (should_draw
                    || matches!(action, Some(Action::ForceRender))
                    || should_draw_error_popup
                    || self.effects_manager.is_running()
                    || self
                        .toast_engine
                        .as_ref()
                        .is_some_and(|engine| engine.has_toast()))
            {
                if full_redraw && let Err(err) = terminal.clear() {
                    self.capture_error(err);
                }
                if let Err(err) = self.draw(terminal) {
                    self.capture_error(err);
                }
            }
            if self.cancel_action.is_cancelled() {
                if let Ok(bm) = self.bookmarks.try_write() {
                    if let Err(err) = bm.write_to_file() {
                        error!(error = %err, "failed to write bookmarks to file on shutdown");
                    } else {
                        info!("Saved bookmarks to file");
                    }
                } else {
                    error!("failed to acquire write lock for bookmarks on shutdown");
                }
                break;
            }
        }

        Ok(())
    }
    #[instrument(skip(self))]
    async fn handle_event(&mut self, event: &crossterm::event::Event) -> Result<(), AppError> {
        use crossterm::event::Event::Key;
        use crossterm::event::KeyCode::*;
        use rat_widget::event::ct_event;
        trace!(?event, "Handling event");
        if matches!(
            event,
            ct_event!(key press CONTROL-'c') | ct_event!(key press CONTROL-'q')
        ) {
            self.cancel_action.cancel();
            return Ok(());
        }
        if self.last_event_error.is_some() {
            if matches!(
                event,
                ct_event!(keycode press Esc) | ct_event!(keycode press Enter)
            ) {
                self.last_event_error = None;
            }
            return Ok(());
        }
        if matches!(event, ct_event!(key press CONTROL-'h')) {
            self.in_help = !self.in_help;
            self.help = Some(HELP_TEXT);
            return Ok(());
        }
        if self.in_help && matches!(event, ct_event!(keycode press Esc)) {
            self.in_help = false;
            return Ok(());
        }

        let capture_focus = self
            .components
            .iter()
            .any(|c| c.should_render() && c.capture_focus_event(event));
        let focus = focus(self)?;
        let outcome = focus.handle(event, Regular);
        trace!(outcome = ?outcome, "Focus");
        if let Outcome::Continue = outcome
            && let Key(key) = event
            && !capture_focus
        {
            self.handle_key(key).await?;
        }
        if let Key(key) = event {
            match key.code {
                Char(char)
                    if ('1'..='6').contains(&char)
                        && !self
                            .components
                            .iter()
                            .any(|c| c.should_render() && c.capture_focus_event(event)) =>
                {
                    //SAFETY: char is in range
                    let index: u8 = char
                        .to_digit(10)
                        .ok_or_else(|| {
                            AppError::Other(anyhow!("failed to parse focus shortcut from key"))
                        })?
                        .try_into()
                        .map_err(|_| {
                            AppError::Other(anyhow!("focus shortcut is out of expected range"))
                        })?;
                    //SAFETY: cid is always in map, and map is static
                    trace!("Focusing {}", index);
                    let cid_map = CIDMAP
                        .get()
                        .ok_or_else(|| AppError::ErrorSettingGlobal("component id map"))?;
                    let cid = cid_map.get(&index).ok_or_else(|| {
                        AppError::Other(anyhow!("component id {index} not found in focus map"))
                    })?;
                    //SAFETY: cid is in map, and map is static
                    let component = unsafe { self.components.get_unchecked(*cid) };

                    if let Some(f) = self.focus.as_mut() {
                        f.focus(component.as_ref());
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }
    async fn handle_key(&mut self, key: &crossterm::event::KeyEvent) -> Result<(), AppError> {
        use crossterm::event::KeyCode::*;
        if matches!(key.code, Char('q'))
            | matches!(
                key,
                KeyEvent {
                    code: Char('c' | 'q'),
                    modifiers: crossterm::event::KeyModifiers::CONTROL,
                    ..
                }
            )
        {
            self.cancel_action.cancel();
        }
        if matches!(key.code, Char('?')) {
            self.in_help = !self.in_help;
        }

        Ok(())
    }

    fn has_animated_components(&self) -> bool {
        self.components
            .iter()
            .any(|component| component.should_render() && component.is_animating())
    }

    fn draw(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<impl std::io::Write>>,
    ) -> Result<(), AppError> {
        terminal.draw(|f| {
            let elapsed = self.last_frame.elapsed();
            self.last_frame = time::Instant::now();
            let area = f.area();
            let fullscreen = self.current_screen == MainScreen::DetailsFullscreen;
            let layout = if fullscreen {
                layout::Layout::fullscreen(area)
            } else {
                layout::Layout::new(area)
            };
            for component in self.components.iter() {
                if component.should_render()
                    && let Some(p) = component.cursor()
                {
                    f.set_cursor_position(p);
                }
            }
            let buf = f.buffer_mut();

            for component in self.components.iter_mut() {
                if component.should_render() {
                    component.render(layout, buf);
                }
            }
            if !fullscreen {
                for component in self.dumb_components.iter_mut() {
                    component.render(layout, buf);
                }
            }
            if self.in_help {
                let help_text = self.help.unwrap_or(HELP_TEXT);
                let help_component = components::help::HelpComponent::new(help_text)
                    .set_constraint(30)
                    .block(
                        Block::bordered()
                            .title("Help")
                            .padding(Padding::horizontal(2))
                            .border_type(ratatui::widgets::BorderType::Rounded),
                    );
                help_component.render(area, buf);
            }
            if let Some(err) = self.last_event_error.as_ref() {
                let popup_area = area.centered(Constraint::Percentage(60), Constraint::Length(5));
                Clear.render(popup_area, buf);
                let popup = Paragraph::new(err.as_str())
                    .wrap(Wrap { trim: false })
                    .block(
                        Block::bordered()
                            .title("Error")
                            .title_bottom("Esc/Enter: dismiss")
                            .padding(Padding::horizontal(1))
                            .border_type(ratatui::widgets::BorderType::Rounded),
                    );
                popup.render(popup_area, buf);
            }
            if let Some(ref mut toast_engine) = self.toast_engine {
                toast_engine.set_area(area);
                toast_engine.render_ref(area, buf);
                self.effects_manager.process_effects(elapsed, buf, area);
            }
        })?;
        Ok(())
    }
}

#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Action {
    None,
    Tick,
    Quit,
    AppEvent(crossterm::event::Event),
    RefreshIssueList,
    NewPage(Arc<Page<Issue>>, MergeStrategy),
    ForceRender,
    SelectedIssue {
        number: u64,
        labels: Vec<Label>,
    },
    SelectedIssuePreview {
        seed: IssuePreviewSeed,
    },
    IssuePreviewLoaded {
        number: u64,
        open_prs: Vec<PrSummary>,
    },
    IssuePreviewError {
        number: u64,
        message: String,
    },
    BookmarkTitleLoaded {
        number: u64,
        title: Arc<str>,
    },
    BookmarkTitleLoadError {
        number: u64,
        message: Arc<str>,
    },
    BookmarkedIssueLoaded {
        issue_id: IssueId,
    },
    BookmarkedIssueLoadError {
        number: u64,
        message: Arc<str>,
    },
    EnterIssueDetails {
        seed: IssueConversationSeed,
    },
    ChangeIssueBodyPreview(Arc<str>),
    IssueListPreviewUpdated {
        issue_ids: Vec<IssueId>,
        selected_number: u64,
    },
    IssueCommentsLoaded {
        number: u64,
        comments: Vec<CommentView>,
    },
    IssueTimelineLoaded {
        number: u64,
        events: Vec<TimelineEventView>,
    },
    IssueTimelineError {
        number: u64,
        message: String,
    },
    IssueReactionsLoaded {
        reactions: HashMap<u64, Vec<(ReactionContent, u64)>>,
        own_reactions: HashMap<u64, Vec<ReactionContent>>,
    },
    IssueBodyReactionsLoaded {
        number: u64,
        reactions: Vec<(ReactionContent, u64)>,
        own_reactions: Vec<ReactionContent>,
    },
    IssueReactionEditError {
        comment_id: u64,
        message: String,
    },
    IssueCommentPosted {
        number: u64,
        comment: CommentView,
    },
    IssueCommentsError {
        number: u64,
        message: String,
    },
    IssueCommentPostError {
        number: u64,
        message: String,
    },
    IssueCommentEditFinished {
        issue_number: u64,
        comment_id: u64,
        result: std::result::Result<String, String>,
    },
    IssueBodyEditFinished {
        issue_number: u64,
        result: std::result::Result<String, String>,
    },
    IssueCommentPatched {
        issue_number: u64,
        comment: CommentView,
    },
    IssueBodyPatched {
        issue_id: IssueId,
    },
    EnterIssueCreate,
    IssueCreateSuccess {
        issue_id: IssueId,
    },
    IssueCreateError {
        message: String,
    },
    IssueCloseSuccess {
        issue_id: IssueId,
    },
    IssueCloseError {
        number: u64,
        message: String,
    },
    IssueLabelsUpdated {
        number: u64,
        labels: Vec<Label>,
    },
    LabelMissing {
        name: String,
    },
    LabelEditError {
        message: String,
    },
    LabelSearchPageAppend {
        request_id: u64,
        items: Vec<Label>,
        scanned: u32,
        matched: u32,
    },
    LabelSearchFinished {
        request_id: u64,
        scanned: u32,
        matched: u32,
    },
    LabelSearchError {
        request_id: u64,
        message: String,
    },
    ChangeIssueScreen(MainScreen),
    FinishedLoading,
    ForceFocusChange,
    ForceFocusChangeRev,
    SetHelp(&'static [HelpElementKind]),
    EditorModeChanged(bool),
    ToastAction(ratatui_toaster::ToastMessage),
}

impl From<ratatui_toaster::ToastMessage> for Action {
    fn from(value: ratatui_toaster::ToastMessage) -> Self {
        Self::ToastAction(value)
    }
}

#[derive(Debug, Clone)]
pub enum MergeStrategy {
    Append,
    Replace,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CloseIssueReason {
    Completed,
    NotPlanned,
    Duplicate,
}

impl CloseIssueReason {
    pub const ALL: [Self; 3] = [Self::Completed, Self::NotPlanned, Self::Duplicate];

    pub const fn label(self) -> &'static str {
        match self {
            Self::Completed => "Completed",
            Self::NotPlanned => "Not planned",
            Self::Duplicate => "Duplicate",
        }
    }

    pub const fn to_octocrab(self) -> octocrab::models::issues::IssueStateReason {
        match self {
            Self::Completed => octocrab::models::issues::IssueStateReason::Completed,
            Self::NotPlanned => octocrab::models::issues::IssueStateReason::NotPlanned,
            Self::Duplicate => octocrab::models::issues::IssueStateReason::Duplicate,
        }
    }
}

fn finish_teardown() -> Result<()> {
    let mut stdout = stdout();
    execute!(stdout, PopKeyboardEnhancementFlags)?;
    execute!(stdout, DisableBracketedPaste)?;

    Ok(())
}

fn setup_terminal() -> Result<()> {
    let mut stdout = stdout();
    execute!(
        stdout,
        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::REPORT_EVENT_TYPES)
    )?;
    execute!(
        stdout,
        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES)
    )?;
    execute!(
        stdout,
        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
    )?;
    execute!(
        stdout,
        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
    )?;
    execute!(stdout, EnableBracketedPaste)?;

    Ok(())
}

fn setup_more_panic_hooks() {
    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        // we want to log the panic with tracing, but also preserve the default panic behavior of printing to stderr and aborting
        tracing::error!(panic_info = ?info, "Panic occurred");
        let _ = finish_teardown();
        hook(info);
    }));
}

fn toast_action(message: impl Into<String>, toast_type: ratatui_toaster::ToastType) -> Action {
    use ratatui_toaster::ToastPosition::TopRight;
    Action::ToastAction(ratatui_toaster::ToastMessage::Show {
        message: message.into(),
        toast_type,
        position: TopRight,
    })
}