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
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
|
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IconButton, Size } from '@dash/components';
import { IReactionDisposer, action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { ClientUtils, lightOrDark, return18, returnEmptyFilter, returnEmptyString, returnFalse, returnTrue, returnZero, setupMoveUpEvents, simulateMouseClick } from '../../../ClientUtils';
import { emptyFunction } from '../../../Utils';
import { Doc, DocListCast, Field, FieldType, Opt, StrListCast, returnEmptyDoclist } from '../../../fields/Doc';
import { DocData, DocLayout } from '../../../fields/DocSymbols';
import { Id } from '../../../fields/FieldSymbols';
import { List } from '../../../fields/List';
import { RichTextField } from '../../../fields/RichTextField';
import { listSpec } from '../../../fields/Schema';
import { ComputedField, ScriptField } from '../../../fields/ScriptField';
import { BoolCast, Cast, DocCast, FieldValue, NumCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
import { TraceMobx } from '../../../fields/util';
import { DocUtils } from '../../documents/DocUtils';
import { CollectionViewType, DocumentType } from '../../documents/DocumentTypes';
import { Docs } from '../../documents/Documents';
import { DragManager } from '../../util/DragManager';
import { dropActionType } from '../../util/DropActionTypes';
import { SettingsManager } from '../../util/SettingsManager';
import { SnappingManager } from '../../util/SnappingManager';
import { Transform } from '../../util/Transform';
import { UndoManager, undoBatch, undoable } from '../../util/UndoManager';
import { EditableView } from '../EditableView';
import { ObservableReactComponent } from '../ObservableReactComponent';
import { StyleProp } from '../StyleProp';
import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView';
import { FieldViewProps, StyleProviderFuncType } from '../nodes/FieldView';
import { OpenWhere } from '../nodes/OpenWhere';
import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
import { RichTextMenu } from '../nodes/formattedText/RichTextMenu';
import { CollectionTreeView } from './CollectionTreeView';
import { TreeViewType } from './CollectionTreeViewType';
import { CollectionView } from './CollectionView';
import { TreeSort } from './TreeSort';
import './TreeView.scss';
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { TREE_BULLET_WIDTH } = require('../global/globalCssVariables.module.scss'); // prettier-ignore
export interface TreeViewProps {
treeView: CollectionTreeView;
// eslint-disable-next-line no-use-before-define
parentTreeView: TreeView | CollectionTreeView | undefined;
observeHeight: (ref: HTMLDivElement) => void;
unobserveHeight: (ref: HTMLDivElement) => void;
prevSibling?: Doc;
Document: Doc;
dataDoc?: Doc;
treeViewParent: Doc;
renderDepth: number;
dragAction: dropActionType;
addDocTab: (doc: Doc | Doc[], where: OpenWhere) => boolean;
panelWidth: () => number;
panelHeight: () => number;
addDocument: (doc: Doc | Doc[], annotationKey?: string, relativeTo?: Doc, before?: boolean) => boolean;
removeDoc: ((doc: Doc | Doc[]) => boolean) | undefined;
moveDocument: DragManager.MoveFunction;
isContentActive: (outsideReaction?: boolean) => boolean;
whenChildContentsActiveChanged: (isActive: boolean) => void;
indentDocument?: (editTitle: boolean) => void;
outdentDocument?: (editTitle: boolean) => void;
ScreenToLocalTransform: () => Transform;
contextMenuItems?: { script: ScriptField; filter: ScriptField; icon: string; label: string }[];
dontRegisterView?: boolean;
styleProvider?: StyleProviderFuncType | undefined;
treeViewHideHeaderFields: () => boolean;
renderedIds: string[]; // list of document ids rendered used to avoid unending expansion of items in a cycle
onCheckedClick?: () => ScriptField;
onChildClick?: () => ScriptField | undefined;
skipFields?: string[];
firstLevel: boolean;
// TODO: [AL] add these
AddToMap?: (treeViewDoc: Doc, index: number[]) => void;
RemFromMap?: (treeViewDoc: Doc, index: number[]) => void;
hierarchyIndex?: number[];
}
const treeBulletWidth = function () {
return Number(TREE_BULLET_WIDTH.replace('px', ''));
};
/**
* Renders a treeView of a collection of documents
*
* special fields:
* treeView_Open : flag denoting whether the documents sub-tree (contents) is visible or hidden
* treeView_ExpandedView : name of field whose contents are being displayed as the document's subtree
*/
@observer
export class TreeView extends ObservableReactComponent<TreeViewProps> {
// eslint-disable-next-line no-use-before-define
static _editTitleOnLoad: Opt<{ id: string; parent: TreeView | CollectionTreeView | undefined }>;
static _openTitleScript: Opt<ScriptField | undefined>;
static _openLevelScript: Opt<ScriptField | undefined>;
private _header: React.RefObject<HTMLDivElement> = React.createRef();
private _tref = React.createRef<HTMLDivElement>();
@observable _docRef: Opt<DocumentView> = undefined;
private _disposers: { [name: string]: IReactionDisposer } = {};
private _editTitleScript: (() => ScriptField) | undefined;
private _openScript: (() => ScriptField) | undefined;
private _treedropDisposer?: DragManager.DragDropDisposer;
get treeViewOpenIsTransient() {
return this.treeView.Document.treeView_OpenIsTransient || Doc.IsDataProto(this.Document);
}
@computed get treeViewOpen() {
return (!this.treeViewOpenIsTransient && Doc.GetT(this.Document, 'treeView_Open', 'boolean', true)) || this._transientOpenState;
}
set treeViewOpen(c: boolean) {
if (this.treeViewOpenIsTransient) this._transientOpenState = c;
else {
this.Document.treeView_Open = c;
this._transientOpenState = false;
}
}
@observable _transientOpenState = false; // override of the treeView_Open field allowing the display state to be independent of the document's state
@observable _editTitle: boolean = false;
@observable _dref: DocumentView | undefined | null = undefined;
get displayName() {
return 'TreeView(' + this.Document.title + ')';
} // this makes mobx trace() statements more descriptive
get defaultExpandedView() {
return this.Document._type_collection === CollectionViewType.Docking
? this.fieldKey
: this.treeView.dashboardMode
? this.fieldKey
: this.treeView.fileSysMode
? this.Document.isFolder
? this.fieldKey
: 'data' // file system folders display their contents (data). used to be they displayed their embeddings but now its a tree structure and not a flat list
: this.treeView.outlineMode || this.childDocs
? this.fieldKey
: Doc.noviceMode
? 'layout'
: StrCast(this.treeView.Document.treeView_ExpandedView, 'fields');
}
@computed get treeView() {
return this._props.treeView;
}
@computed get Document() {
return this._props.Document;
}
@computed get treeViewExpandedView() {
return this.validExpandViewTypes.includes(StrCast(this.Document.treeView_ExpandedView)) ? StrCast(this.Document.treeView_ExpandedView) : this.defaultExpandedView;
}
@computed get MAX_EMBED_HEIGHT() {
return NumCast(this._props.treeViewParent.maxEmbedHeight, 200);
}
@computed get dataDoc() {
return this.Document[DocData];
}
@computed get layoutDoc() {
return this.Document[DocLayout];
}
@computed get fieldKey() {
return StrCast(this.Document._treeView_FieldKey, Doc.LayoutDataKey(this.Document));
}
@computed get childDocs() {
return this.childDocList(this.fieldKey);
}
@computed get childLinks() {
return this.childDocList('links');
}
@computed get childEmbeddings() {
return this.childDocList('proto_embeddings');
}
@computed get childAnnos() {
return this.childDocList(this.fieldKey + '_annotations');
}
@computed get selected() {
return this._docRef?.IsSelected;
}
ScreenToLocalTransform = () => this._props.ScreenToLocalTransform();
childDocList(field: string) {
const layout = Cast(Doc.LayoutField(this.Document), Doc, null);
return DocListCast(this._props.dataDoc?.[field], DocListCast(layout?.[field], DocListCast(this.Document[field])));
}
moving: boolean = false;
@undoBatch move = (doc: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => {
if (this.Document !== target && addDoc !== returnFalse) {
const canAdd1 = (this._props.parentTreeView as TreeView).dropping || !(ComputedField.DisableCompute(() => FieldValue(this._props.parentTreeView?.Document.data)) instanceof ComputedField);
// bcz: this should all be running in a Temp undo batch instead of hackily testing for returnFalse
if (canAdd1 && this._props.removeDoc?.(doc) === true) {
this._props.parentTreeView instanceof TreeView && (this._props.parentTreeView.moving = true);
const res = addDoc(doc);
this._props.parentTreeView instanceof TreeView && (this._props.parentTreeView.moving = false);
return res;
}
}
return false;
};
@undoBatch remove = (docIn: Doc | Doc[], key: string) => {
const docs = toList(docIn);
this.treeView._props.select(false);
const ind = DocListCast(this.dataDoc[key]).indexOf(docs.lastElement());
const res = docs.reduce((flg, doc) => flg && Doc.RemoveDocFromList(this.dataDoc, key, doc), true);
res && ind > 0 && DocumentView.getDocumentView(DocListCast(this.dataDoc[key])[ind - 1], this.treeView.DocumentView?.())?.select(false);
return res;
};
@action setEditTitle = (docView?: DocumentView) => {
this._disposers.selection?.();
if (!docView) {
this._editTitle = false;
} else if (docView.IsSelected) {
this._editTitle = true;
this._disposers.selection = reaction(
() => docView.IsSelected,
isSel => !isSel && this.setEditTitle(undefined)
);
} else {
docView.select(false);
}
};
@action
openLevel = (docView: DocumentView) => {
if (this.Document.isFolder || Doc.IsSystem(this.Document)) {
this.treeViewOpen = !this.treeViewOpen;
} else {
// choose an appropriate embedding or make one. --- choose the first embedding that (1) user owns, (2) has no context field ... otherwise make a new embedding
const bestEmbedding = docView.Document.author === ClientUtils.CurrentUserEmail() && !Doc.IsDataProto(docView.Document) ? docView.Document : Doc.BestEmbedding(docView.Document);
this._props.addDocTab(bestEmbedding, OpenWhere.lightboxAlways);
}
};
@undoBatch
recurToggle = (childList: Doc[]) => {
if (childList.length > 0) {
childList.forEach(child => {
child.runProcess = !child.runProcess;
TreeView.ToggleChildrenRun.get(child)?.();
});
}
};
@undoBatch
getRunningChildren = (childList: Doc[]) => {
if (childList.length === 0) {
return [];
}
const runningChildren: Doc[] = [];
childList.forEach(child => {
if (child.runProcess && TreeView.GetRunningChildren.get(child)) {
if (child.runProcess) {
runningChildren.push(child);
}
runningChildren.push(...(TreeView.GetRunningChildren.get(child)?.() ?? []));
}
});
return runningChildren;
};
static GetRunningChildren = new Map<Doc, () => Doc[]>();
static ToggleChildrenRun = new Map<Doc, () => void>();
constructor(props: TreeViewProps) {
super(props);
makeObservable(this);
if (!TreeView._openLevelScript) {
TreeView._openTitleScript = ScriptField.MakeScript('scriptContext.setEditTitle(documentView)', { scriptContext: 'any', documentView: 'any' });
TreeView._openLevelScript = ScriptField.MakeScript(`scriptContext.openLevel(documentView)`, { scriptContext: 'any', documentView: 'any' });
}
this._openScript = Doc.IsSystem(this.Document) ? undefined : () => TreeView._openLevelScript!;
this._editTitleScript = Doc.IsSystem(this.Document) ? () => TreeView._openLevelScript! : () => TreeView._openTitleScript!;
// set for child processing highligting
this.dataDoc.hasChildren = this.childDocs.length > 0;
// this.dataDoc.children = this.childDocs;
TreeView.ToggleChildrenRun.set(this.Document, () => {
this.recurToggle(this.childDocs);
});
TreeView.GetRunningChildren.set(this.Document, () => this.getRunningChildren(this.childDocs));
}
_treeEle: HTMLDivElement | null = null;
protected createTreeDropTarget = (ele: HTMLDivElement) => {
this._treedropDisposer?.();
ele && ((this._treedropDisposer = DragManager.MakeDropTarget(ele, this.treeDrop.bind(this), this.Document, this.preTreeDrop.bind(this))), this.Document);
if (this._treeEle) this._props.unobserveHeight(this._treeEle);
this._props.observeHeight((this._treeEle = ele));
};
componentWillUnmount() {
this._treedropDisposer?.();
this._renderTimer && clearTimeout(this._renderTimer);
Object.values(this._disposers).forEach(disposer => disposer?.());
this._treeEle && this._props.unobserveHeight(this._treeEle);
document.removeEventListener('pointermove', this.onDragMove, true);
document.removeEventListener('pointermove', this.onDragUp, true);
// TODO: [AL] add these
this._props.hierarchyIndex !== undefined && this._props.RemFromMap?.(this.Document, this._props.hierarchyIndex);
}
componentDidUpdate(prevProps: Readonly<TreeViewProps>) {
super.componentDidUpdate(prevProps);
this._disposers.opening = reaction(
() => this.treeViewOpen,
open => {
!open && (this._renderCount = 20);
}
);
this._props.hierarchyIndex !== undefined && this._props.AddToMap?.(this.Document, this._props.hierarchyIndex);
}
componentDidMount() {
this._props.hierarchyIndex !== undefined && this._props.AddToMap?.(this.Document, this._props.hierarchyIndex);
}
onDragUp = () => {
document.removeEventListener('pointerup', this.onDragUp, true);
document.removeEventListener('pointermove', this.onDragMove, true);
};
onPointerEnter = (e: React.PointerEvent): void => {
this._props.isContentActive(true) && Doc.BrushDoc(this.dataDoc);
if (e.buttons === 1 && SnappingManager.IsDragging && this._props.isContentActive()) {
this._header.current!.className = 'treeView-header';
document.removeEventListener('pointermove', this.onDragMove, true);
document.removeEventListener('pointerup', this.onDragUp, true);
document.addEventListener('pointermove', this.onDragMove, true);
document.addEventListener('pointerup', this.onDragUp, true);
}
};
onPointerLeave = (): void => {
Doc.UnBrushDoc(this.dataDoc);
if (this._header.current?.className !== 'treeView-header-editing') {
this._header.current!.className = 'treeView-header';
}
document.removeEventListener('pointerup', this.onDragUp, true);
document.removeEventListener('pointermove', this.onDragMove, true);
};
onDragMove = (e: PointerEvent): void => {
Doc.UnBrushDoc(this.dataDoc);
const pt = [e.clientX, e.clientY];
const rect = this._header.current!.getBoundingClientRect();
const before = pt[1] < rect.top + rect.height / 2;
const inside = pt[0] > rect.left + rect.width * 0.33 || (!before && this.treeViewOpen && this.childDocs?.length);
this._header.current!.className = 'treeView-header';
if (inside) this._header.current!.className += ' treeView-header-inside';
else if (before) this._header.current!.className += ' treeView-header-above';
else if (!before) this._header.current!.className += ' treeView-header-below';
e.stopPropagation();
};
public static makeTextBullet() {
const bullet = Docs.Create.TextDocument('', {
layout: CollectionView.LayoutString('data'),
title: '-title-',
treeView_ExpandedViewLock: true,
treeView_ExpandedView: 'data',
_type_collection: CollectionViewType.Tree,
layout_hideLinkButton: true,
_layout_showSidebar: true,
_layout_fitWidth: true,
treeView_Type: TreeViewType.outline,
x: 0,
y: 0,
_xMargin: 0,
_yMargin: 0,
_layout_autoHeight: true,
_createDocOnCR: true,
_width: 1000,
_height: 10,
});
bullet.$title = ComputedField.MakeFunction('this.text?.Text');
bullet.$data = new List<Doc>([]);
DocumentView.addViewRenderedCb(bullet, dv => dv.ComponentView?.setFocus?.());
return bullet;
}
makeTextCollection = () => {
const bullet = TreeView.makeTextBullet();
TreeView._editTitleOnLoad = { id: bullet[Id], parent: this };
return this._props.addDocument(bullet);
};
makeFolder = () => {
const folder = Docs.Create.TreeDocument([], { title: 'Untitled folder', _dragOnlyWithinContainer: true, isFolder: true });
TreeView._editTitleOnLoad = { id: folder[Id], parent: this._props.parentTreeView };
return this.localAdd(folder);
};
preTreeDrop = () => {
// fall through and let the CollectionTreeView handle this since treeView items have no special properties of their own
};
@undoBatch
treeDrop = (e: Event, de: DragManager.DropEvent) => {
const pt = [de.x, de.y];
if (!this._header.current) return false;
const rect = this._header.current.getBoundingClientRect();
const before = pt[1] < rect.top + rect.height / 2;
const inside = this.treeView.fileSysMode && !this.Document.isFolder ? false : pt[0] > rect.left + rect.width * 0.33 || !!(!before && this.treeViewOpen && this.childDocs?.length);
if (de.complete.linkDragData) {
const sourceDoc = de.complete.linkDragData.linkSourceGetAnchor();
const destDoc = this.Document;
DocUtils.MakeLink(sourceDoc, destDoc, { link_relationship: 'tree link' });
e.stopPropagation();
return true;
}
const { docDragData } = de.complete;
if (docDragData && pt[0] < rect.left + rect.width) {
if (docDragData.draggedDocuments[0] === this.Document) return true;
const added = this.dropDocuments(
docDragData.droppedDocuments, //
before,
inside,
docDragData.dropAction,
docDragData.removeDocument,
docDragData.moveDocument,
docDragData.treeViewDoc === this.treeView.Document,
de.embedKey
);
e.stopPropagation();
!added && e.preventDefault();
return added;
}
return false;
};
localAdd = (docs: Doc | Doc[]): boolean => {
const innerAdd = (doc: Doc): boolean => {
const dataIsComputed = ComputedField.DisableCompute(() => FieldValue(this.dataDoc[this.fieldKey])) instanceof ComputedField;
const added = (!dataIsComputed || (this.dropping && this.moving)) && Doc.AddDocToList(this.dataDoc, this.fieldKey, doc);
dataIsComputed && DocCast(this.Document.embedContainer) && Doc.SetContainer(doc, DocCast(this.Document.embedContainer)!);
return added;
};
return toList(docs).reduce((flg, doc) => flg && innerAdd(doc), true as boolean);
};
dropping: boolean = false;
dropDocuments(
droppedDocuments: Doc[],
before: boolean,
inside: number | boolean,
dropAction: dropActionType | undefined,
removeDocument: DragManager.RemoveFunction | undefined,
moveDocument: DragManager.MoveFunction | undefined,
forceAdd: boolean,
canEmbed?: boolean
) {
const parentAddDoc = (doc: Doc | Doc[]) => this._props.addDocument(doc, undefined, undefined, before);
const addDoc = inside ? this.localAdd : parentAddDoc;
const canAdd = !StrCast((inside ? this.Document : this._props.treeViewParent)?.treeView_FreezeChildren).includes('add') || forceAdd;
if (canAdd && (dropAction !== dropActionType.inPlace || droppedDocuments.every(d => d.embedContainer === this._props.parentTreeView?.Document))) {
const move =
(!dropAction || (canEmbed && dropAction !== dropActionType.copy) || dropAction === dropActionType.proto || dropAction === dropActionType.move || dropAction === dropActionType.same || dropAction === dropActionType.inPlace) &&
moveDocument;
this._props.parentTreeView instanceof TreeView && (this._props.parentTreeView.dropping = true);
const res = droppedDocuments.reduce((added, d) => (move ? move(d, undefined, addDoc) || (dropAction === dropActionType.proto ? addDoc(d) : false) : addDoc(d)) || added, false);
this._props.parentTreeView instanceof TreeView && (this._props.parentTreeView.dropping = false);
return res;
}
return false;
}
refTransform = (ref: HTMLDivElement | undefined | null) => {
if (!ref) return this.ScreenToLocalTransform();
const { translateX, translateY, scale } = ClientUtils.GetScreenTransform(ref);
return new Transform(-translateX, -translateY, 1).scale(1 / scale);
};
docTransform = () => this.refTransform(this._dref?.ContentDiv);
getTransform = () => this.refTransform(this._tref.current);
embeddedPanelWidth = () => this._props.panelWidth() / (this.treeView._props.NativeDimScaling?.() || 1) - 3 /* paddingRight for bullet */;
embeddedPanelHeight = () => {
const layoutDoc = (temp => temp && Doc.expandTemplateLayout(temp, this.Document))(this.treeView._props.childLayoutTemplate?.()) || this.layoutDoc;
return Math.min(
NumCast(layoutDoc._height),
this.MAX_EMBED_HEIGHT,
(() => {
const aspect = Doc.NativeAspect(layoutDoc);
if (aspect) return this.embeddedPanelWidth() / (aspect || 1);
return layoutDoc._layout_fitWidth
? !Doc.NativeHeight(layoutDoc)
? NumCast(layoutDoc._height)
: Math.min((this.embeddedPanelWidth() * NumCast(layoutDoc.scrollHeight, Doc.NativeHeight(layoutDoc))) / (Doc.NativeWidth(layoutDoc) || NumCast(this._props.treeViewParent._height)))
: (this.embeddedPanelWidth() * NumCast(layoutDoc._height)) / NumCast(layoutDoc._width);
})()
);
};
@computed get expandedField() {
const ids: { [key: string]: string } = {};
const rows: JSX.Element[] = [];
const doc = this.Document;
doc &&
Object.keys(doc).forEach(key => {
!(key in ids) && doc[key] !== ComputedField.undefined && (ids[key] = key);
});
for (const key of Object.keys(ids).slice().sort()) {
if (this._props.skipFields?.includes(key) || key === 'title' || key === 'treeView_Open') continue;
const contents = doc[key];
let contentElement: (JSX.Element | null)[] | JSX.Element = [];
const leftOffset = observable({ width: 0 });
const expandedWidth = () => this._props.panelWidth() - leftOffset.width;
if (contents instanceof Doc || (Cast(contents, listSpec(Doc)) && Cast(contents, listSpec(Doc))!.length && Cast(contents, listSpec(Doc))![0] instanceof Doc)) {
const remDoc = (docs: Doc | Doc[]) => this.remove(docs, key);
const moveDoc = (docs: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => this.move(docs, target, addDoc);
const addDoc = (docs: Doc | Doc[], addBefore?: Doc, before?: boolean) => {
const innerAdd = (iDoc: Doc) => {
const dataIsComputed = ComputedField.DisableCompute(() => FieldValue(this.dataDoc[key])) instanceof ComputedField;
const added = (!dataIsComputed || (this.dropping && this.moving)) && Doc.AddDocToList(this.dataDoc, key, iDoc, addBefore, before, false, true);
dataIsComputed && DocCast(this.Document.embedContainer) && Doc.SetContainer(iDoc, DocCast(this.Document.embedContainer)!);
return added;
};
return toList(docs).reduce((flg, iDoc) => flg && innerAdd(iDoc), true as boolean);
};
contentElement = TreeView.GetChildElements(
contents instanceof Doc ? [contents] : DocListCast(contents),
this.treeView,
this,
doc,
undefined,
this._props.treeViewParent,
this._props.prevSibling,
addDoc,
remDoc,
moveDoc,
this._props.dragAction,
this._props.addDocTab,
this.titleStyleProvider,
this.ScreenToLocalTransform,
this._props.isContentActive,
expandedWidth,
this._props.renderDepth,
this._props.treeViewHideHeaderFields,
[...this._props.renderedIds, doc[Id]],
this._props.onCheckedClick,
this._props.onChildClick,
this._props.skipFields,
false,
this._props.whenChildContentsActiveChanged,
this._props.dontRegisterView,
emptyFunction,
emptyFunction,
this.childContextMenuItems(),
// TODO: [AL] Add these
this._props.AddToMap,
this._props.RemFromMap,
this._props.hierarchyIndex
);
} else {
contentElement = (
<EditableView
key="editableView"
contents={contents !== undefined ? Field.toString(contents as FieldType) : 'null'}
height={13}
fontSize={12}
GetValue={() => Field.toKeyValueString(doc, key)}
SetValue={(value: string) => Doc.SetField(doc, key, value, true)}
/>
);
}
rows.push(
<div style={{ display: 'flex', overflow: 'auto' }} key={key}>
<span
ref={r =>
runInAction(() => {
if (r) leftOffset.width = r.getBoundingClientRect().width;
})
}
style={{ fontWeight: 'bold' }}>
{key + ':'}
</span>
{contentElement}
</div>
);
}
rows.push(
<div style={{ display: 'flex', overflow: 'auto' }} key="newKeyValue">
<EditableView
key="editableView"
contents="+key=value"
height={13}
fontSize={12}
GetValue={returnEmptyString}
SetValue={input => {
const match = input.match(/([a-zA-Z0-9_-]+)(=|=:=)([a-zA-Z,_@?+\-*/ 0-9()]+)/);
if (match) {
const key = match[1];
const assign = match[2];
const val = match[3];
Doc.SetField(doc, key, assign + val);
return true;
}
return false;
}}
/>
</div>
);
return rows;
}
_renderTimer: NodeJS.Timeout | undefined;
@observable _renderCount = 1;
@computed get renderContent() {
TraceMobx();
const expandKey = this.treeViewExpandedView;
const sortings = (this._props.styleProvider?.(this.Document, this.treeView._props, StyleProp.TreeViewSortings) as { [key: string]: { color: string; icon: JSX.Element | string } }) ?? {};
if (['links', 'annotations', 'embeddings', this.fieldKey].includes(expandKey)) {
const sorting = StrCast(this.Document.treeView_SortCriterion, TreeSort.WhenAdded);
const sortKeys = Object.keys(sortings);
const curSortIndex = Math.max(
0,
sortKeys.findIndex(val => val === sorting)
);
const key = (expandKey === 'annotations' ? `${this.fieldKey}-` : '') + expandKey;
const remDoc = (doc: Doc | Doc[]) => this.remove(doc, key);
const moveDoc = (doc: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => this.move(doc, target, addDoc);
const localAdd = (doc: Doc, addBefore?: Doc, before?: boolean) => {
// if there's a sort ordering specified that can be modified on drop (eg, zorder can be modified, alphabetical can't),
// then the modification would be done here
const ordering = StrCast(this.Document.treeView_SortCriterion);
if (ordering === TreeSort.Zindex) {
const docs = TreeView.sortDocs(this.childDocs || ([] as Doc[]), ordering);
doc.zIndex = addBefore ? NumCast(addBefore.zIndex) + (before ? -0.5 : 0.5) : 1000;
docs.push(doc);
docs.sort((a, b) => (NumCast(a.zIndex) > NumCast(b.zIndex) ? 1 : -1)).forEach((d, i) => {
d.zIndex = i;
});
}
const dataIsComputed = ComputedField.DisableCompute(() => FieldValue(this.dataDoc[key])) instanceof ComputedField;
const added = (!dataIsComputed || (this.dropping && this.moving)) && Doc.AddDocToList(this.dataDoc, key, doc, addBefore, before, false);
!dataIsComputed && added && Doc.SetContainer(doc, this.Document);
return added;
};
const addDoc = (docs: Doc | Doc[], addBefore?: Doc, before?: boolean) => toList(docs).reduce((flg, doc) => flg && localAdd(doc, addBefore, before), true);
const docs = expandKey === 'embeddings' ? this.childEmbeddings : expandKey === 'links' ? this.childLinks : expandKey === 'annotations' ? this.childAnnos : this.childDocs;
let downX = 0;
let downY = 0;
if (docs?.length && this._renderCount < docs?.length) {
this._renderTimer && clearTimeout(this._renderTimer);
this._renderTimer = setTimeout(
action(() => {
this._renderCount = Math.min(docs!.length, this._renderCount + 20);
})
);
}
return (
<div>
{!docs?.length || this.treeView.outlineMode || this._props.AddToMap /* hack to identify pres box trees */ ? null : (
<div className="treeView-sorting">
<IconButton
color={sortings[sorting]?.color}
size={Size.XSMALL}
tooltip={`Sorted by : ${this.Document.treeView_SortCriterion}. click to cycle`}
icon={sortings[sorting]?.icon}
onPointerDown={e => {
downX = e.clientX;
downY = e.clientY;
e.stopPropagation();
}}
onClick={undoable(e => {
if (this._props.isContentActive() && Math.abs(e.clientX - downX) < 3 && Math.abs(e.clientY - downY) < 3) {
!this.treeView.outlineMode && (this.Document.treeView_SortCriterion = sortKeys[(curSortIndex + 1) % sortKeys.length]);
e.stopPropagation();
}
}, 'sort order')}
/>
</div>
)}
<ul
style={{ cursor: 'inherit' }}
key={expandKey + 'more'}
title={`Sorted by : ${this.Document.treeView_SortCriterion}. click to cycle`}
className="" // this.doc.treeView_HideTitle ? 'no-indent' : ''}
onPointerDown={e => {
downX = e.clientX;
downY = e.clientY;
e.stopPropagation();
}}
onClick={undoable(e => {
if (this._props.isContentActive() && Math.abs(e.clientX - downX) < 3 && Math.abs(e.clientY - downY) < 3) {
!this.treeView.outlineMode && (this.Document.treeView_SortCriterion = sortKeys[(curSortIndex + 1) % sortKeys.length]);
e.stopPropagation();
}
}, 'sort order')}>
{!docs
? null
: TreeView.GetChildElements(
docs,
this.treeView,
this,
this.layoutDoc,
this.dataDoc,
this._props.treeViewParent,
this._props.prevSibling,
addDoc,
remDoc,
moveDoc,
StrCast(this.Document.childDragAction, this._props.dragAction) as dropActionType,
this._props.addDocTab,
this.titleStyleProvider,
this.ScreenToLocalTransform,
this._props.isContentActive,
this._props.panelWidth,
this._props.renderDepth,
this._props.treeViewHideHeaderFields,
[...this._props.renderedIds, this.Document[Id]],
this._props.onCheckedClick,
this._props.onChildClick,
this._props.skipFields,
false,
this._props.whenChildContentsActiveChanged,
this._props.dontRegisterView,
emptyFunction,
emptyFunction,
this.childContextMenuItems(),
// TODO: [AL] add these
this._props.AddToMap,
this._props.RemFromMap,
this._props.hierarchyIndex,
this._renderCount
)}
</ul>
</div>
);
}
if (this.treeViewExpandedView === 'fields') {
return (
<ul key={this.Document[Id] + this.Document.title} style={{ cursor: 'inherit' }}>
<div>{this.expandedField}</div>
</ul>
);
}
return (
<ul
style={{}}
onPointerDown={e => {
e.preventDefault();
e.stopPropagation();
}}>
{this.renderEmbeddedDocument(false, this.treeView._props.childDocumentsActive ?? returnFalse)}
</ul>
); // "layout"
}
get onCheckedClick() {
return this.Document.type === DocumentType.COL ? undefined : (this._props.onCheckedClick?.() ?? ScriptCast(this.Document.onCheckedClick));
}
@action
bulletClick = (e: React.MouseEvent) => {
if (this.onCheckedClick) {
this.onCheckedClick?.script.run(
{
this: this.Document.isTemplateForField && this._props.dataDoc ? this._props.dataDoc : this.Document,
heading: this._props.treeViewParent.title,
checked: this.Document.treeView_Checked === 'check' ? 'x' : this.Document.treeView_Checked === 'x' ? 'remove' : 'check',
containingTreeView: this.treeView.Document,
},
console.log
);
} else {
this.treeViewOpen = !this.treeViewOpen;
}
e.stopPropagation();
};
@computed get renderBullet() {
TraceMobx();
const iconType = (this.treeView._props.styleProvider?.(this.Document, this.treeView._props, StyleProp.TreeViewIcon + (this.treeViewOpen ? ':treeOpen' : !this.childDocs.length ? ':empty' : '')) as string) || 'question';
const color = SettingsManager.userColor;
const checked = this.onCheckedClick ? (this.Document.treeView_Checked ?? 'unchecked') : undefined;
return (
<div
className={`bullet${this.treeView.outlineMode ? '-outline' : ''}`}
key="bullet"
title={this.childDocs?.length ? `click to see ${this.childDocs?.length} items` : `view ${this.Document.type} content`}
onClick={this.bulletClick}
style={
this.treeView.outlineMode
? {
opacity: this.titleStyleProvider?.(this.Document, this.treeView._props, StyleProp.Opacity) as number,
}
: {
pointerEvents: this._props.isContentActive() ? 'all' : undefined,
opacity: checked === 'unchecked' || typeof iconType !== 'string' ? undefined : 0.4,
color: checked === 'unchecked' ? SettingsManager.userColor : 'inherit',
}
}>
{this.treeView.outlineMode ? (
!(this.Document.text as RichTextField)?.Text ? null : (
<IconButton color={color} icon={<FontAwesomeIcon icon={[this.childDocs?.length && !this.treeViewOpen ? 'fas' : 'far', 'circle']} />} size={Size.XSMALL} />
)
) : (
<div className="treeView-bulletIcons">
<div className={`treeView-${this.onCheckedClick ? 'checkIcon' : 'expandIcon'}`}>
<FontAwesomeIcon
size="sm"
style={{ display: this.childDocs?.length >= 1 ? 'block' : 'none' }}
icon={checked === 'check' ? 'check' : checked === 'x' ? 'times' : checked === 'unchecked' ? 'square' : !this.treeViewOpen ? 'caret-right' : 'caret-down'}
/>
</div>
{this.onCheckedClick ? null : typeof iconType === 'string' ? <FontAwesomeIcon icon={iconType as IconProp} /> : iconType}
</div>
)}
</div>
);
}
@computed get validExpandViewTypes() {
const annos = () => (DocListCast(this.Document[this.fieldKey + '_annotations']).length && !this.treeView.dashboardMode ? 'annotations' : '');
const links = () => (Doc.Links(this.Document).length && !this.treeView.dashboardMode ? 'links' : '');
const data = () => (this.childDocs || this.treeView.dashboardMode ? this.fieldKey : '');
const embeddings = () => (this.treeView.dashboardMode ? '' : 'embeddings');
const fields = () => (Doc.noviceMode ? '' : 'fields');
const layout = Doc.noviceMode || this.Document._type_collection === CollectionViewType.Docking ? [] : ['layout'];
return [data(), ...layout, ...(this.treeView.fileSysMode ? [embeddings(), links(), annos()] : []), fields()].filter(m => m);
}
@action
expandNextviewType = () => {
if (this.treeViewOpen && !this.Document.isFolder && !this.treeView.outlineMode && !this.Document.treeView_ExpandedViewLock) {
const next = (modes: string[]) => modes[(modes.indexOf(StrCast(this.treeViewExpandedView)) + 1) % modes.length];
this.Document.treeView_ExpandedView = next(this.validExpandViewTypes);
}
this.treeViewOpen = true;
};
@observable headerEleWidth = 0;
@computed get titleButtons() {
const customHeaderButtons = this._props.styleProvider?.(this.Document, this.treeView._props, StyleProp.Decorations) as JSX.Element;
const color = SettingsManager.userColor;
return this._props.treeViewHideHeaderFields() || this.Document.treeView_HideHeaderFields ? null : (
<>
{customHeaderButtons} {/* e.g.,. hide button is set by dashboardStyleProvider */}
<IconButton
color={color}
icon={<FontAwesomeIcon icon="bars" />}
size={Size.XSMALL}
onClick={e => {
this.showContextMenu(e);
e.stopPropagation();
}}
/>
{Doc.noviceMode ? null : this.Document.treeView_ExpandedViewLock || Doc.IsSystem(this.Document) ? null : (
<span className="collectionTreeView-keyHeader" title="type of expanded data" key={this.treeViewExpandedView} onPointerDown={this.expandNextviewType}>
{this.treeViewExpandedView}
</span>
)}
</>
);
}
showContextMenu = (e: React.MouseEvent) => {
DocumentViewInternal.SelectAfterContextMenu = false;
simulateMouseClick(this._docRef?.ContentDiv, e.clientX, e.clientY + 30, e.screenX, e.screenY + 30);
DocumentViewInternal.SelectAfterContextMenu = true;
};
contextMenuItems = () => {
const makeFolder = { script: ScriptField.MakeFunction(`scriptContext.makeFolder()`, { scriptContext: 'any' })!, icon: 'folder-plus', label: 'New Folder' };
const openEmbedding = { script: ScriptField.MakeFunction(`openDoc(getEmbedding(this), "${OpenWhere.addRight}")`)!, icon: 'copy', label: 'Open New Embedding' };
const focusDoc = { script: ScriptField.MakeFunction(`DocFocusOrOpen(this)`)!, icon: 'eye', label: 'Focus or Open' };
const reopenDoc = { script: ScriptField.MakeFunction(`DocFocusOrOpen(this)`)!, icon: 'eye', label: 'Reopen' };
return [
...(this._props.contextMenuItems ?? []).filter(mi => (!mi.filter ? true : mi.filter.script.run({ doc: this.Document })?.result)),
...(this.Document.isFolder
? [makeFolder]
: Doc.IsSystem(this.Document)
? []
: this.treeView.fileSysMode && this.Document === this.Document[DocData]
? [openEmbedding, makeFolder]
: this.Document._type_collection === CollectionViewType.Docking
? []
: this.treeView.Document === Doc.MyRecentlyClosed
? [reopenDoc]
: [openEmbedding, focusDoc]),
];
};
childContextMenuItems = () => {
const customScripts = Cast(this.Document.childContextMenuScripts, listSpec(ScriptField), [])!;
const customFilters = Cast(this.Document.childContextMenuFilters, listSpec(ScriptField), [])!;
const icons = StrListCast(this.Document.childContextMenuIcons);
return StrListCast(this.Document.childContextMenuLabels).map((label, i) => ({ script: customScripts[i], filter: customFilters[i], icon: icons[i], label }));
};
onChildClick = () => this._props.onChildClick?.() ?? (this._editTitleScript?.() || ScriptField.MakeFunction(`DocFocusOrOpen(this)`)!);
onChildDoubleClick = () => ScriptCast(this.treeView.Document.treeView_ChildDoubleClick, !this.treeView.outlineMode ? this._openScript?.() : null);
refocus = () => this.treeView._props.focus(this.treeView.Document, {});
ignoreEvent = (e: React.MouseEvent) => {
if (this._props.isContentActive(true)) {
e.stopPropagation();
e.preventDefault();
}
};
titleStyleProvider = (doc: Doc | undefined, props: Opt<FieldViewProps>, property: string) => {
if (!doc || doc !== this.Document) return this._props?.treeView?._props.styleProvider?.(doc, props, property); // properties are inherited from the CollectionTreeView, not the hierarchical parent in the treeView
const { treeView } = this;
// prettier-ignore
switch (property.split(':')[0]) {
case StyleProp.Opacity: return this.treeView.outlineMode ? undefined : 1;
case StyleProp.BackgroundColor: return this.selected ? '#7089bb' : undefined; // StrCast(doc._backgroundColor, StrCast(doc.backgroundColor));
case StyleProp.Highlighting: if (this.treeView.outlineMode) return undefined;
break;
case StyleProp.BoxShadow: return undefined;
case StyleProp.DocContents: {
const highlightIndex = this.treeView.outlineMode ? Doc.DocBrushStatus.unbrushed : Doc.GetBrushHighlightStatus(doc);
const highlightColor = ['transparent', 'rgb(68, 118, 247)', 'rgb(68, 118, 247)', 'orange', 'lightBlue'][highlightIndex];
return treeView.outlineMode ? null : (
<div
className="treeView-label"
style={{
// just render a title for a tree view label (identified by treeViewDoc being set in 'props')
maxWidth: props?.PanelWidth() || undefined,
background: props?.styleProvider?.(doc, props, StyleProp.BackgroundColor) as string,
outline: SnappingManager.IsDragging ? undefined: `solid ${highlightColor} ${highlightIndex}px`,
paddingLeft: NumCast(treeView.Document.childXPadding, NumCast(treeView._props.childXPadding, Doc.IsComicStyle(doc)?20:0)),
paddingRight: NumCast(treeView.Document.childXPadding, NumCast(treeView._props.childXPadding, Doc.IsComicStyle(doc)?20:0)),
paddingTop: treeView._props.childYPadding,
paddingBottom: treeView._props.childYPadding,
}}>
{StrCast(doc?.title)}
</div>
);
}
default:
}
return treeView._props.styleProvider?.(doc, props, property);
};
embeddedStyleProvider = (doc: Doc | undefined, props: Opt<FieldViewProps>, property: string) => {
if (property.startsWith(StyleProp.Decorations)) return null;
return this._props?.treeView?._props.styleProvider?.(doc, props, property); // properties are inherited from the CollectionTreeView, not the hierarchical parent in the treeView
};
onKey = (e: KeyboardEvent) => {
if (this.Document.treeView_HideHeader || (this.Document.treeView_HideHeaderIfTemplate && this.treeView._props.childLayoutTemplate?.()) || this.treeView.outlineMode) {
switch (e.key) {
case 'Tab':
e.stopPropagation?.();
e.preventDefault?.();
setTimeout(() => RichTextMenu.Instance?.TextView?.EditorView?.focus(), 150);
UndoManager.RunInBatch(() => (e.shiftKey ? this._props.outdentDocument?.(true) : this._props.indentDocument?.(true)), 'tab');
return true;
case 'Backspace':
if (!(this.Document.text as RichTextField)?.Text && this._props.removeDoc?.(this.Document)) {
e.stopPropagation?.();
e.preventDefault?.();
return true;
}
break;
case 'Enter':
e.stopPropagation?.();
e.preventDefault?.();
return UndoManager.RunInBatch(this.makeTextCollection, 'bullet');
default:
}
}
return false;
};
titleWidth = () => Math.max(20, Math.min(this.treeView.truncateTitleWidth(), this._props.panelWidth())) / (this.treeView._props.NativeDimScaling?.() || 1) - this.headerEleWidth - treeBulletWidth();
/**
* Renders the EditableView title element for placement into the tree.
*/
@computed
get renderTitle() {
TraceMobx();
const view = this._editTitle ? (
<EditableView
key="_editTitle"
oneLine
display="inline-block"
editing={this._editTitle}
background="#7089bb"
contents={StrCast(this.Document.title)}
height={12}
sizeToContent
fontSize={12}
isEditingCallback={action(e => {
this._editTitle = e;
})}
GetValue={() => StrCast(this.Document.title)}
OnTab={undoable((shift?: boolean) => {
if (!shift) this._props.indentDocument?.(true);
else this._props.outdentDocument?.(true);
}, 'create new tree Doc')}
OnEmpty={undoable(() => this.treeView.outlineMode && this._props.removeDoc?.(this.Document), 'remove tree doc')}
OnFillDown={() => this.treeView.fileSysMode && this.makeFolder()}
SetValue={undoable((value: string, shiftKey: boolean, enterKey: boolean) => {
Doc.SetInPlace(this.Document, 'title', value, false);
return this.treeView.outlineMode && enterKey && this.makeTextCollection();
}, 'set tree doc title')}
/>
) : (
<DocumentView
key="title"
ref={r =>
runInAction(() => {
this._docRef = r || undefined;
if (this._docRef && TreeView._editTitleOnLoad?.id === this.Document[Id] && TreeView._editTitleOnLoad.parent === this._props.parentTreeView) {
this._docRef.select(false);
this.setEditTitle(this._docRef);
TreeView._editTitleOnLoad = undefined;
}
})
}
Document={this.Document}
fitWidth={returnTrue}
scriptContext={this}
hideDecorations
hideClickBehaviors
styleProvider={this.titleStyleProvider}
onClickScriptDisable="never" // tree docViews have a script to show fields, etc.
containerViewPath={this.treeView.childContainerViewPath}
addDocument={undefined}
addDocTab={this._props.addDocTab}
pinToPres={this.treeView._props.pinToPres}
onClickScript={this.onChildClick}
onDoubleClickScript={this.onChildDoubleClick}
dragAction={this._props.dragAction}
dragConfig={this.treeView.dragConfig}
moveDocument={this.move}
removeDocument={this._props.removeDoc}
ScreenToLocalTransform={this.getTransform}
NativeHeight={returnZero}
NativeWidth={returnZero}
PanelWidth={this.titleWidth}
PanelHeight={return18}
contextMenuItems={this.contextMenuItems}
renderDepth={1}
isContentActive={emptyFunction} // this._props.isContentActive}
isDocumentActive={this._props.isContentActive}
focus={this.refocus}
whenChildContentsActiveChanged={this._props.whenChildContentsActiveChanged}
disableBrushing={this.treeView._props.disableBrushing}
hideLinkButton={BoolCast(this.treeView.Document.childHideLinkButton)}
dontRegisterView={BoolCast(this.treeView.Document.childDontRegisterViews, this._props.dontRegisterView)}
xMargin={NumCast(this.treeView.Document.childXPadding, this.treeView._props.childXPadding)}
yMargin={NumCast(this.treeView.Document.childYPadding, this.treeView._props.childYPadding)}
childFilters={returnEmptyFilter}
childFiltersByRanges={returnEmptyFilter}
searchFilterDocs={returnEmptyDoclist}
/>
);
return (
<>
<div
className={`docContainer${Doc.IsSystem(this.Document) || this.Document.isFolder ? '-system' : ''}`}
ref={this._tref}
title="click to edit title. Double Click or Drag to Open"
style={{
backgroundColor: Doc.IsSystem(this.Document) || this.Document.isFolder ? SettingsManager.userVariantColor : undefined,
color: Doc.IsSystem(this.Document) || this.Document.isFolder ? lightOrDark(SettingsManager.userVariantColor) : undefined,
fontWeight: Doc.IsSearchMatch(this.Document) !== undefined ? 'bold' : undefined,
textDecoration: Doc.GetT(this.Document, 'title', 'string', true) ? 'underline' : undefined,
outline: this.Document === Doc.ActiveDashboard ? 'dashed 1px #06123232' : undefined,
pointerEvents: !this._props.isContentActive() ? 'none' : undefined,
}}>
{view}
</div>
<div
className="treeView-rightButtons"
ref={r =>
runInAction(() => {
r && (this.headerEleWidth = r.getBoundingClientRect().width);
})
}>
{this.titleButtons}
</div>
</>
);
}
renderBulletHeader = (contents: JSX.Element, editing: boolean) => (
<>
<div
className={`treeView-header` + (editing ? '-editing' : '')}
key="titleheader"
ref={this._header}
onClick={this.ignoreEvent}
onPointerDown={e => {
this.treeView.isContentActive() &&
setupMoveUpEvents(
this,
e,
() => {
(this._dref ?? this._docRef)?.startDragging(e.clientX, e.clientY, undefined);
return true;
},
returnFalse,
emptyFunction
);
}}
onPointerEnter={this.onPointerEnter}
onPointerLeave={this.onPointerLeave}>
<div
className="treeView-background"
style={{
background: SettingsManager.userColor,
}}
/>
{contents}
</div>
{this.renderBorder}
</>
);
fitWidthFilter = (doc: Doc) => (doc.type === DocumentType.IMG ? false : undefined);
renderEmbeddedDocument = (asText: boolean, isActive: () => boolean | undefined) => (
<div style={{ height: this.embeddedPanelHeight(), width: this.embeddedPanelWidth() }}>
<DocumentView
key={this.Document[Id]}
ref={action((r: DocumentView | null) => {
this._dref = r;
})}
Document={this.Document}
fitWidth={this.fitWidthFilter}
PanelWidth={this.embeddedPanelWidth}
PanelHeight={this.embeddedPanelHeight}
LayoutTemplateString={asText ? FormattedTextBox.LayoutString('text') : undefined}
LayoutTemplate={this.treeView._props.childLayoutTemplate}
isContentActive={isActive}
isDocumentActive={isActive}
styleProvider={asText ? this.titleStyleProvider : this.embeddedStyleProvider}
fitContentsToBox={returnTrue}
hideTitle={asText}
hideDecorations
hideClickBehaviors
hideLinkButton={BoolCast(this.treeView.Document.childHideLinkButton)}
dontRegisterView={BoolCast(this.treeView.Document.childDontRegisterViews, this._props.dontRegisterView)}
ScreenToLocalTransform={this.docTransform}
renderDepth={this._props.renderDepth + 1}
onClickScript={this.onChildClick}
onKey={this.onKey}
containerViewPath={this.treeView.childContainerViewPath}
childFilters={returnEmptyFilter}
childFiltersByRanges={returnEmptyFilter}
searchFilterDocs={returnEmptyDoclist}
focus={this.refocus}
addDocument={this._props.addDocument}
moveDocument={this.move}
removeDocument={this._props.removeDoc}
whenChildContentsActiveChanged={this._props.whenChildContentsActiveChanged}
xMargin={NumCast(this.treeView.Document.childXPadding, this.treeView._props.childXPadding)}
yMargin={NumCast(this.treeView.Document.childYPadding, this.treeView._props.childYPadding)}
addDocTab={this._props.addDocTab}
pinToPres={this.treeView._props.pinToPres}
disableBrushing={this.treeView._props.disableBrushing}
scriptContext={this}
/>
</div>
);
// renders the text version of a document as the header. This is used in the file system mode and in other vanilla tree views.
@computed get renderTitleAsHeader() {
return this.treeView.Document.treeView_HideUnrendered && this.Document.layout_unrendered && !this.Document.treeView_FieldKey ? (
<div />
) : (
<>
{this.renderBullet}
{this.renderTitle}
</>
);
}
// renders the document in the header field instead of a text proxy.
renderDocumentAsHeader = (asText: boolean) => (
<>
{this.renderBullet}
{this.renderEmbeddedDocument(asText, this._props.isContentActive)}
</>
);
@computed get renderBorder() {
const sorting = StrCast(this.Document.treeView_SortCriterion, TreeSort.WhenAdded);
const sortings = (this._props.styleProvider?.(this.Document, this.treeView._props, StyleProp.TreeViewSortings) ?? {}) as { [key: string]: { color: string; icon: JSX.Element } };
return (
<div className={`treeView-border${this.treeView.outlineMode ? TreeViewType.outline : ''}`} style={{ borderColor: sortings[sorting]?.color }}>
{!this.treeViewOpen ? null : this.renderContent}
</div>
);
}
onTreeDrop = (de: React.DragEvent) => {
const pt = [de.clientX, de.clientY];
const rect = this._header.current!.getBoundingClientRect();
const before = pt[1] < rect.top + rect.height / 2;
const inside = this.treeView.fileSysMode && !this.Document.isFolder ? false : pt[0] > rect.left + rect.width * 0.33 || !!(!before && this.treeViewOpen && this.childDocs?.length);
this.treeView.onTreeDrop(de, (docs: Doc[]) => this.dropDocuments(docs, before, inside, dropActionType.copy, undefined, undefined, false, false));
};
render() {
TraceMobx();
const hideTitle = this.Document.treeView_HideHeader || (this.Document.treeView_HideHeaderIfTemplate && this.treeView._props.childLayoutTemplate?.()) || this.treeView.outlineMode;
return this._props.renderedIds?.indexOf(this.Document[Id]) !== -1 ? (
'<' + this.Document.title + '>' // just print the title of documents we've previously rendered in this hierarchical path to avoid cycles
) : (
<div
className={`treeView-container${this._props.isContentActive() ? '-active' : ''}`}
ref={this.createTreeDropTarget}
onDrop={this.onTreeDrop}
// onPointerDown={e => this._props.isContentActive(true) && DocumentView.DeselectAll()} // bcz: this breaks entering a text filter in a filterBox since it deselects the filter's target document
// onKeyDown={this.onKeyDown}
>
<li className="collection-child">
{hideTitle && this.Document.type !== DocumentType.RTF && !this.Document.treeView_RenderAsBulletHeader // should test for prop 'treeView_RenderDocWithBulletAsHeader"
? this.renderEmbeddedDocument(false, returnFalse)
: this.renderBulletHeader(hideTitle ? this.renderDocumentAsHeader(!this.Document.treeView_RenderAsBulletHeader) : this.renderTitleAsHeader, this._editTitle)}
</li>
</div>
);
}
public static sortDocs(childDocs: Doc[], criterion: string | undefined) {
const docs = childDocs.slice();
if (criterion !== TreeSort.WhenAdded) {
const sortAlphaNum = (a: string, b: string): 0 | 1 | -1 => {
const reN = /[0-9]*$/;
const aA = a.replace(reN, '') ? a.replace(reN, '') : +a; // get rid of trailing numbers
const bA = b.replace(reN, '') ? b.replace(reN, '') : +b;
if (aA === bA) {
// if header string matches, then compare numbers numerically
const aN = parseInt(a.match(reN)![0], 10);
const bN = parseInt(b.match(reN)![0], 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}
return aA > bA ? 1 : -1;
};
docs.sort((d1, d2): 0 | 1 | -1 => {
const a = criterion === TreeSort.AlphaUp ? d2 : d1;
const b = criterion === TreeSort.AlphaUp ? d1 : d2;
const first = a[criterion === TreeSort.Zindex ? 'zIndex' : 'title'];
const second = b[criterion === TreeSort.Zindex ? 'zIndex' : 'title'];
if (typeof first === 'number' && typeof second === 'number') return first - second > 0 ? 1 : -1;
if (typeof first === 'string' && typeof second === 'string') return sortAlphaNum(first, second);
return criterion ? 1 : -1;
});
}
return docs;
}
public static GetChildElements(
childDocs: Doc[],
treeView: CollectionTreeView,
parentTreeView: CollectionTreeView | TreeView | undefined,
treeViewParent: Doc,
dataDoc: Doc | undefined,
parentCollectionDoc: Doc | undefined,
containerPrevSibling: Doc | undefined,
add: (doc: Doc | Doc[], relativeTo?: Doc, before?: boolean) => boolean,
remove: undefined | ((doc: Doc | Doc[]) => boolean),
move: DragManager.MoveFunction,
dragAction: dropActionType,
addDocTab: (doc: Doc | Doc[], where: OpenWhere) => boolean,
styleProvider: undefined | StyleProviderFuncType,
screenToLocalXf: () => Transform,
isContentActive: (outsideReaction?: boolean) => boolean,
panelWidth: () => number,
renderDepth: number,
treeViewHideHeaderFields: () => boolean,
renderedIds: string[],
onCheckedClick: undefined | (() => ScriptField),
onChildClick: undefined | (() => ScriptField | undefined),
skipFields: string[] | undefined,
firstLevel: boolean,
whenChildContentsActiveChanged: (isActive: boolean) => void,
dontRegisterView: boolean | undefined,
observerHeight: (ref: HTMLElement) => void,
unobserveHeight: (ref: HTMLElement) => void,
contextMenuItems: { script: ScriptField; filter: ScriptField; label: string; icon: string }[],
// TODO: [AL] add these
AddToMap?: (treeViewDoc: Doc, index: number[]) => void,
RemFromMap?: (treeViewDoc: Doc, index: number[]) => void,
hierarchyIndex?: number[],
renderCount?: number
) {
const docs = TreeView.sortDocs(childDocs, StrCast(treeViewParent.treeView_SortCriterion, TreeSort.WhenAdded));
const rowWidth = () => panelWidth() - treeBulletWidth() * (treeView._props.NativeDimScaling?.() || 1);
const treeViewRefs = new Map<Doc, TreeView | undefined>();
return docs
.filter(child => child instanceof Doc)
.map((child, i) => {
if (renderCount && i > renderCount) return null;
const pair = Doc.GetLayoutDataDocPair(treeViewParent, dataDoc, child);
if (!pair.layout || pair.data instanceof Promise) {
return null;
}
const setRef = (r: TreeView | null) => treeViewRefs.set(child, r || undefined);
const dentDoc = (editTitle: boolean, newParent: Doc, addAfter: Doc | undefined, parent: TreeView | CollectionTreeView | undefined) => {
if (parent instanceof TreeView && parent._props.treeView.fileSysMode && !newParent.isFolder) return;
const fieldKey = Doc.LayoutDataKey(newParent);
if (remove && fieldKey && Cast(newParent[fieldKey], listSpec(Doc)) !== undefined) {
remove(child);
DocumentView.SetSelectOnLoad(child);
TreeView._editTitleOnLoad = editTitle ? { id: child[Id], parent } : undefined;
Doc.AddDocToList(newParent, fieldKey, child, addAfter, false);
newParent.treeView_Open = true;
Doc.SetContainer(child, treeView.Document);
}
};
const indent = i === 0 ? undefined : (editTitle: boolean) => dentDoc(editTitle, docs[i - 1], undefined, treeViewRefs.get(docs[i - 1]));
const outdent = !parentCollectionDoc ? undefined : (editTitle: boolean) => dentDoc(editTitle, parentCollectionDoc, containerPrevSibling, parentTreeView instanceof TreeView ? parentTreeView._props.parentTreeView : undefined);
const addDocument = (doc: Doc | Doc[], annotationKey?: string, relativeTo?: Doc, before?: boolean) => add(doc, relativeTo ?? docs[i], before !== undefined ? before : false);
const childLayout = pair.layout[DocLayout];
const rowHeight = () => {
const aspect = Doc.NativeAspect(childLayout);
return aspect ? Math.min(NumCast(childLayout._width), rowWidth()) / aspect : NumCast(childLayout._height);
};
return (
<TreeView
key={child[Id]}
ref={setRef}
Document={pair.layout}
dataDoc={pair.data}
treeViewParent={treeViewParent}
prevSibling={docs[i]}
hierarchyIndex={hierarchyIndex ? [...hierarchyIndex, i + 1] : undefined}
AddToMap={AddToMap}
RemFromMap={RemFromMap}
treeView={treeView}
indentDocument={indent}
outdentDocument={outdent}
onCheckedClick={onCheckedClick}
onChildClick={onChildClick}
renderDepth={renderDepth}
removeDoc={StrCast(treeViewParent.treeView_FreezeChildren).includes('remove') ? undefined : remove}
addDocument={addDocument}
styleProvider={styleProvider}
panelWidth={rowWidth}
panelHeight={rowHeight}
dontRegisterView={dontRegisterView}
moveDocument={move}
dragAction={dragAction}
addDocTab={addDocTab}
ScreenToLocalTransform={screenToLocalXf}
isContentActive={isContentActive}
treeViewHideHeaderFields={treeViewHideHeaderFields}
renderedIds={renderedIds}
skipFields={skipFields}
firstLevel={firstLevel}
whenChildContentsActiveChanged={whenChildContentsActiveChanged}
parentTreeView={parentTreeView}
observeHeight={observerHeight}
unobserveHeight={unobserveHeight}
contextMenuItems={contextMenuItems}
/>
);
});
}
}
|