aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/CurrentUserUtils.ts
blob: 1c0f11c913d92032971e64a8ae0169460127cfb8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
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
import { reaction, runInAction } from "mobx";
import * as rp from 'request-promise';
import { ClientUtils, OmitKeys } from "../../ClientUtils";
import { Doc, DocListCast, DocListCastAsync, FieldType, Opt } from "../../fields/Doc";
import { InkEraserTool, InkInkTool, InkProperty, InkTool } from "../../fields/InkField";
import { List } from "../../fields/List";
import { PrefetchProxy } from "../../fields/Proxy";
import { RichTextField } from "../../fields/RichTextField";
import { listSpec } from "../../fields/Schema";
import { ScriptField } from "../../fields/ScriptField";
import { Cast, DateCast, DocCast, StrCast } from "../../fields/Types";
import { WebField, nullAudio } from "../../fields/URLField";
import { SetCachedGroups, SharingPermissions } from "../../fields/util";
import { Gestures } from "../../pen-gestures/GestureTypes";
import { DocServer } from "../DocServer";
import { DocUtils, FollowLinkScript } from '../documents/DocUtils';
import { CollectionViewType, DocumentType, standardViewTypes } from "../documents/DocumentTypes";
import { Docs, DocumentOptions, FInfo, FInfoFieldType } from "../documents/Documents";
import { DashboardView } from "../views/DashboardView";
import { OverlayView } from "../views/OverlayView";
import { CollectionTreeView } from "../views/collections/CollectionTreeView";
import { TreeViewType } from "../views/collections/CollectionTreeViewType";
import { CollectionView } from "../views/collections/CollectionView";
import { Colors } from "../views/global/globalEnums";
import { mediaState } from "../views/nodes/AudioBox";
import { ButtonType, FontIconBox } from "../views/nodes/FontIconBox/FontIconBox";
import { ImageBox } from "../views/nodes/ImageBox";
import { LabelBox } from "../views/nodes/LabelBox";
import { OpenWhere } from "../views/nodes/OpenWhere";
import { ImportElementBox } from "../views/nodes/importBox/ImportElementBox";
import { DragManager } from "./DragManager";
import { dropActionType } from "./DropActionTypes";
import { MakeTemplate } from "./DropConverter";
import { UPDATE_SERVER_CACHE } from "./LinkManager";
import { ScriptingGlobals } from "./ScriptingGlobals";
import { SelectionManager } from "./SelectionManager";
import { ColorScheme } from "./SettingsManager";
import { SnappingManager } from "./SnappingManager";
import { UndoManager } from "./UndoManager";
import { DocumentView } from "../views/nodes/DocumentView";
import { IconProp } from "@fortawesome/fontawesome-svg-core";

export interface Button {
    // DocumentOptions fields a button can set
    title?: string;
    toolTip?: string;
    icon?: string;
    isSystem?: boolean;
    btnType?: ButtonType;
    numBtnMin?: number;
    numBtnMax?: number;
    switchToggle?: boolean;
    width?: number;
    linearBtnWidth?: number;
    toolType?: string; // type of pen tool
    expertMode?: boolean;// available only in expert mode
    btnList?: List<string>;
    ignoreClick?: boolean;
    showUntilToggle?: boolean; // whether the popup should stay open when the background is clicked.
    buttonText?: string;
    backgroundColor?: string;
    waitForDoubleClickToClick?: boolean;

    // fields that do not correspond to DocumentOption fields
    scripts?: { script?: string; onClick?: string; onDoubleClick?: string }
    funcs?: { [key:string]: string};
    subMenu?: Button[];
}

// Not really necessary, but for now, all tags should start with a capital first letter
export type TagName<T extends string> =
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        T extends `${infer First}${infer Rest}`
          ? First extends Uppercase<First> 
            ? First extends Lowercase<First> 
              ? never  // If it's the same when uppercased and lowercased, it's not a letter.
              : T      // Otherwise, it's a valid capitalized string.
            : never
          : never;
export function ToTagName(key: string):"Tag"{
    return ((str => str[0].toUpperCase() + str.slice(1))(key.startsWith('#') ? key.substring(1) : key)) as "Tag";
}


export let resolvedPorts: { server: number, socket: number };
export class CurrentUserUtils {

    // initializes experimental advanced template views - slideView,  headerView
    static setupUserDocumentCreatorButtons(doc: Doc, userDocTemplates: Opt<Doc>) {
        const userTemplates = DocListCast(userDocTemplates?.data).filter(fdoc => !Doc.IsSystem(fdoc));
        const reqdOpts:DocumentOptions = {
            title: "User Tools", _xMargin: 0, _layout_showTitle: "title", _chromeHidden: true, hidden: false,
            _dragOnlyWithinContainer: true, layout_hideContextMenu: true, isSystem: true, _forceActive: true,
            _layout_autoHeight: true, _width: 500, _height: 300, _layout_fitWidth: true, _layout_columnWidth: 35, ignoreClick: true, _lockedPosition: true,
        };
        const reqdScripts = { dropConverter : "convertToButtons(dragData)" };
        const reqdFuncs = { /* hidden: "IsNoviceMode()"  */ };
        return DocUtils.AssignScripts(userDocTemplates ?? Docs.Create.MasonryDocument(userTemplates, reqdOpts), reqdScripts, reqdFuncs);
    }

    /// Initializes templates for editing click funcs of a document 
    static setupChildClickEditors(doc: Doc, field = "clickFuncs-child") {
        const tempClicks = DocCast(doc[field]);
        const reqdClickOpts:DocumentOptions = {_width: 300, _height:200, isSystem: true};
        const reqdTempOpts:{opts:DocumentOptions, script: string}[] = [
            { opts: { title: "Open In Target",        targetScriptKey: "onChildClick"},       script: "docCastAsync(documentView?.containerViewPath().lastElement()?.Document.target).then((target) => target && (target.proto.data = new List([this])))"},
            { opts: { title: "Open Detail On Right",  targetScriptKey: "onChildDoubleClick"}, script: `openDoc(this.doubleClickView, "${OpenWhere.addRight}")`}];
        const reqdClickList = reqdTempOpts.map(opts => {
            const allOpts = {...reqdClickOpts, ...opts.opts};
            const clickDoc = tempClicks ? DocListCast(tempClicks.data).find(fdoc => fdoc.title === opts.opts.title): undefined;
            return DocUtils.AssignOpts(clickDoc, allOpts) ?? Docs.Create.ScriptingDocument(ScriptField.MakeScript(opts.script),allOpts);
        });

        const reqdOpts:DocumentOptions = { title: "child click editors", _height:75, isSystem: true};
        return DocUtils.AssignOpts(tempClicks, reqdOpts, reqdClickList) ?? (doc[field] = Docs.Create.TreeDocument(reqdClickList, reqdOpts));
    }

    /// Initializes templates for editing click funcs of a document 
    static setupClickEditorTemplates(doc: Doc, field = "template_clickFuncs") {
        const tempClicks = DocCast(doc[field]);
        const reqdClickOpts:DocumentOptions = { _width: 300, _height:200, isSystem: true};
        const reqdTempOpts:{opts:DocumentOptions, script: string}[] = [
            { opts: { title: "onClick"},             script: "console.log('click')"},
            { opts: { title: "onDoubleClick"},       script: "console.log('click')"},
            { opts: { title: "onChildClick"},        script: "console.log('click')"},
            { opts: { title: "onChildDoubleClick"},  script: "console.log('click')"},
            { opts: { title: "onCheckedClick"},      script: "console.log(heading, checked, containingTreeView)"},
        ];
        const reqdClickList = reqdTempOpts.map(opts => {
            const title = opts.opts.title?.toString();
            const allOpts = {...reqdClickOpts, ...opts.opts};
            const clickDoc = tempClicks ? DocListCast(tempClicks.data).find(fdoc => fdoc.title === title): undefined;
            const script = ScriptField.MakeScript(opts.script, {heading:Doc.name, checked:"boolean", containingTreeView:Doc.name});
            const scriptDoc = Docs.Create.ScriptingDocument(script, allOpts, title)
            return DocUtils.AssignOpts(clickDoc, allOpts) ?? MakeTemplate(scriptDoc);
        });

        const reqdOpts:DocumentOptions = {title: "click editor templates", _height:75, isSystem: true};
        return DocUtils.AssignOpts(tempClicks, reqdOpts, reqdClickList) ?? (doc[field] = Docs.Create.TreeDocument(reqdClickList, reqdOpts));
    }

    /// Initializes templates that can be applied to notes
    static setupNoteTemplates(doc: Doc, field="template_notes") {
        const tempNotes = DocCast(doc[field]);
        const reqdTempOpts:DocumentOptions[] = [
            { title: "Postit", backgroundColor: "yellow",    icon: "sticky-note", _layout_showTitle: "title", layout_borderRounding: "5px"},
            { title: "Idea",   backgroundColor: "pink",      icon: "lightbulb"  , _layout_showTitle: "title"},
            { title: "Topic",  backgroundColor: "lightblue", icon: "book-open"  , _layout_showTitle: "title"}];

        
        const reqdNoteList = [...reqdTempOpts.map(opts => {
            const reqdOpts = {...opts, isSystem:true, width:200, layout_autoHeight: true, layout_fitWidth: true};
            const noteTemp = tempNotes ? DocListCast(tempNotes.data).find(fdoc => fdoc.title === opts.title): undefined;
            return DocUtils.AssignOpts(noteTemp, reqdOpts) ?? MakeTemplate(Docs.Create.TextDocument("",reqdOpts));
        }), DocCast(doc.emptyMetaNote), ... DocListCast(tempNotes?.data).filter(note => !reqdTempOpts.find(reqd => reqd.title === note.title))];

        const reqdOpts:DocumentOptions = { title: "Note Layouts", _height: 75, isSystem: true };
        return DocUtils.AssignOpts(tempNotes, reqdOpts, reqdNoteList) ?? (doc[field] = Docs.Create.TreeDocument(reqdNoteList, reqdOpts));
    }
    static setupUserTemplates(doc: Doc, field="template_user") {
        const tempUsers = DocCast(doc[field]);
        const reqdUserList = DocListCast(tempUsers?.data);

        const reqdOpts:DocumentOptions = { title: "User Layouts", _height: 75, isSystem: true };
        return DocUtils.AssignOpts(tempUsers, reqdOpts, reqdUserList) ?? (doc[field] = Docs.Create.TreeDocument(reqdUserList, reqdOpts));
    }

    /// Initializes collection of templates for notes and click functions
    static setupDocTemplates(doc: Doc, field="myTemplates") {
        const templates = [
            CurrentUserUtils.setupNoteTemplates(doc),
            CurrentUserUtils.setupUserTemplates(doc),
            CurrentUserUtils.setupClickEditorTemplates(doc)
        ];
        CurrentUserUtils.setupChildClickEditors(doc)
        const reqdOpts = { title: "template layouts", _xMargin: 0, isSystem: true,  };
        const reqdScripts = {  dropConverter: "convertToButtons(dragData)"  };
        return DocUtils.AssignDocField(doc, field, (opts,items) => Docs.Create.TreeDocument(items??[], opts), reqdOpts, templates, reqdScripts);
    }
    
    static setupAnnoPalette(doc: Doc, field="myStickers") {
        const reqdOpts:DocumentOptions = {
            title: "Stickers", _xMargin: 0, _layout_showTitle: "title", hidden: false, _chromeHidden: true,
            _dragOnlyWithinContainer: true, layout_hideContextMenu: true, isSystem: true, _forceActive: true,
            _layout_autoHeight: true, _width: 500, _height: 300, _layout_fitWidth: true, _layout_columnWidth: 35, ignoreClick: true, _lockedPosition: true,
        };
        const reqdScripts = {  dropConverter: "convertToButtons(dragData)"  };
        const savedAnnos = DocCast(doc[field]);
        return DocUtils.AssignDocField(doc, field, (opts,items) => Docs.Create.MasonryDocument(items??[], opts), reqdOpts, DocListCast(savedAnnos?.data), reqdScripts);
    }

    static setupLightboxDrawingPreviews(doc: Doc, field="myLightboxDrawings") {
        const reqdOpts:DocumentOptions = {
            title: "Preview", _header_height: 0, _layout_fitWidth: true,  childLayoutFitWidth: true,
        };
        const reqdScripts = {};
        const drawings = DocCast(doc[field]);
        return DocUtils.AssignDocField(doc, field, (opts,items) => Docs.Create.CarouselDocument(items??[], opts), reqdOpts, DocListCast(drawings?.data), reqdScripts);
    }

    // setup templates for different document types when they are iconified from Document Decorations
    static setupDefaultIconTemplates(doc: Doc, field="template_icons") {
        const reqdOpts = { title: "icon templates", _height: 75, isSystem: true };
        const templateIconsDoc = DocUtils.AssignOpts(DocCast(doc[field]), reqdOpts) ?? (doc[field] = Docs.Create.TreeDocument([], reqdOpts));

        const labelBox = (opts: DocumentOptions, fieldKey:string) => Docs.Create.LabelDocument({
            layout: LabelBox.LayoutString(fieldKey), letterSpacing: "unset", _label_minFontSize: 14, _label_maxFontSize: 14, layout_borderRounding: "5px",  _width: 150, _height: 70, _xPadding: 10, _yPadding: 10, ...opts
        });
        const imageBox = (opts: DocumentOptions, fieldKey:string) => Docs.Create.ImageDocument( "http://www.cs.brown.edu/~bcz/noImage.png", { layout:ImageBox.LayoutString(fieldKey), "icon_nativeWidth": 360 / 4, "icon_nativeHeight": 270 / 4, iconTemplate:DocumentType.IMG,  _width: 360 / 4, _height: 270 / 4,  _layout_showTitle: "title", ...opts });
        const fontBox = (opts:DocumentOptions, fieldKey:string) => Docs.Create.FontIconDocument({ layout:FontIconBox.LayoutString(fieldKey), _nativeHeight: 30, _nativeWidth: 30, _width: 30, _height: 30, ...opts  });
        
        const makeIconTemplate = (name: DocumentType | string | undefined, templateField: string, opts:DocumentOptions) => {
            const title = "icon" + (name ? "_" + name : "");
            const curIcon = DocCast(templateIconsDoc[title]);
            const creator =  (() => { switch (opts.iconTemplate) {
                                        case DocumentType.IMG : return imageBox;
                                        case DocumentType.FONTICON: return fontBox;
                                        default: return labelBox;
                                    }})();
            const allopts = {isSystem: true, onClickScriptDisable: "never",  ...opts, title};
            return DocUtils.AssignScripts(  (curIcon?.iconTemplate === opts.iconTemplate ? 
                      DocUtils.AssignOpts(curIcon, allopts):undefined) ?? ((templateIconsDoc[title] = MakeTemplate(creator(allopts, templateField)))),
                {onClick:"deiconifyView(documentView)", onDoubleClick: "deiconifyViewToLightbox(documentView)", });
        };
        const iconTemplates = [
            // see createCustomView for where icon templates are created at run time
            // templates defined by a Docs icon_fieldKey (e.g., ink with a transciprtion shows a template of the transcribed text, not miniature ink)
            makeIconTemplate("transcription",    "text",  { iconTemplate:DocumentType.LABEL, backgroundColor: "orange" }),
            // templates defined by a Doc's type
            makeIconTemplate(undefined,          "title", { iconTemplate:DocumentType.LABEL, backgroundColor: "dimgray"}),
            makeIconTemplate(DocumentType.AUDIO, "title", { iconTemplate:DocumentType.LABEL, backgroundColor: "lightgreen"}),
            makeIconTemplate(DocumentType.PDF,   "title", { iconTemplate:DocumentType.LABEL, backgroundColor: "pink"}),
            makeIconTemplate(DocumentType.WEB,   "title", { iconTemplate:DocumentType.LABEL, backgroundColor: "brown"}),
            makeIconTemplate(DocumentType.RTF,   "text",  { iconTemplate:DocumentType.LABEL, _layout_showTitle: "title"}),
            makeIconTemplate(DocumentType.IMG,   "data",  { iconTemplate:DocumentType.IMG,   _height: undefined}),
            makeIconTemplate(DocumentType.COL,   "icon",  { iconTemplate:DocumentType.IMG}),
            makeIconTemplate(DocumentType.COL,   "icon",  { iconTemplate:DocumentType.IMG}),
            makeIconTemplate(DocumentType.VID,   "icon",  { iconTemplate:DocumentType.IMG}),
            makeIconTemplate(DocumentType.BUTTON,"title", { iconTemplate:DocumentType.FONTICON}),
         // makeIconTemplate(DocumentType.PDF,   "icon",  { iconTemplate:DocumentType.IMG}),
         ].filter(d => d).map(d => d!);

        DocUtils.AssignOpts(DocCast(doc[field]), {}, iconTemplates);
    }

    /// initalizes the set of "empty<DocType>" versions of each document type with default fields.  e.g.,. emptyNote, emptyTrail
    static creatorBtnDescriptors(doc: Doc): {
        title: string, toolTip: string, icon: string,  ignoreClick?: boolean, dragFactory?: Doc, 
        backgroundColor?: string, openFactoryAsDelegate?:boolean, openFactoryLocation?:string, clickFactory?: Doc, scripts?: { onClick?: string, onDragStart?: string}, funcs?: {onDragStart?:string, hidden?: string},
    }[] {
        const json = {
            doc: {
                type: "doc",
                content: [
                    {
                        type: "paragraph", attrs: {}, content: [{
                            type: "dashField",
                            attrs: { fieldKey: "author", docId: "", hideKey: false },
                            marks: [{ type: "strong" }]
                        }, {
                            type: "dashField",
                            attrs: { fieldKey: "author_date", docId: "", hideKey: false },
                            marks: [{ type: "strong" }]
                        }]
                    }]
            },
            selection: { type: "text", anchor: 1, head: 1 },
            storedMarks: []
        };

            // "<div style={'height:100%'}>" +
            // "    <FormattedTextBox {...props} fieldKey={'header'} dontSelectOnLoad={'true'} ignoreAutoHeight={'true'} pointerEvents='{this._header_pointerEvents||`none`}' fontSize='{this._header_fontSize}px' height='{this._header_height}px' background='{this._header_color}' />" +
            // "    <FormattedTextBox {...props} fieldKey={'text'} position='absolute' top='{this._header_height}px' height='calc(100% - {this._header_height}px)'/>" +
            // "</div>";
        const metadataBtnHght = 10;
        const metaNoteTemplate = (opts:DocumentOptions) => 
            MakeTemplate(Docs.Create.RTFDocument(new RichTextField(JSON.stringify(json), ""), { ...opts, title: "MetaNote", 
                layout:`<HTMLdiv transformOrigin='top left' width='100%' height='100%'>
                            <FormattedTextBox {...props} dontScale='true' fieldKey={'text'} height='calc(100% - ${metadataBtnHght}px - {this._header_height||0}px)'  />
                            <FormattedTextBox {...props} dontScale='true' fieldKey={'header'} dontSelectOnLoad='true' ignoreAutoHeight='true' fontSize='{this._header_fontSize||9}px' height='{(this._header_height||0)}px' backgroundColor='{this._header_color || "lightGray"}' />
                            <HTMLdiv fontSize='${metadataBtnHght - 1}px' height='${metadataBtnHght}px' backgroundColor='yellow'
                                   onClick={‘(this._header_height=(this._header_height===0?50:0)) + (this._layout_autoHeightMargins=this._header_height ? this._header_height+${metadataBtnHght}:0)’} > Metadata
                                   </HTMLdiv>
                        </HTMLdiv>`
                    }, "metaNote"));
        const slideView = (opts:DocumentOptions) => 
            MakeTemplate(Docs.Create.MultirowDocument(
                    [
                        Docs.Create.MulticolumnDocument([], { title: "hero", _xMargin: 10, _height: 200,  isSystem: true }),
                        Docs.Create.TextDocument("", { title: "text", _layout_fitWidth:true,  _height: 100, isSystem: true, text_fontFamily: StrCast(Doc.UserDoc().fontFamily), text_fontSize: StrCast(Doc.UserDoc().fontSize) })
                    ], {...opts, title: "Slide View Template"}));
        const plotlyApi = () => {
            let plotly = Doc.MyPublishedDocs.find(fdoc => fdoc.title === "@plotly");
            if (!plotly) {
                plotly = Docs.Create.TextDocument(
                    `await import("https://cdn.plot.ly/plotly-2.27.0.min.js");
                    Plotly.newPlot(dashDiv.id, [ --DOCDATA-- ])`
                    , {title: "@plotly", title_custom: true, _layout_showTitle:"title",  _width:300,_height:400});
                Doc.AddToMyPublished(plotly);
            }
            return plotly;
        }
        const plotlyView = (opts:DocumentOptions) => {
            const rtfield = new RichTextField(JSON.stringify(
                {doc: {type:"doc",content:[
                    {type:"code_block",content:[
                        {type:"text",text:"^@plotly"},
                        {type:"text",text:"\n"},
                        {type:"text",text:"\n{"},
                        {type:"text",text:"\n  x: [1,2,3,5,19],"},
                        {type:"text",text:"\n  y: [1, 9, 15, 12,3],"},
                        {type:"text",text:"\n  mode: 'lines+markers', "},
                        {type:"text",text:"\n  type: 'scatter'"},
                        {type:"text",text:"\n}"}
                    ]}
                ]},
                selection:{type:"text",anchor:2,head:2}}), 
            `^@plotly
            {
                x: [1,2,3,5,19],
                y: [1, 9, 15, 12,3],
                mode: 'lines+markers', 
                type: 'scatter'
            }`);
            const slide = Docs.Create.TextDocument("", opts);
            slide.$text  = rtfield;
            slide.$layout_textPainted = `<CollectionView {...props} fieldKey={'text'}/>`;
            slide.$type_collection = CollectionViewType.Freeform;
            slide.onPaint = ScriptField.MakeScript(`toggleDetail(documentView, "textPainted")`, {documentView:"any"});
            return slide; 
        }
        const mermaidsApi = () => {
            let mermaids = Doc.MyPublishedDocs.find(fdoc => fdoc.title === "@mermaids");
            if (!mermaids) {
                mermaids = Docs.Create.TextDocument(
                `const mdef = (await import("https://cdn.jsdelivr.net/npm/mermaid@10.8.0/dist/mermaid.esm.min.mjs")).default;
                window["callb"] = (x)  => { 
                   alert(x);
                }
                mdef.initialize({
                    securityLevel : "loose",
                    startOnLoad: true,
                    flowchart: { useMaxWidth: true, htmlLabels: true, curve: 'cardinal' },
                });
                const mermaid = async (str) => (await mdef.render("graph"+Date.now(),str));
                const {svg, bindFunctions} = await mermaid(\`--DOCDATA--\`);
                dashDiv.innerHTML = svg;
                if (bindFunctions) {
                    bindFunctions(dashDiv);
                }`
                , {title: "@mermaids", title_custom: true, _layout_showTitle:"title",  _width:300,_height:400});
                Doc.AddToMyPublished(mermaids);
            }
            return mermaids;
        }
        const mermaidsView = (opts:DocumentOptions) => {
            const rtfield = new RichTextField(JSON.stringify(
                {doc: {type:"doc",content:[
                    {type:"code_block",content:[
                        {type:"text",text:`^@mermaids\n`},
                        {type:"text",text:`\n pie title Minerals in my tap water`},
                        {type:"text",text:`\n    "Calcium" : `},
                        {type:"dashField",attrs:{fieldKey:"calcium",docId:"",hideKey:true,hideValue:false,editable:true}},
                        {type:"text",text:`\n    "Potassium" : `},
                        {type:"dashField",attrs:{fieldKey:"pot",docId:"",hideKey:true,hideValue:false,editable:true}},
                        {type:"text",text:`\n    "Magnesium" : 10.01`}
                    ]}
                ]},
            selection:{type:"text",anchor:1,head:1}
        }), 
            `^@mermaids
pie title Minerals in my tap water
    "Calcium" : 42.96
    "Potassium" : 50
    "Magnesium" : 10.01`);
            const slide = Docs.Create.TextDocument("", opts);
            slide.$text  = rtfield;
            slide.$layout_textPainted = `<CollectionView {...props} fieldKey={'text'}/>`;
            slide.$_type_collection = CollectionViewType.Freeform;
            slide.onPaint = ScriptField.MakeScript(`toggleDetail(documentView, "textPainted")`, {documentView:"any"});
            return slide; 
        }
        plotlyApi(); mermaidsApi();
        const emptyThings:{key:string,  // the field name where the empty thing will be stored
                          opts:DocumentOptions,   // the document options that are required for the empty thing
                          funcs?:{[key:string]: string},  // computed fields that are rquired for the empth thing
                          scripts?:{[key:string]: string},
                          creator:(opts:DocumentOptions)=> Doc // how to create the empty thing if it doesn't exist
              }[] = [
            {key: "Note",       creator: opts => Docs.Create.TextDocument("", opts),        opts: { _width: 200, _layout_autoHeight: true }},
            {key: "Flashcard",  creator: opts => Docs.Create.FlashcardDocument("", undefined, undefined, opts),opts: { _width: 300, _height: 300}},
            {key: "Image",      creator: opts => Docs.Create.ImageDocument("", opts),       opts: { _width: 400, _height:400 }},
            {key: "Equation",   creator: opts => Docs.Create.EquationDocument("",opts),     opts: { _width: 50,  _height: 50, nativeWidth: 40, nativeHeight: 40, _xMargin: 10, _yMargin: 10}},
            {key: "Noteboard",  creator: opts => Docs.Create.NoteTakingDocument([], opts),  opts: { _width: 250, _height: 200, _layout_fitWidth: true}},
            {key: "Collection", creator: opts => Docs.Create.FreeformDocument([], opts),    opts: { _width: 150, _height: 100, _layout_fitWidth: true }},
            {key: "Webpage",    creator: opts => Docs.Create.WebDocument("",opts),          opts: { _width: 400, _height: 512, _nativeWidth: 850, data_useCors: true, }},
            {key: "Comparison", creator: opts => Docs.Create.ComparisonDocument("", opts),  opts: { _width: 300, _height: 300 }},
            {key: "Diagram",    creator: opts => Docs.Create.DiagramDocument("", opts),     opts: { _width: 300, _height: 300, _type_collection: CollectionViewType.Freeform, layout_diagramEditor: CollectionView.LayoutString("data") }, scripts: { onPaint: `toggleDetail(documentView, "diagramEditor","")`}},
            {key: "Audio",      creator: opts => Docs.Create.AudioDocument(nullAudio, opts),opts: { _width: 200, _height: 100, }},
            {key: "Audio",      creator: opts => Docs.Create.AudioDocument(nullAudio, opts),opts: { _width: 200, _height: 100, _layout_fitWidth: true, }},
            {key: "Map",        creator: opts => Docs.Create.MapDocument([], opts),         opts: { _width: 800, _height: 600, _layout_fitWidth: true, }},
            {key: "Screengrab", creator: Docs.Create.ScreenshotDocument,                    opts: { _width: 400, _height: 200 }},
            {key: "WebCam",     creator: opts => Docs.Create.WebCamDocument("", opts),      opts: { _width: 400, _height: 200, recording:true, isSystem: true, cloneFieldFilter: new List<string>(["isSystem"]) }},
            {key: "Button",     creator: Docs.Create.ButtonDocument,                        opts: { _width: 150, _height: 50, _xPadding: 10, _yPadding: 10, title_custom: true,  waitForDoubleClickToClick: 'never'}, scripts: {onClick: FollowLinkScript()?.script.originalScript ?? ""}},
            {key: "Script",     creator: opts => Docs.Create.ScriptingDocument(null, opts), opts: { _width: 200, _height: 250, }},
            {key: "DataViz",    creator: opts => Docs.Create.DataVizDocument("", opts),     opts: { _width: 300, _height: 300, }},
            // AARAV ADD //
            {key: "DailyJournal",creator:opts => Docs.Create.DailyJournalDocument("", opts),opts: { _width: 300, _height: 300}},
            {key: "Chat",       creator: Docs.Create.ChatDocument,                          opts: { _width: 500, _height: 500, _layout_fitWidth: true, }},
            {key: "MetaNote",   creator: metaNoteTemplate,                                  opts: { _width: 300, _height: 120, _header_pointerEvents: "all", _header_height: 50, _header_fontSize: 9,_layout_autoHeightMargins: 50, _layout_autoHeight: true, treeView_HideUnrendered: true}},
            {key: "ViewSlide",  creator: slideView,                                         opts: { _width: 400, _height: 300, _xMargin: 3, _yMargin: 3,}},
            {key: "Trail",      creator: Docs.Create.PresDocument,                          opts: { _width: 400, _height: 30, _type_collection: CollectionViewType.Stacking, _layout_dontCenter:'xy', dropAction: dropActionType.embed, treeView_HideTitle: true, _layout_fitWidth:true, layout_boxShadow: "0 0" }},
            {key: "Tab",        creator: opts => Docs.Create.FreeformDocument([], opts),    opts: { _width: 500, _height: 800, _layout_fitWidth: true, _freeform_backgroundGrid: true, }},
            {key: "Slide",      creator: opts => Docs.Create.TreeDocument([], opts),        opts: { _width: 300, _height: 200, _type_collection: CollectionViewType.Tree, 
                                                                                                treeView_HasOverlay: true, text_fontSize: "20px", _layout_autoHeight: true, 
                                                                                                dropAction:dropActionType.move, treeView_Type: TreeViewType.outline, 
                                                                                                backgroundColor: "white", _xMargin: 0, _yMargin: 0, _createDocOnCR: true 
                                                                                            }, funcs: {title: 'this.text?.Text'}},
            {key: "Mermaids",   creator: mermaidsView,                                      opts: { _width: 300, _height: 300, }},
            {key: "Plotly",     creator: plotlyView,                                        opts: { _width: 300, _height: 300, }},
                                                                                        ];

        const standardOps = (key:string) => ({ title : "Untitled "+ key, _layout_fitWidth: false, isSystem: true, "dragFactory_count": 0, cloneFieldFilter: new List<string>(["isSystem"]) });
        emptyThings.forEach(
            thing => DocUtils.AssignDocField(doc, "empty"+thing.key, (opts) => thing.creator(opts), {...standardOps(thing.key), ...thing.opts}, undefined, thing.scripts, thing.funcs));
        DocCast(Doc.UserDoc().emptyMetaNote).title = "MetaNote"; // hack: metanotes are used a template, so 'untitled metaNote' is an awkward name 

        return [
            { toolTip: "Tap or drag to create a note",            title: "Note",        icon: "sticky-note",     dragFactory: doc.emptyNote as Doc,       clickFactory: DocCast(doc.emptyNote)},
            { toolTip: "Tap or drag to create a flashcard",       title: "Flashcard",   icon: "id-card",         dragFactory: doc.emptyFlashcard as Doc,  clickFactory: DocCast(doc.emptyFlashcard)},
            { toolTip: "Tap or drag to create an equation",       title: "Math",        icon: "calculator",      dragFactory: doc.emptyEquation as Doc,   clickFactory: DocCast(doc.emptyEquation)},
            { toolTip: "Tap or drag to create a mermaid node",    title: "Mermaids",    icon: "rocket",          dragFactory: doc.emptyMermaids as Doc,   clickFactory: DocCast(doc.emptyMermaids)}, 
            { toolTip: "Tap or drag to create a plotly node",     title: "Plotly",      icon: "rocket",          dragFactory: doc.emptyPlotly as Doc,     clickFactory: DocCast(doc.emptyMermaids)}, 
            { toolTip: "Tap or drag to create a note board",      title: "Notes",       icon: "book",            dragFactory: doc.emptyNoteboard as Doc,  clickFactory: DocCast(doc.emptyNoteboard)},
            { toolTip: "Tap or drag to create an image",          title: "Image",       icon: "image",           dragFactory: doc.emptyImage as Doc,      clickFactory: DocCast(doc.emptyImage)},
            { toolTip: "Tap or drag to create a collection",      title: "Col",         icon: "folder",          dragFactory: doc.emptyCollection as Doc, clickFactory: DocCast(doc.emptyTab)},
            { toolTip: "Tap or drag to create a webpage",         title: "Web",         icon: "globe-asia",      dragFactory: doc.emptyWebpage as Doc,    clickFactory: DocCast(doc.emptyWebpage)},
            { toolTip: "Tap or drag to create a comparison box",  title: "Compare",     icon: "columns",         dragFactory: doc.emptyComparison as Doc, clickFactory: DocCast(doc.emptyComparison)},
            { toolTip: "Tap or drag to create a diagram",         title: "Diagram",     icon: "tree",            dragFactory: doc.emptyDiagram as Doc,    clickFactory: DocCast(doc.emptyDiagram)},
            { toolTip: "Tap or drag to create an audio recorder", title: "Audio",       icon: "microphone",      dragFactory: doc.emptyAudio as Doc,      clickFactory: DocCast(doc.emptyAudio),      openFactoryLocation: OpenWhere.overlay},
            { toolTip: "Tap or drag to create a map",             title: "Map",         icon: "map-marker-alt",  dragFactory: doc.emptyMap as Doc,        clickFactory: DocCast(doc.emptyMap)},
            { toolTip: "Tap or drag to create a chat assistant",  title: "Chat Assist", icon: "book",            dragFactory: doc.emptyChat as Doc,       clickFactory: DocCast(doc.emptyChat)},
            { toolTip: "Tap or drag to create a screen grabber",  title: "Grab",        icon: "photo-video",     dragFactory: doc.emptyScreengrab as Doc, clickFactory: DocCast(doc.emptyScreengrab), openFactoryLocation: OpenWhere.overlay, funcs: { hidden: "IsNoviceMode()"}},
            { toolTip: "Tap or drag to create a WebCam recorder", title: "WebCam",      icon: "photo-video",     dragFactory: doc.emptyWebCam as Doc,     clickFactory: DocCast(doc.emptyWebCam),     openFactoryLocation: OpenWhere.overlay, funcs: { hidden: "IsNoviceMode()"}},
            { toolTip: "Tap or drag to create a button",          title: "Button",      icon: "circle",          dragFactory: doc.emptyButton as Doc,     clickFactory: DocCast(doc.emptyButton)},
            { toolTip: "Tap or drag to create a scripting box",   title: "Script",      icon: "terminal",        dragFactory: doc.emptyScript as Doc,     clickFactory: DocCast(doc.emptyScript),                                             funcs: { hidden: "IsNoviceMode()"}},
            { toolTip: "Tap or drag to create a data viz node",   title: "DataViz",     icon: "chart-bar",       dragFactory: doc.emptyDataViz as Doc,    clickFactory: DocCast(doc.emptyDataViz)},
            { toolTip: "Tap or drag to create a journal entry",   title: "Journal",     icon: "book",            dragFactory:doc.emptyDailyJournal as Doc,clickFactory: DocCast(doc.emptyDataJournal), },
            { toolTip: "Tap or drag to create a bullet slide",    title: "PPT Slide",   icon:"person-chalkboard",dragFactory: doc.emptySlide as Doc,      clickFactory: DocCast(doc.emptySlide),     openFactoryLocation: OpenWhere.overlay, funcs: { hidden: "IsNoviceMode()"}},
            { toolTip: "Tap or drag to create a view slide",      title: "View Slide",  icon: "address-card",    dragFactory: doc.emptyViewSlide as Doc,  clickFactory: DocCast(doc.emptyViewSlide), openFactoryLocation: OpenWhere.overlay, funcs: { hidden: "IsNoviceMode()"}},
            { toolTip: "Tap or drag to create a data note",       title: "MetaNote",    icon: "window-maximize", dragFactory: doc.emptyMetaNote as Doc,   clickFactory: DocCast(doc.emptyMetaNote),  openFactoryAsDelegate: true,            funcs: { hidden: "IsNoviceMode()"} },
            { toolTip: "Toggle a Calculator REPL",                title: "replviewer",  icon: "calculator",                                               clickFactory: '<ScriptingRepl />' as unknown as Doc, openFactoryLocation: OpenWhere.overlay}, // hack: clickFactory is not a Doc but will get interpreted as a custom UI by the openDoc() onClick script
          ].map(tuple => (
              { openFactoryLocation: OpenWhere.addRight, 
                scripts: { onClick:     'openDoc(copyDragFactory(this.clickFactory,this.openFactoryAsDelegate), this.openFactoryLocation)', 
                           onDragStart: '{ return copyDragFactory(this.dragFactory,this.openFactoryAsDelegate); }'}, 
                funcs: tuple.funcs,
                ...tuple, }));
    }

    /// Initalizes the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools
    static setupCreatorButtons(doc: Doc, dragCreatorDoc?:Doc):Doc {
        const creatorBtns = CurrentUserUtils.creatorBtnDescriptors(doc).map((reqdOpts) => {
            const btn = dragCreatorDoc ? DocListCast(dragCreatorDoc.data).find(fdoc => fdoc.title === reqdOpts.title): undefined;
            const opts:DocumentOptions = {...OmitKeys(reqdOpts, ["funcs", "scripts", "backgroundColor"]).omit, 
                _width: 60, _height: 60, _dragOnlyWithinContainer: true, 
                btnType: ButtonType.ToolButton, backgroundColor: reqdOpts.backgroundColor ?? Colors.DARK_GRAY, color: Colors.WHITE, isSystem: true,
                };
            return DocUtils.AssignScripts(DocUtils.AssignOpts(btn, opts) ?? Docs.Create.FontIconDocument(opts), reqdOpts.scripts, reqdOpts.funcs);
        });

        const reqdOpts:DocumentOptions = {
            title: "Document Creators", _layout_showTitle: "title", _xMargin: 0, _dragOnlyWithinContainer: true, layout_hideContextMenu: true, _chromeHidden: true, isSystem: true,
            _layout_autoHeight: true, _width: 500, _height: 300, _layout_fitWidth: true, _layout_columnWidth: 40, ignoreClick: true, _lockedPosition: true, _forceActive: true,
             childDragAction: dropActionType.embed
        };
        const reqdScripts = { dropConverter: "convertToButtons(dragData)" };
        return DocUtils.AssignScripts(DocUtils.AssignOpts(dragCreatorDoc, reqdOpts, creatorBtns) ?? Docs.Create.MasonryDocument(creatorBtns, reqdOpts), reqdScripts);
    }

    /// returns descriptions needed to buttons for the left sidebar to open up panes displaying different collections of documents
    static leftSidebarMenuBtnDescriptions(doc: Doc):{title:string, target:Doc, icon:string, toolTip: string, scripts:{[key:string]:undefined|string}, funcs?:{[key:string]:undefined|string}, hidden?: boolean}[] {
      const badgeValue = "((len) => len && len !== '0' ? len: undefined)(docList(this.target?.data).filter(doc => !docList(this.target.viewed).includes(doc)).length.toString())"; 
      const getActiveDashTrails = "Doc.ActiveDashboard?.myTrails";
        return [
            { title: "Dashboards",      toolTip: "Dashboards",      target: this.setupDashboards(doc, "myDashboards"),         icon: "desktop",     funcs: {hidden: "IsNoviceMode()"} },
            { title: "Search",          toolTip: "Search ⌘F",       target: this.setupSearcher(doc, "mySearcher"),             icon: "search",      },
            { title: "Files",           toolTip: "Files",           target: this.setupFilesystem(doc, "myFilesystem"),         icon: "folder-open", },
            { title: "Tools",           toolTip: "Tools",           target: this.setupToolsBtnPanel(doc, "myTools"),           icon: "wrench",      },
            { title: "Imports",         toolTip: "Imports ⌘I",      target: this.setupImportSidebar(doc, "myImports"),         icon: "upload",      },
            { title: "Closed",          toolTip: "Recently Closed", target: this.setupRecentlyClosed(doc, "myRecentlyClosed"), icon: "archive",     hidden: true }, // this doc is hidden from the Sidebar, but it's still being used in MyFilesystem which ignores the hidden field
            { title: "Shared",          toolTip: "Shared Docs",     target: Doc.MySharedDocs,                                  icon: "users",       funcs: {badgeValue: badgeValue}},
            { title: "Trails",          toolTip: "Trails ⌘R",       target: Doc.UserDoc(),                                     icon: "pres-trail",  funcs: {target: getActiveDashTrails}},
            { title: "Image Grouper",   toolTip: "Image Grouper",   target: this.setupImageGrouper(doc, "myImageGrouper"),     icon: "folder-open", hidden: false },
            { title: "Faces",           toolTip: "Unique Faces",    target: this.setupFaceCollection(doc, "myFaceCollection"), icon: "face-smile",  hidden: false },
            { title: "User Doc",        toolTip: "User Doc",        target: this.setupUserDocView(doc, "myUserDocView"),       icon: "address-card",funcs: {hidden: "IsNoviceMode()"} },
            ].map(tuple => ({...tuple, scripts:{onClick: 'selectMainMenu(this)'}}));
    }

    /// the empty panel that is filled with whichever left menu button's panel has been selected
    static setupLeftSidebarPanel(doc: Doc, field="myLeftSidebarPanel") {
        const panel = DocCast(doc[field]);
        if (panel) panel.proto = undefined;
        DocUtils.AssignDocField(doc, field, (opts) => Doc.assign(new Doc(), opts as {[key:string]: FieldType}), {title:"leftSidebarPanel", isSystem:true, undoIgnoreFields: new List<string>(['proto'])});
    }

    /// Initializes the left sidebar menu buttons and the panels they open up
    static setupLeftSidebarMenu(doc: Doc, field="myLeftSidebarMenu") {
        this.setupLeftSidebarPanel(doc);
        const myLeftSidebarMenu = DocCast(doc[field]);
        const menuBtns = CurrentUserUtils.leftSidebarMenuBtnDescriptions(doc).map(({ title, target, icon, toolTip, hidden, scripts, funcs }) => {
            const btnDoc = myLeftSidebarMenu ? DocListCast(myLeftSidebarMenu.data).find(fdoc => fdoc.title === title) : undefined;
            const reqdBtnOpts:DocumentOptions = {
                title, icon, target, toolTip, hidden, btnType: ButtonType.MenuButton, isSystem: true, undoIgnoreFields: new List<string>(['height', 'data_columnHeaders']), dontRegisterView: true,
                _width: 60, _height: 60,  _dragOnlyWithinContainer: true,
            };
            return DocUtils.AssignScripts(DocUtils.AssignOpts(btnDoc, reqdBtnOpts) ?? Docs.Create.FontIconDocument(reqdBtnOpts), scripts, funcs);
        });

        const reqdStackOpts:DocumentOptions ={
            title: "menuItemPanel", childDragAction: dropActionType.same, layout_boxShadow: "rgba(0,0,0,0)",  dontRegisterView: true, ignoreClick: true,
            _layout_dontCenter: 'y',
            _chromeHidden: true, _gridGap: 0, _yMargin: 0, _xMargin: 0, _layout_autoHeight: false, _width: 60, _layout_columnWidth: 60, _lockedPosition: true, isSystem: true,
        };
        return DocUtils.AssignDocField(doc, field, (opts, items) => Docs.Create.StackingDocument(items??[], opts), reqdStackOpts, menuBtns, { dropConverter: "convertToButtons(dragData)" });
    }

    /// Search option on the left side button panel
    static setupSearcher(doc: Doc, field:string) {
        return DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.SearchDocument(opts), {
                dontRegisterView: true, backgroundColor: "dimgray", ignoreClick: true, title: "Search Panel", isSystem: true, childDragAction: dropActionType.embed, 
                _lockedPosition: true, _type_collection: CollectionViewType.Schema  });
    }

    static setupImageGrouper(doc: Doc, field: string) {
        return DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.ImageGrouperDocument(opts), {
            dontRegisterView: true, backgroundColor: "dimgray", ignoreClick: true, title: "Image Grouper", isSystem: true, childDragAction: dropActionType.embed, 
            _lockedPosition: true, _type_collection: CollectionViewType.Schema  });
    }

    static setupFaceCollection(doc: Doc, field: string) {
        return DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.FaceCollectionDocument(opts), {
            dontRegisterView: true, ignoreClick: true, title: "Face Collection", isSystem: true, childDragAction: dropActionType.embed, 
            _lockedPosition: true, _type_collection: CollectionViewType.Schema  });
    }

    /// Initializes the panel of draggable tools that is opened from the left sidebar.
    static setupToolsBtnPanel(doc: Doc, field:string) {
        const allTools = DocListCast(DocCast(doc[field])?.data);
        const creatorBtns = CurrentUserUtils.setupCreatorButtons(doc, allTools?.length ? allTools[0]:undefined);
        const userTools = allTools && allTools?.length > 1 ? allTools[1]:undefined;
        const userBtns = CurrentUserUtils.setupUserDocumentCreatorButtons(doc, userTools);
        // doc.myUserBtns = new PrefetchProxy(userBtns);
        const reqdToolOps:DocumentOptions = {
            title: "My Tools", isSystem: true, ignoreClick: true, layout_boxShadow: "0 0",
            layout_explainer: "This is a palette of documents that can be created.", _layout_dontCenter: "y",
            _layout_showTitle: "title", _width: 500, _yMargin: 20, _lockedPosition: true, _forceActive: true, _dragOnlyWithinContainer: true, layout_hideContextMenu: true, _chromeHidden: true, 
        };
        return DocUtils.AssignDocField(doc, field, (opts, items) => Docs.Create.StackingDocument(items??[], opts), reqdToolOps, [creatorBtns, userBtns]);
    }

    /// initializes the left sidebar dashboard pane
    static setupDashboards(doc: Doc, field:string) {
        let myDashboards = DocCast(doc[field]);

        const newDashboard = `createNewDashboard()`;

        const reqdBtnOpts:DocumentOptions = { _forceActive: true,  _width: 30, _height: 30, _dragOnlyWithinContainer: true,
             title: "new Dash", btnType: ButtonType.ClickButton, toolTip: "Create new dashboard", buttonText: "New trail", icon: "plus", isSystem: true };
        const reqdBtnScript = {onClick: newDashboard,}
        const newDashboardButton = DocUtils.AssignScripts(DocUtils.AssignOpts(DocCast(myDashboards?.layout_headerButton), reqdBtnOpts) ?? Docs.Create.FontIconDocument(reqdBtnOpts), reqdBtnScript);
       
        const contextMenuScripts = [/* newDashboard */] as string[];
        const contextMenuLabels = [/* "Create New Dashboard" */]  as string[];
        const contextMenuIcons = [/* "plus" */]  as string[];
        const childContextMenuScripts = [`toggleComicMode()`, `snapshotDashboard()`, `shareDashboard(this)`, 'removeDashboard(this)', 'resetDashboard(this)']; // entries must be kept in synch with childContextMenuLabels, childContextMenuIcons, and childContextMenuFilters
        const childContextMenuFilters =  ['!IsNoviceMode()', '!IsNoviceMode()', undefined, undefined, '!IsNoviceMode()'];// entries must be kept in synch with childContextMenuLabels, childContextMenuIcons, and childContextMenuScripts
        const childContextMenuLabels =  ["Toggle Comic Mode", "Snapshot Dashboard", "Share Dashboard", "Remove Dashboard", "Reset Dashboard"];// entries must be kept in synch with childContextMenuScripts, childContextMenuIcons, and childContextMenuFilters
        const childContextMenuIcons = ["tv", "camera", "users", "times", "trash"]; // entries must be kept in synch with childContextMenuScripts, childContextMenuLabels, and childContextMenuFilters
        const reqdOpts:DocumentOptions = {
            title: "My Dashboards", childHideLinkButton: true, treeView_FreezeChildren: "remove|add", treeView_HideTitle: true, layout_boxShadow: "0 0", childDontRegisterViews: true,
            dropAction: dropActionType.inPlace, treeView_Type: TreeViewType.fileSystem, isFolder: true, isSystem: true,  treeView_TruncateTitleWidth: 350, ignoreClick: true, 
            layout_headerButton: newDashboardButton, childDragAction: dropActionType.inPlace,
            _layout_showTitle: "title", _height: 400, _gridGap: 5, _forceActive: true, _lockedPosition: true,
            contextMenuLabels:new List<string>(contextMenuLabels),
            contextMenuIcons:new List<string>(contextMenuIcons),
            childContextMenuLabels:new List<string>(childContextMenuLabels),
            childContextMenuIcons:new List<string>(childContextMenuIcons),
            layout_explainer: "This is your collection of dashboards. A dashboard represents the tab configuration of your workspace. To manage documents as folders, go to the Files."
        };
        myDashboards = DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.TreeDocument([], opts), reqdOpts);
        if (Cast(myDashboards.contextMenuScripts, listSpec(ScriptField), null)?.length !== contextMenuScripts.length) {
            myDashboards.contextMenuScripts = new List<ScriptField>(contextMenuScripts.map(script => ScriptField.MakeFunction(script)!));
        } 
        if (Cast(myDashboards.childContextMenuScripts, listSpec(ScriptField), null)?.length !== childContextMenuScripts.length) {
            myDashboards.childContextMenuScripts = new List<ScriptField>(childContextMenuScripts.map(script => ScriptField.MakeFunction(script)!));
        } 
        if (Cast(myDashboards.childContextMenuFilters, listSpec(ScriptField), null)?.length !== childContextMenuFilters.length) {
            myDashboards.childContextMenuFilters = new List<ScriptField>(childContextMenuFilters.map(script => !script ? script as unknown as ScriptField: ScriptField.MakeFunction(script)!));
        }
        return myDashboards;
    }

    /// initializes the left sidebar File system pane
    static setupFilesystem(doc: Doc, field:string) {
        const myFilesystem = DocCast(doc[field]);
        
        const newFolderOpts: DocumentOptions = {
            _forceActive: true, _dragOnlyWithinContainer: true, embedContainer: Doc.MyFilesystem, _width: 30, _height: 30, undoIgnoreFields:new List<string>(['treeView_SortCriterion']),
            title: "New folder", color: Colors.BLACK, btnType: ButtonType.ClickButton, toolTip: "Create new folder", buttonText: "New folder", icon: "folder-plus", isSystem: true
        };
        const newFolderScript = { onClick: CollectionTreeView.AddTreeFunc};
        const newFolderButton = DocUtils.AssignScripts(DocUtils.AssignOpts(DocCast(myFilesystem?.layout_headerButton), newFolderOpts) ?? Docs.Create.FontIconDocument(newFolderOpts), newFolderScript);
        
        const reqdOpts:DocumentOptions = { _layout_showTitle: "title", _height: 100, _forceActive: true, 
            title: "My Documents", layout_headerButton: newFolderButton, treeView_HideTitle: true, dropAction: dropActionType.add, isSystem: true,
            isFolder: true, treeView_Type: TreeViewType.fileSystem, childHideLinkButton: true, layout_boxShadow: "0 0", childDontRegisterViews: true, 
            treeView_TruncateTitleWidth: 350, ignoreClick: true, childDragAction: dropActionType.embed,
            layout_explainer: "This is your file manager where you can create folders to keep track of documents independently of your dashboard."
        };
        const fileFolders = new Set(DocListCast(DocCast(doc[field])?.data));
        return  DocUtils.AssignDocField(doc, field, (opts, items) => Docs.Create.TreeDocument(items??[], opts), reqdOpts, Array.from(fileFolders));
    }

    /// initializes the panel displaying docs that have been recently closed
    static setupRecentlyClosed(doc: Doc, field:string) {
        const reqdOpts:DocumentOptions = { _layout_showTitle: "title", _lockedPosition: true, _gridGap: 5, _forceActive: true, isFolder: true,
            title: "My Recently Closed", childHideLinkButton: true, treeView_HideTitle: true, childDragAction: dropActionType.move, isSystem: true,
            treeView_TruncateTitleWidth: 350, ignoreClick: true,  layout_boxShadow: "0 0", childDontRegisterViews: true, dropAction: dropActionType.same,
            contextMenuLabels: new List<string>(["Empty recently closed"]),
            contextMenuIcons:new List<string>(["trash"]),
            layout_explainer: "Recently closed documents appear in this menu. They will only be deleted if you explicity empty this list."
        };
        const recentlyClosed = DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.TreeDocument([], opts), reqdOpts);

        const clearAll = (target:string) => `getProto(${target}).data = new List([])`;
        const clearBtnsOpts:DocumentOptions = { _width: 30, _height: 30, _forceActive: true, _dragOnlyWithinContainer: true, layout_hideContextMenu: true, 
            title: "Empty", target: recentlyClosed, btnType: ButtonType.ClickButton, color: Colors.BLACK, buttonText: "Empty", icon: "trash", isSystem: true,
            toolTip: "Empty recently closed",};
        DocUtils.AssignDocField(recentlyClosed, "layout_headerButton", (opts) => Docs.Create.FontIconDocument(opts), clearBtnsOpts, undefined, {onClick: clearAll("this.target")});

        if (!Cast(recentlyClosed.contextMenuScripts, listSpec(ScriptField),null)?.find((script) => script?.script.originalScript === clearAll("this"))) {
            recentlyClosed.contextMenuScripts = new List<ScriptField>([ScriptField.MakeScript(clearAll("this"))!])
        }
        return recentlyClosed;
    }

    /// initializes the left sidebar panel view of the UserDoc
    static setupUserDocView(doc: Doc, field:string) {
        const reqdOpts:DocumentOptions = {
            _lockedPosition: true, _gridGap: 5, _forceActive: true, title: ClientUtils.CurrentUserEmail() +"-view",
            layout_boxShadow: "0 0", childDontRegisterViews: true, dropAction: dropActionType.same, ignoreClick: true, isSystem: true,
            treeView_HideTitle: true, treeView_TruncateTitleWidth: 350
        };
        if (!doc[field]) DocUtils.AssignOpts(doc, {treeView_Open: true, treeView_ExpandedView: "fields" });
        return DocUtils.AssignDocField(doc, field, (opts, items) => Docs.Create.TreeDocument(items??[], opts), reqdOpts, [doc]);
    }

    static linearButtonList = (opts: DocumentOptions, docs: Doc[]) => Docs.Create.LinearDocument(docs, {
        ...opts, _gridGap: 0, _xMargin: 5, _yMargin: 5, layout_boxShadow: "0 0", _forceActive: true,
        dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }),
        _lockedPosition: true, isSystem: true, flexDirection: "row"
    })
    static multiToggleList = (opts: DocumentOptions, docs: Doc[]) => Docs.Create.FontIconDocument({
        ...opts, data: new List<Doc>(docs), _gridGap: 0, _xMargin: 5, _yMargin: 5, layout_boxShadow: "0 0", _forceActive: true,
        dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }),
        _lockedPosition: true, isSystem: true, flexDirection: "row"
    })

    static createToolButton = (opts: DocumentOptions) => Docs.Create.FontIconDocument({
        btnType: ButtonType.ToolButton, _dropPropertiesToRemove: new List<string>([ "layout_hideContextMenu"]), 
        /* _nativeWidth: 40, _nativeHeight: 40, */ _width: 40, _height: 40, isSystem: true, ...opts,
    })

    /// initializes the required buttons in the expanding button menu at the bottom of the Dash window
    static setupDockedButtons(doc: Doc, field="myDockedBtns") {
        const dockedBtns = DocCast(doc[field]);
        const dockBtn = (opts: DocumentOptions, scripts: {[key:string]:string|undefined}, funcs?: {[key:string]:string}) =>
            DocUtils.AssignScripts(DocUtils.AssignOpts(DocListCast(dockedBtns?.data)?.find(fdoc => fdoc.title === opts.title), opts) ?? 
                            CurrentUserUtils.createToolButton(opts), scripts, funcs);
        
        const btnDescs = [// setup reactions to change the highlights on the undo/redo buttons -- would be better to encode this in the undo/redo buttons, but the undo/redo stacks are not wired up that way yet
            { scripts: { onClick: "undo()"},  opts: { title: "Undo",              icon: "undo-alt",               toolTip: "Undo ⌘Z" }},
            { scripts: { onClick: "redo()"},  opts: { title: "Redo",              icon: "redo-alt",               toolTip: "Redo ⌘⇧Z" }},
            { scripts: { },                   opts: { title: "undoStack",         layout: "<UndoStack>",          toolTip: "Undo/Redo Stack"}}, // note: layout fields are hacks -- they don't actually run through the JSX parser (yet)
            { scripts: { },                   opts: { title: "linker",            layout: "<LinkingUI>",          toolTip: "link started"}},
            { scripts: { },                   opts: { title: "currently playing", layout: "<CurrentlyPlayingUI>", toolTip: "currently playing media"}},
            { scripts: { onClick: "hideUI()"},opts: { title: "Toggle UI",         icon: "portrait",               toolTip: "Toggle visibility of UI buttons"}},
            { scripts: { },                   opts: { title: "Branching",         layout: "<Branching>",          toolTip: "Branch, baby!"}}
        ];
        const btns = btnDescs.map(desc => dockBtn({_width: 30, _height: 30, defaultDoubleClick: 'ignore', undoIgnoreFields: new List<string>(['opacity']), _dragOnlyWithinContainer: true, ...desc.opts}, desc.scripts));
        const dockBtnsReqdOpts:DocumentOptions = {
            title: "docked buttons", _height: 40, flexGap: 0, layout_boxShadow: "standard", childDragAction: dropActionType.move,
            childDontRegisterViews: true, linearView_IsOpen: true, linearView_Expandable: true, ignoreClick: true
        };
        reaction(() => UndoManager.redoStack.slice(), () => { Doc.GetProto(btns.find(btn => btn.title === "Redo")!).opacity = UndoManager.CanRedo() ? 1 : 0.4; }, { fireImmediately: true });
        reaction(() => UndoManager.undoStack.slice(), () => { Doc.GetProto(btns.find(btn => btn.title === "Undo")!).opacity = UndoManager.CanUndo() ? 1 : 0.4; }, { fireImmediately: true });
        return DocUtils.AssignDocField(doc, field, (opts, items) => this.linearButtonList(opts, items??[]), dockBtnsReqdOpts, btns);
    }

    static freeTools(): Button[] {
        return [
            { title: "Bottom",  icon: "arrows-down-to-line",toolTip: "Make doc topmost",     btnType: ButtonType.ClickButton,  expertMode: false, funcs: {}, scripts: { onClick: 'sendToBack()'}}, // Only when floating document is selected in freeform
            { title: "Top",     icon: "arrows-up-to-line",  toolTip: "Make doc bottommost",  btnType: ButtonType.ClickButton,  expertMode: false, funcs: {}, scripts: { onClick: 'bringToFront()'}}, // Only when floating document is selected in freeform
            { title: "Z order", icon: "z",                  toolTip: "Keep Z order on Drag", btnType: ButtonType.ToggleButton, expertMode: false, funcs: {}, scripts: { onClick: '{ return toggleRaiseOnDrag(_readOnly_);}'}}, // Only when floating document is selected in freeform
        ]
    }
    static stackTools(): Button[] {
        return [
            { title: "V. Align",  icon: "pallet",        toolTip: "Center Align Stack",  btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"vcenter",    funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform
            { title: "Center",    icon: "align-center",  toolTip: "Center Align Stack",  btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"hcenter",    funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform
        ]
    }
    static sortTools(): Button[] {
        return [
            { title: "Time",      icon:"hourglass-half", toolTip:"Sort by most recent document creation",          btnType: ButtonType.ToggleButton, expertMode: false, toolType:"time",       funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}},
            { title: "Type",      icon:"eye",            toolTip:"Sort by document type",                          btnType: ButtonType.ToggleButton, expertMode: false, toolType:"docType",    funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}},
            { title: "Color",     icon:"palette",        toolTip:"Sort by document color",                         btnType: ButtonType.ToggleButton, expertMode: false, toolType:"color",      funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}},
            { title: "Tags",      icon:"bolt",           toolTip:"Sort by document's tags",                        btnType: ButtonType.ToggleButton, expertMode: false, toolType:"tag",        funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}},
            { title: "Reverse",   icon: "sort-up",       toolTip: "Sort the cards in reverse order",               btnType: ButtonType.ToggleButton, expertMode: false, toolType:"reverse",    funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} },
         ]
    }

    static filterBtnDesc<T extends string>(tag:TagName<T>|"Tag", icon:IconProp):Button {
        return { title: tag, isSystem: false, icon: icon.toString(),  toolTip:`Click to toggle visibility of ${tag} tagged Docs`,  btnType: ButtonType.ToggleButton,  expertMode: false, toolType:`#${tag.toLowerCase()}`, funcs: {}, scripts: { onClick: '{ return setTagFilter(this.toolType, _added_, _readOnly_);}'}}
    }
  
    static filterTools(): Button[] {
        // If there's no active dashboard, then a default set of tags are added, otherwise, the user controls which tags are kept
        const tagButtonDescs = Doc.UserDoc().activeDashboard ? [] : [
            this.filterBtnDesc("Star", "star"),
            this.filterBtnDesc("Like", "heart"),
            this.filterBtnDesc("Todo", "bolt"),
            this.filterBtnDesc("Idea", "cloud"),
            this.filterBtnDesc("Chat", "robot")
        ];
        return [
            { title:"Options",isSystem: true,icon: "gear",  toolTip:"Click to customize list of filter buttons", btnType: ButtonType.ClickButton, expertMode: false, toolType:"-opts-",funcs: {}, scripts: { onClick: '{ return setTagFilter(this.toolType, false,_readOnly_);}'}},
            ...tagButtonDescs
        ]
    } 
    static viewTools(): Button[] {
        return [
            { title: "Tags",     icon: "id-card",      toolTip: "Toggle Tags display", btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"toggle-tags",funcs: { },                                                                              scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} },
            { title: "Snap",     icon: "th",           toolTip: "Show Snap Lines",     btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"snaplines",  funcs: { hidden: `!SelectedDocType("${CollectionViewType.Freeform}", this.expertMode)`}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform
            { title: "Grid",     icon: "border-all",   toolTip: "Show Grid",           btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"grid",       funcs: { hidden: `!SelectedDocType("${CollectionViewType.Freeform}", this.expertMode)`}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform
            { title: "Fit All",  icon: "object-group", toolTip:"Fit Docs to View (double tap to persist)",
                                                                                       btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"viewAll",    funcs: { hidden: `!SelectedDocType("${CollectionViewType.Freeform}", this.expertMode)`}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}', onDoubleClick: '{ return showFreeform(this.toolType, _readOnly_, true);}'}}, // Only when floating document is selected in freeform
            { title: "Clusters", icon: "braille",      toolTip: "Show Doc Clusters",   btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"clusters",   funcs: { hidden: `!SelectedDocType("${CollectionViewType.Freeform}", this.expertMode)`}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform
        ]
    }
    static textTools():Button[] {
        return [
            { title: "Font",     toolTip: "Font", width: 100,     btnType: ButtonType.DropdownList,                      toolType:"font",     ignoreClick: true,   scripts: {script:  '{ return setFontAttr(this.toolType, value, _readOnly_);}'},
              btnList: new List<string>(["Roboto", "Roboto Mono", "Nunito", "Times New Roman", "Arial", "Georgia", "Comic Sans MS", "Tahoma", "Impact", "Crimson Text", "Math"]) },
            { title: " Size",    toolTip: "Font size (%size)",    btnType: ButtonType.NumberDropdownButton,              toolType:"fontSize", ignoreClick: true,   scripts: {script:  '{ return setFontAttr(this.toolType, value, _readOnly_);}'}, numBtnMax: 200, numBtnMin: 9 },
            { title: "Color",    toolTip: "Font color (%color)",  btnType: ButtonType.ColorButton,  icon: "font",        toolType:"fontColor",ignoreClick: true,   scripts: {script:  '{ return setFontAttr(this.toolType, value, _readOnly_);}'} },
            { title: "Highlight",toolTip: "Font highlight",       btnType: ButtonType.ColorButton,  icon: "highlighter", toolType:"highlight",ignoreClick: true,   scripts: {script:  '{ return setFontAttr(this.toolType, value, _readOnly_);}'} },
            { title: "Bold",     toolTip: "Bold (Ctrl+B)",        btnType: ButtonType.ToggleButton, icon: "bold",        toolType:"bold",     ignoreClick: true,   scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Italic",   toolTip: "Italic (Ctrl+I)",      btnType: ButtonType.ToggleButton, icon: "italic",      toolType:"italic",   ignoreClick: true,   scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Under",    toolTip: "Underline (Ctrl+U)",   btnType: ButtonType.ToggleButton, icon: "underline",   toolType:"underline",ignoreClick: true,   scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Bullets",  toolTip: "Bullet List",          btnType: ButtonType.ToggleButton, icon: "list",        toolType:"bullet",   ignoreClick: true,   scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "#",        toolTip: "Number List",          btnType: ButtonType.ToggleButton, icon: "list-ol",     toolType:"decimal",  ignoreClick: true,   scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Vcenter",  toolTip: "Vertical center",      btnType: ButtonType.ToggleButton, icon: "pallet",      toolType:"vcent",    ignoreClick: true,   scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Align",    toolTip: "Alignment",            btnType: ButtonType.MultiToggleButton,                 toolType:"alignment",ignoreClick: true,
              subMenu: [
             { title: "Left",    toolTip: "Left align (Cmd-[)",   btnType: ButtonType.ToggleButton, icon: "align-left",  toolType:"left",     ignoreClick: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
             { title: "Center",  toolTip: "Center align (Cmd-\\)",btnType: ButtonType.ToggleButton, icon: "align-center",toolType:"center",   ignoreClick: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
             { title: "Right",   toolTip: "Right align (Cmd-])",  btnType: ButtonType.ToggleButton, icon: "align-right", toolType:"right",    ignoreClick: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            ]},
            { title: "Fit Box",  toolTip: "Fit text to box",      btnType: ButtonType.ToggleButton, icon: "object-group",toolType:"fitBox",   ignoreClick: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Elide",    toolTip: "Elide selection",      btnType: ButtonType.ToggleButton, icon: "eye",         toolType:"elide",    ignoreClick: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "Dictate",  toolTip: "Dictate",              btnType: ButtonType.ToggleButton, icon: "microphone",  toolType:"dictation",ignoreClick: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'} },
            { title: "NoLink",   toolTip: "Auto Link",            btnType: ButtonType.ToggleButton, icon: "link",        toolType:"noAutoLink",expertMode: true,  scripts: {onClick: '{ return toggleCharStyle(this.toolType, _readOnly_);}'}, funcs: {hidden: 'IsNoviceMode()'}},
            // { title: "Strikethrough", tooltip: "Strikethrough", btnType: ButtonType.ToggleButton, icon: "strikethrough", scripts: {onClick:: 'toggleStrikethrough()'}},
            // { title: "Superscript", tooltip: "Superscript", btnType: ButtonType.ToggleButton, icon: "superscript", scripts: {onClick:: 'toggleSuperscript()'}},
            // { title: "Subscript", tooltip: "Subscript", btnType: ButtonType.ToggleButton, icon: "subscript", scripts: {onClick:: 'toggleSubscript()'}},
             ];
    }

    static inkTools():Button[] {
        return [
            { title: "Circle", toolTip: "Circle (double tap to lock mode)", btnType: ButtonType.ToggleButton, icon: "circle",      toolType: Gestures.Circle,                           scripts: {onClick:`{ return setActiveTool(this.toolType, false, _readOnly_);}`,   onDoubleClick:`{ return setActiveTool(this.toolType, true, _readOnly_);}`} },
            { title: "Square", toolTip: "Square (double tap to lock mode)", btnType: ButtonType.ToggleButton, icon: "square",      toolType: Gestures.Rectangle,                        scripts: {onClick:`{ return setActiveTool(this.toolType, false, _readOnly_);}`,   onDoubleClick:`{ return setActiveTool(this.toolType, true, _readOnly_);}`} },
            { title: "Line",   toolTip: "Line (double tap to lock mode)",   btnType: ButtonType.ToggleButton, icon: "minus",       toolType: Gestures.Line,                             scripts: {onClick:`{ return setActiveTool(this.toolType, false, _readOnly_);}`,   onDoubleClick:`{ return setActiveTool(this.toolType, true, _readOnly_);}`} },
            { title: "Ink",    toolTip: "Ink",                              btnType: ButtonType.MultiToggleButton,                 toolType: InkTool.Ink,        showUntilToggle: true,  scripts: {onClick:'{ return setActiveTool(this.toolType, true, _readOnly_);}' }, 
                subMenu: [
                    { title: "Pen",      toolTip: "Pen (Ctrl+P)",           btnType: ButtonType.ToggleButton, icon: "pen-nib",     toolType: InkInkTool.Pen,         ignoreClick: true, scripts: {onClick:'{ return setActiveTool(this.toolType, true, _readOnly_);}' }},
                    { title: "Highlight",toolTip: "Highlight (Ctrl+H)",     btnType: ButtonType.ToggleButton, icon: "highlighter", toolType: InkInkTool.Highlight,   ignoreClick: true, scripts: {onClick:'{ return setActiveTool(this.toolType, true, _readOnly_);}' }},
                    { title: "Write",    toolTip: "Write (Ctrl+Shift+P)",   btnType: ButtonType.ToggleButton, icon: "pen",         toolType: InkInkTool.Write,       ignoreClick: true, scripts: {onClick:'{ return setActiveTool(this.toolType, true, _readOnly_);}' },  funcs: {hidden:"IsNoviceMode()" }},      
                ]},
            { title: "Width",      toolTip: "Stroke width",                 btnType: ButtonType.NumberSliderButton,                toolType: InkProperty.StrokeWidth,ignoreClick: true, scripts: {script: '{ return setInkProperty(this.toolType, value, _readOnly_);}'}, funcs: {hidden:"!activeInkTool()"}, numBtnMin: 1, linearBtnWidth:40},
            { title: "Color",      toolTip: "Stroke color",                 btnType: ButtonType.ColorButton,  icon: "pen",         toolType: InkProperty.StrokeColor,ignoreClick: true, scripts: {script: '{ return setInkProperty(this.toolType, value, _readOnly_);}'}, funcs: {hidden:"!activeInkTool()"}},
            { title: "Eraser",     toolTip: "Eraser (Ctrl+E)",              btnType: ButtonType.MultiToggleButton,                 toolType: InkTool.Eraser,     showUntilToggle: true,  scripts: {onClick:'{ return setActiveTool(this.toolType, false, _readOnly_);}' },
              subMenu: [
                    { title: "Stroke",   toolTip: "Eraser complete strokes",btnType: ButtonType.ToggleButton, icon: "eraser",      toolType:InkEraserTool.Stroke,    ignoreClick: true, scripts: {onClick: '{ return setActiveTool(this.toolType, false, _readOnly_);}'}},
                    { title: "Segment",  toolTip: "Erase between intersections",btnType:ButtonType.ToggleButton,icon:"xmark",      toolType:InkEraserTool.Segment,   ignoreClick: true, scripts: {onClick: '{ return setActiveTool(this.toolType, false, _readOnly_);}'}},
                    { title: "Area",     toolTip: "Erase like a pencil",    btnType: ButtonType.ToggleButton, icon: "circle-xmark",toolType:InkEraserTool.Radius,    ignoreClick: true, scripts: {onClick: '{ return setActiveTool(this.toolType, false, _readOnly_);}'}},
            ]},
            { title: " Size",      toolTip: "Size of area pencil eraser",   btnType: ButtonType.NumberSliderButton,                toolType: InkProperty.EraserWidth,ignoreClick: true, scripts: {script: '{ return setInkProperty(this.toolType, value, _readOnly_);}'}, funcs: {hidden:"NotRadiusEraser()"}, numBtnMin: 1, linearBtnWidth:40},
            { title: "Mask",       toolTip: "Make Stroke a Stencil Mask",   btnType: ButtonType.ToggleButton, icon: "user-circle", toolType: InkProperty.Mask,                          scripts: {onClick:'{ return setInkProperty(this.toolType, value, _readOnly_);}'}, funcs: {hidden:"IsNoviceMode()" } },
            { title: "Labels",     toolTip: "Show Labels Inside Shapes",    btnType: ButtonType.ToggleButton, icon: "text-width",  toolType: InkProperty.Labels,                        scripts: {onClick:'{ return setInkProperty(this.toolType, value, _readOnly_);}'}},
            { title: "Smart Draw", toolTip: "Draw with AI",                btnType: ButtonType.ToggleButton, icon: "user-pen",    toolType: InkTool.SmartDraw,                         scripts: {onClick:'{ return setActiveTool(this.toolType, false, _readOnly_);}'},  funcs: {hidden: "IsNoviceMode()"}},
        ];
    }

    static schemaTools():Button[] {
        return [
            {title: "Preview", toolTip: "Show selection preview", btnType: ButtonType.ToggleButton, icon: "portrait", scripts:{ onClick: '{ return toggleSchemaPreview(_readOnly_); }'} },
            {title: "1 Line",  toolTip: "Single Line Rows",       btnType: ButtonType.ToggleButton, icon: "eye",      scripts:{ onClick: '{ return toggleSingleLineSchema(_readOnly_); }'} },
            {title: "DataViz", toolTip: "Turn Schema Table into Data Visualization Doc",       btnType: ButtonType.ClickButton, icon: "chart-bar", scripts:{ onClick: 'datavizFromSchema()'} }, ];
    }

    static webTools() {
        return [
            { title: "Back",    toolTip: "Go back",         btnType: ButtonType.ClickButton,  icon: "arrow-left",              scripts: { onClick: '{ return webBack(); }' }},
            { title: "Forward", toolTip: "Go forward",      btnType: ButtonType.ClickButton,  icon: "arrow-right",             scripts: { onClick: '{ return webForward(); }'}},
            { title: "URL",     toolTip: "URL", width: 250, btnType: ButtonType.EditText,     icon: "lock", ignoreClick: true, scripts: { script:  '{ return webSetURL(value, _readOnly_); }'} },
        ];
    }
    static videoTools() {
        return [
            { title: "Snapshot",toolTip: "Take snapshot of current frame", btnType: ButtonType.ClickButton,  icon: "camera",   scripts: { onClick: '{ return videoSnapshot(); }' }},
        ];
    }
    static imageTools() {
        return [
            { title: "Pixels",toolTip: "Set Native Pixel Size", btnType: ButtonType.ClickButton,  icon: "portrait",  scripts: { onClick: 'imageSetPixelSize();' }},
            { title: "Rotate",toolTip: "Rotate 90",             btnType: ButtonType.ClickButton,  icon: "redo-alt",  scripts: { onClick: 'imageRotate90();' }},
        ];
    }
    static contextMenuTools():Button[] {
        return [
            { title: "Perspective",                    toolTip: "View",                 btnType: ButtonType.DropdownList, expertMode: false, btnList: new List<string>(standardViewTypes),                                                                                                                           ignoreClick: true, width: 100, scripts: { script:  '{ return setView(value, shiftKey, _readOnly_); }'}},
            { title: "Pin",     icon: "map-pin",       toolTip: "Pin View to Trail",    btnType: ButtonType.ClickButton,  expertMode: false,                                                                                                                             width: 30,  scripts: { onClick: 'pinWithView(altKey)'}, funcs: {hidden: "IsNoneSelected()"}},
            { title: "Header",  icon: "heading",       toolTip: "Doc Titlebar Color",   btnType: ButtonType.ColorButton,  expertMode: false,                                                                                                          ignoreClick: true,             scripts: { script:  'return setHeaderColor(value, _readOnly_)'} },
            { title: "Template",icon: "scroll",        toolTip: "Default Note Template",btnType: ButtonType.ToggleButton, expertMode: false, toolType:DocumentType.RTF,                                                                                                              scripts: { onClick: '{ return setDefaultTemplate(_readOnly_); }'} },
            { title: "Fill",    icon: "fill-drip",     toolTip: "Fill/Background Color",btnType: ButtonType.ColorButton,  expertMode: false,                                                                                                          ignoreClick: true, width: 30,  scripts: { script:  'return setBackgroundColor(value, _readOnly_)'} }, // Only when a document is selected
            { title: "Border",  icon: "border-style",  toolTip: "Border Color",         btnType: ButtonType.ColorButton,  expertMode: false,                                                                                                          ignoreClick: true, width: 30,  scripts: { script:  'return setBorderColor(value, _readOnly_)'} }, // Only when a document is selected
            { title: "B.Width",                        toolTip: "Border width",         btnType: ButtonType.NumberSliderButton,                                                                                                                       ignoreClick: true,             scripts: {script: '{ return setBorderWidth(value, _readOnly_);}'}, numBtnMin: 0, linearBtnWidth:40},
            { title: "Overlay", icon: "layer-group",   toolTip: "Overlay",              btnType: ButtonType.ToggleButton, expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode, true)'},                        scripts: { onClick: '{ return toggleOverlay(_readOnly_); }'}}, // Only when floating document is selected in freeform
            { title: "Back",    icon: "chevron-left",  toolTip: "Prev Animation Frame", btnType: ButtonType.ClickButton,  expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)'},                  width: 30,  scripts: { onClick: 'prevKeyFrame(_readOnly_)'}},
            { title: "Num",     icon:"", toolTip: "Frame # (click to toggle edit mode)",btnType: ButtonType.TextButton,   expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)', buttonText: 'selectedDocs()?.lastElement()?.currentFrame?.toString()'}, width: 20, scripts: { onClick: '{ return curKeyFrame(_readOnly_);}'}},
            { title: "Fwd",     icon: "chevron-right", toolTip: "Next Animation Frame", btnType: ButtonType.ClickButton,  expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)'},                  width: 30,  scripts: { onClick: 'nextKeyFrame(_readOnly_)'}},
            { title: "Chat",    icon: "lightbulb",     toolTip: "Toggle Chat Assistant",btnType: ButtonType.ToggleButton, expertMode: false, toolType:"toggle-chat",               funcs: {},                                                                            width: 30,  scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} },
            { title: "Filter",  icon: "=",             toolTip: "Filter cards by tags", btnType: ButtonType.MultiToggleButton, 
                                                                                        subMenu: this.filterTools(),      expertMode: false, toolType:DocumentType.COL,            funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)'},ignoreClick:true, width: 30},
            { title: "Sort",    icon: "Sort",          toolTip: "Sort Documents",       subMenu: this.sortTools(),        expertMode: false, toolType:DocumentType.COL,            funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available
            { title: "Text",    icon: "Text",          toolTip: "Text functions",       subMenu: this.textTools(),        expertMode: false, toolType:DocumentType.RTF,            funcs: {                                                            linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available
            { title: "Ink",     icon: "Ink",           toolTip: "Ink functions",        subMenu: this.inkTools(),         expertMode: false, toolType:DocumentType.INK,            funcs: {hidden: `IsExploreMode()`,                                  linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`}, scripts: { onClick: 'setInkToolDefaults()'} }, // Always available
            { title: "Doc",     icon: "Doc",           toolTip: "Freeform Doc tools",   subMenu: this.freeTools(),        expertMode: false, toolType:CollectionViewType.Freeform, funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode, true)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available
            { title: "View",    icon: "View",          toolTip: "View tools",           subMenu: this.viewTools(),        expertMode: false, toolType:DocumentType.COL,            funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available
            { title: "Stack",   icon: "View",          toolTip: "Stacking tools",       subMenu: this.stackTools(),       expertMode: false, toolType:CollectionViewType.Stacking, funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available
                   
            { title: "Web",     icon: "Web",           toolTip: "Web functions",        subMenu: this.webTools(),         expertMode: false, toolType:DocumentType.WEB,            funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Only when Web is selected
            { title: "Video",   icon: "Video",         toolTip: "Video functions",      subMenu: this.videoTools(),       expertMode: false, toolType:DocumentType.VID,            funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Only when video is selected
            { title: "Image",   icon: "Image",         toolTip: "Image functions",      subMenu: this.imageTools(),       expertMode: false, toolType:DocumentType.IMG,            funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Only when image is selected
            { title: "Schema",  icon: "Schema",        toolTip: "Schema functions",     subMenu: this.schemaTools(),      expertMode: false, toolType:CollectionViewType.Schema,   funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`}, linearBtnWidth:58 }, // Only when Schema is selected
         ];
    }

    /// initializes a context menu button for the top bar context menu
    static setupContextMenuButton(params:Button, btnDoc?:Doc, btnContainer?:Doc) {
        const reqdOpts:DocumentOptions = {
            isSystem: true,
            ...OmitKeys(params, ["scripts", "funcs", "subMenu"]).omit,
            color: Colors.WHITE, 
            _nativeWidth: params.width ?? 30, _width: params.width ?? 30,
            _height: 30, _nativeHeight: 30, linearBtnWidth: params.linearBtnWidth,
            toolType: params.toolType, expertMode: params.expertMode,
            _dragOnlyWithinContainer: true, _lockedPosition: true,
            embedContainer: btnContainer
        };
        const reqdFuncs:{[key:string]:string} = {
            ...params.funcs,
        }
        return DocUtils.AssignScripts(DocUtils.AssignOpts(btnDoc, reqdOpts) ?? Docs.Create.FontIconDocument(reqdOpts), params.scripts, reqdFuncs);
    }

    
    static setupContextMenuBtn(params:Button, menuDoc:Doc):Doc {
        const menuBtnDoc = DocListCast(menuDoc?.data).find( doc => doc.title === params.title);
        const {subMenu} = params;
        if (!subMenu) { // button does not have a sub menu
            return this.setupContextMenuButton(params, menuBtnDoc, menuDoc);
        }  
        // linear view
        const reqdSubMenuOpts = { ...OmitKeys(params, ["scripts", "funcs", "subMenu"]).omit, undoIgnoreFields: new List<string>(['width', "linearView_IsOpen"]),
            childDontRegisterViews: true, flexGap: 0, _height: 30, _width: 30, ignoreClick: !params.scripts?.onClick,
            linearView_SubMenu: true, linearView_Expandable: true, embedContainer: menuDoc};
        
        const items = (menuBtn?:Doc) => !menuBtn ? [] : subMenu.map(sub => this.setupContextMenuBtn(sub, menuBtn) );
        const creator = params.btnType === ButtonType.MultiToggleButton ? this.multiToggleList : this.linearButtonList;
        const btnDoc = DocUtils.AssignScripts( DocUtils.AssignDocField(menuDoc, StrCast(params.title), 
                (opts) => creator(opts, items(menuBtnDoc)), reqdSubMenuOpts, items(menuBtnDoc)), params.scripts, params.funcs);
        if (!menuBtnDoc) Doc.GetProto(btnDoc).data = new List<Doc>(items(btnDoc));   
        return btnDoc;
    }

    /// Initializes all the default buttons for the top bar context menu
    static setupContextMenuButtons(doc: Doc, field="myContextMenuBtns") {
        const reqdCtxtOpts:DocumentOptions = { title: "context menu buttons", undoIgnoreFields:new List<string>(['width', "linearView_IsOpen"]), flexGap: 0, childDragAction: dropActionType.embed, childDontRegisterViews: true,  linearView_IsOpen: true, ignoreClick: true, linearView_Expandable: false, _height: 35 };
        const ctxtMenuBtnsDoc = DocUtils.AssignDocField(doc, field, (opts, items) => this.linearButtonList(opts, items??[]), reqdCtxtOpts, undefined);
        const ctxtMenuBtns = CurrentUserUtils.contextMenuTools().map(params => this.setupContextMenuBtn(params, ctxtMenuBtnsDoc) );
        return DocUtils.AssignOpts(ctxtMenuBtnsDoc, reqdCtxtOpts, ctxtMenuBtns);
    }
    /// Initializes all the default buttons for the top bar context menu
    static setupTopbarButtons(doc: Doc, field="myTopBarBtns") {
        Doc.UserDoc().currentRecording = undefined;
        Doc.UserDoc().workspaceRecordingState = undefined;
        Doc.UserDoc().workspaceReplayingState = undefined;
        const dockedBtns = DocCast(doc[field]);
        const dockBtn = (opts: DocumentOptions, scripts: {[key:string]:string|undefined}, funcs?: {[key:string]:string|undefined}) =>
            DocUtils.AssignScripts(DocUtils.AssignOpts(DocListCast(dockedBtns?.data)?.find(fdoc => fdoc.title === opts.title), opts) ?? 
                            CurrentUserUtils.createToolButton(opts), scripts, funcs);
        
        const btnDescs = [// setup reactions to change the highlights on the undo/redo buttons -- would be better to encode this in the undo/redo buttons, but the undo/redo stacks are not wired up that way yet
            { opts: { title: "Replicate",icon:"camera",toolTip:"Copy dashboard layout",btnType: ButtonType.ClickButton, expertMode: true},                                                                                             scripts: { onClick:  `snapshotDashboard()`}},
            { opts: { title: "Recordings",            toolTip: "Workspace Recordings", btnType: ButtonType.DropdownList,expertMode: false, ignoreClick: true, width: 100}, funcs: {hidden: `false`, btnList:`getWorkspaceRecordings()`},scripts: { script:  `{ return replayWorkspace(value, _readOnly_); }`, onDragScript: `{ return startRecordingDrag(value); }`}},
            { opts: { title: "Stop Rec",icon: "stop", toolTip: "Stop recording",       btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `!isWorkspaceRecording()`},                                                 scripts: { onClick: `stopWorkspaceRecording()`}},
            { opts: { title: "Play",    icon: "play", toolTip: "Play recording",       btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `isWorkspaceReplaying() !== "${mediaState.Paused}"`},                       scripts: { onClick: `resumeWorkspaceReplaying(getCurrentRecording())`}},
            { opts: { title: "Pause",   icon: "pause",toolTip: "Pause playback",       btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `isWorkspaceReplaying() !== "${mediaState.Playing}"`},                      scripts: { onClick: `pauseWorkspaceReplaying(getCurrentRecording())`}},
            { opts: { title: "Stop",    icon: "stop", toolTip: "Stop playback",        btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `isWorkspaceReplaying() !== "${mediaState.Paused}"`},                       scripts: { onClick: `stopWorkspaceReplaying(getCurrentRecording())`}},
            { opts: { title: "Delete",  icon: "trash",toolTip: "delete selected rec",  btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `isWorkspaceReplaying() !== "${mediaState.Paused}"`},                       scripts: { onClick: `removeWorkspaceReplaying(getCurrentRecording())`}}
        ];
        const btns = btnDescs.map(desc => dockBtn({_width: desc.opts.width??30, _height: 30, defaultDoubleClick: 'ignore', undoIgnoreFields: new List<string>(['opacity']), _dragOnlyWithinContainer: true, ...desc.opts}, desc.scripts, desc.funcs));
        const dockBtnsReqdOpts:DocumentOptions = {
            title: "docked buttons", _height: 40, flexGap: 0, layout_boxShadow: "standard", childDragAction: dropActionType.move,
            childDontRegisterViews: true, linearView_IsOpen: true, linearView_Expandable: false, ignoreClick: true
        };
        return DocUtils.AssignDocField(doc, field, (opts, items) => this.linearButtonList(opts, items??[]), dockBtnsReqdOpts, btns);
    }

    static setupPublished(doc:Doc, field = "myPublishedDocs") {
        return DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.TreeDocument([], opts), { title: "published docs", backgroundColor: "#aca3a6", isSystem: true });
    }
    
    static newAccount: boolean = false;

    // The database of all links on all documents
    static setupLinkDocs(doc: Doc, linkDatabaseId: string) {
        if (!(CurrentUserUtils.newAccount ? undefined : DocCast(doc.myLinkDatabase))) {
            const linkDocs = new Doc(linkDatabaseId, true);
            linkDocs.title = "LINK DATABASE: " + ClientUtils.CurrentUserEmail();
            linkDocs.author = ClientUtils.CurrentUserEmail();
            linkDocs.isSystem = true;
            linkDocs.data = new List<Doc>([]);
            linkDocs.acl_Guest = SharingPermissions.Augment;
            doc.myLinkDatabase = new PrefetchProxy(linkDocs);
        }
    }

    /// Shared documents option on the left side button panel
    // A user's sharing document is where all documents that are shared to that user are placed.  
    // When the user views one of these documents, it will be added to the sharing documents 'viewed' list field
    // The sharing document also stores the user's color value which helps distinguish shared documents from personal documents
    static setupSharedDocs(doc: Doc, sharingDocumentId: string) {
        const dblClkScript = "{scriptContext.openLevel(documentView); addDocToList(getSharingDoc(), 'viewed', documentView.Document);}";
        
        const sharedScripts = {  treeView_ChildDoubleClick: dblClkScript,  }
        const sharedDocOpts:DocumentOptions = {
            title: "My Shared Docs",
            userColor: "rgb(202, 202, 202)",
            isFolder:true, undoIgnoreFields:new List<string>(['treeView_SortCriterion']),
            // childContextMenuFilters: new List<ScriptField>([dashboardFilter!,]),
            // childContextMenuScripts: new List<ScriptField>([addToDashboards!,]),
            // childContextMenuLabels: new List<string>(["Add to Dashboards",]),
            // childContextMenuIcons: new List<string>(["user-plus",]),
            acl_Guest: SharingPermissions.Augment, _acl_Guest: SharingPermissions.Augment,
            childDragAction: dropActionType.embed, isSystem: true, childContentPointerEvents: "none", childLimitHeight: 0, _yMargin: 0, _gridGap: 15, childDontRegisterViews:true,
            // NOTE: treeView_HideTitle & _layout_showTitle is for a TreeView's editable title, _layout_showTitle is for DocumentViews title bar
            _layout_showTitle: "title", treeView_HideTitle: true, ignoreClick: true, _lockedPosition: true, layout_boxShadow: "0 0", _chromeHidden: true, dontRegisterView: true, 
            layout_explainer: "This is where documents or dashboards that other users have shared with you will appear. To share a document or dashboard right click and select 'Share'"
        };
        
        DocUtils.AssignDocField(doc, "mySharedDocs", opts => Docs.Create.TreeDocument([], opts, sharingDocumentId + "layout", sharingDocumentId), sharedDocOpts, undefined, sharedScripts);
        if (!Doc.GetProto(DocCast(doc.mySharedDocs)).data_dashboards) Doc.GetProto(DocCast(doc.mySharedDocs)).data_dashboards = new List<Doc>();
    }

    /// Import option on the left side button panel 
    static setupImportSidebar(doc: Doc, field:string) {
        const reqdOpts:DocumentOptions = {
            title: "My Imports", _forceActive: true, _layout_showTitle: "title", childLayoutString: ImportElementBox.LayoutString('data'),
            _dragOnlyWithinContainer: true, layout_hideContextMenu: true, childLimitHeight: 0, onClickScriptDisable:"never",
            childDragAction: dropActionType.copy, _layout_autoHeight: true, _yMargin: 50, _gridGap: 15, layout_boxShadow: "0 0", _lockedPosition: true, isSystem: true, _chromeHidden: true,
            dontRegisterView: true, layout_explainer: "This is where documents that are Imported into Dash will go."
        };
        const myImports = DocUtils.AssignDocField(doc, field, (opts) => Docs.Create.MasonryDocument([], opts), reqdOpts, undefined, {onClick: "deselectAll()"});
    
        const reqdBtnOpts:DocumentOptions = { _forceActive: true, toolTip: "Import from computer",
            _width: 30, _height: 30, color: Colors.BLACK, _dragOnlyWithinContainer: true, title: "Import", btnType: ButtonType.ClickButton, 
            buttonText: "Import", icon: "upload", isSystem: true };
        DocUtils.AssignDocField(myImports, "layout_headerButton", (opts) => Docs.Create.FontIconDocument(opts), reqdBtnOpts, undefined, { onClick: "importDocument()" });
        return myImports;
    }
    /// Updates the UserDoc to have all required fields, docs, etc.  No changes should need to be
    /// written to the server if the code hasn't changed.  However, choices need to be made for each Doc/field
    /// whether to revert to "default" values, or to leave them as the user/system last set them.
    static updateUserDocument(docIn: Doc, sharingDocumentId: string, linkDatabaseId: string) {
        const doc = docIn;
        DocUtils.AssignDocField(doc, "globalGroupDatabase", () => Docs.Prototypes.MainGroupDocument(), {});
        reaction(() => DateCast(DocCast(doc.globalGroupDatabase).data_modificationDate),
            async () => {
                const groups = await DocListCastAsync(DocCast(doc.globalGroupDatabase).data);
                const mygroups = groups?.filter(group => JSON.parse(StrCast(group.members)).includes(ClientUtils.CurrentUserEmail())) || [];
                SetCachedGroups(["Guest", ...(mygroups?.map(g => StrCast(g.title))??[])]);
            }, { fireImmediately: true });
        doc.isSystem ?? (doc.isSystem = true);
        doc.title ?? (doc.title = ClientUtils.CurrentUserEmail());
        Doc.noviceMode ?? (Doc.noviceMode = true);
        doc._showLabel ?? (doc._showLabel = true);
        doc.textAlign ?? (doc.textAlign = "left");
        doc.textBackgroundColor ?? (doc.textBackgroundColor = Colors.LIGHT_GRAY);
        doc.activeTool = InkTool.None;
        doc.openInkInLightbox ?? (doc.openInkInLightbox = false);
        doc.activeHideTextLabels ?? (doc.activeHideTextLabels = false);
        doc[`active${InkInkTool.Pen}Color`]        ?? (doc[`active${InkInkTool.Pen}Color`] = "rgb(0, 0, 0)");
        doc[`active${InkInkTool.Pen}Width`]        ?? (doc[`active${InkInkTool.Pen}Width`] = 2);
        doc[`active${InkInkTool.Pen}Bezier`]       ?? (doc[`active${InkInkTool.Pen}Bezier`] = "0");
        doc[`active${InkInkTool.Write}Color`]      ?? (doc[`active${InkInkTool.Write}Color`] = "rgb(255, 0, 0)");
        doc[`active${InkInkTool.Write}Width`]      ?? (doc[`active${InkInkTool.Write}Width`] = 1);
        doc[`active${InkInkTool.Write}Bezier`]     ?? (doc[`active${InkInkTool.Write}Bezier`] = "0");
        doc[`active${InkInkTool.Highlight}Color`]  ?? (doc[`active${InkInkTool.Highlight}Color`] = 'transparent');
        doc[`active${InkInkTool.Highlight}Width`]  ?? (doc[`active${InkInkTool.Highlight}Width`] = 20);
        doc[`active${InkInkTool.Highlight}Bezier`] ?? (doc[`active${InkInkTool.Highlight}Bezier`] = "0");
        doc[`active${InkInkTool.Highlight}Fill`]   ?? (doc[`active${InkInkTool.Highlight}Fill`] = "rgba(0, 255, 255, 0.4)");
        doc.activeInkTool ?? (doc.activeInkTool = InkInkTool.Pen);
        doc.activeEraserTool ?? (doc.activeEraserTool = InkEraserTool.Stroke);
        doc.activeEraserWidth ?? (doc.activeEraserWidth = 20);
        doc.activeDash ?? (doc.activeDash === "0");
        doc.fontSize ?? (doc.fontSize = "12px");
        doc.fontFamily ?? (doc.fontFamily = "Arial");
        doc.fontColor ?? (doc.fontColor = "black");
        doc.fontHighlight ?? (doc.fontHighlight = "");
        doc.defaultAclPrivate ?? (doc.defaultAclPrivate = false);
        doc.userBackgroundColor ?? (doc.userBackgroundColor = Colors.DARK_GRAY);
        doc.userVariantColor ?? (doc.userVariantColor = Colors.MEDIUM_BLUE);
        doc.userColor ?? (doc.userColor = Colors.LIGHT_GRAY);
        doc.userTheme ?? (doc.userTheme = ColorScheme.Dark);
        doc.treeView_FreezeChildren = "remove|add";
        doc.activePage = doc.activeDashboard === undefined ? 'home': doc.activePage;

        this.setupLinkDocs(doc, linkDatabaseId);
        this.setupSharedDocs(doc, sharingDocumentId);  // sets up the right sidebar collection for mobile upload documents and sharing
        this.setupDefaultIconTemplates(doc);  // creates a set of icon templates triggered by the document deoration icon
        this.setupPublished(doc);  // sets up the list doc of all docs that have been published (meaning that they can be auto-linked by typing their title into another text box)
        this.setupContextMenuButtons(doc); // set up the row of buttons at the top of the dashboard that change depending on what is selected
        this.setupTopbarButtons(doc);
        this.setupDockedButtons(doc);  // the bottom bar of font icons
        this.setupLeftSidebarMenu(doc); // the left-side column of buttons that open their contents in a flyout panel on the left
        this.setupAnnoPalette(doc);
        this.setupLightboxDrawingPreviews(doc);
        this.setupDocTemplates(doc); // sets up the template menu of templates
        // sthis.setupFieldInfos(doc); // sets up the collection of field info descriptions for each possible DocumentOption
        DocUtils.AssignDocField(doc, "globalScriptDatabase", () =>  Docs.Prototypes.MainScriptDocument(), {});
        DocUtils.AssignDocField(doc, "myHeaderBar", (opts) => Docs.Create.MulticolumnDocument([], opts), { title: "My Header Bar", isSystem: true, _chromeHidden:true, layout_maxShown: 10, childLayoutFitWidth:false, childDocumentsActive:false, dropAction: dropActionType.move}); // drop down panel at top of dashboard for stashing documents
        
        SelectionManager.DeselectAll(); // this forces SelectionManager implementation to copy over to DocumentView's API.  This also triggers the LinkManager to be created
        
        Doc.AddDocToList(Doc.MyFilesystem, undefined, Doc.MyDashboards);
        Doc.AddDocToList(Doc.MyFilesystem, undefined, Doc.MySharedDocs);
        Doc.AddDocToList(Doc.MyFilesystem, undefined, Doc.MyRecentlyClosed);

        Doc.GetProto(DocCast(Doc.UserDoc().emptyWebpage)).data = new WebField("https://www.wikipedia.org");

        DocServer.CacheNeedsUpdate() && setTimeout(UPDATE_SERVER_CACHE, 2500);
        setInterval(UPDATE_SERVER_CACHE, 120000);
        return doc;
    }
    static setupFieldInfos(doc:Doc, field="fieldInfos") {
        const fieldInfoOpts = { title: "Field Infos", isSystem: true}; // bcz: all possible document options have associated field infos which are stored on the FieldInfos document **except for title and system which are used as part of the definition of the fieldInfos object
        const infos = DocUtils.AssignDocField(doc, field, opts => Doc.assign(new Doc(), opts as {[key:string]: FieldType}), fieldInfoOpts);
        const entries = Object.entries(new DocumentOptions());
        entries.forEach(pair => {
            if (!Array.from(Object.keys(fieldInfoOpts)).includes(pair[0])) {
                const options = pair[1] as FInfo;
                const opts:DocumentOptions = { isSystem: true, title: pair[0], ...OmitKeys(options, ["values"]).omit};
                switch (options.fieldType) {
                    case FInfoFieldType.boolean: opts.fieldValues = new List<boolean>(options.values as boolean[]); break;
                    case FInfoFieldType.number: opts.fieldValues = new List<number>(options.values as number[]); break;
                    case FInfoFieldType.Doc: opts.fieldValues = new List<Doc>(options.values as Doc[]); break;
                    default: opts.fieldValues = new List<FieldType>(options.values); break;// string, pointerEvents, dimUnit, dropActionType
                }
                DocUtils.AssignDocField(infos, pair[0], docOpts => Doc.assign(new Doc(), OmitKeys(docOpts,["values"]).omit as {[key:string]: FieldType}), opts);
            }
        });
    }

    public static async loadCurrentUser() {
        return rp.get(ClientUtils.prepend("/getCurrentUser")).then(async response => {
            if (response) {
                const result: { version: string, userDocumentId: string, sharingDocumentId: string, linkDatabaseId: string,  email: string, cacheDocumentIds: string, resolvedPorts: {server: number, socket: number} } = JSON.parse(response);
                runInAction(() => { SnappingManager.SetServerVersion(result.version); });
                ClientUtils.SetCurrentUserEmail(result.email);
                resolvedPorts = result.resolvedPorts;
                DocServer.init(window.location.protocol, window.location.hostname, resolvedPorts?.socket, result.email);
                if (result.cacheDocumentIds) 
                {
                    const ids = result.cacheDocumentIds.split(";");
                    const batch = 30000;
                    for (let i = 0; i < ids.length; i += batch) {
                        // eslint-disable-next-line no-await-in-loop
                        await DocServer.GetRefFields(ids.slice(i, i+batch));
                    }
                }
                return result;
            } 
            throw new Error("There should be a user! Why does Dash think there isn't one?");
        });
    }

    public static async loadUserDocument(info:{
        userDocumentId: string;
        sharingDocumentId: string;
        linkDatabaseId: string;
    }) {
        return DocServer.GetRefField(info.userDocumentId).then(async field => {
            CurrentUserUtils.newAccount = !(field instanceof Doc);
            await Docs.Prototypes.initialize();
            const userDoc = CurrentUserUtils.newAccount ? new Doc(info.userDocumentId, true) : field as Doc;
            this.updateUserDocument(Doc.SetUserDoc(userDoc), info.sharingDocumentId, info.linkDatabaseId);
            if (CurrentUserUtils.newAccount) {
                if (ClientUtils.CurrentUserEmail() === "guest") {
                    DashboardView.createNewDashboard(undefined, "guest dashboard");
                } else {
                    userDoc.activePage = "home";
                    userDoc.noviceMode = true;
                }
            }
            return userDoc;
        });
    }


    public static importDocument = () => {
        const input = document.createElement("input");
        input.type = "file";
        input.multiple = true;
        input.accept = ".zip, application/pdf, video/*, image/*, audio/*";
        input.onchange = async () => {
            const file = input.files?.[0];
            if (file?.type === 'application/zip' || file?.type === 'application/x-zip-compressed') {
                const doc = await Doc.importDocument(file);
                const list = Cast(Doc.MyImports.data, listSpec(Doc), null);
                doc instanceof Doc && list?.splice(0, 0, doc);
            } else if (input.files && input.files.length !== 0) {
                const disposer = OverlayView.ShowSpinner();
                const results = await DocUtils.uploadFilesToDocs(Array.from(input.files || []), {});
                if (results.length !== input.files?.length) {
                    alert("Error uploading files - possibly due to unsupported file types");
                }
                const list = Cast(Doc.MyImports.data, listSpec(Doc), null);
                list?.splice(0, 0, ...results);
                disposer();
            } else {
                console.log("No file selected");
            }
        };
        input.click();
    }
}

// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function activeInkTool()   { return Doc.ActiveTool=== InkTool.Ink || DocumentView.Selected().some(dv => dv.layoutDoc.layout_isSvg); }, "is a pen tool or an ink stroke active");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function NotRadiusEraser() { return Doc.ActiveTool !== InkTool.Eraser || Doc.ActiveEraser !== InkEraserTool.Radius; }, "is the active tool anything but the radius eraser");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function MySharedDocs()    { return Doc.MySharedDocs; }, "document containing all shared Docs");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function IsExploreMode()   { return SnappingManager.ExploreMode; }, "is Dash in exploration mode");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function IsNoviceMode()    { return Doc.noviceMode; }, "is Dash in novice mode");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function toggleComicMode() { Doc.UserDoc().renderStyle = Doc.UserDoc().renderStyle === "comic" ? undefined : "comic"; }, "switches between comic and normal document rendering");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function importDocument()  { return CurrentUserUtils.importDocument(); }, "imports files from device directly into the import sidebar");
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function setInkToolDefaults() { Doc.ActiveTool = InkTool.None; });
// eslint-disable-next-line prefer-arrow-callback
ScriptingGlobals.add(function getSharingDoc()   { return Doc.SharingDoc() });