-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.rs
1835 lines (1679 loc) · 78.3 KB
/
model.rs
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
use electron_sys::ipc_renderer;
use pest::Parser;
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU32;
use std::ops::Deref;
use std::option::Option;
use stdweb::traits::IEvent;
use stdweb::unstable::TryInto;
use stdweb::web::event::{
ContextMenuEvent, IKeyboardEvent, KeyDownEvent, KeyPressEvent, KeyUpEvent,
};
use stdweb::web::{document, IElement, INode, IParentNode};
use wasm_bindgen::JsValue;
use yew::prelude::*;
use yew::services::reader::{File, FileData, ReaderService, ReaderTask};
use yew::services::ConsoleService;
use crate::coordinate::{Col, Coordinate, Row};
use crate::grammar::{Grammar, Kind, Lookup};
use crate::grammar_map::*;
use crate::session::Session;
use crate::style::Style;
use crate::util::{move_grammar, non_zero_u32_tuple, resize, resize_diff};
use crate::view::{view_context_menu, view_grammar, view_menu_bar, view_side_nav, view_tab_bar};
use crate::{coord, coord_col, coord_row, g, grid, row_col_vec};
#[derive(Parser)]
#[grammar = "coordinate.pest"]
pub struct CoordinateParser;
// Model contains the entire state of the application
#[derive(Debug)]
pub struct Model {
// Parts of the application state are described below:
// - `view_root` represents the parent grammar that the view starts rendering from
view_root: Coordinate,
// - `active_cell`
pub active_cell: Option<Coordinate>,
// - `first_select_cell` is the top-leftmost cell in a selection
// - `last_select_cell` is the bottom-rightmost cell in a selection
pub first_select_cell: Option<Coordinate>,
pub last_select_cell: Option<Coordinate>,
pub secondary_selections: HashSet<Coordinate>,
// TODO: are `min_select_cell` and `max_select_cell` still useful
pub min_select_cell: Option<Coordinate>,
pub max_select_cell: Option<Coordinate>,
// - `shift_key_pressed` is a simple indicator for when shift key is togridled
pub shift_key_pressed: bool,
// - `zoom` is the value that corresponds to how "zoomed" the sheet is
pub zoom: f32,
// - `suggestion` contains a list of either Completion, Binding or Command suggestions
pub suggestions: Vec<SuggestionType>,
// - `lookups` represent an ordered list of coordinates that have lookups corresponding
// to them. the indexes are used to generate correspoding color coding for each lookup
pub lookups: Vec<Coordinate>,
// - `col_widths` & `row_heights` map coordinate to sizes based on column or row
pub col_widths: HashMap<Col, f64>,
pub row_heights: HashMap<Row, f64>,
// - `sessions` represents the currently open sessions that are shown in the tab bar,
// where each session
// - `current_session_index` tells us which of the open sessions is currently active
pub sessions: Vec<Session>,
pub current_session_index: usize,
// - `side_menus` represent the state
pub side_menus: Vec<SideMenu>,
pub open_side_menu: Option<i32>,
// - `focus_node_ref` is a reference to the current cell that should be in focus
pub focus_node_ref: NodeRef,
pub next_focus_node_ref: NodeRef,
// - `resizing` is an optional reference to the current coordinate being resized
// (which is None if no resizing is happening)
pub resizing: Option<Coordinate>,
// - `link` is a function of the Yew framework for referring back to the current component
// so actions can be chained, for instance
pub link: ComponentLink<Model>,
// - `default_nested_row_cols` shows the default number of rows and columns
// created by Ctrl+G or the "Nest Grid" button
// - `default_definition_name` shows the default name of the grammar created
// by Ctrl+G the "Add Definition" button
pub default_nested_row_cols: (NonZeroU32, NonZeroU32),
pub context_menu_position: Option<(f64, f64)>,
pub default_definition_name: String,
// - `mouse_cursor` corresponds to the appearance of the mouse cursor
pub mouse_cursor: CursorType,
// - `current_cursor_position` preserves the cursor on the focused input grammar while typing
pub current_cursor_position: u32,
// - `console` and `reader` are used to access native browser APIs for the
// dev console and FileReader respectively
console: ConsoleService,
reader: ReaderService,
// - `tasks` are used to store asynchronous requests to read/load files
tasks: Vec<ReaderTask>,
}
#[derive(Clone, Debug)]
pub enum SuggestionType {
Completion(String, Coordinate),
Binding(String, Coordinate),
Command(String, Action),
}
#[derive(Debug)]
pub struct SideMenu {
pub name: String,
pub icon_path: String,
}
// SUBACTIONS
// Sub-actions for resize-related operations
#[derive(Clone, Debug)]
pub enum ResizeMsg {
Start(Coordinate),
X(f64),
Y(f64),
End,
}
// Sub-actions for adjusting the current look of the cursor
#[derive(Clone, Debug)]
pub enum CursorType {
NS,
EW,
Default,
}
#[derive(Clone, Debug)]
pub enum SelectMsg {
Start(Coordinate),
End(Coordinate),
}
// ACTIONS
// Triggered in the view, sent to update function
#[derive(Clone, Debug)]
pub enum Action {
// Do nothing
Noop,
// Change string value of Input grammar
ChangeInput(Coordinate, /* new_value: */ String),
SetActiveCell(Coordinate),
NextSuggestion(Coordinate, /* index */ i32),
DoCompletion(
/* source: */ Coordinate,
/* destination */ Coordinate,
),
SetActiveMenu(Option<i32>),
ReadSession(/* filename: */ File),
LoadSession(FileData),
SaveSession(),
SetSessionTitle(String),
ReadDriverFiles(Vec<File>),
LoadDriverMainFile(FileData),
UploadDriverMiscFile(FileData),
// Grid Operations
AddNestedGrid(Coordinate, (u32 /*rows*/, u32 /*cols*/)),
InsertRow,
InsertCol,
DeleteRow,
DeleteCol,
Recreate,
ZoomIn,
ZoomOut,
ZoomReset,
Resize(ResizeMsg),
SetCursorType(CursorType),
Select(SelectMsg),
Lookup(
/* source: */ Coordinate,
/* lookup_type: */ Lookup,
),
MergeCells(),
ChangeDefaultNestedGrid((NonZeroU32, NonZeroU32)),
SetCurrentDefinitionName(String),
// SetCurrentParentGrammar(Coordinate),
ToggleLookup(Coordinate),
AddDefinition(Coordinate, /* name */ String, /* staging */ bool),
StageDefinition(
/* definition coord */ Coordinate,
/* name */ String,
),
BindDefinition(
/* definition coord */ Coordinate,
/* binding coord */ Coordinate,
/* name */ String,
),
TogridleShiftKey(bool),
// Alerts and stuff
Alert(String),
ShowContextMenu((f64, f64)),
HideContextMenu,
}
impl Model {
pub fn get_session(&self) -> &Session {
&self.sessions[self.current_session_index]
}
pub fn get_session_mut(&mut self) -> &mut Session {
&mut self.sessions[self.current_session_index]
}
// only use this if you need a COPY of the current session
// i.e. not changing its values
pub fn to_session(&self) -> Session {
self.get_session().clone()
}
fn load_session(&mut self, session: Session) {
self.get_session_mut().root = session.root;
self.get_session_mut().meta = session.meta;
self.get_session_mut().grammars = session.grammars;
}
fn query_parent(&self, coord_parent: Coordinate) -> Vec<Coordinate> {
self.get_session()
.grammars
.keys()
.clone()
.filter_map(|k| {
if k.parent() == Some(coord_parent.clone()) {
Some(k.clone())
} else {
None
}
})
.collect()
}
fn query_col(&self, coord_col: Col) -> Vec<Coordinate> {
self.get_session()
.grammars
.keys()
.clone()
.filter_map(|k| {
if k.row_cols.len() == 1
/* ignore root & meta */
{
None
} else if k.full_col() == coord_col {
Some(k.clone())
} else {
None
}
})
.collect()
}
fn query_row(&self, coord_row: Row) -> Vec<Coordinate> {
self.get_session()
.grammars
.keys()
.clone()
.filter_map(|k| {
if k.row_cols.len() == 1
/* ignore root & meta */
{
None
} else if k.full_row() == coord_row {
Some(k.clone())
} else {
None
}
})
.collect()
}
}
impl Component for Model {
type Message = Action;
type Properties = ();
fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
let root_grammar = Grammar {
name: "root".to_string(),
style: Style::default(),
kind: Kind::Grid(row_col_vec![(1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2)]),
};
let meta_grammar = Grammar {
name: "meta".to_string(),
style: Style::default(),
kind: Kind::Grid(row_col_vec![(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)]),
};
let mut m = Model {
view_root: coord!("root"),
col_widths: hashmap! {
coord_col!("root","A") => 90.0,
coord_col!("root","B") => 90.0,
coord_col!("meta","A") => 180.0,
coord_col!("meta-A3","A") => 90.0,
coord_col!("meta-A3","B") => 180.0,
},
row_heights: hashmap! {
coord_row!("root","1") => 30.0,
coord_row!("root","2") => 30.0,
coord_row!("root","3") => 30.0,
coord_row!("meta","1") => 180.0,
},
active_cell: Some(coord!("root-A1")),
suggestions: vec![
SuggestionType::Completion("js_grammar".to_string(), coord!("meta-A1")),
SuggestionType::Completion("java_grammar".to_string(), coord!("meta-A2")),
SuggestionType::Completion("defn".to_string(), coord!("meta-A3")),
],
console: ConsoleService::new(),
reader: ReaderService::new(),
first_select_cell: None,
last_select_cell: None,
secondary_selections: HashSet::new(),
min_select_cell: None,
max_select_cell: None,
zoom: 1.0,
sessions: vec![Session {
title: "my session".to_string(),
root: root_grammar.clone(),
meta: meta_grammar.clone(),
grammars: {
let mut map = HashMap::new();
build_grammar_map(
&mut map,
coord!("root"),
grid![
[
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", ""))
],
[
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", ""))
],
[
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", ""))
],
[
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", ""))
],
[
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", ""))
],
[
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", "")),
g!(Grammar::input("", ""))
]
],
);
build_grammar_map(
&mut map,
coord!("meta"),
grid![
[g!(Grammar::input("", "A1"))],
[g!(Grammar::input("", "A2"))],
[g!(Grammar::default_button())],
[g!(Grammar::default_slider())],
[g!(Grammar::default_toggle())],
[g!(Grammar::input("js", ""))],
[grid!(
"js::var".to_string(),
[[
g!(Grammar::text("", "var")),
g!(Grammar::input("", "")),
g!(Grammar::text("", "=")),
g!(Grammar::input("", ""))
]]
)],
[grid!(
"js::assn".to_string(),
[[
g!(Grammar::input("", "")),
g!(Grammar::text("", "=")),
g!(Grammar::input("", ""))
]]
)],
[grid!(
"js::function".to_string(),
[
[
g!(Grammar::text("function", "")),
g!(Grammar::text("", "(")),
g!(Grammar::input("", "")),
g!(Grammar::text("", ")")),
g!(Grammar::text("", "{"))
],
[g!(Grammar::input("", ""))],
[g!(Grammar::text("", "}"))]
]
)]
],
);
build_grammar_map(
&mut map,
coord!("meta-A6"),
grid![
[
g!(Grammar {
name: "defn_label".to_string(),
style: {
let mut s = Style::default();
s.font_weight = 600;
s
},
kind: Kind::Text("Define Grammar".to_string()),
}),
g!(Grammar {
name: "defn_name".to_string(),
style: Style::default(),
kind: Kind::Input(String::new()),
})
],
[grid![
[
g!(Grammar::input("rule_name", "")),
g!(Grammar::input("rule_grammar", ""))
],
[
g!(Grammar::input("rule_name", "")),
g!(Grammar::input("rule_grammar", ""))
]
]]
],
);
assert!(map.contains_key(&(coord!("root"))));
assert!(map.contains_key(&(coord!("meta-A6-A1"))));
map
},
}],
current_session_index: 0,
side_menus: vec![
SideMenu {
name: "Home".to_string(),
icon_path: "assets/logo.png".to_string(),
},
SideMenu {
name: "File Explorer".to_string(),
icon_path: "assets/folder_icon.png".to_string(),
},
SideMenu {
name: "Settings".to_string(),
icon_path: "assets/settings_icon.png".to_string(),
},
SideMenu {
name: "Info".to_string(),
icon_path: "assets/info_icon.png".to_string(),
},
],
open_side_menu: None,
resizing: None,
link,
tasks: vec![],
focus_node_ref: NodeRef::default(),
next_focus_node_ref: NodeRef::default(),
shift_key_pressed: false,
default_nested_row_cols: non_zero_u32_tuple((3, 3)),
context_menu_position: None,
default_definition_name: "".to_string(),
mouse_cursor: CursorType::Default,
current_cursor_position: 0,
lookups: vec![],
};
// load suggestions from meta
// regular suggestions exist in column meta-A
m.suggestions = m
.query_col(coord_col!("meta", "A"))
.iter()
.filter_map(|coord| {
if let Some(name) = m.get_session().grammars.get(coord).map(|g| g.name.clone()) {
Some(SuggestionType::Completion(name, coord.clone()))
} else {
None
}
})
.collect();
// staged definitions, that have not yet been bound exist in column meta-B
m.suggestions.append(
&mut m
.query_col(coord_col!("meta", "B"))
.iter()
.filter_map(|coord| {
if let Some(name) = m.get_session().grammars.get(coord).map(|g| g.name.clone())
{
Some(SuggestionType::Binding(name, coord.clone()))
} else {
None
}
})
.collect(),
);
m
}
// The update function is split into sub-update functions that
// are specifc to each EventType
fn update(&mut self, event_type: Self::Message) -> ShouldRender {
let should_render = match event_type {
Action::Noop => false,
Action::Alert(message) => {
self.console.log(&message);
// TODO: make this into a more visual thing
false
}
Action::ChangeInput(coord, new_value) => {
// i'm using this hack to preserve the cursor
// position in the current input grammar
let cursor_position: u32 = js! {
let selObj = window.getSelection();
let range = selObj.getRangeAt(0);
if (range.startContainer == range.endContainer) {
return range.startOffset;
}
return 0;
}
.try_into()
.unwrap();
self.current_cursor_position = cursor_position;
if let Some(g) = self.get_session_mut().grammars.get_mut(&coord) {
match g {
Grammar {
kind: Kind::Input(_),
..
} => {
g.kind = Kind::Input(new_value);
}
Grammar {
kind: Kind::Lookup(_, lookup_type),
..
} => {
g.kind = Kind::Lookup(new_value, lookup_type.clone());
}
_ => (),
}
}
// NOTE: setting this to false messes with
true
}
Action::SetActiveCell(coord) => {
self.active_cell = Some(coord.clone());
let active_cell_id = format! {"cell-{}", coord.to_string()};
js! {
try {
let element = document.getElementById(@{active_cell_id.clone()});
element.firstChild.focus();
} catch (e) {
console.log("cannot focus cell with coordinate ", @{active_cell_id});
}
};
true
}
Action::NextSuggestion(coord, index) => {
let next_suggestion_id =
format! {"cell-{}-suggestion-{}", coord.to_string(), index};
js! {
try {
let element = document.getElementById(@{next_suggestion_id.clone()});
element.focus();
} catch (e) {
console.log("cannot focus on next suggestion ", @{coord.to_string()}, @{index});
}
};
true
}
Action::Select(SelectMsg::Start(coord)) => {
self.first_select_cell = Some(coord.clone());
self.last_select_cell = None;
true
}
Action::Select(SelectMsg::End(coord)) => {
if let Some(mut selection_start) = self.first_select_cell.clone() {
// ensure that selection_start and selection_end have common parent
let mut common_parent = selection_start.parent();
let mut selection_end = Some(coord.clone());
let depth_start = selection_start.row_cols.len();
let depth_end = selection_end.clone().unwrap().row_cols.len();
// depend on which select coord has higher depth, find their common parent
if depth_start < depth_end {
while selection_end.clone().and_then(|c| c.parent()) != common_parent {
selection_end = selection_end.and_then(|c| c.parent());
}
} else {
common_parent = selection_end.clone().unwrap().parent();
while selection_start.parent() != common_parent {
selection_start = selection_start.parent().unwrap();
}
}
// find the min of row,col and max of row,col in selected region
// which may contain a span coord that has smaller or larger row,col
let (mut start_row, mut start_col) = selection_start.clone().row_col();
let (mut end_row, mut end_col) = selection_end.clone().unwrap().row_col();
if start_row > end_row {
let tmp = start_row.clone();
start_row = end_row;
end_row = tmp;
}
if start_col > end_col {
let tmp = start_col.clone();
start_col = end_col;
end_col = tmp;
}
let depth_check = selection_start.row_cols.len().clone();
let ref_grammas = self.get_session().grammars.clone();
let mut check = false;
while !check {
check = true;
let row_range = start_row.get()..=end_row.get();
let col_range = start_col.get()..=end_col.get();
for (coord, grammar) in ref_grammas.iter() {
let (coord_row, coord_col) = coord.clone().row_col();
let coord_depth = coord.clone().row_cols.len();
if row_range.contains(&coord_row.get())
&& col_range.contains(&coord_col.get())
&& (coord_depth == depth_check)
{
let col_span = grammar.clone().style.col_span;
let row_span = grammar.clone().style.row_span;
if col_span.0 != 0 && col_span.1 != 0 {
if col_span.0 < start_col.get() {
start_col = NonZeroU32::new(col_span.0).unwrap();
check = false;
}
if col_span.1 > end_col.get() {
end_col = NonZeroU32::new(col_span.1).unwrap();
check = false;
}
}
if row_span.0 != 0 && row_span.1 != 0 {
if row_span.0 < start_row.get() {
start_row = NonZeroU32::new(row_span.0).unwrap();
check = false;
}
if row_span.1 > end_row.get() {
end_row = NonZeroU32::new(row_span.1).unwrap();
check = false;
}
}
}
}
}
selection_start.row_cols[depth_check - 1] = (start_row, start_col);
selection_end.as_mut().unwrap().row_cols[depth_check - 1] = (end_row, end_col);
self.first_select_cell = Some(selection_start.clone());
self.last_select_cell = selection_end.clone();
}
true
}
Action::MergeCells() => {
if self.first_select_cell.is_none() || self.last_select_cell.is_none() {
info!("Expect for select for two coord");
return false;
}
let (first_row, first_col) = self.first_select_cell.clone().unwrap().row_col();
let (last_row, last_col) = self.last_select_cell.clone().unwrap().row_col();
let depth_check = self.last_select_cell.clone().unwrap().row_cols.len();
let parent_check = self.last_select_cell.clone().unwrap().parent();
let row_range = first_row.get()..=last_row.get();
let col_range = first_col.get()..=last_col.get();
let mut merge_height = 0.00;
let mut merge_width = 0.00;
let mut max_coord = Coordinate::default();
let mut max_grammar = Grammar::default();
let mut ref_grammas = self.get_session_mut().grammars.clone();
for (coord, grammar) in ref_grammas.iter_mut() {
if coord.parent() == parent_check {}
if coord.to_string().contains("root-") {
if row_range.contains(&coord.row().get())
&& col_range.contains(&coord.col().get())
&& coord.parent() == parent_check
{
let coord_style = grammar.style.clone();
if coord_style.display != false {
if coord.row().get() == last_row.get() {
merge_width = merge_width + coord_style.width;
}
if coord.col().get() == last_col.get() {
merge_height = merge_height + coord_style.height;
}
if coord.row().get() == last_row.get()
&& (coord.col().get() == last_col.get())
{
max_coord = coord.clone();
max_grammar = grammar.clone();
} else {
grammar.style.display = false;
}
}
grammar.kind = Kind::Input("".to_string());
grammar.style.col_span.0 = first_col.get();
grammar.style.col_span.1 = last_col.get();
grammar.style.row_span.0 = first_row.get();
grammar.style.row_span.1 = last_row.get();
self.get_session_mut()
.grammars
.insert(coord.clone(), grammar.clone());
}
}
}
max_grammar.kind = Kind::Input("".to_string());
max_grammar.style.width = merge_width;
max_grammar.style.height = merge_height;
max_grammar.style.col_span.0 = first_col.get();
max_grammar.style.col_span.1 = last_col.get();
max_grammar.style.row_span.0 = first_row.get();
max_grammar.style.row_span.1 = last_row.get();
self.get_session_mut()
.grammars
.insert(max_coord.clone(), max_grammar.clone());
true
}
Action::DoCompletion(source_coord, dest_coord) => {
move_grammar(self, source_coord, dest_coord.clone());
// HACK to prevent VDOM update error where the text of the completion
// query isn't cleared and distorts how the completed grammar looks
let cell_id = format! {"cell-{}", dest_coord.to_string()};
js! {
try {
let element = document.getElementById(@{cell_id.clone()} + "-A1");
if (element.firstChild && element.firstChild.nodeType == Node.TEXT_NODE) {
element.firstChild.remove();
}
} catch (e) {
console.log("cannot find cell with ID ", @{cell_id});
}
};
// if let Some(
// g @ Grammar {
// kind: Kind::Input(_),
// ..
// },
// ) = self.get_session_mut().grammars.get_mut(&dest_coord)
// {
// g.kind = Kind::Input("".to_string());
// }
true
}
Action::SetActiveMenu(active_menu) => {
self.open_side_menu = active_menu;
true
}
Action::ReadSession(file) => {
let callback = self.link.callback(Action::LoadSession);
if let Ok(task) = self.reader.read_file(file, callback) {
self.tasks.push(task);
}
false
}
Action::LoadSession(file_data) => {
let session: Session =
serde_json::from_str(format! {"{:?}", file_data}.deref()).unwrap();
self.load_session(session);
true
}
Action::SaveSession() => {
/* TODO: new approach to saving session, should work better but there's still some
* compile errors to be handled later
let session = self.to_session();
let json = serde_json::to_string(&session.clone());
let filename = format! {"{}.json", session.title.to_string()};
let _ = js! {
let dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(@{&json}));
let dlAnchorElem = document.getElementById("downloadAnchorElem");
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", @{&filename});
dlAnchorElem.click();
return 0;
};
*/
false
}
Action::SetSessionTitle(name) => {
self.get_session_mut().title = name;
true
}
Action::MergeCells() => {
if self.min_select_cell.is_none() || self.max_select_cell.is_none() {
return false;
}
let mut min_select_row = self.min_select_cell.as_ref().unwrap().row();
let mut max_select_row = self.max_select_cell.as_ref().unwrap().row();
let mut min_select_col = self.min_select_cell.as_ref().unwrap().col();
let mut max_select_col = self.max_select_cell.as_ref().unwrap().col();
let mut merge_height = 0.00;
let mut merge_width = 0.00;
let mut max_coord = Coordinate::default();
let mut max_grammar = Grammar::default();
let mut ref_grammas = self.get_session().grammars.clone();
for (coord, grammar) in ref_grammas.iter_mut() {
if min_select_row <= coord.row()
&& coord.row() <= max_select_row
&& min_select_col <= coord.col()
&& coord.col() <= max_select_col
&& coord.to_string().contains("root-")
&& grammar.style.display == true
{
let coord_style = grammar.style.clone();
if (coord.row() == max_select_row) && (coord.col() == max_select_col) {
merge_width = merge_width + coord_style.width;
merge_height = merge_height + coord_style.height;
max_coord = coord.clone();
max_grammar = grammar.clone();
continue;
} else if (coord.row() == max_select_row) {
merge_width = merge_width + coord_style.width;
} else if coord.col() == max_select_col {
merge_height = merge_height + coord_style.height;
}
if (coord.row() != max_select_row) || (coord.col() != max_select_col) {
grammar.style.display = false;
merge_height = merge_height;
merge_width = merge_width;
}
grammar.style.col_span = (min_select_col.get(), max_select_col.get());
grammar.style.row_span = (min_select_row.get(), max_select_row.get());
self.get_session_mut()
.grammars
.insert(coord.clone(), grammar.clone());
}
}
max_grammar.style.width = merge_width;
max_grammar.style.height = merge_height;
max_grammar.style.col_span = (min_select_col.get(), max_select_col.get());
max_grammar.style.row_span = (min_select_row.get(), max_select_row.get());
self.get_session_mut()
.grammars
.insert(max_coord, max_grammar);
self.min_select_cell = None;
self.max_select_cell = None;
true
}
Action::ReadDriverFiles(files_list) => {
// Get the main file and miscellaneous/additional files from the drivers list
let (main_file, misc_files) = {
let (main_file_as_vec, misc_files) : (Vec<File>, Vec<File>) = files_list.iter().fold((Vec::new(), Vec::new()), |accum, file| {
// Iter::partition is used to divide a list into two given a certain condition.
// Here the condition here is to separate the main file of the driver from the
// addditional ones, where the main file's path looks like
// '{directory_name}/{file_name}.js' and the directory_name == file_name
let mut new_accum = accum.clone();
// use `webkitRelativePath` as the `name`, if it's available
// we'll call out to regular JS to do this using the `js!` macro.
// Note that yew::services::reader::File::name() calls "file.name" under the
// hood (https://docs.rs/stdweb/0.4.20/src/stdweb/webapi/file.rs.html#23)
let full_file_name : String = js!(
if (!!@{&file}.webkitRelativePath) {
return @{&file}.webkitRelativePath;
} else {
console.log("couldn't get relative path of file: ", @{&file}.name);
return @{&file}.name; // equivalent to yew::services::reader::File::name()
}
).try_into().unwrap();
let path_parts : Vec<&str> = full_file_name.split("/").collect();
match (path_parts.first(), path_parts.last(), path_parts.len()) {
(Some(directory), Some(file_name), 2) if format!{"{}.js", directory} == file_name.to_string() => {
if new_accum.0.len() == 0 {
new_accum.0.push(file.clone());
} else {
panic!("[Action::ReadDriverFiles]: there shouldn't be more than 1 main file in the driver directory")
}
},
_ => {
new_accum.1.push(file.clone());
},
};
new_accum
});
// the `partition` call above gives us a tuple of two Vecs (Vec, Vec) where the first Vec
// should have only one element, so we'll convert it to a (Vec::Item, Vec).
// If this has an error, then there's something wrong with how the driver
// directory is organized.
(
main_file_as_vec.first().unwrap().clone(),
misc_files.clone(),
)
};
// upload misc files so they can be served by electron to be used by main driver file
let upload_callback = self
.link
.callback(|file_data| Action::UploadDriverMiscFile(file_data));
for file in misc_files {
if let Ok(task) = self.reader.read_file(file, upload_callback.clone()) {
self.tasks.push(task);
}
}
// Load main driver file. After this task has been scheduled and executed, the
// driver is ready for use.
if let Ok(task) = self
.reader
.read_file(main_file, self.link.callback(Action::LoadDriverMainFile))
{
self.tasks.push(task);
}
false
}
Action::UploadDriverMiscFile(file_data) => {
// Here, we use some electron APIs to call out to the main process in JS.
// For this, we use the `electron_sys` library which is pretty experimental but
// feature complete.