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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
use crate::config::DiaryConfig;
use crate::{data, error, io, ui};
use chrono::Local;
use itertools::Itertools;
use ratatui::crossterm::event::KeyCode;
use ratatui::{prelude::*, widgets::*};
use tui_textarea::TextArea;
/// Describes the current mode of the UI.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
enum SelectMode {
/// Selecting a note from the list.
#[default]
Select,
/// File managment submenu
SubmenuFile,
/// Sorting submenu
SubmenuSorting,
/// Typing into the filter box.
Filter,
/// Show the help screen for the filter box.
FilterHelp,
/// Show a list of all tags in the vault.
TagList(usize),
/// Typing into the create box.
Create,
/// Typing into the create box to rename a note.
Rename,
/// Typing into the create box to move a note.
Move,
/// Confirmation for deletion
Delete,
}
/// Describes when to show a which stats area.
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
pub enum StatsShow {
// Always shows both stats
#[default]
Both,
// Shows local stats when filtering and nothing otherwise
Relevant,
// Always shows only local stats
Local,
}
/// The select screen shows the user statistical information about their notes and allows them to select one for display.
pub struct SelectScreen {
// === DATA ===
/// A reference to the index of all notes
index: data::NoteIndexContainer,
/// The currently displayed statistics for all notes.
local_stats: data::EnvironmentStats,
/// The currently displayed statistics for all notes matching the current filter.
global_stats: data::EnvironmentStats,
// === Config ===
/// The file manager this screen uses to enact the user's file system requests on the file system.
manager: io::FileManager,
/// The git repository the vault is stored in, if any.
git_manager: Option<io::GitManager>,
/// The HtmlBuider this screen uses to continuously build html files.
builder: io::HtmlBuilder,
/// The used styles.
styles: ui::UiStyles,
/// Configuration for the daily diary feature.
diary_config: DiaryConfig,
// === UI ===
/// The text area to type in filters.
filter_area: TextArea<'static>,
/// The text area used to create new notes.
name_area: TextArea<'static>,
/// Current input mode
mode: SelectMode,
/// Current state of the list
///
/// This is saved as a simple usize from which the ListState to use with ratatui is constructed in immediate mode.
/// This allows us to convert only the neccessary notes to ListItems and save some time.
selected: usize,
// === Sorting options ===
/// UI mode whether the user wants the filter conditions to all apply or if any (one of them) is enough.
any_conditions: bool,
/// UI mode whether to match tags by prefix or exactly.
tag_match: data::TagMatch,
/// Default sorting of the note list.
default_sorting: data::NoteColumn,
/// Default sorting direction of the note list.
default_sorting_asc: bool,
/// Default sorting of the note list.
sorting: data::NoteColumn,
/// Default sorting direction of the note list.
sorting_asc: bool,
/// How to display the two stats blocks.
stats_show: StatsShow,
/// What columns to display
column_config: Vec<(String, data::NoteColumn)>,
}
impl SelectScreen {
/// Creates a new stats screen, with no filter applied by default
pub fn new(
index: data::NoteIndexContainer,
manager: io::FileManager,
git_manager: Option<io::GitManager>,
builder: io::HtmlBuilder,
styles: ui::UiStyles,
config: &crate::Config,
) -> Self {
let mut res = Self {
local_stats: data::EnvironmentStats::new_with_filter(&index, data::Filter::default()),
global_stats: data::EnvironmentStats::new_with_filter(&index, data::Filter::default()),
index: index.clone(),
styles,
builder,
manager,
git_manager,
filter_area: TextArea::default(),
name_area: TextArea::default(),
mode: SelectMode::Select,
any_conditions: false,
tag_match: config.tag_match,
default_sorting: config.default_sorting,
default_sorting_asc: config.default_sorting_asc,
sorting: config.default_sorting,
sorting_asc: config.default_sorting_asc,
selected: 0,
stats_show: config.stats_show,
column_config: config.select_columns.clone(),
diary_config: config.diary.clone(),
};
res.local_stats
.sort(index, config.default_sorting, config.default_sorting_asc);
res.style_text_area();
res
}
/// Styling of TextArea extracted from constructor to keep it clean.
fn style_text_area(&mut self) {
// === Filter ===
// The actual title
let title_top = Line::from(vec![
Span::styled("F", self.styles.hotkey_style),
Span::styled("ilter", self.styles.title_style),
])
.left_aligned();
// The hotkey instructions at the bottom.
let instructions = Line::from(vec![
Span::styled("T", self.styles.hotkey_style),
Span::styled("ag List", self.styles.text_style),
Span::styled("──", self.styles.text_style),
Span::styled("C", self.styles.hotkey_style),
Span::styled("lear filter", self.styles.text_style),
])
.right_aligned();
let instructions_bot = Line::from(vec![
Span::styled("A", self.styles.hotkey_style),
Span::styled(
if self.any_conditions { "ny" } else { "ll" },
self.styles.text_style,
),
Span::styled(" Conditions", self.styles.text_style),
Span::styled("──", self.styles.text_style),
Span::styled("H", self.styles.hotkey_style),
Span::styled("elp", self.styles.text_style),
])
.right_aligned();
// Apply default self.styles to the filter area
self.filter_area.set_style(self.styles.input_style);
self.filter_area
.set_cursor_line_style(self.styles.input_style);
self.filter_area.set_block(
Block::bordered()
.title_top(title_top)
.title_top(instructions)
.title_bottom(instructions_bot),
);
// === Create ===
// The title
let title_top = Line::from(vec![Span::styled(
"Enter note name...",
self.styles.title_style,
)]);
// Apply default self.styles to the create area
self.name_area.set_style(self.styles.input_style);
self.name_area
.set_cursor_line_style(self.styles.input_style);
self.name_area.set_block(Block::bordered().title(title_top));
}
/// Sets the title & content of the name_area block
fn set_name_area(&mut self, title: &str, content: Option<String>) {
let title_top = Line::from(vec![Span::styled(
title.to_owned(),
self.styles.title_style,
)]);
self.name_area.set_block(Block::bordered().title(title_top));
// it is assumed the buffer is empty so far
if let Some(content) = content {
self.name_area.insert_str(content);
}
}
/// Returns the heights of the global and local stats area with this filter string
pub fn stats_heights(&self, filter_string: Option<&String>) -> (u16, u16) {
let filtered = filter_string.map(|s| !s.is_empty()).unwrap_or(false);
match self.stats_show {
StatsShow::Both => (5, 6),
StatsShow::Relevant => {
if filtered {
(0, 6)
} else {
(6, 0)
}
}
StatsShow::Local => (0, 6),
}
}
/// Sorts the display according to the current mode
fn set_mode_sort(&mut self, sorting: data::NoteColumn, sorting_asc: bool) {
self.sorting = sorting;
self.sorting_asc = sorting_asc;
self.local_stats
.sort(self.index.clone(), self.sorting, self.sorting_asc);
self.selected = 0;
}
/// Creates a filter from the current content of the filter area.
fn filter_from_input(&self) -> data::Filter {
self.filter_area
.lines()
.first()
.map(|l| data::Filter::new(l, self.any_conditions, self.tag_match))
.unwrap_or_default()
}
/// Reloads the displayed statistics, showing stats for only those elements of the index matching the specified filter.
/// Every filtering neccessarily triggers a non-stable resort.
fn filter(&mut self, filter: data::Filter) {
// actual filtering
self.local_stats = data::EnvironmentStats::new_with_filter(&self.index, filter);
// reset sorting
self.set_mode_sort(data::NoteColumn::Score, false);
}
/// Re-creates the global and local stats from the index.
/// To be performed after file management operations.
pub fn refresh_env_stats(&mut self) {
// Refresh global stats
self.global_stats =
data::EnvironmentStats::new_with_filter(&self.index, data::Filter::default());
// Refresh local stats
self.local_stats =
data::EnvironmentStats::new_with_filter(&self.index, self.filter_from_input());
// Refresh sorting
self.local_stats
.sort(self.index.clone(), self.sorting, self.sorting_asc);
}
}
impl super::Screen for SelectScreen {
fn update(&mut self, key: ratatui::crossterm::event::KeyEvent) -> error::Result<ui::Message> {
let key: ratatui::crossterm::event::KeyEvent = key;
// Check for mode
match self.mode {
// Main mode: Switch to modes, general command
SelectMode::Select => match key.code {
// Q: Quit application
KeyCode::Char('q' | 'Q') => return Ok(ui::Message::Quit),
// M: Got to file management submenu
KeyCode::Char('m' | 'M') => {
self.mode = SelectMode::SubmenuFile;
}
// S: Got to sorting submenu
KeyCode::Char('s' | 'S') => {
self.mode = SelectMode::SubmenuSorting;
}
// F, /: Go to filter mode
KeyCode::Char('f' | 'F' | '/') => {
self.mode = SelectMode::Filter;
}
// ?, h, H: Go to filter help mode
KeyCode::Char('?' | 'h' | 'H') => {
self.mode = SelectMode::FilterHelp;
}
// C: Clear filter
KeyCode::Char('c' | 'C') => {
let _ = super::extract_string_and_clear(&mut self.filter_area);
self.filter(data::Filter::default());
// reset filter to default
self.set_mode_sort(self.default_sorting, self.default_sorting_asc);
}
// A: Change all/any words requirement
KeyCode::Char('a' | 'A') => {
self.any_conditions = !self.any_conditions;
self.filter(self.filter_from_input());
self.style_text_area();
}
// T: Show tags list
KeyCode::Char('t' | 'T') => self.mode = SelectMode::TagList(0),
// Open selected item in editor
KeyCode::Char('e' | 'E') => {
self.mode = SelectMode::Select;
if let Some(res) = self
// get the selected item in the list for the id
.local_stats
.get_selected(self.selected)
// use this id in the index to get the note
.and_then(|env_stats| {
// use the id to get the path
self.index
.borrow()
.get(&env_stats.id)
.map(|note| note.path.clone())
})
{
// use the config to create a valid opening command
return Ok(ui::Message::OpenExternalCommand(Box::new(
self.manager.create_edit_command(&res)?,
)));
}
}
// Open view mode
KeyCode::Char('v' | 'V') => {
self.mode = SelectMode::Select;
if let Some(env_stats) = self.local_stats.get_selected(self.selected) {
if let Some(note) = self.index.borrow().get(&env_stats.id) {
self.builder.create_html(note, true)?;
return Ok(ui::Message::OpenExternalCommand(Box::new(
self.manager
.create_view_command(note, key.code == KeyCode::Char('v'))?,
)));
}
}
}
// Selection
// Down
KeyCode::Char('j' | 'J') | KeyCode::Down => {
self.selected = self
.selected
.saturating_add(1)
.min(self.local_stats.len().saturating_sub(1));
}
// Up
KeyCode::Char('k' | 'K') | KeyCode::Up => {
self.selected = self.selected.saturating_sub(1);
}
// PageDown
KeyCode::PageDown => {
self.selected = self
.selected
.saturating_add(10)
.min(self.local_stats.len().saturating_sub(1));
}
// PageUp
KeyCode::PageUp => {
self.selected = self.selected.saturating_sub(10);
}
// To the start
KeyCode::Char('0') => {
self.selected = 0;
}
// Open selected item in display view
KeyCode::Enter | KeyCode::Char('l' | 'L') | KeyCode::Right => {
if let Some(env_stats) = self.local_stats.get_selected(self.selected) {
return Ok(ui::Message::DisplayStackPush(env_stats.id.clone()));
}
}
// Shortcut to the diary entry for the current day
KeyCode::Char('d' | 'D') if self.diary_config.enabled => {
// Get the current date
let title_format = self.diary_config.title_format.as_deref().unwrap_or("%F");
// Determine the desired note id for today's diary entry
let diary_entry_name = format!("{}", Local::now().format(title_format));
let diary_entry_id = data::name_to_id(&diary_entry_name);
// Create the note if it note yet exists
if self.index.borrow().get(&diary_entry_id).is_none() {
let created_note_path = self.manager.create_note_file(
&diary_entry_name,
self.diary_config.initial_content.clone(),
)?;
// Directly insert the new note into the index rather than relying on
// the file watcher.
self.index
.borrow_mut()
.insert_note_from_path(&created_note_path)?;
self.refresh_env_stats();
// Open the new note in an external editor
return Ok(ui::Message::OpenExternalCommand(Box::new(
self.manager.create_edit_command(&created_note_path)?,
)));
}
return Ok(ui::Message::DisplayStackPush(diary_entry_id));
}
_ => {}
},
// Filter mode: Type in filter values
SelectMode::Filter => {
match key.code {
// Escape or Enter: Back to main mode
KeyCode::Esc | KeyCode::Enter => {
self.mode = SelectMode::Select;
self.filter(self.filter_from_input());
}
// All other key events are passed on to the text area, then the filter is immediately applied
_ => {
// Else -> Pass on to the text area
self.filter_area.input(key);
self.filter(self.filter_from_input());
}
};
}
SelectMode::FilterHelp => {
match key.code {
// Escape or Enter: Back to main mode
KeyCode::Esc | KeyCode::Char('c' | 'C') => {
self.mode = SelectMode::Select;
}
// All other key events are ignored
_ => {}
};
}
SelectMode::TagList(selected) => {
match key.code {
// Escape or Enter: Back to main mode
KeyCode::Esc | KeyCode::Char('c' | 'C') => {
self.mode = SelectMode::Select;
}
// J: Navigate Down
KeyCode::Char('j' | 'J') | KeyCode::Down => {
let total = self.index.borrow().tags_vec().len();
self.mode = SelectMode::TagList(
(selected.saturating_add(1)).min(total.saturating_sub(1)),
);
}
// K: Navigate Up
KeyCode::Char('k' | 'K') | KeyCode::Up => {
self.mode = SelectMode::TagList(selected.saturating_sub(1));
}
// PageDown
KeyCode::PageDown => {
let total = self.index.borrow().tags_vec().len();
self.mode = SelectMode::TagList(
(selected.saturating_add(10)).min(total.saturating_sub(1)),
);
}
// PageUp
KeyCode::PageUp => {
self.mode = SelectMode::TagList(selected.saturating_sub(10));
}
// Enter: Find the tag that is selected, then filter by it
KeyCode::Enter => {
// extract the selected tag
if let Some(tag) = self
.index
.borrow()
.tags_vec()
.get(selected)
.map(|(tag, _count)| tag)
{
// if successfull, replace the filter with it
let _ = super::extract_string_and_clear(&mut self.filter_area);
self.filter_area.insert_str(tag.replace(" ", "-"));
}
// filter and go to select mode
self.filter(self.filter_from_input());
self.mode = SelectMode::Select;
}
// G: Change exact/prefix match
KeyCode::Char('m' | 'M') => {
self.tag_match = self.tag_match.cycle();
self.filter(self.filter_from_input());
self.style_text_area();
}
// All other key events are ignored
_ => {}
};
}
// File mode: Wait for second input
SelectMode::SubmenuFile => {
match key.code {
// D: Delete note
KeyCode::Char('d' | 'D') => {
self.mode = SelectMode::Delete;
}
// C: Copy note
KeyCode::Char('c' | 'C') => {
if let Some(env_stats) = self
// get the selected item in the list for the id
.local_stats
.get_selected(self.selected)
{
// delete it from index & filesystem
self.manager
.copy_note_file(self.index.clone(), &env_stats.id)?;
// if successful, refresh the ui
self.index.borrow().poll_file_system();
self.refresh_env_stats();
}
self.mode = SelectMode::Select;
} // N: Create note
KeyCode::Char('n' | 'N') => {
self.mode = SelectMode::Create;
self.set_name_area("Enter name of new note...", None);
}
// R: Rename note
KeyCode::Char('r' | 'R') => {
self.mode = SelectMode::Rename;
let name = self
// get the selected item in the list for the id
.local_stats
.get_selected(self.selected)
// use this id in the index to get the note
.and_then(|env_stats| {
// use the id to get the name
self.index
.borrow()
.get(&env_stats.id)
.map(|note| note.name.clone())
});
self.set_name_area("Enter new name of note...", name);
}
// M: Move note
KeyCode::Char('m' | 'M') => {
self.mode = SelectMode::Move;
self.set_name_area("Enter new location relative to vault...", None);
}
// Back to select mode
KeyCode::Esc => {
self.mode = SelectMode::Select;
}
_ => {}
}
}
// Modes that require input in the text box.
SelectMode::Create | SelectMode::Rename | SelectMode::Move => {
match key.code {
// Escape: Back to main mode, clear the buffer
KeyCode::Esc => {
let _ = super::extract_string_and_clear(&mut self.name_area);
self.mode = SelectMode::Select;
}
// Enter: Create note, back to main mode, clear the buffer
KeyCode::Enter => {
// Switch back to base mode
let mode = std::mem::replace(&mut self.mode, SelectMode::Select);
// Here, we need to check which mode we are in again
match mode {
SelectMode::Create => {
// Create & register the note
let created_note_path = self.manager.create_note_file(
&super::extract_string_and_clear(&mut self.name_area)
.ok_or_else(|| {
error::RucolaError::Input(String::from(
"New note may not be empty.",
))
})?,
None,
)?;
// if successful, add to the index and refresh ui
self.index
.borrow_mut()
.insert_note_from_path(&created_note_path)?;
self.refresh_env_stats();
}
SelectMode::Rename => {
// Get the id of currently selected, then delegate to note_file::rename.
if let Some(env_stats) =
self.local_stats.get_selected(self.selected)
{
self.manager.rename_note_file(
self.index.clone(),
&env_stats.id,
super::extract_string_and_clear(&mut self.name_area)
.ok_or_else(|| {
error::RucolaError::Input(
"New name is empty.".to_string(),
)
})?,
)?;
// if successful, update the index and refresh the ui
self.index.borrow().poll_file_system();
self.refresh_env_stats();
}
}
SelectMode::Move => {
// Get the id of currently selected, then delegate to note_file::move.
if let Some(env_stats) =
self.local_stats.get_selected(self.selected)
{
self.manager.move_note_file(
self.index.clone(),
&env_stats.id,
super::extract_string_and_clear(&mut self.name_area)
.ok_or_else(|| {
error::RucolaError::Input(
"Move target is empty.".to_string(),
)
})?,
)?;
// if successful, refresh the ui
self.index.borrow().poll_file_system();
self.refresh_env_stats();
}
}
_ => {
//This should NOT happen
}
}
}
// All other key events are passed on to the text area
_ => {
// Else -> Pass on to the text area
self.name_area.input(key);
}
};
}
// Deletion submenu: Enter deletes, all others cancel.
SelectMode::Delete => match key.code {
KeyCode::Enter => {
if let Some(env_stats) = self
// get the selected item in the list for the id
.local_stats
.get_selected(self.selected)
{
// delete it from index & filesystem
self.manager
.delete_note_file(self.index.clone(), &env_stats.id)?;
// if successful, refresh the ui
self.index.borrow().poll_file_system();
self.refresh_env_stats();
}
self.mode = SelectMode::Select;
}
_ => {
self.mode = SelectMode::Select;
}
},
// Sorting submenu: Wait for second input
SelectMode::SubmenuSorting => {
self.mode = SelectMode::Select;
match key.code {
KeyCode::Char('s' | 'S') => {
self.set_mode_sort(data::NoteColumn::Shuffle, true);
}
KeyCode::Char('a' | 'A') => {
self.set_mode_sort(data::NoteColumn::Name, true);
}
KeyCode::Char('w' | 'W') => {
self.set_mode_sort(data::NoteColumn::Words, false);
}
KeyCode::Char('c' | 'C') => {
self.set_mode_sort(data::NoteColumn::Chars, false);
}
KeyCode::Char('o' | 'O') => {
self.set_mode_sort(data::NoteColumn::GlobalOutLinks, false);
}
KeyCode::Char('u' | 'U') => {
self.set_mode_sort(data::NoteColumn::LocalOutLinks, false);
}
KeyCode::Char('i' | 'I') => {
self.set_mode_sort(data::NoteColumn::GlobalInLinks, false);
}
KeyCode::Char('n' | 'N') => {
self.set_mode_sort(data::NoteColumn::LocalInLinks, false);
}
KeyCode::Char('b' | 'B') => {
self.set_mode_sort(data::NoteColumn::Broken, false);
}
KeyCode::Char('m' | 'M') => {
self.set_mode_sort(data::NoteColumn::LastModified, false);
}
KeyCode::Char('e' | 'E') => {
self.set_mode_sort(data::NoteColumn::Score, false);
}
KeyCode::Char('r' | 'R') => {
self.local_stats.reverse_order();
}
KeyCode::Esc => {}
_ => self.mode = SelectMode::SubmenuSorting,
}
}
};
Ok(ui::Message::None)
}
fn draw(&self, area: layout::Rect, buf: &mut buffer::Buffer) {
// Get the filter string (neccssary to determine if a filter is active)
let (global_size, local_size) = self.stats_heights(self.filter_area.lines().last());
// Vertical layout
let vertical = Layout::vertical([
Constraint::Length(1),
Constraint::Length(global_size),
Constraint::Length(local_size),
Constraint::Length(3),
Constraint::Min(6),
]);
// Generate areas
let [title_area, global_stats_area, local_stats_area, filter_area, table_area] =
vertical.areas(area);
// Title
let title = Line::from(vec![Span::styled(
self.manager.get_vault_title(),
self.styles.title_style,
)])
.alignment(Alignment::Center);
let version = Line::from(vec![Span::styled(
format!("rucola v{}", env!("CARGO_PKG_VERSION")),
self.styles.subtitle_style,
)])
.alignment(Alignment::Right);
// Generate stats areas
let global_stats =
self.global_stats
.to_global_stats_table(&self.styles)
.block(Block::bordered().title(style::Styled::set_style(
"Global Statistics",
self.styles.title_style,
)));
let local_stats = self
.local_stats
.to_local_stats_table(&self.global_stats, &self.styles)
.block(Block::bordered().title(style::Styled::set_style(
"Local Statistics",
self.styles.title_style,
)));
// === Table Area ===
// Generate state from selected element
let mut state = TableState::new()
.with_offset(
self.selected
// try to keep element at above 1/3rd of the total height
.saturating_sub(table_area.height as usize / 3)
.min(
// but when reaching the end of the list, still scroll down
self.local_stats
.len()
// correct for table edges
.saturating_add(3)
.saturating_sub(table_area.height as usize),
),
)
// In certain modes, show a selected element
.with_selected(match self.mode {
SelectMode::Select
| SelectMode::Rename
| SelectMode::Move
| SelectMode::Delete
| SelectMode::SubmenuFile
| SelectMode::SubmenuSorting => Some(self.selected),
SelectMode::Filter
| SelectMode::FilterHelp
| SelectMode::TagList(_)
| SelectMode::Create => None,
});
// Instructions at the bottom of the page
let instructions_bot_left = Line::from(vec![
Span::styled("J", self.styles.hotkey_style),
Span::styled("/", self.styles.text_style),
Span::styled("↓", self.styles.hotkey_style),
Span::styled(": Down──", self.styles.text_style),
Span::styled("K", self.styles.hotkey_style),
Span::styled("/", self.styles.text_style),
Span::styled("↑", self.styles.hotkey_style),
Span::styled(": Up──", self.styles.text_style),
Span::styled("L", self.styles.hotkey_style),
Span::styled("/", self.styles.text_style),
Span::styled("→", self.styles.hotkey_style),
Span::styled("/", self.styles.text_style),
Span::styled("↵", self.styles.hotkey_style),
Span::styled(": Open──", self.styles.text_style),
])
.left_aligned();
// Display some git info:
let git_info = if let Some(git_manager) = &self.git_manager {
let mut info = "Git ".to_owned();
let (ahead, behind) = git_manager.calculate_ahead_behind().unwrap_or((0, 0));
let (untracked, uncommited) = git_manager.changes();
if ahead > 0 {
info.push('↑');
}
if behind > 0 {
info.push('↓');
}
if untracked {
info.push('!');
}
if uncommited {
info.push('+');
}
info.push_str("──");
info
} else {
String::new()
};
let mut keybinding_spans = vec![
Span::styled("E", self.styles.hotkey_style),
Span::styled("dit──", self.styles.text_style),
Span::styled("V", self.styles.hotkey_style),
Span::styled("iew──", self.styles.text_style),
Span::styled("S", self.styles.hotkey_style),
Span::styled("orting──", self.styles.text_style),
Span::styled(git_info, self.styles.text_style),
Span::styled("M", self.styles.hotkey_style),
Span::styled("anage Files──", self.styles.text_style),
Span::styled("Q", self.styles.hotkey_style),
Span::styled("uit", self.styles.text_style),
];
if self.diary_config.enabled {
keybinding_spans.insert(0, Span::styled("iary──", self.styles.text_style));
keybinding_spans.insert(0, Span::styled("D", self.styles.hotkey_style));
}
let instructions_bot_right = Line::from(keybinding_spans).right_aligned();
let table_heading_key_style = if self.mode == SelectMode::SubmenuSorting {
self.styles.hotkey_style
} else {
self.styles.subtitle_style
};
// Finally generate the table from the generated row and width data
let table = self
.local_stats
.to_note_table(self.index.clone(), &self.styles, &self.column_config)
// Add Headers
.header(Row::new(self.column_config.iter().map(
|(title, column)| {
column.title_line(title, self.styles.subtitle_style, table_heading_key_style)
},
)))
.row_highlight_style(self.styles.selected_style)
// Add Instructions and a title
.block(
Block::bordered()
.title_top(style::Styled::set_style("Notes", self.styles.title_style))
.title_bottom(instructions_bot_left)
.title_bottom(instructions_bot_right),
);
// === Rendering ===
Widget::render(title, title_area, buf);
Widget::render(version, title_area, buf);
Widget::render(&self.filter_area, filter_area, buf);
Widget::render(global_stats, global_stats_area, buf);
Widget::render(local_stats, local_stats_area, buf);
StatefulWidget::render(table, table_area, buf, &mut state);
// Render possible pop-ups
match self.mode {
SelectMode::SubmenuFile | SelectMode::SubmenuSorting => {
let contents = if self.mode == SelectMode::SubmenuFile {
vec![
("N", "New note"),
("R", "Rename selected note"),
("M", "Move selected note"),
("C", "Copy selected file"),
("D", "Delete selected note"),
]
} else {
vec![
("S", "Shuffle"),
("A", "Sort by name"),
("W", "Sort by words"),
("C", "Sort by characters"),
("O", "Sort by global outlinks"),
("U", "Sort by local outlinks"),
("I", "Sort by global inlinks"),
("N", "Sort by local inlinks"),
("B", "Sort by broken links"),
("M", "Sort by last modification"),
("E", "Sort by score"),
("R", "Reverse sorting"),
]
}
.iter()
.map(|(a, b)| (a.to_string(), b.to_string()))
.collect_vec();
let popup_areas = Layout::vertical([
Constraint::Fill(1),
Constraint::Length(contents.len() as u16 + 2),
Constraint::Length(1),
])
.split(area);
let br_area = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(
contents
.iter()
.map(|(_key, desc)| desc.len())
.max()
.unwrap_or_default() as u16
+ 5,
),
Constraint::Length(1),
])
.split(popup_areas[1])[1];
let rows = contents
.into_iter()
.map(|(key, description)| {
Row::new(vec![
Span::styled(key, self.styles.hotkey_style),
Span::styled(description, self.styles.text_style),
])
})
.collect::<Vec<_>>();
let widths = [Constraint::Length(2), Constraint::Fill(1)];
let popup_table = Table::new(rows, widths)
.block(Block::bordered())
.column_spacing(1);
// Clear the area and then render the widget on top.
Widget::render(Clear, br_area, buf);
Widget::render(popup_table, br_area, buf);
}
SelectMode::Filter | SelectMode::Select => {}
SelectMode::Create | SelectMode::Rename | SelectMode::Move => {
let popup_areas = Layout::vertical([
Constraint::Fill(1),
Constraint::Length(3),
Constraint::Fill(1),
])
.split(area);
let center_area = Layout::horizontal([
Constraint::Fill(1),
Constraint::Percentage(60),
Constraint::Fill(1),
])
.split(popup_areas[1])[1];
// Clear the area and then render the widget on top.
Widget::render(Clear, center_area, buf);
Widget::render(&self.name_area, center_area, buf);
}
SelectMode::Delete => {
let delete_confirmation = Paragraph::new(Text::styled(
format!(
"Delete selected note \"{}\"?",
self.local_stats
.get_selected(self.selected)
.and_then(|note| self
.index
.borrow()
.get(¬e.id)
.map(|note| note.display_name.clone()))
.unwrap_or(String::from("<Unknown Note>"))
),
self.styles.text_style,
))
.block(
Block::bordered()
.title(style::Styled::set_style(
"Confirm deletion",
self.styles.title_style,
))
.title_bottom(
Line::from(vec![
Span::styled("↵", self.styles.hotkey_style),
Span::styled(": Confirm──", self.styles.text_style),
Span::styled("Esc", self.styles.hotkey_style),
Span::styled("/", self.styles.text_style),
Span::styled("Any", self.styles.hotkey_style),
Span::styled(": Cancel", self.styles.text_style),
])
.right_aligned(),
),
);
let popup_areas = Layout::vertical([
Constraint::Fill(1),
Constraint::Length(3),
Constraint::Fill(1),
])
.split(area);
let center_area = Layout::horizontal([
Constraint::Fill(1),
Constraint::Percentage(60),
Constraint::Fill(1),
])
.split(popup_areas[1])[1];
// Clear the area and then render the widget on top.
Widget::render(Clear, center_area, buf);
Widget::render(delete_confirmation, center_area, buf);
}
SelectMode::FilterHelp => {
let help_widths = [Constraint::Length(9), Constraint::Min(0)];
let help_rows = [
Row::new(vec![
Cell::from("/ or F").style(self.styles.subtitle_style),
Cell::from("Enter the filter text box.").style(self.styles.text_style),
]),
Row::new(vec![
Cell::from("↵ or Esc").style(self.styles.subtitle_style),
Cell::from("Exit the filter text box").style(self.styles.text_style),
]),
Row::new(vec![Cell::from("").style(self.styles.subtitle_style)]),
Row::new(vec![
Cell::from("#[tag]").style(self.styles.subtitle_style),
match self.tag_match {
data::TagMatch::Exact => Cell::from("Show notes with tag [tag].")
.style(self.styles.text_style),
data::TagMatch::Prefix => {
Cell::from("Show notes with a tag starting with [tag].")
.style(self.styles.text_style)
}
},
]),
Row::new(vec![
Cell::from("!#[tag]").style(self.styles.subtitle_style),
match self.tag_match {
data::TagMatch::Exact => Cell::from("Show notes without tag [tag].")
.style(self.styles.text_style),
data::TagMatch::Prefix => {
Cell::from("Show notes with no tag starting with [tag].")
.style(self.styles.text_style)
}
},
]),
Row::new(vec![
Cell::from("").style(self.styles.subtitle_style),
Cell::from("Use '-' instead of ' ' for multi-word tags.")
.style(self.styles.text_style),
]),
Row::new(vec![
Cell::from(" ").style(self.styles.subtitle_style),
Cell::from("").style(self.styles.text_style),
]),
Row::new(vec![
Cell::from(">[note]").style(self.styles.subtitle_style),
Cell::from("Show notes linking to [note].").style(self.styles.text_style),
]),
Row::new(vec![
Cell::from("<[note]").style(self.styles.subtitle_style),
Cell::from("Show notes linked to from [note].")
.style(self.styles.text_style),
]),
Row::new(vec![
Cell::from("!>[note]").style(self.styles.subtitle_style),
Cell::from("Show notes not linking to [note].")
.style(self.styles.text_style),
]),
Row::new(vec![
Cell::from("!<[note]").style(self.styles.subtitle_style),
Cell::from("Show notes not linked to from [note].")
.style(self.styles.text_style),
]),
Row::new(vec![
Cell::from("").style(self.styles.subtitle_style),
Cell::from("Use '-' instead of ' ' for multi-word titles.")
.style(self.styles.text_style),
]),
Row::new(vec![Cell::from("").style(self.styles.subtitle_style)]),
Row::new(vec![
Cell::from("|").style(self.styles.subtitle_style),
Cell::from("All text after | will be searched in the full text.")
.style(self.styles.text_style),
]),
Row::new(vec![
Cell::from(" ").style(self.styles.subtitle_style),
Cell::from("All other text will be matched against the title.")
.style(self.styles.text_style),
]),
];
// Pop-up should be as tall as the number of help dialog rows
// plus 2 rows for top and bottom border
let popup_height = help_rows.len() as u16 + 2;
let help_table = Table::new(help_rows, help_widths).column_spacing(1).block(
Block::bordered()
.title(style::Styled::set_style(
"Filter Syntax",
self.styles.title_style,
))
.title_bottom(
Line::from(vec![
Span::styled("C", self.styles.hotkey_style),
Span::styled("lose", self.styles.text_style),
])
.right_aligned(),
),
);
let popup_areas = Layout::vertical([
Constraint::Fill(1),
Constraint::Length(popup_height),
Constraint::Fill(1),
])
.split(area);
let center_area = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(64),
Constraint::Fill(1),
])
.split(popup_areas[1])[1];
// Clear the area and then render the help menu on top.
Widget::render(Clear, center_area, buf);
Widget::render(help_table, center_area, buf);
}
SelectMode::TagList(selected) => {
let tag_widths = [Constraint::Min(0), Constraint::Length(4)];
let tag_rows = self
.index
.borrow()
.tags_vec()
.into_iter()
.map(|(tag, count)| {
Row::new(vec![
Cell::from(tag).style(self.styles.text_style),
Cell::from(format!("{:4}", count)).style(self.styles.text_style),
])
})
.collect_vec();
// Pop-up should be as tall as the number of tags, but a maximum of 16 rows
// plus 2 rows for top and bottom border
let tags_height = (tag_rows.len() as u16 + 2).min(16);
let tags_areas = Layout::vertical([
Constraint::Fill(1),
Constraint::Length(tags_height),
Constraint::Fill(1),
])
.split(area);
// generate a table state for selection etc.
let mut state = TableState::new()
.with_offset(
selected
// try to keep element at above 1/3rd of the total height
.saturating_sub(tags_height as usize / 3)
.min(
// but when reaching the end of the list, still scroll down
tag_rows
.len()
// correct for table edges
.saturating_add(2)
.saturating_sub(tags_height as usize),
),
)
// In certain modes, show a selected element
.with_selected(selected);
// Generate the table
let tag_table = Table::new(tag_rows, tag_widths)
.column_spacing(1)
.block(
Block::bordered()
.title(style::Styled::set_style("Tags", self.styles.title_style))
.title_bottom(
Line::from(vec![
Span::styled("C", self.styles.hotkey_style),
Span::styled("lose", self.styles.text_style),
])
.right_aligned(),
)
.title_bottom(
Line::from(vec![
Span::styled("↵", self.styles.hotkey_style),
Span::styled(": Apply tag filter──", self.styles.text_style),
Span::styled("M", self.styles.hotkey_style),
Span::styled("atch tags ", self.styles.text_style),
Span::styled(
match self.tag_match {
data::TagMatch::Exact => "exactly",
data::TagMatch::Prefix => "by prefix",
},
self.styles.text_style,
),
])
.left_aligned(),
),
)
.row_highlight_style(self.styles.selected_style);
// Generate an area to clear for the tag list
let center_area = Layout::horizontal([
Constraint::Fill(1),
Constraint::Length(64),
Constraint::Fill(1),
])
.split(tags_areas[1])[1];
// Clear the area and then render the tag list on top.
Widget::render(Clear, center_area, buf);
StatefulWidget::render(tag_table, center_area, buf, &mut state);
}
}
}
}