aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx
blob: 9e5dbe967959275804195ee70aba249d23197346 (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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Colors } from 'browndash-components';
import { action, computed, makeObservable, observable, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import { IDisposer } from 'mobx-utils';
import * as React from 'react';
import ReactLoading from 'react-loading';
import { ClientUtils, returnEmptyFilter, returnFalse, setupMoveUpEvents } from '../../../../../ClientUtils';
import { emptyFunction } from '../../../../../Utils';
import { Doc, DocListCast, FieldType, NumListCast, StrListCast, returnEmptyDoclist } from '../../../../../fields/Doc';
import { Id } from '../../../../../fields/FieldSymbols';
import { ImageCast, StrCast } from '../../../../../fields/Types';
import { ImageField } from '../../../../../fields/URLField';
import { Networking } from '../../../../Network';
import { GPTCallType, gptAPICall, gptImageCall } from '../../../../apis/gpt/GPT';
import { Docs, DocumentOptions } from '../../../../documents/Documents';
import { DragManager } from '../../../../util/DragManager';
import { SnappingManager } from '../../../../util/SnappingManager';
import { UndoManager, undoable } from '../../../../util/UndoManager';
import { ObservableReactComponent } from '../../../ObservableReactComponent';
import { CollectionFreeFormView } from '../../../collections/collectionFreeForm/CollectionFreeFormView';
import { DocumentView, DocumentViewInternal } from '../../DocumentView';
import { OpenWhere } from '../../OpenWhere';
import { DataVizBox } from '../DataVizBox';
import './DocCreatorMenu.scss';
import { DefaultStyleProvider } from '../../../StyleProvider';
import { Transform } from '../../../../util/Transform';
import { TemplateFieldSize, TemplateFieldType, TemplateLayouts } from './TemplateBackend';
import { TemplateManager } from './TemplateManager';
import { Template } from './Template';
import { Field, ViewType } from './FieldTypes/Field';
import { TabDocView } from '../../../collections/TabDocView';
import { DocData } from '../../../../../fields/DocSymbols';
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { Upload } from '../../../../../server/SharedMediaTypes';

export enum LayoutType {
    FREEFORM = 'Freeform',
    CAROUSEL = 'Carousel',
    CAROUSEL3D = '3D Carousel',
    MASONRY = 'Masonry',
    CARD = 'Card View',
}

export interface DataVizTemplateInfo {
    doc: Doc;
    layout: { type: LayoutType; xMargin: number; yMargin: number; repeat: number };
    columns: number;
    referencePos: { x: number; y: number };
}

export interface DataVizTemplateLayout {
    template: Doc;
    docsNumList: number[];
    layout: { type: LayoutType; xMargin: number; yMargin: number; repeat: number };
    columns: number;
    rows: number;
}

export type Col = {
    sizes: TemplateFieldSize[];
    desc: string;
    title: string;
    type: TemplateFieldType;
    defaultContent?: string;
};

interface DocCreateMenuProps {
    addDocTab: (doc: Doc | Doc[], where: OpenWhere) => boolean;
}

@observer
export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps> {
    // eslint-disable-next-line no-use-before-define
    static Instance: DocCreatorMenu;

    private DEBUG_MODE: boolean = false;

    private _disposers: { [name: string]: IDisposer } = {};

    private _ref: HTMLDivElement | null = null;

    private templateManager: TemplateManager;

    @observable _fullyRenderedDocs: Doc[] = []; // collection of templates filled in with content
    @observable _renderedDocCollection: Doc | undefined = undefined; // fullyRenderedDocs in a parent collection
    @observable _docsRendering: boolean = false; // dictates loading symbol

    @observable _userTemplates: Template[] = []; 
    @observable _selectedTemplate: Template | undefined = undefined;
    @observable _currEditingTemplate: Template | undefined = undefined;

    @observable _userCreatedFields: Col[] = [];
    @observable _selectedCols: { title: string; type: string; desc: string }[] | undefined = [];

    @observable _layout: { type: LayoutType; yMargin: number; xMargin: number; columns?: number; repeat: number } = { type: LayoutType.FREEFORM, yMargin: 10, xMargin: 10, columns: 3, repeat: 0 };
    @observable _savedLayouts: DataVizTemplateLayout[] = [];
    @observable _expandedPreview: Doc | undefined = undefined;

    @observable _suggestedTemplates: Template[] = [];
    @observable _GPTOpt: boolean = false;
    @observable _callCount: number = 0;
    @observable _GPTLoading: boolean = false;
    @observable _DOCCC: Doc | undefined;

    @observable _pageX: number = 0;
    @observable _pageY: number = 0;

    @observable _hoveredLayoutPreview: number | undefined = undefined;
    @observable _mouseX: number = -1;
    @observable _mouseY: number = -1;
    @observable _startPos?: { x: number; y: number };
    @observable _shouldDisplay: boolean = false;

    @observable _menuContent: 'templates' | 'options' | 'saved' | 'dashboard' = 'templates';
    @observable _dragging: boolean = false;
    @observable _draggingIndicator: boolean = false;
    @observable _dataViz?: DataVizBox;
    @observable _interactionLock: boolean | undefined;
    @observable _snapPt: { x: number; y: number } = { x: 0, y: 0 };
    @observable _resizeHdlId: string = '';
    @observable _resizing: boolean = false;
    @observable _offset: { x: number; y: number } = { x: 0, y: 0 };
    @observable _resizeUndo: UndoManager.Batch | undefined = undefined;
    @observable _initDimensions: { width: number; height: number; x?: number; y?: number } = { width: 300, height: 400, x: undefined, y: undefined };
    @observable _menuDimensions: { width: number; height: number } = { width: 400, height: 400 };
    @observable _editing: boolean = false;

    constructor(props: DocCreateMenuProps) {
        super(props);
        makeObservable(this);
        DocCreatorMenu.Instance = this;
        this.templateManager = new TemplateManager(TemplateLayouts.allTemplates);
    }

    @action setDataViz = (dataViz: DataVizBox) => {
        this._dataViz = dataViz;
        this._selectedTemplate = undefined;
        this._renderedDocCollection = undefined;
        this._fullyRenderedDocs = [];
        this._suggestedTemplates = [];
        this._userCreatedFields = [];
    };
    @action addUserTemplate = (template: Template) => {
        this._userTemplates.push(template);
    };
    @action removeUserTemplate = (template: Template) => {
        this._userTemplates.splice(this._userTemplates.indexOf(template), 1);
    }
    @action setSuggestedTemplates = (templates: Template[]) => {
        this._suggestedTemplates = templates; //prettier-ignore
    };

    @computed get docsToRender() {
        if (this.DEBUG_MODE) {
            return [1, 2, 3, 4];
        } else {
            return this._selectedTemplate ? NumListCast(this._dataViz?.layoutDoc.dataViz_selectedRows) : [];
        }
    }

    @computed get rowsCount() {
        switch (this._layout.type) {
            case LayoutType.FREEFORM:
                return Math.ceil(this.docsToRender.length / (this._layout.columns ?? 1)) ?? 0;
            case LayoutType.CAROUSEL3D:
                return 1.8;
            default:
                return 1;
        }
    }

    @computed get columnsCount() {
        switch (this._layout.type) {
            case LayoutType.FREEFORM:
                return this._layout.columns ?? 0;
            case LayoutType.CAROUSEL3D:
                return 3;
            default:
                return 1;
        }
    }

    @computed get selectedFields() {
        return StrListCast(this._dataViz?.layoutDoc._dataViz_axes);
    }

    @computed get fieldsInfos(): Col[] {
        const colInfo = this._dataViz?.colsInfo;
        return this.selectedFields
            .map(field => {
                const fieldInfo = colInfo?.get(field);

                const col: Col = {
                    title: field,
                    type: fieldInfo?.type ?? TemplateFieldType.UNSET,
                    desc: fieldInfo?.desc ?? '',
                    sizes: fieldInfo?.sizes ?? [TemplateFieldSize.MEDIUM],
                };

                if (fieldInfo?.defaultContent !== undefined) {
                    col.defaultContent = fieldInfo.defaultContent;
                }

                return col;
            })
            .concat(this._userCreatedFields);
    }

    @computed get canMakeDocs() {
        return this._selectedTemplate !== undefined && this._layout !== undefined;
    }

    get bounds(): { t: number; b: number; l: number; r: number } {
        const rect = this._ref?.getBoundingClientRect();
        const bounds = { t: rect?.top ?? 0, b: rect?.bottom ?? 0, l: rect?.left ?? 0, r: rect?.right ?? 0 };
        return bounds;
    }

    setUpButtonClick = (e: React.PointerEvent, func: () => void) => {
        setupMoveUpEvents(
            this,
            e,
            returnFalse,
            emptyFunction,
            undoable(clickEv => {
                clickEv.stopPropagation();
                clickEv.preventDefault();
                func();
            }, 'create docs')
        );
    };

    @action
    onPointerDown = (e: PointerEvent) => {
        this._mouseX = e.clientX;
        this._mouseY = e.clientY;
    };

    @action
    onPointerUp = (e: PointerEvent) => {
        if (this._resizing) {
            this._initDimensions.width = this._menuDimensions.width;
            this._initDimensions.height = this._menuDimensions.height;
            this._initDimensions.x = this._pageX;
            this._initDimensions.y = this._pageY;
            document.removeEventListener('pointermove', this.onResize);
            SnappingManager.SetIsResizing(undefined);
            this._resizing = false;
        }
        if (this._dragging) {
            document.removeEventListener('pointermove', this.onDrag);
            this._dragging = false;
        }
        if (e.button !== 2 && !e.ctrlKey) return;
        const curX = e.clientX;
        const curY = e.clientY;
        if (Math.abs(this._mouseX - curX) > 1 || Math.abs(this._mouseY - curY) > 1) {
            this._shouldDisplay = false;
        }
    };

    componentDidMount() {
        document.addEventListener('pointerdown', this.onPointerDown, true);
        document.addEventListener('pointerup', this.onPointerUp);
    }

    componentWillUnmount() {
        Object.values(this._disposers).forEach(disposer => disposer?.());
        document.removeEventListener('pointerdown', this.onPointerDown, true);
        document.removeEventListener('pointerup', this.onPointerUp);
    }

    @action
    toggleDisplay = (x: number, y: number) => {
        if (this._shouldDisplay) {
            this._shouldDisplay = false;
        } else {
            this._pageX = x;
            this._pageY = y;
            this._shouldDisplay = true;
        }
    };

    @action
    closeMenu = () => {
        this._shouldDisplay = false;
    };

    @action
    openMenu = () => {
        this._shouldDisplay = true;
    };

    @action
    onResizePointerDown = (e: React.PointerEvent): void => {
        this._resizing = true;
        document.addEventListener('pointermove', this.onResize);
        SnappingManager.SetIsResizing(DocumentView.Selected().lastElement()?.Document[Id]); // turns off pointer events on things like youtube videos and web pages so that dragging doesn't get "stuck" when cursor moves over them
        e.stopPropagation();
        const id = (this._resizeHdlId = e.currentTarget.className);
        const pad = id.includes('Left') || id.includes('Right') ? Number(getComputedStyle(e.target as HTMLElement).width.replace('px', '')) / 2 : 0;
        const bounds = e.currentTarget.getBoundingClientRect();
        this._offset = {
            x: id.toLowerCase().includes('left') ? bounds.right - e.clientX - pad : bounds.left - e.clientX + pad, //
            y: id.toLowerCase().includes('top') ? bounds.bottom - e.clientY - pad : bounds.top - e.clientY + pad,
        };
        this._resizeUndo = UndoManager.StartBatch('drag resizing');
        this._snapPt = { x: e.pageX, y: e.pageY };
    };

    @action
    onResize = (e: PointerEvent): boolean => {
        const dragHdl = this._resizeHdlId.split(' ')[1];
        const thisPt = DragManager.snapDrag(e, -this._offset.x, -this._offset.y, this._offset.x, this._offset.y);

        const { scale, refPt, transl } = this.getResizeVals(thisPt, dragHdl);
        !this._interactionLock && runInAction(async () => {   // resize selected docs if we're not in the middle of a resize (ie, throttle input events to frame rate)
        this._interactionLock = true;
        const scaleAspect = {x: scale.x, y: scale.y};
        this.resizeView(refPt, scaleAspect, transl); // prettier-ignore
        await new Promise<boolean | undefined>(res => { setTimeout(() => { res(this._interactionLock = undefined)})});
        }); // prettier-ignore
        return true;
    };

    @action
    onDrag = (e: PointerEvent): boolean => {
        this._pageX = e.pageX - (this._startPos?.x ?? 0);
        this._pageY = e.pageY - (this._startPos?.y ?? 0);
        this._initDimensions.x = this._pageX;
        this._initDimensions.y = this._pageY;
        return true;
    };

    getResizeVals = (thisPt: { x: number; y: number }, dragHdl: string) => {
        const [w, h] = [this._initDimensions.width, this._initDimensions.height];
        const [moveX, moveY] = [thisPt.x - this._snapPt!.x, thisPt.y - this._snapPt!.y];
        let vals: { scale: { x: number; y: number }; refPt: [number, number]; transl: { x: number; y: number } };
        switch (dragHdl) {
            case 'topLeft':    vals = { scale: { x: 1 - moveX / w, y: 1 -moveY / h },  refPt: [this.bounds.r, this.bounds.b], transl: {x: moveX, y: moveY } }; break;
            case 'topRight':   vals = { scale: { x: 1 + moveX / w, y: 1 -moveY / h },  refPt: [this.bounds.l, this.bounds.b], transl: {x: 0, y: moveY } }; break;
            case 'top':        vals = { scale: { x: 1,             y: 1 -moveY / h },  refPt: [this.bounds.l, this.bounds.b], transl: {x: 0, y: moveY } }; break;
            case 'left':       vals = { scale: { x: 1 - moveX / w, y: 1 },             refPt: [this.bounds.r, this.bounds.t], transl: {x: moveX, y: 0 } }; break;
            case 'bottomLeft': vals = { scale: { x: 1 - moveX / w, y: 1 + moveY / h }, refPt: [this.bounds.r, this.bounds.t], transl: {x: moveX, y: 0 } }; break;
            case 'right':      vals = { scale: { x: 1 + moveX / w, y: 1 },             refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break;
            case 'bottomRight':vals = { scale: { x: 1 + moveX / w, y: 1 + moveY / h }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break;
            case 'bottom':     vals = { scale: { x: 1,             y: 1 + moveY / h }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break;
            default:           vals = { scale: { x: 1,             y: 1 },             refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break;
        } // prettier-ignore
        return vals;
    };

    resizeView = (refPt: number[], scale: { x: number; y: number }, translation: { x: number; y: number }) => {
        if (this._initDimensions.x === undefined) this._initDimensions.x = this._pageX;
        if (this._initDimensions.y === undefined) this._initDimensions.y = this._pageY;
        const { height, width, x, y } = this._initDimensions;

        this._menuDimensions.width = Math.max(300, scale.x * width);
        this._menuDimensions.height = Math.max(200, scale.y * height);
        this._pageX = x + translation.x;
        this._pageY = y + translation.y;
    };

    async getIcon(doc: Doc) {
        const docView = DocumentView.getDocumentView(doc);
        if (docView) {
            docView.ComponentView?.updateIcon?.();
            return new Promise<ImageField | undefined>(res => setTimeout(() => res(ImageCast(docView.Document.icon)), 500));
        }
        return undefined;
    }

    @action updateRenderedPreviewCollection = async (template: Template) => {
        this._fullyRenderedDocs = await this.createDocsFromTemplate(template) ?? [];
        console.log(this._fullyRenderedDocs);
        this.updateRenderedDocCollection();
    }

    @action updateSelectedTemplate = async (template: Template) => {
        if (this._selectedTemplate === template) {
            this._selectedTemplate = undefined;
            return;
        } else {
            this._selectedTemplate = template;
            //template.renderUpdates();
            this.updateRenderedPreviewCollection(template);
        }
    };

    @action updateSelectedSavedLayout = (layout: DataVizTemplateLayout) => {
        this._layout.xMargin = layout.layout.xMargin;
        this._layout.yMargin = layout.layout.yMargin;
        this._layout.type = layout.layout.type;
        this._layout.columns = layout.columns;
    };

    isSelectedLayout = (layout: DataVizTemplateLayout) => {
        return this._layout.xMargin === layout.layout.xMargin && this._layout.yMargin === layout.layout.yMargin && this._layout.type === layout.layout.type && this._layout.columns === layout.columns;
    };

    editTemplate = (doc: Doc) => {
        DocumentViewInternal.addDocTabFunc(doc, OpenWhere.addRight);
        DocumentView.DeselectAll();
        Doc.UnBrushDoc(doc);
    };

    testTemplate = async () => {

        this._suggestedTemplates = this.templateManager.templates; //prettier-ignore

        //console.log(this.templateManager.templates)

        // const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView;
        
        // this.templateManager.templates.forEach(template => {
        //     const doc = template.mainField.renderedDoc();
        //     mainCollection.addDocument(doc);
        // })

        // this.forceUpdate();

        // try {
        //     const res = await gptImageCall('Image of panda eating a cookie');

        //     if (res) {
        //         const result = await Networking.PostToServer('/uploadRemoteImage', { sources: res });

        //         console.log(result);
        //     }
        // } catch (e) {
        //     console.log(e);
        // }
    };

    @action addField = () => {
        const newFields: Col[] = this._userCreatedFields.concat([{ title: '', type: TemplateFieldType.UNSET, desc: '', sizes: [] }]);
        this._userCreatedFields = newFields;
    };

    @action removeField = (field: { title: string; type: string; desc: string }) => {
        if (this._dataViz?.axes.includes(field.title)) {
            this._dataViz.selectAxes(this._dataViz.axes.filter(col => col !== field.title));
        } else {
            const toRemove = this._userCreatedFields.filter(f => f === field);
            if (!toRemove) return;

            if (toRemove.length > 1) {
                while (toRemove.length > 1) {
                    toRemove.pop();
                }
            }

            if (this._userCreatedFields.length === 1) {
                this._userCreatedFields = [];
            } else {
                this._userCreatedFields.splice(this._userCreatedFields.indexOf(toRemove[0]), 1);
            }
        }
    };

    @action setColTitle = (column: Col, title: string) => {
        if (this.selectedFields.includes(column.title)) {
            this._dataViz?.setColumnTitle(column.title, title);
        } else {
            column.title = title;
        }
        this.forceUpdate();
    };

    @action setColType = (column: Col, type: TemplateFieldType) => {
        if (this.selectedFields.includes(column.title)) {
            this._dataViz?.setColumnType(column.title, type);
        } else {
            column.type = type;
        }
        this.forceUpdate();
    };

    modifyColSizes = (column: Col, size: TemplateFieldSize, valid: boolean) => {
        if (this.selectedFields.includes(column.title)) {
            this._dataViz?.modifyColumnSizes(column.title, size, valid);
        } else {
            if (!valid && column.sizes.includes(size)) {
                column.sizes.splice(column.sizes.indexOf(size), 1);
            } else if (valid && !column.sizes.includes(size)) {
                column.sizes.push(size);
            }
        }
        this.forceUpdate();
    };

    setColDesc = (column: Col, desc: string) => {
        if (this.selectedFields.includes(column.title)) {
            this._dataViz?.setColumnDesc(column.title, desc);
        } else {
            column.desc = desc;
        }
        this.forceUpdate();
    };

    generateGPTImage = async (prompt: string): Promise<string | undefined> => {
        try {
            const res = await gptImageCall(prompt);

            if (res) {
                const result = (await Networking.PostToServer('/uploadRemoteImage', { sources: res })) as Upload.FileInformation[];
                const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client);
                return source;
            }
        } catch (e) {
            console.log(e);
        }
    };

    /**
     * Populates a preset template framework with content from a datavizbox or any AI-generated content.
     * @param template the preloaded template framework being filled in
     * @param assignments a list of template field numbers (from top to bottom) and their assigned columns from the linked dataviz
     * @returns a doc containing the fully rendered template
     */
    applyGPTContentToTemplate = async (template: Template, assignments: { [field: string]: Col }): Promise<Template | undefined> => {
        const GPTTextCalls = Object.entries(assignments).filter(([, col]) => col.type === TemplateFieldType.TEXT && this._userCreatedFields.includes(col));
        const GPTIMGCalls = Object.entries(assignments).filter(([, col]) => col.type === TemplateFieldType.VISUAL && this._userCreatedFields.includes(col));

        if (GPTTextCalls.length) {
            const promises = GPTTextCalls.map(([str, col]) => {
                return this.renderGPTTextCall(template, col, Number(str));
            });

            await Promise.all(promises);
        }

        if (GPTIMGCalls.length) {
            const promises = GPTIMGCalls.map(async ([fieldNum, col]) => {
                return this.renderGPTImageCall(template, col, Number(fieldNum));
            });

            await Promise.all(promises);
        }

        return template;
    };

    compileFieldDescriptions = (templates: Template[]): string => {
        let descriptions: string = '';
        templates.forEach(template => {
            descriptions += `----------  NEW TEMPLATE TO INCLUDE: The title is: ${template.title}. Its fields are: `;
            descriptions += template.descriptionSummary;
        });

        return descriptions;
    };

    compileColDescriptions = (cols: Col[]): string => {
        let descriptions: string = ' ------------- COL DESCRIPTIONS START HERE:';
        cols.forEach(col => (descriptions += `{title: ${col.title}, sizes: ${String(col.sizes)}, type: ${col.type}, descreiption: ${col.desc}} `));

        return descriptions;
    };

    getColByTitle = (title: string) => {
        return this.fieldsInfos.filter(col => col.title === title)[0];
    };

    @action
    assignColsToFields = async (templates: Template[], cols: Col[]): Promise<[Template, { [field: number]: Col }][]> => {
        const fieldDescriptions: string = this.compileFieldDescriptions(templates);
        const colDescriptions: string = this.compileColDescriptions(cols);

        const inputText = fieldDescriptions.concat(colDescriptions);

        ++this._callCount;
        const origCount = this._callCount;

        const prompt: string = `(${origCount}) ${inputText}`;

        this._GPTLoading = true;

        try {
            const res = await gptAPICall(prompt, GPTCallType.TEMPLATE);

            if (res) {
                const assignments: { [templateTitle: string]: { [fieldID: string]: string } } = JSON.parse(res);
                const brokenDownAssignments: [Template, { [fieldID: number]: Col }][] = [];

                Object.entries(assignments).forEach(([tempTitle, assignment]) => {
                    const template = templates.filter(template => template.title === tempTitle)[0];
                    if (!template) return;
                    const toObj = Object.entries(assignment).reduce(
                        (a, [fieldID, colTitle]) => {
                            const col = this.getColByTitle(colTitle);
                            if (!this._userCreatedFields.includes(col)){ // do the following for any fields not added by the user; will change in the future, for now only GPT content works with user-added field
                                const field = template.getFieldByID(Number(fieldID));
                                field.setContent(col.defaultContent ?? '', col.type === TemplateFieldType.VISUAL ? ViewType.IMG : ViewType.TEXT);
                                field.setTitle(col.title);
                            } else {
                                a[Number(fieldID)] = this.getColByTitle(colTitle);
                            }
                            return a;
                        },
                        {} as { [field: number]: Col }
                    );
                    brokenDownAssignments.push([template, toObj]);
                });

                return brokenDownAssignments;
            }
        } catch (err) {
            console.error(err);
        }

        return [];
    };

    generatePresetTemplates = async () => {

        const templates: Template[] = [];

        if (this.DEBUG_MODE) {
            templates.push(...this.templateManager.templates)
        } else {
            this._dataViz?.updateColDefaults();

            const cols = this.fieldsInfos;
            templates.push(...this.templateManager.getValidTemplates(cols));

            const assignments: [Template, { [field: number]: Col }][] = await this.assignColsToFields(templates, cols);

            const renderedTemplatePromises: Promise<Template | undefined>[] = assignments.map(([template, assignments]) => this.applyGPTContentToTemplate(template, assignments));

            const renderedTemplates: (Template | undefined)[] = await Promise.all(renderedTemplatePromises);
        }

        templates.forEach(template => template.mainField.initializeDocument())

        setTimeout(() => {
            this.setSuggestedTemplates(templates);
            this._GPTLoading = false;
        });
    };

    renderGPTImageCall = async (template: Template, col: Col, fieldNumber: number): Promise<boolean> => {
        const generateAndLoadImage = async (fieldNum: string, column: Col, prompt: string) => {
            const url = await this.generateGPTImage(prompt);
            const field: Field = template.getFieldByID(Number(fieldNum));

            field.setContent(url ?? '', ViewType.IMG);
            field.setTitle(col.title);
        };

        const fieldContent: string = template.compiledContent;

        try {
            const sysPrompt =
                'Your job is to create a prompt for an AI image generator to help it generate an image based on existing content in a template and a user prompt. Your prompt should focus heavily on visual elements to help the image generator; avoid unecessary info that might distract it. ONLY INCLUDE THE PROMPT, NO OTHER TEXT OR EXPLANATION. The existing content is as follows: ' +
                fieldContent +
                ' **** The user prompt is: ' +
                col.desc;

            const prompt = await gptAPICall(sysPrompt, GPTCallType.COMPLETEPROMPT);

            await generateAndLoadImage(String(fieldNumber), col, prompt);
        } catch (e) {
            console.log(e);
        }
        return true;
    };

    renderGPTTextCall = async (template: Template, col: Col, fieldNum: number): Promise<boolean> => {
        const wordLimit = (size: TemplateFieldSize) => {
            switch (size) {
                case TemplateFieldSize.TINY:
                    return 2;
                case TemplateFieldSize.SMALL:
                    return 5;
                case TemplateFieldSize.MEDIUM:
                    return 20;
                case TemplateFieldSize.LARGE:
                    return 50;
                case TemplateFieldSize.HUGE:
                    return 100;
                default:
                    return 10;
            }
        };

        const textAssignment = `--- title: ${col.title}, prompt: ${col.desc}, word limit: ${wordLimit(col.sizes[0])} words, assigned field: ${fieldNum} ---`;

        const fieldContent: string = template.compiledContent;

        try {
            const prompt = fieldContent + textAssignment;

            const res = await gptAPICall(`${++this._callCount}: ${prompt}`, GPTCallType.FILL);

            // console.log('prompt: ', prompt, ' response: ', res);

            if (res) {
                const assignments: { [title: string]: { number: string; content: string } } = JSON.parse(res);
                Object.entries(assignments).forEach(([title, info]) => {
                    const field: Field = template.getFieldByID(Number(info.number));
                    const column = this.getColByTitle(title);

                    field.setContent(info.content ?? '', ViewType.TEXT);
                    field.setTitle(col.title);
                });
            }
        } catch (err) {
            console.log(err);
        }

        return true;
    };

    createDocsFromTemplate = async (template: Template) => {
        const dv = this._dataViz;

        if (!dv) return;

        this._docsRendering = true;

        const fields: string[] = Array.from(Object.keys(dv.records[0]));
        const selectedRows = NumListCast(dv.layoutDoc.dataViz_selectedRows);

        const rowContents: { [title: string]: string }[] = selectedRows.map(row => {
            const values: { [title: string]: string } = {};
            fields.forEach(col => {
                values[col] = dv.records[row][col];
            });

            return values;
        });
    
        const processContent = async (content: {[title: string]: string}) => {

            const templateCopy = await template.cloneBase(); 

            fields.filter(title => title).forEach(title => {
                const field = templateCopy.getFieldByTitle(title);
                if (field === undefined) return;
                field.setContent(content[title], field.viewType);
            });
    
            const gptPromises = this._userCreatedFields.filter(field => field.type === TemplateFieldType.TEXT).map(field => {
                const title = field.title;
                const templateField = templateCopy.getFieldByTitle(title);
                if (templateField === undefined) return;
                const templatefieldID = templateField.getID;
    
                return this.renderGPTTextCall(templateCopy, field, templatefieldID);
            });

            const imagePromises = this._userCreatedFields.filter(field => field.type === TemplateFieldType.VISUAL).map(field => {
                const title = field.title;
                const templateField = templateCopy.getFieldByTitle(title);
                if (templateField === undefined) return;
                const templatefieldID = templateField.getID;
    
                return this.renderGPTImageCall(templateCopy, field, templatefieldID);
            });
    
            await Promise.all(gptPromises);

            await Promise.all(imagePromises);

            this._DOCCC = templateCopy.mainField.renderedDoc;
            return templateCopy.mainField.renderedDoc;
        };
        
        let docs: Promise<Doc>[];
        if (this.DEBUG_MODE) {
            docs = [1, 2, 3, 4].map(() => processContent({}));
        } else {
            docs = rowContents.map(content => processContent(content));
        }

        const renderedDocs = await Promise.all(docs);

        this._docsRendering = false; // removes loading indicator

        return renderedDocs;
    }

    addRenderedCollectionToMainview = () => {
        const collection = this._renderedDocCollection;
        if (!collection) return;
        const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView;
        collection.x = this._pageX - this._menuDimensions.width;
        collection.y = this._pageY - this._menuDimensions.height;
        mainCollection.addDocument(collection);
        this.closeMenu();
    };

    @action setExpandedView = (template: Template | undefined) => {
        if (template) {
            this._currEditingTemplate = template;
            this._expandedPreview = template.doc; //Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''});
        } else {
            this._currEditingTemplate = undefined;
            this._expandedPreview = undefined;
        }
    };

    get editingWindow() {
        const rendered = !this._expandedPreview ? null : (
            <div className="docCreatorMenu-expanded-template-preview">
                <DocumentView
                    Document={this._expandedPreview}
                    isContentActive={emptyFunction}
                    addDocument={returnFalse}
                    moveDocument={returnFalse}
                    removeDocument={returnFalse}
                    PanelWidth={() => this._menuDimensions.width - 10}
                    PanelHeight={() => this._menuDimensions.height - 60}
                    ScreenToLocalTransform={() => new Transform(-this._pageX - 5, -this._pageY - 35, 1)}
                    renderDepth={5}
                    whenChildContentsActiveChanged={emptyFunction}
                    focus={emptyFunction}
                    styleProvider={DefaultStyleProvider}
                    addDocTab={DocumentViewInternal.addDocTabFunc}
                    pinToPres={() => undefined}
                    childFilters={returnEmptyFilter}
                    childFiltersByRanges={returnEmptyFilter}
                    searchFilterDocs={returnEmptyDoclist}
                    fitContentsToBox={returnFalse}
                    fitWidth={returnFalse}
                />
            </div>
        );

        return (
            <div className="docCreatorMenu-expanded-template-preview">
                <div className="top-panel" />
                {rendered}
                <div className="right-buttons-panel">
                    <button className="docCreatorMenu-menu-button section-reveal-options top-right" onPointerDown={e => this.setUpButtonClick(e, () => {
                        if (!this._currEditingTemplate) return; 
                        if (this._currEditingTemplate === this._selectedTemplate) {
                            this.updateRenderedPreviewCollection(this._currEditingTemplate);
                        }
                        this.setExpandedView(undefined);
                        })}>
                        <FontAwesomeIcon icon="minimize" />
                    </button>
                    <button className="docCreatorMenu-menu-button section-reveal-options top-right-lower" onPointerDown={e => this.setUpButtonClick(e, () => {this._currEditingTemplate?.printFieldInfo();/*this._currEditingTemplate?.resetToBase();*/ this.setExpandedView(this._currEditingTemplate);})}>
                        <FontAwesomeIcon icon="arrows-rotate" color="white" />
                    </button>
                </div>
            </div>
        );
    }

    get templatesPreviewContents() {

        const GPTOptions = <div></div>;

        const previewDoc = (doc: Doc, template: Template) => 
        <DocumentView
        Document={doc}
        isContentActive={emptyFunction} // !!! should be return false
        addDocument={returnFalse}
        moveDocument={returnFalse}
        removeDocument={returnFalse}
        PanelWidth={() => this._selectedTemplate === template ? 104 : 111}
        PanelHeight={() => this._selectedTemplate === template ? 104 : 111}
        ScreenToLocalTransform={() => new Transform(-this._pageX - 5,-this._pageY - 35, 1)}
        renderDepth={1}
        whenChildContentsActiveChanged={emptyFunction}
        focus={emptyFunction}
        styleProvider={DefaultStyleProvider}
        addDocTab={this._props.addDocTab}
        // eslint-disable-next-line no-use-before-define
        pinToPres={() => undefined}
        childFilters={returnEmptyFilter}
        childFiltersByRanges={returnEmptyFilter}
        searchFilterDocs={returnEmptyDoclist}
        fitContentsToBox={returnFalse}
        fitWidth={returnFalse}
        hideDecorations={true}
        />

        //<img className='docCreatorMenu-preview-image expanded' src={this._expandedPreview.icon!.url.href.replace(".png", "_o.png")} />

        return (
            <div className={`docCreatorMenu-templates-view`}>
                {this._expandedPreview ? (
                    this.editingWindow
                ) : (
                    <div>
                        <div className="docCreatorMenu-section" style={{ height: this._GPTOpt ? 200 : 200 }}>
                            <div className="docCreatorMenu-section-topbar">
                                <div className="docCreatorMenu-section-title">Suggested Templates</div>
                                <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._menuContent = 'dashboard')))}>
                                    <FontAwesomeIcon icon="gear" />
                                </button>
                            </div>
                            <div className="docCreatorMenu-templates-preview-window" style={{ justifyContent: this._GPTLoading || this._menuDimensions.width > 400 ? 'center' : '' }}>
                                {this._GPTLoading ? (
                                    <div className="loading-spinner">
                                        <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} />
                                    </div>
                                ) : (
                                    this._suggestedTemplates
                                        .map(template => (
                                            <div
                                                className="docCreatorMenu-preview-window"
                                                style={{
                                                    border: this._selectedTemplate === template ? `solid 3px ${Colors.MEDIUM_BLUE}` : '',
                                                    boxShadow: this._selectedTemplate === template ? `0 0 15px rgba(68, 118, 247, .8)` : '',
                                                }}
                                                onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedTemplate(template)))}>
                                                <button
                                                    className="option-button left"
                                                    onPointerDown={e =>
                                                        this.setUpButtonClick(e, () => {
                                                            this.setExpandedView(template);
                                                        })
                                                    }>
                                                    <FontAwesomeIcon icon="magnifying-glass" color="white" />
                                                </button>
                                                <button className="option-button right" onPointerDown={e => this.setUpButtonClick(e, () => this.addUserTemplate(template))}>
                                                    <FontAwesomeIcon icon="plus" color="white" />
                                                </button>
                                                {previewDoc(template.getRenderedDoc(), template)}
                                            </div>
                                        ))
                                )}
                            </div>
                            <div className="docCreatorMenu-GPT-options">
                                <div className="docCreatorMenu-GPT-options-container">
                                    <button className="docCreatorMenu-menu-button" onPointerDown={e => this.setUpButtonClick(e, () => this.generatePresetTemplates())}>
                                        <FontAwesomeIcon icon="arrows-rotate" />
                                    </button>
                                </div>
                                {this._GPTOpt ? GPTOptions : null}
                            </div>
                        </div>
                        <hr className="docCreatorMenu-option-divider full no-margin" />
                        <div className="docCreatorMenu-section">
                            <div className="docCreatorMenu-section-topbar">
                                <div className="docCreatorMenu-section-title">Your Templates</div>
                                <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, () => (this._GPTOpt = !this._GPTOpt))}>
                                    <FontAwesomeIcon icon="gear" />
                                </button>
                            </div>
                            <div className="docCreatorMenu-templates-preview-window" style={{ justifyContent: this._menuDimensions.width > 400 ? 'center' : '' }}>
                                <div className="docCreatorMenu-preview-window empty">
                                    <FontAwesomeIcon icon="plus" color="rgb(160, 160, 160)" />
                                </div>
                                {this._userTemplates
                                    .map(template => (
                                        <div
                                            className="docCreatorMenu-preview-window"
                                            style={{
                                                border: this._selectedTemplate === template ? `solid 3px ${Colors.MEDIUM_BLUE}` : '',
                                                boxShadow: this._selectedTemplate === template ? `0 0 15px rgba(68, 118, 247, .8)` : '',
                                            }}
                                            onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedTemplate(template)))}>
                                            <button
                                                className="option-button left"
                                                onPointerDown={e =>
                                                    this.setUpButtonClick(e, () => {
                                                        this.setExpandedView(template);
                                                    })
                                                }>
                                                <FontAwesomeIcon icon="magnifying-glass" color="white" />
                                            </button>
                                            <button className="option-button right" onPointerDown={e => this.setUpButtonClick(e, () => this.removeUserTemplate(template))}>
                                                <FontAwesomeIcon icon="minus" color="white" />
                                            </button>
                                            {previewDoc(template.getRenderedDoc(), template)}
                                        </div>
                                    ))}
                            </div>
                        </div>
                    </div>
                )}
            </div>
        );
    }

    @action updateXMargin = (input: string) => {
        this._layout.xMargin = Number(input);
        setTimeout(() => {
            if (!this._renderedDocCollection || !this._fullyRenderedDocs) return;
            this.applyLayout(this._renderedDocCollection, this._fullyRenderedDocs);
        });
    };
    @action updateYMargin = (input: string) => {
        this._layout.yMargin = Number(input);
        setTimeout(() => {
            if (!this._renderedDocCollection || !this._fullyRenderedDocs) return;
            this.applyLayout(this._renderedDocCollection, this._fullyRenderedDocs);
        });
    };
    @action updateColumns = (input: string) => {
        this._layout.columns = Number(input);
        this.updateRenderedDocCollection();
    };

    get layoutConfigOptions() {
        const optionInput = (icon: string, func: (input: string) => void, def?: number, key?: string, noMargin?: boolean) => {
            return (
                <div className="docCreatorMenu-option-container small no-margin" key={key} style={{ marginTop: noMargin ? '0px' : '' }}>
                    <div className="docCreatorMenu-option-title config layout-config">
                        <FontAwesomeIcon icon={icon as IconProp} />
                    </div>
                    <input defaultValue={def} onInput={e => func(e.currentTarget.value)} className="docCreatorMenu-input config layout-config" />
                </div>
            );
        };

        switch (this._layout.type) {
            case LayoutType.FREEFORM:
                return (
                    <div className="docCreatorMenu-configuration-bar">
                        {optionInput('arrows-up-down', this.updateYMargin, this._layout.xMargin, '2')}
                        {optionInput('arrows-left-right', this.updateXMargin, this._layout.xMargin, '3')}
                        {optionInput('table-columns', this.updateColumns, this._layout.columns, '4', true)}
                    </div>
                );
            default:
                break;
        }
    }

    applyLayout = (collection: Doc, docs: Doc[]) => {
        const { horizontalSpan, verticalSpan } = this.previewInfo;
        collection._height = verticalSpan;
        collection._width = horizontalSpan;

        const columns: number = this._layout.columns ?? this.columnsCount;
        const xGap: number = this._layout.xMargin;
        const yGap: number = this._layout.yMargin;
        const startX: number = -Number(collection._width)/2;
        const startY: number = -Number(collection._height)/2;
        const docHeight: number = Number(docs[0]._height);
        const docWidth: number = Number(docs[0]._width);

        if (columns === 0 || docs.length === 0) {
            return;
        }

        let i: number = 0;
        let docsChanged: number = 0;
        let curX: number = startX;
        let curY: number = startY;

        while (docsChanged < docs.length) {
            while (i < columns && docsChanged < docs.length) {
                docs[docsChanged].x = curX;
                docs[docsChanged].y = curY;
                curX += docWidth + xGap;
                ++docsChanged;
                ++i;
            }
            i = 0;
            curX = startX;
            curY += docHeight + yGap;
        }
    };

    @computed
    get previewInfo() {
        const docHeight: number = Number(this._fullyRenderedDocs[0]._height);
        const docWidth: number = Number(this._fullyRenderedDocs[0]._width);
        const layout = this._layout;
        return {
            docHeight: docHeight,
            docWidth: docWidth,
            horizontalSpan: (docWidth + layout.xMargin) * this.columnsCount - layout.xMargin,
            verticalSpan: (docHeight + layout.yMargin) * this.rowsCount - layout.yMargin,
        };
    }

    /**
     * Updates the preview that shows how all docs will be rendered in the chosen collection type.
    @type the type of collection the docs should render to (ie. freeform, carousel, card)
     */
    updateRenderedDocCollection = () => {
        if (!this._fullyRenderedDocs) return;

        const collectionFactory = (): ((docs: Doc[], options: DocumentOptions) => Doc) => {
            switch (this._layout.type) {
                case LayoutType.CAROUSEL3D:
                    return Docs.Create.Carousel3DDocument;
                case LayoutType.FREEFORM:
                    return Docs.Create.FreeformDocument;
                case LayoutType.CARD:
                    return Docs.Create.CardDeckDocument;
                case LayoutType.MASONRY:
                    return Docs.Create.MasonryDocument;
                case LayoutType.CAROUSEL:
                    return Docs.Create.CarouselDocument;
                default:
                    return Docs.Create.FreeformDocument;
            }
        };

        const collection = collectionFactory()([this._fullyRenderedDocs[6], this._fullyRenderedDocs[9]], {
            isDefaultTemplateDoc: true,
            title: 'title',
            backgroundColor: 'gray',
            x: 200,
            y: 200,
            _width: 4000,
            _height: 4000,
        });

        this.applyLayout(collection, this._fullyRenderedDocs);

        this._renderedDocCollection = collection;

        const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView;
        mainCollection.addDocument(collection);

        console.log('changed to: ', collection);
    }

    layoutPreviewContents = () => {
        return this._docsRendering ? (
            <div className="docCreatorMenu-layout-preview-window-wrapper loading">
                <div className="loading-spinner">
                    <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} />
                </div>
            </div>
            ) : !this._renderedDocCollection ? null : (
            <div className="docCreatorMenu-layout-preview-window-wrapper">
                <DocumentView
                    Document={this._renderedDocCollection}
                    isContentActive={emptyFunction}
                    addDocument={returnFalse}
                    moveDocument={returnFalse}
                    removeDocument={returnFalse}
                    PanelWidth={() => this._menuDimensions.width - 80}
                    PanelHeight={() => this._menuDimensions.height - 105}
                    ScreenToLocalTransform={() => new Transform(-this._pageX - 5, -this._pageY - 35, 1)}
                    renderDepth={5}
                    whenChildContentsActiveChanged={emptyFunction}
                    focus={emptyFunction}
                    styleProvider={DefaultStyleProvider}
                    addDocTab={this._props.addDocTab}
                    pinToPres={() => undefined}
                    childFilters={returnEmptyFilter}
                    childFiltersByRanges={returnEmptyFilter}
                    searchFilterDocs={returnEmptyDoclist}
                    fitContentsToBox={returnFalse}
                    fitWidth={returnFalse}
                    hideDecorations={true}
                />
            </div>
        );
    };

    get optionsMenuContents() {
        const layoutOption = (option: LayoutType, optStyle?: object, specialFunc?: () => void) => {
            return (
                <div
                    className="docCreatorMenu-dropdown-option"
                    style={optStyle}
                    onPointerDown={e =>
                        this.setUpButtonClick(e, () => {
                            specialFunc?.();
                            runInAction(() => {
                                this._layout.type = option;
                                this.updateRenderedDocCollection();
                            });
                        })
                    }>
                    {option}
                </div>
            );
        };

        const selectionBox = (width: number, height: number, icon: string, specClass?: string, options?: JSX.Element[], manual?: boolean): JSX.Element => {
            return (
                <div className="docCreatorMenu-option-container">
                    <div className={`docCreatorMenu-option-title config ${specClass}`} style={{ width: width * 0.4, height: height }}>
                        <FontAwesomeIcon icon={icon as IconProp} />
                    </div>
                    {manual ? (
                        <input className={`docCreatorMenu-input config ${specClass}`} style={{ width: width * 0.6, height: height }} />
                    ) : (
                        <select className={`docCreatorMenu-input config ${specClass}`} style={{ width: width * 0.6, height: height }}>
                            {options}
                        </select>
                    )}
                </div>
            );
        };

        const repeatOptions = [0, 1, 2, 3, 4, 5];

        return (
            <div className="docCreatorMenu-menu-container">
                <div className="docCreatorMenu-option-container layout">
                    <div className="docCreatorMenu-dropdown-hoverable">
                        <div className="docCreatorMenu-option-title">{this._layout.type ? this._layout.type.toUpperCase() : 'Choose Layout'}</div>
                        <div className="docCreatorMenu-dropdown-content">
                            {layoutOption(LayoutType.FREEFORM, undefined, () => {
                                if (!this._layout.columns) this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length));
                            })}
                            {layoutOption(LayoutType.CAROUSEL)}
                            {layoutOption(LayoutType.CAROUSEL3D)}
                            {layoutOption(LayoutType.MASONRY)}
                        </div>
                    </div>
                </div>
                {this._layout.type ? this.layoutConfigOptions : null}
                {this.layoutPreviewContents()}
                {selectionBox(
                    60,
                    20,
                    'repeat',
                    undefined,
                    repeatOptions.map(num => <option key={num} onPointerDown={() => (this._layout.repeat = num)}>{`${num}x`}</option>)
                )}
                <hr className="docCreatorMenu-option-divider" />
                <div className="docCreatorMenu-general-options-container">
                    <button
                        className="docCreatorMenu-save-layout-button"
                        onPointerDown={e =>
                            setupMoveUpEvents(
                                this,
                                e,
                                returnFalse,
                                emptyFunction,
                                undoable(clickEv => {
                                    clickEv.stopPropagation();
                                    if (!this._selectedTemplate) return;
                                    const layout: DataVizTemplateLayout = {
                                        template: this._selectedTemplate.getRenderedDoc(),
                                        layout: { type: this._layout.type, xMargin: this._layout.xMargin, yMargin: this._layout.yMargin, repeat: 0 },
                                        columns: this.columnsCount,
                                        rows: this.rowsCount,
                                        docsNumList: this.docsToRender,
                                    };
                                    if (!this._savedLayouts.includes(layout)) {
                                        this._savedLayouts.push(layout);
                                    }
                                }, 'make docs')
                            )
                        }>
                        <FontAwesomeIcon icon="floppy-disk" />
                    </button>
                    <button
                        className="docCreatorMenu-create-docs-button"
                        style={{ backgroundColor: this.canMakeDocs ? '' : 'rgb(155, 155, 155)', border: this.canMakeDocs ? '' : 'solid 2px rgb(180, 180, 180)' }}
                        onPointerDown={e =>
                            setupMoveUpEvents(
                                this,
                                e,
                                returnFalse,
                                emptyFunction,
                                undoable(clickEv => {
                                    clickEv.stopPropagation();
                                    if (!this._selectedTemplate) return;
                                    this.addRenderedCollectionToMainview();
                                }, 'make docs')
                            )
                        }>
                        <FontAwesomeIcon icon="plus" />
                    </button>
                </div>
            </div>
        );
    }

    get dashboardContents() {
        const sizes: string[] = ['tiny', 'small', 'medium', 'large', 'huge'];

        const fieldPanel = (field: Col, id: number) => {
            return (
                <div className="field-panel" key={id}>
                    <div className="top-bar">
                        <span className="field-title">{`${field.title} Field`}</span>
                        <button className="docCreatorMenu-menu-button section-reveal-options no-margin" onPointerDown={e => this.setUpButtonClick(e, () => this.removeField(field))} style={{ position: 'absolute', right: '0px' }}>
                            <FontAwesomeIcon icon="minus" />
                        </button>
                    </div>
                    <div className="opts-bar">
                        <div className="opt-box">
                            <div className="top-bar"> Title </div>
                            <textarea className="content" style={{ width: '100%', height: 'calc(100% - 20px)' }} value={field.title} placeholder={'Enter title'} onChange={e => this.setColTitle(field, e.target.value)} />
                        </div>
                        <div className="opt-box">
                            <div className="top-bar"> Type </div>
                            <div className="content">
                                <span className="type-display">{field.type === TemplateFieldType.TEXT ? 'Text Field' : field.type === TemplateFieldType.VISUAL ? 'File Field' : ''}</span>
                                <div className="bubbles">
                                    <input
                                        className="bubble"
                                        type="radio"
                                        name="type"
                                        onClick={() => {
                                            this.setColType(field, TemplateFieldType.TEXT);
                                        }}
                                    />
                                    <div className="text">Text</div>
                                    <input
                                        className="bubble"
                                        type="radio"
                                        name="type"
                                        onClick={() => {
                                            this.setColType(field, TemplateFieldType.VISUAL);
                                        }}
                                    />
                                    <div className="text">File</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="sizes-box">
                        <div className="top-bar"> Valid Sizes </div>
                        <div className="content">
                            <div className="bubbles">
                                {sizes.map(size => (
                                    <>
                                        <input
                                            className="bubble"
                                            type="checkbox"
                                            name="type"
                                            checked={field.sizes.includes(size as TemplateFieldSize)}
                                            onChange={e => {
                                                this.modifyColSizes(field, size as TemplateFieldSize, e.target.checked);
                                            }}
                                        />
                                        <div className="text">{size}</div>
                                    </>
                                ))}
                            </div>
                        </div>
                    </div>
                    <div className="desc-box">
                        <div className="top-bar"> Prompt </div>
                        <textarea
                            className="content"
                            onChange={e => this.setColDesc(field, e.target.value)}
                            defaultValue={field.desc === this._dataViz?.GPTSummary?.get(field.title)?.desc ? '' : field.desc}
                            placeholder={this._dataViz?.GPTSummary?.get(field.title)?.desc ?? 'Add a description/prompt to help with template generation.'}
                        />
                    </div>
                </div>
            );
        };

        return (
            <div className="docCreatorMenu-dashboard-view">
                <div className="topbar">
                    <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, this.addField)}>
                        <FontAwesomeIcon icon="plus" />
                    </button>
                    <button className="docCreatorMenu-menu-button section-reveal-options float-right" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._menuContent = 'templates')))}>
                        <FontAwesomeIcon icon="arrow-left" />
                    </button>
                </div>
                <div className="panels-container">{this.fieldsInfos.map((field, i) => fieldPanel(field, i))}</div>
            </div>
        );
    }

    get renderSelectedViewType() {
        switch (this._menuContent) {
            case 'templates':
                return this.templatesPreviewContents;
            case 'options':
                return this.optionsMenuContents;
            case 'dashboard':
                return this.dashboardContents;
            default:
                return undefined;
        }
    }

    get resizePanes() {
        const ref = this._ref?.getBoundingClientRect();
        const height: number = ref?.height ?? 0;
        const width: number = ref?.width ?? 0;

        return [
            <div className='docCreatorMenu-resizer top' key='0' onPointerDown={this.onResizePointerDown} style={{width: width, left: 0, top: -7}}/>, 
            <div className='docCreatorMenu-resizer left' key='1' onPointerDown={this.onResizePointerDown} style={{height: height, left: -7, top: 0}}/>,
            <div className='docCreatorMenu-resizer right' key='2' onPointerDown={this.onResizePointerDown} style={{height: height, left: width - 3, top: 0}}/>, 
            <div className='docCreatorMenu-resizer bottom' key='3' onPointerDown={this.onResizePointerDown} style={{width: width, left: 0, top: height - 3}}/>,
            <div className='docCreatorMenu-resizer topLeft' key='4' onPointerDown={this.onResizePointerDown} style={{left: -10, top: -10, cursor: 'nwse-resize'}}/>,
            <div className='docCreatorMenu-resizer topRight' key='5' onPointerDown={this.onResizePointerDown} style={{left: width - 5, top: -10, cursor: 'nesw-resize'}}/>,
            <div className='docCreatorMenu-resizer bottomLeft' key='6' onPointerDown={this.onResizePointerDown} style={{left: -10, top: height - 5, cursor: 'nesw-resize'}}/>,
            <div className='docCreatorMenu-resizer bottomRight' key='7' onPointerDown={this.onResizePointerDown} style={{left: width - 5, top: height - 5, cursor: 'nwse-resize'}}/>,
        ]; //prettier-ignore
    }

    render() {
        const topButton = (icon: string, opt: string, func: () => void, tag: string) => {
            return (
                <div className={`top-button-container ${tag} ${opt === this._menuContent ? 'selected' : ''}`}>
                    <div
                        className="top-button-content"
                        onPointerDown={e =>
                            this.setUpButtonClick(e, () =>
                                runInAction(() => {
                                    func();
                                })
                            )
                        }>
                        <FontAwesomeIcon icon={icon as IconProp} />
                    </div>
                </div>
            );
        };

        const onPreviewSelected = () => {
            this._menuContent = 'templates';
        };
        const onSavedSelected = () => {
            this._menuContent = 'dashboard';
        };
        const onOptionsSelected = () => {
            this._menuContent = 'options';
            if (!this._layout.columns) this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length));
        };

        return (
            <div className="docCreatorMenu">
                {!this._shouldDisplay ? undefined : (
                    <div
                        className="docCreatorMenu-cont"
                        ref={r => (this._ref = r)}
                        style={{
                            display: '',
                            left: this._pageX,
                            top: this._pageY,
                            width: this._menuDimensions.width,
                            height: this._menuDimensions.height,
                            background: SnappingManager.userBackgroundColor,
                            color: SnappingManager.userColor,
                        }}>
                        {this.resizePanes}
                        <div
                            className="docCreatorMenu-menu"
                            onPointerDown={e =>
                                setupMoveUpEvents(
                                    this,
                                    e,
                                    event => {
                                        this._dragging = true;
                                        this._startPos = { x: 0, y: 0 };
                                        this._startPos.x = event.pageX - (this._ref?.getBoundingClientRect().left ?? 0);
                                        this._startPos.y = event.pageY - (this._ref?.getBoundingClientRect().top ?? 0);
                                        document.addEventListener('pointermove', this.onDrag);
                                        return true;
                                    },
                                    emptyFunction,
                                    undoable(clickEv => {
                                        clickEv.stopPropagation();
                                    }, 'drag menu')
                                )
                            }>
                            <div className="docCreatorMenu-top-buttons-container">
                                {topButton('lightbulb', 'templates', onPreviewSelected, 'left')}
                                {topButton('magnifying-glass', 'options', onOptionsSelected, 'middle')}
                                {topButton('bars', 'saved', onSavedSelected, 'right')}
                            </div>
                            <button className="docCreatorMenu-menu-button close-menu" onPointerDown={e => this.setUpButtonClick(e, this.closeMenu)}>
                                <FontAwesomeIcon icon={'minus'} />
                            </button>
                        </div>
                        {this.renderSelectedViewType}
                    </div>
                )}
            </div>
        );
    }
}