glues-tui 0.8.1

TUI and WASM frontends for the Glues note-taking experience
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
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
mod tree_item;

use {
    crate::{
        action::{Action, TuiAction},
        input::{Input, KeyCode, KeyEvent, to_textarea_input},
        logger::*,
    },
    glues_core::{
        NotebookEvent,
        data::Note,
        state::notebook::{DirectoryItem, Tab},
        types::{Id, NoteId},
    },
    ratatui::{text::Line, widgets::ListState},
    std::collections::HashMap,
    tui_textarea::TextArea,
};

#[cfg(not(target_arch = "wasm32"))]
use arboard::Clipboard;

pub use tree_item::{TreeItem, TreeItemKind};

pub const REMOVE_NOTE: &str = "Remove note";
pub const RENAME_NOTE: &str = "Rename note";

pub const ADD_NOTE: &str = "Add note";
pub const ADD_DIRECTORY: &str = "Add directory";
pub const RENAME_DIRECTORY: &str = "Rename directory";
pub const REMOVE_DIRECTORY: &str = "Remove directory";

pub const CLOSE: &str = "Close";

pub const NOTE_ACTIONS: [&str; 3] = [RENAME_NOTE, REMOVE_NOTE, CLOSE];
pub const DIRECTORY_ACTIONS: [&str; 5] = [
    ADD_NOTE,
    ADD_DIRECTORY,
    RENAME_DIRECTORY,
    REMOVE_DIRECTORY,
    CLOSE,
];

#[derive(Clone, Copy, PartialEq)]
pub enum ContextState {
    NoteTreeBrowsing,
    NoteTreeNumbering,
    NoteTreeGateway,
    NoteActionsDialog,
    DirectoryActionsDialog,
    MoveMode,
    EditorNormalMode { idle: bool },
    EditorVisualMode,
    EditorInsertMode,
}

impl ContextState {
    pub fn is_editor(&self) -> bool {
        matches!(
            self,
            ContextState::EditorNormalMode { .. }
                | ContextState::EditorInsertMode
                | ContextState::EditorVisualMode
        )
    }
}

pub struct NotebookContext {
    pub state: ContextState,

    // note tree
    pub tree_state: ListState,
    pub tree_items: Vec<TreeItem>,
    pub tree_width: u16,

    // note actions
    pub note_actions_state: ListState,

    // directory actions
    pub directory_actions_state: ListState,

    // editor
    pub editor_height: u16,
    pub tabs: Vec<Tab>,
    pub tab_index: Option<usize>,
    pub editors: HashMap<NoteId, EditorItem>,

    pub show_line_number: bool,
    pub show_browser: bool,
    pub line_yanked: bool,
    pub yank: Option<String>,
}

pub struct EditorItem {
    pub editor: TextArea<'static>,
    pub dirty: bool,
}

impl Default for NotebookContext {
    fn default() -> Self {
        Self {
            state: ContextState::NoteTreeBrowsing,
            tree_state: ListState::default().with_selected(Some(0)),
            tree_items: vec![],
            tree_width: 45,

            note_actions_state: ListState::default(),
            directory_actions_state: ListState::default(),

            editor_height: 0,
            tabs: vec![],
            tab_index: None,
            editors: HashMap::new(),

            show_line_number: true,
            show_browser: true,
            line_yanked: false,
            yank: None,
        }
    }
}

impl NotebookContext {
    pub fn get_opened_note(&self) -> Option<&Note> {
        self.tab_index
            .and_then(|i| self.tabs.get(i))
            .map(|t| &t.note)
    }

    pub fn get_editor(&self) -> &TextArea<'static> {
        let note_id = &self
            .tab_index
            .and_then(|i| self.tabs.get(i))
            .log_expect("[NotebookContext::get_editor] no opened note")
            .note
            .id;

        &self
            .editors
            .get(note_id)
            .log_expect("[NotebookContext::get_editor] editor not found")
            .editor
    }

    pub fn get_editor_mut(&mut self) -> &mut TextArea<'static> {
        let note_id = &self
            .tab_index
            .and_then(|i| self.tabs.get(i))
            .log_expect("[NotebookContext::get_editor_mut] no opened note")
            .note
            .id;

        &mut self
            .editors
            .get_mut(note_id)
            .log_expect("[NotebookContext::get_editor_mut] editor not found")
            .editor
    }

    pub fn mark_dirty(&mut self) {
        if let Some(editor_item) = self
            .tab_index
            .and_then(|i| self.tabs.get(i))
            .and_then(|tab| self.editors.get_mut(&tab.note.id))
        {
            editor_item.dirty = true;
        }
    }

    pub fn mark_clean(&mut self, note_id: &NoteId) {
        if let Some(editor_item) = self.editors.get_mut(note_id) {
            editor_item.dirty = false;
        }
    }

    pub fn update_items(&mut self, directory_item: &DirectoryItem) {
        self.tree_items = self.flatten(directory_item, 0, true);
    }

    fn flatten(
        &self,
        directory_item: &DirectoryItem,
        depth: usize,
        selectable: bool,
    ) -> Vec<TreeItem> {
        let id = self
            .tree_state
            .selected()
            .and_then(|i| self.tree_items.get(i))
            .map(|item| item.id());
        let is_move_mode = matches!(self.state, ContextState::MoveMode);
        let selectable = !is_move_mode || (selectable && Some(&directory_item.directory.id) != id);

        let mut items = vec![TreeItem {
            depth,
            target: Some(&directory_item.directory.id) == id,
            selectable,
            kind: TreeItemKind::Directory {
                directory: directory_item.directory.clone(),
                opened: directory_item.children.is_some(),
            },
        }];

        if let Some(children) = &directory_item.children {
            for item in &children.directories {
                items.extend(self.flatten(item, depth + 1, selectable));
            }

            for note in &children.notes {
                items.push(TreeItem {
                    depth: depth + 1,
                    target: Some(&note.id) == id,
                    selectable: !is_move_mode,
                    kind: TreeItemKind::Note { note: note.clone() },
                })
            }
        }

        items
    }

    pub fn select_item(&mut self, id: &Id) {
        for (i, item) in self.tree_items.iter().enumerate() {
            if item.id() == id {
                self.tree_state.select(Some(i));
                break;
            }
        }
    }

    pub fn select_first(&mut self) {
        let i = self
            .tree_items
            .iter()
            .enumerate()
            .find(|(_, item)| item.selectable)
            .map(|(i, _)| i);

        if i.is_some() {
            self.tree_state.select(i);
        }
    }

    pub fn select_last(&mut self) {
        let i = self
            .tree_items
            .iter()
            .enumerate()
            .rev()
            .find(|(_, item)| item.selectable)
            .map(|(i, _)| i);

        if i.is_some() {
            self.tree_state.select(i);
        }
    }

    pub fn select_next(&mut self, step: usize) {
        let i = match self.tree_state.selected().unwrap_or_default() + step {
            i if i >= self.tree_items.len() => self.tree_items.len() - 1,
            i => i,
        };

        let i = self
            .tree_items
            .iter()
            .enumerate()
            .skip(i)
            .find(|(_, item)| item.selectable)
            .map(|(i, _)| i);

        if i.is_some() {
            self.tree_state.select(i);
        }
    }

    pub fn select_prev(&mut self, step: usize) {
        let i = self
            .tree_state
            .selected()
            .unwrap_or_default()
            .saturating_sub(step);

        let i = self
            .tree_items
            .iter()
            .enumerate()
            .rev()
            .skip(self.tree_items.len() - i - 1)
            .find(|(_, item)| item.selectable)
            .map(|(i, _)| i);

        if i.is_some() {
            self.tree_state.select(i);
        }
    }

    pub fn select_next_dir(&mut self) {
        let i = self.tree_state.selected().unwrap_or_default() + 1;

        if i >= self.tree_items.len() {
            return;
        }

        let i = self
            .tree_items
            .iter()
            .enumerate()
            .skip(i)
            .filter(|(_, item)| item.is_directory())
            .find(|(_, item)| item.selectable)
            .map(|(i, _)| i);

        if i.is_some() {
            self.tree_state.select(i);
        }
    }

    pub fn select_prev_dir(&mut self) {
        let i = self
            .tree_state
            .selected()
            .unwrap_or_default()
            .saturating_sub(1);

        let i = self
            .tree_items
            .iter()
            .enumerate()
            .rev()
            .skip(self.tree_items.len() - i - 1)
            .filter(|(_, item)| item.is_directory())
            .find(|(_, item)| item.selectable)
            .map(|(i, _)| i);

        if i.is_some() {
            self.tree_state.select(i);
        }
    }

    pub fn selected(&self) -> &TreeItem {
        self.tree_state
            .selected()
            .and_then(|i| self.tree_items.get(i))
            .log_expect("[NotebookContext::selected] selected must not be empty")
    }

    pub fn open_note(&mut self, note_id: NoteId, content: String) {
        let item = EditorItem {
            editor: TextArea::from(content.lines()),
            dirty: false,
        };

        self.editors.insert(note_id, item);
    }

    pub fn apply_yank(&mut self) {
        if self.tabs.is_empty() {
            return;
        }

        if let Some(yank) = self.yank.as_ref().cloned() {
            self.get_editor_mut().set_yank_text(yank);
        }
    }

    pub fn update_yank(&mut self) {
        let text = self.get_editor().yank_text();

        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut clipboard) = Clipboard::new() {
            let _ = clipboard.set_text(&text);
        }

        #[cfg(target_arch = "wasm32")]
        crate::web::copy_to_clipboard(&text);

        self.yank = Some(text);
    }

    pub fn consume(&mut self, input: &Input) -> Action {
        let code = match input {
            Input::Key(key) => key.code,
            _ => return Action::None,
        };

        match self.state {
            ContextState::NoteTreeBrowsing => self.consume_on_note_tree_browsing(code),
            ContextState::NoteTreeGateway
            | ContextState::NoteTreeNumbering
            | ContextState::MoveMode => Action::PassThrough,
            ContextState::EditorNormalMode { idle } => self.consume_on_editor_normal(input, idle),
            ContextState::EditorVisualMode => Action::PassThrough,
            ContextState::EditorInsertMode => self.consume_on_editor_insert(input),
            ContextState::NoteActionsDialog => self.consume_on_note_actions(code),
            ContextState::DirectoryActionsDialog => self.consume_on_directory_actions(code),
        }
    }

    fn consume_on_note_tree_browsing(&mut self, code: KeyCode) -> Action {
        match code {
            KeyCode::Char('m') => {
                if self
                    .tree_state
                    .selected()
                    .and_then(|idx| self.tree_items.get(idx))
                    .log_expect("[NotebookContext::consume] selected must not be empty")
                    .is_directory()
                {
                    self.directory_actions_state.select_first();
                } else {
                    self.note_actions_state.select_first();
                }

                Action::PassThrough
            }
            KeyCode::Esc => TuiAction::OpenNotebookQuitMenu {
                save_before_open: false,
            }
            .into(),
            _ => Action::PassThrough,
        }
    }

    fn consume_on_editor_normal(&mut self, input: &Input, idle: bool) -> Action {
        let code = match input {
            Input::Key(key) => key.code,
            _ => return Action::None,
        };

        match code {
            KeyCode::Esc if idle => TuiAction::OpenNotebookQuitMenu {
                save_before_open: true,
            }
            .into(),
            KeyCode::Tab if idle => {
                self.show_browser = true;
                self.update_yank();

                TuiAction::SaveAndPassThrough.into()
            }
            _ => Action::PassThrough,
        }
    }

    fn consume_on_editor_insert(&mut self, input: &Input) -> Action {
        match input {
            Input::Key(KeyEvent {
                code: KeyCode::Esc, ..
            }) => Action::Dispatch(NotebookEvent::ViewNote.into()),
            Input::Key(KeyEvent {
                code: KeyCode::Char('h'),
                modifiers,
                ..
            }) if modifiers.ctrl => TuiAction::ShowEditorKeymap.into(),
            Input::Key(KeyEvent {
                code: KeyCode::Char('c' | 'x' | 'w' | 'k' | 'j'),
                modifiers,
                ..
            }) if modifiers.ctrl => {
                self.line_yanked = false;
                if let Some(text_input) = to_textarea_input(input) {
                    self.get_editor_mut().input(text_input);
                }
                Action::None
            }
            _ => {
                if let Some(text_input) = to_textarea_input(input) {
                    self.get_editor_mut().input(text_input);
                }
                Action::None
            }
        }
    }

    fn consume_on_note_actions(&mut self, code: KeyCode) -> Action {
        match code {
            KeyCode::Char('j') | KeyCode::Down => {
                self.note_actions_state.select_next();
                Action::None
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.note_actions_state.select_previous();
                Action::None
            }
            KeyCode::Esc => Action::Dispatch(NotebookEvent::CloseNoteActionsDialog.into()),
            KeyCode::Enter => {
                match NOTE_ACTIONS[self
                    .note_actions_state
                    .selected()
                    .log_expect("note action must not be empty")]
                {
                    RENAME_NOTE => TuiAction::Prompt {
                        message: vec![Line::raw("Enter new note name:")],
                        action: Box::new(TuiAction::RenameNote.into()),
                        default: Some(self.selected().name()),
                    }
                    .into(),
                    REMOVE_NOTE => TuiAction::Confirm {
                        message: "Confirm to remove note?".to_owned(),
                        action: Box::new(TuiAction::RemoveNote.into()),
                    }
                    .into(),
                    CLOSE => Action::Dispatch(NotebookEvent::CloseNoteActionsDialog.into()),
                    _ => Action::None,
                }
            }
            _ => Action::PassThrough,
        }
    }

    fn consume_on_directory_actions(&mut self, code: KeyCode) -> Action {
        match code {
            KeyCode::Char('j') | KeyCode::Down => {
                self.directory_actions_state.select_next();
                Action::None
            }
            KeyCode::Char('k') | KeyCode::Up => {
                self.directory_actions_state.select_previous();
                Action::None
            }
            KeyCode::Enter => {
                match DIRECTORY_ACTIONS[self
                    .directory_actions_state
                    .selected()
                    .log_expect("directory action must not be empty")]
                {
                    ADD_NOTE => TuiAction::Prompt {
                        message: vec![Line::raw("Enter note name:")],
                        action: Box::new(TuiAction::AddNote.into()),
                        default: None,
                    }
                    .into(),
                    ADD_DIRECTORY => TuiAction::Prompt {
                        message: vec![Line::raw("Enter directory name:")],
                        action: Box::new(TuiAction::AddDirectory.into()),
                        default: None,
                    }
                    .into(),
                    RENAME_DIRECTORY => TuiAction::Prompt {
                        message: vec![Line::raw("Enter new directory name:")],
                        action: Box::new(TuiAction::RenameDirectory.into()),
                        default: Some(self.selected().name()),
                    }
                    .into(),
                    REMOVE_DIRECTORY => TuiAction::Confirm {
                        message: "Confirm to remove directory?".to_owned(),
                        action: Box::new(TuiAction::RemoveDirectory.into()),
                    }
                    .into(),
                    CLOSE => Action::Dispatch(NotebookEvent::CloseDirectoryActionsDialog.into()),
                    _ => Action::None,
                }
            }
            KeyCode::Esc => Action::Dispatch(NotebookEvent::CloseDirectoryActionsDialog.into()),
            _ => Action::PassThrough,
        }
    }
}