aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/collections/CollectionMenu.tsx
blob: aaf24356768b076b88a635225ea0caf2d46267b5 (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
1182
1183
1184
1185
1186
1187
1188
1189
1190
import React = require("react");
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon, FontAwesomeIconProps } from "@fortawesome/react-fontawesome";
import { Tooltip } from "@material-ui/core";
import { action, computed, Lambda, observable, reaction, runInAction } from "mobx";
import { observer } from "mobx-react";
import { ColorState } from "react-color";
import { Doc, DocListCast, Opt } from "../../../fields/Doc";
import { Document } from "../../../fields/documentSchemas";
import { Id } from "../../../fields/FieldSymbols";
import { InkTool } from "../../../fields/InkField";
import { List } from "../../../fields/List";
import { ObjectField } from "../../../fields/ObjectField";
import { RichTextField } from "../../../fields/RichTextField";
import { listSpec } from "../../../fields/Schema";
import { ScriptField } from "../../../fields/ScriptField";
import { BoolCast, Cast, NumCast, StrCast } from "../../../fields/Types";
import { emptyFunction, setupMoveUpEvents, Utils } from "../../../Utils";
import { DocumentType } from "../../documents/DocumentTypes";
import { CurrentUserUtils } from "../../util/CurrentUserUtils";
import { DragManager } from "../../util/DragManager";
import { Scripting } from "../../util/Scripting";
import { SelectionManager } from "../../util/SelectionManager";
import { undoBatch } from "../../util/UndoManager";
import { AntimodeMenu, AntimodeMenuProps } from "../AntimodeMenu";
import { EditableView } from "../EditableView";
import { GestureOverlay } from "../GestureOverlay";
import { ActiveFillColor, ActiveInkColor, SetActiveArrowEnd, SetActiveArrowStart, SetActiveBezierApprox, SetActiveFillColor, SetActiveInkColor, SetActiveInkWidth, ActiveArrowStart, ActiveArrowEnd } from "../InkingStroke";
import { CollectionFreeFormDocumentView } from "../nodes/CollectionFreeFormDocumentView";
import { DocumentView } from "../nodes/DocumentView";
import { RichTextMenu } from "../nodes/formattedText/RichTextMenu";
import { PresBox } from "../nodes/PresBox";
import "./CollectionMenu.scss";
import { CollectionViewType, COLLECTION_BORDER_WIDTH } from "./CollectionView";
import { TabDocView } from "./TabDocView";
import { LightboxView } from "../LightboxView";

@observer
export class CollectionMenu extends AntimodeMenu<AntimodeMenuProps> {
    @observable static Instance: CollectionMenu;

    @observable SelectedCollection: DocumentView | undefined;
    @observable FieldKey: string;

    constructor(props: any) {
        super(props);
        this.FieldKey = "";
        runInAction(() => CollectionMenu.Instance = this);
        this._canFade = false; // don't let the inking menu fade away
        runInAction(() => this.Pinned = Cast(Doc.UserDoc()["menuCollections-pinned"], "boolean", true));
        this.jumpTo(300, 300);
    }

    componentDidMount() {
        reaction(() => SelectionManager.Views().length && SelectionManager.Views()[0],
            (doc) => doc && this.SetSelection(doc));
    }

    @action
    SetSelection(view: DocumentView) {
        this.SelectedCollection = view;
    }

    @action
    toggleMenuPin = (e: React.MouseEvent) => {
        Doc.UserDoc()["menuCollections-pinned"] = this.Pinned = !this.Pinned;
        if (!this.Pinned && this._left < 0) {
            this.jumpTo(300, 300);
        }
    }

    @action
    toggleProperties = () => {
        if (CurrentUserUtils.propertiesWidth > 0) {
            CurrentUserUtils.propertiesWidth = 0;
        } else {
            CurrentUserUtils.propertiesWidth = 250;
        }
    }

    render() {
        const button = <Tooltip title={<div className="dash-tooltip">Pin Menu</div>} key="pin menu" placement="bottom">
            <button className="antimodeMenu-button" onClick={this.toggleMenuPin} style={{ backgroundColor: "#121721" }}>
                <FontAwesomeIcon icon="thumbtack" size="lg" style={{ transitionProperty: "transform", transitionDuration: "0.1s", transform: `rotate(${this.Pinned ? 45 : 0}deg)` }} />
            </button>
        </Tooltip>;

        const propIcon = CurrentUserUtils.propertiesWidth > 0 ? "angle-double-right" : "angle-double-left";
        const propTitle = CurrentUserUtils.propertiesWidth > 0 ? "Close Properties Panel" : "Open Properties Panel";

        const prop = <Tooltip title={<div className="dash-tooltip">{propTitle}</div>} key="properties" placement="bottom">
            <button className="antimodeMenu-button" key="properties" style={{ backgroundColor: "#424242" }}
                onPointerDown={this.toggleProperties}>
                <FontAwesomeIcon icon={propIcon} size="lg" />
            </button>
        </Tooltip>;

        return this.getElement(!this.SelectedCollection ? [/*button*/] :
            [<CollectionViewBaseChrome key="chrome"
                docView={this.SelectedCollection}
                fieldKey={this.SelectedCollection.LayoutFieldKey}
                type={StrCast(this.SelectedCollection?.props.Document._viewType, CollectionViewType.Invalid) as CollectionViewType} />,
                prop,
                /*button*/]);
    }
}

interface CollectionMenuProps {
    type: CollectionViewType;
    fieldKey: string;
    docView: DocumentView;
}

const stopPropagation = (e: React.SyntheticEvent) => e.stopPropagation();

@observer
export class CollectionViewBaseChrome extends React.Component<CollectionMenuProps> {
    //(!)?\(\(\(doc.(\w+) && \(doc.\w+ as \w+\).includes\(\"(\w+)\"\)

    get document() { return this.props.docView?.props.Document; }
    get target() { return this.document; }
    _templateCommand = {
        params: ["target", "source"], title: "item view",
        script: "self.target.childLayoutTemplate = getDocTemplate(self.source?.[0])",
        immediate: undoBatch((source: Doc[]) => {
            let formatStr = source.length && Cast(source[0].text, RichTextField, null)?.Text;
            try { formatStr && JSON.parse(formatStr); } catch (e) { formatStr = ""; }
            if (source.length === 1 && formatStr) {
                Doc.SetInPlace(this.target, "childLayoutString", formatStr, false);
            } else if (source.length) {
                this.target.childLayoutTemplate = Doc.getDocTemplate(source?.[0]);
            } else {
                Doc.SetInPlace(this.target, "childLayoutString", undefined, true);
                Doc.SetInPlace(this.target, "childLayoutTemplate", undefined, true);
            }
        }),
        initialize: emptyFunction,
    };
    _narrativeCommand = {
        params: ["target", "source"], title: "child click view",
        script: "self.target.childClickedOpenTemplateView = getDocTemplate(self.source?.[0])",
        immediate: undoBatch((source: Doc[]) => source.length && (this.target.childClickedOpenTemplateView = Doc.getDocTemplate(source?.[0]))),
        initialize: emptyFunction,
    };
    _contentCommand = {
        params: ["target", "source"], title: "set content",
        script: "getProto(self.target).data = copyField(self.source);",
        immediate: undoBatch((source: Doc[]) => Doc.GetProto(this.target).data = new List<Doc>(source)),
        initialize: emptyFunction,
    };
    _onClickCommand = {
        params: ["target", "proxy"], title: "copy onClick",
        script: `{ if (self.proxy?.[0]) {
             getProto(self.proxy[0]).onClick = copyField(self.target.onClick); 
             getProto(self.proxy[0]).target = self.target.target;
             getProto(self.proxy[0]).source = copyField(self.target.source); 
            }}`,
        immediate: undoBatch((source: Doc[]) => { }),
        initialize: emptyFunction,
    };
    _openLinkInCommand = {
        params: ["target", "container"], title: "link follow target",
        script: `{ if (self.container?.length) {
            getProto(self.target).linkContainer = self.container[0];
            getProto(self.target).isLinkButton = true;
            getProto(self.target).onClick = makeScript("getProto(self.linkContainer).data = new List([self.links[0]?.anchor2])");
            }}`,
        immediate: undoBatch((container: Doc[]) => {
            if (container.length) {
                Doc.GetProto(this.target).linkContainer = container[0];
                Doc.GetProto(this.target).isLinkButton = true;
                Doc.GetProto(this.target).onClick = ScriptField.MakeScript("getProto(self.linkContainer).data = new List([self.links[0]?.anchor2])");
            }
        }),
        initialize: emptyFunction,
    };
    _viewCommand = {
        params: ["target"], title: "bookmark view",
        script: "self.target._panX = self['target-panX']; self.target._panY = self['target-panY']; self.target._viewScale = self['target-viewScale']; gotoFrame(self.target, self['target-currentFrame']);",
        immediate: undoBatch((source: Doc[]) => { this.target._panX = 0; this.target._panY = 0; this.target._viewScale = 1; this.target._currentFrame = (this.target._currentFrame === undefined ? undefined : 0); }),
        initialize: (button: Doc) => { button['target-panX'] = this.target._panX; button['target-panY'] = this.target._panY; button['target-viewScale'] = this.target._viewScale; button['target-currentFrame'] = this.target._currentFrame; },
    };
    _clusterCommand = {
        params: ["target"], title: "fit content",
        script: "self.target._fitToBox = !self.target._fitToBox;",
        immediate: undoBatch((source: Doc[]) => this.target._fitToBox = !this.target._fitToBox),
        initialize: emptyFunction
    };
    _fitContentCommand = {
        params: ["target"], title: "toggle clusters",
        script: "self.target._useClusters = !self.target._useClusters;",
        immediate: undoBatch((source: Doc[]) => this.target._useClusters = !this.target._useClusters),
        initialize: emptyFunction
    };
    _saveFilterCommand = {
        params: ["target"], title: "save filter",
        script: `self.target._docFilters = compareLists(self['target-docFilters'],self.target._docFilters) ? undefined : copyField(self['target-docFilters']); 
                 self.target._searchFilterDocs = compareLists(self['target-searchFilterDocs'],self.target._searchFilterDocs) ? undefined: copyField(self['target-searchFilterDocs']);`,
        immediate: undoBatch((source: Doc[]) => { this.target._docFilters = undefined; this.target._searchFilterDocs = undefined; }),
        initialize: (button: Doc) => {
            button['target-docFilters'] = (Cast(Doc.UserDoc().mySearchPanelDoc, Doc, null)._docFilters || Cast(Doc.UserDoc().activeDashboard, Doc, null)._docFilters) instanceof ObjectField ?
                ObjectField.MakeCopy((Cast(Doc.UserDoc().mySearchPanelDoc, Doc, null)._docFilters || Cast(Doc.UserDoc().activeDashboard, Doc, null)._docFilters) as any as ObjectField) : undefined;
            button['target-searchFilterDocs'] = CurrentUserUtils.ActiveDashboard._searchFilterDocs instanceof ObjectField ? ObjectField.MakeCopy(CurrentUserUtils.ActiveDashboard._searchFilterDocs as any as ObjectField) : undefined;
        },
    };

    @computed get _freeform_commands() { return Doc.UserDoc().noviceMode ? [this._viewCommand, this._saveFilterCommand] : [this._viewCommand, this._saveFilterCommand, this._contentCommand, this._templateCommand, this._narrativeCommand]; }
    @computed get _stacking_commands() { return Doc.UserDoc().noviceMode ? undefined : [this._contentCommand, this._templateCommand]; }
    @computed get _masonry_commands() { return Doc.UserDoc().noviceMode ? undefined : [this._contentCommand, this._templateCommand]; }
    @computed get _schema_commands() { return Doc.UserDoc().noviceMode ? undefined : [this._templateCommand, this._narrativeCommand]; }
    @computed get _doc_commands() { return Doc.UserDoc().noviceMode ? undefined : [this._openLinkInCommand, this._onClickCommand]; }
    @computed get _tree_commands() { return undefined; }
    private get _buttonizableCommands() {
        switch (this.props.type) {
            default: return this._doc_commands;
            case CollectionViewType.Freeform: return this._freeform_commands;
            case CollectionViewType.Tree: return this._tree_commands;
            case CollectionViewType.Schema: return this._schema_commands;
            case CollectionViewType.Stacking: return this._stacking_commands;
            case CollectionViewType.Masonry: return this._stacking_commands;
            case CollectionViewType.Time: return this._freeform_commands;
            case CollectionViewType.Carousel: return this._freeform_commands;
            case CollectionViewType.Carousel3D: return this._freeform_commands;
        }
    }
    private _commandRef = React.createRef<HTMLInputElement>();
    private _viewRef = React.createRef<HTMLInputElement>();
    @observable private _currentKey: string = "";

    componentDidMount = action(() => {
        this._currentKey = this._currentKey || (this._buttonizableCommands?.length ? this._buttonizableCommands[0]?.title : "");
    });

    @undoBatch
    viewChanged = (e: React.ChangeEvent) => {
        const target = this.document !== Doc.UserDoc().sidebar ? this.document : this.document.proto as Doc;
        //@ts-ignore
        target._viewType = e.target.selectedOptions[0].value;
    }

    commandChanged = (e: React.ChangeEvent) => {
        //@ts-ignore
        runInAction(() => this._currentKey = e.target.selectedOptions[0].value);
    }


    @action closeViewSpecs = () => {
        this.document._facetWidth = 0;
    }

    @computed get subChrome() {
        switch (this.props.docView.props.LayoutTemplateString ? CollectionViewType.Freeform : this.props.type) { // bcz: ARgh!  hack to get menu for tree view outline items
            default: return this.otherSubChrome;
            case CollectionViewType.Invalid:
            case CollectionViewType.Freeform: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={this.props.type === CollectionViewType.Invalid} />);
            case CollectionViewType.Stacking: return (<CollectionStackingViewChrome key="collchrome" {...this.props} />);
            case CollectionViewType.Schema: return (<CollectionSchemaViewChrome key="collchrome" {...this.props} />);
            case CollectionViewType.Tree: return (<CollectionTreeViewChrome key="collchrome" {...this.props} />);
            case CollectionViewType.Masonry: return (<CollectionStackingViewChrome key="collchrome" {...this.props} />);
            case CollectionViewType.Carousel3D: return (<Collection3DCarouselViewChrome key="collchrome" {...this.props} />);
            case CollectionViewType.Grid: return (<CollectionGridViewChrome key="collchrome" {...this.props} />);
            case CollectionViewType.Docking: return (<CollectionDockingChrome key="collchrome" {...this.props} />);
        }
    }

    @computed get otherSubChrome() {
        const docType = this.props.docView.Document.type;
        switch (docType) {
            default: return (null);
            case DocumentType.IMG: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={false} isDoc={true} />);
            case DocumentType.PDF: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={false} isDoc={true} />);
            case DocumentType.INK: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={false} isDoc={true} />);
            case DocumentType.WEB: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={false} isDoc={true} />);
            case DocumentType.VID: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={false} isDoc={true} />);
            case DocumentType.RTF: return (<CollectionFreeFormViewChrome key="collchrome" {...this.props} isOverlay={this.props.type === CollectionViewType.Invalid} isDoc={true} />);
        }
    }


    private dropDisposer?: DragManager.DragDropDisposer;
    protected createDropTarget = (ele: HTMLDivElement) => {
        this.dropDisposer?.();
        if (ele) {
            this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this), this.document);
        }
    }

    @undoBatch
    @action
    protected drop(e: Event, de: DragManager.DropEvent): boolean {
        const docDragData = de.complete.docDragData;
        if (docDragData?.draggedDocuments.length) {
            this._buttonizableCommands?.filter(c => c.title === this._currentKey).map(c => c.immediate(docDragData.draggedDocuments || []));
            e.stopPropagation();
        }
        return true;
    }

    dragViewDown = (e: React.PointerEvent) => {
        setupMoveUpEvents(this, e, (e, down, delta) => {
            const vtype = this.props.type;
            const c = {
                params: ["target"], title: vtype,
                script: `this.target._viewType = '${StrCast(this.props.type)}'`,
                immediate: (source: Doc[]) => this.document._viewType = Doc.getDocTemplate(source?.[0]),
                initialize: emptyFunction,
            };
            DragManager.StartButtonDrag([this._viewRef.current!], c.script, StrCast(c.title),
                { target: this.document }, c.params, c.initialize, e.clientX, e.clientY);
            return true;
        }, emptyFunction, emptyFunction);
    }
    dragCommandDown = (e: React.PointerEvent) => {
        setupMoveUpEvents(this, e, (e, down, delta) => {
            this._buttonizableCommands?.filter(c => c.title === this._currentKey).map(c =>
                DragManager.StartButtonDrag([this._commandRef.current!], c.script, c.title,
                    { target: this.document }, c.params, c.initialize, e.clientX, e.clientY));
            return true;
        }, emptyFunction, () => {
            this._buttonizableCommands?.filter(c => c.title === this._currentKey).map(c => c.immediate([]));
        });
    }

    @computed get templateChrome() {
        return <div className="collectionViewBaseChrome-template" ref={this.createDropTarget} >
            <Tooltip title={<div className="dash-tooltip">drop document to apply or drag to create button</div>} placement="bottom">
                <div className="commandEntry-outerDiv" ref={this._commandRef} onPointerDown={this.dragCommandDown}>
                    <button className={"antimodeMenu-button"} >
                        <FontAwesomeIcon icon="bullseye" size="lg" />
                    </button>
                    <select
                        className="collectionViewBaseChrome-cmdPicker" onPointerDown={stopPropagation} onChange={this.commandChanged} value={this._currentKey}>
                        <option className="collectionViewBaseChrome-viewOption" onPointerDown={stopPropagation} key={"empty"} value={""} />
                        {this._buttonizableCommands?.map(cmd =>
                            <option className="collectionViewBaseChrome-viewOption" onPointerDown={stopPropagation} key={cmd.title} value={cmd.title}>{cmd.title}</option>
                        )}
                    </select>
                </div>
            </Tooltip>
        </div>;
    }

    @computed get viewModes() {
        const excludedViewTypes = Doc.UserDoc().noviceMode ? [CollectionViewType.Invalid, CollectionViewType.Docking, CollectionViewType.Pile, CollectionViewType.StackedTimeline, CollectionViewType.Stacking, CollectionViewType.Map, CollectionViewType.Linear] :
            [CollectionViewType.Invalid, CollectionViewType.Docking, CollectionViewType.Pile, CollectionViewType.StackedTimeline, CollectionViewType.Linear];
        const isPres: boolean = (this.document && this.document.type === DocumentType.PRES);
        return isPres ? (null) : (<div className="collectionViewBaseChrome-viewModes" >
            <Tooltip title={<div className="dash-tooltip">drop document to apply or drag to create button</div>} placement="bottom">
                <div className="commandEntry-outerDiv" ref={this._viewRef} onPointerDown={this.dragViewDown}>
                    <button className={"antimodeMenu-button"}>
                        <FontAwesomeIcon icon="bullseye" size="lg" />
                    </button>
                    <select
                        className="collectionViewBaseChrome-viewPicker"
                        onPointerDown={stopPropagation}
                        onChange={this.viewChanged}
                        value={StrCast(this.props.type)}>
                        {Object.values(CollectionViewType).filter(type => !excludedViewTypes.includes(type)).map(type => (
                            <option
                                key={Utils.GenerateGuid()}
                                className="collectionViewBaseChrome-viewOption"
                                onPointerDown={stopPropagation}
                                value={type}>
                                {type[0].toUpperCase() + type.substring(1)}
                            </option>
                        ))}
                    </select>
                </div>
            </Tooltip>
        </div>);
    }

    @computed get selectedDocumentView() {
        return SelectionManager.Views().length ? SelectionManager.Views()[0] : undefined;
    }
    @computed get selectedDoc() { return this.selectedDocumentView?.rootDoc; }
    @computed get notACollection() {
        if (this.selectedDoc) {
            const layoutField = Doc.LayoutField(this.selectedDoc);
            return this.props.type === CollectionViewType.Docking ||
                typeof (layoutField) === "string" && !layoutField?.includes("CollectionView");
        }
        else return false;
    }
    @computed
    get pinButton() {
        const targetDoc = this.selectedDoc;
        const isPinned = targetDoc && Doc.isDocPinned(targetDoc);
        return !targetDoc ? (null) : <Tooltip key="pin" title={<div className="dash-tooltip">{Doc.isDocPinned(targetDoc) ? "Unpin from presentation" : "Pin to presentation"}</div>} placement="top">
            <button className="antimodeMenu-button" style={{ backgroundColor: isPinned ? "121212" : undefined, borderLeft: "1px solid gray" }}
                onClick={e => TabDocView.PinDoc(targetDoc, { unpin: isPinned })}>
                <FontAwesomeIcon className="documentdecorations-icon" size="lg" icon="map-pin" />
            </button>
        </Tooltip>;
    }

    @undoBatch
    @action
    pinWithView = (targetDoc: Opt<Doc>) => {
        if (targetDoc) {
            TabDocView.PinDoc(targetDoc);
            const presArray: Doc[] = PresBox.Instance?.sortArray();
            const size: number = PresBox.Instance?._selectedArray.size;
            const presSelected: Doc | undefined = presArray && size ? presArray[size - 1] : undefined;
            const activeDoc = presSelected ? PresBox.Instance?.childDocs[PresBox.Instance?.childDocs.indexOf(presSelected) + 1] : PresBox.Instance?.childDocs[PresBox.Instance?.childDocs.length - 1];
            if (targetDoc.type === DocumentType.PDF || targetDoc.type === DocumentType.RTF || targetDoc.type === DocumentType.WEB || targetDoc._viewType === CollectionViewType.Stacking) {
                const scroll = targetDoc._scrollTop;
                activeDoc.presPinView = true;
                activeDoc.presPinViewScroll = scroll;
            } else if ((targetDoc.type === DocumentType.COL && targetDoc._viewType === CollectionViewType.Freeform) || targetDoc.type === DocumentType.IMG) {
                const x = targetDoc._panX;
                const y = targetDoc._panY;
                const scale = targetDoc._viewScale;
                activeDoc.presPinView = true;
                activeDoc.presPinViewX = x;
                activeDoc.presPinViewY = y;
                activeDoc.presPinViewScale = scale;
            } else if (targetDoc.type === DocumentType.VID) {
                activeDoc.presPinTimecode = targetDoc._currentTimecode;
                activeDoc.presPinView = true;
            } else if (targetDoc.type === DocumentType.COMPARISON) {
                const width = targetDoc._clipWidth;
                activeDoc.presPinClipWidth = width;
                activeDoc.presPinView = true;
            }
        }
    }

    @computed
    get pinWithViewButton() {
        const presPinWithViewIcon = <img src={`/assets/pinWithView.png`} style={{ margin: "auto", width: 19 }} />;
        return !this.selectedDoc ? (null) :
            <Tooltip title={<div className="dash-tooltip">{"Pin with current view"}</div>} placement="top">
                <button className="antimodeMenu-button" style={{ justifyContent: 'center' }}
                    onClick={() => this.pinWithView(this.selectedDoc)}>
                    {presPinWithViewIcon}
                </button>
            </Tooltip>;
    }


    @undoBatch
    onAlias = () => {
        if (this.selectedDoc && this.selectedDocumentView) {
            // const copy = Doc.MakeCopy(this.selectedDocumentView.props.Document, true);
            // copy.x = NumCast(this.selectedDoc.x) + NumCast(this.selectedDoc._width);
            // copy.y = NumCast(this.selectedDoc.y) + 30;
            // this.selectedDocumentView.props.addDocument?.(copy);
            const alias = Doc.MakeAlias(this.selectedDoc);
            alias.x = NumCast(this.selectedDoc.x) + NumCast(this.selectedDoc._width);
            alias.y = NumCast(this.selectedDoc.y) + 30;
            this.selectedDocumentView.props.addDocument?.(alias);
        }
    }
    onAliasButtonDown = (e: React.PointerEvent): void => {
        setupMoveUpEvents(this, e, this.onAliasButtonMoved, emptyFunction, emptyFunction);
    }

    @undoBatch
    onAliasButtonMoved = (e: PointerEvent) => {
        const contentDiv = this.selectedDocumentView?.ContentDiv;
        if (contentDiv) {
            const dragData = new DragManager.DocumentDragData([this.selectedDocumentView!.props.Document]);
            const offset = [e.clientX - contentDiv.getBoundingClientRect().x, e.clientY - contentDiv.getBoundingClientRect().y];
            dragData.defaultDropAction = "alias";
            dragData.canEmbed = true;
            DragManager.StartDocumentDrag([contentDiv], dragData, e.clientX, e.clientY, {
                offsetX: offset[0],
                offsetY: offset[1],
                hideSource: false
            });
            return true;
        }
        return false;
    }

    @computed
    get aliasButton() {
        const targetDoc = this.selectedDoc;
        return !targetDoc || targetDoc.type === DocumentType.PRES ? (null) : <Tooltip title={<div className="dash-tooltip">{"Tap or Drag to create an alias"}</div>} placement="top">
            <button className="antimodeMenu-button" onPointerDown={this.onAliasButtonDown} onClick={this.onAlias} style={{ cursor: "drag" }}>
                <FontAwesomeIcon className="documentdecorations-icon" icon="copy" size="lg" />
            </button>
        </Tooltip>;
    }

    @computed get lightboxButton() {
        const targetDoc = this.selectedDoc;
        return !targetDoc ? (null) : <Tooltip title={<div className="dash-tooltip">{"View in Lightbox"}</div>} placement="top">
            <button className="antimodeMenu-button" style={{ borderRight: "1px solid gray", justifyContent: 'center' }} onPointerDown={() => {
                const docs = DocListCast(targetDoc[Doc.LayoutFieldKey(targetDoc)]);
                LightboxView.SetLightboxDoc(targetDoc, undefined, docs);
            }}>
                <FontAwesomeIcon className="documentdecorations-icon" icon="desktop" size="lg" />
            </button>
        </Tooltip>;
    }

    render() {
        return (
            <div className="collectionMenu-cont" >
                <div className="collectionMenu">
                    <div className="collectionViewBaseChrome">
                        {this.aliasButton}
                        {/* {this.pinButton} */}
                        {this.pinWithViewButton}
                        {this.lightboxButton}
                        <Tooltip title={<div className="dash-tooltip">Toggle Overlay Layer</div>} placement="bottom">
                            <button className={"antimodeMenu-button"} key="float"
                                style={{
                                    backgroundColor: this.props.docView.layoutDoc.z ? "121212" : undefined, borderRight: "1px solid gray",
                                    pointerEvents: this.props.docView.props.ContainingCollectionDoc?._viewType !== CollectionViewType.Freeform ? "none" : undefined,
                                    color: this.props.docView.props.ContainingCollectionDoc?._viewType !== CollectionViewType.Freeform ? "dimgrey" : undefined
                                }}
                                onClick={undoBatch(() => this.props.docView.props.CollectionFreeFormDocumentView?.().float())}>
                                <FontAwesomeIcon icon={["fab", "buffer"]} size={"lg"} />
                            </button>
                        </Tooltip>
                        {this.subChrome}
                        {this.notACollection || this.props.type === CollectionViewType.Invalid ? (null) : this.viewModes}
                        {!this._buttonizableCommands ? (null) : this.templateChrome}
                    </div>
                </div>
            </div>
        );
    }
}

@observer
export class CollectionDockingChrome extends React.Component<CollectionMenuProps> {
    render() {
        return (null);
    }
}

@observer
export class CollectionFreeFormViewChrome extends React.Component<CollectionMenuProps & { isOverlay: boolean, isDoc?: boolean }> {
    public static Instance: CollectionFreeFormViewChrome;
    constructor(props: any) {
        super(props);
        CollectionFreeFormViewChrome.Instance = this;
    }
    get document() { return this.props.docView.props.Document; }
    @computed get dataField() {
        return this.document[this.props.docView.LayoutFieldKey + (this.props.isOverlay ? "-annotations" : "")];
    }
    @computed get childDocs() { return DocListCast(this.dataField); }
    @computed get selectedDocumentView() { return SelectionManager.Views().length ? SelectionManager.Views()[0] : undefined; }
    @computed get selectedDoc() { return this.selectedDocumentView?.rootDoc; }
    @computed get isText() {
        return this.selectedDoc?.type === DocumentType.RTF || (RichTextMenu.Instance?.view as any) ? true : false;
    }

    @undoBatch
    @action
    nextKeyframe = (): void => {
        const currentFrame = Cast(this.document._currentFrame, "number", null);
        if (currentFrame === undefined) {
            this.document._currentFrame = 0;
            CollectionFreeFormDocumentView.setupKeyframes(this.childDocs, 0);
        }
        CollectionFreeFormDocumentView.updateKeyframe(this.childDocs, currentFrame || 0);
        this.document._currentFrame = Math.max(0, (currentFrame || 0) + 1);
        this.document.lastFrame = Math.max(NumCast(this.document._currentFrame), NumCast(this.document.lastFrame));
    }
    @undoBatch
    @action
    prevKeyframe = (): void => {
        const currentFrame = Cast(this.document._currentFrame, "number", null);
        if (currentFrame === undefined) {
            this.document._currentFrame = 0;
            CollectionFreeFormDocumentView.setupKeyframes(this.childDocs, 0);
        }
        CollectionFreeFormDocumentView.gotoKeyframe(this.childDocs.slice());
        this.document._currentFrame = Math.max(0, (currentFrame || 0) - 1);
    }

    private _palette = ["#D0021B", "#F5A623", "#F8E71C", "#8B572A", "#7ED321", "#417505", "#9013FE", "#4A90E2", "#50E3C2", "#B8E986", "#000000", "#4A4A4A", "#9B9B9B", "#FFFFFF", ""];
    private _width = ["1", "5", "10", "100"];
    private _dotsize = [10, 20, 30, 40];
    private _draw = ["∿", "⎯", "→", "↔︎", "ロ", "O"];
    private _head = ["", "", "", "arrow", "", ""];
    private _end = ["", "", "arrow", "arrow", "", ""];
    private _shapePrims = ["", "line", "line", "line", "rectangle", "circle"];
    private _title = ["pen", "line", "line with arrow", "line with double arrows", "square", "circle",];
    private _faName = ["pen-fancy", "minus", "long-arrow-alt-right", "arrows-alt-h", "square", "circle"];
    @observable _selectedPrimitive = this._shapePrims.length;
    @observable _keepPrimitiveMode = false; // for whether primitive selection enters a one-shot or persistent mode
    @observable _colorBtn = false;
    @observable _widthBtn = false;
    @observable _fillBtn = false;

    @action clearKeepPrimitiveMode() { this._selectedPrimitive = this._shapePrims.length; }
    @action primCreated() {
        if (!this._keepPrimitiveMode) { //get out of ink mode after each stroke=
            CurrentUserUtils.SelectedTool = InkTool.None;
            this._selectedPrimitive = this._shapePrims.length;
            SetActiveArrowStart("none");
            SetActiveArrowEnd("none");
        }
    }

    @action
    changeColor = (color: string, type: string) => {
        const col: ColorState = {
            hex: color, hsl: { a: 0, h: 0, s: 0, l: 0, source: "" }, hsv: { a: 0, h: 0, s: 0, v: 0, source: "" },
            rgb: { a: 0, r: 0, b: 0, g: 0, source: "" }, oldHue: 0, source: "",
        };
        if (type === "color") {
            SetActiveInkColor(Utils.colorString(col));
        } else if (type === "fill") {
            SetActiveFillColor(Utils.colorString(col));
        }
    }

    @action
    editProperties = (value: any, field: string) => {
        SelectionManager.Views().forEach(action((element: DocumentView) => {
            const doc = Document(element.rootDoc);
            if (doc.type === DocumentType.INK) {
                switch (field) {
                    case "width": doc.strokeWidth = Number(value); break;
                    case "color": doc.color = String(value); break;
                    case "fill": doc.fillColor = String(value); break;
                    case "dash": doc.strokeDash = value;
                }
            }
        }));
    }

    @computed get drawButtons() {
        const func = action((i: number, keep: boolean) => {
            this._keepPrimitiveMode = keep;
            if (this._selectedPrimitive !== i) {
                this._selectedPrimitive = i;
                CurrentUserUtils.SelectedTool = InkTool.Pen;
                SetActiveArrowStart(this._head[i]);
                SetActiveArrowEnd(this._end[i]);
                SetActiveBezierApprox("300");

                GestureOverlay.Instance.InkShape = this._shapePrims[i];
            } else {
                this._selectedPrimitive = this._shapePrims.length;
                CurrentUserUtils.SelectedTool = InkTool.None;
                SetActiveArrowStart("");
                SetActiveArrowEnd("");
                GestureOverlay.Instance.InkShape = "";
                SetActiveBezierApprox("0");
            }
        });
        return <div className="btn-draw" key="draw">
            {this._draw.map((icon, i) =>
                <Tooltip key={icon} title={<div className="dash-tooltip">{this._title[i]}</div>} placement="bottom">
                    <button className="antimodeMenu-button"
                        onPointerDown={() => func(i, false)}
                        onDoubleClick={() => func(i, true)}
                        style={{ backgroundColor: i === this._selectedPrimitive ? "525252" : "", fontSize: "20" }}>
                        <FontAwesomeIcon icon={this._faName[i] as IconProp} size="sm" />
                    </button>
                </Tooltip>)}
        </div>;
    }

    toggleButton = (key: string, value: boolean, setter: () => {}, icon: FontAwesomeIconProps["icon"], ele: JSX.Element | null) => {
        return <Tooltip title={<div className="dash-tooltip">{key}</div>} placement="bottom">
            <button className="antimodeMenu-button" key={key}
                onPointerDown={action(e => setter())}
                style={{ backgroundColor: value ? "121212" : "" }}>
                <FontAwesomeIcon icon={icon} size="lg" />
                {ele}
            </button>
        </Tooltip>;
    }

    @computed get widthPicker() {
        const widthPicker = this.toggleButton("stroke width", this._widthBtn, () => this._widthBtn = !this._widthBtn, "bars", null);
        return !this._widthBtn ? widthPicker :
            <div className="btn2-group" key="width">
                {widthPicker}
                {this._width.map((wid, i) =>
                    <Tooltip title={<div className="dash-tooltip">change width</div>} placement="bottom">
                        <button className="antimodeMenu-button" key={wid}
                            onPointerDown={action(() => { SetActiveInkWidth(wid); this._widthBtn = false; this.editProperties(wid, "width"); })}
                            style={{ backgroundColor: this._widthBtn ? "121212" : "", zIndex: 1001, fontSize: this._dotsize[i], padding: 0, textAlign: "center" }}>
                            •
                    </button>
                    </Tooltip>)}
            </div>;
    }

    @computed get colorPicker() {
        const colorPicker = this.toggleButton("stroke color", this._colorBtn, () => this._colorBtn = !this._colorBtn, "pen-nib",
            <div className="color-previewI" style={{ backgroundColor: ActiveInkColor() ?? "121212" }} />);
        return !this._colorBtn ? colorPicker :
            <div className="btn-group" key="color">
                {colorPicker}
                {this._palette.map(color =>
                    <button className="antimodeMenu-button" key={color}
                        onPointerDown={action(() => { this.changeColor(color, "color"); this._colorBtn = false; this.editProperties(color, "color"); })}
                        style={{ backgroundColor: this._colorBtn ? "121212" : "", zIndex: 1001 }}>
                        {/* <FontAwesomeIcon icon="pen-nib" size="lg" /> */}
                        <div className="color-previewII" style={{ backgroundColor: color }}>
                            {color === "" ? <p style={{ fontSize: 40, color: "red", marginTop: -10, marginLeft: -5, position: "fixed" }}>☒</p> : ""}
                        </div>
                    </button >)}
            </div >;
    }
    @computed get fillPicker() {
        const fillPicker = this.toggleButton("shape fill color", this._fillBtn, () => this._fillBtn = !this._fillBtn, "fill-drip",
            <div className="color-previewI" style={{ backgroundColor: ActiveFillColor() ?? "121212" }} />);
        return !this._fillBtn ? fillPicker :
            <div className="btn-group" key="fill" >
                {fillPicker}
                {this._palette.map(color =>
                    <button className="antimodeMenu-button" key={color}
                        onPointerDown={action(() => { this.changeColor(color, "fill"); this._fillBtn = false; this.editProperties(color, "fill"); })}
                        style={{ backgroundColor: this._fillBtn ? "121212" : "", zIndex: 1001 }}>
                        <div className="color-previewII" style={{ backgroundColor: color }}>
                            {color === "" ? <p style={{ fontSize: 40, color: "red", marginTop: -10, marginLeft: -5, position: "fixed" }}>☒</p> : ""}
                        </div>
                    </button>)}

            </div>;
    }
    @observable viewType = this.selectedDoc?._viewType;

    render() {
        return !this.props.docView.layoutDoc ? (null) :
            <div className="collectionFreeFormMenu-cont">

                {!this.isText ?
                    <>
                        {this.drawButtons}
                        {this.widthPicker}
                        {this.colorPicker}
                        {this.fillPicker}
                        {Doc.UserDoc().noviceMode || this.props.isDoc ? (null) :
                            <>
                                <Tooltip key="back" title={<div className="dash-tooltip">Back Frame</div>} placement="bottom">
                                    <div className="backKeyframe" onClick={this.prevKeyframe}>
                                        <FontAwesomeIcon icon={"caret-left"} size={"lg"} />
                                    </div>
                                </Tooltip>
                                <Tooltip key="num" title={<div className="dash-tooltip">Toggle View All</div>} placement="bottom">
                                    <div className="numKeyframe" style={{ color: this.props.docView.ComponentView?.getKeyFrameEditing?.() ? "white" : "black", backgroundColor: this.props.docView.ComponentView?.getKeyFrameEditing?.() ? "#5B9FDD" : "#AEDDF8" }}
                                        onClick={action(() => this.props.docView.ComponentView?.setKeyFrameEditing?.(!this.props.docView.ComponentView?.getKeyFrameEditing?.()))} >
                                        {NumCast(this.document._currentFrame)}
                                    </div>
                                </Tooltip>
                                <Tooltip key="fwd" title={<div className="dash-tooltip">Forward Frame</div>} placement="bottom">
                                    <div className="fwdKeyframe" onClick={this.nextKeyframe}>
                                        <FontAwesomeIcon icon={"caret-right"} size={"lg"} />
                                    </div>
                                </Tooltip>
                            </>}
                    </> :
                    <RichTextMenu />
                }
                {!this.selectedDocumentView?.ComponentView?.menuControls ? (null) : this.selectedDocumentView?.ComponentView?.menuControls?.()}
            </div>;
    }
}
@observer
export class CollectionStackingViewChrome extends React.Component<CollectionMenuProps> {
    @observable private _currentKey: string = "";
    @observable private suggestions: string[] = [];

    get document() { return this.props.docView.props.Document; }

    @computed private get descending() { return StrCast(this.document._columnsSort) === "descending"; }
    @computed get pivotField() { return StrCast(this.document._pivotField); }

    getKeySuggestions = async (value: string): Promise<string[]> => {
        const val = value.toLowerCase();
        const docs = DocListCast(this.document[this.props.fieldKey]);

        if (Doc.UserDoc().noviceMode) {
            if (docs instanceof Doc) {
                const keys = Object.keys(docs).filter(key => key.indexOf("title") >= 0 || key.indexOf("author") >= 0 ||
                    key.indexOf("creationDate") >= 0 || key.indexOf("lastModified") >= 0 ||
                    (key[0].toUpperCase() === key[0] && key[0] !== "_"));
                return keys.filter(key => key.toLowerCase().indexOf(val) > -1);
            } else {
                const keys = new Set<string>();
                docs.forEach(doc => Doc.allKeys(doc).forEach(key => keys.add(key)));
                const noviceKeys = Array.from(keys).filter(key => key.indexOf("title") >= 0 || key.indexOf("author") >= 0 ||
                    key.indexOf("creationDate") >= 0 || key.indexOf("lastModified") >= 0 ||
                    (key[0]?.toUpperCase() === key[0] && key[0] !== "_"));
                return noviceKeys.filter(key => key.toLowerCase().indexOf(val) > -1);
            }
        }

        if (docs instanceof Doc) {
            return Object.keys(docs).filter(key => key.toLowerCase().indexOf(val) > -1);
        } else {
            const keys = new Set<string>();
            docs.forEach(doc => Doc.allKeys(doc).forEach(key => keys.add(key)));
            return Array.from(keys).filter(key => key.toLowerCase().indexOf(val) > -1);
        }
    }

    @action
    onKeyChange = (e: React.ChangeEvent, { newValue }: { newValue: string }) => {
        this._currentKey = newValue;
    }

    getSuggestionValue = (suggestion: string) => suggestion;

    renderSuggestion = (suggestion: string) => {
        return <p>{suggestion}</p>;
    }

    onSuggestionFetch = async ({ value }: { value: string }) => {
        const sugg = await this.getKeySuggestions(value);
        runInAction(() => {
            this.suggestions = sugg;
        });
    }

    @action
    onSuggestionClear = () => {
        this.suggestions = [];
    }

    @action
    setValue = (value: string) => {
        this.document._pivotField = value;
        return true;
    }

    @action toggleSort = () => {
        this.document._columnsSort =
            this.document._columnsSort === "descending" ? "ascending" :
                this.document._columnsSort === "ascending" ? undefined : "descending";
    }
    @action resetValue = () => { this._currentKey = this.pivotField; };

    render() {
        const doctype = this.props.docView.Document.type;
        const isPres: boolean = (doctype === DocumentType.PRES);
        return (
            isPres ? (null) : <div className="collectionStackingViewChrome-cont">
                <div className="collectionStackingViewChrome-pivotField-cont">
                    <div className="collectionStackingViewChrome-pivotField-label">
                        GROUP BY:
                    </div>
                    <div className="collectionStackingViewChrome-sortIcon" onClick={this.toggleSort} style={{ transform: `rotate(${this.descending ? "180" : "0"}deg)` }}>
                        <FontAwesomeIcon icon="caret-up" size="2x" color="white" />
                    </div>
                    <div className="collectionStackingViewChrome-pivotField">
                        <EditableView
                            GetValue={() => this.pivotField}
                            autosuggestProps={
                                {
                                    resetValue: this.resetValue,
                                    value: this._currentKey,
                                    onChange: this.onKeyChange,
                                    autosuggestProps: {
                                        inputProps:
                                        {
                                            value: this._currentKey,
                                            onChange: this.onKeyChange
                                        },
                                        getSuggestionValue: this.getSuggestionValue,
                                        suggestions: this.suggestions,
                                        alwaysRenderSuggestions: true,
                                        renderSuggestion: this.renderSuggestion,
                                        onSuggestionsFetchRequested: this.onSuggestionFetch,
                                        onSuggestionsClearRequested: this.onSuggestionClear
                                    }
                                }}
                            oneLine
                            SetValue={this.setValue}
                            contents={this.pivotField ? this.pivotField : "N/A"}
                        />
                    </div>
                </div>
            </div>
        );
    }
}


@observer
export class CollectionSchemaViewChrome extends React.Component<CollectionMenuProps> {
    // private _textwrapAllRows: boolean = Cast(this.document.textwrappedSchemaRows, listSpec("string"), []).length > 0;
    get document() { return this.props.docView.props.Document; }

    @undoBatch
    togglePreview = () => {
        const dividerWidth = 4;
        const borderWidth = Number(COLLECTION_BORDER_WIDTH);
        const panelWidth = this.props.docView.props.PanelWidth();
        const previewWidth = NumCast(this.document.schemaPreviewWidth);
        const tableWidth = panelWidth - 2 * borderWidth - dividerWidth - previewWidth;
        this.document.schemaPreviewWidth = previewWidth === 0 ? Math.min(tableWidth / 3, 200) : 0;
    }

    @undoBatch
    @action
    toggleTextwrap = async () => {
        const textwrappedRows = Cast(this.document.textwrappedSchemaRows, listSpec("string"), []);
        if (textwrappedRows.length) {
            this.document.textwrappedSchemaRows = new List<string>([]);
        } else {
            const docs = DocListCast(this.document[this.props.fieldKey]);
            const allRows = docs instanceof Doc ? [docs[Id]] : docs.map(doc => doc[Id]);
            this.document.textwrappedSchemaRows = new List<string>(allRows);
        }
    }


    render() {
        const previewWidth = NumCast(this.document.schemaPreviewWidth);
        const textWrapped = Cast(this.document.textwrappedSchemaRows, listSpec("string"), []).length > 0;

        return (
            <div className="collectionSchemaViewChrome-cont">
                <div className="collectionSchemaViewChrome-toggle">
                    <div className="collectionSchemaViewChrome-label">Show Preview: </div>
                    <div className="collectionSchemaViewChrome-toggler" onClick={this.togglePreview}>
                        <div className={"collectionSchemaViewChrome-togglerButton" + (previewWidth !== 0 ? " on" : " off")}>
                            {previewWidth !== 0 ? "on" : "off"}
                        </div>
                    </div>
                </div>
            </div >
        );
    }
}

@observer
export class CollectionTreeViewChrome extends React.Component<CollectionMenuProps> {

    get document() { return this.props.docView.props.Document; }
    get sortAscending() {
        return this.document[this.props.fieldKey + "-sortAscending"];
    }
    set sortAscending(value) {
        this.document[this.props.fieldKey + "-sortAscending"] = value;
    }
    @computed private get ascending() {
        return Cast(this.sortAscending, "boolean", null);
    }

    @action toggleSort = () => {
        if (this.sortAscending) this.sortAscending = undefined;
        else if (this.sortAscending === undefined) this.sortAscending = false;
        else this.sortAscending = true;
    }

    render() {
        return (
            <div className="collectionTreeViewChrome-cont">
                <button className="collectionTreeViewChrome-sort" onClick={this.toggleSort}>
                    <div className="collectionTreeViewChrome-sortLabel">
                        Sort
                        </div>
                    <div className="collectionTreeViewChrome-sortIcon" style={{ transform: `rotate(${this.ascending === undefined ? "90" : this.ascending ? "180" : "0"}deg)` }}>
                        <FontAwesomeIcon icon="caret-up" size="2x" color="white" />
                    </div>
                </button>
            </div>
        );
    }
}

// Enter scroll speed for 3D Carousel 
@observer
export class Collection3DCarouselViewChrome extends React.Component<CollectionMenuProps> {
    get document() { return this.props.docView.props.Document; }
    @computed get scrollSpeed() {
        return this.document._autoScrollSpeed;
    }

    @action
    setValue = (value: string) => {
        const numValue = Number(StrCast(value));
        if (numValue > 0) {
            this.document._autoScrollSpeed = numValue;
            return true;
        }
        return false;
    }

    render() {
        return (
            <div className="collection3DCarouselViewChrome-cont">
                <div className="collection3DCarouselViewChrome-scrollSpeed-cont">
                    <div className="collectionStackingViewChrome-scrollSpeed-label">
                        AUTOSCROLL SPEED:
                    </div>
                    <div className="collection3DCarouselViewChrome-scrollSpeed">
                        <EditableView
                            GetValue={() => StrCast(this.scrollSpeed)}
                            oneLine
                            SetValue={this.setValue}
                            contents={this.scrollSpeed ? this.scrollSpeed : 1000} />
                    </div>
                </div>
            </div>
        );
    }
}

/**
 * Chrome for grid view.
 */
@observer
export class CollectionGridViewChrome extends React.Component<CollectionMenuProps> {

    private clicked: boolean = false;
    private entered: boolean = false;
    private decrementLimitReached: boolean = false;
    @observable private resize = false;
    private resizeListenerDisposer: Opt<Lambda>;
    get document() { return this.props.docView.props.Document; }

    componentDidMount() {

        runInAction(() => this.resize = this.props.docView.props.PanelWidth() < 700);

        // listener to reduce text on chrome resize (panel resize)
        this.resizeListenerDisposer = computed(() => this.props.docView.props.PanelWidth()).observe(({ newValue }) => {
            runInAction(() => this.resize = newValue < 700);
        });
    }

    componentWillUnmount() {
        this.resizeListenerDisposer?.();
    }

    get numCols() { return NumCast(this.document.gridNumCols, 10); }

    /**
    * Sets the value of `numCols` on the grid's Document to the value entered.
    */
    onNumColsChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.currentTarget.valueAsNumber > 0) undoBatch(() => this.document.gridNumCols = e.currentTarget.valueAsNumber)();
    }

    /**
     * Sets the value of `rowHeight` on the grid's Document to the value entered.
     */
    // @undoBatch
    // onRowHeightEnter = (e: React.KeyboardEvent<HTMLInputElement>) => {
    //     if (e.key === "Enter" || e.key === "Tab") {
    //         if (e.currentTarget.valueAsNumber > 0 && this.document.rowHeight as number !== e.currentTarget.valueAsNumber) {
    //             this.document.rowHeight = e.currentTarget.valueAsNumber;
    //         }
    //     }
    // }

    /**
     * Sets whether the grid is flexible or not on the grid's Document.
     */
    @undoBatch
    toggleFlex = () => {
        this.document.gridFlex = !BoolCast(this.document.gridFlex, true);
    }

    /**
     * Increments the value of numCols on button click
     */
    onIncrementButtonClick = () => {
        this.clicked = true;
        this.entered && (this.document.gridNumCols as number)--;
        undoBatch(() => this.document.gridNumCols = this.numCols + 1)();
        this.entered = false;
    }

    /**
     * Decrements the value of numCols on button click
     */
    onDecrementButtonClick = () => {
        this.clicked = true;
        if (this.numCols > 1 && !this.decrementLimitReached) {
            this.entered && (this.document.gridNumCols as number)++;
            undoBatch(() => this.document.gridNumCols = this.numCols - 1)();
            if (this.numCols === 1) this.decrementLimitReached = true;
        }
        this.entered = false;
    }

    /**
     * Increments the value of numCols on button hover
     */
    incrementValue = () => {
        this.entered = true;
        if (!this.clicked && !this.decrementLimitReached) {
            this.document.gridNumCols = this.numCols + 1;
        }
        this.decrementLimitReached = false;
        this.clicked = false;
    }

    /**
     * Decrements the value of numCols on button hover
     */
    decrementValue = () => {
        this.entered = true;
        if (!this.clicked) {
            if (this.numCols > 1) {
                this.document.gridNumCols = this.numCols - 1;
            }
            else {
                this.decrementLimitReached = true;
            }
        }

        this.clicked = false;
    }

    /**
     * Toggles the value of preventCollision
     */
    toggleCollisions = () => {
        this.document.gridPreventCollision = !this.document.gridPreventCollision;
    }

    /**
     * Changes the value of the compactType
     */
    changeCompactType = (e: React.ChangeEvent<HTMLSelectElement>) => {
        // need to change startCompaction so that this operation will be undoable.
        this.document.gridStartCompaction = e.target.selectedOptions[0].value;
    }

    render() {
        return (
            <div className="collectionGridViewChrome-cont" >
                <span className="grid-control" style={{ width: this.resize ? "25%" : "30%" }}>
                    <span className="grid-icon">
                        <FontAwesomeIcon icon="columns" size="1x" />
                    </span>
                    <input className="collectionGridViewChrome-entryBox" type="number" value={this.numCols} onChange={this.onNumColsChange} onClick={(e: React.MouseEvent<HTMLInputElement, MouseEvent>) => { e.stopPropagation(); e.preventDefault(); e.currentTarget.focus(); }} />
                    <input className="collectionGridViewChrome-columnButton" onClick={this.onIncrementButtonClick} onMouseEnter={this.incrementValue} onMouseLeave={this.decrementValue} type="button" value="↑" />
                    <input className="collectionGridViewChrome-columnButton" style={{ marginRight: 5 }} onClick={this.onDecrementButtonClick} onMouseEnter={this.decrementValue} onMouseLeave={this.incrementValue} type="button" value="↓" />
                </span>
                {/* <span className="grid-control">
                    <span className="grid-icon">
                        <FontAwesomeIcon icon="text-height" size="1x" />
                    </span>
                    <input className="collectionGridViewChrome-entryBox" type="number" placeholder={this.document.rowHeight as string} onKeyDown={this.onRowHeightEnter} onClick={(e: React.MouseEvent<HTMLInputElement, MouseEvent>) => { e.stopPropagation(); e.preventDefault(); e.currentTarget.focus(); }} />
                </span> */}
                <span className="grid-control" style={{ width: this.resize ? "12%" : "20%" }}>
                    <input type="checkbox" style={{ marginRight: 5 }} onChange={this.toggleCollisions} checked={!this.document.gridPreventCollision} />
                    <label className="flexLabel">{this.resize ? "Coll" : "Collisions"}</label>
                </span>

                <select className="collectionGridViewChrome-viewPicker"
                    style={{ marginRight: 5 }}
                    onPointerDown={stopPropagation}
                    onChange={this.changeCompactType}
                    value={StrCast(this.document.gridStartCompaction, StrCast(this.document.gridCompaction))}>
                    {["vertical", "horizontal", "none"].map(type =>
                        <option className="collectionGridViewChrome-viewOption"
                            onPointerDown={stopPropagation}
                            value={type}>
                            {this.resize ? type[0].toUpperCase() + type.substring(1) : "Compact: " + type}
                        </option>
                    )}
                </select>

                <span className="grid-control" style={{ width: this.resize ? "12%" : "20%" }}>
                    <input style={{ marginRight: 5 }} type="checkbox" onChange={this.toggleFlex}
                        checked={BoolCast(this.document.gridFlex, true)} />
                    <label className="flexLabel">{this.resize ? "Flex" : "Flexible"}</label>
                </span>

                <button onClick={() => this.document.gridResetLayout = true}>
                    {!this.resize ? "Reset" :
                        <FontAwesomeIcon icon="redo-alt" size="1x" />}
                </button>

            </div>
        );
    }
}
Scripting.addGlobal(function gotoFrame(doc: any, newFrame: any) {
    const dataField = doc[Doc.LayoutFieldKey(doc)];
    const childDocs = DocListCast(dataField);
    const currentFrame = Cast(doc._currentFrame, "number", null);
    if (currentFrame === undefined) {
        doc._currentFrame = 0;
        CollectionFreeFormDocumentView.setupKeyframes(childDocs, 0);
    }
    CollectionFreeFormDocumentView.updateKeyframe(childDocs, currentFrame || 0);
    doc._currentFrame = newFrame === undefined ? 0 : Math.max(0, newFrame);
});