aboutsummaryrefslogtreecommitdiff
path: root/ticket/src/tui.rs
blob: e1aa66656927ced726aefd9fb00297eaf2f03c2e (plain)
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
use crate::{
  actions::{
    get_closed_tickets,
    get_open_tickets,
  },
  Status,
  Ticket,
};
use anyhow::Result;
use std::{
  collections::BTreeMap,
  io,
  sync::mpsc,
  thread,
  time::Duration,
};
use termion::{
  event::Key,
  input::{
    MouseTerminal,
    TermRead,
  },
  raw::IntoRawMode,
  screen::AlternateScreen,
};
use tui::{
  backend::TermionBackend,
  layout::{
    Alignment,
    Constraint,
    Direction,
    Layout,
  },
  style::{
    Color,
    Modifier,
    Style,
  },
  widgets::{
    Block,
    Borders,
    Paragraph,
    Row,
    Table,
    Tabs,
    Text,
    Widget,
  },
  Terminal,
};

pub struct TabsState<'a> {
  pub titles: Vec<&'a str>,
  pub index: usize,
}

impl<'a> TabsState<'a> {
  pub fn new(titles: Vec<&'a str>) -> TabsState {
    TabsState { titles, index: 0 }
  }

  pub fn next(&mut self) {
    self.index = (self.index + 1) % self.titles.len();
  }

  pub fn previous(&mut self) {
    if self.index > 0 {
      self.index -= 1;
    } else {
      self.index = self.titles.len() - 1;
    }
  }
}
pub enum Event<I> {
  Input(I),
  Tick,
}

pub struct TicketState {
  pub tickets: BTreeMap<String, Vec<Ticket>>,
  pub index: usize,
  pub status: Status,
}

impl TicketState {
  pub fn new(tickets: BTreeMap<String, Vec<Ticket>>) -> Self {
    Self {
      tickets,
      index: 0,
      status: Status::Open,
    }
  }

  fn len(&self) -> usize {
    match self.status {
      Status::Open => self.tickets.get("Open").unwrap().len(),
      Status::Closed => self.tickets.get("Closed").unwrap().len(),
    }
  }

  pub fn next(&mut self) {
    self.index = (self.index + 1) % self.len();
  }

  pub fn previous(&mut self) {
    if self.index > 0 {
      self.index -= 1;
    } else {
      self.index = self.len() - 1;
    }
  }
}
/// A small event handler that wrap termion input and tick events. Each event
/// type is handled in its own thread and returned to a common `Receiver`
#[allow(dead_code)]
pub struct Events {
  rx: mpsc::Receiver<Event<Key>>,
  input_handle: thread::JoinHandle<()>,
  tick_handle: thread::JoinHandle<()>,
}

struct App<'a> {
  tabs: TabsState<'a>,
  tickets: TicketState,
}
#[derive(Debug, Clone, Copy)]
pub struct Config {
  pub exit_key: Key,
  pub tick_rate: Duration,
}

impl Default for Config {
  fn default() -> Config {
    Config {
      exit_key: Key::Char('q'),
      tick_rate: Duration::from_millis(250),
    }
  }
}

impl Events {
  pub fn new() -> Events {
    Events::with_config(Config::default())
  }

  pub fn with_config(config: Config) -> Events {
    let (tx, rx) = mpsc::channel();
    let input_handle = {
      let tx = tx.clone();
      thread::spawn(move || {
        let stdin = io::stdin();
        for evt in stdin.keys() {
          if let Ok(key) = evt {
            if tx.send(Event::Input(key)).is_err() {
              return;
            }
            if key == config.exit_key {
              return;
            }
          }
        }
      })
    };
    let tick_handle = {
      let tx = tx.clone();
      thread::spawn(move || {
        let tx = tx.clone();
        loop {
          tx.send(Event::Tick).unwrap();
          thread::sleep(config.tick_rate);
        }
      })
    };
    Events {
      rx,
      input_handle,
      tick_handle,
    }
  }

  pub fn next(&self) -> Result<Event<Key>, mpsc::RecvError> {
    self.rx.recv()
  }
}
pub fn run() -> Result<()> {
  // Terminal initialization
  let stdout = io::stdout().into_raw_mode()?;
  let stdout = MouseTerminal::from(stdout);
  let stdout = AlternateScreen::from(stdout);
  let backend = TermionBackend::new(stdout);
  let mut terminal = Terminal::new(backend)?;
  terminal.hide_cursor()?;

  let events = Events::new();

  // App
  let mut app = App {
    tabs: TabsState::new(vec!["Open", "Closed"]),
    tickets: {
      let mut map = BTreeMap::new();
      map.insert("Open".into(), get_open_tickets()?);
      map.insert("Closed".into(), get_closed_tickets()?);
      TicketState::new(map)
    },
  };

  // Main loop
  loop {
    terminal.draw(|mut f| {
      let size = f.size();
      let vertical = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(0)].as_ref())
        .split(size);
      let horizontal = Layout::default()
        .direction(Direction::Horizontal)
        .vertical_margin(3)
        .constraints(
          [Constraint::Percentage(30), Constraint::Percentage(70)].as_ref(),
        )
        .split(size);

      Tabs::default()
        .block(Block::default().borders(Borders::ALL).title("Status"))
        .titles(&app.tabs.titles)
        .select(app.tabs.index)
        .style(Style::default().fg(Color::Cyan))
        .highlight_style(Style::default().fg(Color::Yellow))
        .render(&mut f, vertical[0]);

      match app.tabs.index {
        0 => {
          app.table("Open").render(&mut f, horizontal[0]);

          Paragraph::new(app.description("Open").iter())
            .block(Block::default().title("Description").borders(Borders::ALL))
            .alignment(Alignment::Left)
            .wrap(true)
            .render(&mut f, horizontal[1]);
        }
        1 => {
          app.table("Closed").render(&mut f, horizontal[0]);

          Paragraph::new(app.description("Closed").iter())
            .block(Block::default().title("Description").borders(Borders::ALL))
            .alignment(Alignment::Left)
            .wrap(true)
            .render(&mut f, horizontal[1]);
        }
        _ => {}
      }
    })?;

    match events.next()? {
      Event::Input(input) => match input {
        Key::Char('q') => {
          break;
        }
        Key::Right => {
          if app.tabs.index == 0 {
            app.tickets.status = Status::Closed;
            app.tickets.index = 0;
          }
          app.tabs.next();
        }
        Key::Left => {
          if app.tabs.index != 0 {
            app.tickets.status = Status::Open;
            app.tickets.index = 0;
          }
          app.tabs.previous();
        }
        Key::Up => app.tickets.previous(),
        Key::Down => app.tickets.next(),
        _ => {}
      },
      Event::Tick => continue,
    }
  }
  Ok(())
}

impl<'a> App<'a> {
  fn table(&self, tab: &'a str) -> impl Widget + '_ {
    Table::new(
      ["Id", "Title"].iter(),
      self
        .tickets
        .tickets
        .get(tab)
        .unwrap()
        .iter()
        .enumerate()
        .map(move |(idx, i)| {
          let data = vec![i.id.to_string(), i.title.to_string()].into_iter();
          let normal_style = Style::default().fg(Color::Yellow);
          let selected_style =
            Style::default().fg(Color::White).modifier(Modifier::BOLD);
          if idx == self.tickets.index {
            Row::StyledData(data, selected_style)
          } else {
            Row::StyledData(data, normal_style)
          }
        }),
    )
    .block(Block::default().title(tab).borders(Borders::ALL))
    .header_style(Style::default().fg(Color::Yellow))
    .widths(&[Constraint::Percentage(30), Constraint::Percentage(70)])
    .style(Style::default().fg(Color::White))
    .column_spacing(1)
  }

  fn description(&self, tab: &'a str) -> Vec<Text> {
    let mut description = vec![];
    for (idx, i) in self.tickets.tickets.get(tab).unwrap().iter().enumerate() {
      if idx == self.tickets.index {
        description = vec![Text::raw(i.description.to_owned())];
        break;
      }
    }

    description
  }
}